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