1 /* Argument parsing and main program of GNU Make.
2 Copyright (C) 1988-2016 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 <http://www.gnu.org/licenses/>. */
31 # include <proto/dos.h>
36 # include "pathstuff.h"
37 # include "sub_proc.h"
41 # include <sys/types.h>
42 # include <sys/wait.h>
49 int __stack = 20000; /* Make sure we have 20K of stack space */
52 int vms_use_mcr_command = 0;
53 int vms_always_use_cmd_file = 0;
54 int vms_gnv_shell = 0;
55 int vms_legacy_behavior = 0;
56 int vms_comma_separator = 0;
57 int vms_unix_simulation = 0;
58 int vms_report_unix_paths = 0;
60 /* Evaluates if a VMS environment option is set, only look at first character */
62 get_vms_env_flag (const char *name, int default_value)
67 value = getenv (name);
71 x = toupper (value[0]);
87 #if defined HAVE_WAITPID || defined HAVE_WAIT3
88 # define HAVE_WAIT_NOHANG
95 # ifndef sun /* Sun has an incorrect decl in a header. */
96 void exit (int) __attribute__ ((noreturn));
101 static void clean_jobserver (int status);
102 static void print_data_base (void);
103 static void print_version (void);
104 static void decode_switches (int argc, const char **argv, int env);
105 static void decode_env_switches (const char *envar, unsigned int len);
106 static struct variable *define_makeflags (int all, int makefile);
107 static char *quote_for_env (char *out, const char *in);
108 static void initialize_global_hash_tables (void);
111 /* The structure that describes an accepted command switch. */
113 struct command_switch
115 int c; /* The switch character. */
117 enum /* Type of the value. */
119 flag, /* Turn int flag on. */
120 flag_off, /* Turn int flag off. */
121 string, /* One string per invocation. */
122 strlist, /* One string per switch. */
123 filename, /* A string containing a file name. */
124 positive_int, /* A positive integer. */
125 floating, /* A floating-point number (double). */
126 ignore /* Ignored. */
129 void *value_ptr; /* Pointer to the value-holding variable. */
131 unsigned int env:1; /* Can come from MAKEFLAGS. */
132 unsigned int toenv:1; /* Should be put in MAKEFLAGS. */
133 unsigned int no_makefile:1; /* Don't propagate when remaking makefiles. */
135 const void *noarg_value; /* Pointer to value used if no arg given. */
136 const void *default_value; /* Pointer to default value. */
138 const char *long_name; /* Long option name. */
141 /* True if C is a switch value that corresponds to a short option. */
143 #define short_option(c) ((c) <= CHAR_MAX)
145 /* The structure used to hold the list of strings given
146 in command switches of a type that takes strlist arguments. */
150 const char **list; /* Nil-terminated list of strings. */
151 unsigned int idx; /* Index into above. */
152 unsigned int max; /* Number of pointers allocated. */
156 /* The recognized command switches. */
158 /* Nonzero means do extra verification (that may slow things down). */
162 /* Nonzero means do not print commands to be executed (-s). */
166 /* Nonzero means just touch the files
167 that would appear to need remaking (-t) */
171 /* Nonzero means just print what commands would need to be executed,
172 don't actually execute them (-n). */
176 /* Print debugging info (--debug). */
178 static struct stringlist *db_flags = 0;
179 static int debug_flag = 0;
183 /* Synchronize output (--output-sync). */
185 char *output_sync_option = 0;
188 /* Suspend make in main for a short time to allow debugger to attach */
190 int suspend_flag = 0;
193 /* Environment variables override makefile definitions. */
195 int env_overrides = 0;
197 /* Nonzero means ignore status codes returned by commands
198 executed to remake files. Just treat them all as successful (-i). */
200 int ignore_errors_flag = 0;
202 /* Nonzero means don't remake anything, just print the data base
203 that results from reading the makefile (-p). */
205 int print_data_base_flag = 0;
207 /* Nonzero means don't remake anything; just return a nonzero status
208 if the specified targets are not up to date (-q). */
210 int question_flag = 0;
212 /* Nonzero means do not use any of the builtin rules (-r) / variables (-R). */
214 int no_builtin_rules_flag = 0;
215 int no_builtin_variables_flag = 0;
217 /* Nonzero means keep going even if remaking some file fails (-k). */
220 int default_keep_going_flag = 0;
222 /* Nonzero means check symlink mtimes. */
224 int check_symlink_flag = 0;
226 /* Nonzero means print directory before starting and when done (-w). */
228 int print_directory_flag = 0;
230 /* Nonzero means ignore print_directory_flag and never print the directory.
231 This is necessary because print_directory_flag is set implicitly. */
233 int inhibit_print_directory_flag = 0;
235 /* Nonzero means print version information. */
237 int print_version_flag = 0;
239 /* List of makefiles given with -f switches. */
241 static struct stringlist *makefiles = 0;
243 /* Size of the stack when we started. */
245 #ifdef SET_STACK_SIZE
246 struct rlimit stack_limit;
250 /* Number of job slots for parallelism. */
252 unsigned int job_slots;
254 #define INVALID_JOB_SLOTS (-1)
255 static unsigned int master_job_slots = 0;
256 static int arg_job_slots = INVALID_JOB_SLOTS;
258 static const int default_job_slots = INVALID_JOB_SLOTS;
260 /* Value of job_slots that means no limit. */
262 static const int inf_jobs = 0;
264 /* Authorization for the jobserver. */
266 static char *jobserver_auth = NULL;
268 /* Handle for the mutex used on Windows to synchronize output of our
269 children under -O. */
271 char *sync_mutex = NULL;
273 /* Maximum load average at which multiple jobs will be run.
274 Negative values mean unlimited, while zero means limit to
275 zero load (which could be useful to start infinite jobs remotely
276 but one at a time locally). */
278 double max_load_average = -1.0;
279 double default_load_average = -1.0;
281 int max_load_average = -1;
282 int default_load_average = -1;
285 /* List of directories given with -C switches. */
287 static struct stringlist *directories = 0;
289 /* List of include directories given with -I switches. */
291 static struct stringlist *include_directories = 0;
293 /* List of files given with -o switches. */
295 static struct stringlist *old_files = 0;
297 /* List of files given with -W switches. */
299 static struct stringlist *new_files = 0;
301 /* List of strings to be eval'd. */
302 static struct stringlist *eval_strings = 0;
304 /* If nonzero, we should just print usage and exit. */
306 static int print_usage_flag = 0;
308 /* If nonzero, we should print a warning message
309 for each reference to an undefined variable. */
311 int warn_undefined_variables_flag;
313 /* If nonzero, always build all targets, regardless of whether
314 they appear out of date or not. */
316 static int always_make_set = 0;
317 int always_make_flag = 0;
319 /* If nonzero, we're in the "try to rebuild makefiles" phase. */
321 int rebuilding_makefiles = 0;
323 /* Remember the original value of the SHELL variable, from the environment. */
325 struct variable shell_var;
327 /* This character introduces a command: it's the first char on the line. */
329 char cmd_prefix = '\t';
332 /* The usage output. We write it this way to make life easier for the
333 translators, especially those trying to translate to right-to-left
334 languages like Hebrew. */
336 static const char *const usage[] =
340 -b, -m Ignored for compatibility.\n"),
342 -B, --always-make Unconditionally make all targets.\n"),
344 -C DIRECTORY, --directory=DIRECTORY\n\
345 Change to DIRECTORY before doing anything.\n"),
347 -d Print lots of debugging information.\n"),
349 --debug[=FLAGS] Print various types of debugging information.\n"),
351 -e, --environment-overrides\n\
352 Environment variables override makefiles.\n"),
354 --eval=STRING Evaluate STRING as a makefile statement.\n"),
356 -f FILE, --file=FILE, --makefile=FILE\n\
357 Read FILE as a makefile.\n"),
359 -h, --help Print this message and exit.\n"),
361 -i, --ignore-errors Ignore errors from recipes.\n"),
363 -I DIRECTORY, --include-dir=DIRECTORY\n\
364 Search DIRECTORY for included makefiles.\n"),
366 -j [N], --jobs[=N] Allow N jobs at once; infinite jobs with no arg.\n"),
368 -k, --keep-going Keep going when some targets can't be made.\n"),
370 -l [N], --load-average[=N], --max-load[=N]\n\
371 Don't start multiple jobs unless load is below N.\n"),
373 -L, --check-symlink-times Use the latest mtime between symlinks and target.\n"),
375 -n, --just-print, --dry-run, --recon\n\
376 Don't actually run any recipe; just print them.\n"),
378 -o FILE, --old-file=FILE, --assume-old=FILE\n\
379 Consider FILE to be very old and don't remake it.\n"),
381 -O[TYPE], --output-sync[=TYPE]\n\
382 Synchronize output of parallel jobs by TYPE.\n"),
384 -p, --print-data-base Print make's internal database.\n"),
386 -q, --question Run no recipe; exit status says if up to date.\n"),
388 -r, --no-builtin-rules Disable the built-in implicit rules.\n"),
390 -R, --no-builtin-variables Disable the built-in variable settings.\n"),
392 -s, --silent, --quiet Don't echo recipes.\n"),
394 -S, --no-keep-going, --stop\n\
397 -t, --touch Touch targets instead of remaking them.\n"),
399 --trace Print tracing information.\n"),
401 -v, --version Print the version number of make and exit.\n"),
403 -w, --print-directory Print the current directory.\n"),
405 --no-print-directory Turn off -w, even if it was turned on implicitly.\n"),
407 -W FILE, --what-if=FILE, --new-file=FILE, --assume-new=FILE\n\
408 Consider FILE to be infinitely new.\n"),
410 --warn-undefined-variables Warn when an undefined variable is referenced.\n"),
414 /* The table of command switches.
415 Order matters here: this is the order MAKEFLAGS will be constructed.
416 So be sure all simple flags (single char, no argument) come first. */
418 static const struct command_switch switches[] =
420 { 'b', ignore, 0, 0, 0, 0, 0, 0, 0 },
421 { 'B', flag, &always_make_set, 1, 1, 0, 0, 0, "always-make" },
422 { 'd', flag, &debug_flag, 1, 1, 0, 0, 0, 0 },
424 { 'D', flag, &suspend_flag, 1, 1, 0, 0, 0, "suspend-for-debug" },
426 { 'e', flag, &env_overrides, 1, 1, 0, 0, 0, "environment-overrides", },
427 { 'h', flag, &print_usage_flag, 0, 0, 0, 0, 0, "help" },
428 { 'i', flag, &ignore_errors_flag, 1, 1, 0, 0, 0, "ignore-errors" },
429 { 'k', flag, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
431 { 'L', flag, &check_symlink_flag, 1, 1, 0, 0, 0, "check-symlink-times" },
432 { 'm', ignore, 0, 0, 0, 0, 0, 0, 0 },
433 { 'n', flag, &just_print_flag, 1, 1, 1, 0, 0, "just-print" },
434 { 'p', flag, &print_data_base_flag, 1, 1, 0, 0, 0, "print-data-base" },
435 { 'q', flag, &question_flag, 1, 1, 1, 0, 0, "question" },
436 { 'r', flag, &no_builtin_rules_flag, 1, 1, 0, 0, 0, "no-builtin-rules" },
437 { 'R', flag, &no_builtin_variables_flag, 1, 1, 0, 0, 0,
438 "no-builtin-variables" },
439 { 's', flag, &silent_flag, 1, 1, 0, 0, 0, "silent" },
440 { 'S', flag_off, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
442 { 't', flag, &touch_flag, 1, 1, 1, 0, 0, "touch" },
443 { 'v', flag, &print_version_flag, 1, 1, 0, 0, 0, "version" },
444 { 'w', flag, &print_directory_flag, 1, 1, 0, 0, 0, "print-directory" },
446 /* These options take arguments. */
447 { 'C', filename, &directories, 0, 0, 0, 0, 0, "directory" },
448 { 'f', filename, &makefiles, 0, 0, 0, 0, 0, "file" },
449 { 'I', filename, &include_directories, 1, 1, 0, 0, 0,
451 { 'j', positive_int, &arg_job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,
454 { 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,
455 &default_load_average, "load-average" },
457 { 'l', positive_int, &max_load_average, 1, 1, 0, &default_load_average,
458 &default_load_average, "load-average" },
460 { 'o', filename, &old_files, 0, 0, 0, 0, 0, "old-file" },
461 { 'O', string, &output_sync_option, 1, 1, 0, "target", 0, "output-sync" },
462 { 'W', filename, &new_files, 0, 0, 0, 0, 0, "what-if" },
464 /* These are long-style options. */
465 { CHAR_MAX+1, strlist, &db_flags, 1, 1, 0, "basic", 0, "debug" },
466 { CHAR_MAX+2, string, &jobserver_auth, 1, 1, 0, 0, 0, "jobserver-auth" },
467 { CHAR_MAX+3, flag, &trace_flag, 1, 1, 0, 0, 0, "trace" },
468 { CHAR_MAX+4, flag, &inhibit_print_directory_flag, 1, 1, 0, 0, 0,
469 "no-print-directory" },
470 { CHAR_MAX+5, flag, &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
471 "warn-undefined-variables" },
472 { CHAR_MAX+6, strlist, &eval_strings, 1, 0, 0, 0, 0, "eval" },
473 { CHAR_MAX+7, string, &sync_mutex, 1, 1, 0, 0, 0, "sync-mutex" },
474 { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
477 /* Secondary long names for options. */
479 static struct option long_option_aliases[] =
481 { "quiet", no_argument, 0, 's' },
482 { "stop", no_argument, 0, 'S' },
483 { "new-file", required_argument, 0, 'W' },
484 { "assume-new", required_argument, 0, 'W' },
485 { "assume-old", required_argument, 0, 'o' },
486 { "max-load", optional_argument, 0, 'l' },
487 { "dry-run", no_argument, 0, 'n' },
488 { "recon", no_argument, 0, 'n' },
489 { "makefile", required_argument, 0, 'f' },
492 /* List of goal targets. */
494 static struct goaldep *goals, *lastgoal;
496 /* List of variables which were defined on the command line
497 (or, equivalently, in MAKEFLAGS). */
499 struct command_variable
501 struct command_variable *next;
502 struct variable *variable;
504 static struct command_variable *command_variables;
506 /* The name we were invoked with. */
509 /* On MS-Windows, we chop off the .exe suffix in 'main', so this
510 cannot be 'const'. */
516 /* Our current directory before processing any -C options. */
518 char *directory_before_chdir;
520 /* Our current directory after processing all -C options. */
522 char *starting_directory;
524 /* Value of the MAKELEVEL variable at startup (or 0). */
526 unsigned int makelevel;
528 /* Pointer to the value of the .DEFAULT_GOAL special variable.
529 The value will be the name of the goal to remake if the command line
530 does not override it. It can be set by the makefile, or else it's
531 the first target defined in the makefile whose name does not start
534 struct variable * default_goal_var;
536 /* Pointer to structure for the file .DEFAULT
537 whose commands are used for any file that has none of its own.
538 This is zero if the makefiles do not define .DEFAULT. */
540 struct file *default_file;
542 /* Nonzero if we have seen the magic '.POSIX' target.
543 This turns on pedantic compliance with POSIX.2. */
547 /* Nonzero if we have seen the '.SECONDEXPANSION' target.
548 This turns on secondary expansion of prerequisites. */
550 int second_expansion;
552 /* Nonzero if we have seen the '.ONESHELL' target.
553 This causes the entire recipe to be handed to SHELL
554 as a single string, potentially containing newlines. */
558 /* One of OUTPUT_SYNC_* if the "--output-sync" option was given. This
559 attempts to synchronize the output of parallel jobs such that the results
560 of each job stay together. */
562 int output_sync = OUTPUT_SYNC_NONE;
564 /* Nonzero if the "--trace" option was given. */
568 /* Nonzero if we have seen the '.NOTPARALLEL' target.
569 This turns off parallel builds for this invocation of make. */
573 /* Nonzero if some rule detected clock skew; we keep track so (a) we only
574 print one warning about it during the run, and (b) we can print a final
575 warning at the end of the run. */
577 int clock_skew_detected;
579 /* Map of possible stop characters for searching strings. */
581 # define UCHAR_MAX 255
583 unsigned short stopchar_map[UCHAR_MAX + 1] = {0};
585 /* If output-sync is enabled we'll collect all the output generated due to
586 options, while reading makefiles, etc. */
588 struct output make_sync;
591 /* Mask of signals that are being caught with fatal_error_signal. */
594 sigset_t fatal_signal_set;
596 # ifdef HAVE_SIGSETMASK
597 int fatal_signal_mask;
601 #if !HAVE_DECL_BSD_SIGNAL && !defined bsd_signal
602 # if !defined HAVE_SIGACTION
603 # define bsd_signal signal
605 typedef RETSIGTYPE (*bsd_signal_ret_t) (int);
607 static bsd_signal_ret_t
608 bsd_signal (int sig, bsd_signal_ret_t func)
610 struct sigaction act, oact;
611 act.sa_handler = func;
612 act.sa_flags = SA_RESTART;
613 sigemptyset (&act.sa_mask);
614 sigaddset (&act.sa_mask, sig);
615 if (sigaction (sig, &act, &oact) != 0)
617 return oact.sa_handler;
623 initialize_global_hash_tables (void)
625 init_hash_global_variable_set ();
628 hash_init_directories ();
629 hash_init_function_table ();
632 /* This character map locate stop chars when parsing GNU makefiles.
633 Each element is true if we should stop parsing on that character. */
636 initialize_stopchar_map (void)
640 stopchar_map[(int)'\0'] = MAP_NUL;
641 stopchar_map[(int)'#'] = MAP_COMMENT;
642 stopchar_map[(int)';'] = MAP_SEMI;
643 stopchar_map[(int)'='] = MAP_EQUALS;
644 stopchar_map[(int)':'] = MAP_COLON;
645 stopchar_map[(int)'%'] = MAP_PERCENT;
646 stopchar_map[(int)'|'] = MAP_PIPE;
647 stopchar_map[(int)'.'] = MAP_DOT | MAP_USERFUNC;
648 stopchar_map[(int)','] = MAP_COMMA;
649 stopchar_map[(int)'$'] = MAP_VARIABLE;
651 stopchar_map[(int)'-'] = MAP_USERFUNC;
652 stopchar_map[(int)'_'] = MAP_USERFUNC;
654 stopchar_map[(int)' '] = MAP_BLANK;
655 stopchar_map[(int)'\t'] = MAP_BLANK;
657 stopchar_map[(int)'/'] = MAP_DIRSEP;
659 stopchar_map[(int)':'] |= MAP_DIRSEP;
660 stopchar_map[(int)']'] |= MAP_DIRSEP;
661 stopchar_map[(int)'>'] |= MAP_DIRSEP;
662 #elif defined(HAVE_DOS_PATHS)
663 stopchar_map[(int)'\\'] |= MAP_DIRSEP;
666 for (i = 1; i <= UCHAR_MAX; ++i)
668 if (isspace (i) && NONE_SET (stopchar_map[i], MAP_BLANK))
669 /* Don't mark blank characters as newline characters. */
670 stopchar_map[i] |= MAP_NEWLINE;
671 else if (isalnum (i))
672 stopchar_map[i] |= MAP_USERFUNC;
677 expand_command_line_file (const char *name)
683 O (fatal, NILF, _("empty string invalid as file name"));
687 expanded = tilde_expand (name);
688 if (expanded && expanded[0] != '\0')
692 /* This is also done in parse_file_seq, so this is redundant
693 for names read from makefiles. It is here for names passed
694 on the command line. */
695 while (name[0] == '.' && name[1] == '/')
698 while (name[0] == '/')
699 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
705 /* Nothing else but one or more "./", maybe plus slashes! */
709 cp = strcache_add (name);
716 /* Toggle -d on receipt of SIGUSR1. */
720 debug_signal_handler (int sig UNUSED)
722 db_level = db_level ? DB_NONE : DB_BASIC;
727 decode_debug_flags (void)
735 for (pp=db_flags->list; *pp; ++pp)
741 switch (tolower (p[0]))
747 db_level |= DB_BASIC;
750 db_level |= DB_BASIC | DB_IMPLICIT;
756 db_level |= DB_BASIC | DB_MAKEFILES;
762 db_level |= DB_BASIC | DB_VERBOSE;
766 _("unknown debug level specification '%s'"), p);
769 while (*(++p) != '\0')
770 if (*p == ',' || *p == ' ')
789 decode_output_sync_flags (void)
791 #ifdef NO_OUTPUT_SYNC
792 output_sync = OUTPUT_SYNC_NONE;
794 if (output_sync_option)
796 if (streq (output_sync_option, "none"))
797 output_sync = OUTPUT_SYNC_NONE;
798 else if (streq (output_sync_option, "line"))
799 output_sync = OUTPUT_SYNC_LINE;
800 else if (streq (output_sync_option, "target"))
801 output_sync = OUTPUT_SYNC_TARGET;
802 else if (streq (output_sync_option, "recurse"))
803 output_sync = OUTPUT_SYNC_RECURSE;
806 _("unknown output-sync type '%s'"), output_sync_option);
810 RECORD_SYNC_MUTEX (sync_mutex);
816 #ifndef NO_OUTPUT_SYNC
818 /* This is called from start_job_command when it detects that
819 output_sync option is in effect. The handle to the synchronization
820 mutex is passed, as a string, to sub-makes via the --sync-mutex
821 command-line argument. */
823 prepare_mutex_handle_string (sync_handle_t handle)
827 /* Prepare the mutex handle string for our children. */
828 /* 2 hex digits per byte + 2 characters for "0x" + null. */
829 sync_mutex = xmalloc ((2 * sizeof (sync_handle_t)) + 2 + 1);
830 sprintf (sync_mutex, "0x%Ix", handle);
831 define_makeflags (1, 0);
835 #endif /* NO_OUTPUT_SYNC */
838 * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
839 * exception and print it to stderr instead.
841 * If ! DB_VERBOSE, just print a simple message and exit.
842 * If DB_VERBOSE, print a more verbose message.
843 * If compiled for DEBUG, let exception pass through to GUI so that
844 * debuggers can attach.
847 handle_runtime_exceptions (struct _EXCEPTION_POINTERS *exinfo)
849 PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
850 LPSTR cmdline = GetCommandLine ();
851 LPSTR prg = strtok (cmdline, " ");
855 LPTSTR lpszStrings[1];
858 if (! ISDB (DB_VERBOSE))
861 _("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\n"),
862 prg, exrec->ExceptionCode, exrec->ExceptionAddress);
863 fprintf (stderr, errmsg);
868 _("\nUnhandled exception filter called from program %s\nExceptionCode = %lx\nExceptionFlags = %lx\nExceptionAddress = 0x%p\n"),
869 prg, exrec->ExceptionCode, exrec->ExceptionFlags,
870 exrec->ExceptionAddress);
872 if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
873 && exrec->NumberParameters >= 2)
874 sprintf (&errmsg[strlen(errmsg)],
875 (exrec->ExceptionInformation[0]
876 ? _("Access violation: write operation at address 0x%p\n")
877 : _("Access violation: read operation at address 0x%p\n")),
878 (PVOID)exrec->ExceptionInformation[1]);
880 /* turn this on if we want to put stuff in the event log too */
882 hEventSource = RegisterEventSource (NULL, "GNU Make");
883 lpszStrings[0] = errmsg;
885 if (hEventSource != NULL)
887 ReportEvent (hEventSource, /* handle of event source */
888 EVENTLOG_ERROR_TYPE, /* event type */
889 0, /* event category */
891 NULL, /* current user's SID */
892 1, /* strings in lpszStrings */
893 0, /* no bytes of raw data */
894 lpszStrings, /* array of error strings */
895 NULL); /* no raw data */
897 (VOID) DeregisterEventSource (hEventSource);
901 /* Write the error to stderr too */
902 fprintf (stderr, errmsg);
905 return EXCEPTION_CONTINUE_SEARCH;
908 return (255); /* not reached */
913 * On WIN32 systems we don't have the luxury of a /bin directory that
914 * is mapped globally to every drive mounted to the system. Since make could
915 * be invoked from any drive, and we don't want to propagate /bin/sh
916 * to every single drive. Allow ourselves a chance to search for
917 * a value for default shell here (if the default path does not exist).
921 find_and_set_default_shell (const char *token)
925 const char *search_token;
928 extern const char *default_shell;
931 search_token = default_shell;
933 search_token = atoken = xstrdup (token);
935 /* If the user explicitly requests the DOS cmd shell, obey that request.
936 However, make sure that's what they really want by requiring the value
937 of SHELL either equal, or have a final path element of, "cmd" or
938 "cmd.exe" case-insensitive. */
939 tokend = search_token + strlen (search_token) - 3;
940 if (((tokend == search_token
941 || (tokend > search_token
942 && (tokend[-1] == '/' || tokend[-1] == '\\')))
943 && !strcasecmp (tokend, "cmd"))
944 || ((tokend - 4 == search_token
945 || (tokend - 4 > search_token
946 && (tokend[-5] == '/' || tokend[-5] == '\\')))
947 && !strcasecmp (tokend - 4, "cmd.exe")))
949 batch_mode_shell = 1;
951 sprintf (sh_path, "%s", search_token);
952 default_shell = xstrdup (w32ify (sh_path, 0));
953 DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
957 else if (!no_default_sh_exe
958 && (token == NULL || !strcmp (search_token, default_shell)))
960 /* no new information, path already set or known */
963 else if (_access (search_token, 0) == 0)
965 /* search token path was found */
966 sprintf (sh_path, "%s", search_token);
967 default_shell = xstrdup (w32ify (sh_path, 0));
968 DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
975 struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
977 /* Search Path for shell */
983 ep = strchr (p, PATH_SEPARATOR_CHAR);
989 sprintf (sh_path, "%s/%s", p, search_token);
990 if (_access (sh_path, 0) == 0)
992 default_shell = xstrdup (w32ify (sh_path, 0));
994 *ep = PATH_SEPARATOR_CHAR;
1001 *ep = PATH_SEPARATOR_CHAR;
1005 ep = strchr (p, PATH_SEPARATOR_CHAR);
1008 /* be sure to check last element of Path */
1011 sprintf (sh_path, "%s/%s", p, search_token);
1012 if (_access (sh_path, 0) == 0)
1014 default_shell = xstrdup (w32ify (sh_path, 0));
1021 (_("find_and_set_shell() path search set default_shell = %s\n"),
1027 if (!unixy_shell && sh_found
1028 && (strstr (default_shell, "sh") || strstr (default_shell, "SH")))
1031 batch_mode_shell = 0;
1034 #ifdef BATCH_MODE_ONLY_SHELL
1035 batch_mode_shell = 1;
1042 #endif /* WINDOWS32 */
1046 msdos_return_to_initial_directory (void)
1048 if (directory_before_chdir)
1049 chdir (directory_before_chdir);
1051 #endif /* __MSDOS__ */
1054 reset_jobserver (void)
1057 free (jobserver_auth);
1058 jobserver_auth = NULL;
1063 main (int argc, char **argv)
1066 main (int argc, char **argv, char **envp)
1069 static char *stdin_nm = 0;
1070 int makefile_status = MAKE_SUCCESS;
1071 struct goaldep *read_files;
1072 PATH_VAR (current_directory);
1073 unsigned int restarts = 0;
1074 unsigned int syncing = 0;
1077 const char *unix_path = NULL;
1078 const char *windows32_path = NULL;
1080 SetUnhandledExceptionFilter (handle_runtime_exceptions);
1082 /* start off assuming we have no shell */
1084 no_default_sh_exe = 1;
1087 output_init (&make_sync);
1089 initialize_stopchar_map();
1091 #ifdef SET_STACK_SIZE
1092 /* Get rid of any avoidable limit on stack size. */
1096 /* Set the stack limit huge so that alloca does not fail. */
1097 if (getrlimit (RLIMIT_STACK, &rlim) == 0
1098 && rlim.rlim_cur > 0 && rlim.rlim_cur < rlim.rlim_max)
1101 rlim.rlim_cur = rlim.rlim_max;
1102 setrlimit (RLIMIT_STACK, &rlim);
1105 stack_limit.rlim_cur = 0;
1109 /* Needed for OS/2 */
1110 initialize_main (&argc, &argv);
1112 #ifdef MAKE_MAINTAINER_MODE
1113 /* In maintainer mode we always enable verification. */
1117 #if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
1118 /* Request the most powerful version of 'system', to
1119 make up for the dumb default shell. */
1120 __system_flags = (__system_redirect
1121 | __system_use_shell
1122 | __system_allow_multiple_cmds
1123 | __system_allow_long_cmds
1124 | __system_handle_null_commands
1125 | __system_emulate_chdir);
1129 /* Set up gettext/internationalization support. */
1130 setlocale (LC_ALL, "");
1131 /* The cast to void shuts up compiler warnings on systems that
1133 (void)bindtextdomain (PACKAGE, LOCALEDIR);
1134 (void)textdomain (PACKAGE);
1137 sigemptyset (&fatal_signal_set);
1138 #define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
1140 #ifdef HAVE_SIGSETMASK
1141 fatal_signal_mask = 0;
1142 #define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
1144 #define ADD_SIG(sig) (void)sig
1148 #define FATAL_SIG(sig) \
1149 if (bsd_signal (sig, fatal_error_signal) == SIG_IGN) \
1150 bsd_signal (sig, SIG_IGN); \
1158 FATAL_SIG (SIGQUIT);
1161 FATAL_SIG (SIGTERM);
1164 /* Windows 9X delivers FP exceptions in child programs to their
1165 parent! We don't want Make to die when a child divides by zero,
1166 so we work around that lossage by catching SIGFPE. */
1171 FATAL_SIG (SIGDANGER);
1174 FATAL_SIG (SIGXCPU);
1177 FATAL_SIG (SIGXFSZ);
1182 /* Do not ignore the child-death signal. This must be done before
1183 any children could possibly be created; otherwise, the wait
1184 functions won't work on systems with the SVR4 ECHILD brain
1185 damage, if our invoker is ignoring this signal. */
1187 #ifdef HAVE_WAIT_NOHANG
1188 # if defined SIGCHLD
1189 (void) bsd_signal (SIGCHLD, SIG_DFL);
1191 # if defined SIGCLD && SIGCLD != SIGCHLD
1192 (void) bsd_signal (SIGCLD, SIG_DFL);
1198 /* Figure out where this program lives. */
1201 argv[0] = (char *)"";
1202 if (argv[0][0] == '\0')
1206 program = strrchr (argv[0], '/');
1207 #if defined(__MSDOS__) || defined(__EMX__)
1209 program = strrchr (argv[0], '\\');
1212 /* Some weird environments might pass us argv[0] with
1213 both kinds of slashes; we must find the rightmost. */
1214 char *p = strrchr (argv[0], '\\');
1215 if (p && p > program)
1218 if (program == 0 && argv[0][1] == ':')
1219 program = argv[0] + 1;
1224 /* Extract program from full path */
1225 program = strrchr (argv[0], '\\');
1228 int argv0_len = strlen (program);
1229 if (argv0_len > 4 && streq (&program[argv0_len - 4], ".exe"))
1230 /* Remove .exe extension */
1231 program[argv0_len - 4] = '\0';
1236 set_program_name (argv[0]);
1237 program = program_name;
1242 shell = getenv ("SHELL");
1246 /* Need to know if CRTL set to report UNIX paths. Use getcwd as
1247 it works on all versions of VMS. */
1248 pwd = getcwd(pwdbuf, 256);
1250 vms_report_unix_paths = 1;
1252 vms_use_mcr_command = get_vms_env_flag ("GNV$MAKE_USE_MCR", 0);
1254 vms_always_use_cmd_file = get_vms_env_flag ("GNV$MAKE_USE_CMD_FILE", 0);
1256 /* Legacy behavior is on VMS is older behavior that needed to be
1257 changed to be compatible with standard make behavior.
1258 For now only completely disable when running under a Bash shell.
1259 TODO: Update VMS built in recipes and macros to not need this
1260 behavior, at which time the default may change. */
1261 vms_legacy_behavior = get_vms_env_flag ("GNV$MAKE_OLD_VMS",
1264 /* VMS was changed to use a comma separator in the past, but that is
1265 incompatible with built in functions that expect space separated
1266 lists. Allow this to be selectively turned off. */
1267 vms_comma_separator = get_vms_env_flag ("GNV$MAKE_COMMA",
1268 vms_legacy_behavior);
1270 /* Some Posix shell syntax options are incompatible with VMS syntax.
1271 VMS requires double quotes for strings and escapes quotes
1272 differently. When this option is active, VMS will try
1273 to simulate Posix shell simulations instead of using
1274 VMS DCL behavior. */
1275 vms_unix_simulation = get_vms_env_flag ("GNV$MAKE_SHELL_SIM",
1276 !vms_legacy_behavior);
1279 if (need_vms_symbol () && !vms_use_mcr_command)
1280 create_foreign_command (program_name, argv[0]);
1289 /* Set up to access user data (files). */
1292 initialize_global_hash_tables ();
1294 /* Figure out where we are. */
1297 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1299 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1303 perror_with_name ("getcwd", "");
1305 OS (error, NILF, "getwd: %s", current_directory);
1307 current_directory[0] = '\0';
1308 directory_before_chdir = 0;
1311 directory_before_chdir = xstrdup (current_directory);
1314 /* Make sure we will return to the initial directory, come what may. */
1315 atexit (msdos_return_to_initial_directory);
1318 /* Initialize the special variables. */
1319 define_variable_cname (".VARIABLES", "", o_default, 0)->special = 1;
1320 /* define_variable_cname (".TARGETS", "", o_default, 0)->special = 1; */
1321 define_variable_cname (".RECIPEPREFIX", "", o_default, 0)->special = 1;
1322 define_variable_cname (".SHELLFLAGS", "-c", o_default, 0);
1323 define_variable_cname (".LOADED", "", o_default, 0);
1326 Use a separate variable because define_variable_cname() is a macro and
1327 some compilers (MSVC) don't like conditionals in macros. */
1329 const char *features = "target-specific order-only second-expansion"
1330 " else-if shortest-stem undefine oneshell"
1334 #ifdef MAKE_JOBSERVER
1337 #ifndef NO_OUTPUT_SYNC
1340 #ifdef MAKE_SYMLINKS
1351 define_variable_cname (".FEATURES", features, o_default, 0);
1354 /* Configure GNU Guile support */
1355 guile_gmake_setup (NILF);
1357 /* Read in variables from the environment. It is important that this be
1358 done before $(MAKE) is figured out so its definitions will not be
1359 from the environment. */
1365 for (i = 0; envp[i] != 0; ++i)
1368 const char *ep = envp[i];
1369 /* By default, export all variables culled from the environment. */
1370 enum variable_export export = v_export;
1373 while (! STOP_SET (*ep, MAP_EQUALS))
1376 /* If there's no equals sign it's a malformed environment. Ignore. */
1381 if (!unix_path && strneq (envp[i], "PATH=", 5))
1383 else if (!strnicmp (envp[i], "Path=", 5))
1385 if (!windows32_path)
1386 windows32_path = ep+1;
1387 /* PATH gets defined after the loop exits. */
1392 /* Length of the variable name, and skip the '='. */
1393 len = ep++ - envp[i];
1395 /* If this is MAKE_RESTARTS, check to see if the "already printed
1396 the enter statement" flag is set. */
1397 if (len == 13 && strneq (envp[i], "MAKE_RESTARTS", 13))
1404 restarts = (unsigned int) atoi (ep);
1405 export = v_noexport;
1408 v = define_variable (envp[i], len, ep, o_env, 1);
1410 /* POSIX says the value of SHELL set in the makefile won't change the
1411 value of SHELL given to subprocesses. */
1412 if (streq (v->name, "SHELL"))
1415 export = v_noexport;
1417 shell_var.name = xstrdup ("SHELL");
1418 shell_var.length = 5;
1419 shell_var.value = xstrdup (ep);
1426 /* If we didn't find a correctly spelled PATH we define PATH as
1427 * either the first misspelled value or an empty string
1430 define_variable_cname ("PATH", windows32_path ? windows32_path : "",
1431 o_env, 1)->export = v_export;
1433 #else /* For Amiga, read the ENV: device, ignoring all dirs */
1435 BPTR env, file, old;
1438 __aligned struct FileInfoBlock fib;
1440 env = Lock ("ENV:", ACCESS_READ);
1443 old = CurrentDir (DupLock (env));
1444 Examine (env, &fib);
1446 while (ExNext (env, &fib))
1448 if (fib.fib_DirEntryType < 0) /* File */
1450 /* Define an empty variable. It will be filled in
1451 variable_lookup(). Makes startup quite a bit faster. */
1452 define_variable (fib.fib_FileName,
1453 strlen (fib.fib_FileName),
1454 "", o_env, 1)->export = v_export;
1458 UnLock (CurrentDir (old));
1463 /* Decode the switches. */
1464 decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
1466 /* Clear GNUMAKEFLAGS to avoid duplication. */
1467 define_variable_cname ("GNUMAKEFLAGS", "", o_env, 0);
1469 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1472 /* People write things like:
1473 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
1474 and we set the -p, -i and -e switches. Doesn't seem quite right. */
1475 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1478 /* In output sync mode we need to sync any output generated by reading the
1479 makefiles, such as in $(info ...) or stderr from $(shell ...) etc. */
1481 syncing = make_sync.syncout = (output_sync == OUTPUT_SYNC_LINE
1482 || output_sync == OUTPUT_SYNC_TARGET);
1483 OUTPUT_SET (&make_sync);
1485 /* Remember the job slots set through the environment vs. command line. */
1487 int env_slots = arg_job_slots;
1488 arg_job_slots = INVALID_JOB_SLOTS;
1490 decode_switches (argc, (const char **)argv, 0);
1491 argv_slots = arg_job_slots;
1493 if (arg_job_slots == INVALID_JOB_SLOTS)
1494 arg_job_slots = env_slots;
1497 /* Set a variable specifying whether stdout/stdin is hooked to a TTY. */
1499 if (isatty (fileno (stdout)))
1500 if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMOUT")))
1502 const char *tty = TTYNAME (fileno (stdout));
1503 define_variable_cname ("MAKE_TERMOUT", tty ? tty : DEFAULT_TTYNAME,
1504 o_default, 0)->export = v_export;
1506 if (isatty (fileno (stderr)))
1507 if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMERR")))
1509 const char *tty = TTYNAME (fileno (stderr));
1510 define_variable_cname ("MAKE_TERMERR", tty ? tty : DEFAULT_TTYNAME,
1511 o_default, 0)->export = v_export;
1515 /* Reset in case the switches changed our minds. */
1516 syncing = (output_sync == OUTPUT_SYNC_LINE
1517 || output_sync == OUTPUT_SYNC_TARGET);
1519 if (make_sync.syncout && ! syncing)
1520 output_close (&make_sync);
1522 make_sync.syncout = syncing;
1523 OUTPUT_SET (&make_sync);
1525 /* Figure out the level of recursion. */
1527 struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
1528 if (v && v->value[0] != '\0' && v->value[0] != '-')
1529 makelevel = (unsigned int) atoi (v->value);
1537 fprintf (stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId ());
1538 fprintf (stderr, _("%s is suspending for 30 seconds..."), argv[0]);
1540 fprintf (stderr, _("done sleep(30). Continuing.\n"));
1544 /* Set always_make_flag if -B was given and we've not restarted already. */
1545 always_make_flag = always_make_set && (restarts == 0);
1547 /* Print version information, and exit. */
1548 if (print_version_flag)
1554 if (ISDB (DB_BASIC))
1558 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
1559 (If it is a relative pathname with a slash, prepend our directory name
1560 so the result will run the same program regardless of the current dir.
1561 If it is a name with no slash, we can only hope that PATH did not
1562 find it in the current directory.) */
1565 * Convert from backslashes to forward slashes for
1566 * programs like sh which don't like them. Shouldn't
1567 * matter if the path is one way or the other for
1570 if (strpbrk (argv[0], "/:\\") || strstr (argv[0], "..")
1571 || strneq (argv[0], "//", 2))
1572 argv[0] = xstrdup (w32ify (argv[0], 1));
1573 #else /* WINDOWS32 */
1574 #if defined (__MSDOS__) || defined (__EMX__)
1575 if (strchr (argv[0], '\\'))
1579 argv[0] = xstrdup (argv[0]);
1580 for (p = argv[0]; *p; p++)
1584 /* If argv[0] is not in absolute form, prepend the current
1585 directory. This can happen when Make is invoked by another DJGPP
1586 program that uses a non-absolute name. */
1587 if (current_directory[0] != '\0'
1589 && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
1591 /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
1592 && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
1595 argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
1596 #else /* !__MSDOS__ */
1597 if (current_directory[0] != '\0'
1598 && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0
1599 #ifdef HAVE_DOS_PATHS
1600 && (argv[0][0] != '\\' && (!argv[0][0] || argv[0][1] != ':'))
1601 && strchr (argv[0], '\\') != 0
1604 argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
1605 #endif /* !__MSDOS__ */
1606 #endif /* WINDOWS32 */
1609 /* We may move, but until we do, here we are. */
1610 starting_directory = current_directory;
1612 /* Set up the job_slots value and the jobserver. This can't be usefully set
1613 in the makefile, and we want to verify the authorization is valid before
1614 make has a chance to start using it for something else. */
1618 if (argv_slots == INVALID_JOB_SLOTS)
1620 if (jobserver_parse_auth (jobserver_auth))
1622 /* Success! Use the jobserver. */
1624 goto job_setup_complete;
1627 O (error, NILF, _("warning: jobserver unavailable: using -j1. Add '+' to parent make rule."));
1631 /* The user provided a -j setting on the command line: use it. */
1633 /* If restarts is >0 we already printed this message. */
1635 _("warning: -jN forced in submake: disabling jobserver mode."));
1637 /* We failed to use our parent's jobserver. */
1639 job_slots = (unsigned int)arg_job_slots;
1641 else if (arg_job_slots == INVALID_JOB_SLOTS)
1642 /* The default is one job at a time. */
1645 /* Use whatever was provided. */
1646 job_slots = (unsigned int)arg_job_slots;
1650 /* The extra indirection through $(MAKE_COMMAND) is done
1651 for hysterical raisins. */
1654 if (vms_use_mcr_command)
1655 define_variable_cname ("MAKE_COMMAND", vms_command (argv[0]), o_default, 0);
1657 define_variable_cname ("MAKE_COMMAND", program, o_default, 0);
1659 define_variable_cname ("MAKE_COMMAND", argv[0], o_default, 0);
1661 define_variable_cname ("MAKE", "$(MAKE_COMMAND)", o_default, 1);
1663 if (command_variables != 0)
1665 struct command_variable *cv;
1667 unsigned int len = 0;
1670 /* Figure out how much space will be taken up by the command-line
1671 variable definitions. */
1672 for (cv = command_variables; cv != 0; cv = cv->next)
1675 len += 2 * strlen (v->name);
1679 len += 2 * strlen (v->value);
1683 /* Now allocate a buffer big enough and fill it. */
1684 p = value = alloca (len);
1685 for (cv = command_variables; cv != 0; cv = cv->next)
1688 p = quote_for_env (p, v->name);
1692 p = quote_for_env (p, v->value);
1695 p[-1] = '\0'; /* Kill the final space and terminate. */
1697 /* Define an unchangeable variable with a name that no POSIX.2
1698 makefile could validly use for its own variable. */
1699 define_variable_cname ("-*-command-variables-*-", value, o_automatic, 0);
1701 /* Define the variable; this will not override any user definition.
1702 Normally a reference to this variable is written into the value of
1703 MAKEFLAGS, allowing the user to override this value to affect the
1704 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
1705 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
1706 a reference to this hidden variable is written instead. */
1707 define_variable_cname ("MAKEOVERRIDES", "${-*-command-variables-*-}",
1710 vms_export_dcl_symbol ("MAKEOVERRIDES", "${-*-command-variables-*-}");
1714 /* If there were -C flags, move ourselves about. */
1715 if (directories != 0)
1718 for (i = 0; directories->list[i] != 0; ++i)
1720 const char *dir = directories->list[i];
1722 /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1723 But allow -C/ just in case someone wants that. */
1725 char *p = (char *)dir + strlen (dir) - 1;
1726 while (p > dir && (p[0] == '/' || p[0] == '\\'))
1731 if (chdir (dir) < 0)
1732 pfatal_with_name (dir);
1738 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1739 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1741 * The functions in dir.c can incorrectly cache information for "."
1742 * before we have changed directory and this can cause file
1743 * lookups to fail because the current directory (.) was pointing
1744 * at the wrong place when it was first evaluated.
1746 no_default_sh_exe = !find_and_set_default_shell (NULL);
1747 #endif /* WINDOWS32 */
1749 /* Except under -s, always do -w in sub-makes and under -C. */
1750 if (!silent_flag && (directories != 0 || makelevel > 0))
1751 print_directory_flag = 1;
1753 /* Let the user disable that with --no-print-directory. */
1754 if (inhibit_print_directory_flag)
1755 print_directory_flag = 0;
1757 /* If -R was given, set -r too (doesn't make sense otherwise!) */
1758 if (no_builtin_variables_flag)
1759 no_builtin_rules_flag = 1;
1761 /* Construct the list of include directories to search. */
1763 construct_include_path (include_directories == 0
1764 ? 0 : include_directories->list);
1766 /* If we chdir'ed, figure out where we are now. */
1770 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1772 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1776 perror_with_name ("getcwd", "");
1778 OS (error, NILF, "getwd: %s", current_directory);
1780 starting_directory = 0;
1783 starting_directory = current_directory;
1786 define_variable_cname ("CURDIR", current_directory, o_file, 0);
1788 /* Read any stdin makefiles into temporary files. */
1793 for (i = 0; i < makefiles->idx; ++i)
1794 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
1796 /* This makefile is standard input. Since we may re-exec
1797 and thus re-read the makefiles, we read standard input
1798 into a temporary file and read from that. */
1805 _("Makefile from standard input specified twice."));
1808 # define DEFAULT_TMPDIR "/sys$scratch/"
1811 # define DEFAULT_TMPDIR P_tmpdir
1813 # define DEFAULT_TMPDIR "/tmp"
1816 #define DEFAULT_TMPFILE "GmXXXXXX"
1818 if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
1819 #if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
1820 /* These are also used commonly on these platforms. */
1821 && ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
1822 && ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
1825 tmpdir = DEFAULT_TMPDIR;
1827 template = alloca (strlen (tmpdir) + CSTRLEN (DEFAULT_TMPFILE) + 2);
1828 strcpy (template, tmpdir);
1830 #ifdef HAVE_DOS_PATHS
1831 if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
1832 strcat (template, "/");
1835 if (template[strlen (template) - 1] != '/')
1836 strcat (template, "/");
1838 #endif /* !HAVE_DOS_PATHS */
1840 strcat (template, DEFAULT_TMPFILE);
1841 outfile = output_tmpfile (&stdin_nm, template);
1843 pfatal_with_name (_("fopen (temporary file)"));
1844 while (!feof (stdin) && ! ferror (stdin))
1847 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
1848 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
1849 pfatal_with_name (_("fwrite (temporary file)"));
1853 /* Replace the name that read_all_makefiles will
1854 see with the name of the temporary file. */
1855 makefiles->list[i] = strcache_add (stdin_nm);
1857 /* Make sure the temporary file will not be remade. */
1859 struct file *f = enter_file (strcache_add (stdin_nm));
1861 f->update_status = us_success;
1862 f->command_state = cs_finished;
1863 /* Can't be intermediate, or it'll be removed too early for
1865 f->intermediate = 0;
1871 #ifndef __EMX__ /* Don't use a SIGCHLD handler for OS/2 */
1872 #if !defined(HAVE_WAIT_NOHANG) || defined(MAKE_JOBSERVER)
1873 /* Set up to handle children dying. This must be done before
1874 reading in the makefiles so that 'shell' function calls will work.
1876 If we don't have a hanging wait we have to fall back to old, broken
1877 functionality here and rely on the signal handler and counting
1880 If we're using the jobs pipe we need a signal handler so that SIGCHLD is
1881 not ignored; we need it to interrupt the read(2) of the jobserver pipe if
1882 we're waiting for a token.
1884 If none of these are true, we don't need a signal handler at all. */
1886 # if defined SIGCHLD
1887 bsd_signal (SIGCHLD, child_handler);
1889 # if defined SIGCLD && SIGCLD != SIGCHLD
1890 bsd_signal (SIGCLD, child_handler);
1895 /* If we have pselect() then we need to block SIGCHLD so it's deferred. */
1898 sigemptyset (&block);
1899 sigaddset (&block, SIGCHLD);
1900 if (sigprocmask (SIG_SETMASK, &block, NULL) < 0)
1901 pfatal_with_name ("sigprocmask(SIG_SETMASK, SIGCHLD)");
1908 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
1910 bsd_signal (SIGUSR1, debug_signal_handler);
1913 /* Define the initial list of suffixes for old-style rules. */
1914 set_default_suffixes ();
1916 /* Define the file rules for the built-in suffix rules. These will later
1917 be converted into pattern rules. We used to do this in
1918 install_default_implicit_rules, but since that happens after reading
1919 makefiles, it results in the built-in pattern rules taking precedence
1920 over makefile-specified suffix rules, which is wrong. */
1921 install_default_suffix_rules ();
1923 /* Define some internal and special variables. */
1924 define_automatic_variables ();
1926 /* Set up the MAKEFLAGS and MFLAGS variables for makefiles to see.
1927 Initialize it to be exported but allow the makefile to reset it. */
1928 define_makeflags (0, 0)->export = v_export;
1930 /* Define the default variables. */
1931 define_default_variables ();
1933 default_file = enter_file (strcache_add (".DEFAULT"));
1935 default_goal_var = define_variable_cname (".DEFAULT_GOAL", "", o_file, 0);
1937 /* Evaluate all strings provided with --eval.
1938 Also set up the $(-*-eval-flags-*-) variable. */
1944 unsigned int len = (CSTRLEN ("--eval=") + 1) * eval_strings->idx;
1946 for (i = 0; i < eval_strings->idx; ++i)
1948 p = xstrdup (eval_strings->list[i]);
1949 len += 2 * strlen (p);
1950 eval_buffer (p, NULL);
1954 p = value = alloca (len);
1955 for (i = 0; i < eval_strings->idx; ++i)
1957 strcpy (p, "--eval=");
1958 p += CSTRLEN ("--eval=");
1959 p = quote_for_env (p, eval_strings->list[i]);
1964 define_variable_cname ("-*-eval-flags-*-", value, o_automatic, 0);
1967 /* Read all the makefiles. */
1969 read_files = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
1972 /* look one last time after reading all Makefiles */
1973 if (no_default_sh_exe)
1974 no_default_sh_exe = !find_and_set_default_shell (NULL);
1975 #endif /* WINDOWS32 */
1977 #if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
1978 /* We need to know what kind of shell we will be using. */
1980 extern int _is_unixy_shell (const char *_path);
1981 struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
1982 extern int unixy_shell;
1983 extern const char *default_shell;
1985 if (shv && *shv->value)
1987 char *shell_path = recursively_expand (shv);
1989 if (shell_path && _is_unixy_shell (shell_path))
1994 default_shell = shell_path;
1997 #endif /* __MSDOS__ || __EMX__ */
2000 int old_builtin_rules_flag = no_builtin_rules_flag;
2001 int old_builtin_variables_flag = no_builtin_variables_flag;
2003 /* Decode switches again, for variables set by the makefile. */
2004 decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
2006 /* Clear GNUMAKEFLAGS to avoid duplication. */
2007 define_variable_cname ("GNUMAKEFLAGS", "", o_override, 0);
2009 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
2011 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
2014 /* Reset in case the switches changed our mind. */
2015 syncing = (output_sync == OUTPUT_SYNC_LINE
2016 || output_sync == OUTPUT_SYNC_TARGET);
2018 if (make_sync.syncout && ! syncing)
2019 output_close (&make_sync);
2021 make_sync.syncout = syncing;
2022 OUTPUT_SET (&make_sync);
2024 /* If we've disabled builtin rules, get rid of them. */
2025 if (no_builtin_rules_flag && ! old_builtin_rules_flag)
2027 if (suffix_file->builtin)
2029 free_dep_chain (suffix_file->deps);
2030 suffix_file->deps = 0;
2032 define_variable_cname ("SUFFIXES", "", o_default, 0);
2035 /* If we've disabled builtin variables, get rid of them. */
2036 if (no_builtin_variables_flag && ! old_builtin_variables_flag)
2037 undefine_default_variables ();
2040 #if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
2041 if (arg_job_slots != 1
2043 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
2048 _("Parallel jobs (-j) are not supported on this platform."));
2049 O (error, NILF, _("Resetting to single job (-j1) mode."));
2050 arg_job_slots = job_slots = 1;
2054 /* If we have >1 slot at this point, then we're a top-level make.
2055 Set up the jobserver.
2057 Every make assumes that it always has one job it can run. For the
2058 submakes it's the token they were given by their parent. For the top
2059 make, we just subtract one from the number the user wants. */
2061 if (job_slots > 1 && jobserver_setup (job_slots - 1))
2063 /* Fill in the jobserver_auth for our children. */
2064 jobserver_auth = jobserver_get_auth ();
2068 /* We're using the jobserver so set job_slots to 0. */
2069 master_job_slots = job_slots;
2074 /* If we're not using parallel jobs, then we don't need output sync.
2075 This is so people can enable output sync in GNUMAKEFLAGS or similar, but
2076 not have it take effect unless parallel builds are enabled. */
2077 if (syncing && job_slots == 1)
2080 output_close (&make_sync);
2082 output_sync = OUTPUT_SYNC_NONE;
2085 #ifndef MAKE_SYMLINKS
2086 if (check_symlink_flag)
2088 O (error, NILF, _("Symbolic links not supported: disabling -L."));
2089 check_symlink_flag = 0;
2093 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
2095 define_makeflags (1, 0);
2097 /* Make each 'struct goaldep' point at the 'struct file' for the file
2098 depended on. Also do magic for special targets. */
2102 /* Convert old-style suffix rules to pattern rules. It is important to
2103 do this before installing the built-in pattern rules below, so that
2104 makefile-specified suffix rules take precedence over built-in pattern
2107 convert_to_pattern ();
2109 /* Install the default implicit pattern rules.
2110 This used to be done before reading the makefiles.
2111 But in that case, built-in pattern rules were in the chain
2112 before user-defined ones, so they matched first. */
2114 install_default_implicit_rules ();
2116 /* Compute implicit rule limits. */
2118 count_implicit_rule_limits ();
2120 /* Construct the listings of directories in VPATH lists. */
2122 build_vpath_lists ();
2124 /* Mark files given with -o flags as very old and as having been updated
2125 already, and files given with -W flags as brand new (time-stamp as far
2126 as possible into the future). If restarts is set we'll do -W later. */
2131 for (p = old_files->list; *p != 0; ++p)
2133 struct file *f = enter_file (*p);
2134 f->last_mtime = f->mtime_before_update = OLD_MTIME;
2136 f->update_status = us_success;
2137 f->command_state = cs_finished;
2141 if (!restarts && new_files != 0)
2144 for (p = new_files->list; *p != 0; ++p)
2146 struct file *f = enter_file (*p);
2147 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2151 /* Initialize the remote job module. */
2154 /* Dump any output we've collected. */
2157 output_close (&make_sync);
2159 if (read_files != 0)
2161 /* Update any makefiles if necessary. */
2163 FILE_TIMESTAMP *makefile_mtimes = 0;
2164 unsigned int mm_idx = 0;
2165 char **aargv = NULL;
2168 enum update_status status;
2170 DB (DB_BASIC, (_("Updating makefiles....\n")));
2172 /* Remove any makefiles we don't want to try to update.
2173 Also record the current modtimes so we can compare them later. */
2175 register struct goaldep *d, *last;
2180 struct file *f = d->file;
2181 if (f->double_colon)
2182 for (f = f->double_colon; f != NULL; f = f->prev)
2184 if (f->deps == 0 && f->cmds != 0)
2186 /* This makefile is a :: target with commands, but
2187 no dependencies. So, it will always be remade.
2188 This might well cause an infinite loop, so don't
2189 try to remake it. (This will only happen if
2190 your makefiles are written exceptionally
2191 stupidly; but if you work for Athena, that's how
2192 you write your makefiles.) */
2195 (_("Makefile '%s' might loop; not remaking it.\n"),
2199 read_files = d->next;
2201 last->next = d->next;
2203 /* Free the storage. */
2206 d = last == 0 ? read_files : last->next;
2212 if (f == NULL || !f->double_colon)
2214 makefile_mtimes = xrealloc (makefile_mtimes,
2216 * sizeof (FILE_TIMESTAMP));
2217 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
2224 /* Set up 'MAKEFLAGS' specially while remaking makefiles. */
2225 define_makeflags (1, 1);
2228 int orig_db_level = db_level;
2230 if (! ISDB (DB_MAKEFILES))
2233 rebuilding_makefiles = 1;
2234 status = update_goal_chain (read_files);
2235 rebuilding_makefiles = 0;
2237 db_level = orig_db_level;
2243 /* The only way this can happen is if the user specified -q and asked
2244 for one of the makefiles to be remade as a target on the command
2245 line. Since we're not actually updating anything with -q we can
2246 treat this as "did nothing". */
2253 /* Failed to update. Figure out if we care. */
2255 /* Nonzero if any makefile was successfully remade. */
2257 /* Nonzero if any makefile we care about failed
2258 in updating or could not be found at all. */
2263 for (i = 0, d = read_files; d != 0; ++i, d = d->next)
2265 if (d->file->updated)
2267 /* This makefile was updated. */
2268 if (d->file->update_status == us_success)
2270 /* It was successfully updated. */
2271 any_remade |= (file_mtime_no_search (d->file)
2272 != makefile_mtimes[i]);
2274 else if (! (d->flags & RM_DONTCARE))
2276 FILE_TIMESTAMP mtime;
2277 /* The update failed and this makefile was not
2278 from the MAKEFILES variable, so we care. */
2279 OS (error, NILF, _("Failed to remake makefile '%s'."),
2281 mtime = file_mtime_no_search (d->file);
2282 any_remade |= (mtime != NONEXISTENT_MTIME
2283 && mtime != makefile_mtimes[i]);
2284 makefile_status = MAKE_FAILURE;
2288 /* This makefile was not found at all. */
2289 if (! (d->flags & RM_DONTCARE))
2291 const char *dnm = dep_name (d);
2292 size_t l = strlen (dnm);
2294 /* This is a makefile we care about. See how much. */
2295 if (d->flags & RM_INCLUDED)
2296 /* An included makefile. We don't need to die, but we
2297 do want to complain. */
2299 _("Included makefile '%s' was not found."), dnm);
2302 /* A normal makefile. We must die later. */
2304 _("Makefile '%s' was not found"), dnm);
2309 /* Reset this to empty so we get the right error message below. */
2321 /* Updated successfully. Re-exec ourselves. */
2323 remove_intermediates (0);
2325 if (print_data_base_flag)
2328 clean_jobserver (0);
2332 /* These names might have changed. */
2334 for (i = 1; i < argc; ++i)
2335 if (strneq (argv[i], "-f", 2)) /* XXX */
2337 if (argv[i][2] == '\0')
2338 /* This cast is OK since we never modify argv. */
2339 argv[++i] = (char *) makefiles->list[j];
2341 argv[i] = xstrdup (concat (2, "-f", makefiles->list[j]));
2346 /* Add -o option for the stdin temporary file, if necessary. */
2350 void *m = xmalloc ((nargc + 2) * sizeof (char *));
2352 memcpy (aargv, argv, argc * sizeof (char *));
2353 aargv[nargc++] = xstrdup (concat (2, "-o", stdin_nm));
2358 nargv = (const char**)argv;
2360 if (directories != 0 && directories->idx > 0)
2363 if (directory_before_chdir != 0)
2365 if (chdir (directory_before_chdir) < 0)
2366 perror_with_name ("chdir", "");
2372 _("Couldn't change back to original directory."));
2377 if (ISDB (DB_BASIC))
2380 printf (_("Re-executing[%u]:"), restarts);
2381 for (p = nargv; *p != 0; ++p)
2390 for (p = environ; *p != 0; ++p)
2392 if (strneq (*p, MAKELEVEL_NAME "=", MAKELEVEL_LENGTH+1))
2395 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2397 vms_putenv_symbol (*p);
2400 else if (strneq (*p, "MAKE_RESTARTS=", CSTRLEN ("MAKE_RESTARTS=")))
2403 sprintf (*p, "MAKE_RESTARTS=%s%u",
2404 OUTPUT_IS_TRACED () ? "-" : "", restarts);
2413 sprintf (buffer, "%u", makelevel);
2414 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2416 sprintf (buffer, "%s%u", OUTPUT_IS_TRACED () ? "-" : "", restarts);
2417 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2422 /* If we didn't set the restarts variable yet, add it. */
2425 char *b = alloca (40);
2426 sprintf (b, "MAKE_RESTARTS=%s%u",
2427 OUTPUT_IS_TRACED () ? "-" : "", restarts);
2435 exec_command (nargv);
2437 #elif defined (__EMX__)
2439 /* It is not possible to use execve() here because this
2440 would cause the parent process to be terminated with
2441 exit code 0 before the child process has been terminated.
2442 Therefore it may be the best solution simply to spawn the
2443 child process including all file handles and to wait for its
2447 pid = child_execute_job (NULL, 1, nargv, environ);
2449 /* is this loop really necessary? */
2453 /* use the exit code of the child process */
2454 exit (WIFEXITED(r) ? WEXITSTATUS(r) : EXIT_FAILURE);
2457 #ifdef SET_STACK_SIZE
2458 /* Reset limits, if necessary. */
2459 if (stack_limit.rlim_cur)
2460 setrlimit (RLIMIT_STACK, &stack_limit);
2462 exec_command ((char **)nargv, environ);
2468 /* Free the makefile mtimes. */
2469 free (makefile_mtimes);
2472 /* Set up 'MAKEFLAGS' again for the normal targets. */
2473 define_makeflags (1, 0);
2475 /* Set always_make_flag if -B was given. */
2476 always_make_flag = always_make_set;
2478 /* If restarts is set we haven't set up -W files yet, so do that now. */
2479 if (restarts && new_files != 0)
2482 for (p = new_files->list; *p != 0; ++p)
2484 struct file *f = enter_file (*p);
2485 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2489 /* If there is a temp file from reading a makefile from stdin, get rid of
2491 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
2492 perror_with_name (_("unlink (temporary file): "), stdin_nm);
2494 /* If there were no command-line goals, use the default. */
2499 if (default_goal_var->recursive)
2500 p = variable_expand (default_goal_var->value);
2503 p = variable_buffer_output (variable_buffer, default_goal_var->value,
2504 strlen (default_goal_var->value));
2506 p = variable_buffer;
2511 struct file *f = lookup_file (p);
2513 /* If .DEFAULT_GOAL is a non-existent target, enter it into the
2514 table and let the standard logic sort it out. */
2519 ns = PARSE_SIMPLE_SEQ (&p, struct nameseq);
2522 /* .DEFAULT_GOAL should contain one target. */
2525 _(".DEFAULT_GOAL contains more than one target"));
2527 f = enter_file (strcache_add (ns->name));
2529 ns->name = 0; /* It was reused by enter_file(). */
2536 goals = alloc_goaldep ();
2547 if (read_files == 0)
2548 O (fatal, NILF, _("No targets specified and no makefile found"));
2550 O (fatal, NILF, _("No targets"));
2553 /* Update the goals. */
2555 DB (DB_BASIC, (_("Updating goal targets....\n")));
2558 switch (update_goal_chain (goals))
2561 /* Nothing happened. */
2564 /* Keep the previous result. */
2567 /* We are under -q and would run some commands. */
2568 makefile_status = MAKE_TROUBLE;
2571 /* Updating failed. POSIX.2 specifies exit status >1 for this; */
2572 makefile_status = MAKE_FAILURE;
2576 /* If we detected some clock skew, generate one last warning */
2577 if (clock_skew_detected)
2579 _("warning: Clock skew detected. Your build may be incomplete."));
2582 die (makefile_status);
2586 exit (MAKE_SUCCESS);
2589 /* Parsing of arguments, decoding of switches. */
2591 static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
2592 static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
2593 (sizeof (long_option_aliases) /
2594 sizeof (long_option_aliases[0]))];
2596 /* Fill in the string and vector for getopt. */
2598 init_switches (void)
2604 if (options[0] != '\0')
2610 /* Return switch and non-switch args in order, regardless of
2611 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
2614 for (i = 0; switches[i].c != '\0'; ++i)
2616 long_options[i].name = (switches[i].long_name == 0 ? "" :
2617 switches[i].long_name);
2618 long_options[i].flag = 0;
2619 long_options[i].val = switches[i].c;
2620 if (short_option (switches[i].c))
2621 *p++ = switches[i].c;
2622 switch (switches[i].type)
2627 long_options[i].has_arg = no_argument;
2635 if (short_option (switches[i].c))
2637 if (switches[i].noarg_value != 0)
2639 if (short_option (switches[i].c))
2641 long_options[i].has_arg = optional_argument;
2644 long_options[i].has_arg = required_argument;
2649 for (c = 0; c < (sizeof (long_option_aliases) /
2650 sizeof (long_option_aliases[0]));
2652 long_options[i++] = long_option_aliases[c];
2653 long_options[i].name = 0;
2657 /* Non-option argument. It might be a variable definition. */
2659 handle_non_switch_argument (const char *arg, int env)
2663 if (arg[0] == '-' && arg[1] == '\0')
2664 /* Ignore plain '-' for compatibility. */
2669 /* VMS DCL quoting can result in foo="bar baz" showing up here.
2670 Need to remove the double quotes from the value. */
2673 eq_ptr = strchr (arg, '=');
2674 if ((eq_ptr != NULL) && (eq_ptr[1] == '"'))
2680 new_arg = alloca(len);
2681 seg1 = eq_ptr - arg + 1;
2682 strncpy(new_arg, arg, (seg1));
2683 seg2 = len - seg1 - 1;
2684 strncpy(&new_arg[seg1], &eq_ptr[2], seg2);
2685 new_arg[seg1 + seg2] = 0;
2686 if (new_arg[seg1 + seg2 - 1] == '"')
2687 new_arg[seg1 + seg2 - 1] = 0;
2692 v = try_variable_definition (0, arg, o_command, 0);
2695 /* It is indeed a variable definition. If we don't already have this
2696 one, record a pointer to the variable for later use in
2697 define_makeflags. */
2698 struct command_variable *cv;
2700 for (cv = command_variables; cv != 0; cv = cv->next)
2701 if (cv->variable == v)
2706 cv = xmalloc (sizeof (*cv));
2708 cv->next = command_variables;
2709 command_variables = cv;
2714 /* Not an option or variable definition; it must be a goal
2715 target! Enter it as a file and add it to the dep chain of
2717 struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
2722 goals = alloc_goaldep ();
2727 lastgoal->next = alloc_goaldep ();
2728 lastgoal = lastgoal->next;
2734 /* Add this target name to the MAKECMDGOALS variable. */
2735 struct variable *gv;
2738 gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
2743 /* Paste the old and new values together */
2744 unsigned int oldlen, newlen;
2747 oldlen = strlen (gv->value);
2748 newlen = strlen (f->name);
2749 vp = alloca (oldlen + 1 + newlen + 1);
2750 memcpy (vp, gv->value, oldlen);
2752 memcpy (&vp[oldlen + 1], f->name, newlen + 1);
2755 define_variable_cname ("MAKECMDGOALS", value, o_default, 0);
2760 /* Print a nice usage method. */
2763 print_usage (int bad)
2765 const char *const *cpp;
2768 if (print_version_flag)
2771 usageto = bad ? stderr : stdout;
2773 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
2775 for (cpp = usage; *cpp; ++cpp)
2776 fputs (_(*cpp), usageto);
2778 if (!remote_description || *remote_description == '\0')
2779 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
2781 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
2782 make_host, remote_description);
2784 fprintf (usageto, _("Report bugs to <bug-make@gnu.org>\n"));
2787 /* Decode switches from ARGC and ARGV.
2788 They came from the environment if ENV is nonzero. */
2791 decode_switches (int argc, const char **argv, int env)
2794 register const struct command_switch *cs;
2795 register struct stringlist *sl;
2798 /* getopt does most of the parsing for us.
2799 First, get its vectors set up. */
2803 /* Let getopt produce error messages for the command line,
2804 but not for options from the environment. */
2806 /* Reset getopt's state. */
2809 while (optind < argc)
2811 const char *coptarg;
2813 /* Parse the next argument. */
2814 c = getopt_long (argc, (char*const*)argv, options, long_options, NULL);
2817 /* End of arguments, or "--" marker seen. */
2820 /* An argument not starting with a dash. */
2821 handle_non_switch_argument (coptarg, env);
2823 /* Bad option. We will print a usage message and die later.
2824 But continue to parse the other options so the user can
2825 see all he did wrong. */
2828 for (cs = switches; cs->c != '\0'; ++cs)
2831 /* Whether or not we will actually do anything with
2832 this switch. We test this individually inside the
2833 switch below rather than just once outside it, so that
2834 options which are to be ignored still consume args. */
2835 int doit = !env || cs->env;
2848 *(int *) cs->value_ptr = cs->type == flag;
2858 coptarg = xstrdup (cs->noarg_value);
2859 else if (*coptarg == '\0')
2862 const char *op = opt;
2864 if (short_option (cs->c))
2869 error (NILF, strlen (op),
2870 _("the '%s%s' option requires a non-empty string argument"),
2871 short_option (cs->c) ? "-" : "--", op);
2876 if (cs->type == string)
2878 char **val = (char **)cs->value_ptr;
2880 *val = xstrdup (coptarg);
2884 sl = *(struct stringlist **) cs->value_ptr;
2887 sl = xmalloc (sizeof (struct stringlist));
2890 sl->list = xmalloc (5 * sizeof (char *));
2891 *(struct stringlist **) cs->value_ptr = sl;
2893 else if (sl->idx == sl->max - 1)
2896 /* MSVC erroneously warns without a cast here. */
2897 sl->list = xrealloc ((void *)sl->list,
2898 sl->max * sizeof (char *));
2900 if (cs->type == filename)
2901 sl->list[sl->idx++] = expand_command_line_file (coptarg);
2903 sl->list[sl->idx++] = xstrdup (coptarg);
2904 sl->list[sl->idx] = 0;
2908 /* See if we have an option argument; if we do require that
2909 it's all digits, not something like "10foo". */
2910 if (coptarg == 0 && argc > optind)
2913 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
2916 coptarg = argv[optind++];
2924 int i = atoi (coptarg);
2927 /* Yes, I realize we're repeating this in some cases. */
2928 for (cp = coptarg; ISDIGIT (cp[0]); ++cp)
2931 if (i < 1 || cp[0] != '\0')
2934 _("the '-%c' option requires a positive integer argument"),
2939 *(unsigned int *) cs->value_ptr = i;
2942 *(unsigned int *) cs->value_ptr
2943 = *(unsigned int *) cs->noarg_value;
2948 if (coptarg == 0 && optind < argc
2949 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
2950 coptarg = argv[optind++];
2953 *(double *) cs->value_ptr
2954 = (coptarg != 0 ? atof (coptarg)
2955 : *(double *) cs->noarg_value);
2961 /* We've found the switch. Stop looking. */
2966 /* There are no more options according to getting getopt, but there may
2967 be some arguments left. Since we have asked for non-option arguments
2968 to be returned in order, this only happens when there is a "--"
2969 argument to prevent later arguments from being options. */
2970 while (optind < argc)
2971 handle_non_switch_argument (argv[optind++], env);
2973 if (!env && (bad || print_usage_flag))
2976 die (bad ? MAKE_FAILURE : MAKE_SUCCESS);
2979 /* If there are any options that need to be decoded do it now. */
2980 decode_debug_flags ();
2981 decode_output_sync_flags ();
2984 /* Decode switches from environment variable ENVAR (which is LEN chars long).
2985 We do this by chopping the value into a vector of words, prepending a
2986 dash to the first word if it lacks one, and passing the vector to
2990 decode_env_switches (const char *envar, unsigned int len)
2992 char *varref = alloca (2 + len + 2);
2993 char *value, *p, *buf;
2997 /* Get the variable's value. */
3000 memcpy (&varref[2], envar, len);
3001 varref[2 + len] = ')';
3002 varref[2 + len + 1] = '\0';
3003 value = variable_expand (varref);
3005 /* Skip whitespace, and check for an empty value. */
3007 len = strlen (value);
3011 /* Allocate a vector that is definitely big enough. */
3012 argv = alloca ((1 + len + 1) * sizeof (char *));
3014 /* getopt will look at the arguments starting at ARGV[1].
3015 Prepend a spacer word. */
3019 /* We need a buffer to copy the value into while we split it into words
3020 and unquote it. Set up in case we need to prepend a dash later. */
3021 buf = alloca (1 + len + 1);
3025 while (*value != '\0')
3027 if (*value == '\\' && value[1] != '\0')
3028 ++value; /* Skip the backslash. */
3029 else if (ISBLANK (*value))
3031 /* End of the word. */
3036 while (ISBLANK (*value));
3043 assert (p < buf + len + 2);
3045 if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
3046 /* The first word doesn't start with a dash and isn't a variable
3047 definition, so add a dash. */
3050 /* Parse those words. */
3051 decode_switches (argc, argv, 1);
3054 /* Quote the string IN so that it will be interpreted as a single word with
3055 no magic by decode_env_switches; also double dollar signs to avoid
3056 variable expansion in make itself. Write the result into OUT, returning
3057 the address of the next character to be written.
3058 Allocating space for OUT twice the length of IN is always sufficient. */
3061 quote_for_env (char *out, const char *in)
3067 else if (ISBLANK (*in) || *in == '\\')
3075 /* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
3076 command switches. Include options with args if ALL is nonzero.
3077 Don't include options with the 'no_makefile' flag set if MAKEFILE. */
3079 static struct variable *
3080 define_makeflags (int all, int makefile)
3082 const char ref[] = "$(MAKEOVERRIDES)";
3083 const char posixref[] = "$(-*-command-variables-*-)";
3084 const char evalref[] = "$(-*-eval-flags-*-)";
3085 const struct command_switch *cs;
3089 /* We will construct a linked list of 'struct flag's describing
3090 all the flags which need to go in MAKEFLAGS. Then, once we
3091 know how many there are and their lengths, we can put them all
3092 together in a string. */
3097 const struct command_switch *cs;
3100 struct flag *flags = 0;
3101 struct flag *last = 0;
3102 unsigned int flagslen = 0;
3103 #define ADD_FLAG(ARG, LEN) \
3105 struct flag *new = alloca (sizeof (struct flag)); \
3114 if (new->arg == 0) \
3115 /* Just a single flag letter: " -x" */ \
3118 /* " -xfoo", plus space to escape "foo". */ \
3119 flagslen += 1 + 1 + 1 + (3 * (LEN)); \
3120 if (!short_option (cs->c)) \
3121 /* This switch has no single-letter version, so we use the long. */ \
3122 flagslen += 2 + strlen (cs->long_name); \
3125 for (cs = switches; cs->c != '\0'; ++cs)
3126 if (cs->toenv && (!makefile || !cs->no_makefile))
3134 if ((!*(int *) cs->value_ptr) == (cs->type == flag_off)
3135 && (cs->default_value == 0
3136 || *(int *) cs->value_ptr != *(int *) cs->default_value))
3143 if ((cs->default_value != 0
3144 && (*(unsigned int *) cs->value_ptr
3145 == *(unsigned int *) cs->default_value)))
3147 else if (cs->noarg_value != 0
3148 && (*(unsigned int *) cs->value_ptr ==
3149 *(unsigned int *) cs->noarg_value))
3150 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3153 char *buf = alloca (30);
3154 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3155 ADD_FLAG (buf, strlen (buf));
3164 if (cs->default_value != 0
3165 && (*(double *) cs->value_ptr
3166 == *(double *) cs->default_value))
3168 else if (cs->noarg_value != 0
3169 && (*(double *) cs->value_ptr
3170 == *(double *) cs->noarg_value))
3171 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3174 char *buf = alloca (100);
3175 sprintf (buf, "%g", *(double *) cs->value_ptr);
3176 ADD_FLAG (buf, strlen (buf));
3185 p = *((char **)cs->value_ptr);
3187 ADD_FLAG (p, strlen (p));
3195 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3199 for (i = 0; i < sl->idx; ++i)
3200 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
3211 /* Four more for the possible " -- ", plus variable references. */
3212 flagslen += 4 + CSTRLEN (posixref) + 1 + CSTRLEN (evalref) + 1;
3214 /* Construct the value in FLAGSTRING.
3215 We allocate enough space for a preceding dash and trailing null. */
3216 flagstring = alloca (1 + flagslen + 1);
3217 memset (flagstring, '\0', 1 + flagslen + 1);
3220 /* Start with a dash, for MFLAGS. */
3223 /* Add simple options as a group. */
3224 while (flags != 0 && !flags->arg && short_option (flags->cs->c))
3226 *p++ = flags->cs->c;
3227 flags = flags->next;
3230 /* Now add more complex flags: ones with options and/or long names. */
3236 /* Add the flag letter or name to the string. */
3237 if (short_option (flags->cs->c))
3238 *p++ = flags->cs->c;
3241 /* Long options require a double-dash. */
3243 strcpy (p, flags->cs->long_name);
3246 /* An omitted optional argument has an ARG of "". */
3247 if (flags->arg && flags->arg[0] != '\0')
3249 if (!short_option (flags->cs->c))
3250 /* Long options require '='. */
3252 p = quote_for_env (p, flags->arg);
3254 flags = flags->next;
3257 /* If no flags at all, get rid of the initial dash. */
3258 if (p == &flagstring[1])
3260 flagstring[0] = '\0';
3264 /* Define MFLAGS before appending variable definitions. Omit an initial
3265 empty dash. Since MFLAGS is not parsed for flags, there is no reason to
3266 override any makefile redefinition. */
3267 define_variable_cname ("MFLAGS",
3268 flagstring + (flagstring[0] == '-' && flagstring[1] == ' ' ? 2 : 0),
3271 /* Write a reference to -*-eval-flags-*-, which contains all the --eval
3276 memcpy (p, evalref, CSTRLEN (evalref));
3277 p += CSTRLEN (evalref);
3280 if (all && command_variables)
3282 /* Write a reference to $(MAKEOVERRIDES), which contains all the
3283 command-line variable definitions. Separate the variables from the
3284 switches with a "--" arg. */
3289 /* Copy in the string. */
3292 memcpy (p, posixref, CSTRLEN (posixref));
3293 p += CSTRLEN (posixref);
3297 memcpy (p, ref, CSTRLEN (ref));
3302 /* If there is a leading dash, omit it. */
3303 if (flagstring[0] == '-')
3306 /* This used to use o_env, but that lost when a makefile defined MAKEFLAGS.
3307 Makefiles set MAKEFLAGS to add switches, but we still want to redefine
3308 its value with the full set of switches. Then we used o_file, but that
3309 lost when users added -e, causing a previous MAKEFLAGS env. var. to take
3310 precedence over the new one. Of course, an override or command
3311 definition will still take precedence. */
3312 return define_variable_cname ("MAKEFLAGS", flagstring,
3313 env_overrides ? o_env_override : o_file, 1);
3316 /* Print version information. */
3319 print_version (void)
3321 static int printed_version = 0;
3323 const char *precede = print_data_base_flag ? "# " : "";
3325 if (printed_version)
3326 /* Do it only once. */
3329 printf ("%sGNU Make %s\n", precede, version_string);
3331 if (!remote_description || *remote_description == '\0')
3332 printf (_("%sBuilt for %s\n"), precede, make_host);
3334 printf (_("%sBuilt for %s (%s)\n"),
3335 precede, make_host, remote_description);
3337 /* Print this untranslated. The coding standards recommend translating the
3338 (C) to the copyright symbol, but this string is going to change every
3339 year, and none of the rest of it should be translated (including the
3340 word "Copyright"), so it hardly seems worth it. */
3342 printf ("%sCopyright (C) 1988-2016 Free Software Foundation, Inc.\n",
3345 printf (_("%sLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
3346 %sThis is free software: you are free to change and redistribute it.\n\
3347 %sThere is NO WARRANTY, to the extent permitted by law.\n"),
3348 precede, precede, precede);
3350 printed_version = 1;
3352 /* Flush stdout so the user doesn't have to wait to see the
3353 version information while make thinks about things. */
3357 /* Print a bunch of information about this and that. */
3360 print_data_base (void)
3362 time_t when = time ((time_t *) 0);
3366 printf (_("\n# Make data base, printed on %s"), ctime (&when));
3368 print_variable_data_base ();
3369 print_dir_data_base ();
3370 print_rule_data_base ();
3371 print_file_data_base ();
3372 print_vpath_data_base ();
3373 strcache_print_stats ("#");
3375 when = time ((time_t *) 0);
3376 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
3380 clean_jobserver (int status)
3382 /* Sanity: have we written all our jobserver tokens back? If our
3383 exit status is 2 that means some kind of syntax error; we might not
3384 have written all our tokens so do that now. If tokens are left
3385 after any other error code, that's bad. */
3387 if (jobserver_enabled() && jobserver_tokens)
3391 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3394 /* Don't write back the "free" token */
3395 while (--jobserver_tokens)
3396 jobserver_release (0);
3400 /* Sanity: If we're the master, were all the tokens written back? */
3402 if (master_job_slots)
3404 /* We didn't write one for ourself, so start at 1. */
3405 unsigned int tokens = 1 + jobserver_acquire_all ();
3407 if (tokens != master_job_slots)
3409 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3410 tokens, master_job_slots);
3416 /* Exit with STATUS, cleaning up as necessary. */
3421 static char dying = 0;
3429 if (print_version_flag)
3432 /* Wait for children to die. */
3433 err = (status != 0);
3434 while (job_slots_used > 0)
3435 reap_children (1, err);
3437 /* Let the remote job module clean up its state. */
3440 /* Remove the intermediate files. */
3441 remove_intermediates (0);
3443 if (print_data_base_flag)
3447 verify_file_data_base ();
3449 clean_jobserver (status);
3453 /* die() might be called in a recipe output context due to an
3454 $(error ...) function. */
3455 output_close (output_context);
3457 if (output_context != &make_sync)
3458 output_close (&make_sync);
3463 output_close (NULL);
3465 /* Try to move back to the original directory. This is essential on
3466 MS-DOS (where there is really only one process), and on Unix it
3467 puts core files in the original directory instead of the -C
3468 directory. Must wait until after remove_intermediates(), or unlinks
3469 of relative pathnames fail. */
3470 if (directory_before_chdir != 0)
3472 /* If it fails we don't care: shut up GCC. */
3474 _x = chdir (directory_before_chdir);