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