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