Imported Upstream version 4.2.1
[platform/upstream/make.git] / main.c
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.
4
5 GNU Make is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
8 version.
9
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License along with
15 this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include "makeint.h"
18 #include "os.h"
19 #include "filedef.h"
20 #include "dep.h"
21 #include "variable.h"
22 #include "job.h"
23 #include "commands.h"
24 #include "rule.h"
25 #include "debug.h"
26 #include "getopt.h"
27
28 #include <assert.h>
29 #ifdef _AMIGA
30 # include <dos/dos.h>
31 # include <proto/dos.h>
32 #endif
33 #ifdef WINDOWS32
34 # include <windows.h>
35 # include <io.h>
36 # include "pathstuff.h"
37 # include "sub_proc.h"
38 # include "w32err.h"
39 #endif
40 #ifdef __EMX__
41 # include <sys/types.h>
42 # include <sys/wait.h>
43 #endif
44 #ifdef HAVE_FCNTL_H
45 # include <fcntl.h>
46 #endif
47
48 #ifdef _AMIGA
49 int __stack = 20000; /* Make sure we have 20K of stack space */
50 #endif
51 #ifdef VMS
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;
59
60 /* Evaluates if a VMS environment option is set, only look at first character */
61 static int
62 get_vms_env_flag (const char *name, int default_value)
63 {
64 char * value;
65 char x;
66
67   value = getenv (name);
68   if (value == NULL)
69     return default_value;
70
71   x = toupper (value[0]);
72   switch (x)
73     {
74     case '1':
75     case 'T':
76     case 'E':
77       return 1;
78       break;
79     case '0':
80     case 'F':
81     case 'D':
82       return 0;
83     }
84 }
85 #endif
86
87 #if defined HAVE_WAITPID || defined HAVE_WAIT3
88 # define HAVE_WAIT_NOHANG
89 #endif
90
91 #ifndef HAVE_UNISTD_H
92 int chdir ();
93 #endif
94 #ifndef STDC_HEADERS
95 # ifndef sun                    /* Sun has an incorrect decl in a header.  */
96 void exit (int) __attribute__ ((noreturn));
97 # endif
98 double atof ();
99 #endif
100
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);
109
110 \f
111 /* The structure that describes an accepted command switch.  */
112
113 struct command_switch
114   {
115     int c;                      /* The switch character.  */
116
117     enum                        /* Type of the value.  */
118       {
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.  */
127       } type;
128
129     void *value_ptr;    /* Pointer to the value-holding variable.  */
130
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.  */
134
135     const void *noarg_value;    /* Pointer to value used if no arg given.  */
136     const void *default_value;  /* Pointer to default value.  */
137
138     const char *long_name;      /* Long option name.  */
139   };
140
141 /* True if C is a switch value that corresponds to a short option.  */
142
143 #define short_option(c) ((c) <= CHAR_MAX)
144
145 /* The structure used to hold the list of strings given
146    in command switches of a type that takes strlist arguments.  */
147
148 struct stringlist
149   {
150     const char **list;  /* Nil-terminated list of strings.  */
151     unsigned int idx;   /* Index into above.  */
152     unsigned int max;   /* Number of pointers allocated.  */
153   };
154
155
156 /* The recognized command switches.  */
157
158 /* Nonzero means do extra verification (that may slow things down).  */
159
160 int verify_flag;
161
162 /* Nonzero means do not print commands to be executed (-s).  */
163
164 int silent_flag;
165
166 /* Nonzero means just touch the files
167    that would appear to need remaking (-t)  */
168
169 int touch_flag;
170
171 /* Nonzero means just print what commands would need to be executed,
172    don't actually execute them (-n).  */
173
174 int just_print_flag;
175
176 /* Print debugging info (--debug).  */
177
178 static struct stringlist *db_flags = 0;
179 static int debug_flag = 0;
180
181 int db_level = 0;
182
183 /* Synchronize output (--output-sync).  */
184
185 char *output_sync_option = 0;
186
187 #ifdef WINDOWS32
188 /* Suspend make in main for a short time to allow debugger to attach */
189
190 int suspend_flag = 0;
191 #endif
192
193 /* Environment variables override makefile definitions.  */
194
195 int env_overrides = 0;
196
197 /* Nonzero means ignore status codes returned by commands
198    executed to remake files.  Just treat them all as successful (-i).  */
199
200 int ignore_errors_flag = 0;
201
202 /* Nonzero means don't remake anything, just print the data base
203    that results from reading the makefile (-p).  */
204
205 int print_data_base_flag = 0;
206
207 /* Nonzero means don't remake anything; just return a nonzero status
208    if the specified targets are not up to date (-q).  */
209
210 int question_flag = 0;
211
212 /* Nonzero means do not use any of the builtin rules (-r) / variables (-R).  */
213
214 int no_builtin_rules_flag = 0;
215 int no_builtin_variables_flag = 0;
216
217 /* Nonzero means keep going even if remaking some file fails (-k).  */
218
219 int keep_going_flag;
220 int default_keep_going_flag = 0;
221
222 /* Nonzero means check symlink mtimes.  */
223
224 int check_symlink_flag = 0;
225
226 /* Nonzero means print directory before starting and when done (-w).  */
227
228 int print_directory_flag = 0;
229
230 /* Nonzero means ignore print_directory_flag and never print the directory.
231    This is necessary because print_directory_flag is set implicitly.  */
232
233 int inhibit_print_directory_flag = 0;
234
235 /* Nonzero means print version information.  */
236
237 int print_version_flag = 0;
238
239 /* List of makefiles given with -f switches.  */
240
241 static struct stringlist *makefiles = 0;
242
243 /* Size of the stack when we started.  */
244
245 #ifdef SET_STACK_SIZE
246 struct rlimit stack_limit;
247 #endif
248
249
250 /* Number of job slots for parallelism.  */
251
252 unsigned int job_slots;
253
254 #define INVALID_JOB_SLOTS (-1)
255 static unsigned int master_job_slots = 0;
256 static int arg_job_slots = INVALID_JOB_SLOTS;
257
258 static const int default_job_slots = INVALID_JOB_SLOTS;
259
260 /* Value of job_slots that means no limit.  */
261
262 static const int inf_jobs = 0;
263
264 /* Authorization for the jobserver.  */
265
266 static char *jobserver_auth = NULL;
267
268 /* Handle for the mutex used on Windows to synchronize output of our
269    children under -O.  */
270
271 char *sync_mutex = NULL;
272
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).  */
277 #ifndef NO_FLOAT
278 double max_load_average = -1.0;
279 double default_load_average = -1.0;
280 #else
281 int max_load_average = -1;
282 int default_load_average = -1;
283 #endif
284
285 /* List of directories given with -C switches.  */
286
287 static struct stringlist *directories = 0;
288
289 /* List of include directories given with -I switches.  */
290
291 static struct stringlist *include_directories = 0;
292
293 /* List of files given with -o switches.  */
294
295 static struct stringlist *old_files = 0;
296
297 /* List of files given with -W switches.  */
298
299 static struct stringlist *new_files = 0;
300
301 /* List of strings to be eval'd.  */
302 static struct stringlist *eval_strings = 0;
303
304 /* If nonzero, we should just print usage and exit.  */
305
306 static int print_usage_flag = 0;
307
308 /* If nonzero, we should print a warning message
309    for each reference to an undefined variable.  */
310
311 int warn_undefined_variables_flag;
312
313 /* If nonzero, always build all targets, regardless of whether
314    they appear out of date or not.  */
315
316 static int always_make_set = 0;
317 int always_make_flag = 0;
318
319 /* If nonzero, we're in the "try to rebuild makefiles" phase.  */
320
321 int rebuilding_makefiles = 0;
322
323 /* Remember the original value of the SHELL variable, from the environment.  */
324
325 struct variable shell_var;
326
327 /* This character introduces a command: it's the first char on the line.  */
328
329 char cmd_prefix = '\t';
330
331 \f
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.  */
335
336 static const char *const usage[] =
337   {
338     N_("Options:\n"),
339     N_("\
340   -b, -m                      Ignored for compatibility.\n"),
341     N_("\
342   -B, --always-make           Unconditionally make all targets.\n"),
343     N_("\
344   -C DIRECTORY, --directory=DIRECTORY\n\
345                               Change to DIRECTORY before doing anything.\n"),
346     N_("\
347   -d                          Print lots of debugging information.\n"),
348     N_("\
349   --debug[=FLAGS]             Print various types of debugging information.\n"),
350     N_("\
351   -e, --environment-overrides\n\
352                               Environment variables override makefiles.\n"),
353     N_("\
354   --eval=STRING               Evaluate STRING as a makefile statement.\n"),
355     N_("\
356   -f FILE, --file=FILE, --makefile=FILE\n\
357                               Read FILE as a makefile.\n"),
358     N_("\
359   -h, --help                  Print this message and exit.\n"),
360     N_("\
361   -i, --ignore-errors         Ignore errors from recipes.\n"),
362     N_("\
363   -I DIRECTORY, --include-dir=DIRECTORY\n\
364                               Search DIRECTORY for included makefiles.\n"),
365     N_("\
366   -j [N], --jobs[=N]          Allow N jobs at once; infinite jobs with no arg.\n"),
367     N_("\
368   -k, --keep-going            Keep going when some targets can't be made.\n"),
369     N_("\
370   -l [N], --load-average[=N], --max-load[=N]\n\
371                               Don't start multiple jobs unless load is below N.\n"),
372     N_("\
373   -L, --check-symlink-times   Use the latest mtime between symlinks and target.\n"),
374     N_("\
375   -n, --just-print, --dry-run, --recon\n\
376                               Don't actually run any recipe; just print them.\n"),
377     N_("\
378   -o FILE, --old-file=FILE, --assume-old=FILE\n\
379                               Consider FILE to be very old and don't remake it.\n"),
380     N_("\
381   -O[TYPE], --output-sync[=TYPE]\n\
382                               Synchronize output of parallel jobs by TYPE.\n"),
383     N_("\
384   -p, --print-data-base       Print make's internal database.\n"),
385     N_("\
386   -q, --question              Run no recipe; exit status says if up to date.\n"),
387     N_("\
388   -r, --no-builtin-rules      Disable the built-in implicit rules.\n"),
389     N_("\
390   -R, --no-builtin-variables  Disable the built-in variable settings.\n"),
391     N_("\
392   -s, --silent, --quiet       Don't echo recipes.\n"),
393     N_("\
394   -S, --no-keep-going, --stop\n\
395                               Turns off -k.\n"),
396     N_("\
397   -t, --touch                 Touch targets instead of remaking them.\n"),
398     N_("\
399   --trace                     Print tracing information.\n"),
400     N_("\
401   -v, --version               Print the version number of make and exit.\n"),
402     N_("\
403   -w, --print-directory       Print the current directory.\n"),
404     N_("\
405   --no-print-directory        Turn off -w, even if it was turned on implicitly.\n"),
406     N_("\
407   -W FILE, --what-if=FILE, --new-file=FILE, --assume-new=FILE\n\
408                               Consider FILE to be infinitely new.\n"),
409     N_("\
410   --warn-undefined-variables  Warn when an undefined variable is referenced.\n"),
411     NULL
412   };
413
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.  */
417
418 static const struct command_switch switches[] =
419   {
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 },
423 #ifdef WINDOWS32
424     { 'D', flag, &suspend_flag, 1, 1, 0, 0, 0, "suspend-for-debug" },
425 #endif
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,
430       "keep-going" },
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,
441       "no-keep-going" },
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" },
445
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,
450       "include-dir" },
451     { 'j', positive_int, &arg_job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,
452       "jobs" },
453 #ifndef NO_FLOAT
454     { 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,
455       &default_load_average, "load-average" },
456 #else
457     { 'l', positive_int, &max_load_average, 1, 1, 0, &default_load_average,
458       &default_load_average, "load-average" },
459 #endif
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" },
463
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 }
475   };
476
477 /* Secondary long names for options.  */
478
479 static struct option long_option_aliases[] =
480   {
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' },
490   };
491
492 /* List of goal targets.  */
493
494 static struct goaldep *goals, *lastgoal;
495
496 /* List of variables which were defined on the command line
497    (or, equivalently, in MAKEFLAGS).  */
498
499 struct command_variable
500   {
501     struct command_variable *next;
502     struct variable *variable;
503   };
504 static struct command_variable *command_variables;
505 \f
506 /* The name we were invoked with.  */
507
508 #ifdef WINDOWS32
509 /* On MS-Windows, we chop off the .exe suffix in 'main', so this
510    cannot be 'const'.  */
511 char *program;
512 #else
513 const char *program;
514 #endif
515
516 /* Our current directory before processing any -C options.  */
517
518 char *directory_before_chdir;
519
520 /* Our current directory after processing all -C options.  */
521
522 char *starting_directory;
523
524 /* Value of the MAKELEVEL variable at startup (or 0).  */
525
526 unsigned int makelevel;
527
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
532    with '.'.  */
533
534 struct variable * default_goal_var;
535
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.  */
539
540 struct file *default_file;
541
542 /* Nonzero if we have seen the magic '.POSIX' target.
543    This turns on pedantic compliance with POSIX.2.  */
544
545 int posix_pedantic;
546
547 /* Nonzero if we have seen the '.SECONDEXPANSION' target.
548    This turns on secondary expansion of prerequisites.  */
549
550 int second_expansion;
551
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.  */
555
556 int one_shell;
557
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.  */
561
562 int output_sync = OUTPUT_SYNC_NONE;
563
564 /* Nonzero if the "--trace" option was given.  */
565
566 int trace_flag = 0;
567
568 /* Nonzero if we have seen the '.NOTPARALLEL' target.
569    This turns off parallel builds for this invocation of make.  */
570
571 int not_parallel;
572
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. */
576
577 int clock_skew_detected;
578
579 /* Map of possible stop characters for searching strings.  */
580 #ifndef UCHAR_MAX
581 # define UCHAR_MAX 255
582 #endif
583 unsigned short stopchar_map[UCHAR_MAX + 1] = {0};
584
585 /* If output-sync is enabled we'll collect all the output generated due to
586    options, while reading makefiles, etc.  */
587
588 struct output make_sync;
589
590 \f
591 /* Mask of signals that are being caught with fatal_error_signal.  */
592
593 #ifdef POSIX
594 sigset_t fatal_signal_set;
595 #else
596 # ifdef HAVE_SIGSETMASK
597 int fatal_signal_mask;
598 # endif
599 #endif
600
601 #if !HAVE_DECL_BSD_SIGNAL && !defined bsd_signal
602 # if !defined HAVE_SIGACTION
603 #  define bsd_signal signal
604 # else
605 typedef RETSIGTYPE (*bsd_signal_ret_t) (int);
606
607 static bsd_signal_ret_t
608 bsd_signal (int sig, bsd_signal_ret_t func)
609 {
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)
616     return SIG_ERR;
617   return oact.sa_handler;
618 }
619 # endif
620 #endif
621
622 static void
623 initialize_global_hash_tables (void)
624 {
625   init_hash_global_variable_set ();
626   strcache_init ();
627   init_hash_files ();
628   hash_init_directories ();
629   hash_init_function_table ();
630 }
631
632 /* This character map locate stop chars when parsing GNU makefiles.
633    Each element is true if we should stop parsing on that character.  */
634
635 static void
636 initialize_stopchar_map (void)
637 {
638   int i;
639
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;
650
651   stopchar_map[(int)'-'] = MAP_USERFUNC;
652   stopchar_map[(int)'_'] = MAP_USERFUNC;
653
654   stopchar_map[(int)' '] = MAP_BLANK;
655   stopchar_map[(int)'\t'] = MAP_BLANK;
656
657   stopchar_map[(int)'/'] = MAP_DIRSEP;
658 #if defined(VMS)
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;
664 #endif
665
666   for (i = 1; i <= UCHAR_MAX; ++i)
667     {
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;
673     }
674 }
675
676 static const char *
677 expand_command_line_file (const char *name)
678 {
679   const char *cp;
680   char *expanded = 0;
681
682   if (name[0] == '\0')
683     O (fatal, NILF, _("empty string invalid as file name"));
684
685   if (name[0] == '~')
686     {
687       expanded = tilde_expand (name);
688       if (expanded && expanded[0] != '\0')
689         name = expanded;
690     }
691
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] == '/')
696     {
697       name += 2;
698       while (name[0] == '/')
699         /* Skip following slashes: ".//foo" is "foo", not "/foo".  */
700         ++name;
701     }
702
703   if (name[0] == '\0')
704     {
705       /* Nothing else but one or more "./", maybe plus slashes!  */
706       name = "./";
707     }
708
709   cp = strcache_add (name);
710
711   free (expanded);
712
713   return cp;
714 }
715
716 /* Toggle -d on receipt of SIGUSR1.  */
717
718 #ifdef SIGUSR1
719 static RETSIGTYPE
720 debug_signal_handler (int sig UNUSED)
721 {
722   db_level = db_level ? DB_NONE : DB_BASIC;
723 }
724 #endif
725
726 static void
727 decode_debug_flags (void)
728 {
729   const char **pp;
730
731   if (debug_flag)
732     db_level = DB_ALL;
733
734   if (db_flags)
735     for (pp=db_flags->list; *pp; ++pp)
736       {
737         const char *p = *pp;
738
739         while (1)
740           {
741             switch (tolower (p[0]))
742               {
743               case 'a':
744                 db_level |= DB_ALL;
745                 break;
746               case 'b':
747                 db_level |= DB_BASIC;
748                 break;
749               case 'i':
750                 db_level |= DB_BASIC | DB_IMPLICIT;
751                 break;
752               case 'j':
753                 db_level |= DB_JOBS;
754                 break;
755               case 'm':
756                 db_level |= DB_BASIC | DB_MAKEFILES;
757                 break;
758               case 'n':
759                 db_level = 0;
760                 break;
761               case 'v':
762                 db_level |= DB_BASIC | DB_VERBOSE;
763                 break;
764               default:
765                 OS (fatal, NILF,
766                     _("unknown debug level specification '%s'"), p);
767               }
768
769             while (*(++p) != '\0')
770               if (*p == ',' || *p == ' ')
771                 {
772                   ++p;
773                   break;
774                 }
775
776             if (*p == '\0')
777               break;
778           }
779       }
780
781   if (db_level)
782     verify_flag = 1;
783
784   if (! db_level)
785     debug_flag = 0;
786 }
787
788 static void
789 decode_output_sync_flags (void)
790 {
791 #ifdef NO_OUTPUT_SYNC
792   output_sync = OUTPUT_SYNC_NONE;
793 #else
794   if (output_sync_option)
795     {
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;
804       else
805         OS (fatal, NILF,
806             _("unknown output-sync type '%s'"), output_sync_option);
807     }
808
809   if (sync_mutex)
810     RECORD_SYNC_MUTEX (sync_mutex);
811 #endif
812 }
813
814 #ifdef WINDOWS32
815
816 #ifndef NO_OUTPUT_SYNC
817
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.  */
822 void
823 prepare_mutex_handle_string (sync_handle_t handle)
824 {
825   if (!sync_mutex)
826     {
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);
832     }
833 }
834
835 #endif  /* NO_OUTPUT_SYNC */
836
837 /*
838  * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
839  * exception and print it to stderr instead.
840  *
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.
845  */
846 LONG WINAPI
847 handle_runtime_exceptions (struct _EXCEPTION_POINTERS *exinfo)
848 {
849   PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
850   LPSTR cmdline = GetCommandLine ();
851   LPSTR prg = strtok (cmdline, " ");
852   CHAR errmsg[1024];
853 #ifdef USE_EVENT_LOG
854   HANDLE hEventSource;
855   LPTSTR lpszStrings[1];
856 #endif
857
858   if (! ISDB (DB_VERBOSE))
859     {
860       sprintf (errmsg,
861                _("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\n"),
862                prg, exrec->ExceptionCode, exrec->ExceptionAddress);
863       fprintf (stderr, errmsg);
864       exit (255);
865     }
866
867   sprintf (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);
871
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]);
879
880   /* turn this on if we want to put stuff in the event log too */
881 #ifdef USE_EVENT_LOG
882   hEventSource = RegisterEventSource (NULL, "GNU Make");
883   lpszStrings[0] = errmsg;
884
885   if (hEventSource != NULL)
886     {
887       ReportEvent (hEventSource,         /* handle of event source */
888                    EVENTLOG_ERROR_TYPE,  /* event type */
889                    0,                    /* event category */
890                    0,                    /* event ID */
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 */
896
897       (VOID) DeregisterEventSource (hEventSource);
898     }
899 #endif
900
901   /* Write the error to stderr too */
902   fprintf (stderr, errmsg);
903
904 #ifdef DEBUG
905   return EXCEPTION_CONTINUE_SEARCH;
906 #else
907   exit (255);
908   return (255); /* not reached */
909 #endif
910 }
911
912 /*
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).
918  */
919
920 int
921 find_and_set_default_shell (const char *token)
922 {
923   int sh_found = 0;
924   char *atoken = 0;
925   const char *search_token;
926   const char *tokend;
927   PATH_VAR(sh_path);
928   extern const char *default_shell;
929
930   if (!token)
931     search_token = default_shell;
932   else
933     search_token = atoken = xstrdup (token);
934
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")))
948     {
949       batch_mode_shell = 1;
950       unixy_shell = 0;
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"),
954                        default_shell));
955       sh_found = 1;
956     }
957   else if (!no_default_sh_exe
958            && (token == NULL || !strcmp (search_token, default_shell)))
959     {
960       /* no new information, path already set or known */
961       sh_found = 1;
962     }
963   else if (_access (search_token, 0) == 0)
964     {
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"),
969                        default_shell));
970       sh_found = 1;
971     }
972   else
973     {
974       char *p;
975       struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
976
977       /* Search Path for shell */
978       if (v && v->value)
979         {
980           char *ep;
981
982           p  = v->value;
983           ep = strchr (p, PATH_SEPARATOR_CHAR);
984
985           while (ep && *ep)
986             {
987               *ep = '\0';
988
989               sprintf (sh_path, "%s/%s", p, search_token);
990               if (_access (sh_path, 0) == 0)
991                 {
992                   default_shell = xstrdup (w32ify (sh_path, 0));
993                   sh_found = 1;
994                   *ep = PATH_SEPARATOR_CHAR;
995
996                   /* terminate loop */
997                   p += strlen (p);
998                 }
999               else
1000                 {
1001                   *ep = PATH_SEPARATOR_CHAR;
1002                   p = ++ep;
1003                 }
1004
1005               ep = strchr (p, PATH_SEPARATOR_CHAR);
1006             }
1007
1008           /* be sure to check last element of Path */
1009           if (p && *p)
1010             {
1011               sprintf (sh_path, "%s/%s", p, search_token);
1012               if (_access (sh_path, 0) == 0)
1013                 {
1014                   default_shell = xstrdup (w32ify (sh_path, 0));
1015                   sh_found = 1;
1016                 }
1017             }
1018
1019           if (sh_found)
1020             DB (DB_VERBOSE,
1021                 (_("find_and_set_shell() path search set default_shell = %s\n"),
1022                  default_shell));
1023         }
1024     }
1025
1026   /* naive test */
1027   if (!unixy_shell && sh_found
1028       && (strstr (default_shell, "sh") || strstr (default_shell, "SH")))
1029     {
1030       unixy_shell = 1;
1031       batch_mode_shell = 0;
1032     }
1033
1034 #ifdef BATCH_MODE_ONLY_SHELL
1035   batch_mode_shell = 1;
1036 #endif
1037
1038   free (atoken);
1039
1040   return (sh_found);
1041 }
1042 #endif  /* WINDOWS32 */
1043
1044 #ifdef __MSDOS__
1045 static void
1046 msdos_return_to_initial_directory (void)
1047 {
1048   if (directory_before_chdir)
1049     chdir (directory_before_chdir);
1050 }
1051 #endif  /* __MSDOS__ */
1052
1053 static void
1054 reset_jobserver (void)
1055 {
1056   jobserver_clear ();
1057   free (jobserver_auth);
1058   jobserver_auth = NULL;
1059 }
1060
1061 #ifdef _AMIGA
1062 int
1063 main (int argc, char **argv)
1064 #else
1065 int
1066 main (int argc, char **argv, char **envp)
1067 #endif
1068 {
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;
1075   int argv_slots;
1076 #ifdef WINDOWS32
1077   const char *unix_path = NULL;
1078   const char *windows32_path = NULL;
1079
1080   SetUnhandledExceptionFilter (handle_runtime_exceptions);
1081
1082   /* start off assuming we have no shell */
1083   unixy_shell = 0;
1084   no_default_sh_exe = 1;
1085 #endif
1086
1087   output_init (&make_sync);
1088
1089   initialize_stopchar_map();
1090
1091 #ifdef SET_STACK_SIZE
1092  /* Get rid of any avoidable limit on stack size.  */
1093   {
1094     struct rlimit rlim;
1095
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)
1099       {
1100         stack_limit = rlim;
1101         rlim.rlim_cur = rlim.rlim_max;
1102         setrlimit (RLIMIT_STACK, &rlim);
1103       }
1104     else
1105       stack_limit.rlim_cur = 0;
1106   }
1107 #endif
1108
1109   /* Needed for OS/2 */
1110   initialize_main (&argc, &argv);
1111
1112 #ifdef MAKE_MAINTAINER_MODE
1113   /* In maintainer mode we always enable verification.  */
1114   verify_flag = 1;
1115 #endif
1116
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);
1126
1127 #endif
1128
1129   /* Set up gettext/internationalization support.  */
1130   setlocale (LC_ALL, "");
1131   /* The cast to void shuts up compiler warnings on systems that
1132      disable NLS.  */
1133   (void)bindtextdomain (PACKAGE, LOCALEDIR);
1134   (void)textdomain (PACKAGE);
1135
1136 #ifdef  POSIX
1137   sigemptyset (&fatal_signal_set);
1138 #define ADD_SIG(sig)    sigaddset (&fatal_signal_set, sig)
1139 #else
1140 #ifdef  HAVE_SIGSETMASK
1141   fatal_signal_mask = 0;
1142 #define ADD_SIG(sig)    fatal_signal_mask |= sigmask (sig)
1143 #else
1144 #define ADD_SIG(sig)    (void)sig
1145 #endif
1146 #endif
1147
1148 #define FATAL_SIG(sig)                                                        \
1149   if (bsd_signal (sig, fatal_error_signal) == SIG_IGN)                        \
1150     bsd_signal (sig, SIG_IGN);                                                \
1151   else                                                                        \
1152     ADD_SIG (sig);
1153
1154 #ifdef SIGHUP
1155   FATAL_SIG (SIGHUP);
1156 #endif
1157 #ifdef SIGQUIT
1158   FATAL_SIG (SIGQUIT);
1159 #endif
1160   FATAL_SIG (SIGINT);
1161   FATAL_SIG (SIGTERM);
1162
1163 #ifdef __MSDOS__
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.  */
1167   FATAL_SIG (SIGFPE);
1168 #endif
1169
1170 #ifdef  SIGDANGER
1171   FATAL_SIG (SIGDANGER);
1172 #endif
1173 #ifdef SIGXCPU
1174   FATAL_SIG (SIGXCPU);
1175 #endif
1176 #ifdef SIGXFSZ
1177   FATAL_SIG (SIGXFSZ);
1178 #endif
1179
1180 #undef  FATAL_SIG
1181
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.  */
1186
1187 #ifdef HAVE_WAIT_NOHANG
1188 # if defined SIGCHLD
1189   (void) bsd_signal (SIGCHLD, SIG_DFL);
1190 # endif
1191 # if defined SIGCLD && SIGCLD != SIGCHLD
1192   (void) bsd_signal (SIGCLD, SIG_DFL);
1193 # endif
1194 #endif
1195
1196   output_init (NULL);
1197
1198   /* Figure out where this program lives.  */
1199
1200   if (argv[0] == 0)
1201     argv[0] = (char *)"";
1202   if (argv[0][0] == '\0')
1203     program = "make";
1204   else
1205     {
1206       program = strrchr (argv[0], '/');
1207 #if defined(__MSDOS__) || defined(__EMX__)
1208       if (program == 0)
1209         program = strrchr (argv[0], '\\');
1210       else
1211         {
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)
1216             program = p;
1217         }
1218       if (program == 0 && argv[0][1] == ':')
1219         program = argv[0] + 1;
1220 #endif
1221 #ifdef WINDOWS32
1222       if (program == 0)
1223         {
1224           /* Extract program from full path */
1225           program = strrchr (argv[0], '\\');
1226           if (program)
1227             {
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';
1232             }
1233         }
1234 #endif
1235 #ifdef VMS
1236       set_program_name (argv[0]);
1237       program = program_name;
1238       {
1239         const char *shell;
1240         char pwdbuf[256];
1241         char *pwd;
1242         shell = getenv ("SHELL");
1243         if (shell != NULL)
1244           vms_gnv_shell = 1;
1245
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);
1249         if (pwd[0] == '/')
1250           vms_report_unix_paths = 1;
1251
1252         vms_use_mcr_command = get_vms_env_flag ("GNV$MAKE_USE_MCR", 0);
1253
1254         vms_always_use_cmd_file = get_vms_env_flag ("GNV$MAKE_USE_CMD_FILE", 0);
1255
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",
1262                                                 !vms_gnv_shell);
1263
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);
1269
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);
1277
1278       }
1279       if (need_vms_symbol () && !vms_use_mcr_command)
1280         create_foreign_command (program_name, argv[0]);
1281 #else
1282       if (program == 0)
1283         program = argv[0];
1284       else
1285         ++program;
1286 #endif
1287     }
1288
1289   /* Set up to access user data (files).  */
1290   user_access ();
1291
1292   initialize_global_hash_tables ();
1293
1294   /* Figure out where we are.  */
1295
1296 #ifdef WINDOWS32
1297   if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1298 #else
1299   if (getcwd (current_directory, GET_PATH_MAX) == 0)
1300 #endif
1301     {
1302 #ifdef  HAVE_GETCWD
1303       perror_with_name ("getcwd", "");
1304 #else
1305       OS (error, NILF, "getwd: %s", current_directory);
1306 #endif
1307       current_directory[0] = '\0';
1308       directory_before_chdir = 0;
1309     }
1310   else
1311     directory_before_chdir = xstrdup (current_directory);
1312
1313 #ifdef  __MSDOS__
1314   /* Make sure we will return to the initial directory, come what may.  */
1315   atexit (msdos_return_to_initial_directory);
1316 #endif
1317
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);
1324
1325   /* Set up .FEATURES
1326      Use a separate variable because define_variable_cname() is a macro and
1327      some compilers (MSVC) don't like conditionals in macros.  */
1328   {
1329     const char *features = "target-specific order-only second-expansion"
1330                            " else-if shortest-stem undefine oneshell"
1331 #ifndef NO_ARCHIVES
1332                            " archives"
1333 #endif
1334 #ifdef MAKE_JOBSERVER
1335                            " jobserver"
1336 #endif
1337 #ifndef NO_OUTPUT_SYNC
1338                            " output-sync"
1339 #endif
1340 #ifdef MAKE_SYMLINKS
1341                            " check-symlink"
1342 #endif
1343 #ifdef HAVE_GUILE
1344                            " guile"
1345 #endif
1346 #ifdef MAKE_LOAD
1347                            " load"
1348 #endif
1349                            ;
1350
1351     define_variable_cname (".FEATURES", features, o_default, 0);
1352   }
1353
1354   /* Configure GNU Guile support */
1355   guile_gmake_setup (NILF);
1356
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.  */
1360
1361 #ifndef _AMIGA
1362   {
1363     unsigned int i;
1364
1365     for (i = 0; envp[i] != 0; ++i)
1366       {
1367         struct variable *v;
1368         const char *ep = envp[i];
1369         /* By default, export all variables culled from the environment.  */
1370         enum variable_export export = v_export;
1371         unsigned int len;
1372
1373         while (! STOP_SET (*ep, MAP_EQUALS))
1374           ++ep;
1375
1376         /* If there's no equals sign it's a malformed environment.  Ignore.  */
1377         if (*ep == '\0')
1378           continue;
1379
1380 #ifdef WINDOWS32
1381         if (!unix_path && strneq (envp[i], "PATH=", 5))
1382           unix_path = ep+1;
1383         else if (!strnicmp (envp[i], "Path=", 5))
1384           {
1385             if (!windows32_path)
1386               windows32_path = ep+1;
1387             /* PATH gets defined after the loop exits.  */
1388             continue;
1389           }
1390 #endif
1391
1392         /* Length of the variable name, and skip the '='.  */
1393         len = ep++ - envp[i];
1394
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))
1398           {
1399             if (*ep == '-')
1400               {
1401                 OUTPUT_TRACED ();
1402                 ++ep;
1403               }
1404             restarts = (unsigned int) atoi (ep);
1405             export = v_noexport;
1406           }
1407
1408         v = define_variable (envp[i], len, ep, o_env, 1);
1409
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"))
1413           {
1414 #ifndef __MSDOS__
1415             export = v_noexport;
1416 #endif
1417             shell_var.name = xstrdup ("SHELL");
1418             shell_var.length = 5;
1419             shell_var.value = xstrdup (ep);
1420           }
1421
1422         v->export = export;
1423       }
1424   }
1425 #ifdef WINDOWS32
1426     /* If we didn't find a correctly spelled PATH we define PATH as
1427      * either the first misspelled value or an empty string
1428      */
1429     if (!unix_path)
1430       define_variable_cname ("PATH", windows32_path ? windows32_path : "",
1431                              o_env, 1)->export = v_export;
1432 #endif
1433 #else /* For Amiga, read the ENV: device, ignoring all dirs */
1434     {
1435         BPTR env, file, old;
1436         char buffer[1024];
1437         int len;
1438         __aligned struct FileInfoBlock fib;
1439
1440         env = Lock ("ENV:", ACCESS_READ);
1441         if (env)
1442           {
1443             old = CurrentDir (DupLock (env));
1444             Examine (env, &fib);
1445
1446             while (ExNext (env, &fib))
1447               {
1448                 if (fib.fib_DirEntryType < 0) /* File */
1449                   {
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;
1455                   }
1456               }
1457             UnLock (env);
1458             UnLock (CurrentDir (old));
1459           }
1460     }
1461 #endif
1462
1463   /* Decode the switches.  */
1464   decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
1465
1466   /* Clear GNUMAKEFLAGS to avoid duplication.  */
1467   define_variable_cname ("GNUMAKEFLAGS", "", o_env, 0);
1468
1469   decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
1470
1471 #if 0
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"));
1476 #endif
1477
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.  */
1480
1481   syncing = make_sync.syncout = (output_sync == OUTPUT_SYNC_LINE
1482                                  || output_sync == OUTPUT_SYNC_TARGET);
1483   OUTPUT_SET (&make_sync);
1484
1485   /* Remember the job slots set through the environment vs. command line.  */
1486   {
1487     int env_slots = arg_job_slots;
1488     arg_job_slots = INVALID_JOB_SLOTS;
1489
1490     decode_switches (argc, (const char **)argv, 0);
1491     argv_slots = arg_job_slots;
1492
1493     if (arg_job_slots == INVALID_JOB_SLOTS)
1494       arg_job_slots = env_slots;
1495   }
1496
1497   /* Set a variable specifying whether stdout/stdin is hooked to a TTY.  */
1498 #ifdef HAVE_ISATTY
1499   if (isatty (fileno (stdout)))
1500     if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMOUT")))
1501       {
1502         const char *tty = TTYNAME (fileno (stdout));
1503         define_variable_cname ("MAKE_TERMOUT", tty ? tty : DEFAULT_TTYNAME,
1504                                o_default, 0)->export = v_export;
1505       }
1506   if (isatty (fileno (stderr)))
1507     if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMERR")))
1508       {
1509         const char *tty = TTYNAME (fileno (stderr));
1510         define_variable_cname ("MAKE_TERMERR", tty ? tty : DEFAULT_TTYNAME,
1511                                o_default, 0)->export = v_export;
1512       }
1513 #endif
1514
1515   /* Reset in case the switches changed our minds.  */
1516   syncing = (output_sync == OUTPUT_SYNC_LINE
1517              || output_sync == OUTPUT_SYNC_TARGET);
1518
1519   if (make_sync.syncout && ! syncing)
1520     output_close (&make_sync);
1521
1522   make_sync.syncout = syncing;
1523   OUTPUT_SET (&make_sync);
1524
1525   /* Figure out the level of recursion.  */
1526   {
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);
1530     else
1531       makelevel = 0;
1532   }
1533
1534 #ifdef WINDOWS32
1535   if (suspend_flag)
1536     {
1537       fprintf (stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId ());
1538       fprintf (stderr, _("%s is suspending for 30 seconds..."), argv[0]);
1539       Sleep (30 * 1000);
1540       fprintf (stderr, _("done sleep(30). Continuing.\n"));
1541     }
1542 #endif
1543
1544   /* Set always_make_flag if -B was given and we've not restarted already.  */
1545   always_make_flag = always_make_set && (restarts == 0);
1546
1547   /* Print version information, and exit.  */
1548   if (print_version_flag)
1549     {
1550       print_version ();
1551       die (MAKE_SUCCESS);
1552     }
1553
1554   if (ISDB (DB_BASIC))
1555     print_version ();
1556
1557 #ifndef VMS
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.)  */
1563 #ifdef WINDOWS32
1564   /*
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
1568    * CreateProcess().
1569    */
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], '\\'))
1576     {
1577       char *p;
1578
1579       argv[0] = xstrdup (argv[0]);
1580       for (p = argv[0]; *p; p++)
1581         if (*p == '\\')
1582           *p = '/';
1583     }
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'
1588       && argv[0] != 0
1589       && (argv[0][0] != '/' && (argv[0][0] == '\0' || argv[0][1] != ':'))
1590 # ifdef __EMX__
1591       /* do not prepend cwd if argv[0] contains no '/', e.g. "make" */
1592       && (strchr (argv[0], '/') != 0 || strchr (argv[0], '\\') != 0)
1593 # endif
1594       )
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
1602 #endif
1603       )
1604     argv[0] = xstrdup (concat (3, current_directory, "/", argv[0]));
1605 #endif /* !__MSDOS__ */
1606 #endif /* WINDOWS32 */
1607 #endif
1608
1609   /* We may move, but until we do, here we are.  */
1610   starting_directory = current_directory;
1611
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.  */
1615
1616   if (jobserver_auth)
1617     {
1618       if (argv_slots == INVALID_JOB_SLOTS)
1619         {
1620           if (jobserver_parse_auth (jobserver_auth))
1621             {
1622               /* Success!  Use the jobserver.  */
1623               job_slots = 0;
1624               goto job_setup_complete;
1625             }
1626
1627           O (error, NILF, _("warning: jobserver unavailable: using -j1.  Add '+' to parent make rule."));
1628           arg_job_slots = 1;
1629         }
1630
1631       /* The user provided a -j setting on the command line: use it.  */
1632       else if (!restarts)
1633         /* If restarts is >0 we already printed this message.  */
1634         O (error, NILF,
1635            _("warning: -jN forced in submake: disabling jobserver mode."));
1636
1637       /* We failed to use our parent's jobserver.  */
1638       reset_jobserver ();
1639       job_slots = (unsigned int)arg_job_slots;
1640     }
1641   else if (arg_job_slots == INVALID_JOB_SLOTS)
1642     /* The default is one job at a time.  */
1643     job_slots = 1;
1644   else
1645     /* Use whatever was provided.  */
1646     job_slots = (unsigned int)arg_job_slots;
1647
1648  job_setup_complete:
1649
1650   /* The extra indirection through $(MAKE_COMMAND) is done
1651      for hysterical raisins.  */
1652
1653 #ifdef VMS
1654   if (vms_use_mcr_command)
1655     define_variable_cname ("MAKE_COMMAND", vms_command (argv[0]), o_default, 0);
1656   else
1657     define_variable_cname ("MAKE_COMMAND", program, o_default, 0);
1658 #else
1659   define_variable_cname ("MAKE_COMMAND", argv[0], o_default, 0);
1660 #endif
1661   define_variable_cname ("MAKE", "$(MAKE_COMMAND)", o_default, 1);
1662
1663   if (command_variables != 0)
1664     {
1665       struct command_variable *cv;
1666       struct variable *v;
1667       unsigned int len = 0;
1668       char *value, *p;
1669
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)
1673         {
1674           v = cv->variable;
1675           len += 2 * strlen (v->name);
1676           if (! v->recursive)
1677             ++len;
1678           ++len;
1679           len += 2 * strlen (v->value);
1680           ++len;
1681         }
1682
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)
1686         {
1687           v = cv->variable;
1688           p = quote_for_env (p, v->name);
1689           if (! v->recursive)
1690             *p++ = ':';
1691           *p++ = '=';
1692           p = quote_for_env (p, v->value);
1693           *p++ = ' ';
1694         }
1695       p[-1] = '\0';             /* Kill the final space and terminate.  */
1696
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);
1700
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-*-}",
1708                              o_env, 1);
1709 #ifdef VMS
1710       vms_export_dcl_symbol ("MAKEOVERRIDES", "${-*-command-variables-*-}");
1711 #endif
1712     }
1713
1714   /* If there were -C flags, move ourselves about.  */
1715   if (directories != 0)
1716     {
1717       unsigned int i;
1718       for (i = 0; directories->list[i] != 0; ++i)
1719         {
1720           const char *dir = directories->list[i];
1721 #ifdef WINDOWS32
1722           /* WINDOWS32 chdir() doesn't work if the directory has a trailing '/'
1723              But allow -C/ just in case someone wants that.  */
1724           {
1725             char *p = (char *)dir + strlen (dir) - 1;
1726             while (p > dir && (p[0] == '/' || p[0] == '\\'))
1727               --p;
1728             p[1] = '\0';
1729           }
1730 #endif
1731           if (chdir (dir) < 0)
1732             pfatal_with_name (dir);
1733         }
1734     }
1735
1736 #ifdef WINDOWS32
1737   /*
1738    * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
1739    * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
1740    *
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.
1745    */
1746    no_default_sh_exe = !find_and_set_default_shell (NULL);
1747 #endif /* WINDOWS32 */
1748
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;
1752
1753   /* Let the user disable that with --no-print-directory.  */
1754   if (inhibit_print_directory_flag)
1755     print_directory_flag = 0;
1756
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;
1760
1761   /* Construct the list of include directories to search.  */
1762
1763   construct_include_path (include_directories == 0
1764                           ? 0 : include_directories->list);
1765
1766   /* If we chdir'ed, figure out where we are now.  */
1767   if (directories)
1768     {
1769 #ifdef WINDOWS32
1770       if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
1771 #else
1772       if (getcwd (current_directory, GET_PATH_MAX) == 0)
1773 #endif
1774         {
1775 #ifdef  HAVE_GETCWD
1776           perror_with_name ("getcwd", "");
1777 #else
1778           OS (error, NILF, "getwd: %s", current_directory);
1779 #endif
1780           starting_directory = 0;
1781         }
1782       else
1783         starting_directory = current_directory;
1784     }
1785
1786   define_variable_cname ("CURDIR", current_directory, o_file, 0);
1787
1788   /* Read any stdin makefiles into temporary files.  */
1789
1790   if (makefiles != 0)
1791     {
1792       unsigned int i;
1793       for (i = 0; i < makefiles->idx; ++i)
1794         if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
1795           {
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.  */
1799             FILE *outfile;
1800             char *template;
1801             const char *tmpdir;
1802
1803             if (stdin_nm)
1804               O (fatal, NILF,
1805                  _("Makefile from standard input specified twice."));
1806
1807 #ifdef VMS
1808 # define DEFAULT_TMPDIR     "/sys$scratch/"
1809 #else
1810 # ifdef P_tmpdir
1811 #  define DEFAULT_TMPDIR    P_tmpdir
1812 # else
1813 #  define DEFAULT_TMPDIR    "/tmp"
1814 # endif
1815 #endif
1816 #define DEFAULT_TMPFILE     "GmXXXXXX"
1817
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')
1823 #endif
1824                )
1825               tmpdir = DEFAULT_TMPDIR;
1826
1827             template = alloca (strlen (tmpdir) + CSTRLEN (DEFAULT_TMPFILE) + 2);
1828             strcpy (template, tmpdir);
1829
1830 #ifdef HAVE_DOS_PATHS
1831             if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
1832               strcat (template, "/");
1833 #else
1834 # ifndef VMS
1835             if (template[strlen (template) - 1] != '/')
1836               strcat (template, "/");
1837 # endif /* !VMS */
1838 #endif /* !HAVE_DOS_PATHS */
1839
1840             strcat (template, DEFAULT_TMPFILE);
1841             outfile = output_tmpfile (&stdin_nm, template);
1842             if (outfile == 0)
1843               pfatal_with_name (_("fopen (temporary file)"));
1844             while (!feof (stdin) && ! ferror (stdin))
1845               {
1846                 char buf[2048];
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)"));
1850               }
1851             fclose (outfile);
1852
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);
1856
1857             /* Make sure the temporary file will not be remade.  */
1858             {
1859               struct file *f = enter_file (strcache_add (stdin_nm));
1860               f->updated = 1;
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
1864                  make re-exec.  */
1865               f->intermediate = 0;
1866               f->dontcare = 0;
1867             }
1868           }
1869     }
1870
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.
1875
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
1878      children.
1879
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.
1883
1884      If none of these are true, we don't need a signal handler at all.  */
1885   {
1886 # if defined SIGCHLD
1887     bsd_signal (SIGCHLD, child_handler);
1888 # endif
1889 # if defined SIGCLD && SIGCLD != SIGCHLD
1890     bsd_signal (SIGCLD, child_handler);
1891 # endif
1892   }
1893
1894 #ifdef HAVE_PSELECT
1895   /* If we have pselect() then we need to block SIGCHLD so it's deferred.  */
1896   {
1897     sigset_t block;
1898     sigemptyset (&block);
1899     sigaddset (&block, SIGCHLD);
1900     if (sigprocmask (SIG_SETMASK, &block, NULL) < 0)
1901       pfatal_with_name ("sigprocmask(SIG_SETMASK, SIGCHLD)");
1902   }
1903 #endif
1904
1905 #endif
1906 #endif
1907
1908   /* Let the user send us SIGUSR1 to toggle the -d flag during the run.  */
1909 #ifdef SIGUSR1
1910   bsd_signal (SIGUSR1, debug_signal_handler);
1911 #endif
1912
1913   /* Define the initial list of suffixes for old-style rules.  */
1914   set_default_suffixes ();
1915
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 ();
1922
1923   /* Define some internal and special variables.  */
1924   define_automatic_variables ();
1925
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;
1929
1930   /* Define the default variables.  */
1931   define_default_variables ();
1932
1933   default_file = enter_file (strcache_add (".DEFAULT"));
1934
1935   default_goal_var = define_variable_cname (".DEFAULT_GOAL", "", o_file, 0);
1936
1937   /* Evaluate all strings provided with --eval.
1938      Also set up the $(-*-eval-flags-*-) variable.  */
1939
1940   if (eval_strings)
1941     {
1942       char *p, *value;
1943       unsigned int i;
1944       unsigned int len = (CSTRLEN ("--eval=") + 1) * eval_strings->idx;
1945
1946       for (i = 0; i < eval_strings->idx; ++i)
1947         {
1948           p = xstrdup (eval_strings->list[i]);
1949           len += 2 * strlen (p);
1950           eval_buffer (p, NULL);
1951           free (p);
1952         }
1953
1954       p = value = alloca (len);
1955       for (i = 0; i < eval_strings->idx; ++i)
1956         {
1957           strcpy (p, "--eval=");
1958           p += CSTRLEN ("--eval=");
1959           p = quote_for_env (p, eval_strings->list[i]);
1960           *(p++) = ' ';
1961         }
1962       p[-1] = '\0';
1963
1964       define_variable_cname ("-*-eval-flags-*-", value, o_automatic, 0);
1965     }
1966
1967   /* Read all the makefiles.  */
1968
1969   read_files = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
1970
1971 #ifdef WINDOWS32
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 */
1976
1977 #if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
1978   /* We need to know what kind of shell we will be using.  */
1979   {
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;
1984
1985     if (shv && *shv->value)
1986       {
1987         char *shell_path = recursively_expand (shv);
1988
1989         if (shell_path && _is_unixy_shell (shell_path))
1990           unixy_shell = 1;
1991         else
1992           unixy_shell = 0;
1993         if (shell_path)
1994           default_shell = shell_path;
1995       }
1996   }
1997 #endif /* __MSDOS__ || __EMX__ */
1998
1999   {
2000     int old_builtin_rules_flag = no_builtin_rules_flag;
2001     int old_builtin_variables_flag = no_builtin_variables_flag;
2002
2003     /* Decode switches again, for variables set by the makefile.  */
2004     decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
2005
2006     /* Clear GNUMAKEFLAGS to avoid duplication.  */
2007     define_variable_cname ("GNUMAKEFLAGS", "", o_override, 0);
2008
2009     decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
2010 #if 0
2011     decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
2012 #endif
2013
2014     /* Reset in case the switches changed our mind.  */
2015     syncing = (output_sync == OUTPUT_SYNC_LINE
2016                || output_sync == OUTPUT_SYNC_TARGET);
2017
2018     if (make_sync.syncout && ! syncing)
2019       output_close (&make_sync);
2020
2021     make_sync.syncout = syncing;
2022     OUTPUT_SET (&make_sync);
2023
2024     /* If we've disabled builtin rules, get rid of them.  */
2025     if (no_builtin_rules_flag && ! old_builtin_rules_flag)
2026       {
2027         if (suffix_file->builtin)
2028           {
2029             free_dep_chain (suffix_file->deps);
2030             suffix_file->deps = 0;
2031           }
2032         define_variable_cname ("SUFFIXES", "", o_default, 0);
2033       }
2034
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 ();
2038   }
2039
2040 #if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
2041   if (arg_job_slots != 1
2042 # ifdef __EMX__
2043       && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
2044 # endif
2045       )
2046     {
2047       O (error, NILF,
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;
2051     }
2052 #endif
2053
2054   /* If we have >1 slot at this point, then we're a top-level make.
2055      Set up the jobserver.
2056
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.  */
2060
2061   if (job_slots > 1 && jobserver_setup (job_slots - 1))
2062     {
2063       /* Fill in the jobserver_auth for our children.  */
2064       jobserver_auth = jobserver_get_auth ();
2065
2066       if (jobserver_auth)
2067         {
2068           /* We're using the jobserver so set job_slots to 0.  */
2069           master_job_slots = job_slots;
2070           job_slots = 0;
2071         }
2072     }
2073
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)
2078     {
2079       OUTPUT_UNSET ();
2080       output_close (&make_sync);
2081       syncing = 0;
2082       output_sync = OUTPUT_SYNC_NONE;
2083     }
2084
2085 #ifndef MAKE_SYMLINKS
2086   if (check_symlink_flag)
2087     {
2088       O (error, NILF, _("Symbolic links not supported: disabling -L."));
2089       check_symlink_flag = 0;
2090     }
2091 #endif
2092
2093   /* Set up MAKEFLAGS and MFLAGS again, so they will be right.  */
2094
2095   define_makeflags (1, 0);
2096
2097   /* Make each 'struct goaldep' point at the 'struct file' for the file
2098      depended on.  Also do magic for special targets.  */
2099
2100   snap_deps ();
2101
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
2105      rules.  */
2106
2107   convert_to_pattern ();
2108
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.  */
2113
2114   install_default_implicit_rules ();
2115
2116   /* Compute implicit rule limits.  */
2117
2118   count_implicit_rule_limits ();
2119
2120   /* Construct the listings of directories in VPATH lists.  */
2121
2122   build_vpath_lists ();
2123
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.  */
2127
2128   if (old_files != 0)
2129     {
2130       const char **p;
2131       for (p = old_files->list; *p != 0; ++p)
2132         {
2133           struct file *f = enter_file (*p);
2134           f->last_mtime = f->mtime_before_update = OLD_MTIME;
2135           f->updated = 1;
2136           f->update_status = us_success;
2137           f->command_state = cs_finished;
2138         }
2139     }
2140
2141   if (!restarts && new_files != 0)
2142     {
2143       const char **p;
2144       for (p = new_files->list; *p != 0; ++p)
2145         {
2146           struct file *f = enter_file (*p);
2147           f->last_mtime = f->mtime_before_update = NEW_MTIME;
2148         }
2149     }
2150
2151   /* Initialize the remote job module.  */
2152   remote_setup ();
2153
2154   /* Dump any output we've collected.  */
2155
2156   OUTPUT_UNSET ();
2157   output_close (&make_sync);
2158
2159   if (read_files != 0)
2160     {
2161       /* Update any makefiles if necessary.  */
2162
2163       FILE_TIMESTAMP *makefile_mtimes = 0;
2164       unsigned int mm_idx = 0;
2165       char **aargv = NULL;
2166       const char **nargv;
2167       int nargc;
2168       enum update_status status;
2169
2170       DB (DB_BASIC, (_("Updating makefiles....\n")));
2171
2172       /* Remove any makefiles we don't want to try to update.
2173          Also record the current modtimes so we can compare them later.  */
2174       {
2175         register struct goaldep *d, *last;
2176         last = 0;
2177         d = read_files;
2178         while (d != 0)
2179           {
2180             struct file *f = d->file;
2181             if (f->double_colon)
2182               for (f = f->double_colon; f != NULL; f = f->prev)
2183                 {
2184                   if (f->deps == 0 && f->cmds != 0)
2185                     {
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.)  */
2193
2194                       DB (DB_VERBOSE,
2195                           (_("Makefile '%s' might loop; not remaking it.\n"),
2196                            f->name));
2197
2198                       if (last == 0)
2199                         read_files = d->next;
2200                       else
2201                         last->next = d->next;
2202
2203                       /* Free the storage.  */
2204                       free_goaldep (d);
2205
2206                       d = last == 0 ? read_files : last->next;
2207
2208                       break;
2209                     }
2210                 }
2211
2212             if (f == NULL || !f->double_colon)
2213               {
2214                 makefile_mtimes = xrealloc (makefile_mtimes,
2215                                             (mm_idx+1)
2216                                             * sizeof (FILE_TIMESTAMP));
2217                 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
2218                 last = d;
2219                 d = d->next;
2220               }
2221           }
2222       }
2223
2224       /* Set up 'MAKEFLAGS' specially while remaking makefiles.  */
2225       define_makeflags (1, 1);
2226
2227       {
2228         int orig_db_level = db_level;
2229
2230         if (! ISDB (DB_MAKEFILES))
2231           db_level = DB_NONE;
2232
2233         rebuilding_makefiles = 1;
2234         status = update_goal_chain (read_files);
2235         rebuilding_makefiles = 0;
2236
2237         db_level = orig_db_level;
2238       }
2239
2240       switch (status)
2241         {
2242         case us_question:
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".  */
2247
2248         case us_none:
2249           /* Did nothing.  */
2250           break;
2251
2252         case us_failed:
2253           /* Failed to update.  Figure out if we care.  */
2254           {
2255             /* Nonzero if any makefile was successfully remade.  */
2256             int any_remade = 0;
2257             /* Nonzero if any makefile we care about failed
2258                in updating or could not be found at all.  */
2259             int any_failed = 0;
2260             unsigned int i;
2261             struct goaldep *d;
2262
2263             for (i = 0, d = read_files; d != 0; ++i, d = d->next)
2264               {
2265                 if (d->file->updated)
2266                   {
2267                     /* This makefile was updated.  */
2268                     if (d->file->update_status == us_success)
2269                       {
2270                         /* It was successfully updated.  */
2271                         any_remade |= (file_mtime_no_search (d->file)
2272                                        != makefile_mtimes[i]);
2273                       }
2274                     else if (! (d->flags & RM_DONTCARE))
2275                       {
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'."),
2280                             d->file->name);
2281                         mtime = file_mtime_no_search (d->file);
2282                         any_remade |= (mtime != NONEXISTENT_MTIME
2283                                        && mtime != makefile_mtimes[i]);
2284                         makefile_status = MAKE_FAILURE;
2285                       }
2286                   }
2287                 else
2288                   /* This makefile was not found at all.  */
2289                   if (! (d->flags & RM_DONTCARE))
2290                     {
2291                       const char *dnm = dep_name (d);
2292                       size_t l = strlen (dnm);
2293
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.  */
2298                         error (NILF, l,
2299                                _("Included makefile '%s' was not found."), dnm);
2300                       else
2301                         {
2302                           /* A normal makefile.  We must die later.  */
2303                           error (NILF, l,
2304                                  _("Makefile '%s' was not found"), dnm);
2305                           any_failed = 1;
2306                         }
2307                     }
2308               }
2309             /* Reset this to empty so we get the right error message below.  */
2310             read_files = 0;
2311
2312             if (any_remade)
2313               goto re_exec;
2314             if (any_failed)
2315               die (MAKE_FAILURE);
2316             break;
2317           }
2318
2319         case us_success:
2320         re_exec:
2321           /* Updated successfully.  Re-exec ourselves.  */
2322
2323           remove_intermediates (0);
2324
2325           if (print_data_base_flag)
2326             print_data_base ();
2327
2328           clean_jobserver (0);
2329
2330           if (makefiles != 0)
2331             {
2332               /* These names might have changed.  */
2333               int i, j = 0;
2334               for (i = 1; i < argc; ++i)
2335                 if (strneq (argv[i], "-f", 2)) /* XXX */
2336                   {
2337                     if (argv[i][2] == '\0')
2338                       /* This cast is OK since we never modify argv.  */
2339                       argv[++i] = (char *) makefiles->list[j];
2340                     else
2341                       argv[i] = xstrdup (concat (2, "-f", makefiles->list[j]));
2342                     ++j;
2343                   }
2344             }
2345
2346           /* Add -o option for the stdin temporary file, if necessary.  */
2347           nargc = argc;
2348           if (stdin_nm)
2349             {
2350               void *m = xmalloc ((nargc + 2) * sizeof (char *));
2351               aargv = m;
2352               memcpy (aargv, argv, argc * sizeof (char *));
2353               aargv[nargc++] = xstrdup (concat (2, "-o", stdin_nm));
2354               aargv[nargc] = 0;
2355               nargv = m;
2356             }
2357           else
2358             nargv = (const char**)argv;
2359
2360           if (directories != 0 && directories->idx > 0)
2361             {
2362               int bad = 1;
2363               if (directory_before_chdir != 0)
2364                 {
2365                   if (chdir (directory_before_chdir) < 0)
2366                       perror_with_name ("chdir", "");
2367                   else
2368                     bad = 0;
2369                 }
2370               if (bad)
2371                 O (fatal, NILF,
2372                    _("Couldn't change back to original directory."));
2373             }
2374
2375           ++restarts;
2376
2377           if (ISDB (DB_BASIC))
2378             {
2379               const char **p;
2380               printf (_("Re-executing[%u]:"), restarts);
2381               for (p = nargv; *p != 0; ++p)
2382                 printf (" %s", *p);
2383               putchar ('\n');
2384               fflush (stdout);
2385             }
2386
2387 #ifndef _AMIGA
2388           {
2389             char **p;
2390             for (p = environ; *p != 0; ++p)
2391               {
2392                 if (strneq (*p, MAKELEVEL_NAME "=", MAKELEVEL_LENGTH+1))
2393                   {
2394                     *p = alloca (40);
2395                     sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
2396 #ifdef VMS
2397                     vms_putenv_symbol (*p);
2398 #endif
2399                   }
2400                 else if (strneq (*p, "MAKE_RESTARTS=", CSTRLEN ("MAKE_RESTARTS=")))
2401                   {
2402                     *p = alloca (40);
2403                     sprintf (*p, "MAKE_RESTARTS=%s%u",
2404                              OUTPUT_IS_TRACED () ? "-" : "", restarts);
2405                     restarts = 0;
2406                   }
2407               }
2408           }
2409 #else /* AMIGA */
2410           {
2411             char buffer[256];
2412
2413             sprintf (buffer, "%u", makelevel);
2414             SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
2415
2416             sprintf (buffer, "%s%u", OUTPUT_IS_TRACED () ? "-" : "", restarts);
2417             SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
2418             restarts = 0;
2419           }
2420 #endif
2421
2422           /* If we didn't set the restarts variable yet, add it.  */
2423           if (restarts)
2424             {
2425               char *b = alloca (40);
2426               sprintf (b, "MAKE_RESTARTS=%s%u",
2427                        OUTPUT_IS_TRACED () ? "-" : "", restarts);
2428               putenv (b);
2429             }
2430
2431           fflush (stdout);
2432           fflush (stderr);
2433
2434 #ifdef _AMIGA
2435           exec_command (nargv);
2436           exit (0);
2437 #elif defined (__EMX__)
2438           {
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
2444                termination. */
2445             int pid;
2446             int r;
2447             pid = child_execute_job (NULL, 1, nargv, environ);
2448
2449             /* is this loop really necessary? */
2450             do {
2451               pid = wait (&r);
2452             } while (pid <= 0);
2453             /* use the exit code of the child process */
2454             exit (WIFEXITED(r) ? WEXITSTATUS(r) : EXIT_FAILURE);
2455           }
2456 #else
2457 #ifdef SET_STACK_SIZE
2458           /* Reset limits, if necessary.  */
2459           if (stack_limit.rlim_cur)
2460             setrlimit (RLIMIT_STACK, &stack_limit);
2461 #endif
2462           exec_command ((char **)nargv, environ);
2463 #endif
2464           free (aargv);
2465           break;
2466         }
2467
2468       /* Free the makefile mtimes.  */
2469       free (makefile_mtimes);
2470     }
2471
2472   /* Set up 'MAKEFLAGS' again for the normal targets.  */
2473   define_makeflags (1, 0);
2474
2475   /* Set always_make_flag if -B was given.  */
2476   always_make_flag = always_make_set;
2477
2478   /* If restarts is set we haven't set up -W files yet, so do that now.  */
2479   if (restarts && new_files != 0)
2480     {
2481       const char **p;
2482       for (p = new_files->list; *p != 0; ++p)
2483         {
2484           struct file *f = enter_file (*p);
2485           f->last_mtime = f->mtime_before_update = NEW_MTIME;
2486         }
2487     }
2488
2489   /* If there is a temp file from reading a makefile from stdin, get rid of
2490      it now.  */
2491   if (stdin_nm && unlink (stdin_nm) < 0 && errno != ENOENT)
2492     perror_with_name (_("unlink (temporary file): "), stdin_nm);
2493
2494   /* If there were no command-line goals, use the default.  */
2495   if (goals == 0)
2496     {
2497       char *p;
2498
2499       if (default_goal_var->recursive)
2500         p = variable_expand (default_goal_var->value);
2501       else
2502         {
2503           p = variable_buffer_output (variable_buffer, default_goal_var->value,
2504                                       strlen (default_goal_var->value));
2505           *p = '\0';
2506           p = variable_buffer;
2507         }
2508
2509       if (*p != '\0')
2510         {
2511           struct file *f = lookup_file (p);
2512
2513           /* If .DEFAULT_GOAL is a non-existent target, enter it into the
2514              table and let the standard logic sort it out. */
2515           if (f == 0)
2516             {
2517               struct nameseq *ns;
2518
2519               ns = PARSE_SIMPLE_SEQ (&p, struct nameseq);
2520               if (ns)
2521                 {
2522                   /* .DEFAULT_GOAL should contain one target. */
2523                   if (ns->next != 0)
2524                     O (fatal, NILF,
2525                        _(".DEFAULT_GOAL contains more than one target"));
2526
2527                   f = enter_file (strcache_add (ns->name));
2528
2529                   ns->name = 0; /* It was reused by enter_file(). */
2530                   free_ns_chain (ns);
2531                 }
2532             }
2533
2534           if (f)
2535             {
2536               goals = alloc_goaldep ();
2537               goals->file = f;
2538             }
2539         }
2540     }
2541   else
2542     lastgoal->next = 0;
2543
2544
2545   if (!goals)
2546     {
2547       if (read_files == 0)
2548         O (fatal, NILF, _("No targets specified and no makefile found"));
2549
2550       O (fatal, NILF, _("No targets"));
2551     }
2552
2553   /* Update the goals.  */
2554
2555   DB (DB_BASIC, (_("Updating goal targets....\n")));
2556
2557   {
2558     switch (update_goal_chain (goals))
2559     {
2560       case us_none:
2561         /* Nothing happened.  */
2562         /* FALLTHROUGH */
2563       case us_success:
2564         /* Keep the previous result.  */
2565         break;
2566       case us_question:
2567         /* We are under -q and would run some commands.  */
2568         makefile_status = MAKE_TROUBLE;
2569         break;
2570       case us_failed:
2571         /* Updating failed.  POSIX.2 specifies exit status >1 for this; */
2572         makefile_status = MAKE_FAILURE;
2573         break;
2574     }
2575
2576     /* If we detected some clock skew, generate one last warning */
2577     if (clock_skew_detected)
2578       O (error, NILF,
2579          _("warning:  Clock skew detected.  Your build may be incomplete."));
2580
2581     /* Exit.  */
2582     die (makefile_status);
2583   }
2584
2585   /* NOTREACHED */
2586   exit (MAKE_SUCCESS);
2587 }
2588 \f
2589 /* Parsing of arguments, decoding of switches.  */
2590
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]))];
2595
2596 /* Fill in the string and vector for getopt.  */
2597 static void
2598 init_switches (void)
2599 {
2600   char *p;
2601   unsigned int c;
2602   unsigned int i;
2603
2604   if (options[0] != '\0')
2605     /* Already done.  */
2606     return;
2607
2608   p = options;
2609
2610   /* Return switch and non-switch args in order, regardless of
2611      POSIXLY_CORRECT.  Non-switch args are returned as option 1.  */
2612   *p++ = '-';
2613
2614   for (i = 0; switches[i].c != '\0'; ++i)
2615     {
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)
2623         {
2624         case flag:
2625         case flag_off:
2626         case ignore:
2627           long_options[i].has_arg = no_argument;
2628           break;
2629
2630         case string:
2631         case strlist:
2632         case filename:
2633         case positive_int:
2634         case floating:
2635           if (short_option (switches[i].c))
2636             *p++ = ':';
2637           if (switches[i].noarg_value != 0)
2638             {
2639               if (short_option (switches[i].c))
2640                 *p++ = ':';
2641               long_options[i].has_arg = optional_argument;
2642             }
2643           else
2644             long_options[i].has_arg = required_argument;
2645           break;
2646         }
2647     }
2648   *p = '\0';
2649   for (c = 0; c < (sizeof (long_option_aliases) /
2650                    sizeof (long_option_aliases[0]));
2651        ++c)
2652     long_options[i++] = long_option_aliases[c];
2653   long_options[i].name = 0;
2654 }
2655
2656
2657 /* Non-option argument.  It might be a variable definition.  */
2658 static void
2659 handle_non_switch_argument (const char *arg, int env)
2660 {
2661   struct variable *v;
2662
2663   if (arg[0] == '-' && arg[1] == '\0')
2664     /* Ignore plain '-' for compatibility.  */
2665     return;
2666
2667 #ifdef VMS
2668   {
2669     /* VMS DCL quoting can result in foo="bar baz" showing up here.
2670        Need to remove the double quotes from the value. */
2671     char * eq_ptr;
2672     char * new_arg;
2673     eq_ptr = strchr (arg, '=');
2674     if ((eq_ptr != NULL) && (eq_ptr[1] == '"'))
2675       {
2676          int len;
2677          int seg1;
2678          int seg2;
2679          len = strlen(arg);
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;
2688          arg = new_arg;
2689       }
2690   }
2691 #endif
2692   v = try_variable_definition (0, arg, o_command, 0);
2693   if (v != 0)
2694     {
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;
2699
2700       for (cv = command_variables; cv != 0; cv = cv->next)
2701         if (cv->variable == v)
2702           break;
2703
2704       if (! cv)
2705         {
2706           cv = xmalloc (sizeof (*cv));
2707           cv->variable = v;
2708           cv->next = command_variables;
2709           command_variables = cv;
2710         }
2711     }
2712   else if (! env)
2713     {
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
2716          goals.  */
2717       struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
2718       f->cmd_target = 1;
2719
2720       if (goals == 0)
2721         {
2722           goals = alloc_goaldep ();
2723           lastgoal = goals;
2724         }
2725       else
2726         {
2727           lastgoal->next = alloc_goaldep ();
2728           lastgoal = lastgoal->next;
2729         }
2730
2731       lastgoal->file = f;
2732
2733       {
2734         /* Add this target name to the MAKECMDGOALS variable. */
2735         struct variable *gv;
2736         const char *value;
2737
2738         gv = lookup_variable (STRING_SIZE_TUPLE ("MAKECMDGOALS"));
2739         if (gv == 0)
2740           value = f->name;
2741         else
2742           {
2743             /* Paste the old and new values together */
2744             unsigned int oldlen, newlen;
2745             char *vp;
2746
2747             oldlen = strlen (gv->value);
2748             newlen = strlen (f->name);
2749             vp = alloca (oldlen + 1 + newlen + 1);
2750             memcpy (vp, gv->value, oldlen);
2751             vp[oldlen] = ' ';
2752             memcpy (&vp[oldlen + 1], f->name, newlen + 1);
2753             value = vp;
2754           }
2755         define_variable_cname ("MAKECMDGOALS", value, o_default, 0);
2756       }
2757     }
2758 }
2759
2760 /* Print a nice usage method.  */
2761
2762 static void
2763 print_usage (int bad)
2764 {
2765   const char *const *cpp;
2766   FILE *usageto;
2767
2768   if (print_version_flag)
2769     print_version ();
2770
2771   usageto = bad ? stderr : stdout;
2772
2773   fprintf (usageto, _("Usage: %s [options] [target] ...\n"), program);
2774
2775   for (cpp = usage; *cpp; ++cpp)
2776     fputs (_(*cpp), usageto);
2777
2778   if (!remote_description || *remote_description == '\0')
2779     fprintf (usageto, _("\nThis program built for %s\n"), make_host);
2780   else
2781     fprintf (usageto, _("\nThis program built for %s (%s)\n"),
2782              make_host, remote_description);
2783
2784   fprintf (usageto, _("Report bugs to <bug-make@gnu.org>\n"));
2785 }
2786
2787 /* Decode switches from ARGC and ARGV.
2788    They came from the environment if ENV is nonzero.  */
2789
2790 static void
2791 decode_switches (int argc, const char **argv, int env)
2792 {
2793   int bad = 0;
2794   register const struct command_switch *cs;
2795   register struct stringlist *sl;
2796   register int c;
2797
2798   /* getopt does most of the parsing for us.
2799      First, get its vectors set up.  */
2800
2801   init_switches ();
2802
2803   /* Let getopt produce error messages for the command line,
2804      but not for options from the environment.  */
2805   opterr = !env;
2806   /* Reset getopt's state.  */
2807   optind = 0;
2808
2809   while (optind < argc)
2810     {
2811       const char *coptarg;
2812
2813       /* Parse the next argument.  */
2814       c = getopt_long (argc, (char*const*)argv, options, long_options, NULL);
2815       coptarg = optarg;
2816       if (c == EOF)
2817         /* End of arguments, or "--" marker seen.  */
2818         break;
2819       else if (c == 1)
2820         /* An argument not starting with a dash.  */
2821         handle_non_switch_argument (coptarg, env);
2822       else if (c == '?')
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.  */
2826         bad = 1;
2827       else
2828         for (cs = switches; cs->c != '\0'; ++cs)
2829           if (cs->c == c)
2830             {
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;
2836
2837               switch (cs->type)
2838                 {
2839                 default:
2840                   abort ();
2841
2842                 case ignore:
2843                   break;
2844
2845                 case flag:
2846                 case flag_off:
2847                   if (doit)
2848                     *(int *) cs->value_ptr = cs->type == flag;
2849                   break;
2850
2851                 case string:
2852                 case strlist:
2853                 case filename:
2854                   if (!doit)
2855                     break;
2856
2857                   if (! coptarg)
2858                     coptarg = xstrdup (cs->noarg_value);
2859                   else if (*coptarg == '\0')
2860                     {
2861                       char opt[2] = "c";
2862                       const char *op = opt;
2863
2864                       if (short_option (cs->c))
2865                         opt[0] = cs->c;
2866                       else
2867                         op = cs->long_name;
2868
2869                       error (NILF, strlen (op),
2870                              _("the '%s%s' option requires a non-empty string argument"),
2871                              short_option (cs->c) ? "-" : "--", op);
2872                       bad = 1;
2873                       break;
2874                     }
2875
2876                   if (cs->type == string)
2877                     {
2878                       char **val = (char **)cs->value_ptr;
2879                       free (*val);
2880                       *val = xstrdup (coptarg);
2881                       break;
2882                     }
2883
2884                   sl = *(struct stringlist **) cs->value_ptr;
2885                   if (sl == 0)
2886                     {
2887                       sl = xmalloc (sizeof (struct stringlist));
2888                       sl->max = 5;
2889                       sl->idx = 0;
2890                       sl->list = xmalloc (5 * sizeof (char *));
2891                       *(struct stringlist **) cs->value_ptr = sl;
2892                     }
2893                   else if (sl->idx == sl->max - 1)
2894                     {
2895                       sl->max += 5;
2896                       /* MSVC erroneously warns without a cast here.  */
2897                       sl->list = xrealloc ((void *)sl->list,
2898                                            sl->max * sizeof (char *));
2899                     }
2900                   if (cs->type == filename)
2901                     sl->list[sl->idx++] = expand_command_line_file (coptarg);
2902                   else
2903                     sl->list[sl->idx++] = xstrdup (coptarg);
2904                   sl->list[sl->idx] = 0;
2905                   break;
2906
2907                 case positive_int:
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)
2911                     {
2912                       const char *cp;
2913                       for (cp=argv[optind]; ISDIGIT (cp[0]); ++cp)
2914                         ;
2915                       if (cp[0] == '\0')
2916                         coptarg = argv[optind++];
2917                     }
2918
2919                   if (!doit)
2920                     break;
2921
2922                   if (coptarg)
2923                     {
2924                       int i = atoi (coptarg);
2925                       const char *cp;
2926
2927                       /* Yes, I realize we're repeating this in some cases.  */
2928                       for (cp = coptarg; ISDIGIT (cp[0]); ++cp)
2929                         ;
2930
2931                       if (i < 1 || cp[0] != '\0')
2932                         {
2933                           error (NILF, 0,
2934                                  _("the '-%c' option requires a positive integer argument"),
2935                                  cs->c);
2936                           bad = 1;
2937                         }
2938                       else
2939                         *(unsigned int *) cs->value_ptr = i;
2940                     }
2941                   else
2942                     *(unsigned int *) cs->value_ptr
2943                       = *(unsigned int *) cs->noarg_value;
2944                   break;
2945
2946 #ifndef NO_FLOAT
2947                 case floating:
2948                   if (coptarg == 0 && optind < argc
2949                       && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
2950                     coptarg = argv[optind++];
2951
2952                   if (doit)
2953                     *(double *) cs->value_ptr
2954                       = (coptarg != 0 ? atof (coptarg)
2955                          : *(double *) cs->noarg_value);
2956
2957                   break;
2958 #endif
2959                 }
2960
2961               /* We've found the switch.  Stop looking.  */
2962               break;
2963             }
2964     }
2965
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);
2972
2973   if (!env && (bad || print_usage_flag))
2974     {
2975       print_usage (bad);
2976       die (bad ? MAKE_FAILURE : MAKE_SUCCESS);
2977     }
2978
2979   /* If there are any options that need to be decoded do it now.  */
2980   decode_debug_flags ();
2981   decode_output_sync_flags ();
2982 }
2983
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
2987    decode_switches.  */
2988
2989 static void
2990 decode_env_switches (const char *envar, unsigned int len)
2991 {
2992   char *varref = alloca (2 + len + 2);
2993   char *value, *p, *buf;
2994   int argc;
2995   const char **argv;
2996
2997   /* Get the variable's value.  */
2998   varref[0] = '$';
2999   varref[1] = '(';
3000   memcpy (&varref[2], envar, len);
3001   varref[2 + len] = ')';
3002   varref[2 + len + 1] = '\0';
3003   value = variable_expand (varref);
3004
3005   /* Skip whitespace, and check for an empty value.  */
3006   NEXT_TOKEN (value);
3007   len = strlen (value);
3008   if (len == 0)
3009     return;
3010
3011   /* Allocate a vector that is definitely big enough.  */
3012   argv = alloca ((1 + len + 1) * sizeof (char *));
3013
3014   /* getopt will look at the arguments starting at ARGV[1].
3015      Prepend a spacer word.  */
3016   argv[0] = 0;
3017   argc = 1;
3018
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);
3022   buf[0] = '-';
3023   p = buf+1;
3024   argv[argc] = p;
3025   while (*value != '\0')
3026     {
3027       if (*value == '\\' && value[1] != '\0')
3028         ++value;                /* Skip the backslash.  */
3029       else if (ISBLANK (*value))
3030         {
3031           /* End of the word.  */
3032           *p++ = '\0';
3033           argv[++argc] = p;
3034           do
3035             ++value;
3036           while (ISBLANK (*value));
3037           continue;
3038         }
3039       *p++ = *value++;
3040     }
3041   *p = '\0';
3042   argv[++argc] = 0;
3043   assert (p < buf + len + 2);
3044
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.  */
3048     argv[1] = buf;
3049
3050   /* Parse those words.  */
3051   decode_switches (argc, argv, 1);
3052 }
3053 \f
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.  */
3059
3060 static char *
3061 quote_for_env (char *out, const char *in)
3062 {
3063   while (*in != '\0')
3064     {
3065       if (*in == '$')
3066         *out++ = '$';
3067       else if (ISBLANK (*in) || *in == '\\')
3068         *out++ = '\\';
3069       *out++ = *in++;
3070     }
3071
3072   return out;
3073 }
3074
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.  */
3078
3079 static struct variable *
3080 define_makeflags (int all, int makefile)
3081 {
3082   const char ref[] = "$(MAKEOVERRIDES)";
3083   const char posixref[] = "$(-*-command-variables-*-)";
3084   const char evalref[] = "$(-*-eval-flags-*-)";
3085   const struct command_switch *cs;
3086   char *flagstring;
3087   char *p;
3088
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.  */
3093
3094   struct flag
3095     {
3096       struct flag *next;
3097       const struct command_switch *cs;
3098       const char *arg;
3099     };
3100   struct flag *flags = 0;
3101   struct flag *last = 0;
3102   unsigned int flagslen = 0;
3103 #define ADD_FLAG(ARG, LEN) \
3104   do {                                                                        \
3105     struct flag *new = alloca (sizeof (struct flag));                         \
3106     new->cs = cs;                                                             \
3107     new->arg = (ARG);                                                         \
3108     new->next = 0;                                                            \
3109     if (! flags)                                                              \
3110       flags = new;                                                            \
3111     else                                                                      \
3112       last->next = new;                                                       \
3113     last = new;                                                               \
3114     if (new->arg == 0)                                                        \
3115       /* Just a single flag letter: " -x"  */                                 \
3116       flagslen += 3;                                                          \
3117     else                                                                      \
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);                                 \
3123   } while (0)
3124
3125   for (cs = switches; cs->c != '\0'; ++cs)
3126     if (cs->toenv && (!makefile || !cs->no_makefile))
3127       switch (cs->type)
3128         {
3129         case ignore:
3130           break;
3131
3132         case flag:
3133         case flag_off:
3134           if ((!*(int *) cs->value_ptr) == (cs->type == flag_off)
3135               && (cs->default_value == 0
3136                   || *(int *) cs->value_ptr != *(int *) cs->default_value))
3137             ADD_FLAG (0, 0);
3138           break;
3139
3140         case positive_int:
3141           if (all)
3142             {
3143               if ((cs->default_value != 0
3144                    && (*(unsigned int *) cs->value_ptr
3145                        == *(unsigned int *) cs->default_value)))
3146                 break;
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.  */
3151               else
3152                 {
3153                   char *buf = alloca (30);
3154                   sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
3155                   ADD_FLAG (buf, strlen (buf));
3156                 }
3157             }
3158           break;
3159
3160 #ifndef NO_FLOAT
3161         case floating:
3162           if (all)
3163             {
3164               if (cs->default_value != 0
3165                   && (*(double *) cs->value_ptr
3166                       == *(double *) cs->default_value))
3167                 break;
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.  */
3172               else
3173                 {
3174                   char *buf = alloca (100);
3175                   sprintf (buf, "%g", *(double *) cs->value_ptr);
3176                   ADD_FLAG (buf, strlen (buf));
3177                 }
3178             }
3179           break;
3180 #endif
3181
3182         case string:
3183           if (all)
3184             {
3185               p = *((char **)cs->value_ptr);
3186               if (p)
3187                 ADD_FLAG (p, strlen (p));
3188             }
3189           break;
3190
3191         case filename:
3192         case strlist:
3193           if (all)
3194             {
3195               struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
3196               if (sl != 0)
3197                 {
3198                   unsigned int i;
3199                   for (i = 0; i < sl->idx; ++i)
3200                     ADD_FLAG (sl->list[i], strlen (sl->list[i]));
3201                 }
3202             }
3203           break;
3204
3205         default:
3206           abort ();
3207         }
3208
3209 #undef  ADD_FLAG
3210
3211   /* Four more for the possible " -- ", plus variable references.  */
3212   flagslen += 4 + CSTRLEN (posixref) + 1 + CSTRLEN (evalref) + 1;
3213
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);
3218   p = flagstring;
3219
3220   /* Start with a dash, for MFLAGS.  */
3221   *p++ = '-';
3222
3223   /* Add simple options as a group.  */
3224   while (flags != 0 && !flags->arg && short_option (flags->cs->c))
3225     {
3226       *p++ = flags->cs->c;
3227       flags = flags->next;
3228     }
3229
3230   /* Now add more complex flags: ones with options and/or long names.  */
3231   while (flags)
3232     {
3233       *p++ = ' ';
3234       *p++ = '-';
3235
3236       /* Add the flag letter or name to the string.  */
3237       if (short_option (flags->cs->c))
3238         *p++ = flags->cs->c;
3239       else
3240         {
3241           /* Long options require a double-dash.  */
3242           *p++ = '-';
3243           strcpy (p, flags->cs->long_name);
3244           p += strlen (p);
3245         }
3246       /* An omitted optional argument has an ARG of "".  */
3247       if (flags->arg && flags->arg[0] != '\0')
3248         {
3249           if (!short_option (flags->cs->c))
3250             /* Long options require '='.  */
3251             *p++ = '=';
3252           p = quote_for_env (p, flags->arg);
3253         }
3254       flags = flags->next;
3255     }
3256
3257   /* If no flags at all, get rid of the initial dash.  */
3258   if (p == &flagstring[1])
3259     {
3260       flagstring[0] = '\0';
3261       p = flagstring;
3262     }
3263
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),
3269                          o_env, 1);
3270
3271   /* Write a reference to -*-eval-flags-*-, which contains all the --eval
3272      flag options.  */
3273   if (eval_strings)
3274     {
3275       *p++ = ' ';
3276       memcpy (p, evalref, CSTRLEN (evalref));
3277       p += CSTRLEN (evalref);
3278     }
3279
3280   if (all && command_variables)
3281     {
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.  */
3285
3286       strcpy (p, " -- ");
3287       p += 4;
3288
3289       /* Copy in the string.  */
3290       if (posix_pedantic)
3291         {
3292           memcpy (p, posixref, CSTRLEN (posixref));
3293           p += CSTRLEN (posixref);
3294         }
3295       else
3296         {
3297           memcpy (p, ref, CSTRLEN (ref));
3298           p += CSTRLEN (ref);
3299         }
3300     }
3301
3302   /* If there is a leading dash, omit it.  */
3303   if (flagstring[0] == '-')
3304     ++flagstring;
3305
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);
3314 }
3315 \f
3316 /* Print version information.  */
3317
3318 static void
3319 print_version (void)
3320 {
3321   static int printed_version = 0;
3322
3323   const char *precede = print_data_base_flag ? "# " : "";
3324
3325   if (printed_version)
3326     /* Do it only once.  */
3327     return;
3328
3329   printf ("%sGNU Make %s\n", precede, version_string);
3330
3331   if (!remote_description || *remote_description == '\0')
3332     printf (_("%sBuilt for %s\n"), precede, make_host);
3333   else
3334     printf (_("%sBuilt for %s (%s)\n"),
3335             precede, make_host, remote_description);
3336
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.  */
3341
3342   printf ("%sCopyright (C) 1988-2016 Free Software Foundation, Inc.\n",
3343           precede);
3344
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);
3349
3350   printed_version = 1;
3351
3352   /* Flush stdout so the user doesn't have to wait to see the
3353      version information while make thinks about things.  */
3354   fflush (stdout);
3355 }
3356
3357 /* Print a bunch of information about this and that.  */
3358
3359 static void
3360 print_data_base (void)
3361 {
3362   time_t when = time ((time_t *) 0);
3363
3364   print_version ();
3365
3366   printf (_("\n# Make data base, printed on %s"), ctime (&when));
3367
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 ("#");
3374
3375   when = time ((time_t *) 0);
3376   printf (_("\n# Finished Make data base on %s\n"), ctime (&when));
3377 }
3378
3379 static void
3380 clean_jobserver (int status)
3381 {
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.  */
3386
3387   if (jobserver_enabled() && jobserver_tokens)
3388     {
3389       if (status != 2)
3390         ON (error, NILF,
3391             "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
3392             jobserver_tokens);
3393       else
3394         /* Don't write back the "free" token */
3395         while (--jobserver_tokens)
3396           jobserver_release (0);
3397     }
3398
3399
3400   /* Sanity: If we're the master, were all the tokens written back?  */
3401
3402   if (master_job_slots)
3403     {
3404       /* We didn't write one for ourself, so start at 1.  */
3405       unsigned int tokens = 1 + jobserver_acquire_all ();
3406
3407       if (tokens != master_job_slots)
3408         ONN (error, NILF,
3409              "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
3410              tokens, master_job_slots);
3411
3412       reset_jobserver ();
3413     }
3414 }
3415 \f
3416 /* Exit with STATUS, cleaning up as necessary.  */
3417
3418 void
3419 die (int status)
3420 {
3421   static char dying = 0;
3422
3423   if (!dying)
3424     {
3425       int err;
3426
3427       dying = 1;
3428
3429       if (print_version_flag)
3430         print_version ();
3431
3432       /* Wait for children to die.  */
3433       err = (status != 0);
3434       while (job_slots_used > 0)
3435         reap_children (1, err);
3436
3437       /* Let the remote job module clean up its state.  */
3438       remote_cleanup ();
3439
3440       /* Remove the intermediate files.  */
3441       remove_intermediates (0);
3442
3443       if (print_data_base_flag)
3444         print_data_base ();
3445
3446       if (verify_flag)
3447         verify_file_data_base ();
3448
3449       clean_jobserver (status);
3450
3451       if (output_context)
3452         {
3453           /* die() might be called in a recipe output context due to an
3454              $(error ...) function.  */
3455           output_close (output_context);
3456
3457           if (output_context != &make_sync)
3458             output_close (&make_sync);
3459
3460           OUTPUT_UNSET ();
3461         }
3462
3463       output_close (NULL);
3464
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)
3471         {
3472           /* If it fails we don't care: shut up GCC.  */
3473           int _x UNUSED;
3474           _x = chdir (directory_before_chdir);
3475         }
3476     }
3477
3478   exit (status);
3479 }