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