1 /* Argument parsing and main program of GNU Make.
2 Copyright (C) 1988-2013 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/>. */
30 # include <proto/dos.h>
35 # include "pathstuff.h"
36 # include "sub_proc.h"
40 # include <sys/types.h>
41 # include <sys/wait.h>
48 int __stack = 20000; /* Make sure we have 20K of stack space */
52 void remote_setup (void);
53 void remote_cleanup (void);
54 RETSIGTYPE fatal_error_signal (int sig);
56 void print_variable_data_base (void);
57 void print_dir_data_base (void);
58 void print_rule_data_base (void);
59 void print_vpath_data_base (void);
61 void verify_file_data_base (void);
63 #if defined HAVE_WAITPID || defined HAVE_WAIT3
64 # define HAVE_WAIT_NOHANG
71 # ifndef sun /* Sun has an incorrect decl in a header. */
72 void exit (int) __attribute__ ((noreturn));
77 static void clean_jobserver (int status);
78 static void print_data_base (void);
79 static void print_version (void);
80 static void decode_switches (int argc, char **argv, int env);
81 static void decode_env_switches (char *envar, unsigned int len);
82 static struct variable *define_makeflags (int all, int makefile);
83 static char *quote_for_env (char *out, const char *in);
84 static void initialize_global_hash_tables (void);
87 /* The structure that describes an accepted command switch. */
91 int c; /* The switch character. */
93 enum /* Type of the value. */
95 flag, /* Turn int flag on. */
96 flag_off, /* Turn int flag off. */
97 string, /* One string per switch. */
98 filename, /* A string containing a file name. */
99 positive_int, /* A positive integer. */
100 floating, /* A floating-point number (double). */
101 ignore /* Ignored. */
104 void *value_ptr; /* Pointer to the value-holding variable. */
106 unsigned int env:1; /* Can come from MAKEFLAGS. */
107 unsigned int toenv:1; /* Should be put in MAKEFLAGS. */
108 unsigned int no_makefile:1; /* Don't propagate when remaking makefiles. */
110 const void *noarg_value; /* Pointer to value used if no arg given. */
111 const void *default_value; /* Pointer to default value. */
113 char *long_name; /* Long option name. */
116 /* True if C is a switch value that corresponds to a short option. */
118 #define short_option(c) ((c) <= CHAR_MAX)
120 /* The structure used to hold the list of strings given
121 in command switches of a type that takes string arguments. */
125 const char **list; /* Nil-terminated list of strings. */
126 unsigned int idx; /* Index into above. */
127 unsigned int max; /* Number of pointers allocated. */
131 /* The recognized command switches. */
133 /* Nonzero means do extra verification (that may slow things down). */
137 /* Nonzero means do not print commands to be executed (-s). */
141 /* Nonzero means just touch the files
142 that would appear to need remaking (-t) */
146 /* Nonzero means just print what commands would need to be executed,
147 don't actually execute them (-n). */
151 /* Print debugging info (--debug). */
153 static struct stringlist *db_flags = 0;
154 static int debug_flag = 0;
158 /* Synchronize output (--output-sync). */
160 static struct stringlist *output_sync_option = 0;
163 /* Suspend make in main for a short time to allow debugger to attach */
165 int suspend_flag = 0;
168 /* Environment variables override makefile definitions. */
170 int env_overrides = 0;
172 /* Nonzero means ignore status codes returned by commands
173 executed to remake files. Just treat them all as successful (-i). */
175 int ignore_errors_flag = 0;
177 /* Nonzero means don't remake anything, just print the data base
178 that results from reading the makefile (-p). */
180 int print_data_base_flag = 0;
182 /* Nonzero means don't remake anything; just return a nonzero status
183 if the specified targets are not up to date (-q). */
185 int question_flag = 0;
187 /* Nonzero means do not use any of the builtin rules (-r) / variables (-R). */
189 int no_builtin_rules_flag = 0;
190 int no_builtin_variables_flag = 0;
192 /* Nonzero means keep going even if remaking some file fails (-k). */
195 int default_keep_going_flag = 0;
197 /* Nonzero means check symlink mtimes. */
199 int check_symlink_flag = 0;
201 /* Nonzero means print directory before starting and when done (-w). */
203 int print_directory_flag = 0;
205 /* Nonzero means ignore print_directory_flag and never print the directory.
206 This is necessary because print_directory_flag is set implicitly. */
208 int inhibit_print_directory_flag = 0;
210 /* Nonzero means print version information. */
212 int print_version_flag = 0;
214 /* List of makefiles given with -f switches. */
216 static struct stringlist *makefiles = 0;
218 /* Size of the stack when we started. */
220 #ifdef SET_STACK_SIZE
221 struct rlimit stack_limit;
225 /* Number of job slots (commands that can be run at once). */
227 unsigned int job_slots = 1;
228 unsigned int default_job_slots = 1;
229 static unsigned int master_job_slots = 0;
231 /* Value of job_slots that means no limit. */
233 static unsigned int inf_jobs = 0;
235 /* File descriptors for the jobs pipe. */
237 static struct stringlist *jobserver_fds = 0;
239 int job_fds[2] = { -1, -1 };
242 /* Handle for the mutex used on Windows to synchronize output of our
243 children under -O. */
245 static struct stringlist *sync_mutex = 0;
247 /* Maximum load average at which multiple jobs will be run.
248 Negative values mean unlimited, while zero means limit to
249 zero load (which could be useful to start infinite jobs remotely
250 but one at a time locally). */
252 double max_load_average = -1.0;
253 double default_load_average = -1.0;
255 int max_load_average = -1;
256 int default_load_average = -1;
259 /* List of directories given with -C switches. */
261 static struct stringlist *directories = 0;
263 /* List of include directories given with -I switches. */
265 static struct stringlist *include_directories = 0;
267 /* List of files given with -o switches. */
269 static struct stringlist *old_files = 0;
271 /* List of files given with -W switches. */
273 static struct stringlist *new_files = 0;
275 /* List of strings to be eval'd. */
276 static struct stringlist *eval_strings = 0;
278 /* If nonzero, we should just print usage and exit. */
280 static int print_usage_flag = 0;
282 /* If nonzero, we should print a warning message
283 for each reference to an undefined variable. */
285 int warn_undefined_variables_flag;
287 /* If nonzero, always build all targets, regardless of whether
288 they appear out of date or not. */
290 static int always_make_set = 0;
291 int always_make_flag = 0;
293 /* If nonzero, we're in the "try to rebuild makefiles" phase. */
295 int rebuilding_makefiles = 0;
297 /* Remember the original value of the SHELL variable, from the environment. */
299 struct variable shell_var;
301 /* This character introduces a command: it's the first char on the line. */
303 char cmd_prefix = '\t';
306 /* The usage output. We write it this way to make life easier for the
307 translators, especially those trying to translate to right-to-left
308 languages like Hebrew. */
310 static const char *const usage[] =
314 -b, -m Ignored for compatibility.\n"),
316 -B, --always-make Unconditionally make all targets.\n"),
318 -C DIRECTORY, --directory=DIRECTORY\n\
319 Change to DIRECTORY before doing anything.\n"),
321 -d Print lots of debugging information.\n"),
323 --debug[=FLAGS] Print various types of debugging information.\n"),
325 -e, --environment-overrides\n\
326 Environment variables override makefiles.\n"),
328 --eval=STRING Evaluate STRING as a makefile statement.\n"),
330 -f FILE, --file=FILE, --makefile=FILE\n\
331 Read FILE as a makefile.\n"),
333 -h, --help Print this message and exit.\n"),
335 -i, --ignore-errors Ignore errors from recipes.\n"),
337 -I DIRECTORY, --include-dir=DIRECTORY\n\
338 Search DIRECTORY for included makefiles.\n"),
340 -j [N], --jobs[=N] Allow N jobs at once; infinite jobs with no arg.\n"),
342 -k, --keep-going Keep going when some targets can't be made.\n"),
344 -l [N], --load-average[=N], --max-load[=N]\n\
345 Don't start multiple jobs unless load is below N.\n"),
347 -L, --check-symlink-times Use the latest mtime between symlinks and target.\n"),
349 -n, --just-print, --dry-run, --recon\n\
350 Don't actually run any recipe; just print them.\n"),
352 -o FILE, --old-file=FILE, --assume-old=FILE\n\
353 Consider FILE to be very old and don't remake it.\n"),
355 -O[TYPE], --output-sync[=TYPE]\n\
356 Synchronize output of parallel jobs by TYPE.\n"),
358 -p, --print-data-base Print make's internal database.\n"),
360 -q, --question Run no recipe; exit status says if up to date.\n"),
362 -r, --no-builtin-rules Disable the built-in implicit rules.\n"),
364 -R, --no-builtin-variables Disable the built-in variable settings.\n"),
366 -s, --silent, --quiet Don't echo recipes.\n"),
368 -S, --no-keep-going, --stop\n\
371 -t, --touch Touch targets instead of remaking them.\n"),
373 --trace Print tracing information.\n"),
375 -v, --version Print the version number of make and exit.\n"),
377 -w, --print-directory Print the current directory.\n"),
379 --no-print-directory Turn off -w, even if it was turned on implicitly.\n"),
381 -W FILE, --what-if=FILE, --new-file=FILE, --assume-new=FILE\n\
382 Consider FILE to be infinitely new.\n"),
384 --warn-undefined-variables Warn when an undefined variable is referenced.\n"),
388 /* The table of command switches.
389 Order matters here: this is the order MAKEFLAGS will be constructed.
390 So be sure all simple flags (single char, no argument) come first. */
392 static const struct command_switch switches[] =
394 { 'b', ignore, 0, 0, 0, 0, 0, 0, 0 },
395 { 'B', flag, &always_make_set, 1, 1, 0, 0, 0, "always-make" },
396 { 'd', flag, &debug_flag, 1, 1, 0, 0, 0, 0 },
398 { 'D', flag, &suspend_flag, 1, 1, 0, 0, 0, "suspend-for-debug" },
400 { 'e', flag, &env_overrides, 1, 1, 0, 0, 0, "environment-overrides", },
401 { 'h', flag, &print_usage_flag, 0, 0, 0, 0, 0, "help" },
402 { 'i', flag, &ignore_errors_flag, 1, 1, 0, 0, 0, "ignore-errors" },
403 { 'k', flag, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
405 { 'L', flag, &check_symlink_flag, 1, 1, 0, 0, 0, "check-symlink-times" },
406 { 'm', ignore, 0, 0, 0, 0, 0, 0, 0 },
407 { 'n', flag, &just_print_flag, 1, 1, 1, 0, 0, "just-print" },
408 { 'p', flag, &print_data_base_flag, 1, 1, 0, 0, 0, "print-data-base" },
409 { 'q', flag, &question_flag, 1, 1, 1, 0, 0, "question" },
410 { 'r', flag, &no_builtin_rules_flag, 1, 1, 0, 0, 0, "no-builtin-rules" },
411 { 'R', flag, &no_builtin_variables_flag, 1, 1, 0, 0, 0,
412 "no-builtin-variables" },
413 { 's', flag, &silent_flag, 1, 1, 0, 0, 0, "silent" },
414 { 'S', flag_off, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
416 { 't', flag, &touch_flag, 1, 1, 1, 0, 0, "touch" },
417 { 'v', flag, &print_version_flag, 1, 1, 0, 0, 0, "version" },
418 { 'w', flag, &print_directory_flag, 1, 1, 0, 0, 0, "print-directory" },
420 /* These options take arguments. */
421 { 'C', filename, &directories, 0, 0, 0, 0, 0, "directory" },
422 { 'f', filename, &makefiles, 0, 0, 0, 0, 0, "file" },
423 { 'I', filename, &include_directories, 1, 1, 0, 0, 0,
425 { 'j', positive_int, &job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,
428 { 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,
429 &default_load_average, "load-average" },
431 { 'l', positive_int, &max_load_average, 1, 1, 0, &default_load_average,
432 &default_load_average, "load-average" },
434 { 'o', filename, &old_files, 0, 0, 0, 0, 0, "old-file" },
435 { 'O', string, &output_sync_option, 1, 1, 0, "target", 0, "output-sync" },
436 { 'W', filename, &new_files, 0, 0, 0, 0, 0, "what-if" },
438 /* These are long-style options. */
439 { CHAR_MAX+1, string, &db_flags, 1, 1, 0, "basic", 0, "debug" },
440 { CHAR_MAX+2, string, &jobserver_fds, 1, 1, 0, 0, 0, "jobserver-fds" },
441 { CHAR_MAX+3, flag, &trace_flag, 1, 1, 0, 0, 0, "trace" },
442 { CHAR_MAX+4, flag, &inhibit_print_directory_flag, 1, 1, 0, 0, 0,
443 "no-print-directory" },
444 { CHAR_MAX+5, flag, &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
445 "warn-undefined-variables" },
446 { CHAR_MAX+6, string, &eval_strings, 1, 0, 0, 0, 0, "eval" },
447 { CHAR_MAX+7, string, &sync_mutex, 1, 1, 0, 0, 0, "sync-mutex" },
448 { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
451 /* Secondary long names for options. */
453 static struct option long_option_aliases[] =
455 { "quiet", no_argument, 0, 's' },
456 { "stop", no_argument, 0, 'S' },
457 { "new-file", required_argument, 0, 'W' },
458 { "assume-new", required_argument, 0, 'W' },
459 { "assume-old", required_argument, 0, 'o' },
460 { "max-load", optional_argument, 0, 'l' },
461 { "dry-run", no_argument, 0, 'n' },
462 { "recon", no_argument, 0, 'n' },
463 { "makefile", required_argument, 0, 'f' },
466 /* List of goal targets. */
468 static struct dep *goals, *lastgoal;
470 /* List of variables which were defined on the command line
471 (or, equivalently, in MAKEFLAGS). */
473 struct command_variable
475 struct command_variable *next;
476 struct variable *variable;
478 static struct command_variable *command_variables;
480 /* The name we were invoked with. */
484 /* Our current directory before processing any -C options. */
486 char *directory_before_chdir;
488 /* Our current directory after processing all -C options. */
490 char *starting_directory;
492 /* Value of the MAKELEVEL variable at startup (or 0). */
494 unsigned int makelevel;
496 /* Pointer to the value of the .DEFAULT_GOAL special variable.
497 The value will be the name of the goal to remake if the command line
498 does not override it. It can be set by the makefile, or else it's
499 the first target defined in the makefile whose name does not start
502 struct variable * default_goal_var;
504 /* Pointer to structure for the file .DEFAULT
505 whose commands are used for any file that has none of its own.
506 This is zero if the makefiles do not define .DEFAULT. */
508 struct file *default_file;
510 /* Nonzero if we have seen the magic '.POSIX' target.
511 This turns on pedantic compliance with POSIX.2. */
515 /* Nonzero if we have seen the '.SECONDEXPANSION' target.
516 This turns on secondary expansion of prerequisites. */
518 int second_expansion;
520 /* Nonzero if we have seen the '.ONESHELL' target.
521 This causes the entire recipe to be handed to SHELL
522 as a single string, potentially containing newlines. */
526 /* One of OUTPUT_SYNC_* if the "--output-sync" option was given. This
527 attempts to synchronize the output of parallel jobs such that the results
528 of each job stay together. */
530 int output_sync = OUTPUT_SYNC_NONE;
532 /* Nonzero if the "--trace" option was given. */
536 /* Nonzero if we have seen the '.NOTPARALLEL' target.
537 This turns off parallel builds for this invocation of make. */
541 /* Nonzero if some rule detected clock skew; we keep track so (a) we only
542 print one warning about it during the run, and (b) we can print a final
543 warning at the end of the run. */
545 int clock_skew_detected;
547 /* Map of possible stop characters for searching strings. */
549 # define UCHAR_MAX 255
551 unsigned short stopchar_map[UCHAR_MAX + 1] = {0};
553 /* If output-sync is enabled we'll collect all the output generated due to
554 options, while reading makefiles, etc. */
556 struct output make_sync;
559 /* Mask of signals that are being caught with fatal_error_signal. */
562 sigset_t fatal_signal_set;
564 # ifdef HAVE_SIGSETMASK
565 int fatal_signal_mask;
569 #if !HAVE_DECL_BSD_SIGNAL && !defined bsd_signal
570 # if !defined HAVE_SIGACTION
571 # define bsd_signal signal
573 typedef RETSIGTYPE (*bsd_signal_ret_t) (int);
575 static bsd_signal_ret_t
576 bsd_signal (int sig, bsd_signal_ret_t func)
578 struct sigaction act, oact;
579 act.sa_handler = func;
580 act.sa_flags = SA_RESTART;
581 sigemptyset (&act.sa_mask);
582 sigaddset (&act.sa_mask, sig);
583 if (sigaction (sig, &act, &oact) != 0)
585 return oact.sa_handler;
591 initialize_global_hash_tables (void)
593 init_hash_global_variable_set ();
596 hash_init_directories ();
597 hash_init_function_table ();
600 /* This character map locate stop chars when parsing GNU makefiles.
601 Each element is true if we should stop parsing on that character. */
604 initialize_stopchar_map ()
608 stopchar_map[(int)'\0'] = MAP_NUL;
609 stopchar_map[(int)'#'] = MAP_COMMENT;
610 stopchar_map[(int)';'] = MAP_SEMI;
611 stopchar_map[(int)'='] = MAP_EQUALS;
612 stopchar_map[(int)':'] = MAP_COLON;
613 stopchar_map[(int)'%'] = MAP_PERCENT;
614 stopchar_map[(int)'|'] = MAP_PIPE;
615 stopchar_map[(int)'.'] = MAP_DOT | MAP_USERFUNC;
616 stopchar_map[(int)','] = MAP_COMMA;
617 stopchar_map[(int)'$'] = MAP_VARIABLE;
619 stopchar_map[(int)'-'] = MAP_USERFUNC;
620 stopchar_map[(int)'_'] = MAP_USERFUNC;
622 stopchar_map[(int)'/'] = MAP_PATHSEP;
624 stopchar_map[(int)']'] = MAP_PATHSEP;
625 #elif defined(HAVE_DOS_PATHS)
626 stopchar_map[(int)'\\'] = MAP_PATHSEP;
629 for (i = 1; i <= UCHAR_MAX; ++i)
632 stopchar_map[i] = MAP_BLANK;
634 stopchar_map[i] |= MAP_SPACE;
636 stopchar_map[i] = MAP_USERFUNC;
641 expand_command_line_file (char *name)
647 fatal (NILF, _("empty string invalid as file name"));
651 expanded = tilde_expand (name);
656 /* This is also done in parse_file_seq, so this is redundant
657 for names read from makefiles. It is here for names passed
658 on the command line. */
659 while (name[0] == '.' && name[1] == '/' && name[2] != '\0')
663 /* Skip following slashes: ".//foo" is "foo", not "/foo". */
669 /* It was all slashes! Move back to the dot and truncate
670 it after the first slash, so it becomes just "./". */
673 while (name[0] != '.');
677 cp = strcache_add (name);
685 /* Toggle -d on receipt of SIGUSR1. */
689 debug_signal_handler (int sig UNUSED)
691 db_level = db_level ? DB_NONE : DB_BASIC;
696 decode_debug_flags (void)
704 for (pp=db_flags->list; *pp; ++pp)
710 switch (tolower (p[0]))
716 db_level |= DB_BASIC;
719 db_level |= DB_BASIC | DB_IMPLICIT;
725 db_level |= DB_BASIC | DB_MAKEFILES;
731 db_level |= DB_BASIC | DB_VERBOSE;
734 fatal (NILF, _("unknown debug level specification '%s'"), p);
737 while (*(++p) != '\0')
738 if (*p == ',' || *p == ' ')
757 decode_output_sync_flags (void)
761 if (!output_sync_option)
764 for (pp=output_sync_option->list; *pp; ++pp)
768 if (streq (p, "none"))
769 output_sync = OUTPUT_SYNC_NONE;
770 else if (streq (p, "line"))
771 output_sync = OUTPUT_SYNC_LINE;
772 else if (streq (p, "target"))
773 output_sync = OUTPUT_SYNC_TARGET;
774 else if (streq (p, "recurse"))
775 output_sync = OUTPUT_SYNC_RECURSE;
777 fatal (NILF, _("unknown output-sync type '%s'"), p);
785 for (idx = 1; idx < sync_mutex->idx; idx++)
786 if (!streq (sync_mutex->list[0], sync_mutex->list[idx]))
787 fatal (NILF, _("internal error: multiple --sync-mutex options"));
789 /* Now parse the mutex handle string. */
790 mp = sync_mutex->list[0];
791 RECORD_SYNC_MUTEX (mp);
797 #ifndef NO_OUTPUT_SYNC
799 /* This is called from start_job_command when it detects that
800 output_sync option is in effect. The handle to the synchronization
801 mutex is passed, as a string, to sub-makes via the --sync-mutex
802 command-line argument. */
804 prepare_mutex_handle_string (sync_handle_t handle)
808 /* 2 hex digits per byte + 2 characters for "0x" + null. */
809 char hdl_string[2 * sizeof (sync_handle_t) + 2 + 1];
811 /* Prepare the mutex handle string for our children. */
812 sprintf (hdl_string, "0x%x", handle);
813 sync_mutex = xmalloc (sizeof (struct stringlist));
814 sync_mutex->list = xmalloc (sizeof (char *));
815 sync_mutex->list[0] = xstrdup (hdl_string);
818 define_makeflags (1, 0);
822 #endif /* NO_OUTPUT_SYNC */
825 * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
826 * exception and print it to stderr instead.
828 * If ! DB_VERBOSE, just print a simple message and exit.
829 * If DB_VERBOSE, print a more verbose message.
830 * If compiled for DEBUG, let exception pass through to GUI so that
831 * debuggers can attach.
834 handle_runtime_exceptions (struct _EXCEPTION_POINTERS *exinfo)
836 PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
837 LPSTR cmdline = GetCommandLine ();
838 LPSTR prg = strtok (cmdline, " ");
842 LPTSTR lpszStrings[1];
845 if (! ISDB (DB_VERBOSE))
848 _("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\n"),
849 prg, exrec->ExceptionCode, exrec->ExceptionAddress);
850 fprintf (stderr, errmsg);
855 _("\nUnhandled exception filter called from program %s\nExceptionCode = %lx\nExceptionFlags = %lx\nExceptionAddress = 0x%p\n"),
856 prg, exrec->ExceptionCode, exrec->ExceptionFlags,
857 exrec->ExceptionAddress);
859 if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
860 && exrec->NumberParameters >= 2)
861 sprintf (&errmsg[strlen(errmsg)],
862 (exrec->ExceptionInformation[0]
863 ? _("Access violation: write operation at address 0x%p\n")
864 : _("Access violation: read operation at address 0x%p\n")),
865 (PVOID)exrec->ExceptionInformation[1]);
867 /* turn this on if we want to put stuff in the event log too */
869 hEventSource = RegisterEventSource (NULL, "GNU Make");
870 lpszStrings[0] = errmsg;
872 if (hEventSource != NULL)
874 ReportEvent (hEventSource, /* handle of event source */
875 EVENTLOG_ERROR_TYPE, /* event type */
876 0, /* event category */
878 NULL, /* current user's SID */
879 1, /* strings in lpszStrings */
880 0, /* no bytes of raw data */
881 lpszStrings, /* array of error strings */
882 NULL); /* no raw data */
884 (VOID) DeregisterEventSource (hEventSource);
888 /* Write the error to stderr too */
889 fprintf (stderr, errmsg);
892 return EXCEPTION_CONTINUE_SEARCH;
895 return (255); /* not reached */
900 * On WIN32 systems we don't have the luxury of a /bin directory that
901 * is mapped globally to every drive mounted to the system. Since make could
902 * be invoked from any drive, and we don't want to propagate /bin/sh
903 * to every single drive. Allow ourselves a chance to search for
904 * a value for default shell here (if the default path does not exist).
908 find_and_set_default_shell (const char *token)
915 extern char *default_shell;
918 search_token = default_shell;
920 atoken = search_token = xstrdup (token);
922 /* If the user explicitly requests the DOS cmd shell, obey that request.
923 However, make sure that's what they really want by requiring the value
924 of SHELL either equal, or have a final path element of, "cmd" or
925 "cmd.exe" case-insensitive. */
926 tokend = search_token + strlen (search_token) - 3;
927 if (((tokend == search_token
928 || (tokend > search_token
929 && (tokend[-1] == '/' || tokend[-1] == '\\')))
930 && !strcasecmp (tokend, "cmd"))
931 || ((tokend - 4 == search_token
932 || (tokend - 4 > search_token
933 && (tokend[-5] == '/' || tokend[-5] == '\\')))
934 && !strcasecmp (tokend - 4, "cmd.exe")))
936 batch_mode_shell = 1;
938 sprintf (sh_path, "%s", search_token);
939 default_shell = xstrdup (w32ify (sh_path, 0));
940 DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
944 else if (!no_default_sh_exe
945 && (token == NULL || !strcmp (search_token, default_shell)))
947 /* no new information, path already set or known */
950 else if (_access (search_token, 0) == 0)
952 /* search token path was found */
953 sprintf (sh_path, "%s", search_token);
954 default_shell = xstrdup (w32ify (sh_path, 0));
955 DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
962 struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
964 /* Search Path for shell */
970 ep = strchr (p, PATH_SEPARATOR_CHAR);
976 sprintf (sh_path, "%s/%s", p, search_token);
977 if (_access (sh_path, 0) == 0)
979 default_shell = xstrdup (w32ify (sh_path, 0));
981 *ep = PATH_SEPARATOR_CHAR;
988 *ep = PATH_SEPARATOR_CHAR;
992 ep = strchr (p, PATH_SEPARATOR_CHAR);
995 /* be sure to check last element of Path */
998 sprintf (sh_path, "%s/%s", p, search_token);
999 if (_access (sh_path, 0) == 0)
1001 default_shell = xstrdup (w32ify (sh_path, 0));
1008 (_("find_and_set_shell() path search set default_shell = %s\n"),
1014 if (!unixy_shell && sh_found
1015 && (strstr (default_shell, "sh") || strstr (default_shell, "SH")))
1018 batch_mode_shell = 0;
1021 #ifdef BATCH_MODE_ONLY_SHELL
1022 batch_mode_shell = 1;
1030 #endif /* WINDOWS32 */
1034 msdos_return_to_initial_directory (void)
1036 if (directory_before_chdir)
1037 chdir (directory_before_chdir);
1039 #endif /* __MSDOS__ */
1043 main (int argc, char **argv)
1046 main (int argc, char **argv, char **envp)
1049 static char *stdin_nm = 0;
1050 int makefile_status = MAKE_SUCCESS;
1051 struct dep *read_files;
1052 PATH_VAR (current_directory);
1053 unsigned int restarts = 0;
1054 unsigned int syncing = 0;
1056 char *unix_path = NULL;
1057 char *windows32_path = NULL;
1059 SetUnhandledExceptionFilter (handle_runtime_exceptions);
1061 /* start off assuming we have no shell */
1063 no_default_sh_exe = 1;
1066 output_init (&make_sync);
1068 initialize_stopchar_map();
1070 #ifdef SET_STACK_SIZE
1071 /* Get rid of any avoidable limit on stack size. */
1075 /* Set the stack limit huge so that alloca does not fail. */
1076 if (getrlimit (RLIMIT_STACK, &rlim) == 0
1077 && rlim.rlim_cur > 0 && rlim.rlim_cur < rlim.rlim_max)
1080 rlim.rlim_cur = rlim.rlim_max;
1081 setrlimit (RLIMIT_STACK, &rlim);
1084 stack_limit.rlim_cur = 0;
1088 /* Needed for OS/2 */
1089 initialize_main (&argc, &argv);
1091 #ifdef MAKE_MAINTAINER_MODE
1092 /* In maintainer mode we always enable verification. */
1096 #if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
1097 /* Request the most powerful version of 'system', to
1098 make up for the dumb default shell. */
1099 __system_flags = (__system_redirect
1100 | __system_use_shell
1101 | __system_allow_multiple_cmds
1102 | __system_allow_long_cmds
1103 | __system_handle_null_commands
1104 | __system_emulate_chdir);
1108 /* Set up gettext/internationalization support. */
1109 setlocale (LC_ALL, "");
1110 /* The cast to void shuts up compiler warnings on systems that
1112 (void)bindtextdomain (PACKAGE, LOCALEDIR);
1113 (void)textdomain (PACKAGE);
1116 sigemptyset (&fatal_signal_set);
1117 #define ADD_SIG(sig) sigaddset (&fatal_signal_set, sig)
1119 #ifdef HAVE_SIGSETMASK
1120 fatal_signal_mask = 0;
1121 #define ADD_SIG(sig) fatal_signal_mask |= sigmask (sig)
1123 #define ADD_SIG(sig) (void)sig
1127 #define FATAL_SIG(sig) \
1128 if (bsd_signal (sig, fatal_error_signal) == SIG_IGN) \
1129 bsd_signal (sig, SIG_IGN); \
1137 FATAL_SIG (SIGQUIT);
1140 FATAL_SIG (SIGTERM);
1143 /* Windows 9X delivers FP exceptions in child programs to their
1144 parent! We don't want Make to die when a child divides by zero,
1145 so we work around that lossage by catching SIGFPE. */
1150 FATAL_SIG (SIGDANGER);
1153 FATAL_SIG (SIGXCPU);
1156 FATAL_SIG (SIGXFSZ);
1161 /* Do not ignore the child-death signal. This must be done before
1162 any children could possibly be created; otherwise, the wait
1163 functions won't work on systems with the SVR4 ECHILD brain
1164 damage, if our invoker is ignoring this signal. */
1166 #ifdef HAVE_WAIT_NOHANG
1167 # if defined SIGCHLD
1168 (void) bsd_signal (SIGCHLD, SIG_DFL);
1170 # if defined SIGCLD && SIGCLD != SIGCHLD
1171 (void) bsd_signal (SIGCLD, SIG_DFL);
1177 /* Figure out where this program lives. */
1181 if (argv[0][0] == '\0')
1186 program = strrchr (argv[0], ']');
1188 program = strrchr (argv[0], '/');
1190 #if defined(__MSDOS__) || defined(__EMX__)
1192 program = strrchr (argv[0], '\\');
1195 /* Some weird environments might pass us argv[0] with
1196 both kinds of slashes; we must find the rightmost. */
1197 char *p = strrchr (argv[0], '\\');
1198 if (p && p > program)
1201 if (program == 0 && argv[0][1] == ':')
1202 program = argv[0] + 1;
1207 /* Extract program from full path */
1208 program = strrchr (argv[0], '\\');
1211 int argv0_len = strlen (program);
1212 if (argv0_len > 4 && streq (&program[argv0_len - 4], ".exe"))
1213 /* Remove .exe extension */
1214 program[argv0_len - 4] = '\0';
1224 /* Set up to access user data (files). */
1227 initialize_global_hash_tables ();
1229 /* Figure out where we are. */
1232 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1234 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1238 perror_with_name ("getcwd", "");
1240 error (NILF, "getwd: %s", current_directory);
1242 current_directory[0] = '\0';
1243 directory_before_chdir = 0;
1246 directory_before_chdir = xstrdup (current_directory);
1249 /* Make sure we will return to the initial directory, come what may. */
1250 atexit (msdos_return_to_initial_directory);
1253 /* Initialize the special variables. */
1254 define_variable_cname (".VARIABLES", "", o_default, 0)->special = 1;
1255 /* define_variable_cname (".TARGETS", "", o_default, 0)->special = 1; */
1256 define_variable_cname (".RECIPEPREFIX", "", o_default, 0)->special = 1;
1257 define_variable_cname (".SHELLFLAGS", "-c", o_default, 0);
1260 Use a separate variable because define_variable_cname() is a macro and
1261 some compilers (MSVC) don't like conditionals in macros. */
1263 const char *features = "target-specific order-only second-expansion"
1264 " else-if shortest-stem undefine oneshell"
1268 #ifdef MAKE_JOBSERVER
1271 #ifndef NO_OUTPUT_SYNC
1274 #ifdef MAKE_SYMLINKS
1285 define_variable_cname (".FEATURES", features, o_default, 0);
1289 /* Configure GNU Guile support */
1290 guile_gmake_setup (NILF);
1293 /* Read in variables from the environment. It is important that this be
1294 done before $(MAKE) is figured out so its definitions will not be
1295 from the environment. */
1301 for (i = 0; envp[i] != 0; ++i)
1305 /* By default, export all variables culled from the environment. */
1306 enum variable_export export = v_export;
1309 while (! STOP_SET (*ep, MAP_EQUALS))
1312 /* If there's no equals sign it's a malformed environment. Ignore. */
1317 if (!unix_path && strneq (envp[i], "PATH=", 5))
1319 else if (!strnicmp (envp[i], "Path=", 5))
1321 if (!windows32_path)
1322 windows32_path = ep+1;
1323 /* PATH gets defined after the loop exits. */
1328 /* Length of the variable name, and skip the '='. */
1329 len = ep++ - envp[i];
1331 /* If this is MAKE_RESTARTS, check to see if the "already printed
1332 the enter statement" flag is set. */
1333 if (len == 13 && strneq (envp[i], "MAKE_RESTARTS", 13))
1340 restarts = (unsigned int) atoi (ep);
1341 export = v_noexport;
1344 v = define_variable (envp[i], len, ep, o_env, 1);
1346 /* POSIX says the value of SHELL set in the makefile won't change the
1347 value of SHELL given to subprocesses. */
1348 if (streq (v->name, "SHELL"))
1351 export = v_noexport;
1353 shell_var.name = "SHELL";
1354 shell_var.length = 5;
1355 shell_var.value = xstrdup (ep);
1362 /* If we didn't find a correctly spelled PATH we define PATH as
1363 * either the first misspelled value or an empty string
1366 define_variable_cname ("PATH", windows32_path ? windows32_path : "",
1367 o_env, 1)->export = v_export;
1369 #else /* For Amiga, read the ENV: device, ignoring all dirs */
1371 BPTR env, file, old;
1374 __aligned struct FileInfoBlock fib;
1376 env = Lock ("ENV:", ACCESS_READ);
1379 old = CurrentDir (DupLock (env));
1380 Examine (env, &fib);
1382 while (ExNext (env, &fib))
1384 if (fib.fib_DirEntryType < 0) /* File */
1386 /* Define an empty variable. It will be filled in
1387 variable_lookup(). Makes startup quite a bit faster. */
1388 define_variable (fib.fib_FileName,
1389 strlen (fib.fib_FileName),
1390 "", o_env, 1)->export = v_export;
1394 UnLock (CurrentDir (old));
1399 /* Decode the switches. */
1401 decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
1403 /* Clear GNUMAKEFLAGS to avoid duplication. */
1404 define_variable_cname ("GNUMAKEFLAGS", "", o_env, 0);
1406 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1408 /* In output sync mode we need to sync any output generated by reading the
1409 makefiles, such as in $(info ...) or stderr from $(shell ...) etc. */
1411 syncing = make_sync.syncout = (output_sync == OUTPUT_SYNC_LINE
1412 || output_sync == OUTPUT_SYNC_TARGET);
1413 OUTPUT_SET (&make_sync);
1416 /* People write things like:
1417 MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
1418 and we set the -p, -i and -e switches. Doesn't seem quite right. */
1419 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1422 decode_switches (argc, argv, 0);
1424 /* Reset in case the switches changed our minds. */
1425 syncing = (output_sync == OUTPUT_SYNC_LINE
1426 || output_sync == OUTPUT_SYNC_TARGET);
1428 if (make_sync.syncout && ! syncing)
1429 output_close (&make_sync);
1431 make_sync.syncout = syncing;
1432 OUTPUT_SET (&make_sync);
1434 /* Figure out the level of recursion. */
1436 struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
1437 if (v && v->value[0] != '\0' && v->value[0] != '-')
1438 makelevel = (unsigned int) atoi (v->value);
1446 fprintf (stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId ());
1447 fprintf (stderr, _("%s is suspending for 30 seconds..."), argv[0]);
1449 fprintf (stderr, _("done sleep(30). Continuing.\n"));
1453 /* Set always_make_flag if -B was given and we've not restarted already. */
1454 always_make_flag = always_make_set && (restarts == 0);
1456 /* Print version information, and exit. */
1457 if (print_version_flag)
1463 if (ISDB (DB_BASIC))
1467 /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
1468 (If it is a relative pathname with a slash, prepend our directory name
1469 so the result will run the same program regardless of the current dir.
1470 If it is a name with no slash, we can only hope that PATH did not
1471 find it in the current directory.) */
1474 * Convert from backslashes to forward slashes for
1475 * programs like sh which don't like them. Shouldn't
1476 * matter if the path is one way or the other for
1479 if (strpbrk (argv[0], "/:\\") || strstr (argv[0], "..")
1480 || strneq (argv[0], "//", 2))
1481 argv[0] = xstrdup (w32ify (argv[0], 1));
1482 #else /* WINDOWS32 */
1483 #if defined (__MSDOS__) || defined (__EMX__)
1484 if (strchr (argv[0], '\\'))
1488 argv[0] = xstrdup (argv[0]);
1489 for (p = argv[0]; *p; p++)
1493 /* If argv[0] is not in absolute form, prepend the current
1494 directory. This can happen when Make is invoked by another DJGPP
1495 program that uses a non-absolute name. */
1496 if (current_directory[0] != '\0'
1498 && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
1500 /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
1501 && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
1504 argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
1505 #else /* !__MSDOS__ */
1506 if (current_directory[0] != '\0'
1507 && argv[0] != 0 && argv[0][0] != '/' && strchr (argv[0], '/') != 0
1508 #ifdef HAVE_DOS_PATHS
1509 && (argv[0][0] != '\\' && (!argv[0][0] || argv[0][1] != ':'))
1510 && strchr (argv[0], '\\') != 0
1513 argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
1514 #endif /* !__MSDOS__ */
1515 #endif /* WINDOWS32 */
1518 /* We may move, but until we do, here we are. */
1519 starting_directory = current_directory;
1521 #ifdef MAKE_JOBSERVER
1522 /* If the jobserver-fds option is seen, make sure that -j is reasonable.
1523 This can't be usefully set in the makefile, and we want to verify the
1524 FDs are valid before any other aspect of make has a chance to start
1525 using them for something else. */
1532 for (ui=1; ui < jobserver_fds->idx; ++ui)
1533 if (!streq (jobserver_fds->list[0], jobserver_fds->list[ui]))
1534 fatal (NILF, _("internal error: multiple --jobserver-fds options"));
1536 /* Now parse the fds string and make sure it has the proper format. */
1538 cp = jobserver_fds->list[0];
1541 if (! open_jobserver_semaphore (cp))
1543 DWORD err = GetLastError ();
1544 fatal (NILF, _("internal error: unable to open jobserver semaphore '%s': (Error %ld: %s)"),
1545 cp, err, map_windows32_error_to_string (err));
1547 DB (DB_JOBS, (_("Jobserver client (semaphore %s)\n"), cp));
1549 if (sscanf (cp, "%d,%d", &job_fds[0], &job_fds[1]) != 2)
1551 _("internal error: invalid --jobserver-fds string '%s'"), cp);
1554 (_("Jobserver client (fds %d,%d)\n"), job_fds[0], job_fds[1]));
1557 /* The combination of a pipe + !job_slots means we're using the
1558 jobserver. If !job_slots and we don't have a pipe, we can start
1559 infinite jobs. If we see both a pipe and job_slots >0 that means the
1560 user set -j explicitly. This is broken; in this case obey the user
1561 (ignore the jobserver pipe for this make) but print a message.
1562 If we've restarted, we already printed this the first time. */
1567 error (NILF, _("warning: -jN forced in submake: disabling jobserver mode."));
1571 # define FD_OK(_f) ((fcntl ((_f), F_GETFD) != -1) || (errno != EBADF))
1573 # define FD_OK(_f) 1
1575 /* Create a duplicate pipe, that will be closed in the SIGCHLD
1576 handler. If this fails with EBADF, the parent has closed the pipe
1577 on us because it didn't think we were a submake. If so, print a
1578 warning then default to -j1. */
1579 else if (!FD_OK (job_fds[0]) || !FD_OK (job_fds[1])
1580 || (job_rfd = dup (job_fds[0])) < 0)
1583 pfatal_with_name (_("dup jobserver"));
1586 _("warning: jobserver unavailable: using -j1. Add '+' to parent make rule."));
1588 job_fds[0] = job_fds[1] = -1;
1595 free_jobserver_semaphore ();
1597 if (job_fds[0] >= 0)
1599 if (job_fds[1] >= 0)
1602 job_fds[0] = job_fds[1] = -1;
1603 free (jobserver_fds->list);
1604 free (jobserver_fds);
1610 /* The extra indirection through $(MAKE_COMMAND) is done
1611 for hysterical raisins. */
1612 define_variable_cname ("MAKE_COMMAND", argv[0], o_default, 0);
1613 define_variable_cname ("MAKE", "$(MAKE_COMMAND)", o_default, 1);
1615 if (command_variables != 0)
1617 struct command_variable *cv;
1619 unsigned int len = 0;
1622 /* Figure out how much space will be taken up by the command-line
1623 variable definitions. */
1624 for (cv = command_variables; cv != 0; cv = cv->next)
1627 len += 2 * strlen (v->name);
1631 len += 2 * strlen (v->value);
1635 /* Now allocate a buffer big enough and fill it. */
1636 p = value = alloca (len);
1637 for (cv = command_variables; cv != 0; cv = cv->next)
1640 p = quote_for_env (p, v->name);
1644 p = quote_for_env (p, v->value);
1647 p[-1] = '\0'; /* Kill the final space and terminate. */
1649 /* Define an unchangeable variable with a name that no POSIX.2
1650 makefile could validly use for its own variable. */
1651 define_variable_cname ("-*-command-variables-*-", value, o_automatic, 0);
1653 /* Define the variable; this will not override any user definition.
1654 Normally a reference to this variable is written into the value of
1655 MAKEFLAGS, allowing the user to override this value to affect the
1656 exported value of MAKEFLAGS. In POSIX-pedantic mode, we cannot
1657 allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
1658 a reference to this hidden variable is written instead. */
1659 define_variable_cname ("MAKEOVERRIDES", "${-*-command-variables-*-}",
1663 /* If there were -C flags, move ourselves about. */
1664 if (directories != 0)
1667 for (i = 0; directories->list[i] != 0; ++i)
1669 const char *dir = directories->list[i];
1671 /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1672 But allow -C/ just in case someone wants that. */
1674 char *p = (char *)dir + strlen (dir) - 1;
1675 while (p > dir && (p[0] == '/' || p[0] == '\\'))
1680 if (chdir (dir) < 0)
1681 pfatal_with_name (dir);
1687 * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1688 * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1690 * The functions in dir.c can incorrectly cache information for "."
1691 * before we have changed directory and this can cause file
1692 * lookups to fail because the current directory (.) was pointing
1693 * at the wrong place when it was first evaluated.
1695 no_default_sh_exe = !find_and_set_default_shell (NULL);
1696 #endif /* WINDOWS32 */
1698 /* Except under -s, always do -w in sub-makes and under -C. */
1699 if (!silent_flag && (directories != 0 || makelevel > 0))
1700 print_directory_flag = 1;
1702 /* Let the user disable that with --no-print-directory. */
1703 if (inhibit_print_directory_flag)
1704 print_directory_flag = 0;
1706 /* If -R was given, set -r too (doesn't make sense otherwise!) */
1707 if (no_builtin_variables_flag)
1708 no_builtin_rules_flag = 1;
1710 /* Construct the list of include directories to search. */
1712 construct_include_path (include_directories == 0
1713 ? 0 : include_directories->list);
1715 /* If we chdir'ed, figure out where we are now. */
1719 if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1721 if (getcwd (current_directory, GET_PATH_MAX) == 0)
1725 perror_with_name ("getcwd", "");
1727 error (NILF, "getwd: %s", current_directory);
1729 starting_directory = 0;
1732 starting_directory = current_directory;
1735 define_variable_cname ("CURDIR", current_directory, o_file, 0);
1737 /* Read any stdin makefiles into temporary files. */
1742 for (i = 0; i < makefiles->idx; ++i)
1743 if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
1745 /* This makefile is standard input. Since we may re-exec
1746 and thus re-read the makefiles, we read standard input
1747 into a temporary file and read from that. */
1749 char *template, *tmpdir;
1752 fatal (NILF, _("Makefile from standard input specified twice."));
1755 # define DEFAULT_TMPDIR "sys$scratch:"
1758 # define DEFAULT_TMPDIR P_tmpdir
1760 # define DEFAULT_TMPDIR "/tmp"
1763 #define DEFAULT_TMPFILE "GmXXXXXX"
1765 if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
1766 #if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
1767 /* These are also used commonly on these platforms. */
1768 && ((tmpdir = getenv ("TEMP")) == NULL || *tmpdir == '\0')
1769 && ((tmpdir = getenv ("TMP")) == NULL || *tmpdir == '\0')
1772 tmpdir = DEFAULT_TMPDIR;
1774 template = alloca (strlen (tmpdir) + CSTRLEN (DEFAULT_TMPFILE) + 2);
1775 strcpy (template, tmpdir);
1777 #ifdef HAVE_DOS_PATHS
1778 if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
1779 strcat (template, "/");
1782 if (template[strlen (template) - 1] != '/')
1783 strcat (template, "/");
1785 #endif /* !HAVE_DOS_PATHS */
1787 strcat (template, DEFAULT_TMPFILE);
1788 outfile = output_tmpfile (&stdin_nm, template);
1790 pfatal_with_name (_("fopen (temporary file)"));
1791 while (!feof (stdin) && ! ferror (stdin))
1794 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
1795 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
1796 pfatal_with_name (_("fwrite (temporary file)"));
1800 /* Replace the name that read_all_makefiles will
1801 see with the name of the temporary file. */
1802 makefiles->list[i] = strcache_add (stdin_nm);
1804 /* Make sure the temporary file will not be remade. */
1806 struct file *f = enter_file (strcache_add (stdin_nm));
1808 f->update_status = us_success;
1809 f->command_state = cs_finished;
1810 /* Can't be intermediate, or it'll be removed too early for
1812 f->intermediate = 0;
1818 #ifndef __EMX__ /* Don't use a SIGCHLD handler for OS/2 */
1819 #if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
1820 /* Set up to handle children dying. This must be done before
1821 reading in the makefiles so that 'shell' function calls will work.
1823 If we don't have a hanging wait we have to fall back to old, broken
1824 functionality here and rely on the signal handler and counting
1827 If we're using the jobs pipe we need a signal handler so that
1828 SIGCHLD is not ignored; we need it to interrupt the read(2) of the
1829 jobserver pipe in job.c if we're waiting for a token.
1831 If none of these are true, we don't need a signal handler at all. */
1833 RETSIGTYPE child_handler (int sig);
1834 # if defined SIGCHLD
1835 bsd_signal (SIGCHLD, child_handler);
1837 # if defined SIGCLD && SIGCLD != SIGCHLD
1838 bsd_signal (SIGCLD, child_handler);
1844 /* Let the user send us SIGUSR1 to toggle the -d flag during the run. */
1846 bsd_signal (SIGUSR1, debug_signal_handler);
1849 /* Define the initial list of suffixes for old-style rules. */
1850 set_default_suffixes ();
1852 /* Define the file rules for the built-in suffix rules. These will later
1853 be converted into pattern rules. We used to do this in
1854 install_default_implicit_rules, but since that happens after reading
1855 makefiles, it results in the built-in pattern rules taking precedence
1856 over makefile-specified suffix rules, which is wrong. */
1857 install_default_suffix_rules ();
1859 /* Define some internal and special variables. */
1860 define_automatic_variables ();
1862 /* Set up the MAKEFLAGS and MFLAGS variables for makefiles to see.
1863 Initialize it to be exported but allow the makefile to reset it. */
1864 define_makeflags (0, 0)->export = v_export;
1866 /* Define the default variables. */
1867 define_default_variables ();
1869 default_file = enter_file (strcache_add (".DEFAULT"));
1871 default_goal_var = define_variable_cname (".DEFAULT_GOAL", "", o_file, 0);
1873 /* Evaluate all strings provided with --eval.
1874 Also set up the $(-*-eval-flags-*-) variable. */
1880 unsigned int len = (CSTRLEN ("--eval=") + 1) * eval_strings->idx;
1882 for (i = 0; i < eval_strings->idx; ++i)
1884 p = xstrdup (eval_strings->list[i]);
1885 len += 2 * strlen (p);
1886 eval_buffer (p, NULL);
1890 p = value = alloca (len);
1891 for (i = 0; i < eval_strings->idx; ++i)
1893 strcpy (p, "--eval=");
1894 p += CSTRLEN ("--eval=");
1895 p = quote_for_env (p, eval_strings->list[i]);
1900 define_variable_cname ("-*-eval-flags-*-", value, o_automatic, 0);
1903 /* Read all the makefiles. */
1905 read_files = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
1908 /* look one last time after reading all Makefiles */
1909 if (no_default_sh_exe)
1910 no_default_sh_exe = !find_and_set_default_shell (NULL);
1911 #endif /* WINDOWS32 */
1913 #if defined (__MSDOS__) || defined (__EMX__)
1914 /* We need to know what kind of shell we will be using. */
1916 extern int _is_unixy_shell (const char *_path);
1917 struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
1918 extern int unixy_shell;
1919 extern char *default_shell;
1921 if (shv && *shv->value)
1923 char *shell_path = recursively_expand (shv);
1925 if (shell_path && _is_unixy_shell (shell_path))
1930 default_shell = shell_path;
1933 #endif /* __MSDOS__ || __EMX__ */
1936 int old_builtin_rules_flag = no_builtin_rules_flag;
1937 int old_builtin_variables_flag = no_builtin_variables_flag;
1939 /* Decode switches again, for variables set by the makefile. */
1940 decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
1942 /* Clear GNUMAKEFLAGS to avoid duplication. */
1943 define_variable_cname ("GNUMAKEFLAGS", "", o_override, 0);
1945 decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1947 decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
1950 /* Reset in case the switches changed our mind. */
1951 syncing = (output_sync == OUTPUT_SYNC_LINE
1952 || output_sync == OUTPUT_SYNC_TARGET);
1954 if (make_sync.syncout && ! syncing)
1955 output_close (&make_sync);
1957 make_sync.syncout = syncing;
1958 OUTPUT_SET (&make_sync);
1960 /* If we've disabled builtin rules, get rid of them. */
1961 if (no_builtin_rules_flag && ! old_builtin_rules_flag)
1963 if (suffix_file->builtin)
1965 free_dep_chain (suffix_file->deps);
1966 suffix_file->deps = 0;
1968 define_variable_cname ("SUFFIXES", "", o_default, 0);
1971 /* If we've disabled builtin variables, get rid of them. */
1972 if (no_builtin_variables_flag && ! old_builtin_variables_flag)
1973 undefine_default_variables ();
1976 #if defined (__MSDOS__) || defined (__EMX__)
1979 && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
1984 _("Parallel jobs (-j) are not supported on this platform."));
1985 error (NILF, _("Resetting to single job (-j1) mode."));
1990 #ifdef MAKE_JOBSERVER
1991 /* If we have >1 slot but no jobserver-fds, then we're a top-level make.
1992 Set up the pipe and install the fds option for our children. */
1999 /* sub_proc.c cannot wait for more than MAXIMUM_WAIT_OBJECTS objects
2000 * and one of them is the job-server semaphore object. Limit the
2001 * number of available job slots to (MAXIMUM_WAIT_OBJECTS - 1). */
2003 if (job_slots >= MAXIMUM_WAIT_OBJECTS)
2005 job_slots = MAXIMUM_WAIT_OBJECTS - 1;
2006 DB (DB_JOBS, (_("Jobserver slots limited to %d\n"), job_slots));
2009 if (! create_jobserver_semaphore (job_slots - 1))
2011 DWORD err = GetLastError ();
2012 fatal (NILF, _("creating jobserver semaphore: (Error %ld: %s)"),
2013 err, map_windows32_error_to_string (err));
2018 if (pipe (job_fds) < 0 || (job_rfd = dup (job_fds[0])) < 0)
2019 pfatal_with_name (_("creating jobs pipe"));
2022 /* Every make assumes that it always has one job it can run. For the
2023 submakes it's the token they were given by their parent. For the
2024 top make, we just subtract one from the number the user wants. We
2025 want job_slots to be 0 to indicate we're using the jobserver. */
2027 master_job_slots = job_slots;
2030 /* We're using the jobserver so set job_slots to 0. */
2037 EINTRLOOP (r, write (job_fds[1], &c, 1));
2039 pfatal_with_name (_("init jobserver pipe"));
2043 /* Fill in the jobserver_fds struct for our children. */
2046 cp = xmalloc (MAX_PATH + 1);
2047 strcpy (cp, get_jobserver_semaphore_name ());
2049 cp = xmalloc ((CSTRLEN ("1024") * 2) + 2);
2050 sprintf (cp, "%d,%d", job_fds[0], job_fds[1]);
2053 jobserver_fds = xmalloc (sizeof (struct stringlist));
2054 jobserver_fds->list = xmalloc (sizeof (char *));
2055 jobserver_fds->list[0] = cp;
2056 jobserver_fds->idx = 1;
2057 jobserver_fds->max = 1;
2061 #ifndef MAKE_SYMLINKS
2062 if (check_symlink_flag)
2064 error (NILF, _("Symbolic links not supported: disabling -L."));
2065 check_symlink_flag = 0;
2069 /* Set up MAKEFLAGS and MFLAGS again, so they will be right. */
2071 define_makeflags (1, 0);
2073 /* Make each 'struct dep' point at the 'struct file' for the file
2074 depended on. Also do magic for special targets. */
2078 /* Convert old-style suffix rules to pattern rules. It is important to
2079 do this before installing the built-in pattern rules below, so that
2080 makefile-specified suffix rules take precedence over built-in pattern
2083 convert_to_pattern ();
2085 /* Install the default implicit pattern rules.
2086 This used to be done before reading the makefiles.
2087 But in that case, built-in pattern rules were in the chain
2088 before user-defined ones, so they matched first. */
2090 install_default_implicit_rules ();
2092 /* Compute implicit rule limits. */
2094 count_implicit_rule_limits ();
2096 /* Construct the listings of directories in VPATH lists. */
2098 build_vpath_lists ();
2100 /* Mark files given with -o flags as very old and as having been updated
2101 already, and files given with -W flags as brand new (time-stamp as far
2102 as possible into the future). If restarts is set we'll do -W later. */
2107 for (p = old_files->list; *p != 0; ++p)
2109 struct file *f = enter_file (*p);
2110 f->last_mtime = f->mtime_before_update = OLD_MTIME;
2112 f->update_status = us_success;
2113 f->command_state = cs_finished;
2117 if (!restarts && new_files != 0)
2120 for (p = new_files->list; *p != 0; ++p)
2122 struct file *f = enter_file (*p);
2123 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2127 /* Initialize the remote job module. */
2130 /* Dump any output we've collected. */
2133 output_close (&make_sync);
2135 if (read_files != 0)
2137 /* Update any makefiles if necessary. */
2139 FILE_TIMESTAMP *makefile_mtimes = 0;
2140 unsigned int mm_idx = 0;
2143 int orig_db_level = db_level;
2144 enum update_status status;
2146 if (! ISDB (DB_MAKEFILES))
2149 DB (DB_BASIC, (_("Updating makefiles....\n")));
2151 /* Remove any makefiles we don't want to try to update.
2152 Also record the current modtimes so we can compare them later. */
2154 register struct dep *d, *last;
2159 struct file *f = d->file;
2160 if (f->double_colon)
2161 for (f = f->double_colon; f != NULL; f = f->prev)
2163 if (f->deps == 0 && f->cmds != 0)
2165 /* This makefile is a :: target with commands, but
2166 no dependencies. So, it will always be remade.
2167 This might well cause an infinite loop, so don't
2168 try to remake it. (This will only happen if
2169 your makefiles are written exceptionally
2170 stupidly; but if you work for Athena, that's how
2171 you write your makefiles.) */
2174 (_("Makefile '%s' might loop; not remaking it.\n"),
2178 read_files = d->next;
2180 last->next = d->next;
2182 /* Free the storage. */
2185 d = last == 0 ? read_files : last->next;
2190 if (f == NULL || !f->double_colon)
2192 makefile_mtimes = xrealloc (makefile_mtimes,
2194 * sizeof (FILE_TIMESTAMP));
2195 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
2202 /* Set up 'MAKEFLAGS' specially while remaking makefiles. */
2203 define_makeflags (1, 1);
2205 rebuilding_makefiles = 1;
2206 status = update_goal_chain (read_files);
2207 rebuilding_makefiles = 0;
2212 /* The only way this can happen is if the user specified -q and asked
2213 * for one of the makefiles to be remade as a target on the command
2214 * line. Since we're not actually updating anything with -q we can
2215 * treat this as "did nothing".
2223 /* Failed to update. Figure out if we care. */
2225 /* Nonzero if any makefile was successfully remade. */
2227 /* Nonzero if any makefile we care about failed
2228 in updating or could not be found at all. */
2233 for (i = 0, d = read_files; d != 0; ++i, d = d->next)
2235 /* Reset the considered flag; we may need to look at the file
2236 again to print an error. */
2237 d->file->considered = 0;
2239 if (d->file->updated)
2241 /* This makefile was updated. */
2242 if (d->file->update_status == us_success)
2244 /* It was successfully updated. */
2245 any_remade |= (file_mtime_no_search (d->file)
2246 != makefile_mtimes[i]);
2248 else if (! (d->changed & RM_DONTCARE))
2250 FILE_TIMESTAMP mtime;
2251 /* The update failed and this makefile was not
2252 from the MAKEFILES variable, so we care. */
2253 error (NILF, _("Failed to remake makefile '%s'."),
2255 mtime = file_mtime_no_search (d->file);
2256 any_remade |= (mtime != NONEXISTENT_MTIME
2257 && mtime != makefile_mtimes[i]);
2258 makefile_status = MAKE_FAILURE;
2262 /* This makefile was not found at all. */
2263 if (! (d->changed & RM_DONTCARE))
2265 /* This is a makefile we care about. See how much. */
2266 if (d->changed & RM_INCLUDED)
2267 /* An included makefile. We don't need
2268 to die, but we do want to complain. */
2270 _("Included makefile '%s' was not found."),
2274 /* A normal makefile. We must die later. */
2275 error (NILF, _("Makefile '%s' was not found"),
2281 /* Reset this to empty so we get the right error message below. */
2293 /* Updated successfully. Re-exec ourselves. */
2295 remove_intermediates (0);
2297 if (print_data_base_flag)
2300 clean_jobserver (0);
2304 /* These names might have changed. */
2306 for (i = 1; i < argc; ++i)
2307 if (strneq (argv[i], "-f", 2)) /* XXX */
2309 if (argv[i][2] == '\0')
2310 /* This cast is OK since we never modify argv. */
2311 argv[++i] = (char *) makefiles->list[j];
2313 argv[i] = xstrdup (concat (2, "-f", makefiles->list[j]));
2318 /* Add -o option for the stdin temporary file, if necessary. */
2322 nargv = xmalloc ((nargc + 2) * sizeof (char *));
2323 memcpy (nargv, argv, argc * sizeof (char *));
2324 nargv[nargc++] = xstrdup (concat (2, "-o", stdin_nm));
2330 if (directories != 0 && directories->idx > 0)
2333 if (directory_before_chdir != 0)
2335 if (chdir (directory_before_chdir) < 0)
2336 perror_with_name ("chdir", "");
2341 fatal (NILF, _("Couldn't change back to original directory."));
2346 /* If we're re-exec'ing the first make, put back the number of
2347 job slots so define_makefiles() will get it right. */
2348 if (master_job_slots)
2349 job_slots = master_job_slots;
2351 if (ISDB (DB_BASIC))
2354 printf (_("Re-executing[%u]:"), restarts);
2355 for (p = nargv; *p != 0; ++p)
2363 for (p = environ; *p != 0; ++p)
2365 if (strneq (*p, MAKELEVEL_NAME "=", MAKELEVEL_LENGTH+1))
2368 sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2370 else if (strneq (*p, "MAKE_RESTARTS=", CSTRLEN ("MAKE_RESTARTS=")))
2373 sprintf (*p, "MAKE_RESTARTS=%s%u",
2374 OUTPUT_IS_TRACED () ? "-" : "", restarts);
2383 sprintf (buffer, "%u", makelevel);
2384 SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2386 sprintf (buffer, "%s%u", OUTPUT_IS_TRACED () ? "-" : "", restarts);
2387 SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2392 /* If we didn't set the restarts variable yet, add it. */
2395 char *b = alloca (40);
2396 sprintf (b, "MAKE_RESTARTS=%s%u",
2397 OUTPUT_IS_TRACED () ? "-" : "", restarts);
2404 /* Close the dup'd jobserver pipe if we opened one. */
2409 exec_command (nargv);
2411 #elif defined (__EMX__)
2413 /* It is not possible to use execve() here because this
2414 would cause the parent process to be terminated with
2415 exit code 0 before the child process has been terminated.
2416 Therefore it may be the best solution simply to spawn the
2417 child process including all file handles and to wait for its
2421 pid = child_execute_job (FD_STDIN, FD_STDOUT, FD_STDERR,
2424 /* is this loop really necessary? */
2428 /* use the exit code of the child process */
2429 exit (WIFEXITED(r) ? WEXITSTATUS(r) : EXIT_FAILURE);
2432 exec_command (nargv, environ);
2436 db_level = orig_db_level;
2438 /* Free the makefile mtimes (if we allocated any). */
2439 if (makefile_mtimes)
2440 free (makefile_mtimes);
2443 /* Set up 'MAKEFLAGS' again for the normal targets. */
2444 define_makeflags (1, 0);
2446 /* Set always_make_flag if -B was given. */
2447 always_make_flag = always_make_set;
2449 /* If restarts is set we haven't set up -W files yet, so do that now. */
2450 if (restarts && new_files != 0)
2453 for (p = new_files->list; *p != 0; ++p)
2455 struct file *f = enter_file (*p);
2456 f->last_mtime = f->mtime_before_update = NEW_MTIME;
2460 /* If there is a temp file from reading a makefile from stdin, get rid of
2462 if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
2463 perror_with_name (_("unlink (temporary file): "), stdin_nm);
2465 /* If there were no command-line goals, use the default. */
2470 if (default_goal_var->recursive)
2471 p = variable_expand (default_goal_var->value);
2474 p = variable_buffer_output (variable_buffer, default_goal_var->value,
2475 strlen (default_goal_var->value));
2477 p = variable_buffer;
2482 struct file *f = lookup_file (p);
2484 /* If .DEFAULT_GOAL is a non-existent target, enter it into the
2485 table and let the standard logic sort it out. */
2490 ns = PARSE_SIMPLE_SEQ (&p, struct nameseq);
2493 /* .DEFAULT_GOAL should contain one target. */
2495 fatal (NILF, _(".DEFAULT_GOAL contains more than one target"));
2497 f = enter_file (strcache_add (ns->name));
2499 ns->name = 0; /* It was reused by enter_file(). */
2506 goals = alloc_dep ();
2517 if (read_files == 0)
2518 fatal (NILF, _("No targets specified and no makefile found"));
2520 fatal (NILF, _("No targets"));
2523 /* Update the goals. */
2525 DB (DB_BASIC, (_("Updating goal targets....\n")));
2528 switch (update_goal_chain (goals))
2531 /* Nothing happened. */
2534 /* Keep the previous result. */
2537 /* We are under -q and would run some commands. */
2538 makefile_status = MAKE_TROUBLE;
2541 /* Updating failed. POSIX.2 specifies exit status >1 for this;
2542 but in VMS, there is only success and failure. */
2543 makefile_status = MAKE_FAILURE;
2547 /* If we detected some clock skew, generate one last warning */
2548 if (clock_skew_detected)
2550 _("warning: Clock skew detected. Your build may be incomplete."));
2553 die (makefile_status);
2560 /* Parsing of arguments, decoding of switches. */
2562 static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
2563 static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
2564 (sizeof (long_option_aliases) /
2565 sizeof (long_option_aliases[0]))];
2567 /* Fill in the string and vector for getopt. */
2569 init_switches (void)
2575 if (options[0] != '\0')
2581 /* Return switch and non-switch args in order, regardless of
2582 POSIXLY_CORRECT. Non-switch args are returned as option 1. */
2585 for (i = 0; switches[i].c != '\0'; ++i)
2587 long_options[i].name = (switches[i].long_name == 0 ? "" :
2588 switches[i].long_name);
2589 long_options[i].flag = 0;
2590 long_options[i].val = switches[i].c;
2591 if (short_option (switches[i].c))
2592 *p++ = switches[i].c;
2593 switch (switches[i].type)
2598 long_options[i].has_arg = no_argument;
2605 if (short_option (switches[i].c))
2607 if (switches[i].noarg_value != 0)
2609 if (short_option (switches[i].c))
2611 long_options[i].has_arg = optional_argument;
2614 long_options[i].has_arg = required_argument;
2619 for (c = 0; c < (sizeof (long_option_aliases) /
2620 sizeof (long_option_aliases[0]));
2622 long_options[i++] = long_option_aliases[c];
2623 long_options[i].name = 0;
2627 /* Non-option argument. It might be a variable definition. */
2629 handle_non_switch_argument (char *arg, int env)
2633 if (arg[0] == '-' && arg[1] == '\0')
2634 /* Ignore plain '-' for compatibility. */
2637 v = try_variable_definition (0, arg, o_command, 0);
2640 /* It is indeed a variable definition. If we don't already have this
2641 one, record a pointer to the variable for later use in
2642 define_makeflags. */
2643 struct command_variable *cv;
2645 for (cv = command_variables; cv != 0; cv = cv->next)
2646 if (cv->variable == v)
2651 cv = xmalloc (sizeof (*cv));
2653 cv->next = command_variables;
2654 command_variables = cv;
2659 /* Not an option or variable definition; it must be a goal
2660 target! Enter it as a file and add it to the dep chain of
2662 struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
2667 goals = alloc_dep ();
2672 lastgoal->next = alloc_dep ();
2673 lastgoal = lastgoal->next;
2679 /* Add this target name to the MAKECMDGOALS variable. */
2680 struct variable *gv;
2683 gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
2688 /* Paste the old and new values together */
2689 unsigned int oldlen, newlen;
2692 oldlen = strlen (gv->value);
2693 newlen = strlen (f->name);
2694 vp = alloca (oldlen + 1 + newlen + 1);
2695 memcpy (vp, gv->value, oldlen);
2697 memcpy (&vp[oldlen + 1], f->name, newlen + 1);
2700 define_variable_cname ("MAKECMDGOALS", value, o_default, 0);
2705 /* Print a nice usage method. */
2708 print_usage (int bad)
2710 const char *const *cpp;
2713 if (print_version_flag)
2716 usageto = bad ? stderr : stdout;
2718 fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
2720 for (cpp = usage; *cpp; ++cpp)
2721 fputs (_(*cpp), usageto);
2723 if (!remote_description || *remote_description == '\0')
2724 fprintf (usageto, _("\nThis program built for %s\n"), make_host);
2726 fprintf (usageto, _("\nThis program built for %s (%s)\n"),
2727 make_host, remote_description);
2729 fprintf (usageto, _("Report bugs to <bug-make@gnu.org>\n"));
2732 /* Decode switches from ARGC and ARGV.
2733 They came from the environment if ENV is nonzero. */
2736 decode_switches (int argc, char **argv, int env)
2739 register const struct command_switch *cs;
2740 register struct stringlist *sl;
2743 /* getopt does most of the parsing for us.
2744 First, get its vectors set up. */
2748 /* Let getopt produce error messages for the command line,
2749 but not for options from the environment. */
2751 /* Reset getopt's state. */
2754 while (optind < argc)
2756 /* Parse the next argument. */
2757 c = getopt_long (argc, argv, options, long_options, (int *) 0);
2759 /* End of arguments, or "--" marker seen. */
2762 /* An argument not starting with a dash. */
2763 handle_non_switch_argument (optarg, env);
2765 /* Bad option. We will print a usage message and die later.
2766 But continue to parse the other options so the user can
2767 see all he did wrong. */
2770 for (cs = switches; cs->c != '\0'; ++cs)
2773 /* Whether or not we will actually do anything with
2774 this switch. We test this individually inside the
2775 switch below rather than just once outside it, so that
2776 options which are to be ignored still consume args. */
2777 int doit = !env || cs->env;
2790 *(int *) cs->value_ptr = cs->type == flag;
2799 optarg = xstrdup (cs->noarg_value);
2800 else if (*optarg == '\0')
2803 const char *op = opt;
2805 if (short_option (cs->c))
2810 error (NILF, _("the '%s%s' option requires a non-empty string argument"),
2811 short_option (cs->c) ? "-" : "--", op);
2815 sl = *(struct stringlist **) cs->value_ptr;
2818 sl = xmalloc (sizeof (struct stringlist));
2821 sl->list = xmalloc (5 * sizeof (char *));
2822 *(struct stringlist **) cs->value_ptr = sl;
2824 else if (sl->idx == sl->max - 1)
2827 /* MSVC erroneously warns without a cast here. */
2828 sl->list = xrealloc ((void *)sl->list,
2829 sl->max * sizeof (char *));
2831 if (cs->type == filename)
2832 sl->list[sl->idx++] = expand_command_line_file (optarg);
2834 sl->list[sl->idx++] = optarg;
2835 sl->list[sl->idx] = 0;
2839 /* See if we have an option argument; if we do require that
2840 it's all digits, not something like "10foo". */
2841 if (optarg == 0 && argc > optind)
2844 for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
2847 optarg = argv[optind++];
2855 int i = atoi (optarg);
2858 /* Yes, I realize we're repeating this in some cases. */
2859 for (cp = optarg; ISDIGIT (cp[0]); ++cp)
2862 if (i < 1 || cp[0] != '\0')
2864 error (NILF, _("the '-%c' option requires a positive integer argument"),
2869 *(unsigned int *) cs->value_ptr = i;
2872 *(unsigned int *) cs->value_ptr
2873 = *(unsigned int *) cs->noarg_value;
2878 if (optarg == 0 && optind < argc
2879 && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
2880 optarg = argv[optind++];
2883 *(double *) cs->value_ptr
2884 = (optarg != 0 ? atof (optarg)
2885 : *(double *) cs->noarg_value);
2891 /* We've found the switch. Stop looking. */
2896 /* There are no more options according to getting getopt, but there may
2897 be some arguments left. Since we have asked for non-option arguments
2898 to be returned in order, this only happens when there is a "--"
2899 argument to prevent later arguments from being options. */
2900 while (optind < argc)
2901 handle_non_switch_argument (argv[optind++], env);
2903 if (!env && (bad || print_usage_flag))
2909 /* If there are any options that need to be decoded do it now. */
2910 decode_debug_flags ();
2911 decode_output_sync_flags ();
2914 /* Decode switches from environment variable ENVAR (which is LEN chars long).
2915 We do this by chopping the value into a vector of words, prepending a
2916 dash to the first word if it lacks one, and passing the vector to
2920 decode_env_switches (char *envar, unsigned int len)
2922 char *varref = alloca (2 + len + 2);
2927 /* Get the variable's value. */
2930 memcpy (&varref[2], envar, len);
2931 varref[2 + len] = ')';
2932 varref[2 + len + 1] = '\0';
2933 value = variable_expand (varref);
2935 /* Skip whitespace, and check for an empty value. */
2936 value = next_token (value);
2937 len = strlen (value);
2941 /* Allocate a vector that is definitely big enough. */
2942 argv = alloca ((1 + len + 1) * sizeof (char *));
2944 /* Allocate a buffer to copy the value into while we split it into words
2945 and unquote it. We must use permanent storage for this because
2946 decode_switches may store pointers into the passed argument words. */
2947 p = xmalloc (2 * len);
2949 /* getopt will look at the arguments starting at ARGV[1].
2950 Prepend a spacer word. */
2954 while (*value != '\0')
2956 if (*value == '\\' && value[1] != '\0')
2957 ++value; /* Skip the backslash. */
2958 else if (isblank ((unsigned char)*value))
2960 /* End of the word. */
2965 while (isblank ((unsigned char)*value));
2973 if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
2974 /* The first word doesn't start with a dash and isn't a variable
2975 definition. Add a dash and pass it along to decode_switches. We
2976 need permanent storage for this in case decode_switches saves
2977 pointers into the value. */
2978 argv[1] = xstrdup (concat (2, "-", argv[1]));
2980 /* Parse those words. */
2981 decode_switches (argc, argv, 1);
2984 /* Quote the string IN so that it will be interpreted as a single word with
2985 no magic by decode_env_switches; also double dollar signs to avoid
2986 variable expansion in make itself. Write the result into OUT, returning
2987 the address of the next character to be written.
2988 Allocating space for OUT twice the length of IN is always sufficient. */
2991 quote_for_env (char *out, const char *in)
2997 else if (isblank ((unsigned char)*in) || *in == '\\')
3005 /* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
3006 command switches. Include options with args if ALL is nonzero.
3007 Don't include options with the 'no_makefile' flag set if MAKEFILE. */
3009 static struct variable *
3010 define_makeflags (int all, int makefile)
3012 const char ref[] = "$(MAKEOVERRIDES)";
3013 const char posixref[] = "$(-*-command-variables-*-)";
3014 const char evalref[] = "$(-*-eval-flags-*-)";
3015 const struct command_switch *cs;
3019 /* We will construct a linked list of 'struct flag's describing
3020 all the flags which need to go in MAKEFLAGS. Then, once we
3021 know how many there are and their lengths, we can put them all
3022 together in a string. */
3027 const struct command_switch *cs;
3030 struct flag *flags = 0;
3031 struct flag *last = 0;
3032 unsigned int flagslen = 0;
3033 #define ADD_FLAG(ARG, LEN) \
3035 struct flag *new = alloca (sizeof (struct flag)); \
3044 if (new->arg == 0) \
3045 /* Just a single flag letter: " -x" */ \
3048 /* " -xfoo", plus space to escape "foo". */ \
3049 flagslen += 1 + 1 + 1 + (3 * (LEN)); \
3050 if (!short_option (cs->c)) \
3051 /* This switch has no single-letter version, so we use the long. */ \
3052 flagslen += 2 + strlen (cs->long_name); \
3055 for (cs = switches; cs->c != '\0'; ++cs)
3056 if (cs->toenv && (!makefile || !cs->no_makefile))
3064 if (!*(int *) cs->value_ptr == (cs->type == flag_off)
3065 && (cs->default_value == 0
3066 || *(int *) cs->value_ptr != *(int *) cs->default_value))
3073 if ((cs->default_value != 0
3074 && (*(unsigned int *) cs->value_ptr
3075 == *(unsigned int *) cs->default_value)))
3077 else if (cs->noarg_value != 0
3078 && (*(unsigned int *) cs->value_ptr ==
3079 *(unsigned int *) cs->noarg_value))
3080 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3083 char *buf = alloca (30);
3084 sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3085 ADD_FLAG (buf, strlen (buf));
3094 if (cs->default_value != 0
3095 && (*(double *) cs->value_ptr
3096 == *(double *) cs->default_value))
3098 else if (cs->noarg_value != 0
3099 && (*(double *) cs->value_ptr
3100 == *(double *) cs->noarg_value))
3101 ADD_FLAG ("", 0); /* Optional value omitted; see below. */
3104 char *buf = alloca (100);
3105 sprintf (buf, "%g", *(double *) cs->value_ptr);
3106 ADD_FLAG (buf, strlen (buf));
3116 struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3120 for (i = 0; i < sl->idx; ++i)
3121 ADD_FLAG (sl->list[i], strlen (sl->list[i]));
3132 /* Four more for the possible " -- ", plus variable references. */
3133 flagslen += 4 + CSTRLEN (posixref) + 1 + CSTRLEN (evalref) + 1;
3135 /* Construct the value in FLAGSTRING.
3136 We allocate enough space for a preceding dash and trailing null. */
3137 flagstring = alloca (1 + flagslen + 1);
3138 memset (flagstring, '\0', 1 + flagslen + 1);
3141 /* Start with a dash, for MFLAGS. */
3144 /* Add simple options as a group. */
3145 while (flags != 0 && !flags->arg && short_option (flags->cs->c))
3147 *p++ = flags->cs->c;
3148 flags = flags->next;
3151 /* Now add more complex flags: ones with options and/or long names. */
3157 /* Add the flag letter or name to the string. */
3158 if (short_option (flags->cs->c))
3159 *p++ = flags->cs->c;
3162 /* Long options require a double-dash. */
3164 strcpy (p, flags->cs->long_name);
3167 /* An omitted optional argument has an ARG of "". */
3168 if (flags->arg && flags->arg[0] != '\0')
3170 if (!short_option (flags->cs->c))
3171 /* Long options require '='. */
3173 p = quote_for_env (p, flags->arg);
3175 flags = flags->next;
3178 /* If no flags at all, get rid of the initial dash. */
3179 if (p == &flagstring[1])
3181 flagstring[0] = '\0';
3185 /* Define MFLAGS before appending variable definitions. Omit an initial
3186 empty dash. Since MFLAGS is not parsed for flags, there is no reason to
3187 override any makefile redefinition. */
3188 define_variable_cname ("MFLAGS",
3189 flagstring + (flagstring[0] == '-' && flagstring[1] == ' ' ? 2 : 0),
3192 /* Write a reference to -*-eval-flags-*-, which contains all the --eval
3197 memcpy (p, evalref, CSTRLEN (evalref));
3198 p += CSTRLEN (evalref);
3201 if (all && command_variables)
3203 /* Write a reference to $(MAKEOVERRIDES), which contains all the
3204 command-line variable definitions. Separate the variables from the
3205 switches with a "--" arg. */
3210 /* Copy in the string. */
3213 memcpy (p, posixref, CSTRLEN (posixref));
3214 p += CSTRLEN (posixref);
3218 memcpy (p, ref, CSTRLEN (ref));
3223 /* If there is a leading dash, omit it. */
3224 if (flagstring[0] == '-')
3227 /* This used to use o_env, but that lost when a makefile defined MAKEFLAGS.
3228 Makefiles set MAKEFLAGS to add switches, but we still want to redefine
3229 its value with the full set of switches. Then we used o_file, but that
3230 lost when users added -e, causing a previous MAKEFLAGS env. var. to take
3231 precedence over the new one. Of course, an override or command
3232 definition will still take precedence. */
3233 return define_variable_cname ("MAKEFLAGS", flagstring,
3234 env_overrides ? o_env_override : o_file, 1);
3237 /* Print version information. */
3240 print_version (void)
3242 static int printed_version = 0;
3244 char *precede = print_data_base_flag ? "# " : "";
3246 if (printed_version)
3247 /* Do it only once. */
3250 printf ("%sGNU Make %s\n", precede, version_string);
3252 if (!remote_description || *remote_description == '\0')
3253 printf (_("%sBuilt for %s\n"), precede, make_host);
3255 printf (_("%sBuilt for %s (%s)\n"),
3256 precede, make_host, remote_description);
3258 /* Print this untranslated. The coding standards recommend translating the
3259 (C) to the copyright symbol, but this string is going to change every
3260 year, and none of the rest of it should be translated (including the
3261 word "Copyright"), so it hardly seems worth it. */
3263 printf ("%sCopyright (C) 1988-2013 Free Software Foundation, Inc.\n",
3266 printf (_("%sLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
3267 %sThis is free software: you are free to change and redistribute it.\n\
3268 %sThere is NO WARRANTY, to the extent permitted by law.\n"),
3269 precede, precede, precede);
3271 printed_version = 1;
3273 /* Flush stdout so the user doesn't have to wait to see the
3274 version information while make thinks about things. */
3278 /* Print a bunch of information about this and that. */
3283 time_t when = time ((time_t *) 0);
3287 printf (_("\n# Make data base, printed on %s"), ctime (&when));
3289 print_variable_data_base ();
3290 print_dir_data_base ();
3291 print_rule_data_base ();
3292 print_file_data_base ();
3293 print_vpath_data_base ();
3294 strcache_print_stats ("#");
3296 when = time ((time_t *) 0);
3297 printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
3301 clean_jobserver (int status)
3303 /* Sanity: have we written all our jobserver tokens back? If our
3304 exit status is 2 that means some kind of syntax error; we might not
3305 have written all our tokens so do that now. If tokens are left
3306 after any other error code, that's bad. */
3309 if (has_jobserver_semaphore () && jobserver_tokens)
3313 if (job_fds[0] != -1 && jobserver_tokens)
3318 "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3321 /* Don't write back the "free" token */
3322 while (--jobserver_tokens)
3325 if (! release_jobserver_semaphore ())
3326 perror_with_name ("release_jobserver_semaphore", "");
3330 EINTRLOOP (r, write (job_fds[1], &token, 1));
3332 perror_with_name ("write", "");
3338 /* Sanity: If we're the master, were all the tokens written back? */
3340 if (master_job_slots)
3342 /* We didn't write one for ourself, so start at 1. */
3343 unsigned int tcnt = 1;
3346 while (acquire_jobserver_semaphore ())
3349 /* Close the write side, so the read() won't hang. */
3352 while (read (job_fds[0], &token, 1) == 1)
3356 if (tcnt != master_job_slots)
3358 "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3359 tcnt, master_job_slots);
3362 free_jobserver_semaphore ();
3367 /* Clean out jobserver_fds so we don't pass this information to any
3368 sub-makes. Also reset job_slots since it will be put on the command
3369 line, not in MAKEFLAGS. */
3370 job_slots = default_job_slots;
3373 /* MSVC erroneously warns without a cast here. */
3374 free ((void *)jobserver_fds->list);
3375 free (jobserver_fds);
3381 /* Exit with STATUS, cleaning up as necessary. */
3386 static char dying = 0;
3394 if (print_version_flag)
3397 /* Wait for children to die. */
3398 err = (status != 0);
3399 while (job_slots_used > 0)
3400 reap_children (1, err);
3402 /* Let the remote job module clean up its state. */
3405 /* Remove the intermediate files. */
3406 remove_intermediates (0);
3408 if (print_data_base_flag)
3412 verify_file_data_base ();
3414 clean_jobserver (status);
3418 assert (output_context == &make_sync);
3420 output_close (&make_sync);
3423 output_close (NULL);
3425 /* Try to move back to the original directory. This is essential on
3426 MS-DOS (where there is really only one process), and on Unix it
3427 puts core files in the original directory instead of the -C
3428 directory. Must wait until after remove_intermediates(), or unlinks
3429 of relative pathnames fail. */
3430 if (directory_before_chdir != 0)
3432 /* If it fails we don't care: shut up GCC. */
3434 _x = chdir (directory_before_chdir);