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.
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
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.
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/>. */
32 # include <proto/dos.h>
38 # include <strings.h> /* for strcasecmp */
40 # include "pathstuff.h"
41 # include "sub_proc.h"
45 # include <sys/types.h>
46 # include <sys/wait.h>
53 int __stack = 20000; /* Make sure we have 20K of stack space */
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;
64 /* Evaluates if a VMS environment option is set, only look at first character */
66 get_vms_env_flag (const char *name, int default_value)
71 value = getenv (name);
75 x = toupper (value[0]);
91 #if defined HAVE_WAITPID || defined HAVE_WAIT3
92 # define HAVE_WAIT_NOHANG
99 # ifndef sun /* Sun has an incorrect decl in a header. */
100 void exit (int) NORETURN;
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);
114 /* True if C is a switch value that corresponds to a short option. */
116 #define short_option(c) ((c) <= CHAR_MAX)
118 /* The structure used to hold the list of strings given
119 in command switches of a type that takes strlist arguments. */
123 const char **list; /* Nil-terminated list of strings. */
124 unsigned int idx; /* Index into above. */
125 unsigned int max; /* Number of pointers allocated. */
129 /* The recognized command switches. */
131 /* Nonzero means do extra verification (that may slow things down). */
135 /* Nonzero means do not print commands to be executed (-s). */
137 static int silent_flag;
138 static const int default_silent_flag = 0;
140 /* Nonzero means either -s was given, or .SILENT-with-no-deps was seen. */
144 /* Nonzero means just touch the files
145 that would appear to need remaking (-t) */
149 /* Nonzero means just print what commands would need to be executed,
150 don't actually execute them (-n). */
154 /* Print debugging info (--debug). */
156 static struct stringlist *db_flags = 0;
157 static int debug_flag = 0;
161 /* Synchronize output (--output-sync). */
163 char *output_sync_option = 0;
165 /* Environment variables override makefile definitions. */
167 int env_overrides = 0;
169 /* Nonzero means ignore status codes returned by commands
170 executed to remake files. Just treat them all as successful (-i). */
172 int ignore_errors_flag = 0;
174 /* Nonzero means don't remake anything, just print the data base
175 that results from reading the makefile (-p). */
177 int print_data_base_flag = 0;
179 /* Nonzero means don't remake anything; just return a nonzero status
180 if the specified targets are not up to date (-q). */
182 int question_flag = 0;
184 /* Nonzero means do not use any of the builtin rules (-r) / variables (-R). */
186 int no_builtin_rules_flag = 0;
187 int no_builtin_variables_flag = 0;
189 /* Nonzero means keep going even if remaking some file fails (-k). */
192 static const int default_keep_going_flag = 0;
194 /* Nonzero means check symlink mtimes. */
196 int check_symlink_flag = 0;
198 /* Nonzero means print directory before starting and when done (-w). */
201 static int print_directory_flag = -1;
202 static const int default_print_directory_flag = -1;
204 /* Nonzero means print version information. */
206 int print_version_flag = 0;
208 /* List of makefiles given with -f switches. */
210 static struct stringlist *makefiles = 0;
212 /* Size of the stack when we started. */
214 #ifdef SET_STACK_SIZE
215 struct rlimit stack_limit;
219 /* Number of job slots for parallelism. */
221 unsigned int job_slots;
223 #define INVALID_JOB_SLOTS (-1)
224 static unsigned int master_job_slots = 0;
225 static int arg_job_slots = INVALID_JOB_SLOTS;
227 static const int default_job_slots = INVALID_JOB_SLOTS;
229 /* Value of job_slots that means no limit. */
231 static const int inf_jobs = 0;
233 /* Authorization for the jobserver. */
235 char *jobserver_auth = NULL;
237 /* Style for the jobserver. */
238 static char *jobserver_style = NULL;
240 /* Shuffle mode for goals and prerequisites. */
242 static char *shuffle_mode = NULL;
244 /* Handle for the mutex to synchronize output of our children under -O. */
246 static char *sync_mutex = NULL;
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;
255 /* List of directories given with -C switches. */
257 static struct stringlist *directories = 0;
259 /* List of include directories given with -I switches. */
261 static struct stringlist *include_dirs = 0;
263 /* List of files given with -o switches. */
265 static struct stringlist *old_files = 0;
267 /* List of files given with -W switches. */
269 static struct stringlist *new_files = 0;
271 /* List of strings to be eval'd. */
272 static struct stringlist *eval_strings = 0;
274 /* If nonzero, we should just print usage and exit. */
276 static int print_usage_flag = 0;
278 /* If nonzero, we should print a warning message
279 for each reference to an undefined variable. */
281 int warn_undefined_variables_flag;
283 /* If nonzero, always build all targets, regardless of whether
284 they appear out of date or not. */
286 static int always_make_set = 0;
287 int always_make_flag = 0;
289 /* If nonzero, we're in the "try to rebuild makefiles" phase. */
291 int rebuilding_makefiles = 0;
293 /* Remember the original value of the SHELL variable, from the environment. */
295 struct variable shell_var;
297 /* This character introduces a command: it's the first char on the line. */
299 char cmd_prefix = '\t';
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. */
304 unsigned long command_count = 1;
306 /* Remember the location of the name of the batch file from stdin. */
308 static int stdin_offset = -1;
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. */
315 static const char *const usage[] =
319 -b, -m Ignored for compatibility.\n"),
321 -B, --always-make Unconditionally make all targets.\n"),
323 -C DIRECTORY, --directory=DIRECTORY\n\
324 Change to DIRECTORY before doing anything.\n"),
326 -d Print lots of debugging information.\n"),
328 --debug[=FLAGS] Print various types of debugging information.\n"),
330 -e, --environment-overrides\n\
331 Environment variables override makefiles.\n"),
333 -E STRING, --eval=STRING Evaluate STRING as a makefile statement.\n"),
335 -f FILE, --file=FILE, --makefile=FILE\n\
336 Read FILE as a makefile.\n"),
338 -h, --help Print this message and exit.\n"),
340 -i, --ignore-errors Ignore errors from recipes.\n"),
342 -I DIRECTORY, --include-dir=DIRECTORY\n\
343 Search DIRECTORY for included makefiles.\n"),
345 -j [N], --jobs[=N] Allow N jobs at once; infinite jobs with no arg.\n"),
347 --jobserver-style=STYLE Select the style of jobserver to use.\n"),
349 -k, --keep-going Keep going when some targets can't be made.\n"),
351 -l [N], --load-average[=N], --max-load[=N]\n\
352 Don't start multiple jobs unless load is below N.\n"),
354 -L, --check-symlink-times Use the latest mtime between symlinks and target.\n"),
356 -n, --just-print, --dry-run, --recon\n\
357 Don't actually run any recipe; just print them.\n"),
359 -o FILE, --old-file=FILE, --assume-old=FILE\n\
360 Consider FILE to be very old and don't remake it.\n"),
362 -O[TYPE], --output-sync[=TYPE]\n\
363 Synchronize output of parallel jobs by TYPE.\n"),
365 -p, --print-data-base Print make's internal database.\n"),
367 -q, --question Run no recipe; exit status says if up to date.\n"),
369 -r, --no-builtin-rules Disable the built-in implicit rules.\n"),
371 -R, --no-builtin-variables Disable the built-in variable settings.\n"),
373 --shuffle[={SEED|random|reverse|none}]\n\
374 Perform shuffle of prerequisites and goals.\n"),
376 -s, --silent, --quiet Don't echo recipes.\n"),
378 --no-silent Echo recipes (disable --silent mode).\n"),
380 -S, --no-keep-going, --stop\n\
383 -t, --touch Touch targets instead of remaking them.\n"),
385 --trace Print tracing information.\n"),
387 -v, --version Print the version number of make and exit.\n"),
389 -w, --print-directory Print the current directory.\n"),
391 --no-print-directory Turn off -w, even if it was turned on implicitly.\n"),
393 -W FILE, --what-if=FILE, --new-file=FILE, --assume-new=FILE\n\
394 Consider FILE to be infinitely new.\n"),
396 --warn-undefined-variables Warn when an undefined variable is referenced.\n"),
400 /* Nonzero if the "--trace" option was given. */
402 static int trace_flag = 0;
404 /* The structure that describes an accepted command switch. */
406 struct command_switch
408 int c; /* The switch character. */
410 enum /* Type of the value. */
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. */
422 void *value_ptr; /* Pointer to the value-holding variable. */
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. */
428 const void *noarg_value; /* Pointer to value used if no arg given. */
429 const void *default_value; /* Pointer to default value. */
431 const char *long_name; /* Long option name. */
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. */
438 #define TEMP_STDIN_OPT (CHAR_MAX+10)
440 static const struct command_switch switches[] =
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,
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,
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" },
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,
472 { 'j', positive_int, &arg_job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,
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" },
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,
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 }
499 /* Secondary long names for options. */
501 static struct option long_option_aliases[] =
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' },
514 /* List of goal targets. */
516 static struct goaldep *goals, *lastgoal;
518 /* List of variables which were defined on the command line
519 (or, equivalently, in MAKEFLAGS). */
521 struct command_variable
523 struct command_variable *next;
524 struct variable *variable;
526 static struct command_variable *command_variables;
528 /* The name we were invoked with. */
532 /* Our current directory before processing any -C options. */
534 char *directory_before_chdir;
536 /* Our current directory after processing all -C options. */
538 char *starting_directory;
540 /* Value of the MAKELEVEL variable at startup (or 0). */
542 unsigned int makelevel;
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
550 struct variable * default_goal_var;
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. */
556 struct file *default_file;
558 /* Nonzero if we have seen the magic '.POSIX' target.
559 This turns on pedantic compliance with POSIX.2. */
563 /* Nonzero if we have seen the '.SECONDEXPANSION' target.
564 This turns on secondary expansion of prerequisites. */
566 int second_expansion;
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. */
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. */
578 int output_sync = OUTPUT_SYNC_NONE;
580 /* Nonzero if we have seen the '.NOTPARALLEL' target.
581 This turns off parallel builds for this invocation of make. */
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. */
589 int clock_skew_detected;
591 /* Map of possible stop characters for searching strings. */
593 # define UCHAR_MAX 255
595 unsigned short stopchar_map[UCHAR_MAX + 1] = {0};
597 /* If output-sync is enabled we'll collect all the output generated due to
598 options, while reading makefiles, etc. */
600 struct output make_sync;
603 /* Mask of signals that are being caught with fatal_error_signal. */
606 sigset_t fatal_signal_set;
607 #elif defined(HAVE_SIGSETMASK)
608 int fatal_signal_mask;
611 #if !HAVE_DECL_BSD_SIGNAL && !defined bsd_signal
612 # if !defined HAVE_SIGACTION
613 # define bsd_signal signal
615 typedef void (*bsd_signal_ret_t) (int);
617 static bsd_signal_ret_t
618 bsd_signal (int sig, bsd_signal_ret_t func)
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)
627 return oact.sa_handler;
633 initialize_global_hash_tables (void)
635 init_hash_global_variable_set ();
638 hash_init_directories ();
639 hash_init_function_table ();
642 /* This character map locate stop chars when parsing GNU makefiles.
643 Each element is true if we should stop parsing on that character. */
646 initialize_stopchar_map (void)
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;
664 stopchar_map[(int)'-'] = MAP_USERFUNC;
665 stopchar_map[(int)'_'] = MAP_USERFUNC;
667 stopchar_map[(int)' '] = MAP_BLANK;
668 stopchar_map[(int)'\t'] = MAP_BLANK;
670 stopchar_map[(int)'/'] = MAP_DIRSEP;
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;
679 for (i = 1; i <= UCHAR_MAX; ++i)
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;
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
694 This is called only through atexit(), which means die() has already been
695 invoked. So, call exit() here directly. Apparently that works...?
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.
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.
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. */
722 int prev_fail = ferror (stdout);
723 int fclose_fail = fclose (stdout);
725 if (prev_fail || fclose_fail)
728 perror_with_name (_("write error: stdout"), "");
730 O (error, NILF, _("write error: stdout"));
736 expand_command_line_file (const char *name)
742 O (fatal, NILF, _("empty string invalid as file name"));
746 expanded = tilde_expand (name);
747 if (expanded && expanded[0] != '\0')
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] == '/')
757 while (name[0] == '/')
758 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
764 /* Nothing else but one or more "./", maybe plus slashes! */
768 cp = strcache_add (name);
775 /* Toggle -d on receipt of SIGUSR1. */
779 debug_signal_handler (int sig UNUSED)
781 db_level = db_level ? DB_NONE : DB_BASIC;
786 decode_debug_flags (void)
794 db_level |= DB_PRINT | DB_WHY;
797 for (pp=db_flags->list; *pp; ++pp)
803 switch (tolower (p[0]))
809 db_level |= DB_BASIC;
812 db_level |= DB_BASIC | DB_IMPLICIT;
818 db_level |= DB_BASIC | DB_MAKEFILES;
824 db_level |= DB_PRINT;
827 db_level |= DB_BASIC | DB_VERBOSE;
834 _("unknown debug level specification '%s'"), p);
837 while (*(++p) != '\0')
838 if (*p == ',' || *p == ' ')
857 decode_output_sync_flags (void)
859 #ifdef NO_OUTPUT_SYNC
860 output_sync = OUTPUT_SYNC_NONE;
862 if (output_sync_option)
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;
874 _("unknown output-sync type '%s'"), output_sync_option);
878 osync_parse_mutex (sync_mutex);
882 /* Print a nice usage method and exit. */
885 print_usage (int bad)
887 const char *const *cpp;
890 if (print_version_flag)
893 fputs ("\n", stdout);
896 usageto = bad ? stderr : stdout;
898 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
900 for (cpp = usage; *cpp; ++cpp)
901 fputs (_(*cpp), usageto);
903 if (!remote_description || *remote_description == '\0')
904 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
906 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
907 make_host, remote_description);
909 fprintf (usageto, _("Report bugs to <bug-make@gnu.org>\n"));
911 die (bad ? MAKE_FAILURE : MAKE_SUCCESS);
917 * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
918 * exception and print it to stderr instead.
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.
926 handle_runtime_exceptions (struct _EXCEPTION_POINTERS *exinfo)
928 PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
929 LPSTR cmdline = GetCommandLine ();
930 LPSTR prg = strtok (cmdline, " ");
934 LPTSTR lpszStrings[1];
937 if (! ISDB (DB_VERBOSE))
940 _("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\n"),
941 prg, exrec->ExceptionCode, exrec->ExceptionAddress);
942 fprintf (stderr, 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);
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]);
959 /* turn this on if we want to put stuff in the event log too */
961 hEventSource = RegisterEventSource (NULL, "GNU Make");
962 lpszStrings[0] = errmsg;
964 if (hEventSource != NULL)
966 ReportEvent (hEventSource, /* handle of event source */
967 EVENTLOG_ERROR_TYPE, /* event type */
968 0, /* event category */
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 */
976 (VOID) DeregisterEventSource (hEventSource);
980 /* Write the error to stderr too */
981 fprintf (stderr, errmsg);
984 return EXCEPTION_CONTINUE_SEARCH;
987 return (255); /* not reached */
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).
1000 find_and_set_default_shell (const char *token)
1004 const char *search_token;
1006 extern const char *default_shell;
1009 search_token = default_shell;
1011 search_token = atoken = xstrdup (token);
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")))
1025 batch_mode_shell = 1;
1027 default_shell = xstrdup (w32ify (search_token, 0));
1028 DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
1032 else if (!no_default_sh_exe
1033 && (token == NULL || !strcmp (search_token, default_shell)))
1035 /* no new information, path already set or known */
1038 else if (_access (search_token, 0) == 0)
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"),
1049 struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
1051 /* Search Path for shell */
1057 ep = strchr (p, PATH_SEPARATOR_CHAR);
1065 snprintf (sh_path, GET_PATH_MAX, "%s/%s", p, search_token);
1066 if (_access (sh_path, 0) == 0)
1068 default_shell = xstrdup (w32ify (sh_path, 0));
1070 *ep = PATH_SEPARATOR_CHAR;
1072 /* terminate loop */
1077 *ep = PATH_SEPARATOR_CHAR;
1081 ep = strchr (p, PATH_SEPARATOR_CHAR);
1084 /* be sure to check last element of Path */
1088 snprintf (sh_path, GET_PATH_MAX, "%s/%s", p, search_token);
1089 if (_access (sh_path, 0) == 0)
1091 default_shell = xstrdup (w32ify (sh_path, 0));
1098 (_("find_and_set_shell() path search set default_shell = %s\n"),
1104 if (!unixy_shell && sh_found
1105 && (strstr (default_shell, "sh") || strstr (default_shell, "SH")))
1108 batch_mode_shell = 0;
1111 #ifdef BATCH_MODE_ONLY_SHELL
1112 batch_mode_shell = 1;
1119 #endif /* WINDOWS32 */
1123 msdos_return_to_initial_directory (void)
1125 if (directory_before_chdir)
1126 chdir (directory_before_chdir);
1128 #endif /* __MSDOS__ */
1131 reset_jobserver (void)
1134 free (jobserver_auth);
1135 jobserver_auth = NULL;
1139 temp_stdin_unlink ()
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)
1145 const char *nm = makefiles->list[stdin_offset];
1149 EINTRLOOP(r, unlink (nm));
1150 if (r < 0 && errno != ENOENT && !handling_fatal_signal)
1151 perror_with_name (_("unlink (temporary file): "), nm);
1157 main (int argc, char **argv)
1160 main (int argc, char **argv, char **envp)
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. */
1170 const char *unix_path = NULL;
1171 const char *windows32_path = NULL;
1173 SetUnhandledExceptionFilter (handle_runtime_exceptions);
1175 /* start off assuming we have no shell */
1177 no_default_sh_exe = 1;
1180 initialize_variable_output ();
1182 /* Useful for attaching debuggers, etc. */
1183 SPIN ("main-entry");
1185 /* Don't die if our stdout sends us SIGPIPE. */
1187 bsd_signal (SIGPIPE, SIG_IGN);
1191 if (ANY_SET (check_io_state (), IO_STDOUT_OK))
1192 atexit (close_stdout);
1195 output_init (&make_sync);
1197 initialize_stopchar_map();
1199 #ifdef SET_STACK_SIZE
1200 /* Get rid of any avoidable limit on stack size. */
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)
1209 rlim.rlim_cur = rlim.rlim_max;
1210 setrlimit (RLIMIT_STACK, &rlim);
1213 stack_limit.rlim_cur = 0;
1217 /* Needed for OS/2 */
1218 initialize_main (&argc, &argv);
1220 #ifdef MAKE_MAINTAINER_MODE
1221 /* In maintainer mode we always enable verification. */
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);
1237 /* Set up gettext/internationalization support. */
1238 setlocale (LC_ALL, "");
1239 /* The cast to void shuts up compiler warnings on systems that
1241 (void)bindtextdomain (PACKAGE, LOCALEDIR);
1242 (void)textdomain (PACKAGE);
1245 sigemptyset (&fatal_signal_set);
1246 #define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
1248 #ifdef HAVE_SIGSETMASK
1249 fatal_signal_mask = 0;
1250 #define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
1252 #define ADD_SIG(sig) (void)sig
1256 #define FATAL_SIG(sig) \
1257 if (bsd_signal (sig, fatal_error_signal) == SIG_IGN) \
1258 bsd_signal (sig, SIG_IGN); \
1266 FATAL_SIG (SIGQUIT);
1269 FATAL_SIG (SIGTERM);
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. */
1279 FATAL_SIG (SIGDANGER);
1282 FATAL_SIG (SIGXCPU);
1285 FATAL_SIG (SIGXFSZ);
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. */
1295 #ifdef HAVE_WAIT_NOHANG
1296 # if defined SIGCHLD
1297 (void) bsd_signal (SIGCHLD, SIG_DFL);
1299 # if defined SIGCLD && SIGCLD != SIGCHLD
1300 (void) bsd_signal (SIGCLD, SIG_DFL);
1306 /* Figure out where this program lives. */
1309 argv[0] = (char *)"";
1310 if (argv[0][0] == '\0')
1314 #if defined(HAVE_DOS_PATHS)
1315 const char* start = argv[0];
1317 /* Skip an initial drive specifier if present. */
1318 if (isalpha ((unsigned char)start[0]) && start[1] == ':')
1321 if (start[0] == '\0')
1325 program = start + strlen (start);
1326 while (program > start && ! ISDIRSEP (program[-1]))
1329 /* Remove the .exe extension if present. */
1331 size_t len = strlen (program);
1332 if (len > 4 && streq (&program[len - 4], ".exe"))
1333 program = xstrndup (program, len - 4);
1337 set_program_name (argv[0]);
1338 program = program_name;
1343 shell = getenv ("SHELL");
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);
1351 vms_report_unix_paths = 1;
1353 vms_use_mcr_command = get_vms_env_flag ("GNV$MAKE_USE_MCR", 0);
1355 vms_always_use_cmd_file = get_vms_env_flag ("GNV$MAKE_USE_CMD_FILE", 0);
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",
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);
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);
1380 if (need_vms_symbol () && !vms_use_mcr_command)
1381 create_foreign_command (program_name, argv[0]);
1383 program = strrchr (argv[0], '/');
1391 initialize_global_hash_tables ();
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. */
1397 /* Figure out where we are. */
1400 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1402 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1406 perror_with_name ("getcwd", "");
1408 OS (error, NILF, "getwd: %s", current_directory);
1410 current_directory[0] = '\0';
1411 directory_before_chdir = 0;
1414 directory_before_chdir = xstrdup (current_directory);
1417 /* Make sure we will return to the initial directory, come what may. */
1418 atexit (msdos_return_to_initial_directory);
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);
1429 Use a separate variable because define_variable_cname() is a macro and
1430 some compilers (MSVC) don't like conditionals in macros. */
1432 const char *features = "target-specific order-only second-expansion"
1433 " else-if shortest-stem undefine oneshell nocomment"
1434 " grouped-target extra-prereqs notintermediate"
1439 #ifdef MAKE_JOBSERVER
1445 #ifndef NO_OUTPUT_SYNC
1448 #ifdef MAKE_SYMLINKS
1457 #ifdef MAKE_MAINTAINER_MODE
1462 define_variable_cname (".FEATURES", features, o_default, 0);
1465 /* Configure GNU Guile support */
1466 guile_gmake_setup (NILF);
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. */
1476 for (i = 0; envp[i] != 0; ++i)
1479 const char *ep = envp[i];
1480 /* By default, export all variables culled from the environment. */
1481 enum variable_export export = v_export;
1484 while (! STOP_SET (*ep, MAP_EQUALS|MAP_NUL))
1487 /* If there's no equals sign it's a malformed environment. Ignore. */
1492 if (!unix_path && strneq (envp[i], "PATH=", 5))
1494 else if (!strnicmp (envp[i], "Path=", 5))
1496 if (!windows32_path)
1497 windows32_path = ep+1;
1498 /* PATH gets defined after the loop exits. */
1503 /* Length of the variable name, and skip the '='. */
1504 len = ep++ - envp[i];
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)
1515 restarts = make_toui (ep, NULL);
1516 export = v_noexport;
1519 v = define_variable (envp[i], len, ep, o_env, 1);
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"))
1526 export = v_noexport;
1528 shell_var.name = xstrdup ("SHELL");
1529 shell_var.length = 5;
1530 shell_var.value = xstrdup (ep);
1537 /* If we didn't find a correctly spelled PATH we define PATH as
1538 * either the first misspelled value or an empty string
1541 define_variable_cname ("PATH", windows32_path ? windows32_path : "",
1542 o_env, 1)->export = v_export;
1544 #else /* For Amiga, read the ENV: device, ignoring all dirs */
1546 BPTR env, file, old;
1549 __aligned struct FileInfoBlock fib;
1551 env = Lock ("ENV:", ACCESS_READ);
1554 old = CurrentDir (DupLock (env));
1555 Examine (env, &fib);
1557 while (ExNext (env, &fib))
1559 if (fib.fib_DirEntryType < 0) /* File */
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;
1569 UnLock (CurrentDir (old));
1574 /* Decode the switches. */
1575 if (lookup_variable (STRING_SIZE_TUPLE (GNUMAKEFLAGS_NAME)))
1577 decode_env_switches (STRING_SIZE_TUPLE (GNUMAKEFLAGS_NAME));
1579 /* Clear GNUMAKEFLAGS to avoid duplication. */
1580 define_variable_cname (GNUMAKEFLAGS_NAME, "", o_env, 0);
1583 decode_env_switches (STRING_SIZE_TUPLE (MAKEFLAGS_NAME));
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"));
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. */
1595 syncing = make_sync.syncout = (output_sync == OUTPUT_SYNC_LINE
1596 || output_sync == OUTPUT_SYNC_TARGET);
1597 OUTPUT_SET (&make_sync);
1599 /* Parse the command line options. Remember the job slots set this way. */
1601 int env_slots = arg_job_slots;
1602 arg_job_slots = INVALID_JOB_SLOTS;
1604 decode_switches (argc, (const char **)argv, 0);
1605 argv_slots = arg_job_slots;
1607 if (arg_job_slots == INVALID_JOB_SLOTS)
1608 arg_job_slots = env_slots;
1611 if (print_usage_flag)
1614 /* Print version information, and exit. */
1615 if (print_version_flag)
1621 /* Now that we know we'll be running, force stdout to be line-buffered. */
1623 setvbuf (stdout, 0, _IOLBF, BUFSIZ);
1624 #elif HAVE_SETLINEBUF
1625 setlinebuf (stdout);
1628 /* Handle shuffle mode argument. */
1631 const char *effective_mode;
1632 shuffle_set_mode (shuffle_mode);
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 ();
1639 shuffle_mode = xstrdup (effective_mode);
1641 shuffle_mode = NULL;
1644 /* Set a variable specifying whether stdout/stdin is hooked to a TTY. */
1646 if (isatty (fileno (stdout)))
1647 if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMOUT")))
1649 const char *tty = TTYNAME (fileno (stdout));
1650 define_variable_cname ("MAKE_TERMOUT", tty ? tty : DEFAULT_TTYNAME,
1651 o_default, 0)->export = v_export;
1653 if (isatty (fileno (stderr)))
1654 if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMERR")))
1656 const char *tty = TTYNAME (fileno (stderr));
1657 define_variable_cname ("MAKE_TERMERR", tty ? tty : DEFAULT_TTYNAME,
1658 o_default, 0)->export = v_export;
1662 /* Reset in case the switches changed our minds. */
1663 syncing = (output_sync == OUTPUT_SYNC_LINE
1664 || output_sync == OUTPUT_SYNC_TARGET);
1666 if (make_sync.syncout && ! syncing)
1667 output_close (&make_sync);
1669 make_sync.syncout = syncing;
1670 OUTPUT_SET (&make_sync);
1672 /* Figure out the level of recursion. */
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);
1681 /* Set always_make_flag if -B was given and we've not restarted already. */
1682 always_make_flag = always_make_set && (restarts == 0);
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. */
1687 if (print_directory_flag == -1)
1688 print_directory = !silent_flag && (directories != 0 || makelevel > 0);
1690 print_directory = print_directory_flag;
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;
1696 if (ISDB (DB_BASIC))
1700 /* Flush stdout so the user doesn't have to wait to see the
1701 version information while make thinks about things. */
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.) */
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
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], '\\'))
1727 argv[0] = xstrdup (argv[0]);
1728 for (p = argv[0]; *p; p++)
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'
1737 && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
1739 /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
1740 && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
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
1752 argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
1753 #endif /* !__MSDOS__ */
1754 #endif /* WINDOWS32 */
1757 /* We may move, but until we do, here we are. */
1758 starting_directory = current_directory;
1760 /* If there were -C flags, move ourselves about. */
1761 if (directories != 0)
1764 for (i = 0; directories->list[i] != 0; ++i)
1766 const char *dir = directories->list[i];
1768 /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1769 But allow -C/ just in case someone wants that. */
1771 char *p = (char *)dir + strlen (dir) - 1;
1772 while (p > dir && ISDIRSEP (p[0]))
1777 if (chdir (dir) < 0)
1778 pfatal_with_name (dir);
1784 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1785 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
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.
1792 no_default_sh_exe = !find_and_set_default_shell (NULL);
1793 #endif /* WINDOWS32 */
1795 /* If we chdir'ed, figure out where we are now. */
1799 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1801 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1805 perror_with_name ("getcwd", "");
1807 OS (error, NILF, "getwd: %s", current_directory);
1809 starting_directory = 0;
1812 starting_directory = current_directory;
1815 define_variable_cname ("CURDIR", current_directory, o_file, 0);
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. */
1824 /* We're a child in an existing jobserver group. */
1825 if (argv_slots == INVALID_JOB_SLOTS)
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;
1832 /* Oops: we have jobserver-auth but it's invalid :(. */
1833 O (error, NILF, _("warning: jobserver unavailable: using -j1. Add '+' to parent make rule."));
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. */
1841 _("warning: -j%d forced in submake: resetting jobserver mode."),
1844 /* We can't use our parent's jobserver, so reset. */
1850 /* The extra indirection through $(MAKE_COMMAND) is done
1851 for hysterical raisins. */
1854 if (vms_use_mcr_command)
1855 define_variable_cname ("MAKE_COMMAND", vms_command (argv[0]), o_default, 0);
1857 define_variable_cname ("MAKE_COMMAND", program, o_default, 0);
1859 define_variable_cname ("MAKE_COMMAND", argv[0], o_default, 0);
1861 define_variable_cname ("MAKE", "$(MAKE_COMMAND)", o_default, 1);
1863 if (command_variables != 0)
1865 struct command_variable *cv;
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)
1875 len += 2 * strlen (v->name);
1879 len += 2 * strlen (v->value);
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)
1888 p = quote_for_env (p, v->name);
1892 p = quote_for_env (p, v->value);
1895 p[-1] = '\0'; /* Kill the final space and terminate. */
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);
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-*-}",
1910 vms_export_dcl_symbol ("MAKEOVERRIDES", "${-*-command-variables-*-}");
1914 /* Read any stdin makefiles into temporary files. */
1919 for (i = 0; i < makefiles->idx; ++i)
1920 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
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. */
1928 if (stdin_offset >= 0)
1930 _("Makefile from standard input specified twice"));
1932 outfile = get_tmpfile (&newnm);
1934 while (!feof (stdin) && ! ferror (stdin))
1937 size_t n = fread (buf, 1, sizeof (buf), stdin);
1938 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
1940 _("fwrite: temporary file %s: %s"), newnm, strerror (errno));
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);
1953 /* Make sure the temporary file is never considered updated. */
1954 if (stdin_offset >= 0)
1956 struct file *f = enter_file (makefiles->list[stdin_offset]);
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;
1963 /* Avoid re-exec due to stdin temp file timestamps. */
1964 f->last_mtime = f->mtime_before_update = f_mtime (f, 0);
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.
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
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.
1980 If none of these are true, we don't need a signal handler at all. */
1982 # if defined SIGCHLD
1983 bsd_signal (SIGCHLD, child_handler);
1985 # if defined SIGCLD && SIGCLD != SIGCHLD
1986 bsd_signal (SIGCLD, child_handler);
1991 /* If we have pselect() then we need to block SIGCHLD so it's deferred. */
1994 sigemptyset (&block);
1995 sigaddset (&block, SIGCHLD);
1996 if (sigprocmask (SIG_SETMASK, &block, NULL) < 0)
1997 pfatal_with_name ("sigprocmask(SIG_SETMASK, SIGCHLD)");
2004 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
2006 bsd_signal (SIGUSR1, debug_signal_handler);
2009 /* Define the initial list of suffixes for old-style rules. */
2010 set_default_suffixes ();
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 ();
2019 /* Define some internal and special variables. */
2020 define_automatic_variables ();
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;
2026 /* Define the default variables. */
2027 define_default_variables ();
2029 default_file = enter_file (strcache_add (".DEFAULT"));
2031 default_goal_var = define_variable_cname (".DEFAULT_GOAL", "", o_file, 0);
2033 /* Evaluate all strings provided with --eval.
2034 Also set up the $(-*-eval-flags-*-) variable. */
2038 char *p, *endp, *value;
2040 size_t len = (CSTRLEN ("--eval=") + 1) * eval_strings->idx;
2042 for (i = 0; i < eval_strings->idx; ++i)
2044 p = xstrdup (eval_strings->list[i]);
2045 len += 2 * strlen (p);
2046 eval_buffer (p, NULL);
2050 p = endp = value = alloca (len);
2051 for (i = 0; i < eval_strings->idx; ++i)
2053 p = stpcpy (p, "--eval=");
2054 p = quote_for_env (p, eval_strings->list[i]);
2060 define_variable_cname ("-*-eval-flags-*-", value, o_automatic, 0);
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;
2068 /* Read all the makefiles. */
2069 read_files = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
2071 arg_job_slots = INVALID_JOB_SLOTS;
2073 /* Decode switches again, for variables set by the makefile. */
2074 decode_env_switches (STRING_SIZE_TUPLE (GNUMAKEFLAGS_NAME));
2076 /* Clear GNUMAKEFLAGS to avoid duplication. */
2077 define_variable_cname (GNUMAKEFLAGS_NAME, "", o_override, 0);
2079 decode_env_switches (STRING_SIZE_TUPLE (MAKEFLAGS_NAME));
2081 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
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;
2089 else if (jobserver_auth && arg_job_slots != old_arg_job_slots)
2091 /* Makefile MAKEFLAGS set -j, but we already have a jobserver.
2092 Make us the master of a new jobserver group. */
2095 _("warning: -j%d forced in makefile: resetting jobserver mode."),
2098 /* We can't use our parent's jobserver, so reset. */
2102 /* Reset in case the switches changed our mind. */
2103 syncing = (output_sync == OUTPUT_SYNC_LINE
2104 || output_sync == OUTPUT_SYNC_TARGET);
2106 if (make_sync.syncout && ! syncing)
2107 output_close (&make_sync);
2109 make_sync.syncout = syncing;
2110 OUTPUT_SET (&make_sync);
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;
2116 /* If we've disabled builtin rules, get rid of them. */
2117 if (no_builtin_rules_flag && ! old_builtin_rules_flag)
2119 if (suffix_file->builtin)
2121 free_dep_chain (suffix_file->deps);
2122 suffix_file->deps = 0;
2124 define_variable_cname ("SUFFIXES", "", o_default, 0);
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 ();
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 */
2138 #if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
2139 /* We need to know what kind of shell we will be using. */
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;
2146 if (shv && *shv->value)
2148 char *shell_path = recursively_expand (shv);
2150 if (shell_path && _is_unixy_shell (shell_path))
2155 default_shell = shell_path;
2158 #endif /* __MSDOS__ || __EMX__ */
2160 /* Final jobserver configuration.
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.
2166 arg_job_slots = INVALID_JOB_SLOTS if we don't want -j in MAKEFLAGS
2168 arg_job_slots = # of jobs of parallelism
2170 job_slots = 0 for no limits on jobs, or when limiting via jobserver.
2172 job_slots = 1 for standard non-parallel mode.
2174 job_slots >1 for old-style parallelism without jobservers. */
2178 else if (arg_job_slots == INVALID_JOB_SLOTS)
2181 job_slots = arg_job_slots;
2183 #if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
2186 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
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;
2198 /* If we have >1 slot at this point, then we're a top-level make.
2199 Set up the jobserver.
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. */
2205 if (job_slots > 1 && jobserver_setup (job_slots - 1, jobserver_style))
2207 /* Fill in the jobserver_auth for our children. */
2208 jobserver_auth = jobserver_get_auth ();
2212 /* We're using the jobserver so set job_slots to 0. */
2213 master_job_slots = job_slots;
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)
2224 output_close (&make_sync);
2226 output_sync = OUTPUT_SYNC_NONE;
2231 /* If there is no mutex we're the base: create one. Else parse it. */
2235 sync_mutex = osync_get_mutex ();
2237 else if (!osync_parse_mutex (sync_mutex))
2239 /* Parsing failed; continue without output sync. */
2248 DB (DB_VERBOSE|DB_JOBS, (_("Using jobserver controller %s\n"), jobserver_auth));
2250 DB (DB_VERBOSE, (_("Using output-sync mutex %s\n"), sync_mutex));
2252 #ifndef MAKE_SYMLINKS
2253 if (check_symlink_flag)
2255 O (error, NILF, _("Symbolic links not supported: disabling -L."));
2256 check_symlink_flag = 0;
2260 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
2262 define_makeflags (1, 0);
2264 /* Make each 'struct goaldep' point at the 'struct file' for the file
2265 depended on. Also do magic for special targets. */
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
2274 convert_to_pattern ();
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. */
2281 install_default_implicit_rules ();
2283 /* Compute implicit rule limits and do magic for pattern rules. */
2285 snap_implicit_rules ();
2287 /* Construct the listings of directories in VPATH lists. */
2289 build_vpath_lists ();
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. */
2298 for (p = old_files->list; *p != 0; ++p)
2300 struct file *f = enter_file (*p);
2301 f->last_mtime = f->mtime_before_update = OLD_MTIME;
2303 f->update_status = us_success;
2304 f->command_state = cs_finished;
2308 if (!restarts && new_files != 0)
2311 for (p = new_files->list; *p != 0; ++p)
2313 struct file *f = enter_file (*p);
2314 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2318 /* Initialize the remote job module. */
2321 /* Dump any output we've collected. */
2324 output_close (&make_sync);
2327 DB (DB_BASIC, (_("Enabled shuffle mode: %s\n"), shuffle_mode));
2331 /* Update any makefiles if necessary. */
2333 FILE_TIMESTAMP *makefile_mtimes;
2334 struct goaldep *skipped_makefiles = NULL;
2335 const char **nargv = (const char **) argv;
2337 enum update_status status;
2339 DB (DB_BASIC, (_("Updating makefiles....\n")));
2341 /* Count the makefiles, and reverse the order so that we attempt to
2342 rebuild them in the order they were read. */
2344 unsigned int num_mkfiles = 0;
2345 struct goaldep *d = read_files;
2349 struct goaldep *t = d;
2351 t->next = read_files;
2356 makefile_mtimes = alloca (num_mkfiles * sizeof (FILE_TIMESTAMP));
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. */
2362 struct goaldep *d = read_files;
2363 struct goaldep *last = NULL;
2364 unsigned int mm_idx = 0;
2369 struct file *f = d->file;
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.) */
2381 for (f = f->double_colon; f != NULL; f = f->prev)
2382 if (f->deps == NULL && f->cmds != NULL)
2390 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
2397 (_("Makefile '%s' might loop; not remaking it.\n"),
2401 last->next = d->next;
2403 read_files = d->next;
2405 if (d->error && ! (d->flags & RM_DONTCARE))
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;
2416 d = last ? last->next : read_files;
2421 /* Set up 'MAKEFLAGS' specially while remaking makefiles. */
2422 define_makeflags (1, 1);
2425 int orig_db_level = db_level;
2427 if (! ISDB (DB_MAKEFILES))
2430 rebuilding_makefiles = 1;
2431 status = update_goal_chain (read_files);
2432 rebuilding_makefiles = 0;
2434 db_level = orig_db_level;
2437 /* Report errors for makefiles that needed to be remade but were not. */
2438 while (skipped_makefiles != NULL)
2440 struct goaldep *d = skipped_makefiles;
2441 const char *err = strerror (d->error);
2443 OSS (error, &d->floc, _("%s: %s"), dep_name (d), err);
2445 skipped_makefiles = skipped_makefiles->next;
2449 /* If we couldn't build something we need but otherwise we succeeded,
2450 reset the status. */
2451 if (any_failed && status == us_success)
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". */
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. */
2470 for (d = read_files; d; d = d->next)
2471 if (d->file->unloaded)
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);
2482 /* No makefiles needed to be updated. If we couldn't read some
2483 included file that we care about, fail. */
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. */
2494 for (d = read_files; d != 0; d = d->next)
2495 if (d->error && ! (d->flags & RM_DONTCARE))
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);
2506 /* Failed to update. Figure out if we care. */
2508 /* Nonzero if any makefile was successfully remade. */
2513 for (i = 0, d = read_files; d != 0; ++i, d = d->next)
2515 if (d->file->updated)
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))
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'."),
2530 mtime = file_mtime_no_search (d->file);
2531 any_remade |= (mtime != NONEXISTENT_MTIME
2532 && mtime != makefile_mtimes[i]);
2533 makefile_status = MAKE_FAILURE;
2538 /* This makefile was not found at all. */
2539 else if (! (d->flags & RM_DONTCARE))
2541 const char *dnm = dep_name (d);
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);
2551 /* A normal makefile. We must die later. */
2552 OS (error, NILF, _("Makefile '%s' was not found"), dnm);
2566 /* Updated successfully. Re-exec ourselves. */
2568 remove_intermediates (0);
2570 if (print_data_base_flag)
2573 clean_jobserver (0);
2577 /* Makefile names might have changed due to expansion.
2578 It's possible we'll need one extra argument:
2581 make -R --temp-stdin=<tmpfile>
2582 so allocate more space.
2588 nv = nargv = alloca (sizeof (char*) * (argc + 1 + 1));
2591 for (; *av; ++av, ++nv)
2595 const char *mf = makefiles->list[mfidx];
2597 assert (strlen (a) > 0);
2601 /* Not an option: we handled option args earlier. */
2605 /* See if this option specifies a filename. If so we need
2606 to replace it with the value from makefiles->list.
2608 To simplify, we'll replace all possible versions of this
2609 flag with a simple "-f<name>". */
2611 /* Handle long options. */
2614 if (strcmp (a, "--file") == 0 || strcmp (a, "--makefile") == 0)
2615 /* Skip the next arg as we'll combine them. */
2617 else if (!strneq (a, "--file=", 7)
2618 && !strneq (a, "--makefile=", 11))
2621 if (mfidx == stdin_offset)
2623 char *na = alloca (CSTRLEN ("--temp-stdin=")
2625 sprintf (na, "--temp-stdin=%s", mf);
2630 char *na = alloca (strlen (mf) + 3);
2631 sprintf (na, "-f%s", mf);
2639 /* Handle short options. If 'f' is the last option, it may
2640 be followed by <name>. */
2641 f = strchr (a, 'f');
2645 /* If there's an extra argument option skip it. */
2649 if (mfidx == stdin_offset)
2651 const size_t al = f - a;
2656 /* Preserve the prior options. */
2657 na = alloca (al + 1);
2663 /* Remove the "f" and any subsequent content. */
2664 na = alloca (CSTRLEN ("--temp-stdin=") + strlen (mf) + 1);
2665 sprintf (na, "--temp-stdin=%s", mf);
2668 else if (f[1] == '\0')
2669 /* -f <name> or -xyzf <name>. Replace the name. */
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);
2678 memcpy (na + al, mf, ml);
2688 if (directories != 0 && directories->idx > 0)
2691 if (directory_before_chdir != 0)
2693 if (chdir (directory_before_chdir) < 0)
2694 perror_with_name ("chdir", "");
2700 _("Couldn't change back to original directory"));
2705 if (ISDB (DB_BASIC))
2708 printf (_("Re-executing[%u]:"), restarts);
2709 for (p = nargv; *p != 0; ++p)
2718 for (p = environ; *p != 0; ++p)
2720 if (strneq (*p, MAKELEVEL_NAME "=", MAKELEVEL_LENGTH+1))
2723 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2725 vms_putenv_symbol (*p);
2728 else if (strneq (*p, "MAKE_RESTARTS=", CSTRLEN ("MAKE_RESTARTS=")))
2731 sprintf (*p, "MAKE_RESTARTS=%s%u",
2732 OUTPUT_IS_TRACED () ? "-" : "", restarts);
2741 sprintf (buffer, "%u", makelevel);
2742 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2744 sprintf (buffer, "%s%u", OUTPUT_IS_TRACED () ? "-" : "", restarts);
2745 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2750 /* If we didn't set the restarts variable yet, add it. */
2753 char *b = alloca (40);
2754 sprintf (b, "MAKE_RESTARTS=%s%u",
2755 OUTPUT_IS_TRACED () ? "-" : "", restarts);
2764 /* The exec'd "child" will be another make, of course. */
2765 jobserver_pre_child(1);
2768 exec_command (nargv);
2770 #elif defined (__EMX__)
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
2780 struct childbase child;
2781 child.cmd_name = NULL;
2782 child.output.syncout = 0;
2783 child.environment = environ;
2785 pid = child_execute_job (&child, 1, nargv);
2787 /* is this loop really necessary? */
2791 /* use the exit code of the child process */
2792 exit (WIFEXITED(r) ? WEXITSTATUS(r) : EXIT_FAILURE);
2795 #ifdef SET_STACK_SIZE
2796 /* Reset limits, if necessary. */
2797 if (stack_limit.rlim_cur)
2798 setrlimit (RLIMIT_STACK, &stack_limit);
2800 exec_command ((char **)nargv, environ);
2802 jobserver_post_child(1);
2804 temp_stdin_unlink ();
2813 /* Set up 'MAKEFLAGS' again for the normal targets. */
2814 define_makeflags (1, 0);
2816 /* Set always_make_flag if -B was given. */
2817 always_make_flag = always_make_set;
2819 /* If restarts is set we haven't set up -W files yet, so do that now. */
2820 if (restarts && new_files != 0)
2823 for (p = new_files->list; *p != 0; ++p)
2825 struct file *f = enter_file (*p);
2826 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2830 temp_stdin_unlink ();
2832 /* If there were no command-line goals, use the default. */
2837 if (default_goal_var->recursive)
2838 p = variable_expand (default_goal_var->value);
2841 p = variable_buffer_output (variable_buffer, default_goal_var->value,
2842 strlen (default_goal_var->value));
2844 p = variable_buffer;
2849 struct file *f = lookup_file (p);
2851 /* If .DEFAULT_GOAL is a non-existent target, enter it into the
2852 table and let the standard logic sort it out. */
2857 ns = PARSE_SIMPLE_SEQ (&p, struct nameseq);
2860 /* .DEFAULT_GOAL should contain one target. */
2863 _(".DEFAULT_GOAL contains more than one target"));
2865 f = enter_file (strcache_add (ns->name));
2867 ns->name = 0; /* It was reused by enter_file(). */
2874 goals = alloc_goaldep ();
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"));
2889 O (fatal, NILF, _("No targets specified and no makefile found"));
2892 /* Shuffle prerequisites to catch makefiles with incomplete depends. */
2894 shuffle_goaldeps_recursive (goals);
2896 /* Update the goals. */
2898 DB (DB_BASIC, (_("Updating goal targets....\n")));
2901 switch (update_goal_chain (goals))
2904 /* Nothing happened. */
2907 /* Keep the previous result. */
2910 /* We are under -q and would run some commands. */
2911 makefile_status = MAKE_TROUBLE;
2914 /* Updating failed. POSIX.2 specifies exit status >1 for this; */
2915 makefile_status = MAKE_FAILURE;
2919 /* If we detected some clock skew, generate one last warning */
2920 if (clock_skew_detected)
2922 _("warning: Clock skew detected. Your build may be incomplete."));
2925 die (makefile_status);
2929 exit (MAKE_SUCCESS);
2932 /* Parsing of arguments, decoding of switches. */
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]))];
2939 /* Fill in the string and vector for getopt. */
2941 init_switches (void)
2947 if (options[0] != '\0')
2953 /* Return switch and non-switch args in order, regardless of
2954 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
2957 for (i = 0; switches[i].c != '\0'; ++i)
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)
2970 long_options[i].has_arg = no_argument;
2978 if (short_option (switches[i].c))
2980 if (switches[i].noarg_value != 0)
2982 if (short_option (switches[i].c))
2984 long_options[i].has_arg = optional_argument;
2987 long_options[i].has_arg = required_argument;
2992 for (c = 0; c < (sizeof (long_option_aliases) /
2993 sizeof (long_option_aliases[0]));
2995 long_options[i++] = long_option_aliases[c];
2996 long_options[i].name = 0;
3000 /* Non-option argument. It might be a variable definition. */
3002 handle_non_switch_argument (const char *arg, int env)
3006 if (arg[0] == '-' && arg[1] == '\0')
3007 /* Ignore plain '-' for compatibility. */
3012 /* VMS DCL quoting can result in foo="bar baz" showing up here.
3013 Need to remove the double quotes from the value. */
3016 eq_ptr = strchr (arg, '=');
3017 if ((eq_ptr != NULL) && (eq_ptr[1] == '"'))
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;
3035 v = try_variable_definition (0, arg, o_command, 0);
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;
3043 for (cv = command_variables; cv != 0; cv = cv->next)
3044 if (cv->variable == v)
3049 cv = xmalloc (sizeof (*cv));
3051 cv->next = command_variables;
3052 command_variables = cv;
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
3060 struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
3065 goals = alloc_goaldep ();
3070 lastgoal->next = alloc_goaldep ();
3071 lastgoal = lastgoal->next;
3077 /* Add this target name to the MAKECMDGOALS variable. */
3078 struct variable *gv;
3081 gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
3086 /* Paste the old and new values together */
3087 size_t oldlen, newlen;
3090 oldlen = strlen (gv->value);
3091 newlen = strlen (f->name);
3092 vp = alloca (oldlen + 1 + newlen + 1);
3093 memcpy (vp, gv->value, oldlen);
3095 memcpy (&vp[oldlen + 1], f->name, newlen + 1);
3098 define_variable_cname ("MAKECMDGOALS", value, o_default, 0);
3103 /* Decode switches from ARGC and ARGV.
3104 They came from the environment if ENV is nonzero. */
3107 decode_switches (int argc, const char **argv, int env)
3110 const struct command_switch *cs;
3111 struct stringlist *sl;
3114 /* getopt does most of the parsing for us.
3115 First, get its vectors set up. */
3119 /* Let getopt produce error messages for the command line,
3120 but not for options from the environment. */
3122 /* Reset getopt's state. */
3125 while (optind < argc)
3127 const char *coptarg;
3129 /* Parse the next argument. */
3130 c = getopt_long (argc, (char *const *)argv, options, long_options, NULL);
3133 /* End of arguments, or "--" marker seen. */
3136 /* An argument not starting with a dash. */
3137 handle_non_switch_argument (coptarg, env);
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. */
3144 for (cs = switches; cs->c != '\0'; ++cs)
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;
3164 *(int *) cs->value_ptr = cs->type == flag;
3174 coptarg = cs->noarg_value;
3175 else if (*coptarg == '\0')
3178 const char *op = opt;
3180 if (short_option (cs->c))
3181 opt[0] = (char) cs->c;
3185 error (NILF, strlen (op),
3186 _("the '%s%s' option requires a non-empty string argument"),
3187 short_option (cs->c) ? "-" : "--", op);
3192 if (cs->type == string)
3194 char **val = (char **)cs->value_ptr;
3196 *val = xstrdup (coptarg);
3200 sl = *(struct stringlist **) cs->value_ptr;
3203 sl = xmalloc (sizeof (struct stringlist));
3206 sl->list = xmalloc (5 * sizeof (char *));
3207 *(struct stringlist **) cs->value_ptr = sl;
3209 else if (sl->idx == sl->max - 1)
3212 /* MSVC erroneously warns without a cast here. */
3213 sl->list = xrealloc ((void *)sl->list,
3214 sl->max * sizeof (char *));
3217 /* Filter out duplicate options.
3218 * Allow duplicate makefiles for backward compatibility. */
3222 for (k = 0; k < sl->idx; ++k)
3223 if (streq (sl->list[k], coptarg))
3229 if (cs->type == strlist)
3230 sl->list[sl->idx++] = xstrdup (coptarg);
3231 else if (cs->c == TEMP_STDIN_OPT)
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);
3240 sl->list[sl->idx++] = expand_command_line_file (coptarg);
3241 sl->list[sl->idx] = 0;
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)
3250 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
3253 coptarg = argv[optind++];
3262 unsigned int i = make_toui (coptarg, &err);
3267 _("the '-%c' option requires a positive integer argument"),
3272 *(unsigned int *) cs->value_ptr = i;
3275 *(unsigned int *) cs->value_ptr
3276 = *(unsigned int *) cs->noarg_value;
3280 if (coptarg == 0 && optind < argc
3281 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
3282 coptarg = argv[optind++];
3285 *(double *) cs->value_ptr = (coptarg != 0 ? atof (coptarg)
3286 : *(double *) cs->noarg_value);
3291 /* We've found the switch. Stop looking. */
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);
3306 /* If there are any options that need to be decoded do it now. */
3307 decode_debug_flags ();
3308 decode_output_sync_flags ();
3310 /* Perform any special switch handling. */
3311 run_silent = silent_flag;
3313 /* Construct the list of include directories to search. */
3314 construct_include_path (include_dirs ? include_dirs->list : NULL);
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
3323 decode_env_switches (const char *envar, size_t len)
3325 char *varref = alloca (2 + len + 2);
3326 char *value, *p, *buf;
3330 /* Get the variable's value. */
3334 p = mempcpy (p, envar, len);
3337 value = variable_expand (varref);
3339 /* Skip whitespace, and check for an empty value. */
3341 len = strlen (value);
3345 /* Allocate a vector that is definitely big enough. */
3346 argv = alloca ((1 + len + 1) * sizeof (char *));
3348 /* getopt will look at the arguments starting at ARGV[1].
3349 Prepend a spacer word. */
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);
3359 while (*value != '\0')
3361 if (*value == '\\' && value[1] != '\0')
3362 ++value; /* Skip the backslash. */
3363 else if (ISBLANK (*value))
3365 /* End of the word. */
3370 while (ISBLANK (*value));
3377 assert (p < buf + len + 2);
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. */
3384 /* Parse those words. */
3385 decode_switches (argc, argv, 1);
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. */
3395 quote_for_env (char *out, const char *in)
3401 else if (ISBLANK (*in) || *in == '\\')
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. */
3413 static struct variable *
3414 define_makeflags (int all, int makefile)
3416 const char ref[] = "MAKEOVERRIDES";
3417 const char posixref[] = "-*-command-variables-*-";
3418 const char evalref[] = "$(-*-eval-flags-*-)";
3419 const struct command_switch *cs;
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. */
3432 const struct command_switch *cs;
3435 struct flag *flags = 0;
3436 struct flag *last = 0;
3437 size_t flagslen = 0;
3438 #define ADD_FLAG(ARG, LEN) \
3440 struct flag *new = alloca (sizeof (struct flag)); \
3449 if (new->arg == 0) \
3450 /* Just a single flag letter: " -x" */ \
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); \
3460 for (cs = switches; cs->c != '\0'; ++cs)
3461 if (cs->toenv && (!makefile || !cs->no_makefile))
3469 if ((!*(int *) cs->value_ptr) == (cs->type == flag_off)
3470 && (cs->default_value == 0
3471 || *(int *) cs->value_ptr != *(int *) cs->default_value))
3476 if ((cs->default_value != 0
3477 && (*(unsigned int *) cs->value_ptr
3478 == *(unsigned int *) cs->default_value)))
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. */
3486 char *buf = alloca (30);
3487 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3488 ADD_FLAG (buf, strlen (buf));
3493 if (cs->default_value != 0
3494 && (*(double *) cs->value_ptr == *(double *) cs->default_value))
3496 if (cs->noarg_value != 0
3497 && (*(double *) cs->value_ptr == *(double *) cs->noarg_value))
3498 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3501 char *buf = alloca (100);
3502 sprintf (buf, "%g", *(double *) cs->value_ptr);
3503 ADD_FLAG (buf, strlen (buf));
3508 p = *((char **)cs->value_ptr);
3510 ADD_FLAG (p, strlen (p));
3516 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3520 for (i = 0; i < sl->idx; ++i)
3521 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
3532 /* Four more for the possible " -- ", plus variable references. */
3533 flagslen += 4 + CSTRLEN (posixref) + 4 + CSTRLEN (evalref) + 4;
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);
3541 /* Start with a dash, for MFLAGS. */
3544 /* Add simple options as a group. */
3545 while (flags != 0 && !flags->arg && short_option (flags->cs->c))
3547 *p++ = (char) flags->cs->c;
3548 flags = flags->next;
3551 /* Now add more complex flags: ones with options and/or long names. */
3557 /* Add the flag letter or name to the string. */
3558 if (short_option (flags->cs->c))
3559 *p++ = (char) flags->cs->c;
3562 /* Long options require a double-dash. */
3564 p = stpcpy (p, flags->cs->long_name);
3566 /* An omitted optional argument has an ARG of "". */
3567 if (flags->arg && flags->arg[0] != '\0')
3569 if (!short_option (flags->cs->c))
3570 /* Long options require '='. */
3572 p = quote_for_env (p, flags->arg);
3574 flags = flags->next;
3577 /* If no flags at all, get rid of the initial dash. */
3578 if (p == &flagstring[1])
3580 flagstring[0] = '\0';
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),
3591 /* Write a reference to -*-eval-flags-*-, which contains all the --eval
3596 p = mempcpy (p, evalref, CSTRLEN (evalref));
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. */
3605 const char *r = posix_pedantic ? posixref : ref;
3606 size_t l = strlen (r);
3607 v = lookup_variable (r, l);
3609 if (v && v->value && v->value[0] != '\0')
3611 p = stpcpy (p, " -- ");
3614 p = mempcpy (p, r, l);
3619 /* If there is a leading dash, omit it. */
3620 if (flagstring[0] == '-')
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);
3636 /* Print version information. */
3639 print_version (void)
3641 static int printed_version = 0;
3643 const char *precede = print_data_base_flag ? "# " : "";
3645 if (printed_version)
3646 /* Do it only once. */
3649 printf ("%sGNU Make %s\n", precede, version_string);
3651 if (!remote_description || *remote_description == '\0')
3652 printf (_("%sBuilt for %s\n"), precede, make_host);
3654 printf (_("%sBuilt for %s (%s)\n"),
3655 precede, make_host, remote_description);
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. */
3662 printf ("%sCopyright (C) 1988-2022 Free Software Foundation, Inc.\n",
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);
3670 printed_version = 1;
3673 /* Print a bunch of information about this and that. */
3676 print_data_base (void)
3678 time_t when = time ((time_t *) 0);
3682 printf (_("\n# Make data base, printed on %s"), ctime (&when));
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 ("#");
3691 when = time ((time_t *) 0);
3692 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
3696 clean_jobserver (int status)
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. */
3703 if (jobserver_enabled() && jobserver_tokens)
3707 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3710 /* Don't write back the "free" token */
3711 while (--jobserver_tokens)
3712 jobserver_release (0);
3716 /* Sanity: If we're the master, were all the tokens written back? */
3718 if (master_job_slots)
3720 /* We didn't write one for ourself, so start at 1. */
3721 unsigned int tokens = 1 + jobserver_acquire_all ();
3723 if (tokens != master_job_slots)
3725 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3726 tokens, master_job_slots);
3732 /* Exit with STATUS, cleaning up as necessary. */
3737 static char dying = 0;
3745 if (print_version_flag)
3748 /* Get rid of a temp file from reading a makefile from stdin. */
3749 temp_stdin_unlink ();
3751 /* Wait for children to die. */
3752 err = (status != 0);
3753 while (job_slots_used > 0)
3754 reap_children (1, err);
3756 /* Let the remote job module clean up its state. */
3759 /* Remove the intermediate files. */
3760 remove_intermediates (0);
3762 if (print_data_base_flag)
3766 verify_file_data_base ();
3768 clean_jobserver (status);
3772 /* die() might be called in a recipe output context due to an
3773 $(error ...) function. */
3774 output_close (output_context);
3776 if (output_context != &make_sync)
3777 output_close (&make_sync);
3782 output_close (NULL);
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)
3793 /* If it fails we don't care: shut up GCC. */
3795 _x = chdir (directory_before_chdir);