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