~vcs-imports/make/master

2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1
/* Argument parsing and main program of GNU Make.
2774 by Paul Smith
* <all>: Update copyright notices.
2
Copyright (C) 1988-2022 Free Software Foundation, Inc.
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3
This file is part of GNU Make.
4
5
GNU Make is free software; you can redistribute it and/or modify it under the
6
terms of the GNU General Public License as published by the Free Software
7
Foundation; either version 3 of the License, or (at your option) any later
8
version.
9
10
GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12
A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13
14
You should have received a copy of the GNU General Public License along with
15
this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17
#include "makeint.h"
18
#include "os.h"
19
#include "filedef.h"
20
#include "dep.h"
21
#include "variable.h"
22
#include "job.h"
23
#include "commands.h"
24
#include "rule.h"
25
#include "debug.h"
26
#include "getopt.h"
27
28
#include <assert.h>
29
#ifdef _AMIGA
30
# include <dos/dos.h>
31
# include <proto/dos.h>
32
#endif
33
#ifdef WINDOWS32
34
# include <windows.h>
35
# include <io.h>
36
#ifdef HAVE_STRINGS_H
2758 by Paul Smith
[SV 61226] Revert changes to detect missing included files
37
# include <strings.h> /* for strcasecmp */
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
38
#endif
39
# include "pathstuff.h"
40
# include "sub_proc.h"
41
# include "w32err.h"
42
#endif
43
#ifdef __EMX__
44
# include <sys/types.h>
45
# include <sys/wait.h>
46
#endif
47
#ifdef HAVE_FCNTL_H
48
# include <fcntl.h>
49
#endif
50
51
#ifdef _AMIGA
52
int __stack = 20000; /* Make sure we have 20K of stack space */
53
#endif
54
#ifdef VMS
55
int vms_use_mcr_command = 0;
56
int vms_always_use_cmd_file = 0;
57
int vms_gnv_shell = 0;
58
int vms_legacy_behavior = 0;
59
int vms_comma_separator = 0;
60
int vms_unix_simulation = 0;
61
int vms_report_unix_paths = 0;
62
63
/* Evaluates if a VMS environment option is set, only look at first character */
64
static int
65
get_vms_env_flag (const char *name, int default_value)
66
{
67
char * value;
68
char x;
69
70
  value = getenv (name);
71
  if (value == NULL)
72
    return default_value;
73
74
  x = toupper (value[0]);
75
  switch (x)
76
    {
77
    case '1':
78
    case 'T':
79
    case 'E':
80
      return 1;
81
      break;
82
    case '0':
83
    case 'F':
84
    case 'D':
85
      return 0;
86
    }
87
}
88
#endif
89
90
#if defined HAVE_WAITPID || defined HAVE_WAIT3
91
# define HAVE_WAIT_NOHANG
92
#endif
93
94
#ifndef HAVE_UNISTD_H
95
int chdir ();
96
#endif
97
#ifndef STDC_HEADERS
98
# ifndef sun                    /* Sun has an incorrect decl in a header.  */
2629 by Paul Smith
Enable compilation with C90 compilers
99
void exit (int) NORETURN;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
100
# endif
101
double atof ();
102
#endif
103
104
static void clean_jobserver (int status);
105
static void print_data_base (void);
106
static void print_version (void);
107
static void decode_switches (int argc, const char **argv, int env);
108
static struct variable *define_makeflags (int all, int makefile);
109
static char *quote_for_env (char *out, const char *in);
110
static void initialize_global_hash_tables (void);
111
112

113
/* True if C is a switch value that corresponds to a short option.  */
114
115
#define short_option(c) ((c) <= CHAR_MAX)
116
117
/* The structure used to hold the list of strings given
118
   in command switches of a type that takes strlist arguments.  */
119
120
struct stringlist
121
  {
122
    const char **list;  /* Nil-terminated list of strings.  */
123
    unsigned int idx;   /* Index into above.  */
124
    unsigned int max;   /* Number of pointers allocated.  */
125
  };
126
127
128
/* The recognized command switches.  */
129
130
/* Nonzero means do extra verification (that may slow things down).  */
131
132
int verify_flag;
133
134
/* Nonzero means do not print commands to be executed (-s).  */
135
2527 by Paul Smith
[SV 54740] Ensure .SILENT settings do not leak into sub-makes
136
static int silent_flag;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
137
static const int default_silent_flag = 0;
138
2527 by Paul Smith
[SV 54740] Ensure .SILENT settings do not leak into sub-makes
139
/* Nonzero means either -s was given, or .SILENT-with-no-deps was seen.  */
140
141
int run_silent = 0;
142
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
143
/* Nonzero means just touch the files
144
   that would appear to need remaking (-t)  */
145
146
int touch_flag;
147
148
/* Nonzero means just print what commands would need to be executed,
149
   don't actually execute them (-n).  */
150
151
int just_print_flag;
152
153
/* Print debugging info (--debug).  */
154
155
static struct stringlist *db_flags = 0;
156
static int debug_flag = 0;
157
158
int db_level = 0;
159
160
/* Synchronize output (--output-sync).  */
161
162
char *output_sync_option = 0;
163
164
/* Environment variables override makefile definitions.  */
165
166
int env_overrides = 0;
167
168
/* Nonzero means ignore status codes returned by commands
169
   executed to remake files.  Just treat them all as successful (-i).  */
170
171
int ignore_errors_flag = 0;
172
173
/* Nonzero means don't remake anything, just print the data base
174
   that results from reading the makefile (-p).  */
175
176
int print_data_base_flag = 0;
177
178
/* Nonzero means don't remake anything; just return a nonzero status
179
   if the specified targets are not up to date (-q).  */
180
181
int question_flag = 0;
182
183
/* Nonzero means do not use any of the builtin rules (-r) / variables (-R).  */
184
185
int no_builtin_rules_flag = 0;
186
int no_builtin_variables_flag = 0;
187
188
/* Nonzero means keep going even if remaking some file fails (-k).  */
189
190
int keep_going_flag;
191
static const int default_keep_going_flag = 0;
192
193
/* Nonzero means check symlink mtimes.  */
194
195
int check_symlink_flag = 0;
196
197
/* Nonzero means print directory before starting and when done (-w).  */
198
2643 by Paul Smith
Obey order of multiple print/no-print directory options
199
int print_directory;
200
static int print_directory_flag = -1;
201
static const int default_print_directory_flag = -1;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
202
203
/* Nonzero means print version information.  */
204
205
int print_version_flag = 0;
206
207
/* List of makefiles given with -f switches.  */
208
209
static struct stringlist *makefiles = 0;
210
211
/* Size of the stack when we started.  */
212
213
#ifdef SET_STACK_SIZE
214
struct rlimit stack_limit;
215
#endif
216
217
218
/* Number of job slots for parallelism.  */
219
220
unsigned int job_slots;
221
222
#define INVALID_JOB_SLOTS (-1)
223
static unsigned int master_job_slots = 0;
224
static int arg_job_slots = INVALID_JOB_SLOTS;
225
226
static const int default_job_slots = INVALID_JOB_SLOTS;
227
228
/* Value of job_slots that means no limit.  */
229
230
static const int inf_jobs = 0;
231
232
/* Authorization for the jobserver.  */
233
234
static char *jobserver_auth = NULL;
235
236
/* Handle for the mutex used on Windows to synchronize output of our
237
   children under -O.  */
238
239
char *sync_mutex = NULL;
240
241
/* Maximum load average at which multiple jobs will be run.
242
   Negative values mean unlimited, while zero means limit to
243
   zero load (which could be useful to start infinite jobs remotely
244
   but one at a time locally).  */
245
double max_load_average = -1.0;
246
double default_load_average = -1.0;
247
248
/* List of directories given with -C switches.  */
249
250
static struct stringlist *directories = 0;
251
252
/* List of include directories given with -I switches.  */
253
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
254
static struct stringlist *include_dirs = 0;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
255
256
/* List of files given with -o switches.  */
257
258
static struct stringlist *old_files = 0;
259
260
/* List of files given with -W switches.  */
261
262
static struct stringlist *new_files = 0;
263
264
/* List of strings to be eval'd.  */
265
static struct stringlist *eval_strings = 0;
266
267
/* If nonzero, we should just print usage and exit.  */
268
269
static int print_usage_flag = 0;
270
271
/* If nonzero, we should print a warning message
272
   for each reference to an undefined variable.  */
273
274
int warn_undefined_variables_flag;
275
276
/* If nonzero, always build all targets, regardless of whether
277
   they appear out of date or not.  */
278
279
static int always_make_set = 0;
280
int always_make_flag = 0;
281
282
/* If nonzero, we're in the "try to rebuild makefiles" phase.  */
283
284
int rebuilding_makefiles = 0;
285
286
/* Remember the original value of the SHELL variable, from the environment.  */
287
288
struct variable shell_var;
289
290
/* This character introduces a command: it's the first char on the line.  */
291
292
char cmd_prefix = '\t';
293
2669 by Paul Smith
[SV 41273] Allow the directory cache to be invalidated
294
/* Count the number of commands we've invoked, that might change something in
295
   the filesystem.  Start with 1 so calloc'd memory never matches.  */
296
297
unsigned long command_count = 1;
298
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
299
/* Remember the location of the name of the batch file from stdin.  */
300
301
static int stdin_offset = -1;
2669 by Paul Smith
[SV 41273] Allow the directory cache to be invalidated
302
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
303

304
/* The usage output.  We write it this way to make life easier for the
305
   translators, especially those trying to translate to right-to-left
306
   languages like Hebrew.  */
