Changeset 3140 for trunk/src/kmk/main.c


Ignore:
Timestamp:
Mar 14, 2018, 10:28:10 PM (7 years ago)
Author:
bird
Message:

kmk: Merged in changes from GNU make 4.2.1 (2e55f5e4abdc0e38c1d64be703b446695e70b3b6 / https://git.savannah.gnu.org/git/make.git).

Location:
trunk/src/kmk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/kmk

  • trunk/src/kmk/main.c

    r3123 r3140  
    11/* 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, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
     18#include "os.h"
     19#include "filedef.h"
    2020#include "dep.h"
    21 #include "filedef.h"
    2221#include "variable.h"
    2322#include "job.h"
     
    3635#endif
    3736#ifdef WINDOWS32
    38 #include <windows.h>
    39 #include <io.h>
    40 #include "pathstuff.h"
     37# include <windows.h>
     38# include <io.h>
     39# include "pathstuff.h"
     40# include "sub_proc.h"
     41# include "w32err.h"
    4142#endif
    4243#ifdef __EMX__
     
    7576int __stack = 20000; /* Make sure we have 20K of stack space */
    7677#endif
    77 
    78 void init_dir (void);
    79 void remote_setup (void);
    80 void remote_cleanup (void);
    81 RETSIGTYPE fatal_error_signal (int sig);
    82 
    83 void print_variable_data_base (void);
    84 void print_dir_data_base (void);
    85 void print_rule_data_base (void);
    86 void print_vpath_data_base (void);
    87 
    88 void verify_file_data_base (void);
     78#ifdef VMS
     79int vms_use_mcr_command = 0;
     80int vms_always_use_cmd_file = 0;
     81int vms_gnv_shell = 0;
     82int vms_legacy_behavior = 0;
     83int vms_comma_separator = 0;
     84int vms_unix_simulation = 0;
     85int vms_report_unix_paths = 0;
     86
     87/* Evaluates if a VMS environment option is set, only look at first character */
     88static int
     89get_vms_env_flag (const char *name, int default_value)
     90{
     91char * value;
     92char x;
     93
     94  value = getenv (name);
     95  if (value == NULL)
     96    return default_value;
     97
     98  x = toupper (value[0]);
     99  switch (x)
     100    {
     101    case '1':
     102    case 'T':
     103    case 'E':
     104      return 1;
     105      break;
     106    case '0':
     107    case 'F':
     108    case 'D':
     109      return 0;
     110    }
     111}
     112#endif
    89113
    90114#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
     
    101125int chdir ();
    102126#endif
    103 #ifndef STDC_HEADERS
    104 # ifndef sun                    /* Sun has an incorrect decl in a header.  */
     127#ifndef STDC_HEADERS
     128# ifndef sun                    /* Sun has an incorrect decl in a header.  */
    105129void exit (int) __attribute__ ((noreturn));
    106130# endif
     
    111135static void print_data_base (void);
    112136static void print_version (void);
    113 static void decode_switches (int argc, char **argv, int env);
    114 static void decode_env_switches (char *envar, unsigned int len);
    115 static const char *define_makeflags (int all, int makefile);
     137static void decode_switches (int argc, const char **argv, int env);
     138static void decode_env_switches (const char *envar, unsigned int len);
     139static struct variable *define_makeflags (int all, int makefile);
    116140static char *quote_for_env (char *out, const char *in);
    117141static void initialize_global_hash_tables (void);
     
    123147struct command_switch
    124148  {
    125     int c;                      /* The switch character.  */
    126 
    127     enum                        /* Type of the value.  */
     149    int c;                      /* The switch character.  */
     150
     151    enum                        /* Type of the value.  */
    128152      {
    129         flag,                   /* Turn int flag on.  */
    130         flag_off,               /* Turn int flag off.  */
    131         string,                 /* One string per switch.  */
    132         filename,               /* A string containing a file name.  */
    133         positive_int,           /* A positive integer.  */
    134         floating,               /* A floating-point number (double).  */
    135         ignore                  /* Ignored.  */
     153        flag,                   /* Turn int flag on.  */
     154        flag_off,               /* Turn int flag off.  */
     155        string,                 /* One string per invocation.  */
     156        strlist,                /* One string per switch.  */
     157        filename,               /* A string containing a file name.  */
     158        positive_int,           /* A positive integer.  */
     159        floating,               /* A floating-point number (double).  */
     160        ignore                  /* Ignored.  */
    136161      } type;
    137162
    138     void *value_ptr;    /* Pointer to the value-holding variable.  */
    139 
    140     unsigned int env:1;         /* Can come from MAKEFLAGS.  */
    141     unsigned int toenv:1;       /* Should be put in MAKEFLAGS.  */
    142     unsigned int no_makefile:1; /* Don't propagate when remaking makefiles.  */
    143 
    144     const void *noarg_value;    /* Pointer to value used if no arg given.  */
    145     const void *default_value;  /* Pointer to default value.  */
    146 
    147     char *long_name;            /* Long option name.  */
     163    void *value_ptr;    /* Pointer to the value-holding variable.  */
     164
     165    unsigned int env:1;         /* Can come from MAKEFLAGS.  */
     166    unsigned int toenv:1;       /* Should be put in MAKEFLAGS.  */
     167    unsigned int no_makefile:1; /* Don't propagate when remaking makefiles.  */
     168
     169    const void *noarg_value;    /* Pointer to value used if no arg given.  */
     170    const void *default_value;  /* Pointer to default value.  */
     171
     172    const char *long_name;      /* Long option name.  */
    148173  };
    149174
     
    153178
    154179/* The structure used to hold the list of strings given
    155    in command switches of a type that takes string arguments.  */
     180   in command switches of a type that takes strlist arguments.  */
    156181
    157182struct stringlist
    158183  {
    159     const char **list;  /* Nil-terminated list of strings.  */
    160     unsigned int idx;   /* Index into above.  */
    161     unsigned int max;   /* Number of pointers allocated.  */
     184    const char **list;  /* Nil-terminated list of strings.  */
     185    unsigned int idx;   /* Index into above.  */
     186    unsigned int max;   /* Number of pointers allocated.  */
    162187  };
    163188
    164189
    165190/* The recognized command switches.  */
     191
     192/* Nonzero means do extra verification (that may slow things down).  */
     193
     194int verify_flag;
    166195
    167196/* Nonzero means do not print commands to be executed (-s).  */
     
    203232/* Print debugging info (--debug).  */
    204233
    205 static struct stringlist *db_flags;
     234static struct stringlist *db_flags = 0;
    206235static int debug_flag = 0;
    207236
    208237int db_level = 0;
    209238
    210 /* Output level (--verbosity).  */
    211 
    212 static struct stringlist *verbosity_flags;
     239/* Synchronize output (--output-sync).  */
     240
     241char *output_sync_option = 0;
    213242
    214243#ifdef WINDOWS32
     
    275304
    276305
    277 /* Number of job slots (commands that can be run at once).  */
    278 
    279 unsigned int job_slots = 1;
    280 unsigned int default_job_slots = 1;
     306/* Number of job slots for parallelism.  */
     307
     308unsigned int job_slots;
     309
     310#define INVALID_JOB_SLOTS (-1)
    281311static unsigned int master_job_slots = 0;
     312static int arg_job_slots = INVALID_JOB_SLOTS;
     313
     314#ifdef KMK
     315static int default_job_slots = INVALID_JOB_SLOTS;
     316#else
     317static const int default_job_slots = INVALID_JOB_SLOTS;
     318#endif
    282319
    283320/* Value of job_slots that means no limit.  */
    284321
    285 static unsigned int inf_jobs = 0;
    286 
    287 /* File descriptors for the jobs pipe.  */
    288 
    289 static struct stringlist *jobserver_fds = 0;
    290 
    291 int job_fds[2] = { -1, -1 };
    292 int job_rfd = -1;
     322static const int inf_jobs = 0;
     323
     324/* Authorization for the jobserver.  */
     325
     326static char *jobserver_auth = NULL;
     327
     328/* Handle for the mutex used on Windows to synchronize output of our
     329   children under -O.  */
     330
     331char *sync_mutex = NULL;
    293332
    294333/* Maximum load average at which multiple jobs will be run.
     
    429468                              Consider FILE to be very old and don't remake it.\n"),
    430469    N_("\
     470  -O[TYPE], --output-sync[=TYPE]\n\
     471                              Synchronize output of parallel jobs by TYPE.\n"),
     472    N_("\
    431473  -p, --print-data-base       Print make's internal database.\n"),
    432474    N_("\
     
    443485    N_("\
    444486  -t, --touch                 Touch targets instead of remaking them.\n"),
     487    N_("\
     488  --trace                     Print tracing information.\n"),
    445489    N_("\
    446490  -v, --version               Print the version number of make and exit.\n"),
     
    486530  };
    487531
    488 /* The table of command switches.  */
     532/* The table of command switches.
     533   Order matters here: this is the order MAKEFLAGS will be constructed.
     534   So be sure all simple flags (single char, no argument) come first.  */
    489535
    490536static const struct command_switch switches[] =
     
    492538    { 'b', ignore, 0, 0, 0, 0, 0, 0, 0 },
    493539    { 'B', flag, &always_make_set, 1, 1, 0, 0, 0, "always-make" },
    494     { 'C', filename, &directories, 0, 0, 0, 0, 0, "directory" },
    495540    { 'd', flag, &debug_flag, 1, 1, 0, 0, 0, 0 },
    496     { CHAR_MAX+1, string, &db_flags, 1, 1, 0, "basic", 0, "debug" },
    497541#ifdef WINDOWS32
    498542    { 'D', flag, &suspend_flag, 1, 1, 0, 0, 0, "suspend-for-debug" },
    499543#endif
    500544    { 'e', flag, &env_overrides, 1, 1, 0, 0, 0, "environment-overrides", },
    501     { 'f', filename, &makefiles, 0, 0, 0, 0, 0, "file" },
    502545    { 'h', flag, &print_usage_flag, 0, 0, 0, 0, 0, "help" },
    503546    { 'i', flag, &ignore_errors_flag, 1, 1, 0, 0, 0, "ignore-errors" },
    504     { 'I', filename, &include_directories, 1, 1, 0, 0, 0,
    505       "include-dir" },
    506     { 'j', positive_int, &job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,
    507       "jobs" },
    508     { CHAR_MAX+2, string, &jobserver_fds, 1, 1, 0, 0, 0, "jobserver-fds" },
    509547    { 'k', flag, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
    510548      "keep-going" },
    511 #ifndef NO_FLOAT
    512     { 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,
    513       &default_load_average, "load-average" },
    514 #else
    515     { 'l', positive_int, &max_load_average, 1, 1, 0, &default_load_average,
    516       &default_load_average, "load-average" },
    517 #endif
    518549    { 'L', flag, &check_symlink_flag, 1, 1, 0, 0, 0, "check-symlink-times" },
    519550    { 'm', ignore, 0, 0, 0, 0, 0, 0, 0 },
    520551    { 'n', flag, &just_print_flag, 1, 1, 1, 0, 0, "just-print" },
    521     { 'o', filename, &old_files, 0, 0, 0, 0, 0, "old-file" },
    522552    { 'p', flag, &print_data_base_flag, 1, 1, 0, 0, 0, "print-data-base" },
    523553#ifdef CONFIG_PRETTY_COMMAND_PRINTING
     
    554584    { 't', flag, &touch_flag, 1, 1, 1, 0, 0, "touch" },
    555585    { 'v', flag, &print_version_flag, 1, 1, 0, 0, 0, "version" },
    556     { CHAR_MAX+3, string, &verbosity_flags, 1, 1, 0, 0, 0,
    557       "verbosity" },
    558586    { 'w', flag, &print_directory_flag, 1, 1, 0, 0, 0, "print-directory" },
     587
     588    /* These options take arguments.  */
     589    { 'C', filename, &directories, 0, 0, 0, 0, 0, "directory" },
     590    { 'f', filename, &makefiles, 0, 0, 0, 0, 0, "file" },
     591    { 'I', filename, &include_directories, 1, 1, 0, 0, 0,
     592      "include-dir" },
     593    { 'j', positive_int, &arg_job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,
     594      "jobs" },
     595#ifndef NO_FLOAT
     596    { 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,
     597      &default_load_average, "load-average" },
     598#else
     599    { 'l', positive_int, &max_load_average, 1, 1, 0, &default_load_average,
     600      &default_load_average, "load-average" },
     601#endif
     602    { 'o', filename, &old_files, 0, 0, 0, 0, 0, "old-file" },
     603    { 'O', string, &output_sync_option, 1, 1, 0, "target", 0, "output-sync" },
     604    { 'W', filename, &new_files, 0, 0, 0, 0, 0, "what-if" },
     605
     606    /* These are long-style options.  */
     607    { CHAR_MAX+1, strlist, &db_flags, 1, 1, 0, "basic", 0, "debug" },
     608    { CHAR_MAX+2, string, &jobserver_auth, 1, 1, 0, 0, 0, "jobserver-auth" },
     609    { CHAR_MAX+3, flag, &trace_flag, 1, 1, 0, 0, 0, "trace" },
    559610    { CHAR_MAX+4, flag, &inhibit_print_directory_flag, 1, 1, 0, 0, 0,
    560611      "no-print-directory" },
    561     { 'W', filename, &new_files, 0, 0, 0, 0, 0, "what-if" },
    562612    { CHAR_MAX+5, flag, &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
    563613      "warn-undefined-variables" },
    564     { CHAR_MAX+6, string, &eval_strings, 1, 0, 0, 0, 0, "eval" },
     614    { CHAR_MAX+6, strlist, &eval_strings, 1, 0, 0, 0, 0, "eval" },
     615    { CHAR_MAX+7, string, &sync_mutex, 1, 1, 0, 0, 0, "sync-mutex" },
    565616    { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
    566617  };
     
    570621static struct option long_option_aliases[] =
    571622  {
    572     { "quiet",          no_argument,            0, 's' },
    573     { "stop",           no_argument,            0, 'S' },
    574     { "new-file",       required_argument,      0, 'W' },
    575     { "assume-new",     required_argument,      0, 'W' },
    576     { "assume-old",     required_argument,      0, 'o' },
    577     { "max-load",       optional_argument,      0, 'l' },
    578     { "dry-run",        no_argument,            0, 'n' },
    579     { "recon",          no_argument,            0, 'n' },
    580     { "makefile",       required_argument,      0, 'f' },
     623    { "quiet",          no_argument,            0, 's' },
     624    { "stop",           no_argument,            0, 'S' },
     625    { "new-file",       required_argument,      0, 'W' },
     626    { "assume-new",     required_argument,      0, 'W' },
     627    { "assume-old",     required_argument,      0, 'o' },
     628    { "max-load",       optional_argument,      0, 'l' },
     629    { "dry-run",        no_argument,            0, 'n' },
     630    { "recon",          no_argument,            0, 'n' },
     631    { "makefile",       required_argument,      0, 'f' },
    581632  };
    582633
     
    586637static
    587638#endif
    588 struct dep *goals, *lastgoal;
     639struct goaldep *goals, *lastgoal;
    589640
    590641/* List of variables which were defined on the command line
     
    601652/* The name we were invoked with.  */
    602653
     654#ifdef WINDOWS32
     655/* On MS-Windows, we chop off the .exe suffix in 'main', so this
     656   cannot be 'const'.  */
    603657char *program;
     658#else
     659const char *program;
     660#endif
    604661
    605662/* Our current directory before processing any -C options.  */
     
    629686struct file *default_file;
    630687
    631 /* Nonzero if we have seen the magic `.POSIX' target.
     688/* Nonzero if we have seen the magic '.POSIX' target.
    632689   This turns on pedantic compliance with POSIX.2.  */
    633690
     
    638695
    639696int second_expansion;
     697
     698#ifdef CONFIG_WITH_2ND_TARGET_EXPANSION
     699/* Nonzero if we have seen the '.SECONDTARGETEXPANSION' target.
     700   This turns on secondary expansion of targets.  */
     701
     702int second_target_expansion;
     703#endif
    640704
    641705/* Nonzero if we have seen the '.ONESHELL' target.
     
    645709int one_shell;
    646710
    647 #ifdef CONFIG_WITH_2ND_TARGET_EXPANSION
    648 /* Nonzero if we have seen the '.SECONDTARGETEXPANSION' target.
    649    This turns on secondary expansion of targets.  */
    650 
    651 int second_target_expansion;
    652 #endif
     711/* One of OUTPUT_SYNC_* if the "--output-sync" option was given.  This
     712   attempts to synchronize the output of parallel jobs such that the results
     713   of each job stay together.  */
     714
     715int output_sync = OUTPUT_SYNC_NONE;
     716
     717/* Nonzero if the "--trace" option was given.  */
     718
     719int trace_flag = 0;
    653720
    654721#ifndef CONFIG_WITH_EXTENDED_NOTPARALLEL
    655722
    656 /* Nonzero if we have seen the `.NOTPARALLEL' target.
     723/* Nonzero if we have seen the '.NOTPARALLEL' target.
    657724   This turns off parallel builds for this invocation of make.  */
    658725
    659726#else  /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
    660727
    661 /* Negative if we have seen the `.NOTPARALLEL' target with an
     728/* Negative if we have seen the '.NOTPARALLEL' target with an
    662729   empty dependency list.
    663730
    664    Zero if no `.NOTPARALLEL' or no file in the dependency list
     731   Zero if no '.NOTPARALLEL' or no file in the dependency list
    665732   is being executed.
    666733
    667    Positive when a file in the `.NOTPARALLEL' dependency list
     734   Positive when a file in the '.NOTPARALLEL' dependency list
    668735   is in progress, the value is the number of notparallel files
    669736   in progress (running or queued for running).
     
    680747int clock_skew_detected;
    681748
     749/* Map of possible stop characters for searching strings.  */
     750#ifndef UCHAR_MAX
     751# define UCHAR_MAX 255
     752#endif
     753#ifdef _MSC_VER
     754__declspec(align(512)) /* bird: improve cacheline & tlb mojo  */
     755#endif
     756unsigned short stopchar_map[UCHAR_MAX + 1] = {0};
     757
     758/* If output-sync is enabled we'll collect all the output generated due to
     759   options, while reading makefiles, etc.  */
     760
     761struct output make_sync;
     762
     763
    682764
    683765/* Mask of signals that are being caught with fatal_error_signal.  */
    684766
    685 #ifdef  POSIX
     767#ifdef POSIX
    686768sigset_t fatal_signal_set;
    687769#else
    688 # ifdef HAVE_SIGSETMASK
     770# ifdef HAVE_SIGSETMASK
    689771int fatal_signal_mask;
    690772# endif
     
    714796#ifdef CONFIG_WITH_ALLOC_CACHES
    715797struct alloccache dep_cache;
     798struct alloccache goaldep_cache;
     799struct alloccache nameseq_cache;
    716800struct alloccache file_cache;
    717801struct alloccache commands_cache;
    718 struct alloccache nameseq_cache;
    719802struct alloccache variable_cache;
    720803struct alloccache variable_set_cache;
     
    725808{
    726809  alloccache_init (&dep_cache,               sizeof (struct dep),               "dep",               NULL, NULL);
     810  alloccache_init (&goaldep_cache,           sizeof (struct goaldep),           "goaldep",           NULL, NULL);
     811  alloccache_init (&nameseq_cache,           sizeof (struct nameseq),           "nameseq",           NULL, NULL);
    727812  alloccache_init (&file_cache,              sizeof (struct file),              "file",              NULL, NULL);
    728813  alloccache_init (&commands_cache,          sizeof (struct commands),          "commands",          NULL, NULL);
    729   alloccache_init (&nameseq_cache,           sizeof (struct nameseq),           "nameseq",           NULL, NULL);
    730814  alloccache_init (&variable_cache,          sizeof (struct variable),          "variable",          NULL, NULL);
    731815  alloccache_init (&variable_set_cache,      sizeof (struct variable_set),      "variable_set",      NULL, NULL);
     
    744828}
    745829
     830/* This character map locate stop chars when parsing GNU makefiles.
     831   Each element is true if we should stop parsing on that character.  */
     832
     833static void
     834initialize_stopchar_map (void)
     835{
     836  int i;
     837
     838  stopchar_map[(int)'\0'] = MAP_NUL;
     839  stopchar_map[(int)'#'] = MAP_COMMENT;
     840  stopchar_map[(int)';'] = MAP_SEMI;
     841  stopchar_map[(int)'='] = MAP_EQUALS;
     842  stopchar_map[(int)':'] = MAP_COLON;
     843  stopchar_map[(int)'%'] = MAP_PERCENT;
     844  stopchar_map[(int)'|'] = MAP_PIPE;
     845  stopchar_map[(int)'.'] = MAP_DOT | MAP_USERFUNC;
     846  stopchar_map[(int)','] = MAP_COMMA;
     847  stopchar_map[(int)'$'] = MAP_VARIABLE;
     848
     849  stopchar_map[(int)'-'] = MAP_USERFUNC;
     850  stopchar_map[(int)'_'] = MAP_USERFUNC;
     851
     852  stopchar_map[(int)' '] = MAP_BLANK;
     853  stopchar_map[(int)'\t'] = MAP_BLANK;
     854
     855  stopchar_map[(int)'/'] = MAP_DIRSEP;
     856#if defined(VMS)
     857  stopchar_map[(int)':'] |= MAP_DIRSEP;
     858  stopchar_map[(int)']'] |= MAP_DIRSEP;
     859  stopchar_map[(int)'>'] |= MAP_DIRSEP;
     860#elif defined(HAVE_DOS_PATHS)
     861  stopchar_map[(int)'\\'] |= MAP_DIRSEP;
     862#endif
     863
     864  for (i = 1; i <= UCHAR_MAX; ++i)
     865    {
     866      if (isspace (i) && NONE_SET (stopchar_map[i], MAP_BLANK))
     867        /* Don't mark blank characters as newline characters.  */
     868        stopchar_map[i] |= MAP_NEWLINE;
     869      else if (isalnum (i))
     870        stopchar_map[i] |= MAP_USERFUNC;
     871    }
     872}
     873
    746874static const char *
    747 expand_command_line_file (char *name)
     875expand_command_line_file (const char *name)
    748876{
    749877  const char *cp;
     
    751879
    752880  if (name[0] == '\0')
    753     fatal (NILF, _("empty string invalid as file name"));
     881    O (fatal, NILF, _("empty string invalid as file name"));
    754882
    755883  if (name[0] == '~')
    756884    {
    757885      expanded = tilde_expand (name);
    758       if (expanded != 0)
    759         name = expanded;
     886      if (expanded && expanded[0] != '\0')
     887        name = expanded;
    760888    }
    761889
     
    763891     for names read from makefiles.  It is here for names passed
    764892     on the command line.  */
    765   while (name[0] == '.' && name[1] == '/' && name[2] != '\0')
     893  while (name[0] == '.' && name[1] == '/')
    766894    {
    767895      name += 2;
    768       while (*name == '/')
    769         /* Skip following slashes: ".//foo" is "foo", not "/foo".  */
    770         ++name;
    771     }
    772 
    773   if (*name == '\0')
    774     {
    775       /* It was all slashes!  Move back to the dot and truncate
    776          it after the first slash, so it becomes just "./".  */
    777       do
    778         --name;
    779       while (name[0] != '.');
    780       name[2] = '\0';
     896      while (name[0] == '/')
     897        /* Skip following slashes: ".//foo" is "foo", not "/foo".  */
     898        ++name;
     899    }
     900
     901  if (name[0] == '\0')
     902    {
     903      /* Nothing else but one or more "./", maybe plus slashes!  */
     904      name = "./";
    781905    }
    782906
    783907  cp = strcache_add (name);
    784908
    785   if (expanded)
    786     free (expanded);
     909  free (expanded);
    787910
    788911  return cp;
     
    807930    db_level = DB_ALL;
    808931
    809   if (!db_flags)
    810     return;
    811 
    812   for (pp=db_flags->list; *pp; ++pp)
    813     {
    814       const char *p = *pp;
    815 
    816       while (1)
    817         {
    818           switch (tolower (p[0]))
    819             {
    820             case 'a':
    821               db_level |= DB_ALL;
     932  if (db_flags)
     933    for (pp=db_flags->list; *pp; ++pp)
     934      {
     935        const char *p = *pp;
     936
     937        while (1)
     938          {
     939            switch (tolower (p[0]))
     940              {
     941              case 'a':
     942                db_level |= DB_ALL;
     943                break;
     944              case 'b':
     945                db_level |= DB_BASIC;
     946                break;
     947              case 'i':
     948                db_level |= DB_BASIC | DB_IMPLICIT;
     949                break;
     950              case 'j':
     951                db_level |= DB_JOBS;
     952                break;
     953              case 'm':
     954                db_level |= DB_BASIC | DB_MAKEFILES;
     955                break;
     956              case 'n':
     957                db_level = 0;
     958                break;
     959              case 'v':
     960                db_level |= DB_BASIC | DB_VERBOSE;
     961                break;
     962#ifdef DB_KMK
     963              case 'k':
     964                db_level |= DB_KMK;
     965                break;
     966#endif /* DB_KMK */
     967              default:
     968                OS (fatal, NILF,
     969                    _("unknown debug level specification '%s'"), p);
     970              }
     971
     972            while (*(++p) != '\0')
     973              if (*p == ',' || *p == ' ')
     974                {
     975                  ++p;
     976                  break;
     977                }
     978
     979            if (*p == '\0')
    822980              break;
    823             case 'b':
    824               db_level |= DB_BASIC;
    825               break;
    826             case 'i':
    827               db_level |= DB_BASIC | DB_IMPLICIT;
    828               break;
    829             case 'j':
    830               db_level |= DB_JOBS;
    831               break;
    832             case 'm':
    833               db_level |= DB_BASIC | DB_MAKEFILES;
    834               break;
    835             case 'v':
    836               db_level |= DB_BASIC | DB_VERBOSE;
    837               break;
    838 #ifdef DB_KMK
    839             case 'k':
    840               db_level |= DB_KMK;
    841               break;
    842 #endif /* DB_KMK */
    843             default:
    844               fatal (NILF, _("unknown debug level specification `%s'"), p);
    845             }
    846 
    847           while (*(++p) != '\0')
    848             if (*p == ',' || *p == ' ')
    849               break;
    850 
    851           if (*p == '\0')
    852             break;
    853 
    854           ++p;
    855         }
    856     }
     981          }
     982      }
     983
     984  if (db_level)
     985    verify_flag = 1;
     986
     987  if (! db_level)
     988    debug_flag = 0;
     989}
     990
     991static void
     992decode_output_sync_flags (void)
     993{
     994#ifdef NO_OUTPUT_SYNC
     995  output_sync = OUTPUT_SYNC_NONE;
     996#else
     997  if (output_sync_option)
     998    {
     999      if (streq (output_sync_option, "none"))
     1000        output_sync = OUTPUT_SYNC_NONE;
     1001      else if (streq (output_sync_option, "line"))
     1002        output_sync = OUTPUT_SYNC_LINE;
     1003      else if (streq (output_sync_option, "target"))
     1004        output_sync = OUTPUT_SYNC_TARGET;
     1005      else if (streq (output_sync_option, "recurse"))
     1006        output_sync = OUTPUT_SYNC_RECURSE;
     1007      else
     1008        OS (fatal, NILF,
     1009            _("unknown output-sync type '%s'"), output_sync_option);
     1010    }
     1011
     1012  if (sync_mutex)
     1013    RECORD_SYNC_MUTEX (sync_mutex);
     1014#endif
    8571015}
    8581016
     
    8781036      case 4:     dwClass = HIGH_PRIORITY_CLASS;         dwPriority = 0xffffffff; break;
    8791037      case 5:     dwClass = REALTIME_PRIORITY_CLASS;     dwPriority = 0xffffffff; break;
    880       default:    fatal (NILF, _("invalid priority %d\n"), process_priority);
     1038      default:    ON (fatal, NILF, _("invalid priority %d\n"), process_priority);
    8811039    }
    8821040  if (!SetPriorityClass (GetCurrentProcess (), dwClass))
     
    9001058      case 4:     iNewPriority = B_URGENT_DISPLAY_PRIORITY; break;
    9011059      case 5:     iNewPriority = B_REAL_TIME_DISPLAY_PRIORITY; break;
    902       default:    fatal (NILF, _("invalid priority %d\n"), process_priority);
     1060      default:    ON (fatal, NILF, _("invalid priority %d\n"), process_priority);
    9031061    }
    9041062  error = set_thread_priority (find_thread (NULL), iNewPriority);
     
    9171075      case 4:     nice_level = -10; break;
    9181076      case 5:     nice_level = -19; break;
    919       default:    fatal (NILF, _("invalid priority %d\n"), process_priority);
     1077      default:    ON (fatal, NILF, _("invalid priority %d\n"), process_priority);
    9201078    }
    9211079  errno = 0;
     
    9291087
    9301088#ifdef WINDOWS32
    931 # ifndef KMK
     1089
     1090#ifndef NO_OUTPUT_SYNC
     1091
     1092/* This is called from start_job_command when it detects that
     1093   output_sync option is in effect.  The handle to the synchronization
     1094   mutex is passed, as a string, to sub-makes via the --sync-mutex
     1095   command-line argument.  */
     1096void
     1097prepare_mutex_handle_string (sync_handle_t handle)
     1098{
     1099  if (!sync_mutex)
     1100    {
     1101      /* Prepare the mutex handle string for our children.  */
     1102      /* 2 hex digits per byte + 2 characters for "0x" + null.  */
     1103      sync_mutex = xmalloc ((2 * sizeof (sync_handle_t)) + 2 + 1);
     1104      sprintf (sync_mutex, "0x%Ix", handle);
     1105      define_makeflags (1, 0);
     1106    }
     1107}
     1108
     1109#endif  /* NO_OUTPUT_SYNC */
     1110
     1111# ifndef KMK /* I'd rather have WER collect dumps. */
    9321112/*
    9331113 * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
     
    9401120 */
    9411121LONG WINAPI
    942 handle_runtime_exceptions( struct _EXCEPTION_POINTERS *exinfo )
     1122handle_runtime_exceptions (struct _EXCEPTION_POINTERS *exinfo)
    9431123{
    9441124  PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
    945   LPSTR cmdline = GetCommandLine();
    946   LPSTR prg = strtok(cmdline, " ");
     1125  LPSTR cmdline = GetCommandLine ();
     1126  LPSTR prg = strtok (cmdline, " ");
    9471127  CHAR errmsg[1024];
    9481128#ifdef USE_EVENT_LOG
     
    9531133  if (! ISDB (DB_VERBOSE))
    9541134    {
    955       sprintf(errmsg,
    956               _("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\n"),
    957               prg, exrec->ExceptionCode, exrec->ExceptionAddress);
    958       fprintf(stderr, errmsg);
    959       exit(255);
    960     }
    961 
    962   sprintf(errmsg,
    963           _("\nUnhandled exception filter called from program %s\nExceptionCode = %lx\nExceptionFlags = %lx\nExceptionAddress = 0x%p\n"),
    964           prg, exrec->ExceptionCode, exrec->ExceptionFlags,
    965           exrec->ExceptionAddress);
     1135      sprintf (errmsg,
     1136               _("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\n"),
     1137               prg, exrec->ExceptionCode, exrec->ExceptionAddress);
     1138      fprintf (stderr, errmsg);
     1139      exit (255);
     1140    }
     1141
     1142  sprintf (errmsg,
     1143           _("\nUnhandled exception filter called from program %s\nExceptionCode = %lx\nExceptionFlags = %lx\nExceptionAddress = 0x%p\n"),
     1144           prg, exrec->ExceptionCode, exrec->ExceptionFlags,
     1145           exrec->ExceptionAddress);
    9661146
    9671147  if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
    9681148      && exrec->NumberParameters >= 2)
    969     sprintf(&errmsg[strlen(errmsg)],
    970             (exrec->ExceptionInformation[0]
    971              ? _("Access violation: write operation at address 0x%p\n")
    972              : _("Access violation: read operation at address 0x%p\n")),
    973             (PVOID)exrec->ExceptionInformation[1]);
     1149    sprintf (&errmsg[strlen(errmsg)],
     1150             (exrec->ExceptionInformation[0]
     1151              ? _("Access violation: write operation at address 0x%p\n")
     1152              : _("Access violation: read operation at address 0x%p\n")),
     1153             (PVOID)exrec->ExceptionInformation[1]);
    9741154
    9751155  /* turn this on if we want to put stuff in the event log too */
    9761156#ifdef USE_EVENT_LOG
    977   hEventSource = RegisterEventSource(NULL, "GNU Make");
     1157  hEventSource = RegisterEventSource (NULL, "GNU Make");
    9781158  lpszStrings[0] = errmsg;
    9791159
    9801160  if (hEventSource != NULL)
    9811161    {
    982       ReportEvent(hEventSource,         /* handle of event source */
    983                   EVENTLOG_ERROR_TYPE,  /* event type */
    984                   0,                    /* event category */
    985                   0,                    /* event ID */
    986                   NULL,                 /* current user's SID */
    987                   1,                    /* strings in lpszStrings */
    988                   0,                    /* no bytes of raw data */
    989                   lpszStrings,          /* array of error strings */
    990                   NULL);                /* no raw data */
    991 
    992       (VOID) DeregisterEventSource(hEventSource);
     1162      ReportEvent (hEventSource,         /* handle of event source */
     1163                   EVENTLOG_ERROR_TYPE,  /* event type */
     1164                   0,                    /* event category */
     1165                   0,                    /* event ID */
     1166                   NULL,                 /* current user's SID */
     1167                   1,                    /* strings in lpszStrings */
     1168                   0,                    /* no bytes of raw data */
     1169                   lpszStrings,          /* array of error strings */
     1170                   NULL);                /* no raw data */
     1171
     1172      (VOID) DeregisterEventSource (hEventSource);
    9931173    }
    9941174#endif
    9951175
    9961176  /* Write the error to stderr too */
    997   fprintf(stderr, errmsg);
     1177  fprintf (stderr, errmsg);
    9981178
    9991179#ifdef DEBUG
    10001180  return EXCEPTION_CONTINUE_SEARCH;
    10011181#else
    1002   exit(255);
     1182  exit (255);
    10031183  return (255); /* not reached */
    10041184#endif
     
    10091189 * On WIN32 systems we don't have the luxury of a /bin directory that
    10101190 * is mapped globally to every drive mounted to the system. Since make could
    1011  * be invoked from any drive, and we don't want to propogate /bin/sh
     1191 * be invoked from any drive, and we don't want to propagate /bin/sh
    10121192 * to every single drive. Allow ourselves a chance to search for
    10131193 * a value for default shell here (if the default path does not exist).
     
    10191199  int sh_found = 0;
    10201200  char *atoken = 0;
    1021   char *search_token;
    1022   char *tokend;
     1201  const char *search_token;
     1202  const char *tokend;
    10231203  PATH_VAR(sh_path);
    1024   extern char *default_shell;
     1204  extern const char *default_shell;
    10251205
    10261206  if (!token)
    10271207    search_token = default_shell;
    10281208  else
    1029     atoken = search_token = xstrdup (token);
     1209    search_token = atoken = xstrdup (token);
    10301210
    10311211  /* If the user explicitly requests the DOS cmd shell, obey that request.
     
    10411221           || (tokend - 4 > search_token
    10421222               && (tokend[-5] == '/' || tokend[-5] == '\\')))
    1043           && !strcasecmp (tokend - 4, "cmd.exe"))) {
    1044     batch_mode_shell = 1;
    1045     unixy_shell = 0;
    1046     sprintf (sh_path, "%s", search_token);
    1047     default_shell = xstrdup (w32ify (sh_path, 0));
    1048     DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
    1049                      default_shell));
    1050     sh_found = 1;
    1051   } else if (!no_default_sh_exe &&
    1052              (token == NULL || !strcmp (search_token, default_shell))) {
    1053     /* no new information, path already set or known */
    1054     sh_found = 1;
    1055   } else if (file_exists_p (search_token)) {
    1056     /* search token path was found */
    1057     sprintf (sh_path, "%s", search_token);
    1058     default_shell = xstrdup (w32ify (sh_path, 0));
    1059     DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
    1060                      default_shell));
    1061     sh_found = 1;
    1062   } else {
    1063     char *p;
    1064     struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
    1065 
    1066     /* Search Path for shell */
    1067     if (v && v->value) {
    1068       char *ep;
    1069 
    1070       p  = v->value;
    1071       ep = strchr (p, PATH_SEPARATOR_CHAR);
    1072 
    1073       while (ep && *ep) {
    1074         *ep = '\0';
    1075 
    1076         if (dir_file_exists_p (p, search_token)) {
    1077           sprintf (sh_path, "%s/%s", p, search_token);
    1078           default_shell = xstrdup (w32ify (sh_path, 0));
    1079           sh_found = 1;
    1080           *ep = PATH_SEPARATOR_CHAR;
    1081 
    1082           /* terminate loop */
    1083           p += strlen (p);
    1084         } else {
    1085           *ep = PATH_SEPARATOR_CHAR;
    1086            p = ++ep;
     1223          && !strcasecmp (tokend - 4, "cmd.exe")))
     1224    {
     1225      batch_mode_shell = 1;
     1226      unixy_shell = 0;
     1227      sprintf (sh_path, "%s", search_token);
     1228      default_shell = xstrdup (w32ify (sh_path, 0));
     1229      DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
     1230                       default_shell));
     1231      sh_found = 1;
     1232    }
     1233  else if (!no_default_sh_exe
     1234           && (token == NULL || !strcmp (search_token, default_shell)))
     1235    {
     1236      /* no new information, path already set or known */
     1237      sh_found = 1;
     1238    }
     1239  else if (_access (search_token, 0) == 0)
     1240    {
     1241      /* search token path was found */
     1242      sprintf (sh_path, "%s", search_token);
     1243      default_shell = xstrdup (w32ify (sh_path, 0));
     1244      DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
     1245                       default_shell));
     1246      sh_found = 1;
     1247    }
     1248  else
     1249    {
     1250      char *p;
     1251      struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
     1252
     1253      /* Search Path for shell */
     1254      if (v && v->value)
     1255        {
     1256          char *ep;
     1257
     1258          p  = v->value;
     1259          ep = strchr (p, PATH_SEPARATOR_CHAR);
     1260
     1261          while (ep && *ep)
     1262            {
     1263              *ep = '\0';
     1264
     1265              sprintf (sh_path, "%s/%s", p, search_token);
     1266              if (_access (sh_path, 0) == 0)
     1267                {
     1268                  default_shell = xstrdup (w32ify (sh_path, 0));
     1269                  sh_found = 1;
     1270                  *ep = PATH_SEPARATOR_CHAR;
     1271
     1272                  /* terminate loop */
     1273                  p += strlen (p);
     1274                }
     1275              else
     1276                {
     1277                  *ep = PATH_SEPARATOR_CHAR;
     1278                  p = ++ep;
     1279                }
     1280
     1281              ep = strchr (p, PATH_SEPARATOR_CHAR);
     1282            }
     1283
     1284          /* be sure to check last element of Path */
     1285          if (p && *p)
     1286            {
     1287              sprintf (sh_path, "%s/%s", p, search_token);
     1288              if (_access (sh_path, 0) == 0)
     1289                {
     1290                  default_shell = xstrdup (w32ify (sh_path, 0));
     1291                  sh_found = 1;
     1292                }
     1293            }
     1294
     1295          if (sh_found)
     1296            DB (DB_VERBOSE,
     1297                (_("find_and_set_shell() path search set default_shell = %s\n"),
     1298                 default_shell));
    10871299        }
    1088 
    1089         ep = strchr (p, PATH_SEPARATOR_CHAR);
    1090       }
    1091 
    1092       /* be sure to check last element of Path */
    1093       if (p && *p && dir_file_exists_p (p, search_token)) {
    1094           sprintf (sh_path, "%s/%s", p, search_token);
    1095           default_shell = xstrdup (w32ify (sh_path, 0));
    1096           sh_found = 1;
    1097       }
    1098 
    1099       if (sh_found)
    1100         DB (DB_VERBOSE,
    1101             (_("find_and_set_shell() path search set default_shell = %s\n"),
    1102              default_shell));
    1103     }
    1104   }
    1105 
    1106 #if 0/* def KMK - has been fixed in sub_proc.c */
    1107   /* WORKAROUND:
    1108     With GNU Make 3.81, this kludge was necessary to get double quotes
    1109     working correctly again (worked fine with the 3.81beta1 code).
    1110     beta1 was forcing batch_mode_shell I think, so let's enforce that
    1111     for the kBuild shell. */
    1112   if (sh_found && strstr(default_shell, "kmk_ash")) {
     1300    }
     1301
     1302  /* naive test */
     1303  if (!unixy_shell && sh_found
     1304      && (strstr (default_shell, "sh") || strstr (default_shell, "SH")))
     1305    {
    11131306      unixy_shell = 1;
    1114       batch_mode_shell = 1;
    1115   } else
    1116 #endif
    1117   /* naive test */
    1118   if (!unixy_shell && sh_found &&
    1119       (strstr (default_shell, "sh") || strstr (default_shell, "SH"))) {
    1120     unixy_shell = 1;
    1121     batch_mode_shell = 0;
    1122   }
     1307      batch_mode_shell = 0;
     1308    }
    11231309
    11241310#ifdef BATCH_MODE_ONLY_SHELL
     
    11261312#endif
    11271313
    1128   if (atoken)
    1129     free (atoken);
     1314  free (atoken);
    11301315
    11311316  return (sh_found);
     
    13371522#endif  /* __MSDOS__ */
    13381523
    1339 #ifndef _MSC_VER /* bird */
    1340 char *mktemp (char *template);
    1341 #endif
    1342 int mkstemp (char *template);
    1343 
    1344 FILE *
    1345 open_tmpfile(char **name, const char *template)
     1524static void
     1525reset_jobserver (void)
    13461526{
    1347 #ifdef HAVE_FDOPEN
    1348   int fd;
    1349 #endif
    1350 
    1351 #if defined HAVE_MKSTEMP || defined HAVE_MKTEMP
    1352 # define TEMPLATE_LEN   strlen (template)
    1353 #else
    1354 # define TEMPLATE_LEN   L_tmpnam
    1355 #endif
    1356   *name = xmalloc (TEMPLATE_LEN + 1);
    1357   strcpy (*name, template);
    1358 
    1359 #if defined HAVE_MKSTEMP && defined HAVE_FDOPEN
    1360   /* It's safest to use mkstemp(), if we can.  */
    1361   fd = mkstemp (*name);
    1362   if (fd == -1)
    1363     return 0;
    1364   return fdopen (fd, "w");
    1365 #else
    1366 # ifdef HAVE_MKTEMP
    1367   (void) mktemp (*name);
    1368 # else
    1369   (void) tmpnam (*name);
    1370 # endif
    1371 
    1372 # ifdef HAVE_FDOPEN
    1373   /* Can't use mkstemp(), but guard against a race condition.  */
    1374   fd = open (*name, O_CREAT|O_EXCL|O_WRONLY, 0600);
    1375   if (fd == -1)
    1376     return 0;
    1377   return fdopen (fd, "w");
    1378 # else
    1379   /* Not secure, but what can we do?  */
    1380   return fopen (*name, "w");
    1381 # endif
    1382 #endif
     1527  jobserver_clear ();
     1528  free (jobserver_auth);
     1529  jobserver_auth = NULL;
    13831530}
    1384 
    1385 #ifdef CONFIG_WITH_FAST_IS_SPACE /*bird*/
    1386 char space_map[space_map_size];
    1387 #endif /* CONFIG_WITH_FAST_IS_SPACE */
    1388 
    13891531
    13901532#ifdef _AMIGA
     
    13971539{
    13981540  static char *stdin_nm = 0;
     1541#ifdef CONFIG_WITH_MAKE_STATS
     1542  unsigned long long uStartTick = CURRENT_CLOCK_TICK();
     1543#endif
    13991544  int makefile_status = MAKE_SUCCESS;
    1400   struct dep *read_makefiles;
     1545  struct goaldep *read_files;
    14011546  PATH_VAR (current_directory);
    14021547  unsigned int restarts = 0;
    1403 #ifdef CONFIG_WITH_MAKE_STATS
    1404   unsigned long long uStartTick = CURRENT_CLOCK_TICK();
    1405 #endif
     1548  unsigned int syncing = 0;
     1549  int argv_slots;
    14061550#ifdef WINDOWS32
    1407   char *unix_path = NULL;
    1408   char *windows32_path = NULL;
     1551  const char *unix_path = NULL;
     1552  const char *windows32_path = NULL;
    14091553
    14101554# ifndef ELECTRIC_HEAP /* Drop this because it prevents JIT debugging. */
    14111555#  ifndef KMK /* Don't want none of this crap. */
    1412   SetUnhandledExceptionFilter(handle_runtime_exceptions);
     1556  SetUnhandledExceptionFilter (handle_runtime_exceptions);
    14131557#  endif
    14141558# endif /* !ELECTRIC_HEAP */
     
    14251569  no_default_sh_exe = 1;
    14261570#endif
    1427 #ifdef CONFIG_WITH_FAST_IS_SPACE /* bird */
    1428   memset (space_map, '\0', sizeof(space_map));
    1429   set_space_map_entry (' ');
    1430   set_space_map_entry ('\f');
    1431   set_space_map_entry ('\n');
    1432   set_space_map_entry ('\r');
    1433   set_space_map_entry ('\t');
    1434   set_space_map_entry ('\v');
    1435 #endif /* CONFIG_WITH_FAST_IS_SPACE */
    1436 
    14371571#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
    14381572  make_start_ts = nano_timestamp ();
    14391573#endif
     1574
     1575  output_init (&make_sync);
     1576
     1577  initialize_stopchar_map();
    14401578
    14411579#ifdef SET_STACK_SIZE
     
    14571595#endif
    14581596
    1459 #ifdef HAVE_ATEXIT
    1460   atexit (close_stdout);
    1461 #endif
    1462 
    14631597  /* Needed for OS/2 */
    1464   initialize_main(&argc, &argv);
     1598  initialize_main (&argc, &argv);
    14651599
    14661600#ifdef KMK
     
    14681602#endif
    14691603
    1470   reading_file = 0;
     1604#ifdef MAKE_MAINTAINER_MODE
     1605  /* In maintainer mode we always enable verification.  */
     1606  verify_flag = 1;
     1607#endif
    14711608
    14721609#if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
    1473   /* Request the most powerful version of `system', to
     1610  /* Request the most powerful version of 'system', to
    14741611     make up for the dumb default shell.  */
    14751612  __system_flags = (__system_redirect
    1476                     | __system_use_shell
    1477                     | __system_allow_multiple_cmds
    1478                     | __system_allow_long_cmds
    1479                     | __system_handle_null_commands
    1480                     | __system_emulate_chdir);
     1613                    | __system_use_shell
     1614                    | __system_allow_multiple_cmds
     1615                    | __system_allow_long_cmds
     1616                    | __system_handle_null_commands
     1617                    | __system_emulate_chdir);
    14811618
    14821619#endif
     
    14911628#endif
    14921629
    1493 #ifdef  POSIX
     1630#ifdef  POSIX
    14941631  sigemptyset (&fatal_signal_set);
    1495 #define ADD_SIG(sig)    sigaddset (&fatal_signal_set, sig)
     1632#define ADD_SIG(sig)    sigaddset (&fatal_signal_set, sig)
    14961633#else
    1497 #ifdef  HAVE_SIGSETMASK
     1634#ifdef  HAVE_SIGSETMASK
    14981635  fatal_signal_mask = 0;
    1499 #define ADD_SIG(sig)    fatal_signal_mask |= sigmask (sig)
     1636#define ADD_SIG(sig)    fatal_signal_mask |= sigmask (sig)
    15001637#else
    1501 #define ADD_SIG(sig)    (void)sig      /* Needed to avoid warnings in MSVC.  */
    1502 #endif
    1503 #endif
    1504 
    1505 #define FATAL_SIG(sig)                                                        \
    1506   if (bsd_signal (sig, fatal_error_signal) == SIG_IGN)                        \
    1507     bsd_signal (sig, SIG_IGN);                                                \
    1508   else                                                                        \
     1638#define ADD_SIG(sig)    (void)sig
     1639#endif
     1640#endif
     1641
     1642#define FATAL_SIG(sig)                                                        \
     1643  if (bsd_signal (sig, fatal_error_signal) == SIG_IGN)                        \
     1644    bsd_signal (sig, SIG_IGN);                                                \
     1645  else                                                                        \
    15091646    ADD_SIG (sig);
    15101647
     
    15251662#endif
    15261663
    1527 #ifdef  SIGDANGER
     1664#ifdef  SIGDANGER
    15281665  FATAL_SIG (SIGDANGER);
    15291666#endif
     
    15411678#endif /* CONFIG_NEW_WIN32_CTRL_EVENT */
    15421679
    1543 #undef  FATAL_SIG
     1680#undef  FATAL_SIG
    15441681
    15451682  /* Do not ignore the child-death signal.  This must be done before
     
    15571694#endif
    15581695
    1559   /* Make sure stdout is line-buffered.  */
    1560 
    1561 #ifdef HAVE_SETVBUF
    1562 # ifdef SETVBUF_REVERSED
    1563   setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
    1564 # else  /* setvbuf not reversed.  */
    1565   /* Some buggy systems lose if we pass 0 instead of allocating ourselves.  */
    1566   setvbuf (stdout, 0, _IOLBF, BUFSIZ);
    1567 # endif /* setvbuf reversed.  */
    1568 #elif HAVE_SETLINEBUF
    1569   setlinebuf (stdout);
    1570 #endif  /* setlinebuf missing.  */
     1696  output_init (NULL);
    15711697
    15721698  /* Figure out where this program lives.  */
    15731699
    15741700  if (argv[0] == 0)
    1575     argv[0] = "";
     1701    argv[0] = (char *)"";
    15761702  if (argv[0][0] == '\0')
    15771703#ifdef KMK
     
    15821708  else
    15831709    {
    1584 #ifdef VMS
    1585       program = strrchr (argv[0], ']');
    1586 #else
    15871710      program = strrchr (argv[0], '/');
    1588 #endif
    15891711#if defined(__MSDOS__) || defined(__EMX__)
    15901712      if (program == 0)
    1591         program = strrchr (argv[0], '\\');
     1713        program = strrchr (argv[0], '\\');
    15921714      else
    1593         {
    1594           /* Some weird environments might pass us argv[0] with
    1595              both kinds of slashes; we must find the rightmost.  */
    1596           char *p = strrchr (argv[0], '\\');
    1597           if (p && p > program)
    1598             program = p;
    1599         }
     1715        {
     1716          /* Some weird environments might pass us argv[0] with
     1717             both kinds of slashes; we must find the rightmost.  */
     1718          char *p = strrchr (argv[0], '\\');
     1719          if (p && p > program)
     1720            program = p;
     1721        }
    16001722      if (program == 0 && argv[0][1] == ':')
    1601         program = argv[0] + 1;
     1723        program = argv[0] + 1;
    16021724#endif
    16031725#ifdef WINDOWS32
     
    16051727        {
    16061728          /* Extract program from full path */
    1607           int argv0_len;
    16081729          program = strrchr (argv[0], '\\');
    16091730          if (program)
    16101731            {
    1611               argv0_len = strlen(program);
     1732              int argv0_len = strlen (program);
    16121733              if (argv0_len > 4 && streq (&program[argv0_len - 4], ".exe"))
    16131734                /* Remove .exe extension */
     
    16161737        }
    16171738#endif
     1739#ifdef VMS
     1740      set_program_name (argv[0]);
     1741      program = program_name;
     1742      {
     1743        const char *shell;
     1744        char pwdbuf[256];
     1745        char *pwd;
     1746        shell = getenv ("SHELL");
     1747        if (shell != NULL)
     1748          vms_gnv_shell = 1;
     1749
     1750        /* Need to know if CRTL set to report UNIX paths.  Use getcwd as
     1751           it works on all versions of VMS. */
     1752        pwd = getcwd(pwdbuf, 256);
     1753        if (pwd[0] == '/')
     1754          vms_report_unix_paths = 1;
     1755
     1756        vms_use_mcr_command = get_vms_env_flag ("GNV$MAKE_USE_MCR", 0);
     1757
     1758        vms_always_use_cmd_file = get_vms_env_flag ("GNV$MAKE_USE_CMD_FILE", 0);
     1759
     1760        /* Legacy behavior is on VMS is older behavior that needed to be
     1761           changed to be compatible with standard make behavior.
     1762           For now only completely disable when running under a Bash shell.
     1763           TODO: Update VMS built in recipes and macros to not need this
     1764           behavior, at which time the default may change. */
     1765        vms_legacy_behavior = get_vms_env_flag ("GNV$MAKE_OLD_VMS",
     1766                                                !vms_gnv_shell);
     1767
     1768        /* VMS was changed to use a comma separator in the past, but that is
     1769           incompatible with built in functions that expect space separated
     1770           lists.  Allow this to be selectively turned off. */
     1771        vms_comma_separator = get_vms_env_flag ("GNV$MAKE_COMMA",
     1772                                                vms_legacy_behavior);
     1773
     1774        /* Some Posix shell syntax options are incompatible with VMS syntax.
     1775           VMS requires double quotes for strings and escapes quotes
     1776           differently.  When this option is active, VMS will try
     1777           to simulate Posix shell simulations instead of using
     1778           VMS DCL behavior. */
     1779        vms_unix_simulation = get_vms_env_flag ("GNV$MAKE_SHELL_SIM",
     1780                                                !vms_legacy_behavior);
     1781
     1782      }
     1783      if (need_vms_symbol () && !vms_use_mcr_command)
     1784        create_foreign_command (program_name, argv[0]);
     1785#else
    16181786      if (program == 0)
    1619         program = argv[0];
     1787        program = argv[0];
    16201788      else
    1621         ++program;
     1789        ++program;
     1790#endif
    16221791    }
    16231792
     
    16441813#endif
    16451814    {
    1646 #ifdef  HAVE_GETCWD
     1815#ifdef  HAVE_GETCWD
    16471816      perror_with_name ("getcwd", "");
    16481817#else
    1649       error (NILF, "getwd: %s", current_directory);
     1818      OS (error, NILF, "getwd: %s", current_directory);
    16501819#endif
    16511820      current_directory[0] = '\0';
     
    16541823  else
    16551824    directory_before_chdir = xstrdup (current_directory);
     1825
    16561826#ifdef  __MSDOS__
    16571827  /* Make sure we will return to the initial directory, come what may.  */
     
    16641834  define_variable_cname (".RECIPEPREFIX", "", o_default, 0)->special = 1;
    16651835  define_variable_cname (".SHELLFLAGS", "-c", o_default, 0);
     1836  define_variable_cname (".LOADED", "", o_default, 0);
    16661837
    16671838  /* Set up .FEATURES
    1668      We must do this in multiple calls because define_variable_cname() is
    1669      a macro and some compilers (MSVC) don't like conditionals in macros.  */
     1839     Use a separate variable because define_variable_cname() is a macro and
     1840     some compilers (MSVC) don't like conditionals in macros.  */
    16701841  {
    16711842    const char *features = "target-specific order-only second-expansion"
    1672                            " else-if shortest-stem undefine"
     1843                           " else-if shortest-stem undefine oneshell"
    16731844#ifndef NO_ARCHIVES
    16741845                           " archives"
     
    16771848                           " jobserver"
    16781849#endif
     1850#ifndef NO_OUTPUT_SYNC
     1851                           " output-sync"
     1852#endif
    16791853#ifdef MAKE_SYMLINKS
    16801854                           " check-symlink"
    16811855#endif
     1856#ifdef HAVE_GUILE
     1857                           " guile"
     1858#endif
     1859#ifdef MAKE_LOAD
     1860                           " load"
     1861#endif
    16821862#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
    16831863                           " explicit-multitarget"
     
    16931873#ifdef KMK
    16941874  /* Initialize the default number of jobs to the cpu/core/smt count. */
    1695   default_job_slots = job_slots = get_online_cpu_count ();
     1875  default_job_slots = arg_job_slots = job_slots = get_online_cpu_count ();
    16961876#endif /* KMK */
     1877
     1878  /* Configure GNU Guile support */
     1879  guile_gmake_setup (NILF);
    16971880
    16981881  /* Read in variables from the environment.  It is important that this be
     
    17061889    for (i = 0; envp[i] != 0; ++i)
    17071890      {
    1708         int do_not_define = 0;
    1709         char *ep = envp[i];
    1710 
    1711         while (*ep != '\0' && *ep != '=')
     1891        struct variable *v;
     1892        const char *ep = envp[i];
     1893        /* By default, export all variables culled from the environment.  */
     1894        enum variable_export export = v_export;
     1895        unsigned int len;
     1896
     1897        while (! STOP_SET (*ep, MAP_EQUALS))
    17121898          ++ep;
     1899
     1900        /* If there's no equals sign it's a malformed environment.  Ignore.  */
     1901        if (*ep == '\0')
     1902          continue;
     1903
    17131904#ifdef WINDOWS32
    1714         if (!unix_path && strneq(envp[i], "PATH=", 5))
     1905        if (!unix_path && strneq (envp[i], "PATH=", 5))
    17151906          unix_path = ep+1;
    1716         else if (!strnicmp(envp[i], "Path=", 5)) {
    1717           do_not_define = 1; /* it gets defined after loop exits */
    1718           if (!windows32_path)
    1719             windows32_path = ep+1;
    1720         }
    1721 #endif
    1722         /* The result of pointer arithmetic is cast to unsigned int for
    1723            machines where ptrdiff_t is a different size that doesn't widen
    1724            the same.  */
    1725         if (!do_not_define)
     1907        else if (!strnicmp (envp[i], "Path=", 5))
    17261908          {
    1727             struct variable *v;
    1728 
    1729             v = define_variable (envp[i], (unsigned int) (ep - envp[i]),
    1730                                  ep + 1, o_env, 1);
    1731             /* Force exportation of every variable culled from the
    1732                environment.  We used to rely on target_environment's
    1733                v_default code to do this.  But that does not work for the
    1734                case where an environment variable is redefined in a makefile
    1735                with `override'; it should then still be exported, because it
    1736                was originally in the environment.  */
    1737             v->export = v_export;
    1738 
    1739             /* Another wrinkle is that POSIX says the value of SHELL set in
    1740                the makefile won't change the value of SHELL given to
    1741                subprocesses.  */
    1742             if (streq (v->name, "SHELL"))
     1909            if (!windows32_path)
     1910              windows32_path = ep+1;
     1911            /* PATH gets defined after the loop exits.  */
     1912            continue;
     1913          }
     1914#endif
     1915
     1916        /* Length of the variable name, and skip the '='.  */
     1917        len = ep++ - envp[i];
     1918
     1919        /* If this is MAKE_RESTARTS, check to see if the "already printed
     1920           the enter statement" flag is set.  */
     1921        if (len == 13 && strneq (envp[i], "MAKE_RESTARTS", 13))
     1922          {
     1923            if (*ep == '-')
    17431924              {
     1925                OUTPUT_TRACED ();
     1926                ++ep;
     1927              }
     1928            restarts = (unsigned int) atoi (ep);
     1929            export = v_noexport;
     1930          }
     1931
     1932        v = define_variable (envp[i], len, ep, o_env, 1);
     1933
     1934        /* POSIX says the value of SHELL set in the makefile won't change the
     1935           value of SHELL given to subprocesses.  */
     1936        if (streq (v->name, "SHELL"))
     1937          {
    17441938#ifndef __MSDOS__
    1745                 v->export = v_noexport;
     1939            export = v_noexport;
    17461940#endif
    17471941#ifndef CONFIG_WITH_STRCACHE2
    1748                 shell_var.name = "SHELL";
     1942            shell_var.name = xstrdup ("SHELL");
    17491943#else
    1750                 shell_var.name = v->name;
    1751 #endif
    1752                 shell_var.length = 5;
     1944            shell_var.name = v->name;
     1945#endif
     1946            shell_var.length = 5;
    17531947#ifndef CONFIG_WITH_VALUE_LENGTH
    1754                 shell_var.value = xstrdup (ep + 1);
     1948            shell_var.value = xstrdup (ep);
    17551949#else
    1756                 shell_var.value = xstrndup (v->value, v->value_length);
    1757                 shell_var.value_length = v->value_length;
    1758 #endif
    1759               }
    1760 
    1761             /* If MAKE_RESTARTS is set, remember it but don't export it.  */
    1762             if (streq (v->name, "MAKE_RESTARTS"))
    1763               {
    1764                 v->export = v_noexport;
    1765                 restarts = (unsigned int) atoi (ep + 1);
    1766               }
     1950            shell_var.value = xstrndup (v->value, v->value_length);
     1951            shell_var.value_length = v->value_length;
     1952#endif
    17671953          }
     1954
     1955        v->export = export;
    17681956      }
    17691957  }
    17701958#ifdef WINDOWS32
    17711959    /* If we didn't find a correctly spelled PATH we define PATH as
    1772      * either the first mispelled value or an empty string
     1960     * either the first misspelled value or an empty string
    17731961     */
    17741962    if (!unix_path)
     
    17781966#else /* For Amiga, read the ENV: device, ignoring all dirs */
    17791967    {
    1780         BPTR env, file, old;
    1781         char buffer[1024];
    1782         int len;
    1783         __aligned struct FileInfoBlock fib;
    1784 
    1785         env = Lock ("ENV:", ACCESS_READ);
    1786         if (env)
    1787         {
    1788             old = CurrentDir (DupLock(env));
    1789             Examine (env, &fib);
    1790 
    1791             while (ExNext (env, &fib))
    1792             {
    1793                 if (fib.fib_DirEntryType < 0) /* File */
    1794                 {
    1795                     /* Define an empty variable. It will be filled in
    1796                         variable_lookup(). Makes startup quite a bit
    1797                         faster. */
    1798                         define_variable (fib.fib_FileName,
    1799                             strlen (fib.fib_FileName),
    1800                         "", o_env, 1)->export = v_export;
    1801                 }
    1802             }
    1803             UnLock (env);
    1804             UnLock(CurrentDir(old));
    1805         }
     1968        BPTR env, file, old;
     1969        char buffer[1024];
     1970        int len;
     1971        __aligned struct FileInfoBlock fib;
     1972
     1973        env = Lock ("ENV:", ACCESS_READ);
     1974        if (env)
     1975          {
     1976            old = CurrentDir (DupLock (env));
     1977            Examine (env, &fib);
     1978
     1979            while (ExNext (env, &fib))
     1980              {
     1981                if (fib.fib_DirEntryType < 0) /* File */
     1982                  {
     1983                    /* Define an empty variable. It will be filled in
     1984                       variable_lookup(). Makes startup quite a bit faster. */
     1985                    define_variable (fib.fib_FileName,
     1986                                     strlen (fib.fib_FileName),
     1987                                     "", o_env, 1)->export = v_export;
     1988                  }
     1989              }
     1990            UnLock (env);
     1991            UnLock (CurrentDir (old));
     1992          }
    18061993    }
    18071994#endif
    18081995
    18091996  /* Decode the switches.  */
     1997  decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
     1998
     1999  /* Clear GNUMAKEFLAGS to avoid duplication.  */
     2000  define_variable_cname ("GNUMAKEFLAGS", "", o_env, 0);
    18102001
    18112002#ifdef KMK
     
    18132004#else /* !KMK */
    18142005  decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
     2006
    18152007#if 0
    18162008  /* People write things like:
     
    18212013#endif /* !KMK */
    18222014
    1823   decode_switches (argc, argv, 0);
    1824 
    1825 #ifdef WINDOWS32
    1826   if (suspend_flag) {
    1827         fprintf(stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId());
    1828         fprintf(stderr, _("%s is suspending for 30 seconds..."), argv[0]);
    1829         Sleep(30 * 1000);
    1830         fprintf(stderr, _("done sleep(30). Continuing.\n"));
     2015  /* In output sync mode we need to sync any output generated by reading the
     2016     makefiles, such as in $(info ...) or stderr from $(shell ...) etc.  */
     2017
     2018  syncing = make_sync.syncout = (output_sync == OUTPUT_SYNC_LINE
     2019                                 || output_sync == OUTPUT_SYNC_TARGET);
     2020  OUTPUT_SET (&make_sync);
     2021
     2022  /* Remember the job slots set through the environment vs. command line.  */
     2023  {
     2024    int env_slots = arg_job_slots;
     2025    arg_job_slots = INVALID_JOB_SLOTS;
     2026
     2027    decode_switches (argc, (const char **)argv, 0);
     2028    argv_slots = arg_job_slots;
     2029
     2030    if (arg_job_slots == INVALID_JOB_SLOTS)
     2031      arg_job_slots = env_slots;
    18312032  }
    1832 #endif
    1833 
    1834   decode_debug_flags ();
     2033
     2034  /* Set a variable specifying whether stdout/stdin is hooked to a TTY.  */
     2035#ifdef HAVE_ISATTY
     2036  if (isatty (fileno (stdout)))
     2037    if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMOUT")))
     2038      {
     2039        const char *tty = TTYNAME (fileno (stdout));
     2040        define_variable_cname ("MAKE_TERMOUT", tty ? tty : DEFAULT_TTYNAME,
     2041                               o_default, 0)->export = v_export;
     2042      }
     2043  if (isatty (fileno (stderr)))
     2044    if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMERR")))
     2045      {
     2046        const char *tty = TTYNAME (fileno (stderr));
     2047        define_variable_cname ("MAKE_TERMERR", tty ? tty : DEFAULT_TTYNAME,
     2048                               o_default, 0)->export = v_export;
     2049      }
     2050#endif
     2051
     2052  /* Reset in case the switches changed our minds.  */
     2053  syncing = (output_sync == OUTPUT_SYNC_LINE
     2054             || output_sync == OUTPUT_SYNC_TARGET);
    18352055
    18362056#ifdef KMK
     
    18382058#endif
    18392059
     2060  if (make_sync.syncout && ! syncing)
     2061    output_close (&make_sync);
     2062
     2063  make_sync.syncout = syncing;
     2064  OUTPUT_SET (&make_sync);
     2065
     2066  /* Figure out the level of recursion.  */
     2067  {
     2068    struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
     2069    if (v && v->value[0] != '\0' && v->value[0] != '-')
     2070      makelevel = (unsigned int) atoi (v->value);
     2071    else
     2072      makelevel = 0;
     2073  }
     2074
     2075#ifdef WINDOWS32
     2076  if (suspend_flag)
     2077    {
     2078      fprintf (stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId ());
     2079      fprintf (stderr, _("%s is suspending for 30 seconds..."), argv[0]);
     2080      Sleep (30 * 1000);
     2081      fprintf (stderr, _("done sleep(30). Continuing.\n"));
     2082    }
     2083#endif
     2084
    18402085  /* Set always_make_flag if -B was given and we've not restarted already.  */
    18412086  always_make_flag = always_make_set && (restarts == 0);
    18422087
    1843   /* Print version information.  */
    1844   if (print_version_flag || print_data_base_flag || db_level)
     2088  /* Print version information, and exit.  */
     2089  if (print_version_flag)
    18452090    {
    18462091      print_version ();
    1847 
    1848       /* `make --version' is supposed to just print the version and exit.  */
    1849       if (print_version_flag)
    1850         die (0);
    1851     }
     2092      die (MAKE_SUCCESS);
     2093    }
     2094
     2095  if (ISDB (DB_BASIC))
     2096    print_version ();
    18522097
    18532098#ifndef VMS
     
    18642109   * CreateProcess().
    18652110   */
    1866   if (strpbrk(argv[0], "/:\\") ||
    1867       strstr(argv[0], "..") ||
    1868       strneq(argv[0], "//", 2))
    1869     argv[0] = xstrdup(w32ify(argv[0],1));
     2111  if (strpbrk (argv[0], "/:\\") || strstr (argv[0], "..")
     2112      || strneq (argv[0], "//", 2))
     2113    argv[0] = xstrdup (w32ify (argv[0], 1));
    18702114#else /* WINDOWS32 */
    18712115#if defined (__MSDOS__) || defined (__EMX__)
     
    18762120      argv[0] = xstrdup (argv[0]);
    18772121      for (p = argv[0]; *p; p++)
    1878         if (*p == '\\')
    1879           *p = '/';
     2122        if (*p == '\\')
     2123          *p = '/';
    18802124    }
    18812125  /* If argv[0] is not in absolute form, prepend the current
     
    19042148#endif
    19052149
     2150  /* We may move, but until we do, here we are.  */
     2151  starting_directory = current_directory;
     2152
     2153  /* Set up the job_slots value and the jobserver.  This can't be usefully set
     2154     in the makefile, and we want to verify the authorization is valid before
     2155     make has a chance to start using it for something else.  */
     2156
     2157  if (jobserver_auth)
     2158    {
     2159      if (argv_slots == INVALID_JOB_SLOTS)
     2160        {
     2161          if (jobserver_parse_auth (jobserver_auth))
     2162            {
     2163              /* Success!  Use the jobserver.  */
     2164              job_slots = 0;
     2165              goto job_setup_complete;
     2166            }
     2167
     2168          O (error, NILF, _("warning: jobserver unavailable: using -j1.  Add '+' to parent make rule."));
     2169          arg_job_slots = 1;
     2170        }
     2171
     2172      /* The user provided a -j setting on the command line: use it.  */
     2173      else if (!restarts)
     2174        /* If restarts is >0 we already printed this message.  */
     2175        O (error, NILF,
     2176           _("warning: -jN forced in submake: disabling jobserver mode."));
     2177
     2178      /* We failed to use our parent's jobserver.  */
     2179      reset_jobserver ();
     2180      job_slots = (unsigned int)arg_job_slots;
     2181    }
     2182  else if (arg_job_slots == INVALID_JOB_SLOTS)
     2183#ifdef KMK
     2184    job_slots = default_job_slots; /* The default is set to CPU count early in main. */
     2185#else
     2186    /* The default is one job at a time.  */
     2187    job_slots = 1;
     2188#endif
     2189  else
     2190    /* Use whatever was provided.  */
     2191    job_slots = (unsigned int)arg_job_slots;
     2192
     2193 job_setup_complete:
     2194
    19062195  /* The extra indirection through $(MAKE_COMMAND) is done
    19072196     for hysterical raisins.  */
     2197
     2198#ifdef VMS
     2199  if (vms_use_mcr_command)
     2200    define_variable_cname ("MAKE_COMMAND", vms_command (argv[0]), o_default, 0);
     2201  else
     2202    define_variable_cname ("MAKE_COMMAND", program, o_default, 0);
     2203#else
    19082204  define_variable_cname ("MAKE_COMMAND", argv[0], o_default, 0);
     2205#endif
    19092206  define_variable_cname ("MAKE", "$(MAKE_COMMAND)", o_default, 1);
    19102207#ifdef KMK
     
    19202217
    19212218      /* Figure out how much space will be taken up by the command-line
    1922         variable definitions.  */
     2219        variable definitions.  */
    19232220      for (cv = command_variables; cv != 0; cv = cv->next)
    1924         {
    1925           v = cv->variable;
    1926           len += 2 * strlen (v->name);
    1927           if (! v->recursive)
    1928             ++len;
    1929           ++len;
    1930           len += 2 * strlen (v->value);
    1931           ++len;
    1932         }
     2221        {
     2222          v = cv->variable;
     2223          len += 2 * strlen (v->name);
     2224          if (! v->recursive)
     2225            ++len;
     2226          ++len;
     2227          len += 2 * strlen (v->value);
     2228          ++len;
     2229        }
    19332230
    19342231      /* Now allocate a buffer big enough and fill it.  */
    19352232      p = value = alloca (len);
    19362233      for (cv = command_variables; cv != 0; cv = cv->next)
    1937         {
    1938           v = cv->variable;
    1939           p = quote_for_env (p, v->name);
    1940           if (! v->recursive)
    1941             *p++ = ':';
    1942           *p++ = '=';
    1943           p = quote_for_env (p, v->value);
    1944           *p++ = ' ';
    1945         }
    1946       p[-1] = '\0';             /* Kill the final space and terminate.  */
     2234        {
     2235          v = cv->variable;
     2236          p = quote_for_env (p, v->name);
     2237          if (! v->recursive)
     2238            *p++ = ':';
     2239          *p++ = '=';
     2240          p = quote_for_env (p, v->value);
     2241          *p++ = ' ';
     2242        }
     2243      p[-1] = '\0';             /* Kill the final space and terminate.  */
    19472244
    19482245      /* Define an unchangeable variable with a name that no POSIX.2
    1949         makefile could validly use for its own variable.  */
     2246        makefile could validly use for its own variable.  */
    19502247      define_variable_cname ("-*-command-variables-*-", value, o_automatic, 0);
    19512248
     
    19622259      define_variable_cname ("MAKEOVERRIDES", "${-*-command-variables-*-}",
    19632260                             o_env, 1);
     2261#endif
     2262#ifdef VMS
     2263      vms_export_dcl_symbol ("MAKEOVERRIDES", "${-*-command-variables-*-}");
    19642264#endif
    19652265    }
     
    20322332
    20332333          if (up_levels >= 16)
    2034             fatal (NILF, _("Makefile.kup recursion is too deep."));
     2334            O (fatal, NILF, _("Makefile.kup recursion is too deep."));
    20352335
    20362336          /* attempt to change to the directory. */
     
    20702370#ifdef KMK /* this is really a candidate for all platforms... */
    20712371  {
    2072     extern char *default_shell;
     2372    extern const char *default_shell;
    20732373    const char *bin = get_kbuild_bin_path();
     2374    char *newshell;
    20742375    size_t len = strlen (bin);
    2075     default_shell = xmalloc (len + sizeof("/kmk_ash.exe"));
    2076     memcpy (default_shell, bin, len);
    2077     strcpy (default_shell + len, "/kmk_ash.exe");
     2376    default_shell = newshell = xmalloc (len + sizeof("/kmk_ash.exe"));
     2377    memcpy (newshell, bin, len);
     2378    strcpy (newshell + len, "/kmk_ash.exe");
    20782379    no_default_sh_exe = 0;
    20792380    batch_mode_shell = 1;
     
    20812382  }
    20822383#else /* !KMK */
    2083    no_default_sh_exe = !find_and_set_default_shell(NULL);
     2384   no_default_sh_exe = !find_and_set_default_shell (NULL);
    20842385#endif /* !KMK */
    20852386#endif /* WINDOWS32 */
    2086   /* Figure out the level of recursion.  */
    2087   {
    2088     struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
    2089     if (v != 0 && v->value[0] != '\0' && v->value[0] != '-')
    2090       makelevel = (unsigned int) atoi (v->value);
    2091     else
    2092       makelevel = 0;
    2093   }
    20942387
    20952388  /* Except under -s, always do -w in sub-makes and under -C.  */
     
    21102403                          ? 0 : include_directories->list);
    21112404
    2112   /* Figure out where we are now, after chdir'ing.  */
    2113   if (directories == 0)
    2114     /* We didn't move, so we're still in the same place.  */
    2115     starting_directory = current_directory;
    2116   else
     2405  /* If we chdir'ed, figure out where we are now.  */
     2406  if (directories)
    21172407    {
    21182408#ifdef WINDOWS32
     
    21212411      if (getcwd (current_directory, GET_PATH_MAX) == 0)
    21222412#endif
    2123         {
    2124 #ifdef  HAVE_GETCWD
    2125           perror_with_name ("getcwd", "");
     2413        {
     2414#ifdef  HAVE_GETCWD
     2415          perror_with_name ("getcwd", "");
    21262416#else
    2127           error (NILF, "getwd: %s", current_directory);
    2128 #endif
    2129           starting_directory = 0;
    2130         }
     2417          OS (error, NILF, "getwd: %s", current_directory);
     2418#endif
     2419          starting_directory = 0;
     2420        }
    21312421      else
    2132         starting_directory = current_directory;
     2422        starting_directory = current_directory;
    21332423    }
    21342424
     
    21412431      unsigned int i;
    21422432      for (i = 0; i < makefiles->idx; ++i)
    2143         if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
    2144           {
    2145             /* This makefile is standard input.  Since we may re-exec
    2146                and thus re-read the makefiles, we read standard input
    2147                into a temporary file and read from that.  */
    2148             FILE *outfile;
    2149             char *template, *tmpdir;
     2433        if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
     2434          {
     2435            /* This makefile is standard input.  Since we may re-exec
     2436               and thus re-read the makefiles, we read standard input
     2437               into a temporary file and read from that.  */
     2438            FILE *outfile;
     2439            char *template;
     2440            const char *tmpdir;
    21502441
    21512442            if (stdin_nm)
    2152               fatal (NILF, _("Makefile from standard input specified twice."));
     2443              O (fatal, NILF,
     2444                 _("Makefile from standard input specified twice."));
    21532445
    21542446#ifdef VMS
    2155 # define DEFAULT_TMPDIR     "sys$scratch:"
     2447# define DEFAULT_TMPDIR     "/sys$scratch/"
    21562448#else
    21572449# ifdef P_tmpdir
     
    21632455#define DEFAULT_TMPFILE     "GmXXXXXX"
    21642456
    2165             if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
     2457            if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
    21662458#if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
    21672459                /* These are also used commonly on these platforms.  */
     
    21702462#endif
    21712463               )
    2172               tmpdir = DEFAULT_TMPDIR;
    2173 
    2174             template = alloca (strlen (tmpdir) + sizeof (DEFAULT_TMPFILE) + 1);
    2175             strcpy (template, tmpdir);
     2464              tmpdir = DEFAULT_TMPDIR;
     2465
     2466            template = alloca (strlen (tmpdir) + CSTRLEN (DEFAULT_TMPFILE) + 2);
     2467            strcpy (template, tmpdir);
    21762468
    21772469#ifdef HAVE_DOS_PATHS
    2178             if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
    2179               strcat (template, "/");
     2470            if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
     2471              strcat (template, "/");
    21802472#else
    21812473# ifndef VMS
    2182             if (template[strlen (template) - 1] != '/')
    2183               strcat (template, "/");
     2474            if (template[strlen (template) - 1] != '/')
     2475              strcat (template, "/");
    21842476# endif /* !VMS */
    21852477#endif /* !HAVE_DOS_PATHS */
    21862478
    2187             strcat (template, DEFAULT_TMPFILE);
    2188             outfile = open_tmpfile (&stdin_nm, template);
    2189             if (outfile == 0)
    2190               pfatal_with_name (_("fopen (temporary file)"));
    2191             while (!feof (stdin) && ! ferror (stdin))
    2192               {
    2193                 char buf[2048];
    2194                 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
    2195                 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
    2196                   pfatal_with_name (_("fwrite (temporary file)"));
    2197               }
    2198             fclose (outfile);
    2199 
    2200             /* Replace the name that read_all_makefiles will
    2201                see with the name of the temporary file.  */
     2479            strcat (template, DEFAULT_TMPFILE);
     2480            outfile = output_tmpfile (&stdin_nm, template);
     2481            if (outfile == 0)
     2482              pfatal_with_name (_("fopen (temporary file)"));
     2483            while (!feof (stdin) && ! ferror (stdin))
     2484              {
     2485                char buf[2048];
     2486                unsigned int n = fread (buf, 1, sizeof (buf), stdin);
     2487                if (n > 0 && fwrite (buf, 1, n, outfile) != n)
     2488                  pfatal_with_name (_("fwrite (temporary file)"));
     2489              }
     2490            fclose (outfile);
     2491
     2492            /* Replace the name that read_all_makefiles will
     2493               see with the name of the temporary file.  */
    22022494            makefiles->list[i] = strcache_add (stdin_nm);
    22032495
    2204             /* Make sure the temporary file will not be remade.  */
     2496            /* Make sure the temporary file will not be remade.  */
    22052497            {
    22062498              struct file *f = enter_file (strcache_add (stdin_nm));
    22072499              f->updated = 1;
    2208               f->update_status = 0;
     2500              f->update_status = us_success;
    22092501              f->command_state = cs_finished;
    22102502              /* Can't be intermediate, or it'll be removed too early for
     
    22132505              f->dontcare = 0;
    22142506            }
    2215           }
     2507          }
    22162508    }
    22172509
    22182510#if !defined(__EMX__) || defined(__KLIBC__) /* Don't use a SIGCHLD handler for good old EMX (bird) */
    2219 #if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
     2511#if !defined(HAVE_WAIT_NOHANG) || defined(MAKE_JOBSERVER)
    22202512  /* Set up to handle children dying.  This must be done before
    2221      reading in the makefiles so that `shell' function calls will work.
     2513     reading in the makefiles so that 'shell' function calls will work.
    22222514
    22232515     If we don't have a hanging wait we have to fall back to old, broken
     
    22252517     children.
    22262518
    2227      If we're using the jobs pipe we need a signal handler so that
    2228      SIGCHLD is not ignored; we need it to interrupt the read(2) of the
    2229      jobserver pipe in job.c if we're waiting for a token.
     2519     If we're using the jobs pipe we need a signal handler so that SIGCHLD is
     2520     not ignored; we need it to interrupt the read(2) of the jobserver pipe if
     2521     we're waiting for a token.
    22302522
    22312523     If none of these are true, we don't need a signal handler at all.  */
    22322524  {
    2233     RETSIGTYPE child_handler (int sig);
    22342525# if defined SIGCHLD
    22352526    bsd_signal (SIGCHLD, child_handler);
     
    22392530# endif
    22402531  }
     2532
     2533#ifdef HAVE_PSELECT
     2534  /* If we have pselect() then we need to block SIGCHLD so it's deferred.  */
     2535  {
     2536    sigset_t block;
     2537    sigemptyset (&block);
     2538    sigaddset (&block, SIGCHLD);
     2539    if (sigprocmask (SIG_SETMASK, &block, NULL) < 0)
     2540      pfatal_with_name ("sigprocmask(SIG_SETMASK, SIGCHLD)");
     2541  }
     2542#endif
     2543
    22412544#endif
    22422545#endif
     
    22482551
    22492552  /* Define the initial list of suffixes for old-style rules.  */
    2250 
    22512553  set_default_suffixes ();
    22522554
     
    22562558     makefiles, it results in the built-in pattern rules taking precedence
    22572559     over makefile-specified suffix rules, which is wrong.  */
    2258 
    22592560  install_default_suffix_rules ();
    22602561
    22612562  /* Define some internal and special variables.  */
    2262 
    22632563  define_automatic_variables ();
    22642564
    2265   /* Set up the MAKEFLAGS and MFLAGS variables
    2266      so makefiles can look at them.  */
    2267 
    2268   define_makeflags (0, 0);
     2565  /* Set up the MAKEFLAGS and MFLAGS variables for makefiles to see.
     2566     Initialize it to be exported but allow the makefile to reset it.  */
     2567  define_makeflags (0, 0)->export = v_export;
    22692568
    22702569  /* Define the default variables.  */
     
    22822581      char *p, *value;
    22832582      unsigned int i;
    2284       unsigned int len = sizeof ("--eval=") * eval_strings->idx;
     2583      unsigned int len = (CSTRLEN ("--eval=") + 1) * eval_strings->idx;
    22852584
    22862585      for (i = 0; i < eval_strings->idx; ++i)
     
    22892588          p = xstrdup (eval_strings->list[i]);
    22902589          len += 2 * strlen (p);
    2291           eval_buffer (p);
     2590          eval_buffer (p, NULL);
    22922591#else
    22932592          unsigned int sub_len = strlen(eval_strings->list[i]);
    22942593          p = xstrndup (eval_strings->list[i], sub_len);
    22952594          len += 2 * sub_len;
    2296           eval_buffer (p, p + sub_len);
     2595          eval_buffer (p, NULL, p + sub_len);
    22972596#endif
    22982597          free (p);
     
    23032602        {
    23042603          strcpy (p, "--eval=");
    2305           p += strlen (p);
     2604          p += CSTRLEN ("--eval=");
    23062605          p = quote_for_env (p, eval_strings->list[i]);
    23072606          *(p++) = ' ';
     
    23142613  /* Read all the makefiles.  */
    23152614
    2316   read_makefiles
    2317     = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
     2615  read_files = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
    23182616
    23192617#ifdef WINDOWS32
    23202618  /* look one last time after reading all Makefiles */
    23212619  if (no_default_sh_exe)
    2322     no_default_sh_exe = !find_and_set_default_shell(NULL);
     2620    no_default_sh_exe = !find_and_set_default_shell (NULL);
    23232621#endif /* WINDOWS32 */
    23242622
    2325 #if defined (__MSDOS__) || defined (__EMX__)
     2623#if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
    23262624  /* We need to know what kind of shell we will be using.  */
    23272625  {
     
    23292627    struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
    23302628    extern int unixy_shell;
    2331     extern char *default_shell;
     2629    extern const char *default_shell;
    23322630
    23332631    if (shv && *shv->value)
    23342632      {
    2335         char *shell_path = recursively_expand(shv);
    2336 
    2337         if (shell_path && _is_unixy_shell (shell_path))
    2338           unixy_shell = 1;
    2339         else
    2340           unixy_shell = 0;
    2341         if (shell_path)
    2342           default_shell = shell_path;
     2633        char *shell_path = recursively_expand (shv);
     2634
     2635        if (shell_path && _is_unixy_shell (shell_path))
     2636          unixy_shell = 1;
     2637        else
     2638          unixy_shell = 0;
     2639        if (shell_path)
     2640          default_shell = shell_path;
    23432641      }
    23442642  }
    23452643#endif /* __MSDOS__ || __EMX__ */
    23462644
    2347   /* Decode switches again, in case the variables were set by the makefile.  */
     2645  {
     2646    int old_builtin_rules_flag = no_builtin_rules_flag;
     2647    int old_builtin_variables_flag = no_builtin_variables_flag;
     2648
     2649    /* Decode switches again, for variables set by the makefile.  */
     2650    decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
     2651
     2652    /* Clear GNUMAKEFLAGS to avoid duplication.  */
     2653    define_variable_cname ("GNUMAKEFLAGS", "", o_override, 0);
     2654
    23482655#ifdef KMK
    2349   decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
     2656    decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
    23502657#else /* !KMK */
    2351   decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
     2658    decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
    23522659#if 0
    2353   decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
     2660    decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
    23542661#endif
    23552662#endif /* !KMK */
    23562663
    2357 #if defined (__MSDOS__) || defined (__EMX__)
    2358   if (job_slots != 1
     2664    /* Reset in case the switches changed our mind.  */
     2665    syncing = (output_sync == OUTPUT_SYNC_LINE
     2666               || output_sync == OUTPUT_SYNC_TARGET);
     2667
     2668    if (make_sync.syncout && ! syncing)
     2669      output_close (&make_sync);
     2670
     2671    make_sync.syncout = syncing;
     2672    OUTPUT_SET (&make_sync);
     2673
     2674    /* If we've disabled builtin rules, get rid of them.  */
     2675    if (no_builtin_rules_flag && ! old_builtin_rules_flag)
     2676      {
     2677        if (suffix_file->builtin)
     2678          {
     2679            free_dep_chain (suffix_file->deps);
     2680            suffix_file->deps = 0;
     2681          }
     2682        define_variable_cname ("SUFFIXES", "", o_default, 0);
     2683      }
     2684
     2685    /* If we've disabled builtin variables, get rid of them.  */
     2686    if (no_builtin_variables_flag && ! old_builtin_variables_flag)
     2687      undefine_default_variables ();
     2688  }
     2689
     2690#if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
     2691  if (arg_job_slots != 1
    23592692# ifdef __EMX__
    23602693      && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
     
    23622695      )
    23632696    {
    2364       error (NILF,
    2365              _("Parallel jobs (-j) are not supported on this platform."));
    2366       error (NILF, _("Resetting to single job (-j1) mode."));
    2367       job_slots = 1;
    2368     }
    2369 #endif
    2370 
    2371 #ifdef MAKE_JOBSERVER
    2372   /* If the jobserver-fds option is seen, make sure that -j is reasonable.  */
    2373 
    2374   if (jobserver_fds)
    2375     {
    2376       const char *cp;
    2377       unsigned int ui;
    2378 
    2379       for (ui=1; ui < jobserver_fds->idx; ++ui)
    2380         if (!streq (jobserver_fds->list[0], jobserver_fds->list[ui]))
    2381           fatal (NILF, _("internal error: multiple --jobserver-fds options"));
    2382 
    2383       /* Now parse the fds string and make sure it has the proper format.  */
    2384 
    2385       cp = jobserver_fds->list[0];
    2386 
    2387       if (sscanf (cp, "%d,%d", &job_fds[0], &job_fds[1]) != 2)
    2388         fatal (NILF,
    2389                _("internal error: invalid --jobserver-fds string `%s'"), cp);
    2390 
    2391       DB (DB_JOBS,
    2392           (_("Jobserver client (fds %d,%d)\n"), job_fds[0], job_fds[1]));
    2393 
    2394       /* The combination of a pipe + !job_slots means we're using the
    2395          jobserver.  If !job_slots and we don't have a pipe, we can start
    2396          infinite jobs.  If we see both a pipe and job_slots >0 that means the
    2397          user set -j explicitly.  This is broken; in this case obey the user
    2398          (ignore the jobserver pipe for this make) but print a message.  */
    2399 
    2400       if (job_slots > 0)
    2401         error (NILF,
    2402                _("warning: -jN forced in submake: disabling jobserver mode."));
    2403 
    2404       /* Create a duplicate pipe, that will be closed in the SIGCHLD
    2405          handler.  If this fails with EBADF, the parent has closed the pipe
    2406          on us because it didn't think we were a submake.  If so, print a
    2407          warning then default to -j1.  */
    2408 
    2409       else if ((job_rfd = dup (job_fds[0])) < 0)
     2697      O (error, NILF,
     2698         _("Parallel jobs (-j) are not supported on this platform."));
     2699      O (error, NILF, _("Resetting to single job (-j1) mode."));
     2700      arg_job_slots = job_slots = 1;
     2701    }
     2702#endif
     2703
     2704  /* If we have >1 slot at this point, then we're a top-level make.
     2705     Set up the jobserver.
     2706
     2707     Every make assumes that it always has one job it can run.  For the
     2708     submakes it's the token they were given by their parent.  For the top
     2709     make, we just subtract one from the number the user wants.  */
     2710
     2711  if (job_slots > 1 && jobserver_setup (job_slots - 1))
     2712    {
     2713      /* Fill in the jobserver_auth for our children.  */
     2714      jobserver_auth = jobserver_get_auth ();
     2715
     2716      if (jobserver_auth)
    24102717        {
    2411           if (errno != EBADF)
    2412             pfatal_with_name (_("dup jobserver"));
    2413 
    2414           error (NILF,
    2415                  _("warning: jobserver unavailable: using -j1.  Add `+' to parent make rule."));
    2416           job_slots = 1;
     2718          /* We're using the jobserver so set job_slots to 0.  */
     2719          master_job_slots = job_slots;
     2720          job_slots = 0;
    24172721        }
    2418 
    2419       if (job_slots > 0)
    2420         {
    2421           close (job_fds[0]);
    2422           close (job_fds[1]);
    2423           job_fds[0] = job_fds[1] = -1;
    2424           free (jobserver_fds->list);
    2425           free (jobserver_fds);
    2426           jobserver_fds = 0;
    2427         }
    2428     }
    2429 
    2430   /* If we have >1 slot but no jobserver-fds, then we're a top-level make.
    2431      Set up the pipe and install the fds option for our children.  */
    2432 
    2433   if (job_slots > 1)
    2434     {
    2435       char *cp;
    2436       char c = '+';
    2437 
    2438       if (pipe (job_fds) < 0 || (job_rfd = dup (job_fds[0])) < 0)
    2439         pfatal_with_name (_("creating jobs pipe"));
    2440 
    2441       /* Every make assumes that it always has one job it can run.  For the
    2442          submakes it's the token they were given by their parent.  For the
    2443          top make, we just subtract one from the number the user wants.  We
    2444          want job_slots to be 0 to indicate we're using the jobserver.  */
    2445 
    2446       master_job_slots = job_slots;
    2447 
    2448       while (--job_slots)
    2449         {
    2450           int r;
    2451 
    2452           EINTRLOOP (r, write (job_fds[1], &c, 1));
    2453           if (r != 1)
    2454             pfatal_with_name (_("init jobserver pipe"));
    2455         }
    2456 
    2457       /* Fill in the jobserver_fds struct for our children.  */
    2458 
    2459       cp = xmalloc ((sizeof ("1024")*2)+1);
    2460       sprintf (cp, "%d,%d", job_fds[0], job_fds[1]);
    2461 
    2462       jobserver_fds = (struct stringlist *)
    2463                         xmalloc (sizeof (struct stringlist));
    2464       jobserver_fds->list = xmalloc (sizeof (char *));
    2465       jobserver_fds->list[0] = cp;
    2466       jobserver_fds->idx = 1;
    2467       jobserver_fds->max = 1;
    2468     }
    2469 #endif
     2722    }
     2723
     2724  /* If we're not using parallel jobs, then we don't need output sync.
     2725     This is so people can enable output sync in GNUMAKEFLAGS or similar, but
     2726     not have it take effect unless parallel builds are enabled.  */
     2727  if (syncing && job_slots == 1)
     2728    {
     2729      OUTPUT_UNSET ();
     2730      output_close (&make_sync);
     2731      syncing = 0;
     2732      output_sync = OUTPUT_SYNC_NONE;
     2733    }
    24702734
    24712735#ifndef MAKE_SYMLINKS
    24722736  if (check_symlink_flag)
    24732737    {
    2474       error (NILF, _("Symbolic links not supported: disabling -L."));
     2738      O (error, NILF, _("Symbolic links not supported: disabling -L."));
    24752739      check_symlink_flag = 0;
    24762740    }
     
    24812745  define_makeflags (1, 0);
    24822746
    2483   /* Make each `struct dep' point at the `struct file' for the file
     2747  /* Make each 'struct goaldep' point at the 'struct file' for the file
    24842748     depended on.  Also do magic for special targets.  */
    24852749
     
    25202784          f->last_mtime = f->mtime_before_update = OLD_MTIME;
    25212785          f->updated = 1;
    2522           f->update_status = 0;
     2786          f->update_status = us_success;
    25232787          f->command_state = cs_finished;
    25242788        }
     
    25292793      const char **p;
    25302794      for (p = new_files->list; *p != 0; ++p)
    2531         {
    2532           struct file *f = enter_file (*p);
    2533           f->last_mtime = f->mtime_before_update = NEW_MTIME;
    2534         }
     2795        {
     2796          struct file *f = enter_file (*p);
     2797          f->last_mtime = f->mtime_before_update = NEW_MTIME;
     2798        }
    25352799    }
    25362800
     
    25382802  remote_setup ();
    25392803
    2540   if (read_makefiles != 0)
     2804  /* Dump any output we've collected.  */
     2805
     2806  OUTPUT_UNSET ();
     2807  output_close (&make_sync);
     2808
     2809  if (read_files != 0)
    25412810    {
    25422811      /* Update any makefiles if necessary.  */
     
    25442813      FILE_TIMESTAMP *makefile_mtimes = 0;
    25452814      unsigned int mm_idx = 0;
    2546       char **nargv;
     2815      char **aargv = NULL;
     2816      const char **nargv;
    25472817      int nargc;
    2548       int orig_db_level = db_level;
    2549       int status;
    2550 
    2551       if (! ISDB (DB_MAKEFILES))
    2552         db_level = DB_NONE;
     2818      enum update_status status;
    25532819
    25542820      DB (DB_BASIC, (_("Updating makefiles....\n")));
    25552821
    25562822      /* Remove any makefiles we don't want to try to update.
    2557         Also record the current modtimes so we can compare them later.  */
     2823        Also record the current modtimes so we can compare them later.  */
    25582824      {
    2559         register struct dep *d, *last;
    2560         last = 0;
    2561         d = read_makefiles;
    2562         while (d != 0)
    2563           {
    2564             struct file *f = d->file;
    2565             if (f->double_colon)
    2566               for (f = f->double_colon; f != NULL; f = f->prev)
    2567                 {
    2568                   if (f->deps == 0 && f->cmds != 0)
    2569                     {
    2570                       /* This makefile is a :: target with commands, but
    2571                         no dependencies.  So, it will always be remade.
    2572                         This might well cause an infinite loop, so don't
    2573                         try to remake it.  (This will only happen if
    2574                         your makefiles are written exceptionally
    2575                         stupidly; but if you work for Athena, that's how
    2576                         you write your makefiles.)  */
    2577 
    2578                       DB (DB_VERBOSE,
    2579                           (_("Makefile `%s' might loop; not remaking it.\n"),
     2825        register struct goaldep *d, *last;
     2826        last = 0;
     2827        d = read_files;
     2828        while (d != 0)
     2829          {
     2830            struct file *f = d->file;
     2831            if (f->double_colon)
     2832              for (f = f->double_colon; f != NULL; f = f->prev)
     2833                {
     2834                  if (f->deps == 0 && f->cmds != 0)
     2835                    {
     2836                      /* This makefile is a :: target with commands, but
     2837                        no dependencies.  So, it will always be remade.
     2838                        This might well cause an infinite loop, so don't
     2839                        try to remake it.  (This will only happen if
     2840                        your makefiles are written exceptionally
     2841                        stupidly; but if you work for Athena, that's how
     2842                        you write your makefiles.)  */
     2843
     2844                      DB (DB_VERBOSE,
     2845                          (_("Makefile '%s' might loop; not remaking it.\n"),
    25802846                           f->name));
    25812847
    2582                       if (last == 0)
    2583                         read_makefiles = d->next;
    2584                       else
    2585                         last->next = d->next;
    2586 
    2587                       /* Free the storage.  */
    2588                       free_dep (d);
    2589 
    2590                       d = last == 0 ? read_makefiles : last->next;
    2591 
    2592                       break;
    2593                     }
    2594                 }
    2595             if (f == NULL || !f->double_colon)
    2596               {
     2848                      if (last == 0)
     2849                        read_files = d->next;
     2850                      else
     2851                        last->next = d->next;
     2852
     2853                      /* Free the storage.  */
     2854                      free_goaldep (d);
     2855
     2856                      d = last == 0 ? read_files : last->next;
     2857
     2858                      break;
     2859                    }
     2860                }
     2861
     2862            if (f == NULL || !f->double_colon)
     2863              {
    25972864                makefile_mtimes = xrealloc (makefile_mtimes,
    25982865                                            (mm_idx+1)
    25992866                                            * sizeof (FILE_TIMESTAMP));
    2600                 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
    2601                 last = d;
    2602                 d = d->next;
    2603               }
    2604           }
     2867                makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
     2868                last = d;
     2869                d = d->next;
     2870              }
     2871          }
    26052872      }
    26062873
    2607       /* Set up `MAKEFLAGS' specially while remaking makefiles.  */
     2874      /* Set up 'MAKEFLAGS' specially while remaking makefiles.  */
    26082875      define_makeflags (1, 1);
    26092876
    2610       rebuilding_makefiles = 1;
    2611       status = update_goal_chain (read_makefiles);
    2612       rebuilding_makefiles = 0;
     2877      {
     2878        int orig_db_level = db_level;
     2879
     2880        if (! ISDB (DB_MAKEFILES))
     2881          db_level = DB_NONE;
     2882
     2883        rebuilding_makefiles = 1;
     2884        status = update_goal_chain (read_files);
     2885        rebuilding_makefiles = 0;
     2886
     2887        db_level = orig_db_level;
     2888      }
    26132889
    26142890      switch (status)
    2615         {
    2616         case 1:
     2891        {
     2892        case us_question:
    26172893          /* The only way this can happen is if the user specified -q and asked
    2618            * for one of the makefiles to be remade as a target on the command
    2619            * line.  Since we're not actually updating anything with -q we can
    2620            * treat this as "did nothing".
    2621            */
    2622 
    2623         case -1:
    2624           /* Did nothing.  */
    2625           break;
    2626 
    2627         case 2:
    2628           /* Failed to update.  Figure out if we care.  */
    2629           {
    2630             /* Nonzero if any makefile was successfully remade.  */
    2631             int any_remade = 0;
    2632             /* Nonzero if any makefile we care about failed
    2633                in updating or could not be found at all.  */
    2634             int any_failed = 0;
    2635             unsigned int i;
    2636             struct dep *d;
    2637 
    2638             for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
     2894             for one of the makefiles to be remade as a target on the command
     2895             line.  Since we're not actually updating anything with -q we can
     2896             treat this as "did nothing".  */
     2897
     2898        case us_none:
     2899          /* Did nothing.  */
     2900          break;
     2901
     2902        case us_failed:
     2903          /* Failed to update.  Figure out if we care.  */
     2904          {
     2905            /* Nonzero if any makefile was successfully remade.  */
     2906            int any_remade = 0;
     2907            /* Nonzero if any makefile we care about failed
     2908               in updating or could not be found at all.  */
     2909            int any_failed = 0;
     2910            unsigned int i;
     2911            struct goaldep *d;
     2912
     2913            for (i = 0, d = read_files; d != 0; ++i, d = d->next)
    26392914              {
    2640                 /* Reset the considered flag; we may need to look at the file
    2641                    again to print an error.  */
    2642                 d->file->considered = 0;
    2643 
    26442915                if (d->file->updated)
    26452916                  {
    26462917                    /* This makefile was updated.  */
    2647                     if (d->file->update_status == 0)
     2918                    if (d->file->update_status == us_success)
    26482919                      {
    26492920                        /* It was successfully updated.  */
     
    26512922                                       != makefile_mtimes[i]);
    26522923                      }
    2653                     else if (! (d->changed & RM_DONTCARE))
     2924                    else if (! (d->flags & RM_DONTCARE))
    26542925                      {
    26552926                        FILE_TIMESTAMP mtime;
    26562927                        /* The update failed and this makefile was not
    26572928                           from the MAKEFILES variable, so we care.  */
    2658                         error (NILF, _("Failed to remake makefile `%s'."),
    2659                                d->file->name);
     2929                        OS (error, NILF, _("Failed to remake makefile '%s'."),
     2930                            d->file->name);
    26602931                        mtime = file_mtime_no_search (d->file);
    26612932                        any_remade |= (mtime != NONEXISTENT_MTIME
     
    26662937                else
    26672938                  /* This makefile was not found at all.  */
    2668                   if (! (d->changed & RM_DONTCARE))
     2939                  if (! (d->flags & RM_DONTCARE))
    26692940                    {
     2941                      const char *dnm = dep_name (d);
     2942                      size_t l = strlen (dnm);
     2943
    26702944                      /* This is a makefile we care about.  See how much.  */
    2671                       if (d->changed & RM_INCLUDED)
    2672                         /* An included makefile.  We don't need
    2673                            to die, but we do want to complain.  */
    2674                         error (NILF,
    2675                                _("Included makefile `%s' was not found."),
    2676                                dep_name (d));
     2945                      if (d->flags & RM_INCLUDED)
     2946                        /* An included makefile.  We don't need to die, but we
     2947                           do want to complain.  */
     2948                        error (NILF, l,
     2949                               _("Included makefile '%s' was not found."), dnm);
    26772950                      else
    26782951                        {
    26792952                          /* A normal makefile.  We must die later.  */
    2680                           error (NILF, _("Makefile `%s' was not found"),
    2681                                  dep_name (d));
     2953                          error (NILF, l,
     2954                                 _("Makefile '%s' was not found"), dnm);
    26822955                          any_failed = 1;
    26832956                        }
     
    26852958              }
    26862959            /* Reset this to empty so we get the right error message below.  */
    2687             read_makefiles = 0;
    2688 
    2689             if (any_remade)
    2690               goto re_exec;
    2691             if (any_failed)
    2692               die (2);
     2960            read_files = 0;
     2961
     2962            if (any_remade)
     2963              goto re_exec;
     2964            if (any_failed)
     2965              die (MAKE_FAILURE);
    26932966            break;
    2694           }
    2695 
    2696         case 0:
    2697         re_exec:
    2698           /* Updated successfully.  Re-exec ourselves.  */
    2699 
    2700           remove_intermediates (0);
    2701 
    2702           if (print_data_base_flag)
    2703             print_data_base ();
    2704 
    2705           log_working_directory (0);
     2967          }
     2968
     2969        case us_success:
     2970        re_exec:
     2971          /* Updated successfully.  Re-exec ourselves.  */
     2972
     2973          remove_intermediates (0);
     2974
     2975          if (print_data_base_flag)
     2976            print_data_base ();
    27062977
    27072978          clean_jobserver (0);
    27082979
    2709           if (makefiles != 0)
    2710             {
    2711               /* These names might have changed.  */
    2712               int i, j = 0;
    2713               for (i = 1; i < argc; ++i)
    2714                 if (strneq (argv[i], "-f", 2)) /* XXX */
    2715                   {
    2716                     if (argv[i][2] == '\0')
     2980          if (makefiles != 0)
     2981            {
     2982              /* These names might have changed.  */
     2983              int i, j = 0;
     2984              for (i = 1; i < argc; ++i)
     2985                if (strneq (argv[i], "-f", 2)) /* XXX */
     2986                  {
     2987                    if (argv[i][2] == '\0')
    27172988                      /* This cast is OK since we never modify argv.  */
    2718                       argv[++i] = (char *) makefiles->list[j];
    2719                     else
    2720                       argv[i] = xstrdup (concat (2, "-f", makefiles->list[j]));
    2721                     ++j;
    2722                   }
    2723             }
     2989                      argv[++i] = (char *) makefiles->list[j];
     2990                    else
     2991                      argv[i] = xstrdup (concat (2, "-f", makefiles->list[j]));
     2992                    ++j;
     2993                  }
     2994            }
    27242995
    27252996          /* Add -o option for the stdin temporary file, if necessary.  */
     
    27272998          if (stdin_nm)
    27282999            {
    2729               nargv = xmalloc ((nargc + 2) * sizeof (char *));
    2730               memcpy (nargv, argv, argc * sizeof (char *));
    2731               nargv[nargc++] = xstrdup (concat (2, "-o", stdin_nm));
    2732               nargv[nargc] = 0;
     3000              void *m = xmalloc ((nargc + 2) * sizeof (char *));
     3001              aargv = m;
     3002              memcpy (aargv, argv, argc * sizeof (char *));
     3003              aargv[nargc++] = xstrdup (concat (2, "-o", stdin_nm));
     3004              aargv[nargc] = 0;
     3005              nargv = m;
    27333006            }
    27343007          else
    2735             nargv = argv;
    2736 
    2737           if (directories != 0 && directories->idx > 0)
    2738             {
    2739               int bad = 1;
    2740               if (directory_before_chdir != 0)
    2741                 {
    2742                   if (chdir (directory_before_chdir) < 0)
    2743                       perror_with_name ("chdir", "");
    2744                   else
    2745                     bad = 0;
    2746                 }
    2747               if (bad)
    2748                 fatal (NILF, _("Couldn't change back to original directory."));
    2749             }
     3008            nargv = (const char**)argv;
     3009
     3010          if (directories != 0 && directories->idx > 0)
     3011            {
     3012              int bad = 1;
     3013              if (directory_before_chdir != 0)
     3014                {
     3015                  if (chdir (directory_before_chdir) < 0)
     3016                      perror_with_name ("chdir", "");
     3017                  else
     3018                    bad = 0;
     3019                }
     3020              if (bad)
     3021                O (fatal, NILF,
     3022                   _("Couldn't change back to original directory."));
     3023            }
    27503024
    27513025          ++restarts;
    27523026
    2753           /* Reset makeflags in case they were changed.  */
    2754           {
    2755             const char *pv = define_makeflags (1, 1);
    2756             char *p = alloca (sizeof ("MAKEFLAGS=") + strlen (pv) + 1);
    2757             sprintf (p, "MAKEFLAGS=%s", pv);
    2758             putenv (p);
    2759           }
    2760 
    2761           if (ISDB (DB_BASIC))
    2762             {
    2763               char **p;
    2764               printf (_("Re-executing[%u]:"), restarts);
    2765               for (p = nargv; *p != 0; ++p)
    2766                 printf (" %s", *p);
    2767               putchar ('\n');
    2768             }
     3027          if (ISDB (DB_BASIC))
     3028            {
     3029              const char **p;
     3030              printf (_("Re-executing[%u]:"), restarts);
     3031              for (p = nargv; *p != 0; ++p)
     3032                printf (" %s", *p);
     3033              putchar ('\n');
     3034              fflush (stdout);
     3035            }
    27693036
    27703037#ifndef _AMIGA
     
    27733040            for (p = environ; *p != 0; ++p)
    27743041              {
    2775                 if (strneq (*p, MAKELEVEL_NAME, MAKELEVEL_LENGTH)
    2776                     && (*p)[MAKELEVEL_LENGTH] == '=')
     3042                if (strneq (*p, MAKELEVEL_NAME "=", MAKELEVEL_LENGTH+1))
    27773043                  {
    27783044                    *p = alloca (40);
    27793045                    sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
     3046#ifdef VMS
     3047                    vms_putenv_symbol (*p);
     3048#endif
    27803049                  }
    2781                 if (strneq (*p, "MAKE_RESTARTS=", 14))
     3050                else if (strneq (*p, "MAKE_RESTARTS=", CSTRLEN ("MAKE_RESTARTS=")))
    27823051                  {
    27833052                    *p = alloca (40);
    2784                     sprintf (*p, "MAKE_RESTARTS=%u", restarts);
     3053                    sprintf (*p, "MAKE_RESTARTS=%s%u",
     3054                             OUTPUT_IS_TRACED () ? "-" : "", restarts);
    27853055                    restarts = 0;
    27863056                  }
     
    27883058          }
    27893059#else /* AMIGA */
    2790           {
    2791             char buffer[256];
     3060          {
     3061            char buffer[256];
    27923062
    27933063            sprintf (buffer, "%u", makelevel);
    27943064            SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
    27953065
    2796             sprintf (buffer, "%u", restarts);
     3066            sprintf (buffer, "%s%u", OUTPUT_IS_TRACED () ? "-" : "", restarts);
    27973067            SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
    27983068            restarts = 0;
    2799           }
     3069          }
    28003070#endif
    28013071
     
    28043074            {
    28053075              char *b = alloca (40);
    2806               sprintf (b, "MAKE_RESTARTS=%u", restarts);
     3076              sprintf (b, "MAKE_RESTARTS=%s%u",
     3077                       OUTPUT_IS_TRACED () ? "-" : "", restarts);
    28073078              putenv (b);
    28083079            }
    28093080
    2810           fflush (stdout);
    2811           fflush (stderr);
    2812 
    2813           /* Close the dup'd jobserver pipe if we opened one.  */
    2814           if (job_rfd >= 0)
    2815             close (job_rfd);
     3081          fflush (stdout);
     3082          fflush (stderr);
    28163083
    28173084#ifdef _AMIGA
    2818           exec_command (nargv);
    2819           exit (0);
     3085          exec_command (nargv);
     3086          exit (0);
    28203087#elif defined (__EMX__)
    2821           {
    2822             /* It is not possible to use execve() here because this
    2823                would cause the parent process to be terminated with
    2824                exit code 0 before the child process has been terminated.
    2825                Therefore it may be the best solution simply to spawn the
    2826                child process including all file handles and to wait for its
    2827                termination. */
    2828             int pid;
    2829             int status;
    2830             pid = child_execute_job (0, 1, nargv, environ);
    2831 
    2832             /* is this loop really necessary? */
    2833             do {
    2834               pid = wait (&status);
    2835             } while (pid <= 0);
    2836             /* use the exit code of the child process */
    2837             exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
    2838           }
     3088          {
     3089            /* It is not possible to use execve() here because this
     3090               would cause the parent process to be terminated with
     3091               exit code 0 before the child process has been terminated.
     3092               Therefore it may be the best solution simply to spawn the
     3093               child process including all file handles and to wait for its
     3094               termination. */
     3095            int pid;
     3096            int r;
     3097            pid = child_execute_job (NULL, 1, nargv, environ);
     3098
     3099            /* is this loop really necessary? */
     3100            do {
     3101              pid = wait (&r);
     3102            } while (pid <= 0);
     3103            /* use the exit code of the child process */
     3104            exit (WIFEXITED(r) ? WEXITSTATUS(r) : EXIT_FAILURE);
     3105          }
    28393106#else
    2840           exec_command (nargv, environ);
    2841 #endif
    2842           /* NOTREACHED */
    2843 
    2844         default:
    2845 #define BOGUS_UPDATE_STATUS 0
    2846           assert (BOGUS_UPDATE_STATUS);
    2847           break;
    2848         }
    2849 
    2850       db_level = orig_db_level;
    2851 
    2852       /* Free the makefile mtimes (if we allocated any).  */
    2853       if (makefile_mtimes)
    2854         free (makefile_mtimes);
    2855     }
    2856 
    2857   /* Set up `MAKEFLAGS' again for the normal targets.  */
     3107#ifdef SET_STACK_SIZE
     3108          /* Reset limits, if necessary.  */
     3109          if (stack_limit.rlim_cur)
     3110            setrlimit (RLIMIT_STACK, &stack_limit);
     3111#endif
     3112          exec_command ((char **)nargv, environ);
     3113#endif
     3114          free (aargv);
     3115          break;
     3116        }
     3117
     3118      /* Free the makefile mtimes.  */
     3119      free (makefile_mtimes);
     3120    }
     3121
     3122  /* Set up 'MAKEFLAGS' again for the normal targets.  */
    28583123  define_makeflags (1, 0);
    28593124
     
    28663131      const char **p;
    28673132      for (p = new_files->list; *p != 0; ++p)
    2868         {
    2869           struct file *f = enter_file (*p);
    2870           f->last_mtime = f->mtime_before_update = NEW_MTIME;
    2871         }
     3133        {
     3134          struct file *f = enter_file (*p);
     3135          f->last_mtime = f->mtime_before_update = NEW_MTIME;
     3136        }
    28723137    }
    28733138
     
    29013166            {
    29023167              struct nameseq *ns;
    2903               ns = PARSE_FILE_SEQ (&p, struct nameseq, '\0', NULL, 0);
     3168
     3169              ns = PARSE_SIMPLE_SEQ (&p, struct nameseq);
    29043170              if (ns)
    29053171                {
    29063172                  /* .DEFAULT_GOAL should contain one target. */
    29073173                  if (ns->next != 0)
    2908                     fatal (NILF, _(".DEFAULT_GOAL contains more than one target"));
     3174                    O (fatal, NILF,
     3175                       _(".DEFAULT_GOAL contains more than one target"));
    29093176
    29103177#ifndef CONFIG_WITH_VALUE_LENGTH
     
    29213188          if (f)
    29223189            {
    2923               goals = alloc_dep ();
     3190              goals = alloc_goaldep ();
    29243191              goals->file = f;
    29253192            }
     
    29323199  if (!goals)
    29333200    {
    2934       if (read_makefiles == 0)
    2935         fatal (NILF, _("No targets specified and no makefile found"));
    2936 
    2937       fatal (NILF, _("No targets"));
     3201      if (read_files == 0)
     3202        O (fatal, NILF, _("No targets specified and no makefile found"));
     3203
     3204      O (fatal, NILF, _("No targets"));
    29383205    }
    29393206
     
    29433210
    29443211  {
    2945     int status;
    2946 
    29473212    switch (update_goal_chain (goals))
    29483213    {
    2949       case -1:
     3214      case us_none:
    29503215        /* Nothing happened.  */
    2951       case 0:
    2952         /* Updated successfully.  */
    2953         status = makefile_status;
     3216        /* FALLTHROUGH */
     3217      case us_success:
     3218        /* Keep the previous result.  */
    29543219        break;
    2955       case 1:
     3220      case us_question:
    29563221        /* We are under -q and would run some commands.  */
    2957         status = MAKE_TROUBLE;
     3222        makefile_status = MAKE_TROUBLE;
    29583223        break;
    2959       case 2:
    2960         /* Updating failed.  POSIX.2 specifies exit status >1 for this;
    2961            but in VMS, there is only success and failure.  */
    2962         status = MAKE_FAILURE;
     3224      case us_failed:
     3225        /* Updating failed.  POSIX.2 specifies exit status >1 for this; */
     3226        makefile_status = MAKE_FAILURE;
    29633227        break;
    2964       default:
    2965         abort ();
    29663228    }
    29673229
    29683230    /* If we detected some clock skew, generate one last warning */
    29693231    if (clock_skew_detected)
    2970       error (NILF,
    2971              _("warning:  Clock skew detected.  Your build may be incomplete."));
     3232      O (error, NILF,
     3233         _("warning:  Clock skew detected.  Your build may be incomplete."));
    29723234
    29733235    MAKE_STATS_2(if (uStartTick) printf("main ticks elapsed: %ull\n", (unsigned long long)(CURRENT_CLOCK_TICK() - uStartTick)) );
    29743236    /* Exit.  */
    2975     die (status);
     3237    die (makefile_status);
    29763238  }
    29773239
    29783240  /* NOTREACHED */
    2979   return 0;
     3241  exit (MAKE_SUCCESS);
    29803242}
    29813243
     
    29853247static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
    29863248static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
    2987                                   (sizeof (long_option_aliases) /
    2988                                    sizeof (long_option_aliases[0]))];
     3249                                  (sizeof (long_option_aliases) /
     3250                                   sizeof (long_option_aliases[0]))];
    29893251
    29903252/* Fill in the string and vector for getopt.  */
     
    30093271    {
    30103272      long_options[i].name = (switches[i].long_name == 0 ? "" :
    3011                               switches[i].long_name);
     3273                              switches[i].long_name);
    30123274      long_options[i].flag = 0;
    30133275      long_options[i].val = switches[i].c;
    30143276      if (short_option (switches[i].c))
    3015         *p++ = switches[i].c;
     3277        *p++ = switches[i].c;
    30163278      switch (switches[i].type)
    3017         {
    3018         case flag:
    3019         case flag_off:
    3020         case ignore:
    3021           long_options[i].has_arg = no_argument;
    3022           break;
    3023 
    3024         case string:
     3279        {
     3280        case flag:
     3281        case flag_off:
     3282        case ignore:
     3283          long_options[i].has_arg = no_argument;
     3284          break;
     3285
     3286        case string:
     3287        case strlist:
    30253288        case filename:
    3026         case positive_int:
    3027         case floating:
    3028           if (short_option (switches[i].c))
    3029             *p++ = ':';
    3030           if (switches[i].noarg_value != 0)
    3031             {
    3032               if (short_option (switches[i].c))
    3033                 *p++ = ':';
    3034               long_options[i].has_arg = optional_argument;
    3035             }
    3036           else
    3037             long_options[i].has_arg = required_argument;
    3038           break;
    3039         }
     3289        case positive_int:
     3290        case floating:
     3291          if (short_option (switches[i].c))
     3292            *p++ = ':';
     3293          if (switches[i].noarg_value != 0)
     3294            {
     3295              if (short_option (switches[i].c))
     3296                *p++ = ':';
     3297              long_options[i].has_arg = optional_argument;
     3298            }
     3299          else
     3300            long_options[i].has_arg = required_argument;
     3301          break;
     3302        }
    30403303    }
    30413304  *p = '\0';
    30423305  for (c = 0; c < (sizeof (long_option_aliases) /
    3043                    sizeof (long_option_aliases[0]));
     3306                   sizeof (long_option_aliases[0]));
    30443307       ++c)
    30453308    long_options[i++] = long_option_aliases[c];
     
    30473310}
    30483311
     3312
     3313/* Non-option argument.  It might be a variable definition.  */
    30493314static void
    3050 handle_non_switch_argument (char *arg, int env)
     3315handle_non_switch_argument (const char *arg, int env)
    30513316{
    3052   /* Non-option argument.  It might be a variable definition.  */
    30533317  struct variable *v;
     3318
    30543319  if (arg[0] == '-' && arg[1] == '\0')
    3055     /* Ignore plain `-' for compatibility.  */
     3320    /* Ignore plain '-' for compatibility.  */
    30563321    return;
     3322
     3323#ifdef VMS
     3324  {
     3325    /* VMS DCL quoting can result in foo="bar baz" showing up here.
     3326       Need to remove the double quotes from the value. */
     3327    char * eq_ptr;
     3328    char * new_arg;
     3329    eq_ptr = strchr (arg, '=');
     3330    if ((eq_ptr != NULL) && (eq_ptr[1] == '"'))
     3331      {
     3332         int len;
     3333         int seg1;
     3334         int seg2;
     3335         len = strlen(arg);
     3336         new_arg = alloca(len);
     3337         seg1 = eq_ptr - arg + 1;
     3338         strncpy(new_arg, arg, (seg1));
     3339         seg2 = len - seg1 - 1;
     3340         strncpy(&new_arg[seg1], &eq_ptr[2], seg2);
     3341         new_arg[seg1 + seg2] = 0;
     3342         if (new_arg[seg1 + seg2 - 1] == '"')
     3343           new_arg[seg1 + seg2 - 1] = 0;
     3344         arg = new_arg;
     3345      }
     3346  }
     3347#endif
    30573348  v = try_variable_definition (0, arg IF_WITH_VALUE_LENGTH_PARAM(NULL), o_command, 0);
    30583349  if (v != 0)
    30593350    {
    30603351      /* It is indeed a variable definition.  If we don't already have this
    3061         one, record a pointer to the variable for later use in
    3062         define_makeflags.  */
     3352        one, record a pointer to the variable for later use in
     3353        define_makeflags.  */
    30633354      struct command_variable *cv;
    30643355
     
    30673358          break;
    30683359
    3069       if (! cv) {
    3070         cv = xmalloc (sizeof (*cv));
    3071         cv->variable = v;
    3072         cv->next = command_variables;
    3073         command_variables = cv;
    3074       }
     3360      if (! cv)
     3361        {
     3362          cv = xmalloc (sizeof (*cv));
     3363          cv->variable = v;
     3364          cv->next = command_variables;
     3365          command_variables = cv;
     3366        }
    30753367    }
    30763368  else if (! env)
    30773369    {
    30783370      /* Not an option or variable definition; it must be a goal
    3079         target!  Enter it as a file and add it to the dep chain of
    3080         goals.  */
     3371        target!  Enter it as a file and add it to the dep chain of
     3372        goals.  */
    30813373      struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
    30823374      f->cmd_target = 1;
    30833375
    30843376      if (goals == 0)
    3085         {
    3086           goals = alloc_dep ();
    3087           lastgoal = goals;
    3088         }
     3377        {
     3378          goals = alloc_goaldep ();
     3379          lastgoal = goals;
     3380        }
    30893381      else
    3090         {
    3091           lastgoal->next = alloc_dep ();
    3092           lastgoal = lastgoal->next;
    3093         }
     3382        {
     3383          lastgoal->next = alloc_goaldep ();
     3384          lastgoal = lastgoal->next;
     3385        }
    30943386
    30953387      lastgoal->file = f;
     
    31623454
    31633455static void
    3164 decode_switches (int argc, char **argv, int env)
     3456decode_switches (int argc, const char **argv, int env)
    31653457{
    31663458  int bad = 0;
     
    31823474  while (optind < argc)
    31833475    {
     3476      const char *coptarg;
     3477
    31843478      /* Parse the next argument.  */
    3185       c = getopt_long (argc, argv, options, long_options, (int *) 0);
     3479      c = getopt_long (argc, (char*const*)argv, options, long_options, NULL);
     3480      coptarg = optarg;
    31863481      if (c == EOF)
    3187         /* End of arguments, or "--" marker seen.  */
    3188         break;
     3482        /* End of arguments, or "--" marker seen.  */
     3483        break;
    31893484      else if (c == 1)
    3190         /* An argument not starting with a dash.  */
    3191         handle_non_switch_argument (optarg, env);
     3485        /* An argument not starting with a dash.  */
     3486        handle_non_switch_argument (coptarg, env);
    31923487      else if (c == '?')
    3193         /* Bad option.  We will print a usage message and die later.
    3194            But continue to parse the other options so the user can
    3195            see all he did wrong.  */
    3196         bad = 1;
     3488        /* Bad option.  We will print a usage message and die later.
     3489           But continue to parse the other options so the user can
     3490           see all he did wrong.  */
     3491        bad = 1;
    31973492      else
    3198         for (cs = switches; cs->c != '\0'; ++cs)
    3199           if (cs->c == c)
    3200             {
    3201               /* Whether or not we will actually do anything with
    3202                  this switch.  We test this individually inside the
    3203                  switch below rather than just once outside it, so that
    3204                  options which are to be ignored still consume args.  */
    3205               int doit = !env || cs->env;
    3206 
    3207               switch (cs->type)
    3208                 {
    3209                 default:
    3210                   abort ();
    3211 
    3212                 case ignore:
    3213                   break;
    3214 
    3215                 case flag:
    3216                 case flag_off:
    3217                   if (doit)
    3218                     *(int *) cs->value_ptr = cs->type == flag;
    3219                   break;
    3220 
    3221                 case string:
    3222                 case filename:
    3223                   if (!doit)
    3224                     break;
    3225 
    3226                   if (optarg == 0)
    3227                     optarg = xstrdup (cs->noarg_value);
    3228                   else if (*optarg == '\0')
     3493        for (cs = switches; cs->c != '\0'; ++cs)
     3494          if (cs->c == c)
     3495            {
     3496              /* Whether or not we will actually do anything with
     3497                 this switch.  We test this individually inside the
     3498                 switch below rather than just once outside it, so that
     3499                 options which are to be ignored still consume args.  */
     3500              int doit = !env || cs->env;
     3501
     3502              switch (cs->type)
     3503                {
     3504                default:
     3505                  abort ();
     3506
     3507                case ignore:
     3508                  break;
     3509
     3510                case flag:
     3511                case flag_off:
     3512                  if (doit)
     3513                    *(int *) cs->value_ptr = cs->type == flag;
     3514                  break;
     3515
     3516                case string:
     3517                case strlist:
     3518                case filename:
     3519                  if (!doit)
     3520                    break;
     3521
     3522                  if (! coptarg)
     3523                    coptarg = xstrdup (cs->noarg_value);
     3524                  else if (*coptarg == '\0')
    32293525                    {
    32303526                      char opt[2] = "c";
     
    32363532                        op = cs->long_name;
    32373533
    3238                       error (NILF, _("the `%s%s' option requires a non-empty string argument"),
     3534                      error (NILF, strlen (op),
     3535                             _("the '%s%s' option requires a non-empty string argument"),
    32393536                             short_option (cs->c) ? "-" : "--", op);
    32403537                      bad = 1;
     3538                      break;
    32413539                    }
    32423540
    3243                   sl = *(struct stringlist **) cs->value_ptr;
    3244                   if (sl == 0)
    3245                     {
    3246                       sl = (struct stringlist *)
    3247                         xmalloc (sizeof (struct stringlist));
    3248                       sl->max = 5;
    3249                       sl->idx = 0;
    3250                       sl->list = xmalloc (5 * sizeof (char *));
    3251                       *(struct stringlist **) cs->value_ptr = sl;
    3252                     }
    3253                   else if (sl->idx == sl->max - 1)
    3254                     {
    3255                       sl->max += 5;
     3541                  if (cs->type == string)
     3542                    {
     3543                      char **val = (char **)cs->value_ptr;
     3544                      free (*val);
     3545                      *val = xstrdup (coptarg);
     3546                      break;
     3547                    }
     3548
     3549                  sl = *(struct stringlist **) cs->value_ptr;
     3550                  if (sl == 0)
     3551                    {
     3552                      sl = xmalloc (sizeof (struct stringlist));
     3553                      sl->max = 5;
     3554                      sl->idx = 0;
     3555                      sl->list = xmalloc (5 * sizeof (char *));
     3556                      *(struct stringlist **) cs->value_ptr = sl;
     3557                    }
     3558                  else if (sl->idx == sl->max - 1)
     3559                    {
     3560                      sl->max += 5;
    32563561                      /* MSVC erroneously warns without a cast here.  */
    3257                       sl->list = xrealloc ((void *)sl->list,
     3562                      sl->list = xrealloc ((void *)sl->list,
    32583563                                           sl->max * sizeof (char *));
    3259                     }
     3564                    }
    32603565                  if (cs->type == filename)
    3261                     sl->list[sl->idx++] = expand_command_line_file (optarg);
     3566                    sl->list[sl->idx++] = expand_command_line_file (coptarg);
    32623567                  else
    3263                     sl->list[sl->idx++] = optarg;
    3264                   sl->list[sl->idx] = 0;
    3265                   break;
    3266 
    3267                 case positive_int:
     3568                    sl->list[sl->idx++] = xstrdup (coptarg);
     3569                  sl->list[sl->idx] = 0;
     3570                  break;
     3571
     3572                case positive_int:
    32683573                  /* See if we have an option argument; if we do require that
    32693574                     it's all digits, not something like "10foo".  */
    3270                   if (optarg == 0 && argc > optind)
     3575                  if (coptarg == 0 && argc > optind)
    32713576                    {
    32723577                      const char *cp;
     
    32743579                        ;
    32753580                      if (cp[0] == '\0')
    3276                         optarg = argv[optind++];
     3581                        coptarg = argv[optind++];
    32773582                    }
    32783583
    3279                   if (!doit)
    3280                     break;
    3281 
    3282                   if (optarg != 0)
    3283                     {
    3284                       int i = atoi (optarg);
     3584                  if (!doit)
     3585                    break;
     3586
     3587                  if (coptarg)
     3588                    {
     3589                      int i = atoi (coptarg);
    32853590                      const char *cp;
    32863591
    32873592                      /* Yes, I realize we're repeating this in some cases.  */
    3288                       for (cp = optarg; ISDIGIT (cp[0]); ++cp)
     3593                      for (cp = coptarg; ISDIGIT (cp[0]); ++cp)
    32893594                        ;
    32903595
    3291                       if (i < 1 || cp[0] != '\0')
    3292                         {
    3293                           error (NILF, _("the `-%c' option requires a positive integral argument"),
     3596                      if (i < 1 || cp[0] != '\0')
     3597                        {
     3598                          error (NILF, 0,
     3599                                 _("the '-%c' option requires a positive integer argument"),
    32943600                                 cs->c);
    3295                           bad = 1;
    3296                         }
    3297                       else
    3298                         *(unsigned int *) cs->value_ptr = i;
    3299                     }
    3300                   else
    3301                     *(unsigned int *) cs->value_ptr
    3302                       = *(unsigned int *) cs->noarg_value;
    3303                   break;
     3601                          bad = 1;
     3602                        }
     3603                      else
     3604                        *(unsigned int *) cs->value_ptr = i;
     3605                    }
     3606                  else
     3607                    *(unsigned int *) cs->value_ptr
     3608                      = *(unsigned int *) cs->noarg_value;
     3609                  break;
    33043610
    33053611#ifndef NO_FLOAT
    3306                 case floating:
    3307                   if (optarg == 0 && optind < argc
    3308                       && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
    3309                     optarg = argv[optind++];
    3310 
    3311                   if (doit)
    3312                     *(double *) cs->value_ptr
    3313                       = (optarg != 0 ? atof (optarg)
    3314                         : *(double *) cs->noarg_value);
    3315 
    3316                   break;
    3317 #endif
    3318                 }
    3319 
    3320               /* We've found the switch.  Stop looking.  */
    3321               break;
    3322             }
     3612                case floating:
     3613                  if (coptarg == 0 && optind < argc
     3614                      && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
     3615                    coptarg = argv[optind++];
     3616
     3617                  if (doit)
     3618                    *(double *) cs->value_ptr
     3619                      = (coptarg != 0 ? atof (coptarg)
     3620                        : *(double *) cs->noarg_value);
     3621
     3622                  break;
     3623#endif
     3624                }
     3625
     3626              /* We've found the switch.  Stop looking.  */
     3627              break;
     3628            }
    33233629    }
    33243630
     
    33303636    handle_non_switch_argument (argv[optind++], env);
    33313637
    3332 
    33333638  if (!env && (bad || print_usage_flag))
    33343639    {
    33353640      print_usage (bad);
    3336       die (bad ? 2 : 0);
    3337     }
     3641      die (bad ? MAKE_FAILURE : MAKE_SUCCESS);
     3642    }
     3643
     3644  /* If there are any options that need to be decoded do it now.  */
     3645  decode_debug_flags ();
     3646  decode_output_sync_flags ();
    33383647}
    33393648
     
    33443653
    33453654static void
    3346 decode_env_switches (char *envar, unsigned int len)
     3655decode_env_switches (const char *envar, unsigned int len)
    33473656{
    33483657  char *varref = alloca (2 + len + 2);
    3349   char *value, *p;
     3658  char *value, *p, *buf;
    33503659  int argc;
    3351   char **argv;
     3660  const char **argv;
    33523661
    33533662  /* Get the variable's value.  */
     
    33603669
    33613670  /* Skip whitespace, and check for an empty value.  */
    3362   value = next_token (value);
     3671  NEXT_TOKEN (value);
    33633672  len = strlen (value);
    33643673  if (len == 0)
     
    33673676  /* Allocate a vector that is definitely big enough.  */
    33683677  argv = alloca ((1 + len + 1) * sizeof (char *));
    3369 
    3370   /* Allocate a buffer to copy the value into while we split it into words
    3371      and unquote it.  We must use permanent storage for this because
    3372      decode_switches may store pointers into the passed argument words.  */
    3373   p = xmalloc (2 * len);
    33743678
    33753679  /* getopt will look at the arguments starting at ARGV[1].
     
    33773681  argv[0] = 0;
    33783682  argc = 1;
     3683
     3684  /* We need a buffer to copy the value into while we split it into words
     3685     and unquote it.  Set up in case we need to prepend a dash later.  */
     3686  buf = alloca (1 + len + 1);
     3687  buf[0] = '-';
     3688  p = buf+1;
    33793689  argv[argc] = p;
    33803690  while (*value != '\0')
    33813691    {
    33823692      if (*value == '\\' && value[1] != '\0')
    3383         ++value;                /* Skip the backslash.  */
    3384       else if (isblank ((unsigned char)*value))
    3385         {
    3386           /* End of the word.  */
    3387           *p++ = '\0';
    3388           argv[++argc] = p;
    3389           do
    3390             ++value;
    3391           while (isblank ((unsigned char)*value));
    3392           continue;
    3393         }
     3693        ++value;                /* Skip the backslash.  */
     3694      else if (ISBLANK (*value))
     3695        {
     3696          /* End of the word.  */
     3697          *p++ = '\0';
     3698          argv[++argc] = p;
     3699          do
     3700            ++value;
     3701          while (ISBLANK (*value));
     3702          continue;
     3703        }
    33943704      *p++ = *value++;
    33953705    }
    33963706  *p = '\0';
    33973707  argv[++argc] = 0;
     3708  assert (p < buf + len + 2);
    33983709
    33993710  if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
    34003711    /* The first word doesn't start with a dash and isn't a variable
    3401        definition.  Add a dash and pass it along to decode_switches.  We
    3402        need permanent storage for this in case decode_switches saves
    3403        pointers into the value.  */
    3404     argv[1] = xstrdup (concat (2, "-", argv[1]));
     3712       definition, so add a dash.  */
     3713    argv[1] = buf;
    34053714
    34063715  /* Parse those words.  */
     
    34213730    {
    34223731      if (*in == '$')
    3423         *out++ = '$';
    3424       else if (isblank ((unsigned char)*in) || *in == '\\')
     3732        *out++ = '$';
     3733      else if (ISBLANK (*in) || *in == '\\')
    34253734        *out++ = '\\';
    34263735      *out++ = *in++;
     
    34323741/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
    34333742   command switches.  Include options with args if ALL is nonzero.
    3434    Don't include options with the `no_makefile' flag set if MAKEFILE.  */
    3435 
    3436 static const char *
     3743   Don't include options with the 'no_makefile' flag set if MAKEFILE.  */
     3744
     3745static struct variable *
    34373746define_makeflags (int all, int makefile)
    34383747{
     
    34463755  const struct command_switch *cs;
    34473756  char *flagstring;
    3448   register char *p;
    3449   unsigned int words;
    3450   struct variable *v;
    3451 
    3452   /* We will construct a linked list of `struct flag's describing
     3757  char *p;
     3758
     3759  /* We will construct a linked list of 'struct flag's describing
    34533760     all the flags which need to go in MAKEFLAGS.  Then, once we
    34543761     know how many there are and their lengths, we can put them all
     
    34623769    };
    34633770  struct flag *flags = 0;
     3771  struct flag *last = 0;
    34643772  unsigned int flagslen = 0;
    3465 #define ADD_FLAG(ARG, LEN) \
    3466   do {                                                                        \
    3467     struct flag *new = alloca (sizeof (struct flag));                         \
    3468     new->cs = cs;                                                             \
    3469     new->arg = (ARG);                                                         \
    3470     new->next = flags;                                                        \
    3471     flags = new;                                                              \
    3472     if (new->arg == 0)                                                        \
    3473       ++flagslen;               /* Just a single flag letter.  */             \
    3474     else                                                                      \
    3475       /* " -x foo", plus space to expand "foo".  */                           \
    3476       flagslen += 1 + 1 + 1 + 1 + (3 * (LEN));                                \
    3477     if (!short_option (cs->c))                                                \
     3773#define ADD_FLAG(ARG, LEN) \
     3774  do {                                                                        \
     3775    struct flag *new = alloca (sizeof (struct flag));                         \
     3776    new->cs = cs;                                                             \
     3777    new->arg = (ARG);                                                         \
     3778    new->next = 0;                                                            \
     3779    if (! flags)                                                              \
     3780      flags = new;                                                            \
     3781    else                                                                      \
     3782      last->next = new;                                                       \
     3783    last = new;                                                               \
     3784    if (new->arg == 0)                                                        \
     3785      /* Just a single flag letter: " -x"  */                                 \
     3786      flagslen += 3;                                                          \
     3787    else                                                                      \
     3788      /* " -xfoo", plus space to escape "foo".  */                            \
     3789      flagslen += 1 + 1 + 1 + (3 * (LEN));                                    \
     3790    if (!short_option (cs->c))                                                \
    34783791      /* This switch has no single-letter version, so we use the long.  */    \
    3479       flagslen += 2 + strlen (cs->long_name);                                 \
     3792      flagslen += 2 + strlen (cs->long_name);                                 \
    34803793  } while (0)
    34813794
     
    34833796    if (cs->toenv && (!makefile || !cs->no_makefile))
    34843797      switch (cs->type)
    3485         {
    3486         case ignore:
    3487           break;
    3488 
    3489         case flag:
    3490         case flag_off:
    3491           if (!*(int *) cs->value_ptr == (cs->type == flag_off)
    3492               && (cs->default_value == 0
    3493                   || *(int *) cs->value_ptr != *(int *) cs->default_value))
    3494             ADD_FLAG (0, 0);
    3495           break;
    3496 
    3497         case positive_int:
    3498           if (all)
    3499             {
    3500               if ((cs->default_value != 0
    3501                    && (*(unsigned int *) cs->value_ptr
    3502                        == *(unsigned int *) cs->default_value)))
    3503                 break;
    3504               else if (cs->noarg_value != 0
    3505                        && (*(unsigned int *) cs->value_ptr ==
    3506                            *(unsigned int *) cs->noarg_value))
    3507                 ADD_FLAG ("", 0); /* Optional value omitted; see below.  */
    3508 #if !defined(KMK) || !defined(WINDOWS32) /* jobserver stuff doesn't work on windows???. */
    3509               else if (cs->c == 'j')
    3510                 /* Special case for `-j'.  */
    3511                 ADD_FLAG ("1", 1);
    3512 #endif
    3513               else
    3514                 {
    3515                   char *buf = alloca (30);
    3516                   sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
    3517                   ADD_FLAG (buf, strlen (buf));
    3518                 }
    3519             }
    3520           break;
     3798        {
     3799        case ignore:
     3800          break;
     3801
     3802        case flag:
     3803        case flag_off:
     3804          if ((!*(int *) cs->value_ptr) == (cs->type == flag_off)
     3805              && (cs->default_value == 0
     3806                  || *(int *) cs->value_ptr != *(int *) cs->default_value))
     3807            ADD_FLAG (0, 0);
     3808          break;
     3809
     3810        case positive_int:
     3811          if (all)
     3812            {
     3813              if ((cs->default_value != 0
     3814                   && (*(unsigned int *) cs->value_ptr
     3815                       == *(unsigned int *) cs->default_value)))
     3816                break;
     3817              else if (cs->noarg_value != 0
     3818                       && (*(unsigned int *) cs->value_ptr ==
     3819                           *(unsigned int *) cs->noarg_value))
     3820                ADD_FLAG ("", 0); /* Optional value omitted; see below.  */
     3821              else
     3822                {
     3823                  char *buf = alloca (30);
     3824                  sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
     3825                  ADD_FLAG (buf, strlen (buf));
     3826                }
     3827            }
     3828          break;
    35213829
    35223830#ifndef NO_FLOAT
    3523         case floating:
    3524           if (all)
    3525             {
    3526               if (cs->default_value != 0
    3527                   && (*(double *) cs->value_ptr
    3528                       == *(double *) cs->default_value))
    3529                 break;
    3530               else if (cs->noarg_value != 0
    3531                        && (*(double *) cs->value_ptr
    3532                            == *(double *) cs->noarg_value))
    3533                 ADD_FLAG ("", 0); /* Optional value omitted; see below.  */
    3534               else
    3535                 {
    3536                   char *buf = alloca (100);
    3537                   sprintf (buf, "%g", *(double *) cs->value_ptr);
    3538                   ADD_FLAG (buf, strlen (buf));
    3539                 }
    3540             }
    3541           break;
    3542 #endif
    3543 
    3544         case filename:
    3545         case string:
    3546           if (all)
    3547             {
    3548               struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
    3549               if (sl != 0)
    3550                 {
    3551                   /* Add the elements in reverse order, because all the flags
    3552                      get reversed below; and the order matters for some
    3553                      switches (like -I).  */
    3554                   unsigned int i = sl->idx;
    3555                   while (i-- > 0)
    3556                     ADD_FLAG (sl->list[i], strlen (sl->list[i]));
    3557                 }
    3558             }
    3559           break;
    3560 
    3561         default:
    3562           abort ();
    3563         }
    3564 
    3565   /* Four more for the possible " -- ".  */
    3566   flagslen += 4 + sizeof (posixref) + sizeof (evalref);
    3567 
    3568 #undef  ADD_FLAG
     3831        case floating:
     3832          if (all)
     3833            {
     3834              if (cs->default_value != 0
     3835                  && (*(double *) cs->value_ptr
     3836                      == *(double *) cs->default_value))
     3837                break;
     3838              else if (cs->noarg_value != 0
     3839                       && (*(double *) cs->value_ptr
     3840                           == *(double *) cs->noarg_value))
     3841                ADD_FLAG ("", 0); /* Optional value omitted; see below.  */
     3842              else
     3843                {
     3844                  char *buf = alloca (100);
     3845                  sprintf (buf, "%g", *(double *) cs->value_ptr);
     3846                  ADD_FLAG (buf, strlen (buf));
     3847                }
     3848            }
     3849          break;
     3850#endif
     3851
     3852        case string:
     3853          if (all)
     3854            {
     3855              p = *((char **)cs->value_ptr);
     3856              if (p)
     3857                ADD_FLAG (p, strlen (p));
     3858            }
     3859          break;
     3860
     3861        case filename:
     3862        case strlist:
     3863          if (all)
     3864            {
     3865              struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
     3866              if (sl != 0)
     3867                {
     3868                  unsigned int i;
     3869                  for (i = 0; i < sl->idx; ++i)
     3870                    ADD_FLAG (sl->list[i], strlen (sl->list[i]));
     3871                }
     3872            }
     3873          break;
     3874
     3875        default:
     3876          abort ();
     3877        }
     3878
     3879#undef  ADD_FLAG
     3880
     3881  /* Four more for the possible " -- ", plus variable references.  */
     3882  flagslen += 4 + CSTRLEN (posixref) + 1 + CSTRLEN (evalref) + 1;
    35693883
    35703884  /* Construct the value in FLAGSTRING.
     
    35733887  memset (flagstring, '\0', 1 + flagslen + 1);
    35743888  p = flagstring;
    3575   words = 1;
     3889
     3890  /* Start with a dash, for MFLAGS.  */
    35763891  *p++ = '-';
    3577   while (flags != 0)
    3578     {
     3892
     3893  /* Add simple options as a group.  */
     3894  while (flags != 0 && !flags->arg && short_option (flags->cs->c))
     3895    {
     3896      *p++ = flags->cs->c;
     3897      flags = flags->next;
     3898    }
     3899
     3900  /* Now add more complex flags: ones with options and/or long names.  */
     3901  while (flags)
     3902    {
     3903      *p++ = ' ';
     3904      *p++ = '-';
     3905
    35793906      /* Add the flag letter or name to the string.  */
    35803907      if (short_option (flags->cs->c))
    3581         *p++ = flags->cs->c;
     3908        *p++ = flags->cs->c;
    35823909      else
    3583         {
    3584           if (*p != '-')
    3585             {
    3586               *p++ = ' ';
    3587               *p++ = '-';
    3588             }
    3589           *p++ = '-';
    3590           strcpy (p, flags->cs->long_name);
    3591           p += strlen (p);
    3592         }
    3593       if (flags->arg != 0)
    3594         {
    3595           /* A flag that takes an optional argument which in this case is
    3596              omitted is specified by ARG being "".  We must distinguish
    3597              because a following flag appended without an intervening " -"
    3598              is considered the arg for the first.  */
    3599           if (flags->arg[0] != '\0')
    3600             {
    3601               /* Add its argument too.  */
    3602               *p++ = !short_option (flags->cs->c) ? '=' : ' ';
    3603               p = quote_for_env (p, flags->arg);
    3604             }
    3605           ++words;
    3606           /* Write a following space and dash, for the next flag.  */
    3607           *p++ = ' ';
    3608           *p++ = '-';
    3609         }
    3610       else if (!short_option (flags->cs->c))
    3611         {
    3612           ++words;
    3613           /* Long options must each go in their own word,
    3614              so we write the following space and dash.  */
    3615           *p++ = ' ';
    3616           *p++ = '-';
    3617         }
     3910        {
     3911          /* Long options require a double-dash.  */
     3912          *p++ = '-';
     3913          strcpy (p, flags->cs->long_name);
     3914          p += strlen (p);
     3915        }
     3916      /* An omitted optional argument has an ARG of "".  */
     3917      if (flags->arg && flags->arg[0] != '\0')
     3918        {
     3919          if (!short_option (flags->cs->c))
     3920            /* Long options require '='.  */
     3921            *p++ = '=';
     3922          p = quote_for_env (p, flags->arg);
     3923        }
    36183924      flags = flags->next;
    36193925    }
    36203926
    3621   /* Define MFLAGS before appending variable definitions.  */
    3622 
     3927  /* If no flags at all, get rid of the initial dash.  */
    36233928  if (p == &flagstring[1])
    3624     /* No flags.  */
    3625     flagstring[0] = '\0';
    3626   else if (p[-1] == '-')
    3627     {
    3628       /* Kill the final space and dash.  */
    3629       p -= 2;
    3630       *p = '\0';
    3631     }
    3632   else
    3633     /* Terminate the string.  */
    3634     *p = '\0';
     3929    {
     3930      flagstring[0] = '\0';
     3931      p = flagstring;
     3932    }
    36353933
    36363934#ifdef KMK
    3637   /* Since MFLAGS is not parsed for flags, there is no reason to
     3935  /* Define MFLAGS before appending variable definitions.  Omit an initial
     3936     empty dash.  Since MFLAGS is not parsed for flags, there is no reason to
    36383937     override any makefile redefinition.  */
    3639   define_variable_cname ("MFLAGS", flagstring, o_env, 1);
     3938  define_variable_cname ("MFLAGS",
     3939                         flagstring + (flagstring[0] == '-' && flagstring[1] == ' ' ? 2 : 0),
     3940                         o_env, 1);
    36403941#endif /* !KMK */
    36413942
     
    36443945  if (eval_strings)
    36453946    {
    3646       if (p == &flagstring[1])
    3647         /* No flags written, so elide the leading dash already written.  */
    3648         p = flagstring;
    3649       else
    3650         *p++ = ' ';
    3651       memcpy (p, evalref, sizeof (evalref) - 1);
    3652       p += sizeof (evalref) - 1;
    3653     }
    3654 
    3655   if (all && command_variables != 0)
    3656     {
    3657       /* Now write a reference to $(MAKEOVERRIDES), which contains all the
    3658          command-line variable definitions.  */
    3659 
    3660       if (p == &flagstring[1])
    3661         /* No flags written, so elide the leading dash already written.  */
    3662         p = flagstring;
    3663       else
    3664         {
    3665           /* Separate the variables from the switches with a "--" arg.  */
    3666           if (p[-1] != '-')
    3667             {
    3668               /* We did not already write a trailing " -".  */
    3669               *p++ = ' ';
    3670               *p++ = '-';
    3671             }
    3672           /* There is a trailing " -"; fill it out to " -- ".  */
    3673           *p++ = '-';
    3674           *p++ = ' ';
    3675         }
     3947      *p++ = ' ';
     3948      memcpy (p, evalref, CSTRLEN (evalref));
     3949      p += CSTRLEN (evalref);
     3950    }
     3951
     3952  if (all && command_variables)
     3953    {
     3954      /* Write a reference to $(MAKEOVERRIDES), which contains all the
     3955         command-line variable definitions.  Separate the variables from the
     3956         switches with a "--" arg.  */
     3957
     3958      strcpy (p, " -- ");
     3959      p += 4;
    36763960
    36773961      /* Copy in the string.  */
    36783962      if (posix_pedantic)
    3679         {
    3680           memcpy (p, posixref, sizeof (posixref) - 1);
    3681           p += sizeof (posixref) - 1;
    3682         }
     3963        {
     3964          memcpy (p, posixref, CSTRLEN (posixref));
     3965          p += CSTRLEN (posixref);
     3966        }
    36833967      else
    3684         {
    3685           memcpy (p, ref, sizeof (ref) - 1);
    3686           p += sizeof (ref) - 1;
    3687         }
    3688     }
    3689   else if (p == &flagstring[1])
    3690     {
    3691       words = 0;
    3692       --p;
    3693     }
    3694   else if (p[-1] == '-')
    3695     /* Kill the final space and dash.  */
    3696     p -= 2;
    3697   /* Terminate the string.  */
    3698   *p = '\0';
    3699 
    3700   /* If there are switches, omit the leading dash unless it is a single long
    3701      option with two leading dashes.  */
    3702   if (flagstring[0] == '-' && flagstring[1] != '-')
     3968        {
     3969          memcpy (p, ref, CSTRLEN (ref));
     3970          p += CSTRLEN (ref);
     3971        }
     3972    }
     3973
     3974  /* If there is a leading dash, omit it.  */
     3975  if (flagstring[0] == '-')
    37033976    ++flagstring;
    3704 
    3705 #ifdef KMK
    3706   v = define_variable_cname ("KMK_FLAGS", flagstring,
    3707                              /* This used to use o_env, but that lost when a
    3708                                 makefile defined MAKEFLAGS.  Makefiles set
    3709                                 MAKEFLAGS to add switches, but we still want
    3710                                 to redefine its value with the full set of
    3711                                 switches.  Of course, an override or command
    3712                                 definition will still take precedence.  */
    3713                              o_file, 1);
    3714 #else
    3715   v = define_variable_cname ("MAKEFLAGS", flagstring,
    3716                              /* This used to use o_env, but that lost when a
    3717                                 makefile defined MAKEFLAGS.  Makefiles set
    3718                                 MAKEFLAGS to add switches, but we still want
    3719                                 to redefine its value with the full set of
    3720                                 switches.  Of course, an override or command
    3721                                 definition will still take precedence.  */
    3722                              o_file, 1);
    3723 #endif
    3724 
    3725   if (! all)
    3726     /* The first time we are called, set MAKEFLAGS to always be exported.
    3727        We should not do this again on the second call, because that is
    3728        after reading makefiles which might have done `unexport MAKEFLAGS'. */
    3729     v->export = v_export;
    37303977
    37313978#ifdef KMK
     
    37544001#endif
    37554002
    3756   return v->value;
     4003  /* This used to use o_env, but that lost when a makefile defined MAKEFLAGS.
     4004     Makefiles set MAKEFLAGS to add switches, but we still want to redefine
     4005     its value with the full set of switches.  Then we used o_file, but that
     4006     lost when users added -e, causing a previous MAKEFLAGS env. var. to take
     4007     precedence over the new one.  Of course, an override or command
     4008     definition will still take precedence.  */
     4009#ifdef KMK
     4010  return define_variable_cname ("KMK_FLAGS", flagstring,
     4011                                env_overrides ? o_env_override : o_file, 1);
     4012#else
     4013  return define_variable_cname ("MAKEFLAGS", flagstring,
     4014                                env_overrides ? o_env_override : o_file, 1);
     4015#endif
    37574016}
    37584017
     
    37654024  static int printed_version = 0;
    37664025
    3767   char *precede = print_data_base_flag ? "# " : "";
     4026  const char *precede = print_data_base_flag ? "# " : "";
    37684027
    37694028  if (printed_version)
     
    37924051     (C) to the copyright symbol, but this string is going to change every
    37934052     year, and none of the rest of it should be translated (including the
    3794      word "Copyright", so it hardly seems worth it.  */
    3795 
    3796   printf ("%sCopyright (C) 2010  Free Software Foundation, Inc.\n", precede);
     4053     word "Copyright"), so it hardly seems worth it.  */
     4054
     4055  printf ("%sCopyright (C) 1988-2016 Free Software Foundation, Inc.\n",
     4056          precede);
    37974057
    37984058  printf (_("%sLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
     
    38404100
    38414101  /* Flush stdout so the user doesn't have to wait to see the
    3842      version information while things are thought about.  */
     4102     version information while make thinks about things.  */
    38434103  fflush (stdout);
    38444104}
     
    38474107
    38484108static void
    3849 print_data_base ()
     4109print_data_base (void)
    38504110{
    3851   time_t when;
    3852 
    3853   when = time ((time_t *) 0);
     4111  time_t when = time ((time_t *) 0);
     4112
     4113  print_version ();
     4114
    38544115  printf (_("\n# Make data base, printed on %s"), ctime (&when));
    38554116
     
    39204181clean_jobserver (int status)
    39214182{
    3922   char token = '+';
    3923 
    39244183  /* Sanity: have we written all our jobserver tokens back?  If our
    39254184     exit status is 2 that means some kind of syntax error; we might not
     
    39274186     after any other error code, that's bad.  */
    39284187
    3929   if (job_fds[0] != -1 && jobserver_tokens)
     4188  if (jobserver_enabled() && jobserver_tokens)
    39304189    {
    39314190      if (status != 2)
    3932         error (NILF,
    3933                "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
    3934                jobserver_tokens);
     4191        ON (error, NILF,
     4192            "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
     4193            jobserver_tokens);
    39354194      else
    3936         while (jobserver_tokens--)
    3937           {
    3938             int r;
    3939 
    3940             EINTRLOOP (r, write (job_fds[1], &token, 1));
    3941             if (r != 1)
    3942               perror_with_name ("write", "");
    3943           }
     4195        /* Don't write back the "free" token */
     4196        while (--jobserver_tokens)
     4197          jobserver_release (0);
    39444198    }
    39454199
     
    39504204    {
    39514205      /* We didn't write one for ourself, so start at 1.  */
    3952       unsigned int tcnt = 1;
    3953 
    3954       /* Close the write side, so the read() won't hang.  */
    3955       close (job_fds[1]);
    3956 
    3957       while (read (job_fds[0], &token, 1) == 1)
    3958         ++tcnt;
    3959 
    3960       if (tcnt != master_job_slots)
    3961         error (NILF,
    3962                "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
    3963                tcnt, master_job_slots);
    3964 
    3965       close (job_fds[0]);
    3966 
    3967       /* Clean out jobserver_fds so we don't pass this information to any
    3968          sub-makes.  Also reset job_slots since it will be put on the command
    3969          line, not in MAKEFLAGS.  */
    3970       job_slots = default_job_slots;
    3971       if (jobserver_fds)
    3972         {
    3973           /* MSVC erroneously warns without a cast here.  */
    3974           free ((void *)jobserver_fds->list);
    3975           free (jobserver_fds);
    3976           jobserver_fds = 0;
    3977         }
     4206      unsigned int tokens = 1 + jobserver_acquire_all ();
     4207
     4208      if (tokens != master_job_slots)
     4209        ONN (error, NILF,
     4210             "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
     4211             tokens, master_job_slots);
     4212
     4213      reset_jobserver ();
    39784214    }
    39794215}
     
    39974233
    39984234      if (print_version_flag)
    3999         print_version ();
     4235        print_version ();
    40004236
    40014237#ifdef KMK
     
    40114247      err = (status != 0);
    40124248      while (job_slots_used > 0)
    4013         reap_children (1, err);
     4249        reap_children (1, err);
    40144250
    40154251      /* Let the remote job module clean up its state.  */
     
    40204256
    40214257      if (print_data_base_flag)
    4022         print_data_base ();
     4258        print_data_base ();
    40234259
    40244260#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
     
    40264262        print_stats ();
    40274263#endif
     4264      if (verify_flag)
     4265        verify_file_data_base ();
    40284266
    40294267#ifdef NDEBUG /* bird: Don't waste time on debug sanity checks.  */
     
    40344272      clean_jobserver (status);
    40354273
     4274      if (output_context)
     4275        {
     4276          /* die() might be called in a recipe output context due to an
     4277             $(error ...) function.  */
     4278          output_close (output_context);
     4279
     4280          if (output_context != &make_sync)
     4281            output_close (&make_sync);
     4282
     4283          OUTPUT_UNSET ();
     4284        }
     4285
     4286      output_close (NULL);
     4287
    40364288      /* Try to move back to the original directory.  This is essential on
    4037         MS-DOS (where there is really only one process), and on Unix it
    4038         puts core files in the original directory instead of the -C
    4039         directory.  Must wait until after remove_intermediates(), or unlinks
     4289        MS-DOS (where there is really only one process), and on Unix it
     4290        puts core files in the original directory instead of the -C
     4291        directory.  Must wait until after remove_intermediates(), or unlinks
    40404292         of relative pathnames fail.  */
    40414293      if (directory_before_chdir != 0)
    40424294        {
    40434295          /* If it fails we don't care: shut up GCC.  */
    4044           int _x;
     4296          int _x UNUSED;
    40454297          _x = chdir (directory_before_chdir);
    40464298        }
     
    40544306              char buf[64];
    40554307              format_elapsed_nano (buf, sizeof (buf), elapsed);
    4056               message (1, _("%*s"), print_time_width, buf);
     4308              message (1, strlen (buf), _("%*s"), print_time_width, buf);
    40574309            }
    40584310        }
    40594311#endif
    4060 
    4061       log_working_directory (0);
    40624312    }
    40634313
     
    40664316     failure again before exiting. */
    40674317  if (need_2nd_error != 0)
    4068     error (NILF, _("*** Exiting with status %d"), status);
     4318    ON (error, NILF, _("*** Exiting with status %d"), status);
    40694319#endif
    40704320
    40714321  exit (status);
    40724322}
    4073 
    4074 
    4075 /* Write a message indicating that we've just entered or
    4076    left (according to ENTERING) the current directory.  */
    4077 
    4078 void
    4079 log_working_directory (int entering)
    4080 {
    4081   static int entered = 0;
    4082 
    4083   /* Print nothing without the flag.  Don't print the entering message
    4084      again if we already have.  Don't print the leaving message if we
    4085      haven't printed the entering message.  */
    4086   if (! print_directory_flag || entering == entered)
    4087     return;
    4088 
    4089   entered = entering;
    4090 
    4091   if (print_data_base_flag)
    4092     fputs ("# ", stdout);
    4093 
    4094   /* Use entire sentences to give the translators a fighting chance.  */
    4095 
    4096   if (makelevel == 0)
    4097     if (starting_directory == 0)
    4098       if (entering)
    4099         printf (_("%s: Entering an unknown directory\n"), program);
    4100       else
    4101         printf (_("%s: Leaving an unknown directory\n"), program);
    4102     else
    4103       if (entering)
    4104         printf (_("%s: Entering directory `%s'\n"),
    4105                 program, starting_directory);
    4106       else
    4107         printf (_("%s: Leaving directory `%s'\n"),
    4108                 program, starting_directory);
    4109   else
    4110     if (starting_directory == 0)
    4111       if (entering)
    4112         printf (_("%s[%u]: Entering an unknown directory\n"),
    4113                 program, makelevel);
    4114       else
    4115         printf (_("%s[%u]: Leaving an unknown directory\n"),
    4116                 program, makelevel);
    4117     else
    4118       if (entering)
    4119         printf (_("%s[%u]: Entering directory `%s'\n"),
    4120                 program, makelevel, starting_directory);
    4121       else
    4122         printf (_("%s[%u]: Leaving directory `%s'\n"),
    4123                 program, makelevel, starting_directory);
    4124 
    4125   /* Flush stdout to be sure this comes before any stderr output.  */
    4126   fflush (stdout);
    4127 }
Note: See TracChangeset for help on using the changeset viewer.