307
308
static const char *const usage[] =
309
  {
310
    N_("Options:\n"),
311
    N_("\
312
  -b, -m                      Ignored for compatibility.\n"),
313
    N_("\
314
  -B, --always-make           Unconditionally make all targets.\n"),
315
    N_("\
316
  -C DIRECTORY, --directory=DIRECTORY\n\
317
                              Change to DIRECTORY before doing anything.\n"),
318
    N_("\
319
  -d                          Print lots of debugging information.\n"),
320
    N_("\
321
  --debug[=FLAGS]             Print various types of debugging information.\n"),
322
    N_("\
323
  -e, --environment-overrides\n\
324
                              Environment variables override makefiles.\n"),
325
    N_("\
326
  -E STRING, --eval=STRING    Evaluate STRING as a makefile statement.\n"),
327
    N_("\
328
  -f FILE, --file=FILE, --makefile=FILE\n\
329
                              Read FILE as a makefile.\n"),
330
    N_("\
331
  -h, --help                  Print this message and exit.\n"),
332
    N_("\
333
  -i, --ignore-errors         Ignore errors from recipes.\n"),
334
    N_("\
335
  -I DIRECTORY, --include-dir=DIRECTORY\n\
336
                              Search DIRECTORY for included makefiles.\n"),
337
    N_("\
338
  -j [N], --jobs[=N]          Allow N jobs at once; infinite jobs with no arg.\n"),
339
    N_("\
340
  -k, --keep-going            Keep going when some targets can't be made.\n"),
341
    N_("\
342
  -l [N], --load-average[=N], --max-load[=N]\n\
343
                              Don't start multiple jobs unless load is below N.\n"),
344
    N_("\
345
  -L, --check-symlink-times   Use the latest mtime between symlinks and target.\n"),
346
    N_("\
347
  -n, --just-print, --dry-run, --recon\n\
348
                              Don't actually run any recipe; just print them.\n"),
349
    N_("\
350
  -o FILE, --old-file=FILE, --assume-old=FILE\n\
351
                              Consider FILE to be very old and don't remake it.\n"),
352
    N_("\
353
  -O[TYPE], --output-sync[=TYPE]\n\
354
                              Synchronize output of parallel jobs by TYPE.\n"),
355
    N_("\
356
  -p, --print-data-base       Print make's internal database.\n"),
357
    N_("\
358
  -q, --question              Run no recipe; exit status says if up to date.\n"),
359
    N_("\
360
  -r, --no-builtin-rules      Disable the built-in implicit rules.\n"),
361
    N_("\
362
  -R, --no-builtin-variables  Disable the built-in variable settings.\n"),
363
    N_("\
364
  -s, --silent, --quiet       Don't echo recipes.\n"),
365
    N_("\
366
  --no-silent                 Echo recipes (disable --silent mode).\n"),
367
    N_("\
368
  -S, --no-keep-going, --stop\n\
369
                              Turns off -k.\n"),
370
    N_("\
371
  -t, --touch                 Touch targets instead of remaking them.\n"),
372
    N_("\
373
  --trace                     Print tracing information.\n"),
374
    N_("\
375
  -v, --version               Print the version number of make and exit.\n"),
376
    N_("\
377
  -w, --print-directory       Print the current directory.\n"),
378
    N_("\
379
  --no-print-directory        Turn off -w, even if it was turned on implicitly.\n"),
380
    N_("\
381
  -W FILE, --what-if=FILE, --new-file=FILE, --assume-new=FILE\n\
382
                              Consider FILE to be infinitely new.\n"),
383
    N_("\
384
  --warn-undefined-variables  Warn when an undefined variable is referenced.\n"),
385
    NULL
386
  };
387
2679 by Paul Smith
[SV 59169] Add --debug=why and --debug=print options
388
/* Nonzero if the "--trace" option was given.  */
389
390
static int trace_flag = 0;
391
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
392
/* The structure that describes an accepted command switch.  */
393
394
struct command_switch
395
  {
396
    int c;                      /* The switch character.  */
397
398
    enum                        /* Type of the value.  */
399
      {
400
        flag,                   /* Turn int flag on.  */
401
        flag_off,               /* Turn int flag off.  */
402
        string,                 /* One string per invocation.  */
403
        strlist,                /* One string per switch.  */
404
        filename,               /* A string containing a file name.  */
405
        positive_int,           /* A positive integer.  */
406
        floating,               /* A floating-point number (double).  */
407
        ignore                  /* Ignored.  */
408
      } type;
409
410
    void *value_ptr;    /* Pointer to the value-holding variable.  */
411
412
    unsigned int env:1;         /* Can come from MAKEFLAGS.  */
413
    unsigned int toenv:1;       /* Should be put in MAKEFLAGS.  */
414
    unsigned int no_makefile:1; /* Don't propagate when remaking makefiles.  */
415
416
    const void *noarg_value;    /* Pointer to value used if no arg given.  */
417
    const void *default_value;  /* Pointer to default value.  */
418
419
    const char *long_name;      /* Long option name.  */
420
  };
421
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
422
/* The table of command switches.
423
   Order matters here: this is the order MAKEFLAGS will be constructed.
424
   So be sure all simple flags (single char, no argument) come first.  */
425
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
426
#define TEMP_STDIN_OPT (CHAR_MAX+10)
427
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
428
static const struct command_switch switches[] =
429
  {
430
    { 'b', ignore, 0, 0, 0, 0, 0, 0, 0 },
431
    { 'B', flag, &always_make_set, 1, 1, 0, 0, 0, "always-make" },
432
    { 'd', flag, &debug_flag, 1, 1, 0, 0, 0, 0 },
433
    { 'e', flag, &env_overrides, 1, 1, 0, 0, 0, "environment-overrides", },
434
    { 'E', strlist, &eval_strings, 1, 0, 0, 0, 0, "eval" },
435
    { 'h', flag, &print_usage_flag, 0, 0, 0, 0, 0, "help" },
436
    { 'i', flag, &ignore_errors_flag, 1, 1, 0, 0, 0, "ignore-errors" },
437
    { 'k', flag, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
438
      "keep-going" },
439
    { 'L', flag, &check_symlink_flag, 1, 1, 0, 0, 0, "check-symlink-times" },
440
    { 'm', ignore, 0, 0, 0, 0, 0, 0, 0 },
441
    { 'n', flag, &just_print_flag, 1, 1, 1, 0, 0, "just-print" },
442
    { 'p', flag, &print_data_base_flag, 1, 1, 0, 0, 0, "print-data-base" },
443
    { 'q', flag, &question_flag, 1, 1, 1, 0, 0, "question" },
444
    { 'r', flag, &no_builtin_rules_flag, 1, 1, 0, 0, 0, "no-builtin-rules" },
445
    { 'R', flag, &no_builtin_variables_flag, 1, 1, 0, 0, 0,
446
      "no-builtin-variables" },
447
    { 's', flag, &silent_flag, 1, 1, 0, 0, &default_silent_flag, "silent" },
448
    { 'S', flag_off, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
449
      "no-keep-going" },
450
    { 't', flag, &touch_flag, 1, 1, 1, 0, 0, "touch" },
451
    { 'v', flag, &print_version_flag, 1, 1, 0, 0, 0, "version" },
2643 by Paul Smith
Obey order of multiple print/no-print directory options
452
    { 'w', flag, &print_directory_flag, 1, 1, 0, 0,
453
      &default_print_directory_flag, "print-directory" },
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
454
455
    /* These options take arguments.  */
456
    { 'C', filename, &directories, 0, 0, 0, 0, 0, "directory" },
457
    { 'f', filename, &makefiles, 0, 0, 0, 0, 0, "file" },
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
458
    { 'I', filename, &include_dirs, 1, 1, 0, 0, 0,
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
459
      "include-dir" },
460
    { 'j', positive_int, &arg_job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,
461
      "jobs" },
462
    { 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,
463
      &default_load_average, "load-average" },
464
    { 'o', filename, &old_files, 0, 0, 0, 0, 0, "old-file" },
465
    { 'O', string, &output_sync_option, 1, 1, 0, "target", 0, "output-sync" },
466
    { 'W', filename, &new_files, 0, 0, 0, 0, 0, "what-if" },
467
468
    /* These are long-style options.  */
469
    { CHAR_MAX+1, strlist, &db_flags, 1, 1, 0, "basic", 0, "debug" },
470
    { CHAR_MAX+2, string, &jobserver_auth, 1, 1, 0, 0, 0, "jobserver-auth" },
471
    { CHAR_MAX+3, flag, &trace_flag, 1, 1, 0, 0, 0, "trace" },
2643 by Paul Smith
Obey order of multiple print/no-print directory options
472
    { CHAR_MAX+4, flag_off, &print_directory_flag, 1, 1, 0, 0,
473
      &default_print_directory_flag, "no-print-directory" },
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
474
    { CHAR_MAX+5, flag, &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
475
      "warn-undefined-variables" },
476
    { CHAR_MAX+7, string, &sync_mutex, 1, 1, 0, 0, 0, "sync-mutex" },
2643 by Paul Smith
Obey order of multiple print/no-print directory options
477
    { CHAR_MAX+8, flag_off, &silent_flag, 1, 1, 0, 0, &default_silent_flag,
478
      "no-silent" },
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
479
    { CHAR_MAX+9, string, &jobserver_auth, 1, 0, 0, 0, 0, "jobserver-fds" },
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
480
    /* There is special-case handling for this in decode_switches() as well.  */
481
    { TEMP_STDIN_OPT, filename, &makefiles, 0, 0, 0, 0, 0, "temp-stdin" },
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
482
    { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
483
  };
484
485
/* Secondary long names for options.  */
486
487
static struct option long_option_aliases[] =
488
  {
489
    { "quiet",          no_argument,            0, 's' },
490
    { "stop",           no_argument,            0, 'S' },
491
    { "new-file",       required_argument,      0, 'W' },
492
    { "assume-new",     required_argument,      0, 'W' },
493
    { "assume-old",     required_argument,      0, 'o' },
494
    { "max-load",       optional_argument,      0, 'l' },
495
    { "dry-run",        no_argument,            0, 'n' },
496
    { "recon",          no_argument,            0, 'n' },
497
    { "makefile",       required_argument,      0, 'f' },
498
  };
499
500
/* List of goal targets.  */
501
502
static struct goaldep *goals, *lastgoal;
503
504
/* List of variables which were defined on the command line
505
   (or, equivalently, in MAKEFLAGS).  */
506
507
struct command_variable
508
  {
509
    struct command_variable *next;
510
    struct variable *variable;
511
  };
512
static struct command_variable *command_variables;
513

514
/* The name we were invoked with.  */
515
516
const char *program;
517
518
/* Our current directory before processing any -C options.  */
519
520
char *directory_before_chdir;
521
522
/* Our current directory after processing all -C options.  */
523
524
char *starting_directory;
525
526
/* Value of the MAKELEVEL variable at startup (or 0).  */
527
528
unsigned int makelevel;
529
530
/* Pointer to the value of the .DEFAULT_GOAL special variable.
531
   The value will be the name of the goal to remake if the command line
532
   does not override it.  It can be set by the makefile, or else it's
533
   the first target defined in the makefile whose name does not start
534
   with '.'.  */
535
536
struct variable * default_goal_var;
537
538
/* Pointer to structure for the file .DEFAULT
539
   whose commands are used for any file that has none of its own.
540
   This is zero if the makefiles do not define .DEFAULT.  */
541
542
struct file *default_file;
543
544
/* Nonzero if we have seen the magic '.POSIX' target.
545
   This turns on pedantic compliance with POSIX.2.  */
546
547
int posix_pedantic;
548
549
/* Nonzero if we have seen the '.SECONDEXPANSION' target.
550
   This turns on secondary expansion of prerequisites.  */
551
552
int second_expansion;
553
554
/* Nonzero if we have seen the '.ONESHELL' target.
555
   This causes the entire recipe to be handed to SHELL
556
   as a single string, potentially containing newlines.  */
557
558
int one_shell;
559
560
/* One of OUTPUT_SYNC_* if the "--output-sync" option was given.  This
561
   attempts to synchronize the output of parallel jobs such that the results
562
   of each job stay together.  */
563
564
int output_sync = OUTPUT_SYNC_NONE;
565
566
/* Nonzero if we have seen the '.NOTPARALLEL' target.
567
   This turns off parallel builds for this invocation of make.  */
568
569
int not_parallel;
570
571
/* Nonzero if some rule detected clock skew; we keep track so (a) we only
572
   print one warning about it during the run, and (b) we can print a final
573
   warning at the end of the run. */
574
575
int clock_skew_detected;
576
577
/* Map of possible stop characters for searching strings.  */
578
#ifndef UCHAR_MAX
579
# define UCHAR_MAX 255
580
#endif
581
unsigned short stopchar_map[UCHAR_MAX + 1] = {0};
582
583
/* If output-sync is enabled we'll collect all the output generated due to
584
   options, while reading makefiles, etc.  */
585
586
struct output make_sync;
587
588

589
/* Mask of signals that are being caught with fatal_error_signal.  */
590
591
#if defined(POSIX)
592
sigset_t fatal_signal_set;
593
#elif defined(HAVE_SIGSETMASK)
594
int fatal_signal_mask;
595
#endif
596
597
#if !HAVE_DECL_BSD_SIGNAL && !defined bsd_signal
598
# if !defined HAVE_SIGACTION
599
#  define bsd_signal signal
600
# else
601
typedef RETSIGTYPE (*bsd_signal_ret_t) (int);
602
603
static bsd_signal_ret_t
604
bsd_signal (int sig, bsd_signal_ret_t func)
605
{
606
  struct sigaction act, oact;
607
  act.sa_handler = func;
608
  act.sa_flags = SA_RESTART;
609
  sigemptyset (&act.sa_mask);
610
  sigaddset (&act.sa_mask, sig);
611
  if (sigaction (sig, &act, &oact) != 0)
612
    return SIG_ERR;
613
  return oact.sa_handler;
614
}
615
# endif
616
#endif
617
618
static void
619
initialize_global_hash_tables (void)
620
{
621
  init_hash_global_variable_set ();
622
  strcache_init ();
623
  init_hash_files ();
624
  hash_init_directories ();
625
  hash_init_function_table ();
626
}
627
628
/* This character map locate stop chars when parsing GNU makefiles.
629
   Each element is true if we should stop parsing on that character.  */
630
631
static void
632
initialize_stopchar_map (void)
633
{
634
  int i;
635
636
  stopchar_map[(int)'\0'] = MAP_NUL;
637
  stopchar_map[(int)'#'] = MAP_COMMENT;
638
  stopchar_map[(int)';'] = MAP_SEMI;
639
  stopchar_map[(int)'='] = MAP_EQUALS;
640
  stopchar_map[(int)':'] = MAP_COLON;
641
  stopchar_map[(int)'|'] = MAP_PIPE;
642
  stopchar_map[(int)'.'] = MAP_DOT | MAP_USERFUNC;
643
  stopchar_map[(int)','] = MAP_COMMA;
644
  stopchar_map[(int)'('] = MAP_VARSEP;
645
  stopchar_map[(int)'{'] = MAP_VARSEP;
646
  stopchar_map[(int)'}'] = MAP_VARSEP;
647
  stopchar_map[(int)')'] = MAP_VARSEP;
648
  stopchar_map[(int)'$'] = MAP_VARIABLE;
649
650
  stopchar_map[(int)'-'] = MAP_USERFUNC;
651
  stopchar_map[(int)'_'] = MAP_USERFUNC;
652
653
  stopchar_map[(int)' '] = MAP_BLANK;
654
  stopchar_map[(int)'\t'] = MAP_BLANK;
655
656
  stopchar_map[(int)'/'] = MAP_DIRSEP;
657
#if defined(VMS)
658
  stopchar_map[(int)':'] |= MAP_DIRSEP;
659
  stopchar_map[(int)']'] |= MAP_DIRSEP;
660
  stopchar_map[(int)'>'] |= MAP_DIRSEP;
661
#elif defined(HAVE_DOS_PATHS)
662
  stopchar_map[(int)'\\'] |= MAP_DIRSEP;
663
#endif
664
665
  for (i = 1; i <= UCHAR_MAX; ++i)
666
    {
667
      if (isspace (i) && NONE_SET (stopchar_map[i], MAP_BLANK))
668
        /* Don't mark blank characters as newline characters.  */
669
        stopchar_map[i] |= MAP_NEWLINE;
670
      else if (isalnum (i))
671
        stopchar_map[i] |= MAP_USERFUNC;
672
    }
673
}
674
675
static const char *
676
expand_command_line_file (const char *name)
677
{
678
  const char *cp;
679
  char *expanded = 0;
680
681
  if (name[0] == '\0')
682
    O (fatal, NILF, _("empty string invalid as file name"));
683
684
  if (name[0] == '~')
685
    {
686
      expanded = tilde_expand (name);
687
      if (expanded && expanded[0] != '\0')
688
        name = expanded;
689
    }
690
691
  /* This is also done in parse_file_seq, so this is redundant
692
     for names read from makefiles.  It is here for names passed
693
     on the command line.  */
694
  while (name[0] == '.' && name[1] == '/')
695
    {
696
      name += 2;
697
      while (name[0] == '/')
698
        /* Skip following slashes: ".//foo" is "foo", not "/foo".  */
699
        ++name;
700
    }
701
702
  if (name[0] == '\0')
703
    {
704
      /* Nothing else but one or more "./", maybe plus slashes!  */
705
      name = "./";
706
    }
707
708
  cp = strcache_add (name);
709
710
  free (expanded);
711
712
  return cp;
713
}
714
715
/* Toggle -d on receipt of SIGUSR1.  */
716
717
#ifdef SIGUSR1
718
static RETSIGTYPE
719
debug_signal_handler (int sig UNUSED)
720
{
721
  db_level = db_level ? DB_NONE : DB_BASIC;
722
}
723
#endif
724
725
static void
726
decode_debug_flags (void)
727
{
728
  const char **pp;
729
730
  if (debug_flag)
731
    db_level = DB_ALL;
732
2679 by Paul Smith
[SV 59169] Add --debug=why and --debug=print options
733
  if (trace_flag)
2723 by Dmitry Goncharov
* src/main.c (decode_debug_flags): [SV 607777] Preserve -d options
734
    db_level |= DB_PRINT | DB_WHY;
2679 by Paul Smith
[SV 59169] Add --debug=why and --debug=print options
735
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
736
  if (db_flags)
737
    for (pp=db_flags->list; *pp; ++pp)
738
      {
739
        const char *p = *pp;
740
741
        while (1)
742
          {
743
            switch (tolower (p[0]))
744
              {
745
              case 'a':
746
                db_level |= DB_ALL;
747
                break;
748
              case 'b':
749
                db_level |= DB_BASIC;
750
                break;
751
              case 'i':
752
                db_level |= DB_BASIC | DB_IMPLICIT;
753
                break;
754
              case 'j':
755
                db_level |= DB_JOBS;
756
                break;
757
              case 'm':
758
                db_level |= DB_BASIC | DB_MAKEFILES;
759
                break;
760
              case 'n':
761
                db_level = 0;
762
                break;
2679 by Paul Smith
[SV 59169] Add --debug=why and --debug=print options
763
              case 'p':
764
                db_level |= DB_PRINT;
765
                break;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
766
              case 'v':
767
                db_level |= DB_BASIC | DB_VERBOSE;
768
                break;
2679 by Paul Smith
[SV 59169] Add --debug=why and --debug=print options
769
              case 'w':
770
                db_level |= DB_WHY;
771
                break;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
772
              default:
773
                OS (fatal, NILF,
774
                    _("unknown debug level specification '%s'"), p);
775
              }
776
777
            while (*(++p) != '\0')
778
              if (*p == ',' || *p == ' ')
779
                {
780
                  ++p;
781
                  break;
782
                }
783
784
            if (*p == '\0')
785
              break;
786
          }
787
      }
788
789
  if (db_level)
790
    verify_flag = 1;
791
792
  if (! db_level)
793
    debug_flag = 0;
794
}
795
796
static void
797
decode_output_sync_flags (void)
798
{
799
#ifdef NO_OUTPUT_SYNC
800
  output_sync = OUTPUT_SYNC_NONE;
801
#else
802
  if (output_sync_option)
803
    {
804
      if (streq (output_sync_option, "none"))
805
        output_sync = OUTPUT_SYNC_NONE;
806
      else if (streq (output_sync_option, "line"))
807
        output_sync = OUTPUT_SYNC_LINE;
808
      else if (streq (output_sync_option, "target"))
809
        output_sync = OUTPUT_SYNC_TARGET;
810
      else if (streq (output_sync_option, "recurse"))
811
        output_sync = OUTPUT_SYNC_RECURSE;
812
      else
813
        OS (fatal, NILF,
814
            _("unknown output-sync type '%s'"), output_sync_option);
815
    }
816
817
  if (sync_mutex)
818
    RECORD_SYNC_MUTEX (sync_mutex);
819
#endif
820
}
821
822
#ifdef WINDOWS32
823
824
#ifndef NO_OUTPUT_SYNC
825
826
/* This is called from start_job_command when it detects that
827
   output_sync option is in effect.  The handle to the synchronization
828
   mutex is passed, as a string, to sub-makes via the --sync-mutex
829
   command-line argument.  */
830
void
831
prepare_mutex_handle_string (sync_handle_t handle)
832
{
833
  if (!sync_mutex)
834
    {
835
      /* Prepare the mutex handle string for our children.  */
836
      /* 2 hex digits per byte + 2 characters for "0x" + null.  */
837
      sync_mutex = xmalloc ((2 * sizeof (sync_handle_t)) + 2 + 1);
838
      sprintf (sync_mutex, "0x%Ix", handle);
839
      define_makeflags (1, 0);
840
    }
841
}
842
843
#endif  /* NO_OUTPUT_SYNC */
844
845
/*
846
 * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
847
 * exception and print it to stderr instead.
848
 *
849
 * If ! DB_VERBOSE, just print a simple message and exit.
850
 * If DB_VERBOSE, print a more verbose message.
851
 * If compiled for DEBUG, let exception pass through to GUI so that
852
 *   debuggers can attach.
853
 */
854
LONG WINAPI
855
handle_runtime_exceptions (struct _EXCEPTION_POINTERS *exinfo)
856
{
857
  PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
858
  LPSTR cmdline = GetCommandLine ();
859
  LPSTR prg = strtok (cmdline, " ");
860
  CHAR errmsg[1024];
861
#ifdef USE_EVENT_LOG
862
  HANDLE hEventSource;
863
  LPTSTR lpszStrings[1];
864
#endif
865
866
  if (! ISDB (DB_VERBOSE))
867
    {
868
      sprintf (errmsg,
869
               _("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\n"),
870
               prg, exrec->ExceptionCode, exrec->ExceptionAddress);
871
      fprintf (stderr, errmsg);
872
      exit (255);
873
    }
874
875
  sprintf (errmsg,
876
           _("\nUnhandled exception filter called from program %s\nExceptionCode = %lx\nExceptionFlags = %lx\nExceptionAddress = 0x%p\n"),
877
           prg, exrec->ExceptionCode, exrec->ExceptionFlags,
878
           exrec->ExceptionAddress);
879
880
  if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
881
      && exrec->NumberParameters >= 2)
882
    sprintf (&errmsg[strlen(errmsg)],
883
             (exrec->ExceptionInformation[0]
884
              ? _("Access violation: write operation at address 0x%p\n")
885
              : _("Access violation: read operation at address 0x%p\n")),
886
             (PVOID)exrec->ExceptionInformation[1]);
887
888
  /* turn this on if we want to put stuff in the event log too */
889
#ifdef USE_EVENT_LOG
890
  hEventSource = RegisterEventSource (NULL, "GNU Make");
891
  lpszStrings[0] = errmsg;
892
893
  if (hEventSource != NULL)
894
    {
895
      ReportEvent (hEventSource,         /* handle of event source */
896
                   EVENTLOG_ERROR_TYPE,  /* event type */
897
                   0,                    /* event category */
898
                   0,                    /* event ID */
899
                   NULL,                 /* current user's SID */
900
                   1,                    /* strings in lpszStrings */
901
                   0,                    /* no bytes of raw data */
902
                   lpszStrings,          /* array of error strings */
903
                   NULL);                /* no raw data */
904
905
      (VOID) DeregisterEventSource (hEventSource);
906
    }
907
#endif
908
909
  /* Write the error to stderr too */
910
  fprintf (stderr, errmsg);
911
912
#ifdef DEBUG
913
  return EXCEPTION_CONTINUE_SEARCH;
914
#else
915
  exit (255);
916
  return (255); /* not reached */
917
#endif
918
}
919
920
/*
921
 * On WIN32 systems we don't have the luxury of a /bin directory that
922
 * is mapped globally to every drive mounted to the system. Since make could
923
 * be invoked from any drive, and we don't want to propagate /bin/sh
924
 * to every single drive. Allow ourselves a chance to search for
925
 * a value for default shell here (if the default path does not exist).
926
 */
927
928
int
929
find_and_set_default_shell (const char *token)
930
{
931
  int sh_found = 0;
932
  char *atoken = 0;
933
  const char *search_token;
934
  const char *tokend;
935
  PATH_VAR(sh_path);
936
  extern const char *default_shell;
937
938
  if (!token)
939
    search_token = default_shell;
940
  else
941
    search_token = atoken = xstrdup (token);
942
943
  /* If the user explicitly requests the DOS cmd shell, obey that request.
944
     However, make sure that's what they really want by requiring the value
945
     of SHELL either equal, or have a final path element of, "cmd" or
946
     "cmd.exe" case-insensitive.  */
947
  tokend = search_token + strlen (search_token) - 3;
948
  if (((tokend == search_token
949
        || (tokend > search_token
950
            && (tokend[-1] == '/' || tokend[-1] == '\\')))
951
       && !strcasecmp (tokend, "cmd"))
952
      || ((tokend - 4 == search_token
953
           || (tokend - 4 > search_token
954
               && (tokend[-5] == '/' || tokend[-5] == '\\')))
955
          && !strcasecmp (tokend - 4, "cmd.exe")))
956
    {
957
      batch_mode_shell = 1;
958
      unixy_shell = 0;
959
      sprintf (sh_path, "%s", search_token);
960
      default_shell = xstrdup (w32ify (sh_path, 0));
961
      DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
962
                       default_shell));
963
      sh_found = 1;
964
    }
965
  else if (!no_default_sh_exe
966
           && (token == NULL || !strcmp (search_token, default_shell)))
967
    {
968
      /* no new information, path already set or known */
969
      sh_found = 1;
970
    }
971
  else if (_access (search_token, 0) == 0)
972
    {
973
      /* search token path was found */
974
      sprintf (sh_path, "%s", search_token);
975
      default_shell = xstrdup (w32ify (sh_path, 0));
976
      DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
977
                       default_shell));
978
      sh_found = 1;
979
    }
980
  else
981
    {
982
      char *p;
983
      struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
984
985
      /* Search Path for shell */
986
      if (v && v->value)
987
        {
988
          char *ep;
989
990
          p  = v->value;
991
          ep = strchr (p, PATH_SEPARATOR_CHAR);
992
993
          while (ep && *ep)
994
            {
995
              *ep = '\0';
996
997
              sprintf (sh_path, "%s/%s", p, search_token);
998
              if (_access (sh_path, 0) == 0)
999
                {
1000
                  default_shell = xstrdup (w32ify (sh_path, 0));
1001
                  sh_found = 1;
1002
                  *ep = PATH_SEPARATOR_CHAR;
1003
1004
                  /* terminate loop */
1005
                  p += strlen (p);
1006
                }
1007
              else
1008
                {
1009
                  *ep = PATH_SEPARATOR_CHAR;
1010
                  p = ++ep;
1011
                }
1012
1013
              ep = strchr (p, PATH_SEPARATOR_CHAR);
1014
            }
1015
1016
          /* be sure to check last element of Path */
1017
          if (p && *p)
1018
            {
1019
              sprintf (sh_path, "%s/%s", p, search_token);
1020
              if (_access (sh_path, 0) == 0)
1021
                {
1022
                  default_shell = xstrdup (w32ify (sh_path, 0));
1023
                  sh_found = 1;
1024
                }
1025
            }
1026
1027
          if (sh_found)
1028
            DB (DB_VERBOSE,
1029
                (_("find_and_set_shell() path search set default_shell = %s\n"),
1030
                 default_shell));
1031
        }
1032
    }
1033
1034
  /* naive test */
1035
  if (!unixy_shell && sh_found
1036
      && (strstr (default_shell, "sh") || strstr (default_shell, "SH")))
1037
    {
1038
      unixy_shell = 1;
1039
      batch_mode_shell = 0;
1040
    }
1041
1042
#ifdef BATCH_MODE_ONLY_SHELL
1043
  batch_mode_shell = 1;
1044
#endif
1045
1046
  free (atoken);
1047
1048
  return (sh_found);
1049
}
1050
#endif  /* WINDOWS32 */
1051
1052
#ifdef __MSDOS__
1053
static void
1054
msdos_return_to_initial_directory (void)
1055
{
1056
  if (directory_before_chdir)
1057
    chdir (directory_before_chdir);
1058
}
1059
#endif  /* __MSDOS__ */
1060
1061
static void
1062
reset_jobserver (void)
1063
{
1064
  jobserver_clear ();
1065
  free (jobserver_auth);
1066
  jobserver_auth = NULL;
1067
}
1068
1069
#ifdef _AMIGA
1070
int
1071
main (int argc, char **argv)
1072
#else
1073
int
1074
main (int argc, char **argv, char **envp)
1075
#endif
1076
{
1077
  int makefile_status = MAKE_SUCCESS;
1078
  struct goaldep *read_files;
1079
  PATH_VAR (current_directory);
1080
  unsigned int restarts = 0;
1081
  unsigned int syncing = 0;
1082
  int argv_slots;
1083
#ifdef WINDOWS32
1084
  const char *unix_path = NULL;
1085
  const char *windows32_path = NULL;
1086
1087
  SetUnhandledExceptionFilter (handle_runtime_exceptions);
1088
1089
  /* start off assuming we have no shell */
1090
  unixy_shell = 0;
1091
  no_default_sh_exe = 1;
1092
#endif
1093
2691 by Paul Smith
Ensure variable_buffer is always set.
1094
  initialize_variable_output ();
1095
2545 by Paul Smith
Update maintainer mode to support debug wait points.
1096
  /* Useful for attaching debuggers, etc.  */
1097
  SPIN ("main-entry");
1098
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1099
  output_init (&make_sync);
1100
1101
  initialize_stopchar_map();
1102
1103
#ifdef SET_STACK_SIZE
1104
 /* Get rid of any avoidable limit on stack size.  */
1105
  {
1106
    struct rlimit rlim;
1107
1108
    /* Set the stack limit huge so that alloca does not fail.  */
1109
    if (getrlimit (RLIMIT_STACK, &rlim) == 0
1110
        && rlim.rlim_cur > 0 && rlim.rlim_cur < rlim.rlim_max)
1111
      {
1112
        stack_limit = rlim;
1113
        rlim.rlim_cur = rlim.rlim_max;
1114
        setrlimit (RLIMIT_STACK, &rlim);
1115
      }
1116
    else
1117
      stack_limit.rlim_cur = 0;
1118
  }
1119
#endif
1120
1121
  /* Needed for OS/2 */
1122
  initialize_main (&argc, &argv);
1123
1124
#ifdef MAKE_MAINTAINER_MODE
1125
  /* In maintainer mode we always enable verification.  */
1126
  verify_flag = 1;
1127
#endif
1128
1129
#if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
1130
  /* Request the most powerful version of 'system', to
1131
     make up for the dumb default shell.  */
1132
  __system_flags = (__system_redirect
1133
                    | __system_use_shell
1134
                    | __system_allow_multiple_cmds
1135
                    | __system_allow_long_cmds
1136
                    | __system_handle_null_commands
1137
                    | __system_emulate_chdir);
1138
1139
#endif
1140
1141
  /* Set up gettext/internationalization support.  */
1142
  setlocale (LC_ALL, "");
1143
  /* The cast to void shuts up compiler warnings on systems that
1144
     disable NLS.  */
1145
  (void)bindtextdomain (PACKAGE, LOCALEDIR);
1146
  (void)textdomain (PACKAGE);
1147
1148
#ifdef  POSIX
1149
  sigemptyset (&fatal_signal_set);
1150
#define ADD_SIG(sig)    sigaddset (&fatal_signal_set, sig)
1151
#else
1152
#ifdef  HAVE_SIGSETMASK
1153
  fatal_signal_mask = 0;
1154
#define ADD_SIG(sig)    fatal_signal_mask |= sigmask (sig)
1155
#else
1156
#define ADD_SIG(sig)    (void)sig
1157
#endif
1158
#endif
1159
1160
#define FATAL_SIG(sig)                                                        \
1161
  if (bsd_signal (sig, fatal_error_signal) == SIG_IGN)                        \
1162
    bsd_signal (sig, SIG_IGN);                                                \
1163
  else                                                                        \
1164
    ADD_SIG (sig);
1165
1166
#ifdef SIGHUP
1167
  FATAL_SIG (SIGHUP);
1168
#endif
1169
#ifdef SIGQUIT
1170
  FATAL_SIG (SIGQUIT);
1171
#endif
1172
  FATAL_SIG (SIGINT);
1173
  FATAL_SIG (SIGTERM);
1174
1175
#ifdef __MSDOS__
1176
  /* Windows 9X delivers FP exceptions in child programs to their
1177
     parent!  We don't want Make to die when a child divides by zero,
1178
     so we work around that lossage by catching SIGFPE.  */
1179
  FATAL_SIG (SIGFPE);
1180
#endif
1181
1182
#ifdef  SIGDANGER
1183
  FATAL_SIG (SIGDANGER);
1184
#endif
1185
#ifdef SIGXCPU
1186
  FATAL_SIG (SIGXCPU);
1187
#endif
1188
#ifdef SIGXFSZ
1189
  FATAL_SIG (SIGXFSZ);
1190
#endif
1191
1192
#undef  FATAL_SIG
1193
1194
  /* Do not ignore the child-death signal.  This must be done before
1195
     any children could possibly be created; otherwise, the wait
1196
     functions won't work on systems with the SVR4 ECHILD brain
1197
     damage, if our invoker is ignoring this signal.  */
1198
1199
#ifdef HAVE_WAIT_NOHANG
1200
# if defined SIGCHLD
1201
  (void) bsd_signal (SIGCHLD, SIG_DFL);
1202
# endif
1203
# if defined SIGCLD && SIGCLD != SIGCHLD
1204
  (void) bsd_signal (SIGCLD, SIG_DFL);
1205
# endif
1206
#endif
1207
1208
  output_init (NULL);
1209
1210
  /* Figure out where this program lives.  */
1211
1212
  if (argv[0] == 0)
1213
    argv[0] = (char *)"";
1214
  if (argv[0][0] == '\0')
1215
    program = "make";
1216
  else
1217
    {
1218
#if defined(HAVE_DOS_PATHS)
1219
      const char* start = argv[0];
1220
1221
      /* Skip an initial drive specifier if present.  */
1222
      if (isalpha ((unsigned char)start[0]) && start[1] == ':')
1223
        start += 2;
1224
1225
      if (start[0] == '\0')
1226
        program = "make";
1227
      else
1228
        {
1229
          program = start + strlen (start);
1230
          while (program > start && ! STOP_SET (program[-1], MAP_DIRSEP))
1231
            --program;
1232
1233
          /* Remove the .exe extension if present.  */
1234
          {
1235
            size_t len = strlen (program);
1236
            if (len > 4 && streq (&program[len - 4], ".exe"))
1237
              program = xstrndup (program, len - 4);
1238
          }
1239
        }
1240
#elif defined(VMS)
1241
      set_program_name (argv[0]);
1242
      program = program_name;
1243
      {
1244
        const char *shell;
1245
        char pwdbuf[256];
1246
        char *pwd;
1247
        shell = getenv ("SHELL");
1248
        if (shell != NULL)
1249
          vms_gnv_shell = 1;
1250
1251
        /* Need to know if CRTL set to report UNIX paths.  Use getcwd as
1252
           it works on all versions of VMS. */
1253
        pwd = getcwd(pwdbuf, 256);
1254
        if (pwd[0] == '/')
1255
          vms_report_unix_paths = 1;
1256
1257
        vms_use_mcr_command = get_vms_env_flag ("GNV$MAKE_USE_MCR", 0);
1258
1259
        vms_always_use_cmd_file = get_vms_env_flag ("GNV$MAKE_USE_CMD_FILE", 0);
1260
1261
        /* Legacy behavior is on VMS is older behavior that needed to be
1262
           changed to be compatible with standard make behavior.
1263
           For now only completely disable when running under a Bash shell.
1264
           TODO: Update VMS built in recipes and macros to not need this
1265
           behavior, at which time the default may change. */
1266
        vms_legacy_behavior = get_vms_env_flag ("GNV$MAKE_OLD_VMS",
1267
                                                !vms_gnv_shell);
1268
1269
        /* VMS was changed to use a comma separator in the past, but that is
1270
           incompatible with built in functions that expect space separated
1271
           lists.  Allow this to be selectively turned off. */
1272
        vms_comma_separator = get_vms_env_flag ("GNV$MAKE_COMMA",
1273
                                                vms_legacy_behavior);
1274
1275
        /* Some Posix shell syntax options are incompatible with VMS syntax.
1276
           VMS requires double quotes for strings and escapes quotes
1277
           differently.  When this option is active, VMS will try
1278
           to simulate Posix shell simulations instead of using
1279
           VMS DCL behavior. */
1280
        vms_unix_simulation = get_vms_env_flag ("GNV$MAKE_SHELL_SIM",
1281
                                                !vms_legacy_behavior);
1282
1283
      }
1284
      if (need_vms_symbol () && !vms_use_mcr_command)
1285
        create_foreign_command (program_name, argv[0]);
1286
#else
1287
      program = strrchr (argv[0], '/');
1288
      if (program == 0)
1289
        program = argv[0];
1290
      else
1291
        ++program;
1292
#endif
1293
    }
1294
1295
  /* Set up to access user data (files).  */
1296
  user_access ();
1297
1298
  initialize_global_hash_tables ();
1299
1300
  /* Figure out where we are.  */
1301
1302
#ifdef WINDOWS32
1303
  if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1304
#else
1305
  if (getcwd (current_directory, GET_PATH_MAX) == 0)
1306
#endif
1307
    {
1308
#ifdef  HAVE_GETCWD
1309
      perror_with_name ("getcwd", "");
1310
#else
1311
      OS (error, NILF, "getwd: %s", current_directory);
1312
#endif
1313
      current_directory[0] = '\0';
1314
      directory_before_chdir = 0;
1315
    }
1316
  else
1317
    directory_before_chdir = xstrdup (current_directory);
1318
1319
#ifdef  __MSDOS__
1320
  /* Make sure we will return to the initial directory, come what may.  */
1321
  atexit (msdos_return_to_initial_directory);
1322
#endif
1323
1324
  /* Initialize the special variables.  */
1325
  define_variable_cname (".VARIABLES", "", o_default, 0)->special = 1;
1326
  /* define_variable_cname (".TARGETS", "", o_default, 0)->special = 1; */
1327
  define_variable_cname (".RECIPEPREFIX", "", o_default, 0)->special = 1;
1328
  define_variable_cname (".SHELLFLAGS", "-c", o_default, 0);
1329
  define_variable_cname (".LOADED", "", o_default, 0);
1330
1331
  /* Set up .FEATURES
1332
     Use a separate variable because define_variable_cname() is a macro and
1333
     some compilers (MSVC) don't like conditionals in macros.  */
1334
  {
1335
    const char *features = "target-specific order-only second-expansion"
1336
                           " else-if shortest-stem undefine oneshell nocomment"
2706 by Dmitry Goncharov
[SV 60297] Add .NOTINTERMEDIATE special target
1337
                           " grouped-target extra-prereqs notintermediate"
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1338
#ifndef NO_ARCHIVES
1339
                           " archives"
1340
#endif
1341
#ifdef MAKE_JOBSERVER
1342
                           " jobserver"
1343
#endif
1344
#ifndef NO_OUTPUT_SYNC
1345
                           " output-sync"
1346
#endif
1347
#ifdef MAKE_SYMLINKS
1348
                           " check-symlink"
1349
#endif
1350
#ifdef HAVE_GUILE
1351
                           " guile"
1352
#endif
1353
#ifdef MAKE_LOAD
1354
                           " load"
1355
#endif
2545 by Paul Smith
Update maintainer mode to support debug wait points.
1356
#ifdef MAKE_MAINTAINER_MODE
1357
                           " maintainer"
1358
#endif
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1359
                           ;
1360
1361
    define_variable_cname (".FEATURES", features, o_default, 0);
1362
  }
1363
1364
  /* Configure GNU Guile support */
1365
  guile_gmake_setup (NILF);
1366
1367
  /* Read in variables from the environment.  It is important that this be
1368
     done before $(MAKE) is figured out so its definitions will not be
1369
     from the environment.  */
1370
1371
#ifndef _AMIGA
1372
  {
1373
    unsigned int i;
1374
1375
    for (i = 0; envp[i] != 0; ++i)
1376
      {
1377
        struct variable *v;
1378
        const char *ep = envp[i];
1379
        /* By default, export all variables culled from the environment.  */
1380
        enum variable_export export = v_export;
2495 by Paul Smith
Resolve most of the Windows Visual Studio warnings.
1381
        size_t len;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1382
2675 by Paul Smith
* src/main.c (main): [SV 59601] Check for malformed env. variables
1383
        while (! STOP_SET (*ep, MAP_EQUALS|MAP_NUL))
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1384
          ++ep;
1385
1386
        /* If there's no equals sign it's a malformed environment.  Ignore.  */
1387
        if (*ep == '\0')
1388
          continue;
1389
1390
#ifdef WINDOWS32
1391
        if (!unix_path && strneq (envp[i], "PATH=", 5))
1392
          unix_path = ep+1;
1393
        else if (!strnicmp (envp[i], "Path=", 5))
1394
          {
1395
            if (!windows32_path)
1396
              windows32_path = ep+1;
1397
            /* PATH gets defined after the loop exits.  */
1398
            continue;
1399
          }
1400
#endif
1401
1402
        /* Length of the variable name, and skip the '='.  */
1403
        len = ep++ - envp[i];
1404
1405
        /* If this is MAKE_RESTARTS, check to see if the "already printed
1406
           the enter statement" flag is set.  */
2803 by Noah Goldstein
Replace strcmp() with memcmp() where possible
1407
        if (len == 13 && memcmp (envp[i], "MAKE_RESTARTS", 13) == 0)
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1408
          {
1409
            if (*ep == '-')
1410
              {
1411
                OUTPUT_TRACED ();
1412
                ++ep;
1413
              }
2806 by Paul Smith
* src/misc.c (make_toui): Parse a string into an unsigned int
1414
            restarts = make_toui (ep, NULL);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1415
            export = v_noexport;
1416
          }
1417
1418
        v = define_variable (envp[i], len, ep, o_env, 1);
1419
1420
        /* POSIX says the value of SHELL set in the makefile won't change the
1421
           value of SHELL given to subprocesses.  */
1422
        if (streq (v->name, "SHELL"))
1423
          {
1424
#ifndef __MSDOS__
1425
            export = v_noexport;
1426
#endif
1427
            shell_var.name = xstrdup ("SHELL");
1428
            shell_var.length = 5;
1429
            shell_var.value = xstrdup (ep);
1430
          }
1431
1432
        v->export = export;
1433
      }
1434
  }
1435
#ifdef WINDOWS32
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1436
  /* If we didn't find a correctly spelled PATH we define PATH as
1437
   * either the first misspelled value or an empty string
1438
   */
1439
  if (!unix_path)
1440
    define_variable_cname ("PATH", windows32_path ? windows32_path : "",
1441
                           o_env, 1)->export = v_export;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1442
#endif
1443
#else /* For Amiga, read the ENV: device, ignoring all dirs */
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1444
  {
1445
    BPTR env, file, old;
1446
    char buffer[1024];
1447
    int len;
1448
    __aligned struct FileInfoBlock fib;
1449
1450
    env = Lock ("ENV:", ACCESS_READ);
1451
    if (env)
1452
      {
1453
        old = CurrentDir (DupLock (env));
1454
        Examine (env, &fib);
1455
1456
        while (ExNext (env, &fib))
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1457
          {
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1458
            if (fib.fib_DirEntryType < 0) /* File */
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1459
              {
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1460
                /* Define an empty variable. It will be filled in
1461
                   variable_lookup(). Makes startup quite a bit faster. */
1462
                define_variable (fib.fib_FileName,
1463
                                 strlen (fib.fib_FileName),
1464
                                 "", o_env, 1)->export = v_export;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1465
              }
1466
          }
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1467
        UnLock (env);
1468
        UnLock (CurrentDir (old));
1469
      }
1470
  }
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1471
#endif
1472
1473
  /* Decode the switches.  */
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1474
  decode_env_switches (STRING_SIZE_TUPLE (GNUMAKEFLAGS_NAME));
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1475
1476
  /* Clear GNUMAKEFLAGS to avoid duplication.  */
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1477
  define_variable_cname (GNUMAKEFLAGS_NAME, "", o_env, 0);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1478
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1479
  decode_env_switches (STRING_SIZE_TUPLE (MAKEFLAGS_NAME));
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1480
1481
#if 0
1482
  /* People write things like:
1483
        MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
1484
     and we set the -p, -i and -e switches.  Doesn't seem quite right.  */
1485
  decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1486
#endif
1487
1488
  /* In output sync mode we need to sync any output generated by reading the
1489
     makefiles, such as in $(info ...) or stderr from $(shell ...) etc.  */
1490
1491
  syncing = make_sync.syncout = (output_sync == OUTPUT_SYNC_LINE
1492
                                 || output_sync == OUTPUT_SYNC_TARGET);
1493
  OUTPUT_SET (&make_sync);
1494
1495
  /* Parse the command line options.  Remember the job slots set this way.  */
1496
  {
1497
    int env_slots = arg_job_slots;
1498
    arg_job_slots = INVALID_JOB_SLOTS;
1499
1500
    decode_switches (argc, (const char **)argv, 0);
1501
    argv_slots = arg_job_slots;
1502
1503
    if (arg_job_slots == INVALID_JOB_SLOTS)
1504
      arg_job_slots = env_slots;
1505
  }
1506
1507
  /* Set a variable specifying whether stdout/stdin is hooked to a TTY.  */
1508
#ifdef HAVE_ISATTY
1509
  if (isatty (fileno (stdout)))
1510
    if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMOUT")))
1511
      {
1512
        const char *tty = TTYNAME (fileno (stdout));
1513
        define_variable_cname ("MAKE_TERMOUT", tty ? tty : DEFAULT_TTYNAME,
1514
                               o_default, 0)->export = v_export;
1515
      }
1516
  if (isatty (fileno (stderr)))
1517
    if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMERR")))
1518
      {
1519
        const char *tty = TTYNAME (fileno (stderr));
1520
        define_variable_cname ("MAKE_TERMERR", tty ? tty : DEFAULT_TTYNAME,
1521
                               o_default, 0)->export = v_export;
1522
      }
1523
#endif
1524
1525
  /* Reset in case the switches changed our minds.  */
1526
  syncing = (output_sync == OUTPUT_SYNC_LINE
1527
             || output_sync == OUTPUT_SYNC_TARGET);
1528
1529
  if (make_sync.syncout && ! syncing)
1530
    output_close (&make_sync);
1531
1532
  make_sync.syncout = syncing;
1533
  OUTPUT_SET (&make_sync);
1534
1535
  /* Figure out the level of recursion.  */
1536
  {
1537
    struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
1538
    if (v && v->value[0] != '\0' && v->value[0] != '-')
2806 by Paul Smith
* src/misc.c (make_toui): Parse a string into an unsigned int
1539
      makelevel = make_toui (v->value, NULL);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1540
    else
1541
      makelevel = 0;
1542
  }
1543
1544
  /* Set always_make_flag if -B was given and we've not restarted already.  */
1545
  always_make_flag = always_make_set && (restarts == 0);
1546
2645 by Paul Smith
[SV 57896] Change directories before checking jobserver auth
1547
  /* If the user didn't specify any print-directory options, compute the
1548
     default setting: disable under -s / print in sub-makes and under -C.  */
1549
1550
  if (print_directory_flag == -1)
1551
    print_directory = !silent_flag && (directories != 0 || makelevel > 0);
1552
  else
1553
    print_directory = print_directory_flag;
1554
1555
  /* If -R was given, set -r too (doesn't make sense otherwise!)  */
1556
  if (no_builtin_variables_flag)
1557
    no_builtin_rules_flag = 1;
1558
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1559
  /* Print version information, and exit.  */
1560
  if (print_version_flag)
1561
    {
1562
      print_version ();
1563
      die (MAKE_SUCCESS);
1564
    }
1565
1566
  if (ISDB (DB_BASIC))
1567
    print_version ();
1568
1569
#ifndef VMS
1570
  /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
1571
     (If it is a relative pathname with a slash, prepend our directory name
1572
     so the result will run the same program regardless of the current dir.
1573
     If it is a name with no slash, we can only hope that PATH did not
1574
     find it in the current directory.)  */
1575
#ifdef WINDOWS32
1576
  /*
1577
   * Convert from backslashes to forward slashes for
1578
   * programs like sh which don't like them. Shouldn't
1579
   * matter if the path is one way or the other for
1580
   * CreateProcess().
1581
   */
1582
  if (strpbrk (argv[0], "/:\\") || strstr (argv[0], "..")
1583
      || strneq (argv[0], "//", 2))
1584
    argv[0] = xstrdup (w32ify (argv[0], 1));
1585
#else /* WINDOWS32 */
1586
#if defined (__MSDOS__) || defined (__EMX__)
1587
  if (strchr (argv[0], '\\'))
1588
    {
1589
      char *p;
1590
1591
      argv[0] = xstrdup (argv[0]);
1592
      for (p = argv[0]; *p; p++)
1593
        if (*p == '\\')
1594
          *p = '/';
1595
    }
1596
  /* If argv[0] is not in absolute form, prepend the current
1597
     directory.  This can happen when Make is invoked by another DJGPP
1598
     program that uses a non-absolute name.  */
1599
  if (current_directory[0] != '\0'
1600
      && argv[0] != 0
1601
      && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
1602
# ifdef __EMX__
1603
      /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
1604
      && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
1605
# endif
1606
      )
1607
    argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
1608
#else  /* !__MSDOS__ */
1609
  if (current_directory[0] != '\0'
1610
      && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0
1611
#ifdef HAVE_DOS_PATHS
1612
      && (argv[0][0] != '\\' && (!argv[0][0] || argv[0][1] != ':'))
1613
      && strchr (argv[0], '\\') != 0
1614
#endif
1615
      )
1616
    argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
1617
#endif /* !__MSDOS__ */
1618
#endif /* WINDOWS32 */
1619
#endif
1620
1621
  /* We may move, but until we do, here we are.  */
1622
  starting_directory = current_directory;
1623
2645 by Paul Smith
[SV 57896] Change directories before checking jobserver auth
1624
  /* If there were -C flags, move ourselves about.  */
1625
  if (directories != 0)
1626
    {
1627
      unsigned int i;
1628
      for (i = 0; directories->list[i] != 0; ++i)
1629
        {
1630
          const char *dir = directories->list[i];
1631
#ifdef WINDOWS32
1632
          /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1633
             But allow -C/ just in case someone wants that.  */
1634
          {
1635
            char *p = (char *)dir + strlen (dir) - 1;
1636
            while (p > dir && (p[0] == '/' || p[0] == '\\'))
1637
              --p;
1638
            p[1] = '\0';
1639
          }
1640
#endif
1641
          if (chdir (dir) < 0)
1642
            pfatal_with_name (dir);
1643
        }
1644
    }
1645
1646
#ifdef WINDOWS32
1647
  /*
1648
   * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1649
   * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1650
   *
1651
   * The functions in dir.c can incorrectly cache information for "."
1652
   * before we have changed directory and this can cause file
1653
   * lookups to fail because the current directory (.) was pointing
1654
   * at the wrong place when it was first evaluated.
1655
   */
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1656
  no_default_sh_exe = !find_and_set_default_shell (NULL);
2645 by Paul Smith
[SV 57896] Change directories before checking jobserver auth
1657
#endif /* WINDOWS32 */
1658
1659
  /* If we chdir'ed, figure out where we are now.  */
1660
  if (directories)
1661
    {
1662
#ifdef WINDOWS32
1663
      if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1664
#else
1665
      if (getcwd (current_directory, GET_PATH_MAX) == 0)
1666
#endif
1667
        {
1668
#ifdef  HAVE_GETCWD
1669
          perror_with_name ("getcwd", "");
1670
#else
1671
          OS (error, NILF, "getwd: %s", current_directory);
1672
#endif
1673
          starting_directory = 0;
1674
        }
1675
      else
1676
        starting_directory = current_directory;
1677
    }
1678
1679
  define_variable_cname ("CURDIR", current_directory, o_file, 0);
1680
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1681
  /* Validate the arg_job_slots configuration before we define MAKEFLAGS so
1682
     users get an accurate value in their makefiles.
1683
     At this point arg_job_slots is the argv setting, if there is one, else
1684
     the MAKEFLAGS env setting, if there is one.  */
1685
1686
  if (jobserver_auth)
1687
    {
1688
      /* We're a child in an existing jobserver group.  */
1689
      if (argv_slots == INVALID_JOB_SLOTS)
1690
        {
1691
          /* There's no -j option on the command line: check authorization.  */
1692
          if (jobserver_parse_auth (jobserver_auth))
2703 by Paul Smith
[SV 58341] Add non-trivial options to $(MAKEFLAGS)
1693
            /* Success!  Use the jobserver.  */
1694
            goto job_setup_complete;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1695
1696
          /* Oops: we have jobserver-auth but it's invalid :(.  */
1697
          O (error, NILF, _("warning: jobserver unavailable: using -j1.  Add '+' to parent make rule."));
1698
          arg_job_slots = 1;
1699
        }
1700
1701
      /* The user provided a -j setting on the command line so use it: we're
1702
         the master make of a new jobserver group.  */
1703
      else if (!restarts)
1704
        ON (error, NILF,
1705
            _("warning: -j%d forced in submake: resetting jobserver mode."),
1706
            argv_slots);
1707
1708
      /* We can't use our parent's jobserver, so reset.  */
1709
      reset_jobserver ();
1710
    }
1711
1712
 job_setup_complete:
1713
1714
  /* The extra indirection through $(MAKE_COMMAND) is done
1715
     for hysterical raisins.  */
1716
1717
#ifdef VMS
1718
  if (vms_use_mcr_command)
1719
    define_variable_cname ("MAKE_COMMAND", vms_command (argv[0]), o_default, 0);
1720
  else
1721
    define_variable_cname ("MAKE_COMMAND", program, o_default, 0);
1722
#else
1723
  define_variable_cname ("MAKE_COMMAND", argv[0], o_default, 0);
1724
#endif
1725
  define_variable_cname ("MAKE", "$(MAKE_COMMAND)", o_default, 1);
1726
1727
  if (command_variables != 0)
1728
    {
1729
      struct command_variable *cv;
1730
      struct variable *v;
2495 by Paul Smith
Resolve most of the Windows Visual Studio warnings.
1731
      size_t len = 0;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1732
      char *value, *p;
1733
1734
      /* Figure out how much space will be taken up by the command-line
1735
         variable definitions.  */
1736
      for (cv = command_variables; cv != 0; cv = cv->next)
1737
        {
1738
          v = cv->variable;
1739
          len += 2 * strlen (v->name);
1740
          if (! v->recursive)
1741
            ++len;
1742
          ++len;
1743
          len += 2 * strlen (v->value);
1744
          ++len;
1745
        }
1746
1747
      /* Now allocate a buffer big enough and fill it.  */
1748
      p = value = alloca (len);
1749
      for (cv = command_variables; cv != 0; cv = cv->next)
1750
        {
1751
          v = cv->variable;
1752
          p = quote_for_env (p, v->name);
1753
          if (! v->recursive)
1754
            *p++ = ':';
1755
          *p++ = '=';
1756
          p = quote_for_env (p, v->value);
1757
          *p++ = ' ';
1758
        }
1759
      p[-1] = '\0';             /* Kill the final space and terminate.  */
1760
1761
      /* Define an unchangeable variable with a name that no POSIX.2
1762
         makefile could validly use for its own variable.  */
1763
      define_variable_cname ("-*-command-variables-*-", value, o_automatic, 0);
1764
1765
      /* Define the variable; this will not override any user definition.
1766
         Normally a reference to this variable is written into the value of
1767
         MAKEFLAGS, allowing the user to override this value to affect the
1768
         exported value of MAKEFLAGS.  In POSIX-pedantic mode, we cannot
1769
         allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
1770
         a reference to this hidden variable is written instead. */
1771
      define_variable_cname ("MAKEOVERRIDES", "${-*-command-variables-*-}",
1772
                             o_env, 1);
1773
#ifdef VMS
1774
      vms_export_dcl_symbol ("MAKEOVERRIDES", "${-*-command-variables-*-}");
1775
#endif
1776
    }
1777
1778
  /* Read any stdin makefiles into temporary files.  */
1779
1780
  if (makefiles != 0)
1781
    {
1782
      unsigned int i;
1783
      for (i = 0; i < makefiles->idx; ++i)
1784
        if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
1785
          {
1786
            /* This makefile is standard input.  Since we may re-exec
1787
               and thus re-read the makefiles, we read standard input
1788
               into a temporary file and read from that.  */
1789
            FILE *outfile;
1790
            char *template;
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
1791
            char *newnm;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1792
            const char *tmpdir;
1793
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
1794
            if (stdin_offset >= 0)
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1795
              O (fatal, NILF,
2781 by Paul Smith
Remove extraneous characters from fatal() calls
1796
                 _("Makefile from standard input specified twice"));
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1797
1798
#ifdef VMS
1799
# define DEFAULT_TMPDIR     "/sys$scratch/"
1800
#else
1801
# ifdef P_tmpdir
1802
#  define DEFAULT_TMPDIR    P_tmpdir
1803
# else
1804
#  define DEFAULT_TMPDIR    "/tmp"
1805
# endif
1806
#endif
1807
#define DEFAULT_TMPFILE     "GmXXXXXX"
1808
2777 by Paul Smith
tests: Preserve Windows temp environment variables
1809
            if (
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1810
#if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
2777 by Paul Smith
tests: Preserve Windows temp environment variables
1811
                ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0') &&
1812
                ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0') &&
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1813
#endif
2777 by Paul Smith
tests: Preserve Windows temp environment variables
1814
                ((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0'))
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1815
              tmpdir = DEFAULT_TMPDIR;
1816
1817
            template = alloca (strlen (tmpdir) + CSTRLEN (DEFAULT_TMPFILE) + 2);
1818
            strcpy (template, tmpdir);
1819
1820
#ifdef HAVE_DOS_PATHS
1821
            if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
1822
              strcat (template, "/");
1823
#else
1824
# ifndef VMS
1825
            if (template[strlen (template) - 1] != '/')
1826
              strcat (template, "/");
1827
# endif /* !VMS */
1828
#endif /* !HAVE_DOS_PATHS */
1829
1830
            strcat (template, DEFAULT_TMPFILE);
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
1831
            outfile = get_tmpfile (&newnm, template);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1832
            if (outfile == 0)
2777 by Paul Smith
tests: Preserve Windows temp environment variables
1833
              OSS (fatal, NILF,
1834
                   _("fopen: temporary file %s: %s"), newnm, strerror (errno));
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1835
            while (!feof (stdin) && ! ferror (stdin))
1836
              {
1837
                char buf[2048];
2495 by Paul Smith
Resolve most of the Windows Visual Studio warnings.
1838
                size_t n = fread (buf, 1, sizeof (buf), stdin);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1839
                if (n > 0 && fwrite (buf, 1, n, outfile) != n)
2777 by Paul Smith
tests: Preserve Windows temp environment variables
1840
                  OSS (fatal, NILF,
1841
                       _("fwrite: temporary file %s: %s"), newnm, strerror (errno));
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1842
              }
1843
            fclose (outfile);
1844
1845
            /* Replace the name that read_all_makefiles will
1846
               see with the name of the temporary file.  */
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
1847
            makefiles->list[i] = strcache_add (newnm);
1848
            stdin_offset = i;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1849
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
1850
            free (newnm);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1851
          }
1852
    }
1853
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
1854
  /* Make sure the temporary file is never considered updated.  */
1855
  if (stdin_offset >= 0)
1856
    {
1857
      struct file *f = enter_file (makefiles->list[stdin_offset]);
1858
      f->updated = 1;
1859
      f->update_status = us_success;
1860
      f->command_state = cs_finished;
1861
      /* Can't be intermediate, or it'll be removed before make re-exec.  */
1862
      f->intermediate = 0;
1863
      f->dontcare = 0;
1864
      /* Avoid re-exec due to stdin temp file timestamps.  */
1865
      f->last_mtime = f->mtime_before_update = f_mtime (f, 0);
1866
    }
1867
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1868
#ifndef __EMX__ /* Don't use a SIGCHLD handler for OS/2 */
1869
#if !defined(HAVE_WAIT_NOHANG) || defined(MAKE_JOBSERVER)
1870
  /* Set up to handle children dying.  This must be done before
1871
     reading in the makefiles so that 'shell' function calls will work.
1872
1873
     If we don't have a hanging wait we have to fall back to old, broken
1874
     functionality here and rely on the signal handler and counting
1875
     children.
1876
1877
     If we're using the jobs pipe we need a signal handler so that SIGCHLD is
1878
     not ignored; we need it to interrupt the read(2) of the jobserver pipe if
1879
     we're waiting for a token.
1880
1881
     If none of these are true, we don't need a signal handler at all.  */
1882
  {
1883
# if defined SIGCHLD
1884
    bsd_signal (SIGCHLD, child_handler);
1885
# endif
1886
# if defined SIGCLD && SIGCLD != SIGCHLD
1887
    bsd_signal (SIGCLD, child_handler);
1888
# endif
1889
  }
1890
1891
#ifdef HAVE_PSELECT
1892
  /* If we have pselect() then we need to block SIGCHLD so it's deferred.  */
1893
  {
1894
    sigset_t block;
1895
    sigemptyset (&block);
1896
    sigaddset (&block, SIGCHLD);
1897
    if (sigprocmask (SIG_SETMASK, &block, NULL) < 0)
1898
      pfatal_with_name ("sigprocmask(SIG_SETMASK, SIGCHLD)");
1899
  }
1900
#endif
1901
1902
#endif
1903
#endif
1904
1905
  /* Let the user send us SIGUSR1 to toggle the -d flag during the run.  */
1906
#ifdef SIGUSR1
1907
  bsd_signal (SIGUSR1, debug_signal_handler);
1908
#endif
1909
1910
  /* Define the initial list of suffixes for old-style rules.  */
1911
  set_default_suffixes ();
1912
1913
  /* Define the file rules for the built-in suffix rules.  These will later
1914
     be converted into pattern rules.  We used to do this in
1915
     install_default_implicit_rules, but since that happens after reading
1916
     makefiles, it results in the built-in pattern rules taking precedence
1917
     over makefile-specified suffix rules, which is wrong.  */
1918
  install_default_suffix_rules ();
1919
1920
  /* Define some internal and special variables.  */
1921
  define_automatic_variables ();
1922
1923
  /* Set up the MAKEFLAGS and MFLAGS variables for makefiles to see.
1924
     Initialize it to be exported but allow the makefile to reset it.  */
1925
  define_makeflags (0, 0)->export = v_export;
1926
1927
  /* Define the default variables.  */
1928
  define_default_variables ();
1929
1930
  default_file = enter_file (strcache_add (".DEFAULT"));
1931
1932
  default_goal_var = define_variable_cname (".DEFAULT_GOAL", "", o_file, 0);
1933
1934
  /* Evaluate all strings provided with --eval.
1935
     Also set up the $(-*-eval-flags-*-) variable.  */
1936
1937
  if (eval_strings)
1938
    {
2750 by Jouke Witteveen
[SV 60798] Silence bogus GCC10 and GCC11 warnings
1939
      char *p, *endp, *value;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1940
      unsigned int i;
2495 by Paul Smith
Resolve most of the Windows Visual Studio warnings.
1941
      size_t len = (CSTRLEN ("--eval=") + 1) * eval_strings->idx;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1942
1943
      for (i = 0; i < eval_strings->idx; ++i)
1944
        {
1945
          p = xstrdup (eval_strings->list[i]);
1946
          len += 2 * strlen (p);
1947
          eval_buffer (p, NULL);
1948
          free (p);
1949
        }
1950
2750 by Jouke Witteveen
[SV 60798] Silence bogus GCC10 and GCC11 warnings
1951
      p = endp = value = alloca (len);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1952
      for (i = 0; i < eval_strings->idx; ++i)
1953
        {
1954
          strcpy (p, "--eval=");
1955
          p += CSTRLEN ("--eval=");
1956
          p = quote_for_env (p, eval_strings->list[i]);
2750 by Jouke Witteveen
[SV 60798] Silence bogus GCC10 and GCC11 warnings
1957
          endp = p++;
1958
          *endp = ' ';
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1959
        }
2750 by Jouke Witteveen
[SV 60798] Silence bogus GCC10 and GCC11 warnings
1960
      *endp = '\0';
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1961
1962
      define_variable_cname ("-*-eval-flags-*-", value, o_automatic, 0);
1963
    }
1964
1965
  {
1966
    int old_builtin_rules_flag = no_builtin_rules_flag;
1967
    int old_builtin_variables_flag = no_builtin_variables_flag;
1968
    int old_arg_job_slots = arg_job_slots;
1969
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1970
    /* Read all the makefiles.  */
1971
    read_files = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
1972
2703 by Paul Smith
[SV 58341] Add non-trivial options to $(MAKEFLAGS)
1973
    /* Reset switches that are taken from MAKEFLAGS so we don't get dups.  */
1974
    reset_switches ();
1975
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1976
    arg_job_slots = INVALID_JOB_SLOTS;
1977
1978
    /* Decode switches again, for variables set by the makefile.  */
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1979
    decode_env_switches (STRING_SIZE_TUPLE (GNUMAKEFLAGS_NAME));
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1980
1981
    /* Clear GNUMAKEFLAGS to avoid duplication.  */
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1982
    define_variable_cname (GNUMAKEFLAGS_NAME, "", o_override, 0);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1983
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
1984
    decode_env_switches (STRING_SIZE_TUPLE (MAKEFLAGS_NAME));
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
1985
#if 0
1986
    decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1987
#endif
1988
1989
    /* If -j is not set in the makefile, or it was set on the command line,
1990
       reset to use the previous value.  */
1991
    if (arg_job_slots == INVALID_JOB_SLOTS || argv_slots != INVALID_JOB_SLOTS)
1992
      arg_job_slots = old_arg_job_slots;
1993
1994
    else if (jobserver_auth)
1995
      {
1996
        /* Makefile MAKEFLAGS set -j, but we already have a jobserver.
1997
           Make us the master of a new jobserver group.  */
1998
        if (!restarts)
1999
          ON (error, NILF,
2000
              _("warning: -j%d forced in makefile: resetting jobserver mode."),
2001
              arg_job_slots);
2002
2003
        /* We can't use our parent's jobserver, so reset.  */
2004
        reset_jobserver ();
2005
      }
2006
2007
    /* Reset in case the switches changed our mind.  */
2008
    syncing = (output_sync == OUTPUT_SYNC_LINE
2009
               || output_sync == OUTPUT_SYNC_TARGET);
2010
2011
    if (make_sync.syncout && ! syncing)
2012
      output_close (&make_sync);
2013
2014
    make_sync.syncout = syncing;
2015
    OUTPUT_SET (&make_sync);
2016
2794 by Dmitry Goncharov
[SV 62356] If -R is set in the makefile, disable -r
2017
    /* If -R was given, set -r too (doesn't make sense otherwise!)  */
2018
    if (no_builtin_variables_flag)
2019
      no_builtin_rules_flag = 1;
2020
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2021
    /* If we've disabled builtin rules, get rid of them.  */
2022
    if (no_builtin_rules_flag && ! old_builtin_rules_flag)
2023
      {
2024
        if (suffix_file->builtin)
2025
          {
2026
            free_dep_chain (suffix_file->deps);
2027
            suffix_file->deps = 0;
2028
          }
2029
        define_variable_cname ("SUFFIXES", "", o_default, 0);
2030
      }
2031
2032
    /* If we've disabled builtin variables, get rid of them.  */
2033
    if (no_builtin_variables_flag && ! old_builtin_variables_flag)
2034
      undefine_default_variables ();
2035
  }
2036
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
2037
#ifdef WINDOWS32
2038
  /* look one last time after reading all Makefiles */
2039
  if (no_default_sh_exe)
2040
    no_default_sh_exe = !find_and_set_default_shell (NULL);
2041
#endif /* WINDOWS32 */
2042
2043
#if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
2044
  /* We need to know what kind of shell we will be using.  */
2045
  {
2046
    extern int _is_unixy_shell (const char *_path);
2047
    struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
2048
    extern int unixy_shell;
2049
    extern const char *default_shell;
2050
2051
    if (shv && *shv->value)
2052
      {
2053
        char *shell_path = recursively_expand (shv);
2054
2055
        if (shell_path && _is_unixy_shell (shell_path))
2056
          unixy_shell = 1;
2057
        else
2058
          unixy_shell = 0;
2059
        if (shell_path)
2060
          default_shell = shell_path;
2061
      }
2062
  }
2063
#endif /* __MSDOS__ || __EMX__ */
2064
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2065
  /* Final jobserver configuration.
2066
2067
     If we have jobserver_auth then we are a client in an existing jobserver
2068
     group, that's already been verified OK above.  If we don't have
2069
     jobserver_auth and jobserver is enabled, then start a new jobserver.
2070
2071
     arg_job_slots = INVALID_JOB_SLOTS if we don't want -j in MAKEFLAGS
2072
2073
     arg_job_slots = # of jobs of parallelism
2074
2075
     job_slots = 0 for no limits on jobs, or when limiting via jobserver.
2076
2077
     job_slots = 1 for standard non-parallel mode.
2078
2079
     job_slots >1 for old-style parallelism without jobservers.  */
2080
2081
  if (jobserver_auth)
2082
    job_slots = 0;
2083
  else if (arg_job_slots == INVALID_JOB_SLOTS)
2084
    job_slots = 1;
2085
  else
2086
    job_slots = arg_job_slots;
2087
2088
#if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
2089
  if (job_slots != 1
2090
# ifdef __EMX__
2091
      && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
2092
# endif
2093
      )
2094
    {
2095
      O (error, NILF,
2096
         _("Parallel jobs (-j) are not supported on this platform."));
2097
      O (error, NILF, _("Resetting to single job (-j1) mode."));
2098
      arg_job_slots = INVALID_JOB_SLOTS;
2099
      job_slots = 1;
2100
    }
2101
#endif
2102
2103
  /* If we have >1 slot at this point, then we're a top-level make.
2104
     Set up the jobserver.
2105
2106
     Every make assumes that it always has one job it can run.  For the
2107
     submakes it's the token they were given by their parent.  For the top
2108
     make, we just subtract one from the number the user wants.  */
2109
2110
  if (job_slots > 1 && jobserver_setup (job_slots - 1))
2111
    {
2112
      /* Fill in the jobserver_auth for our children.  */
2113
      jobserver_auth = jobserver_get_auth ();
2114
2115
      if (jobserver_auth)
2116
        {
2117
          /* We're using the jobserver so set job_slots to 0.  */
2118
          master_job_slots = job_slots;
2119
          job_slots = 0;
2120
        }
2121
    }
2122
2123
  /* If we're not using parallel jobs, then we don't need output sync.
2124
     This is so people can enable output sync in GNUMAKEFLAGS or similar, but
2125
     not have it take effect unless parallel builds are enabled.  */
2126
  if (syncing && job_slots == 1)
2127
    {
2128
      OUTPUT_UNSET ();
2129
      output_close (&make_sync);
2130
      syncing = 0;
2131
      output_sync = OUTPUT_SYNC_NONE;
2132
    }
2133
2134
#ifndef MAKE_SYMLINKS
2135
  if (check_symlink_flag)
2136
    {
2137
      O (error, NILF, _("Symbolic links not supported: disabling -L."));
2138
      check_symlink_flag = 0;
2139
    }
2140
#endif
2141
2142
  /* Set up MAKEFLAGS and MFLAGS again, so they will be right.  */
2143
2144
  define_makeflags (1, 0);
2145
2146
  /* Make each 'struct goaldep' point at the 'struct file' for the file
2147
     depended on.  Also do magic for special targets.  */
2148
2149
  snap_deps ();
2150
2151
  /* Convert old-style suffix rules to pattern rules.  It is important to
2152
     do this before installing the built-in pattern rules below, so that
2153
     makefile-specified suffix rules take precedence over built-in pattern
2154
     rules.  */
2155
2156
  convert_to_pattern ();
2157
2158
  /* Install the default implicit pattern rules.
2159
     This used to be done before reading the makefiles.
2160
     But in that case, built-in pattern rules were in the chain
2161
     before user-defined ones, so they matched first.  */
2162
2163
  install_default_implicit_rules ();
2164
2625 by Paul Smith
Support the .EXTRA_PREREQS special variable
2165
  /* Compute implicit rule limits and do magic for pattern rules.  */
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2166
2625 by Paul Smith
Support the .EXTRA_PREREQS special variable
2167
  snap_implicit_rules ();
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2168
2169
  /* Construct the listings of directories in VPATH lists.  */
2170
2171
  build_vpath_lists ();
2172
2173
  /* Mark files given with -o flags as very old and as having been updated
2174
     already, and files given with -W flags as brand new (time-stamp as far
2175
     as possible into the future).  If restarts is set we'll do -W later.  */
2176
2177
  if (old_files != 0)
2178
    {
2179
      const char **p;
2180
      for (p = old_files->list; *p != 0; ++p)
2181
        {
2182
          struct file *f = enter_file (*p);
2183
          f->last_mtime = f->mtime_before_update = OLD_MTIME;
2184
          f->updated = 1;
2185
          f->update_status = us_success;
2186
          f->command_state = cs_finished;
2187
        }
2188
    }
2189
2190
  if (!restarts && new_files != 0)
2191
    {
2192
      const char **p;
2193
      for (p = new_files->list; *p != 0; ++p)
2194
        {
2195
          struct file *f = enter_file (*p);
2196
          f->last_mtime = f->mtime_before_update = NEW_MTIME;
2197
        }
2198
    }
2199
2200
  /* Initialize the remote job module.  */
2201
  remote_setup ();
2202
2203
  /* Dump any output we've collected.  */
2204
2205
  OUTPUT_UNSET ();
2206
  output_close (&make_sync);
2207
2208
  if (read_files)
2209
    {
2210
      /* Update any makefiles if necessary.  */
2211
2212
      FILE_TIMESTAMP *makefile_mtimes;
2721 by Paul Smith
[SV 60795] Don't remake phony included makefiles and show errors
2213
      struct goaldep *skipped_makefiles = NULL;
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
2214
      const char **nargv = (const char **) argv;
2721 by Paul Smith
[SV 60795] Don't remake phony included makefiles and show errors
2215
      int any_failed = 0;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2216
      enum update_status status;
2217
2218
      DB (DB_BASIC, (_("Updating makefiles....\n")));
2219
2659 by Paul Smith
[SV 58735] Define the order that makefiles are rebuilt.
2220
      /* Count the makefiles, and reverse the order so that we attempt to
2221
         rebuild them in the order they were read.  */
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2222
      {
2223
        unsigned int num_mkfiles = 0;
2659 by Paul Smith
[SV 58735] Define the order that makefiles are rebuilt.
2224
        struct goaldep *d = read_files;
2225
        read_files = NULL;
2226
        while (d != NULL)
2227
          {
2228
            struct goaldep *t = d;
2229
            d = d->next;
2230
            t->next = read_files;
2231
            read_files = t;
2232
            ++num_mkfiles;
2233
          }
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2234
2235
        makefile_mtimes = alloca (num_mkfiles * sizeof (FILE_TIMESTAMP));
2236
      }
2237
2238
      /* Remove any makefiles we don't want to try to update.  Record the
2239
         current modtimes of the others so we can compare them later.  */
2240
      {
2241
        struct goaldep *d = read_files;
2242
        struct goaldep *last = NULL;
2243
        unsigned int mm_idx = 0;
2244
2245
        while (d != 0)
2246
          {
2721 by Paul Smith
[SV 60795] Don't remake phony included makefiles and show errors
2247
            int skip = 0;
2248
            struct file *f = d->file;
2249
2250
            /* Check for makefiles that are either phony or a :: target with
2251
               commands, but no dependencies.  These will always be remade,
2252
               which will cause an infinite restart loop, so don't try to
2253
               remake it (this will only happen if your makefiles are written
2254
               exceptionally stupidly; but if you work for Athena, that's how
2255
               you write your makefiles.)  */
2256
2257
            if (f->phony)
2258
              skip = 1;
2259
            else
2260
              for (f = f->double_colon; f != NULL; f = f->prev)
2261
                if (f->deps == NULL && f->cmds != NULL)
2262
                  {
2263
                    skip = 1;
2264
                    break;
2265
                  }
2266
2267
            if (!skip)
2268
              {
2269
                makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
2270
                last = d;
2271
                d = d->next;
2272
              }
2273
            else
2274
              {
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2275
                DB (DB_VERBOSE,
2276
                    (_("Makefile '%s' might loop; not remaking it.\n"),
2277
                     f->name));
2278
2279
                if (last)
2280
                  last->next = d->next;
2281
                else
2282
                  read_files = d->next;
2283
2721 by Paul Smith
[SV 60795] Don't remake phony included makefiles and show errors
2284
                if (d->error && ! (d->flags & RM_DONTCARE))
2285
                  {
2286
                    /* This file won't be rebuilt, was not found, and we care,
2287
                       so remember it to report later.  */
2288
                    d->next = skipped_makefiles;
2289
                    skipped_makefiles = d;
2290
                    any_failed = 1;
2291
                  }
2292
                else
2293
                  free_goaldep (d);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2294
2295
                d = last ? last->next : read_files;
2296
              }
2297
          }
2298
      }
2299
2300
      /* Set up 'MAKEFLAGS' specially while remaking makefiles.  */
2301
      define_makeflags (1, 1);
2302
2303
      {
2304
        int orig_db_level = db_level;
2305
2306
        if (! ISDB (DB_MAKEFILES))
2307
          db_level = DB_NONE;
2308
2309
        rebuilding_makefiles = 1;
2310
        status = update_goal_chain (read_files);
2311
        rebuilding_makefiles = 0;
2312
2313
        db_level = orig_db_level;
2314
      }
2315
2721 by Paul Smith
[SV 60795] Don't remake phony included makefiles and show errors
2316
      /* Report errors for makefiles that needed to be remade but were not.  */
2317
      while (skipped_makefiles != NULL)
2318
        {
2319
          struct goaldep *d = skipped_makefiles;
2320
          const char *err = strerror (d->error);
2321
2322
          OSS (error, &d->floc, _("%s: %s"), dep_name (d), err);
2323
2324
          skipped_makefiles = skipped_makefiles->next;
2325
          free_goaldep (d);
2326
        }
2327
2328
      /* If we couldn't build something we need but otherwise we succeeded,
2329
         reset the status.  */
2330
      if (any_failed && status == us_success)
2331
        status = us_none;
2332
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2333
      switch (status)
2334
        {
2335
        case us_question:
2336
          /* The only way this can happen is if the user specified -q and asked
2337
             for one of the makefiles to be remade as a target on the command
2338
             line.  Since we're not actually updating anything with -q we can
2339
             treat this as "did nothing".  */
2710 by Paul Smith
[SV 60595] Restart whenever any makefile is rebuilt
2340
          break;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2341
2342
        case us_none:
2710 by Paul Smith
[SV 60595] Restart whenever any makefile is rebuilt
2343
          /* No makefiles needed to be updated.  If we couldn't read some
2344
             included file that we care about, fail.  */
2758 by Paul Smith
[SV 61226] Revert changes to detect missing included files
2345
          if (0)
2346
            {
2347
              /* This runs afoul of https://savannah.gnu.org/bugs/?61226
2348
                 The problem is that many makefiles use a "dummy rule" to
2349
                 pretend that an included file is rebuilt, without actually
2350
                 rebuilding it, and this has always worked.  There are a
2351
                 number of solutions proposed in that bug but for now we'll
2352
                 put things back so they work the way they did before.  */
2353
              struct goaldep *d;
2710 by Paul Smith
[SV 60595] Restart whenever any makefile is rebuilt
2354
2758 by Paul Smith
[SV 61226] Revert changes to detect missing included files
2355
              for (d = read_files; d != 0; d = d->next)
2356
                if (d->error && ! (d->flags & RM_DONTCARE))
2357
                  {
2358
                    /* This makefile couldn't be loaded, and we care.  */
2359
                    const char *err = strerror (d->error);
2360
                    OSS (error, &d->floc, _("%s: %s"), dep_name (d), err);
2361
                    any_failed = 1;
2362
                  }
2363
            }
2364
          break;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2365
2366
        case us_failed:
2367
          /* Failed to update.  Figure out if we care.  */
2368
          {
2369
            /* Nonzero if any makefile was successfully remade.  */
2370
            int any_remade = 0;
2371
            unsigned int i;
2372
            struct goaldep *d;
2373
2374
            for (i = 0, d = read_files; d != 0; ++i, d = d->next)
2375
              {
2376
                if (d->file->updated)
2377
                  {
2378
                    /* This makefile was updated.  */
2379
                    if (d->file->update_status == us_success)
2721 by Paul Smith
[SV 60795] Don't remake phony included makefiles and show errors
2380
                      /* It was successfully updated.  */
2381
                      any_remade |= (file_mtime_no_search (d->file)
2382
                                     != makefile_mtimes[i]);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2383
                    else if (! (d->flags & RM_DONTCARE))
2384
                      {
2385
                        FILE_TIMESTAMP mtime;
2386
                        /* The update failed and this makefile was not
2387
                           from the MAKEFILES variable, so we care.  */
2710 by Paul Smith
[SV 60595] Restart whenever any makefile is rebuilt
2388
                        OS (error, &d->floc,
2389
                            _("Failed to remake makefile '%s'."),
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2390
                            d->file->name);
2391
                        mtime = file_mtime_no_search (d->file);
2392
                        any_remade |= (mtime != NONEXISTENT_MTIME
2393
                                       && mtime != makefile_mtimes[i]);
2394
                        makefile_status = MAKE_FAILURE;
2395
                      }
2396
                  }
2721 by Paul Smith
[SV 60795] Don't remake phony included makefiles and show errors
2397
2398
                /* This makefile was not found at all.  */
2399
                else if (! (d->flags & RM_DONTCARE))
2400
                  {
2401
                    const char *dnm = dep_name (d);
2402
2403
                    /* This is a makefile we care about.  See how much.  */
2404
                    if (d->flags & RM_INCLUDED)
2405
                      /* An included makefile.  We don't need to die, but we
2406
                         do want to complain.  */
2407
                      OS (error, &d->floc,
2408
                          _("Included makefile '%s' was not found."), dnm);
2409
                    else
2410
                      {
2411
                        /* A normal makefile.  We must die later.  */
2412
                        OS (error, NILF, _("Makefile '%s' was not found"), dnm);
2413
                        any_failed = 1;
2414
                      }
2415
                  }
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2416
              }
2417
2418
            if (any_remade)
2419
              goto re_exec;
2721 by Paul Smith
[SV 60795] Don't remake phony included makefiles and show errors
2420
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2421
            break;
2422
          }
2423
2424
        case us_success:
2425
        re_exec:
2426
          /* Updated successfully.  Re-exec ourselves.  */
2427
2428
          remove_intermediates (0);
2429
2430
          if (print_data_base_flag)
2431
            print_data_base ();
2432
2433
          clean_jobserver (0);
2434
2435
          if (makefiles != 0)
2436
            {
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
2437
              /* Makefile names might have changed due to expansion.
2438
                 It's possible we'll need one extra argument:
2439
                   make -Rf-
2440
                 will expand to:
2441
                   make -R --temp-stdin=<tmpfile>
2442
                 so allocate more space.
2443
              */
2444
              int mfidx = 0;
2445
              char** av = argv;
2446
              const char** nv;
2447
2448
              nv = nargv = alloca (sizeof (char*) * (argc + 1 + 1));
2449
              *(nv++) = *(av++);
2450
2451
              for (; *av; ++av, ++nv)
2452
                {
2453
                  size_t len;
2454
                  char *f;
2455
                  char *a = *av;
2456
                  const char *mf = makefiles->list[mfidx];
2457
2458
                  len = strlen (a);
2459
                  assert (len > 0);
2460
2461
                  *nv = a;
2462
2463
                  /* Not an option: we handled option args earlier.  */
2464
                  if (a[0] != '-')
2465
                    continue;
2466
2467
                  /* See if this option specifies a filename.  If so we need
2468
                     to replace it with the value from makefiles->list.
2469
2470
                     To simplify, we'll replace all possible versions of this
2471
                     flag with a simple "-f<name>".  */
2472
2473
                  /* Handle long options.  */
2474
                  if (a[1] == '-')
2475
                    {
2476
                      if (strcmp (a, "--file") == 0 || strcmp (a, "--makefile") == 0)
2477
                        /* Skip the next arg as we'll combine them.  */
2478
                        ++av;
2479
                      else if (!strneq (a, "--file=", 7)
2480
                               && !strneq (a, "--makefile=", 11))
2481
                        continue;
2482
2483
                      if (mfidx == stdin_offset)
2484
                        {
2485
                          char *na = alloca (CSTRLEN ("--temp-stdin=")
2486
                                             + strlen (mf) +  1);
2487
                          sprintf (na, "--temp-stdin=%s", mf);
2488
                          *nv = na;
2489
                        }
2490
                      else
2491
                        {
2492
                          char *na = alloca (strlen (mf) + 3);
2493
                          sprintf (na, "-f%s", mf);
2494
                          *nv = na;
2495
                        }
2496
2497
                      ++mfidx;
2498
                      continue;
2499
                    }
2500
2501
                  /* Handle short options.  If 'f' is the last option, it may
2502
                     be followed by <name>.  */
2503
                  f = strchr (a, 'f');
2504
                  if (!f)
2505
                    continue;
2506
2507
                  /* If there's an extra argument option skip it.  */
2508
                  if (f[1] == '\0')
2509
                    ++av;
2510
2511
                  if (mfidx == stdin_offset)
2512
                    {
2513
                      const size_t al = f - a;
2514
                      char *na;
2515
2516
                      if (al > 1)
2517
                        {
2518
                          /* Preserve the prior options.  */
2519
                          na = alloca (al + 1);
2520
                          memcpy (na, a, al);
2521
                          na[al] = '\0';
2522
                          *(nv++) = na;
2523
                        }
2524
2525
                      /* Remove the "f" and any subsequent content.  */
2526
                      na = alloca (CSTRLEN ("--temp-stdin=") + strlen (mf) + 1);
2527
                      sprintf (na, "--temp-stdin=%s", mf);
2528
                      *nv = na;
2529
                    }
2530
                  else if (f[1] == '\0')
2531
                    /* -f <name> or -xyzf <name>.  Replace the name.  */
2532
                    *(++nv) = mf;
2533
                  else
2534
                    {
2535
                      /* -f<name> or -xyzf<name>. */
2536
                      const size_t al = f - a + 1;
2537
                      const size_t ml = strlen (mf) + 1;
2538
                      char *na = alloca (al + ml);
2539
                      memcpy (na, a, al);
2540
                      memcpy (na + al, mf, ml);
2541
                      *nv = na;
2542
                    }
2543
2544
                  ++mfidx;
2545
                }
2546
2547
              *nv = NULL;
2548
            }
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2549
2550
          if (directories != 0 && directories->idx > 0)
2551
            {
2552
              int bad = 1;
2553
              if (directory_before_chdir != 0)
2554
                {
2555
                  if (chdir (directory_before_chdir) < 0)
2556
                      perror_with_name ("chdir", "");
2557
                  else
2558
                    bad = 0;
2559
                }
2560
              if (bad)
2561
                O (fatal, NILF,
2781 by Paul Smith
Remove extraneous characters from fatal() calls
2562
                   _("Couldn't change back to original directory"));
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2563
            }
2564
2565
          ++restarts;
2566
2567
          if (ISDB (DB_BASIC))
2568
            {
2569
              const char **p;
2570
              printf (_("Re-executing[%u]:"), restarts);
2571
              for (p = nargv; *p != 0; ++p)
2572
                printf (" %s", *p);
2573
              putchar ('\n');
2574
              fflush (stdout);
2575
            }
2576
2577
#ifndef _AMIGA
2578
          {
2579
            char **p;
2580
            for (p = environ; *p != 0; ++p)
2581
              {
2582
                if (strneq (*p, MAKELEVEL_NAME "=", MAKELEVEL_LENGTH+1))
2583
                  {
2584
                    *p = alloca (40);
2585
                    sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2586
#ifdef VMS
2587
                    vms_putenv_symbol (*p);
2588
#endif
2589
                  }
2590
                else if (strneq (*p, "MAKE_RESTARTS=", CSTRLEN ("MAKE_RESTARTS=")))
2591
                  {
2592
                    *p = alloca (40);
2593
                    sprintf (*p, "MAKE_RESTARTS=%s%u",
2594
                             OUTPUT_IS_TRACED () ? "-" : "", restarts);
2595
                    restarts = 0;
2596
                  }
2597
              }
2598
          }
2599
#else /* AMIGA */
2600
          {
2601
            char buffer[256];
2602
2603
            sprintf (buffer, "%u", makelevel);
2604
            SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2605
2606
            sprintf (buffer, "%s%u", OUTPUT_IS_TRACED () ? "-" : "", restarts);
2607
            SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2608
            restarts = 0;
2609
          }
2610
#endif
2611
2612
          /* If we didn't set the restarts variable yet, add it.  */
2613
          if (restarts)
2614
            {
2615
              char *b = alloca (40);
2616
              sprintf (b, "MAKE_RESTARTS=%s%u",
2617
                       OUTPUT_IS_TRACED () ? "-" : "", restarts);
2618
              putenv (b);
2619
            }
2620
2621
          fflush (stdout);
2622
          fflush (stderr);
2623
2518 by Paul Smith
* src/main.c (main): Set jobserver permissions before re-execing
2624
          /* The exec'd "child" will be another make, of course.  */
2625
          jobserver_pre_child(1);
2626
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2627
#ifdef _AMIGA
2628
          exec_command (nargv);
2629
          exit (0);
2630
#elif defined (__EMX__)
2631
          {
2632
            /* It is not possible to use execve() here because this
2633
               would cause the parent process to be terminated with
2634
               exit code 0 before the child process has been terminated.
2635
               Therefore it may be the best solution simply to spawn the
2636
               child process including all file handles and to wait for its
2637
               termination. */
2499 by Aron Barath
* src/makeint.h: Use pid_t to store PIDs, of int.
2638
            pid_t pid;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2639
            int r;
2567 by Paul Smith
Align child_execute_job among different ports
2640
            struct childbase child;
2641
            child.cmd_name = NULL;
2642
            child.output.syncout = 0;
2643
            child.environment = environ;
2644
2645
            pid = child_execute_job (&child, 1, nargv);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2646
2647
            /* is this loop really necessary? */
2648
            do {
2649
              pid = wait (&r);
2650
            } while (pid <= 0);
2651
            /* use the exit code of the child process */
2652
            exit (WIFEXITED(r) ? WEXITSTATUS(r) : EXIT_FAILURE);
2653
          }
2654
#else
2655
#ifdef SET_STACK_SIZE
2656
          /* Reset limits, if necessary.  */
2657
          if (stack_limit.rlim_cur)
2658
            setrlimit (RLIMIT_STACK, &stack_limit);
2659
#endif
2660
          exec_command ((char **)nargv, environ);
2661
#endif
2518 by Paul Smith
* src/main.c (main): Set jobserver permissions before re-execing
2662
          jobserver_post_child(1);
2786 by Dmitry Goncharov
[SV 62145] Remove a stdin temp file on re-exec failure.
2663
2664
          /* Get rid of any stdin temp file.  */
2665
          if (stdin_offset >= 0)
2666
            unlink (makefiles->list[stdin_offset]);
2667
2668
          _exit (127);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2669
        }
2721 by Paul Smith
[SV 60795] Don't remake phony included makefiles and show errors
2670
2671
      if (any_failed)
2672
        die (MAKE_FAILURE);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2673
    }
2674
2675
  /* Set up 'MAKEFLAGS' again for the normal targets.  */
2676
  define_makeflags (1, 0);
2677
2678
  /* Set always_make_flag if -B was given.  */
2679
  always_make_flag = always_make_set;
2680
2681
  /* If restarts is set we haven't set up -W files yet, so do that now.  */
2682
  if (restarts && new_files != 0)
2683
    {
2684
      const char **p;
2685
      for (p = new_files->list; *p != 0; ++p)
2686
        {
2687
          struct file *f = enter_file (*p);
2688
          f->last_mtime = f->mtime_before_update = NEW_MTIME;
2689
        }
2690
    }
2691
2692
  /* If there is a temp file from reading a makefile from stdin, get rid of
2693
     it now.  */
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
2694
  if (stdin_offset >= 0)
2695
    {
2696
      const char *nm = makefiles->list[stdin_offset];
2697
      if (unlink (nm) < 0 && errno != ENOENT)
2698
        perror_with_name (_("unlink (temporary file): "), nm);
2699
      stdin_offset = -1;
2700
    }
2780 by Paul Smith
* src/main.c: Ensure the stdin temp file is deleted when dying.
2701
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2702
  /* If there were no command-line goals, use the default.  */
2703
  if (goals == 0)
2704
    {
2705
      char *p;
2706
2707
      if (default_goal_var->recursive)
2708
        p = variable_expand (default_goal_var->value);
2709
      else
2710
        {
2711
          p = variable_buffer_output (variable_buffer, default_goal_var->value,
2712
                                      strlen (default_goal_var->value));
2713
          *p = '\0';
2714
          p = variable_buffer;
2715
        }
2716
2717
      if (*p != '\0')
2718
        {
2719
          struct file *f = lookup_file (p);
2720
2721
          /* If .DEFAULT_GOAL is a non-existent target, enter it into the
2722
             table and let the standard logic sort it out. */
2723
          if (f == 0)
2724
            {
2725
              struct nameseq *ns;
2726
2727
              ns = PARSE_SIMPLE_SEQ (&p, struct nameseq);
2728
              if (ns)
2729
                {
2730
                  /* .DEFAULT_GOAL should contain one target. */
2731
                  if (ns->next != 0)
2732
                    O (fatal, NILF,
2733
                       _(".DEFAULT_GOAL contains more than one target"));
2734
2735
                  f = enter_file (strcache_add (ns->name));
2736
2737
                  ns->name = 0; /* It was reused by enter_file(). */
2738
                  free_ns_chain (ns);
2739
                }
2740
            }
2741
2742
          if (f)
2743
            {
2744
              goals = alloc_goaldep ();
2745
              goals->file = f;
2746
            }
2747
        }
2748
    }
2749
  else
2750
    lastgoal->next = 0;
2751
2752
2753
  if (!goals)
2754
    {
2755
      struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("MAKEFILE_LIST"));
2756
      if (v && v->value && v->value[0] != '\0')
2757
        O (fatal, NILF, _("No targets"));
2758
2759
      O (fatal, NILF, _("No targets specified and no makefile found"));
2760
    }
2761
2762
  /* Update the goals.  */
2763
2764
  DB (DB_BASIC, (_("Updating goal targets....\n")));
2765
2766
  {
2767
    switch (update_goal_chain (goals))
2768
    {
2769
      case us_none:
2770
        /* Nothing happened.  */
2771
        /* FALLTHROUGH */
2772
      case us_success:
2773
        /* Keep the previous result.  */
2774
        break;
2775
      case us_question:
2776
        /* We are under -q and would run some commands.  */
2777
        makefile_status = MAKE_TROUBLE;
2778
        break;
2779
      case us_failed:
2780
        /* Updating failed.  POSIX.2 specifies exit status >1 for this; */
2781
        makefile_status = MAKE_FAILURE;
2782
        break;
2783
    }
2784
2785
    /* If we detected some clock skew, generate one last warning */
2786
    if (clock_skew_detected)
2787
      O (error, NILF,
2788
         _("warning:  Clock skew detected.  Your build may be incomplete."));
2789
2790
    /* Exit.  */
2791
    die (makefile_status);
2792
  }
2793
2794
  /* NOTREACHED */
2795
  exit (MAKE_SUCCESS);
2796
}
2797

2798
/* Parsing of arguments, decoding of switches.  */
2799
2800
static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
2801
static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
2802
                                  (sizeof (long_option_aliases) /
2803
                                   sizeof (long_option_aliases[0]))];
2804
2805
/* Fill in the string and vector for getopt.  */
2806
static void
2807
init_switches (void)
2808
{
2809
  char *p;
2810
  unsigned int c;
2811
  unsigned int i;
2812
2813
  if (options[0] != '\0')
2814
    /* Already done.  */
2815
    return;
2816
2817
  p = options;
2818
2819
  /* Return switch and non-switch args in order, regardless of
2820
     POSIXLY_CORRECT.  Non-switch args are returned as option 1.  */
2821
  *p++ = '-';
2822
2823
  for (i = 0; switches[i].c != '\0'; ++i)
2824
    {
2551 by Paul Eggert
Pacify Oracle Studio 12.6 in init_switches
2825
      long_options[i].name = (char *) (switches[i].long_name == 0 ? "" :
2567 by Paul Smith
Align child_execute_job among different ports
2826
                                       switches[i].long_name);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2827
      long_options[i].flag = 0;
2828
      long_options[i].val = switches[i].c;
2829
      if (short_option (switches[i].c))
2495 by Paul Smith
Resolve most of the Windows Visual Studio warnings.
2830
        *p++ = (char) switches[i].c;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2831
      switch (switches[i].type)
2832
        {
2833
        case flag:
2834
        case flag_off:
2835
        case ignore:
2836
          long_options[i].has_arg = no_argument;
2837
          break;
2838
2839
        case string:
2840
        case strlist:
2841
        case filename:
2842
        case positive_int:
2843
        case floating:
2844
          if (short_option (switches[i].c))
2845
            *p++ = ':';
2846
          if (switches[i].noarg_value != 0)
2847
            {
2848
              if (short_option (switches[i].c))
2849
                *p++ = ':';
2850
              long_options[i].has_arg = optional_argument;
2851
            }
2852
          else
2853
            long_options[i].has_arg = required_argument;
2854
          break;
2855
        }
2856
    }
2857
  *p = '\0';
2858
  for (c = 0; c < (sizeof (long_option_aliases) /
2859
                   sizeof (long_option_aliases[0]));
2860
       ++c)
2861
    long_options[i++] = long_option_aliases[c];
2862
  long_options[i].name = 0;
2863
}
2864
2865
2866
/* Non-option argument.  It might be a variable definition.  */
2867
static void
2868
handle_non_switch_argument (const char *arg, int env)
2869
{
2870
  struct variable *v;
2871
2872
  if (arg[0] == '-' && arg[1] == '\0')
2873
    /* Ignore plain '-' for compatibility.  */
2874
    return;
2875
2876
#ifdef VMS
2877
  {
2878
    /* VMS DCL quoting can result in foo="bar baz" showing up here.
2879
       Need to remove the double quotes from the value. */
2880
    char * eq_ptr;
2881
    char * new_arg;
2882
    eq_ptr = strchr (arg, '=');
2883
    if ((eq_ptr != NULL) && (eq_ptr[1] == '"'))
2884
      {
2885
         int len;
2886
         int seg1;
2887
         int seg2;
2888
         len = strlen(arg);
2889
         new_arg = alloca(len);
2890
         seg1 = eq_ptr - arg + 1;
2891
         strncpy(new_arg, arg, (seg1));
2892
         seg2 = len - seg1 - 1;
2893
         strncpy(&new_arg[seg1], &eq_ptr[2], seg2);
2894
         new_arg[seg1 + seg2] = 0;
2895
         if (new_arg[seg1 + seg2 - 1] == '"')
2896
           new_arg[seg1 + seg2 - 1] = 0;
2897
         arg = new_arg;
2898
      }
2899
  }
2900
#endif
2901
  v = try_variable_definition (0, arg, o_command, 0);
2902
  if (v != 0)
2903
    {
2904
      /* It is indeed a variable definition.  If we don't already have this
2905
         one, record a pointer to the variable for later use in
2906
         define_makeflags.  */
2907
      struct command_variable *cv;
2908
2909
      for (cv = command_variables; cv != 0; cv = cv->next)
2910
        if (cv->variable == v)
2911
          break;
2912
2913
      if (! cv)
2914
        {
2915
          cv = xmalloc (sizeof (*cv));
2916
          cv->variable = v;
2917
          cv->next = command_variables;
2918
          command_variables = cv;
2919
        }
2920
    }
2921
  else if (! env)
2922
    {
2923
      /* Not an option or variable definition; it must be a goal
2924
         target!  Enter it as a file and add it to the dep chain of
2925
         goals.  */
2926
      struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
2927
      f->cmd_target = 1;
2928
2929
      if (goals == 0)
2930
        {
2931
          goals = alloc_goaldep ();
2932
          lastgoal = goals;
2933
        }
2934
      else
2935
        {
2936
          lastgoal->next = alloc_goaldep ();
2937
          lastgoal = lastgoal->next;
2938
        }
2939
2940
      lastgoal->file = f;
2941
2942
      {
2943
        /* Add this target name to the MAKECMDGOALS variable. */
2944
        struct variable *gv;
2945
        const char *value;
2946
2947
        gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
2948
        if (gv == 0)
2949
          value = f->name;
2950
        else
2951
          {
2952
            /* Paste the old and new values together */
2495 by Paul Smith
Resolve most of the Windows Visual Studio warnings.
2953
            size_t oldlen, newlen;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
2954
            char *vp;
2955
2956
            oldlen = strlen (gv->value);
2957
            newlen = strlen (f->name);
2958
            vp = alloca (oldlen + 1 + newlen + 1);
2959
            memcpy (vp, gv->value, oldlen);
2960
            vp[oldlen] = ' ';
2961
            memcpy (&vp[oldlen + 1], f->name, newlen + 1);
2962
            value = vp;
2963
          }
2964
        define_variable_cname ("MAKECMDGOALS", value, o_default, 0);
2965
      }
2966
    }
2967
}
2968
2969
/* Print a nice usage method.  */
2970
2971
static void
2972
print_usage (int bad)
2973
{
2974
  const char *const *cpp;
2975
  FILE *usageto;
2976
2977
  if (print_version_flag)
2978
    print_version ();
2979
2980
  usageto = bad ? stderr : stdout;
2981
2982
  fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
2983
2984
  for (cpp = usage; *cpp; ++cpp)
2985
    fputs (_(*cpp), usageto);
2986
2987
  if (!remote_description || *remote_description == '\0')
2988
    fprintf (usageto, _("\nThis program built for %s\n"), make_host);
2989
  else
2990
    fprintf (usageto, _("\nThis program built for %s (%s)\n"),
2991
             make_host, remote_description);
2992
2993
  fprintf (usageto, _("Report bugs to <bug-make@gnu.org>\n"));
2994
}
2995
2703 by Paul Smith
[SV 58341] Add non-trivial options to $(MAKEFLAGS)
2996
/* Reset switches that come from MAKEFLAGS and go to MAKEFLAGS.
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
2997
   Before re-parsing MAKEFLAGS, start from scratch.  */
2703 by Paul Smith
[SV 58341] Add non-trivial options to $(MAKEFLAGS)
2998
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
2999
void
2703 by Paul Smith
[SV 58341] Add non-trivial options to $(MAKEFLAGS)
3000
reset_switches ()
3001
{
3002
  const struct command_switch *cs;
3003
3004
  for (cs = switches; cs->c != '\0'; ++cs)
3005
    if (cs->value_ptr && cs->env && cs->toenv)
3006
      switch (cs->type)
3007
        {
3008
        case ignore:
3009
          break;
3010
3011
        case flag:
3012
        case flag_off:
3013
          if (cs->default_value)
3014
            *(int *) cs->value_ptr = *(int *) cs->default_value;
3015
          break;
3016
3017
        case positive_int:
3018
        case string:
3019
          /* These types are handled specially... leave them alone :(  */
3020
          break;
3021
3022
        case floating:
3023
          if (cs->default_value)
3024
            *(double *) cs->value_ptr = *(double *) cs->default_value;
3025
          break;
3026
3027
        case filename:
3028
        case strlist:
3029
          {
3030
            /* The strings are in the cache so don't free them.  */
3031
            struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3032
            if (sl)
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
3033
              {
3034
                sl->idx = 0;
3035
                sl->list[0] = 0;
3036
              }
2703 by Paul Smith
[SV 58341] Add non-trivial options to $(MAKEFLAGS)
3037
          }
3038
          break;
3039
3040
        default:
3041
          abort ();
3042
        }
3043
}
3044
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3045
/* Decode switches from ARGC and ARGV.
3046
   They came from the environment if ENV is nonzero.  */
3047
3048
static void
3049
decode_switches (int argc, const char **argv, int env)
3050
{
3051
  int bad = 0;
3052
  const struct command_switch *cs;
3053
  struct stringlist *sl;
3054
  int c;
3055
3056
  /* getopt does most of the parsing for us.
3057
     First, get its vectors set up.  */
3058
3059
  init_switches ();
3060
3061
  /* Let getopt produce error messages for the command line,
3062
     but not for options from the environment.  */
3063
  opterr = !env;
3064
  /* Reset getopt's state.  */
3065
  optind = 0;
3066
3067
  while (optind < argc)
3068
    {
3069
      const char *coptarg;
3070
3071
      /* Parse the next argument.  */
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
3072
      c = getopt_long (argc, (char *const *)argv, options, long_options, NULL);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3073
      coptarg = optarg;
3074
      if (c == EOF)
3075
        /* End of arguments, or "--" marker seen.  */
3076
        break;
3077
      else if (c == 1)
3078
        /* An argument not starting with a dash.  */
3079
        handle_non_switch_argument (coptarg, env);
3080
      else if (c == '?')
3081
        /* Bad option.  We will print a usage message and die later.
3082
           But continue to parse the other options so the user can
3083
           see all he did wrong.  */
3084
        bad = 1;
3085
      else
3086
        for (cs = switches; cs->c != '\0'; ++cs)
3087
          if (cs->c == c)
3088
            {
3089
              /* Whether or not we will actually do anything with
3090
                 this switch.  We test this individually inside the
3091
                 switch below rather than just once outside it, so that
3092
                 options which are to be ignored still consume args.  */
3093
              int doit = !env || cs->env;
3094
3095
              switch (cs->type)
3096
                {
3097
                default:
3098
                  abort ();
3099
3100
                case ignore:
3101
                  break;
3102
3103
                case flag:
3104
                case flag_off:
3105
                  if (doit)
3106
                    *(int *) cs->value_ptr = cs->type == flag;
3107
                  break;
3108
3109
                case string:
3110
                case strlist:
3111
                case filename:
3112
                  if (!doit)
3113
                    break;
3114
3115
                  if (! coptarg)
2714 by Paul Smith
* src/main.c (decode_switches): Fix memory leak.
3116
                    coptarg = cs->noarg_value;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3117
                  else if (*coptarg == '\0')
3118
                    {
3119
                      char opt[2] = "c";
3120
                      const char *op = opt;
3121
3122
                      if (short_option (cs->c))
2495 by Paul Smith
Resolve most of the Windows Visual Studio warnings.
3123
                        opt[0] = (char) cs->c;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3124
                      else
3125
                        op = cs->long_name;
3126
3127
                      error (NILF, strlen (op),
3128
                             _("the '%s%s' option requires a non-empty string argument"),
3129
                             short_option (cs->c) ? "-" : "--", op);
3130
                      bad = 1;
3131
                      break;
3132
                    }
3133
3134
                  if (cs->type == string)
3135
                    {
3136
                      char **val = (char **)cs->value_ptr;
3137
                      free (*val);
3138
                      *val = xstrdup (coptarg);
3139
                      break;
3140
                    }
3141
3142
                  sl = *(struct stringlist **) cs->value_ptr;
3143
                  if (sl == 0)
3144
                    {
3145
                      sl = xmalloc (sizeof (struct stringlist));
3146
                      sl->max = 5;
3147
                      sl->idx = 0;
3148
                      sl->list = xmalloc (5 * sizeof (char *));
3149
                      *(struct stringlist **) cs->value_ptr = sl;
3150
                    }
3151
                  else if (sl->idx == sl->max - 1)
3152
                    {
3153
                      sl->max += 5;
3154
                      /* MSVC erroneously warns without a cast here.  */
3155
                      sl->list = xrealloc ((void *)sl->list,
3156
                                           sl->max * sizeof (char *));
3157
                    }
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
3158
                  if (cs->type == strlist)
3159
                    sl->list[sl->idx++] = xstrdup (coptarg);
3160
                  else if (cs->c == TEMP_STDIN_OPT)
3161
                    {
3162
                      if (stdin_offset > 0)
3163
                        fatal (NILF, 0, "INTERNAL: multiple --temp-stdin options provided!");
3164
                      /* We don't need to expand the temp file.  */
3165
                      stdin_offset = sl->idx;
3166
                      sl->list[sl->idx++] = strcache_add (coptarg);
3167
                    }
3168
                  else
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3169
                    sl->list[sl->idx++] = expand_command_line_file (coptarg);
3170
                  sl->list[sl->idx] = 0;
3171
                  break;
3172
3173
                case positive_int:
3174
                  /* See if we have an option argument; if we do require that
3175
                     it's all digits, not something like "10foo".  */
3176
                  if (coptarg == 0 && argc > optind)
3177
                    {
3178
                      const char *cp;
3179
                      for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
3180
                        ;
3181
                      if (cp[0] == '\0')
3182
                        coptarg = argv[optind++];
3183
                    }
3184
3185
                  if (!doit)
3186
                    break;
3187
3188
                  if (coptarg)
3189
                    {
2806 by Paul Smith
* src/misc.c (make_toui): Parse a string into an unsigned int
3190
                      const char *err;
3191
                      unsigned int i = make_toui (coptarg, &err);
3192
3193
                      if (err || i == 0)
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3194
                        {
3195
                          error (NILF, 0,
3196
                                 _("the '-%c' option requires a positive integer argument"),
3197
                                 cs->c);
3198
                          bad = 1;
3199
                        }
3200
                      else
3201
                        *(unsigned int *) cs->value_ptr = i;
3202
                    }
3203
                  else
3204
                    *(unsigned int *) cs->value_ptr
3205
                      = *(unsigned int *) cs->noarg_value;
3206
                  break;
3207
3208
                case floating:
3209
                  if (coptarg == 0 && optind < argc
3210
                      && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
3211
                    coptarg = argv[optind++];
3212
3213
                  if (doit)
2703 by Paul Smith
[SV 58341] Add non-trivial options to $(MAKEFLAGS)
3214
                    *(double *) cs->value_ptr = (coptarg != 0 ? atof (coptarg)
3215
                                                 : *(double *) cs->noarg_value);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3216
3217
                  break;
3218
                }
3219
3220
              /* We've found the switch.  Stop looking.  */
3221
              break;
3222
            }
3223
    }
3224
3225
  /* There are no more options according to getting getopt, but there may
3226
     be some arguments left.  Since we have asked for non-option arguments
3227
     to be returned in order, this only happens when there is a "--"
3228
     argument to prevent later arguments from being options.  */
3229
  while (optind < argc)
3230
    handle_non_switch_argument (argv[optind++], env);
3231
3232
  if (!env && (bad || print_usage_flag))
3233
    {
3234
      print_usage (bad);
3235
      die (bad ? MAKE_FAILURE : MAKE_SUCCESS);
3236
    }
3237
3238
  /* If there are any options that need to be decoded do it now.  */
3239
  decode_debug_flags ();
3240
  decode_output_sync_flags ();
2527 by Paul Smith
[SV 54740] Ensure .SILENT settings do not leak into sub-makes
3241
3242
  /* Perform any special switch handling.  */
3243
  run_silent = silent_flag;
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
3244
3245
  /* Construct the list of include directories to search.  */
3246
  construct_include_path (include_dirs ? include_dirs->list : NULL);
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3247
}
3248
3249
/* Decode switches from environment variable ENVAR (which is LEN chars long).
3250
   We do this by chopping the value into a vector of words, prepending a
3251
   dash to the first word if it lacks one, and passing the vector to
3252
   decode_switches.  */
3253
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
3254
void
2495 by Paul Smith
Resolve most of the Windows Visual Studio warnings.
3255
decode_env_switches (const char *envar, size_t len)
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3256
{
3257
  char *varref = alloca (2 + len + 2);
3258
  char *value, *p, *buf;
3259
  int argc;
3260
  const char **argv;
3261
3262
  /* Get the variable's value.  */
3263
  varref[0] = '$';
3264
  varref[1] = '(';
3265
  memcpy (&varref[2], envar, len);
3266
  varref[2 + len] = ')';
3267
  varref[2 + len + 1] = '\0';
3268
  value = variable_expand (varref);
3269
3270
  /* Skip whitespace, and check for an empty value.  */
3271
  NEXT_TOKEN (value);
3272
  len = strlen (value);
3273
  if (len == 0)
3274
    return;
3275
3276
  /* Allocate a vector that is definitely big enough.  */
3277
  argv = alloca ((1 + len + 1) * sizeof (char *));
3278
3279
  /* getopt will look at the arguments starting at ARGV[1].
3280
     Prepend a spacer word.  */
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
3281
  argv[0] = "";
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3282
  argc = 1;
3283
3284
  /* We need a buffer to copy the value into while we split it into words
3285
     and unquote it.  Set up in case we need to prepend a dash later.  */
3286
  buf = alloca (1 + len + 1);
3287
  buf[0] = '-';
3288
  p = buf+1;
3289
  argv[argc] = p;
3290
  while (*value != '\0')
3291
    {
3292
      if (*value == '\\' && value[1] != '\0')
3293
        ++value;                /* Skip the backslash.  */
3294
      else if (ISBLANK (*value))
3295
        {
3296
          /* End of the word.  */
3297
          *p++ = '\0';
3298
          argv[++argc] = p;
3299
          do
3300
            ++value;
3301
          while (ISBLANK (*value));
3302
          continue;
3303
        }
3304
      *p++ = *value++;
3305
    }
3306
  *p = '\0';
3307
  argv[++argc] = 0;
3308
  assert (p < buf + len + 2);
3309
3310
  if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
3311
    /* The first word doesn't start with a dash and isn't a variable
3312
       definition, so add a dash.  */
3313
    argv[1] = buf;
3314
3315
  /* Parse those words.  */
3316
  decode_switches (argc, argv, 1);
3317
}
3318

3319
/* Quote the string IN so that it will be interpreted as a single word with
3320
   no magic by decode_env_switches; also double dollar signs to avoid
3321
   variable expansion in make itself.  Write the result into OUT, returning
3322
   the address of the next character to be written.
3323
   Allocating space for OUT twice the length of IN is always sufficient.  */
3324
3325
static char *
3326
quote_for_env (char *out, const char *in)
3327
{
3328
  while (*in != '\0')
3329
    {
3330
      if (*in == '$')
3331
        *out++ = '$';
3332
      else if (ISBLANK (*in) || *in == '\\')
3333
        *out++ = '\\';
3334
      *out++ = *in++;
3335
    }
3336
3337
  return out;
3338
}
3339
3340
/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
3341
   command switches.  Include options with args if ALL is nonzero.
3342
   Don't include options with the 'no_makefile' flag set if MAKEFILE.  */
3343
3344
static struct variable *
3345
define_makeflags (int all, int makefile)
3346
{
2531 by Paul Smith
[SV 46013] Allow recursive variable overrides from Makefiles
3347
  const char ref[] = "MAKEOVERRIDES";
3348
  const char posixref[] = "-*-command-variables-*-";
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3349
  const char evalref[] = "$(-*-eval-flags-*-)";
3350
  const struct command_switch *cs;
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
3351
  struct variable *v;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3352
  char *flagstring;
3353
  char *p;
3354
3355
  /* We will construct a linked list of 'struct flag's describing
3356
     all the flags which need to go in MAKEFLAGS.  Then, once we
3357
     know how many there are and their lengths, we can put them all
3358
     together in a string.  */
3359
3360
  struct flag
3361
    {
3362
      struct flag *next;
3363
      const struct command_switch *cs;
3364
      const char *arg;
3365
    };
3366
  struct flag *flags = 0;
3367
  struct flag *last = 0;
2495 by Paul Smith
Resolve most of the Windows Visual Studio warnings.
3368
  size_t flagslen = 0;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3369
#define ADD_FLAG(ARG, LEN) \
3370
  do {                                                                        \
3371
    struct flag *new = alloca (sizeof (struct flag));                         \
3372
    new->cs = cs;                                                             \
3373
    new->arg = (ARG);                                                         \
3374
    new->next = 0;                                                            \
3375
    if (! flags)                                                              \
3376
      flags = new;                                                            \
3377
    else                                                                      \
3378
      last->next = new;                                                       \
3379
    last = new;                                                               \
3380
    if (new->arg == 0)                                                        \
3381
      /* Just a single flag letter: " -x"  */                                 \
3382
      flagslen += 3;                                                          \
3383
    else                                                                      \
3384
      /* " -xfoo", plus space to escape "foo".  */                            \
3385
      flagslen += 1 + 1 + 1 + (3 * (LEN));                                    \
3386
    if (!short_option (cs->c))                                                \
3387
      /* This switch has no single-letter version, so we use the long.  */    \
3388
      flagslen += 2 + strlen (cs->long_name);                                 \
3389
  } while (0)
3390
3391
  for (cs = switches; cs->c != '\0'; ++cs)
3392
    if (cs->toenv && (!makefile || !cs->no_makefile))
3393
      switch (cs->type)
3394
        {
3395
        case ignore:
3396
          break;
3397
3398
        case flag:
3399
        case flag_off:
3400
          if ((!*(int *) cs->value_ptr) == (cs->type == flag_off)
3401
              && (cs->default_value == 0
3402
                  || *(int *) cs->value_ptr != *(int *) cs->default_value))
3403
            ADD_FLAG (0, 0);
3404
          break;
3405
3406
        case positive_int:
3407
          if (all)
3408
            {
3409
              if ((cs->default_value != 0
3410
                   && (*(unsigned int *) cs->value_ptr
3411
                       == *(unsigned int *) cs->default_value)))
3412
                break;
2703 by Paul Smith
[SV 58341] Add non-trivial options to $(MAKEFLAGS)
3413
              if (cs->noarg_value != 0
3414
                  && (*(unsigned int *) cs->value_ptr ==
3415
                      *(unsigned int *) cs->noarg_value))
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3416
                ADD_FLAG ("", 0); /* Optional value omitted; see below.  */
3417
              else
3418
                {
3419
                  char *buf = alloca (30);
3420
                  sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3421
                  ADD_FLAG (buf, strlen (buf));
3422
                }
3423
            }
3424
          break;
3425
3426
        case floating:
2703 by Paul Smith
[SV 58341] Add non-trivial options to $(MAKEFLAGS)
3427
          if (cs->default_value != 0
3428
              && (*(double *) cs->value_ptr == *(double *) cs->default_value))
3429
            break;
3430
          if (cs->noarg_value != 0
3431
              && (*(double *) cs->value_ptr == *(double *) cs->noarg_value))
3432
            ADD_FLAG ("", 0); /* Optional value omitted; see below.  */
3433
          else
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3434
            {
2703 by Paul Smith
[SV 58341] Add non-trivial options to $(MAKEFLAGS)
3435
              char *buf = alloca (100);
3436
              sprintf (buf, "%g", *(double *) cs->value_ptr);
3437
              ADD_FLAG (buf, strlen (buf));
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3438
            }
3439
          break;
3440
3441
        case string:
3442
          if (all)
3443
            {
3444
              p = *((char **)cs->value_ptr);
3445
              if (p)
3446
                ADD_FLAG (p, strlen (p));
3447
            }
3448
          break;
3449
3450
        case filename:
3451
        case strlist:
2703 by Paul Smith
[SV 58341] Add non-trivial options to $(MAKEFLAGS)
3452
          {
3453
            struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3454
            if (sl != 0)
3455
              {
3456
                unsigned int i;
3457
                for (i = 0; i < sl->idx; ++i)
3458
                  ADD_FLAG (sl->list[i], strlen (sl->list[i]));
3459
              }
3460
          }
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3461
          break;
3462
3463
        default:
3464
          abort ();
3465
        }
3466
3467
#undef  ADD_FLAG
3468
3469
  /* Four more for the possible " -- ", plus variable references.  */
2531 by Paul Smith
[SV 46013] Allow recursive variable overrides from Makefiles
3470
  flagslen += 4 + CSTRLEN (posixref) + 4 + CSTRLEN (evalref) + 4;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3471
3472
  /* Construct the value in FLAGSTRING.
3473
     We allocate enough space for a preceding dash and trailing null.  */
3474
  flagstring = alloca (1 + flagslen + 1);
3475
  memset (flagstring, '\0', 1 + flagslen + 1);
3476
  p = flagstring;
3477
3478
  /* Start with a dash, for MFLAGS.  */
3479
  *p++ = '-';
3480
3481
  /* Add simple options as a group.  */
3482
  while (flags != 0 && !flags->arg && short_option (flags->cs->c))
3483
    {
2495 by Paul Smith
Resolve most of the Windows Visual Studio warnings.
3484
      *p++ = (char) flags->cs->c;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3485
      flags = flags->next;
3486
    }
3487
3488
  /* Now add more complex flags: ones with options and/or long names.  */
3489
  while (flags)
3490
    {
3491
      *p++ = ' ';
3492
      *p++ = '-';
3493
3494
      /* Add the flag letter or name to the string.  */
3495
      if (short_option (flags->cs->c))
2495 by Paul Smith
Resolve most of the Windows Visual Studio warnings.
3496
        *p++ = (char) flags->cs->c;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3497
      else
3498
        {
3499
          /* Long options require a double-dash.  */
3500
          *p++ = '-';
3501
          strcpy (p, flags->cs->long_name);
3502
          p += strlen (p);
3503
        }
3504
      /* An omitted optional argument has an ARG of "".  */
3505
      if (flags->arg && flags->arg[0] != '\0')
3506
        {
3507
          if (!short_option (flags->cs->c))
3508
            /* Long options require '='.  */
3509
            *p++ = '=';
3510
          p = quote_for_env (p, flags->arg);
3511
        }
3512
      flags = flags->next;
3513
    }
3514
3515
  /* If no flags at all, get rid of the initial dash.  */
3516
  if (p == &flagstring[1])
3517
    {
3518
      flagstring[0] = '\0';
3519
      p = flagstring;
3520
    }
3521
3522
  /* Define MFLAGS before appending variable definitions.  Omit an initial
3523
     empty dash.  Since MFLAGS is not parsed for flags, there is no reason to
3524
     override any makefile redefinition.  */
3525
  define_variable_cname ("MFLAGS",
3526
                         flagstring + (flagstring[0] == '-' && flagstring[1] == ' ' ? 2 : 0),
3527
                         o_env, 1);
3528
3529
  /* Write a reference to -*-eval-flags-*-, which contains all the --eval
3530
     flag options.  */
3531
  if (eval_strings)
3532
    {
3533
      *p++ = ' ';
3534
      memcpy (p, evalref, CSTRLEN (evalref));
3535
      p += CSTRLEN (evalref);
3536
    }
3537
2531 by Paul Smith
[SV 46013] Allow recursive variable overrides from Makefiles
3538
  if (all)
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3539
    {
2531 by Paul Smith
[SV 46013] Allow recursive variable overrides from Makefiles
3540
      /* If there are any overrides to add, write a reference to
3541
         $(MAKEOVERRIDES), which contains command-line variable definitions.
3542
         Separate the variables from the switches with a "--" arg.  */
3543
3544
      const char *r = posix_pedantic ? posixref : ref;
3545
      size_t l = strlen (r);
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
3546
      v = lookup_variable (r, l);
2531 by Paul Smith
[SV 46013] Allow recursive variable overrides from Makefiles
3547
3548
      if (v && v->value && v->value[0] != '\0')
3549
        {
3550
          strcpy (p, " -- ");
3551
          p += 4;
3552
3553
          *(p++) = '$';
3554
          *(p++) = '(';
3555
          memcpy (p, r, l);
3556
          p += l;
3557
          *(p++) = ')';
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3558
        }
3559
    }
3560
3561
  /* If there is a leading dash, omit it.  */
3562
  if (flagstring[0] == '-')
3563
    ++flagstring;
3564
3565
  /* This used to use o_env, but that lost when a makefile defined MAKEFLAGS.
3566
     Makefiles set MAKEFLAGS to add switches, but we still want to redefine
3567
     its value with the full set of switches.  Then we used o_file, but that
3568
     lost when users added -e, causing a previous MAKEFLAGS env. var. to take
3569
     precedence over the new one.  Of course, an override or command
3570
     definition will still take precedence.  */
2712 by Paul Smith
[SV 45211] Parse MAKEFLAGS immediately when it's reset
3571
  v =  define_variable_cname (MAKEFLAGS_NAME, flagstring,
3572
                              env_overrides ? o_env_override : o_file, 1);
3573
  v->special = 1;
3574
3575
  return v;
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3576
}
3577

3578
/* Print version information.  */
3579
3580
static void
3581
print_version (void)
3582
{
3583
  static int printed_version = 0;
3584
3585
  const char *precede = print_data_base_flag ? "# " : "";
3586
3587
  if (printed_version)
3588
    /* Do it only once.  */
3589
    return;
3590
3591
  printf ("%sGNU Make %s\n", precede, version_string);
3592
3593
  if (!remote_description || *remote_description == '\0')
3594
    printf (_("%sBuilt for %s\n"), precede, make_host);
3595
  else
3596
    printf (_("%sBuilt for %s (%s)\n"),
3597
            precede, make_host, remote_description);
3598
3599
  /* Print this untranslated.  The coding standards recommend translating the
3600
     (C) to the copyright symbol, but this string is going to change every
3601
     year, and none of the rest of it should be translated (including the
3602
     word "Copyright"), so it hardly seems worth it.  */
3603
2774 by Paul Smith
* <all>: Update copyright notices.
3604
  printf ("%sCopyright (C) 1988-2022 Free Software Foundation, Inc.\n",
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3605
          precede);
3606
2748 by Paul Smith
Change HTTP URLs to use HTTPS instead
3607
  printf (_("%sLicense GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>\n\
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3608
%sThis is free software: you are free to change and redistribute it.\n\
3609
%sThere is NO WARRANTY, to the extent permitted by law.\n"),
3610
            precede, precede, precede);
3611
3612
  printed_version = 1;
3613
3614
  /* Flush stdout so the user doesn't have to wait to see the
3615
     version information while make thinks about things.  */
3616
  fflush (stdout);
3617
}
3618
3619
/* Print a bunch of information about this and that.  */
3620
3621
static void
3622
print_data_base (void)
3623
{
3624
  time_t when = time ((time_t *) 0);
3625
3626
  print_version ();
3627
3628
  printf (_("\n# Make data base, printed on %s"), ctime (&when));
3629
3630
  print_variable_data_base ();
3631
  print_dir_data_base ();
3632
  print_rule_data_base ();
3633
  print_file_data_base ();
3634
  print_vpath_data_base ();
3635
  strcache_print_stats ("#");
3636
3637
  when = time ((time_t *) 0);
3638
  printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
3639
}
3640
3641
static void
3642
clean_jobserver (int status)
3643
{
3644
  /* Sanity: have we written all our jobserver tokens back?  If our
3645
     exit status is 2 that means some kind of syntax error; we might not
3646
     have written all our tokens so do that now.  If tokens are left
3647
     after any other error code, that's bad.  */
3648
3649
  if (jobserver_enabled() && jobserver_tokens)
3650
    {
3651
      if (status != 2)
3652
        ON (error, NILF,
3653
            "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3654
            jobserver_tokens);
3655
      else
3656
        /* Don't write back the "free" token */
3657
        while (--jobserver_tokens)
3658
          jobserver_release (0);
3659
    }
3660
3661
3662
  /* Sanity: If we're the master, were all the tokens written back?  */
3663
3664
  if (master_job_slots)
3665
    {
3666
      /* We didn't write one for ourself, so start at 1.  */
3667
      unsigned int tokens = 1 + jobserver_acquire_all ();
3668
3669
      if (tokens != master_job_slots)
3670
        ONN (error, NILF,
3671
             "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3672
             tokens, master_job_slots);
3673
3674
      reset_jobserver ();
3675
    }
3676
}
3677

3678
/* Exit with STATUS, cleaning up as necessary.  */
3679
3680
void
3681
die (int status)
3682
{
3683
  static char dying = 0;
3684
3685
  if (!dying)
3686
    {
3687
      int err;
3688
3689
      dying = 1;
3690
3691
      if (print_version_flag)
3692
        print_version ();
3693
2780 by Paul Smith
* src/main.c: Ensure the stdin temp file is deleted when dying.
3694
      /* Get rid of a temp file from reading a makefile from stdin.  */
2784 by Paul Smith
[SV 62118] Correctly handle -f- options on re-exec
3695
      if (stdin_offset >= 0)
3696
        {
3697
          const char *nm = makefiles->list[stdin_offset];
3698
          if (unlink (nm) < 0 && errno != ENOENT)
3699
            perror_with_name (_("unlink (temporary file): "), nm);
3700
          stdin_offset = -1;
3701
        }
2780 by Paul Smith
* src/main.c: Ensure the stdin temp file is deleted when dying.
3702
2484 by Paul Smith
Rework directory structure to use GNU-recommended "src" directory.
3703
      /* Wait for children to die.  */
3704
      err = (status != 0);
3705
      while (job_slots_used > 0)
3706
        reap_children (1, err);
3707
3708
      /* Let the remote job module clean up its state.  */
3709
      remote_cleanup ();
3710
3711
      /* Remove the intermediate files.  */
3712
      remove_intermediates (0);
3713
3714
      if (print_data_base_flag)
3715
        print_data_base ();
3716
3717
      if (verify_flag)
3718
        verify_file_data_base ();
3719
3720
      clean_jobserver (status);
3721
3722
      if (output_context)
3723
        {
3724
          /* die() might be called in a recipe output context due to an
3725
             $(error ...) function.  */
3726
          output_close (output_context);
3727
3728
          if (output_context != &make_sync)
3729
            output_close (&make_sync);
3730
3731
          OUTPUT_UNSET ();
3732
        }
3733
3734
      output_close (NULL);
3735
3736
      /* Try to move back to the original directory.  This is essential on
3737
         MS-DOS (where there is really only one process), and on Unix it
3738
         puts core files in the original directory instead of the -C
3739
         directory.  Must wait until after remove_intermediates(), or unlinks
3740
         of relative pathnames fail.  */
3741
      if (directory_before_chdir != 0)
3742
        {
3743
          /* If it fails we don't care: shut up GCC.  */
3744
          int _x UNUSED;
3745
          _x = chdir (directory_before_chdir);
3746
        }
3747
    }
3748
3749
  exit (status);
3750
}