Ignore:
Timestamp:
Mar 12, 2018, 8:32:29 PM (7 years ago)
Author:
bird
Message:

Imported make 4.2.1 (2e55f5e4abdc0e38c1d64be703b446695e70b3b6) from https://git.savannah.gnu.org/git/make.git.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • vendor/gnumake/current/job.c

    r2596 r3138  
    11/* Job execution and handling for 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"
    2018
    2119#include <assert.h>
     
    2624#include "commands.h"
    2725#include "variable.h"
    28 #include "debug.h"
     26#include "os.h"
    2927
    3028#include <string.h>
     
    3432#include <windows.h>
    3533
    36 char *default_shell = "sh.exe";
     34const char *default_shell = "sh.exe";
    3735int no_default_sh_exe = 1;
    3836int batch_mode_shell = 1;
     
    4139#elif defined (_AMIGA)
    4240
    43 char default_shell[] = "";
     41const char *default_shell = "";
    4442extern int MyExecute (char **);
    4543int batch_mode_shell = 0;
     
    5149   to search the $PATH for it (since MSDOS doesn't have standard
    5250   directories we could trust).  */
    53 char *default_shell = "command.com";
     51const char *default_shell = "command.com";
    5452int batch_mode_shell = 0;
    5553
    5654#elif defined (__EMX__)
    5755
    58 char *default_shell = "/bin/sh";
     56const char *default_shell = "/bin/sh";
    5957int batch_mode_shell = 0;
    6058
     
    6260
    6361# include <descrip.h>
    64 char default_shell[] = "";
     62# include <stsdef.h>
     63const char *default_shell = "";
    6564int batch_mode_shell = 0;
    6665
    67 #elif defined (__riscos__)
    68 
    69 char default_shell[] = "";
    70 int batch_mode_shell = 0;
     66#define strsignal vms_strsignal
     67char * vms_strsignal (int status);
     68
     69#ifndef C_FACILITY_NO
     70# define C_FACILITY_NO 0x350000
     71#endif
     72#ifndef VMS_POSIX_EXIT_MASK
     73# define VMS_POSIX_EXIT_MASK (C_FACILITY_NO | 0xA000)
     74#endif
    7175
    7276#else
    7377
    74 char default_shell[] = "/bin/sh";
     78const char *default_shell = "/bin/sh";
    7579int batch_mode_shell = 0;
    7680
     
    109113# include "w32err.h"
    110114# include "pathstuff.h"
     115# define WAIT_NOHANG 1
    111116#endif /* WINDOWS32 */
    112117
     
    120125
    121126#ifdef HAVE_WAITPID
    122 # define WAIT_NOHANG(status)    waitpid (-1, (status), WNOHANG)
    123 #else   /* Don't have waitpid.  */
     127# define WAIT_NOHANG(status)    waitpid (-1, (status), WNOHANG)
     128#else   /* Don't have waitpid.  */
    124129# ifdef HAVE_WAIT3
    125130#  ifndef wait3
    126131extern int wait3 ();
    127132#  endif
    128 #  define WAIT_NOHANG(status)   wait3 ((status), WNOHANG, (struct rusage *) 0)
     133#  define WAIT_NOHANG(status)   wait3 ((status), WNOHANG, (struct rusage *) 0)
    129134# endif /* Have wait3.  */
    130135#endif /* Have waitpid.  */
     
    134139#endif
    135140
    136 #ifndef HAVE_UNION_WAIT
     141#ifndef HAVE_UNION_WAIT
    137142
    138143# define WAIT_T int
     
    154159# endif
    155160
    156 #else   /* Have `union wait'.  */
     161#else   /* Have 'union wait'.  */
    157162
    158163# define WAIT_T union wait
     
    173178# endif
    174179
    175 #endif  /* Don't have `union wait'.  */
     180#endif  /* Don't have 'union wait'.  */
    176181
    177182#if !defined(HAVE_UNISTD_H) && !defined(WINDOWS32)
     
    203208}
    204209
     210#ifndef HAVE_GETLOADAVG
    205211int getloadavg (double loadavg[], int nelem);
    206 int start_remote_job (char **argv, char **envp, int stdin_fd, int *is_remote,
    207                       int *id_ptr, int *used_stdin);
    208 int start_remote_job_p (int);
    209 int remote_status (int *exit_code_ptr, int *signal_ptr, int *coredump_ptr,
    210                    int block);
    211 
    212 RETSIGTYPE child_handler (int);
     212#endif
     213
    213214static void free_child (struct child *);
    214215static void start_job_command (struct child *child);
     
    226227unsigned int job_slots_used = 0;
    227228
    228 /* Nonzero if the `good' standard input is in use.  */
     229/* Nonzero if the 'good' standard input is in use.  */
    229230
    230231static int good_stdin_used = 0;
     
    245246
    246247unsigned int jobserver_tokens = 0;
     248
    247249
    248250
    249251#ifdef WINDOWS32
    250252/*
    251  * The macro which references this function is defined in make.h.
     253 * The macro which references this function is defined in makeint.h.
    252254 */
    253255int
    254 w32_kill(pid_t pid, int sig)
     256w32_kill (pid_t pid, int sig)
    255257{
    256   return ((process_kill((HANDLE)pid, sig) == TRUE) ? 0 : -1);
     258  return ((process_kill ((HANDLE)pid, sig) == TRUE) ? 0 : -1);
    257259}
    258260
     
    267269  const char *error_string = NULL;
    268270  char temp_path[MAXPATHLEN]; /* need to know its length */
    269   unsigned path_size = GetTempPath(sizeof temp_path, temp_path);
     271  unsigned path_size = GetTempPath (sizeof temp_path, temp_path);
    270272  int path_is_dot = 0;
    271   unsigned uniq = 1;
     273  /* The following variable is static so we won't try to reuse a name
     274     that was generated a little while ago, because that file might
     275     not be on disk yet, since we use FILE_ATTRIBUTE_TEMPORARY below,
     276     which tells the OS it doesn't need to flush the cache to disk.
     277     If the file is not yet on disk, we might think the name is
     278     available, while it really isn't.  This happens in parallel
     279     builds, where Make doesn't wait for one job to finish before it
     280     launches the next one.  */
     281  static unsigned uniq = 0;
     282  static int second_loop = 0;
    272283  const unsigned sizemax = strlen (base) + strlen (ext) + 10;
    273284
     
    278289    }
    279290
     291  ++uniq;
     292  if (uniq >= 0x10000 && !second_loop)
     293    {
     294      /* If we already had 64K batch files in this
     295         process, make a second loop through the numbers,
     296         looking for free slots, i.e. files that were
     297         deleted in the meantime.  */
     298      second_loop = 1;
     299      uniq = 1;
     300    }
    280301  while (path_size > 0 &&
    281302         path_size + sizemax < sizeof temp_path &&
    282          uniq < 0x10000)
     303         !(uniq >= 0x10000 && second_loop))
    283304    {
    284305      unsigned size = sprintf (temp_path + path_size,
     
    297318      if (h == INVALID_HANDLE_VALUE)
    298319        {
    299           const DWORD er = GetLastError();
     320          const DWORD er = GetLastError ();
    300321
    301322          if (er == ERROR_FILE_EXISTS || er == ERROR_ALREADY_EXISTS)
    302             ++uniq;
     323            {
     324              ++uniq;
     325              if (uniq == 0x10000 && !second_loop)
     326                {
     327                  second_loop = 1;
     328                  uniq = 1;
     329                }
     330            }
    303331
    304332          /* the temporary path is not guaranteed to exist */
     
    336364  if (error_string == NULL)
    337365    error_string = _("Cannot create a temporary file\n");
    338   fatal (NILF, error_string);
     366  O (fatal, NILF, error_string);
    339367
    340368  /* not reached */
     
    376404
    377405  i = 0;
    378   while (known_os2shells[i] != NULL) {
    379     if (strcasecmp (name, known_os2shells[i]) == 0)
    380       return 0; /* not a unix shell */
    381     i++;
    382   }
     406  while (known_os2shells[i] != NULL)
     407    {
     408      if (strcasecmp (name, known_os2shells[i]) == 0)
     409        return 0; /* not a unix shell */
     410      i++;
     411    }
    383412
    384413  /* in doubt assume a unix like shell */
     
    391420is_bourne_compatible_shell (const char *path)
    392421{
    393   /* list of known unix (Bourne-like) shells */
    394   const char *unix_shells[] = {
     422  /* List of known POSIX (or POSIX-ish) shells. */
     423  static const char *unix_shells[] = {
    395424    "sh",
    396425    "bash",
     
    402431    NULL
    403432  };
    404   unsigned i, len;
     433  const char **s;
    405434
    406435  /* find the rightmost '/' or '\\' */
     
    415444    name = path;
    416445
    417   if (*name == '/' || *name == '\\') name++;
     446  if (*name == '/' || *name == '\\')
     447    ++name;
    418448
    419449  /* this should be able to deal with extensions on Windows-like systems */
    420   for (i = 0; unix_shells[i] != NULL; i++) {
    421     len = strlen(unix_shells[i]);
     450  for (s = unix_shells; *s != NULL; ++s)
     451    {
    422452#if defined(WINDOWS32) || defined(__MSDOS__)
    423     if ((strncasecmp (name, unix_shells[i], len) == 0) &&
    424       (strlen(name) >= len && (name[len] == '\0' || name[len] == '.')))
     453      unsigned int len = strlen (*s);
     454      if ((strlen (name) >= len && STOP_SET (name[len], MAP_DOT|MAP_NUL))
     455          && strncasecmp (name, *s, len) == 0)
    425456#else
    426     if ((strncmp (name, unix_shells[i], len) == 0) &&
    427       (strlen(name) >= len && name[len] == '\0'))
    428 #endif
    429         return 1; /* a known unix-style shell */
    430   }
     457      if (strcmp (name, *s) == 0)
     458#endif
     459        return 1; /* a known unix-style shell */
     460    }
    431461
    432462  /* if not on the list, assume it's not a Bourne-like shell */
     
    441471
    442472static void
    443 child_error (const char *target_name,
     473child_error (struct child *child,
    444474             int exit_code, int exit_sig, int coredump, int ignored)
    445475{
     476  const char *pre = "*** ";
     477  const char *post = "";
     478  const char *dump = "";
     479  const struct file *f = child->file;
     480  const floc *flocp = &f->cmds->fileinfo;
     481  const char *nm;
     482  size_t l;
     483
    446484  if (ignored && silent_flag)
    447485    return;
    448486
    449 #ifdef VMS
    450   if (!(exit_code & 1))
    451       error (NILF,
    452              (ignored ? _("*** [%s] Error 0x%x (ignored)")
    453               : _("*** [%s] Error 0x%x")),
    454              target_name, exit_code);
    455 #else
     487  if (exit_sig && coredump)
     488    dump = _(" (core dumped)");
     489
     490  if (ignored)
     491    {
     492      pre = "";
     493      post = _(" (ignored)");
     494    }
     495
     496  if (! flocp->filenm)
     497    nm = _("<builtin>");
     498  else
     499    {
     500      char *a = alloca (strlen (flocp->filenm) + 1 + 11 + 1);
     501      sprintf (a, "%s:%lu", flocp->filenm, flocp->lineno + flocp->offset);
     502      nm = a;
     503    }
     504
     505  l = strlen (pre) + strlen (nm) + strlen (f->name) + strlen (post);
     506
     507  OUTPUT_SET (&child->output);
     508
     509  show_goal_error ();
     510
    456511  if (exit_sig == 0)
    457     error (NILF, ignored ? _("[%s] Error %d (ignored)") :
    458            _("*** [%s] Error %d"),
    459            target_name, exit_code);
     512    error (NILF, l + INTSTR_LENGTH,
     513           _("%s[%s: %s] Error %d%s"), pre, nm, f->name, exit_code, post);
    460514  else
    461     error (NILF, "*** [%s] %s%s",
    462            target_name, strsignal (exit_sig),
    463            coredump ? _(" (core dumped)") : "");
    464 #endif /* VMS */
     515    {
     516      const char *s = strsignal (exit_sig);
     517      error (NILF, l + strlen (s) + strlen (dump),
     518             "%s[%s: %s] %s%s%s", pre, nm, f->name, s, dump, post);
     519    }
     520
     521  OUTPUT_UNSET ();
    465522}
    466523
     
    469526/* Handle a dead child.  This handler may or may not ever be installed.
    470527
    471    If we're using the jobserver feature, we need it.  First, installing it
    472    ensures the read will interrupt on SIGCHLD.  Second, we close the dup'd
    473    read FD to ensure we don't enter another blocking read without reaping all
    474    the dead children.  In this case we don't need the dead_children count.
     528   If we're using the jobserver feature without pselect(), we need it.
     529   First, installing it ensures the read will interrupt on SIGCHLD.  Second,
     530   we close the dup'd read FD to ensure we don't enter another blocking read
     531   without reaping all the dead children.  In this case we don't need the
     532   dead_children count.
    475533
    476534   If we don't have either waitpid or wait3, then make is unreliable, but we
     
    484542  ++dead_children;
    485543
    486   if (job_rfd >= 0)
    487     {
    488       close (job_rfd);
    489       job_rfd = -1;
    490     }
     544  jobserver_signal ();
    491545
    492546#ifdef __EMX__
     
    494548  signal (SIGCHLD, SIG_DFL);
    495549#endif
    496 
    497   /* This causes problems if the SIGCHLD interrupts a printf().
    498   DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
    499   */
    500550}
    501551
    502 extern int shell_function_pid, shell_function_completed;
     552extern pid_t shell_function_pid;
    503553
    504554/* Reap all dead children, storing the returned status and the new command
    505    state (`cs_finished') in the `file' member of the `struct child' for the
     555   state ('cs_finished') in the 'file' member of the 'struct child' for the
    506556   dead child, and removing the child from the chain.  In addition, if BLOCK
    507557   nonzero, we block in this function until we've reaped at least one
     
    514564#ifndef WINDOWS32
    515565  WAIT_T status;
     566#endif
    516567  /* Initially, assume we have some.  */
    517568  int reap_more = 1;
    518 #endif
    519569
    520570#ifdef WAIT_NOHANG
     
    535585         && (block || REAP_MORE))
    536586    {
    537       int remote = 0;
     587      unsigned int remote = 0;
    538588      pid_t pid;
    539589      int exit_code, exit_sig, coredump;
    540       register struct child *lastc, *c;
     590      struct child *lastc, *c;
    541591      int child_failed;
    542592      int any_remote, any_local;
     
    544594
    545595      if (err && block)
    546         {
     596        {
    547597          static int printed = 0;
    548598
    549           /* We might block for a while, so let the user know why.
     599          /* We might block for a while, so let the user know why.
    550600             Only print this message once no matter how many jobs are left.  */
    551           fflush (stdout);
     601          fflush (stdout);
    552602          if (!printed)
    553             error (NILF, _("*** Waiting for unfinished jobs...."));
     603            O (error, NILF, _("*** Waiting for unfinished jobs...."));
    554604          printed = 1;
    555         }
     605        }
    556606
    557607      /* We have one less dead child to reap.  As noted in
    558         child_handler() above, this count is completely unimportant for
    559         all modern, POSIX-y systems that support wait3() or waitpid().
    560         The rest of this comment below applies only to early, broken
    561         pre-POSIX systems.  We keep the count only because... it's there...
    562 
    563         The test and decrement are not atomic; if it is compiled into:
    564                 register = dead_children - 1;
    565                 dead_children = register;
    566         a SIGCHLD could come between the two instructions.
    567         child_handler increments dead_children.
    568         The second instruction here would lose that increment.  But the
    569         only effect of dead_children being wrong is that we might wait
    570         longer than necessary to reap a child, and lose some parallelism;
    571         and we might print the "Waiting for unfinished jobs" message above
    572         when not necessary.  */
     608        child_handler() above, this count is completely unimportant for
     609        all modern, POSIX-y systems that support wait3() or waitpid().
     610        The rest of this comment below applies only to early, broken
     611        pre-POSIX systems.  We keep the count only because... it's there...
     612
     613        The test and decrement are not atomic; if it is compiled into:
     614                register = dead_children - 1;
     615                dead_children = register;
     616        a SIGCHLD could come between the two instructions.
     617        child_handler increments dead_children.
     618        The second instruction here would lose that increment.  But the
     619        only effect of dead_children being wrong is that we might wait
     620        longer than necessary to reap a child, and lose some parallelism;
     621        and we might print the "Waiting for unfinished jobs" message above
     622        when not necessary.  */
    573623
    574624      if (dead_children > 0)
    575         --dead_children;
     625        --dead_children;
    576626
    577627      any_remote = 0;
    578628      any_local = shell_function_pid != 0;
    579629      for (c = children; c != 0; c = c->next)
    580         {
    581           any_remote |= c->remote;
    582           any_local |= ! c->remote;
    583           DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
     630        {
     631          any_remote |= c->remote;
     632          any_local |= ! c->remote;
     633          DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
    584634                        c, c->file->name, pid2str (c->pid),
    585635                        c->remote ? _(" (remote)") : ""));
    586636#ifdef VMS
    587           break;
    588 #endif
    589         }
     637          break;
     638#endif
     639        }
    590640
    591641      /* First, check for remote children.  */
    592642      if (any_remote)
    593         pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
     643        pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
    594644      else
    595         pid = 0;
     645        pid = 0;
    596646
    597647      if (pid > 0)
    598         /* We got a remote child.  */
    599         remote = 1;
     648        /* We got a remote child.  */
     649        remote = 1;
    600650      else if (pid < 0)
    601         {
     651        {
    602652          /* A remote status command failed miserably.  Punt.  */
    603         remote_status_lose:
    604           pfatal_with_name ("remote_status");
    605         }
     653        remote_status_lose:
     654          pfatal_with_name ("remote_status");
     655        }
    606656      else
    607         {
    608           /* No remote children.  Check for local children.  */
     657        {
     658          /* No remote children.  Check for local children.  */
    609659#if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
    610           if (any_local)
    611             {
     660          if (any_local)
     661            {
    612662#ifdef VMS
    613               vmsWaitForChildren (&status);
    614               pid = c->pid;
     663              /* Todo: This needs more untangling multi-process support */
     664              /* Just do single child process support now */
     665              vmsWaitForChildren (&status);
     666              pid = c->pid;
     667
     668              /* VMS failure status can not be fully translated */
     669              status = $VMS_STATUS_SUCCESS (c->cstatus) ? 0 : (1 << 8);
     670
     671              /* A Posix failure can be exactly translated */
     672              if ((c->cstatus & VMS_POSIX_EXIT_MASK) == VMS_POSIX_EXIT_MASK)
     673                status = (c->cstatus >> 3 & 255) << 8;
    615674#else
    616675#ifdef WAIT_NOHANG
    617               if (!block)
    618                 pid = WAIT_NOHANG (&status);
    619               else
    620 #endif
    621                 EINTRLOOP(pid, wait (&status));
     676              if (!block)
     677                pid = WAIT_NOHANG (&status);
     678              else
     679#endif
     680                EINTRLOOP (pid, wait (&status));
    622681#endif /* !VMS */
    623             }
    624           else
    625             pid = 0;
    626 
    627           if (pid < 0)
    628             {
     682            }
     683          else
     684            pid = 0;
     685
     686          if (pid < 0)
     687            {
    629688              /* The wait*() failed miserably.  Punt.  */
    630               pfatal_with_name ("wait");
    631             }
    632           else if (pid > 0)
    633             {
    634               /* We got a child exit; chop the status word up.  */
    635               exit_code = WEXITSTATUS (status);
    636               exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
    637               coredump = WCOREDUMP (status);
     689              pfatal_with_name ("wait");
     690            }
     691          else if (pid > 0)
     692            {
     693              /* We got a child exit; chop the status word up.  */
     694              exit_code = WEXITSTATUS (status);
     695              exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
     696              coredump = WCOREDUMP (status);
    638697
    639698              /* If we have started jobs in this second, remove one.  */
    640699              if (job_counter)
    641700                --job_counter;
    642             }
    643           else
    644             {
    645               /* No local children are dead.  */
     701            }
     702          else
     703            {
     704              /* No local children are dead.  */
    646705              reap_more = 0;
    647706
    648               if (!block || !any_remote)
     707              if (!block || !any_remote)
    649708                break;
    650709
     
    659718              /* We got a remote child.  */
    660719              remote = 1;
    661             }
     720            }
    662721#endif /* !__MSDOS__, !Amiga, !WINDOWS32.  */
    663722
    664723#ifdef __MSDOS__
    665           /* Life is very different on MSDOS.  */
    666           pid = dos_pid - 1;
    667           status = dos_status;
    668           exit_code = WEXITSTATUS (status);
    669           if (exit_code == 0xff)
    670             exit_code = -1;
    671           exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
    672           coredump = 0;
     724          /* Life is very different on MSDOS.  */
     725          pid = dos_pid - 1;
     726          status = dos_status;
     727          exit_code = WEXITSTATUS (status);
     728          if (exit_code == 0xff)
     729            exit_code = -1;
     730          exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
     731          coredump = 0;
    673732#endif /* __MSDOS__ */
    674733#ifdef _AMIGA
    675           /* Same on Amiga */
    676           pid = amiga_pid - 1;
    677           status = amiga_status;
    678           exit_code = amiga_status;
    679           exit_sig = 0;
    680           coredump = 0;
     734          /* Same on Amiga */
     735          pid = amiga_pid - 1;
     736          status = amiga_status;
     737          exit_code = amiga_status;
     738          exit_sig = 0;
     739          coredump = 0;
    681740#endif /* _AMIGA */
    682741#ifdef WINDOWS32
    683742          {
    684743            HANDLE hPID;
    685             int werr;
    686744            HANDLE hcTID, hcPID;
     745            DWORD dwWaitStatus = 0;
    687746            exit_code = 0;
    688747            exit_sig = 0;
     
    701760                    fprintf (stderr,
    702761                             "Determine main thread ID (Error %ld: %s)\n",
    703                              e, map_windows32_error_to_string(e));
     762                             e, map_windows32_error_to_string (e));
    704763                  }
    705764                else
     
    708767
    709768            /* wait for anything to finish */
    710             hPID = process_wait_for_any();
     769            hPID = process_wait_for_any (block, &dwWaitStatus);
    711770            if (hPID)
    712771              {
    713 
    714772                /* was an error found on this process? */
    715                 werr = process_last_err(hPID);
     773                int werr = process_last_err (hPID);
    716774
    717775                /* get exit data */
    718                 exit_code = process_exit_code(hPID);
     776                exit_code = process_exit_code (hPID);
    719777
    720778                if (werr)
    721                   fprintf(stderr, "make (e=%d): %s",
    722                           exit_code, map_windows32_error_to_string(exit_code));
     779                  fprintf (stderr, "make (e=%d): %s", exit_code,
     780                           map_windows32_error_to_string (exit_code));
    723781
    724782                /* signal */
    725                 exit_sig = process_signal(hPID);
     783                exit_sig = process_signal (hPID);
    726784
    727785                /* cleanup process */
    728                 process_cleanup(hPID);
     786                process_cleanup (hPID);
    729787
    730788                coredump = 0;
    731789              }
     790            else if (dwWaitStatus == WAIT_FAILED)
     791              {
     792                /* The WaitForMultipleObjects() failed miserably.  Punt.  */
     793                pfatal_with_name ("WaitForMultipleObjects");
     794              }
     795            else if (dwWaitStatus == WAIT_TIMEOUT)
     796              {
     797                /* No child processes are finished.  Give up waiting. */
     798                reap_more = 0;
     799                break;
     800              }
     801
    732802            pid = (pid_t) hPID;
    733803          }
    734804#endif /* WINDOWS32 */
    735         }
    736 
    737       /* Check if this is the child of the `shell' function.  */
     805        }
     806
     807      /* Check if this is the child of the 'shell' function.  */
    738808      if (!remote && pid == shell_function_pid)
    739         {
    740           /* It is.  Leave an indicator for the `shell' function.  */
    741           if (exit_sig == 0 && exit_code == 127)
    742             shell_function_completed = -1;
    743           else
    744             shell_function_completed = 1;
    745           break;
    746         }
    747 
    748       child_failed = exit_sig != 0 || exit_code != 0;
     809        {
     810          shell_completed (exit_code, exit_sig);
     811          break;
     812        }
    749813
    750814      /* Search for a child matching the deceased one.  */
    751815      lastc = 0;
    752816      for (c = children; c != 0; lastc = c, c = c->next)
    753         if (c->remote == remote && c->pid == pid)
    754           break;
     817        if (c->pid == pid && c->remote == remote)
     818          break;
    755819
    756820      if (c == 0)
     
    759823        continue;
    760824
     825      /* Determine the failure status: 0 for success, 1 for updating target in
     826         question mode, 2 for anything else.  */
     827      if (exit_sig == 0 && exit_code == 0)
     828        child_failed = MAKE_SUCCESS;
     829      else if (exit_sig == 0 && exit_code == 1 && question_flag && c->recursive)
     830        child_failed = MAKE_TROUBLE;
     831      else
     832        child_failed = MAKE_FAILURE;
     833
    761834      DB (DB_JOBS, (child_failed
    762835                    ? _("Reaping losing child %p PID %s %s\n")
     
    764837                    c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
    765838
    766       if (c->sh_batch_file) {
    767         DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
    768                       c->sh_batch_file));
    769 
    770         /* just try and remove, don't care if this fails */
    771         remove (c->sh_batch_file);
    772 
    773         /* all done with memory */
    774         free (c->sh_batch_file);
    775         c->sh_batch_file = NULL;
    776       }
     839      if (c->sh_batch_file)
     840        {
     841          int rm_status;
     842
     843          DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
     844                        c->sh_batch_file));
     845
     846          errno = 0;
     847          rm_status = remove (c->sh_batch_file);
     848          if (rm_status)
     849            DB (DB_JOBS, (_("Cleaning up temp batch file %s failed (%d)\n"),
     850                          c->sh_batch_file, errno));
     851
     852          /* all done with memory */
     853          free (c->sh_batch_file);
     854          c->sh_batch_file = NULL;
     855        }
    777856
    778857      /* If this child had the good stdin, say it is now free.  */
     
    788867          static int delete_on_error = -1;
    789868
    790           if (!dontcare)
    791             child_error (c->file->name, exit_code, exit_sig, coredump, 0);
    792 
    793           c->file->update_status = 2;
     869          if (!dontcare && child_failed == MAKE_FAILURE)
     870            child_error (c, exit_code, exit_sig, coredump, 0);
     871
     872          c->file->update_status = child_failed == MAKE_FAILURE ? us_failed : us_question;
    794873          if (delete_on_error == -1)
    795874            {
     
    805884            {
    806885              /* The commands failed, but we don't care.  */
    807               child_error (c->file->name,
    808                            exit_code, exit_sig, coredump, 1);
     886              child_error (c, exit_code, exit_sig, coredump, 1);
    809887              child_failed = 0;
    810888            }
     
    819897                     the target was not completely remade.  So we treat
    820898                     this as if a command had failed.  */
    821                   c->file->update_status = 2;
     899                  c->file->update_status = us_failed;
    822900                }
    823901              else
    824902                {
     903#ifndef NO_OUTPUT_SYNC
     904                  /* If we're sync'ing per line, write the previous line's
     905                     output before starting the next one.  */
     906                  if (output_sync == OUTPUT_SYNC_LINE)
     907                    output_dump (&c->output);
     908#endif
    825909                  /* Check again whether to start remotely.
    826910                     Whether or not we want to changes over time.
     
    840924                }
    841925
    842               if (c->file->update_status != 0)
     926              if (c->file->update_status != us_success)
    843927                /* We failed to start the commands.  */
    844928                delete_child_targets (c);
     
    848932               without an unignored error.  Now the target has been
    849933               successfully updated.  */
    850             c->file->update_status = 0;
     934            c->file->update_status = us_success;
    851935        }
    852936
    853       /* When we get here, all the commands for C->file are finished
    854          (or aborted) and C->file->update_status contains 0 or 2.  But
    855          C->file->command_state is still cs_running if all the commands
     937      /* When we get here, all the commands for c->file are finished.  */
     938
     939#ifndef NO_OUTPUT_SYNC
     940      /* Synchronize any remaining parallel output.  */
     941      output_dump (&c->output);
     942#endif
     943
     944      /* At this point c->file->update_status is success or failed.  But
     945         c->file->command_state is still cs_running if all the commands
    856946         ran; notice_finish_file looks for cs_running to tell it that
    857947         it's interesting to check the file's modtime again now.  */
     
    892982          /* fatal_error_signal will die with the right signal.  */
    893983          !handling_fatal_signal)
    894         die (2);
     984        die (child_failed);
    895985
    896986      /* Only block for one child.  */
     
    907997free_child (struct child *child)
    908998{
     999  output_close (&child->output);
     1000
    9091001  if (!jobserver_tokens)
    910     fatal (NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
    911            child, child->file->name);
     1002    ONS (fatal, NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
     1003         child, child->file->name);
    9121004
    9131005  /* If we're using the jobserver and this child is not the only outstanding
    9141006     job, put a token back into the pipe for it.  */
    9151007
    916   if (job_fds[1] >= 0 && jobserver_tokens > 1)
    917     {
    918       char token = '+';
    919       int r;
    920 
    921       /* Write a job token back to the pipe.  */
    922 
    923       EINTRLOOP (r, write (job_fds[1], &token, 1));
    924       if (r != 1)
    925         pfatal_with_name (_("write jobserver"));
    926 
     1008  if (jobserver_enabled () && jobserver_tokens > 1)
     1009    {
     1010      jobserver_release (1);
    9271011      DB (DB_JOBS, (_("Released token for child %p (%s).\n"),
    9281012                    child, child->file->name));
     
    9381022      register unsigned int i;
    9391023      for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
    940         free (child->command_lines[i]);
     1024        free (child->command_lines[i]);
    9411025      free (child->command_lines);
    9421026    }
     
    9461030      register char **ep = child->environment;
    9471031      while (*ep != 0)
    948         free (*ep++);
     1032        free (*ep++);
    9491033      free (child->environment);
    9501034    }
     
    9801064#endif
    9811065
    982 #ifdef MAKE_JOBSERVER
    983 RETSIGTYPE
    984 job_noop (int sig UNUSED)
    985 {
    986 }
    987 /* Set the child handler action flags to FLAGS.  */
    988 static void
    989 set_child_handler_action_flags (int set_handler, int set_alarm)
    990 {
    991   struct sigaction sa;
    992 
    993 #ifdef __EMX__
    994   /* The child handler must be turned off here.  */
    995   signal (SIGCHLD, SIG_DFL);
    996 #endif
    997 
    998   memset (&sa, '\0', sizeof sa);
    999   sa.sa_handler = child_handler;
    1000   sa.sa_flags = set_handler ? 0 : SA_RESTART;
    1001 #if defined SIGCHLD
    1002   sigaction (SIGCHLD, &sa, NULL);
    1003 #endif
    1004 #if defined SIGCLD && SIGCLD != SIGCHLD
    1005   sigaction (SIGCLD, &sa, NULL);
    1006 #endif
    1007 #if defined SIGALRM
    1008   if (set_alarm)
    1009     {
    1010       /* If we're about to enter the read(), set an alarm to wake up in a
    1011          second so we can check if the load has dropped and we can start more
    1012          work.  On the way out, turn off the alarm and set SIG_DFL.  */
    1013       alarm (set_handler ? 1 : 0);
    1014       sa.sa_handler = set_handler ? job_noop : SIG_DFL;
    1015       sa.sa_flags = 0;
    1016       sigaction (SIGALRM, &sa, NULL);
    1017     }
    1018 #endif
    1019 }
    1020 #endif
    1021 
    10221066
    10231067/* Start a job to run the commands specified in CHILD.
     
    10251069
    10261070   NOTE: On return fatal signals are blocked!  The caller is responsible
    1027    for calling `unblock_sigs', once the new child is safely on the chain so
     1071   for calling 'unblock_sigs', once the new child is safely on the chain so
    10281072   it can be cleaned up in the event of a fatal signal.  */
    10291073
     
    10311075start_job_command (struct child *child)
    10321076{
    1033 #if !defined(_AMIGA) && !defined(WINDOWS32)
    1034   static int bad_stdin = -1;
    1035 #endif
     1077  int flags;
    10361078  char *p;
    1037   /* Must be volatile to silence bogus GCC warning about longjmp/vfork.  */
    1038   volatile int flags;
    10391079#ifdef VMS
    10401080  char *argv;
     
    10501090     the flags specified globally for this target.  */
    10511091  flags = (child->file->command_flags
    1052            | child->file->cmds->lines_flags[child->command_line - 1]);
     1092           | child->file->cmds->lines_flags[child->command_line - 1]);
    10531093
    10541094  p = child->command_ptr;
     
    10581098    {
    10591099      if (*p == '@')
    1060         flags |= COMMANDS_SILENT;
     1100        flags |= COMMANDS_SILENT;
    10611101      else if (*p == '+')
    1062         flags |= COMMANDS_RECURSE;
     1102        flags |= COMMANDS_RECURSE;
    10631103      else if (*p == '-')
    1064         child->noerror = 1;
    1065       else if (!isblank ((unsigned char)*p))
    1066         break;
     1104        child->noerror = 1;
     1105      /* Don't skip newlines.  */
     1106      else if (!ISBLANK (*p))
     1107        break;
    10671108      ++p;
    10681109    }
     1110
     1111  child->recursive = ((flags & COMMANDS_RECURSE) != 0);
    10691112
    10701113  /* Update the file's command flags with any new ones we found.  We only
     
    10741117     order to really fix this, we'll have to keep a lines_flags for every
    10751118     actual line, after expansion.  */
    1076   child->file->cmds->lines_flags[child->command_line - 1]
    1077     |= flags & COMMANDS_RECURSE;
     1119  child->file->cmds->lines_flags[child->command_line - 1] |= flags & COMMANDS_RECURSE;
     1120
     1121  /* POSIX requires that a recipe prefix after a backslash-newline should
     1122     be ignored.  Remove it now so the output is correct.  */
     1123  {
     1124    char prefix = child->file->cmds->recipe_prefix;
     1125    char *p1, *p2;
     1126    p1 = p2 = p;
     1127    while (*p1 != '\0')
     1128      {
     1129        *(p2++) = *p1;
     1130        if (p1[0] == '\n' && p1[1] == prefix)
     1131          ++p1;
     1132        ++p1;
     1133      }
     1134    *p2 = *p1;
     1135  }
    10781136
    10791137  /* Figure out an argument list from this command line.  */
    1080 
    10811138  {
    10821139    char *end = 0;
    10831140#ifdef VMS
     1141    /* Skip any leading whitespace */
     1142    while (*p)
     1143      {
     1144        if (!ISSPACE (*p))
     1145          {
     1146            if (*p != '\\')
     1147              break;
     1148            if ((p[1] != '\n') && (p[1] != 'n') && (p[1] != 't'))
     1149              break;
     1150          }
     1151        p++;
     1152      }
     1153
    10841154    argv = p;
     1155    /* Although construct_command_argv contains some code for VMS, it was/is
     1156       not called/used.  Please note, for VMS argv is a string (not an array
     1157       of strings) which contains the complete command line, which for
     1158       multi-line variables still includes the newlines.  So detect newlines
     1159       and set 'end' (which is used for child->command_ptr) instead of
     1160       (re-)writing construct_command_argv */
     1161    if (!one_shell)
     1162      {
     1163        char *s = p;
     1164        int instring = 0;
     1165        while (*s)
     1166          {
     1167            if (*s == '"')
     1168              instring = !instring;
     1169            else if (*s == '\\' && !instring && *(s+1) != 0)
     1170              s++;
     1171            else if (*s == '\n' && !instring)
     1172              {
     1173                end = s;
     1174                break;
     1175              }
     1176            ++s;
     1177          }
     1178      }
    10851179#else
    10861180    argv = construct_command_argv (p, &end, child->file,
    1087                                    child->file->cmds->lines_flags[child->command_line - 1],
    1088                                    &child->sh_batch_file);
     1181                                   child->file->cmds->lines_flags[child->command_line - 1],
     1182                                   &child->sh_batch_file);
    10891183#endif
    10901184    if (end == NULL)
     
    10921186    else
    10931187      {
    1094         *end++ = '\0';
    1095         child->command_ptr = end;
     1188        *end++ = '\0';
     1189        child->command_ptr = end;
    10961190      }
    10971191  }
    10981192
    1099   /* If -q was given, say that updating `failed' if there was any text on the
    1100      command line, or `succeeded' otherwise.  The exit status of 1 tells the
    1101      user that -q is saying `something to do'; the exit status for a random
     1193  /* If -q was given, say that updating 'failed' if there was any text on the
     1194     command line, or 'succeeded' otherwise.  The exit status of 1 tells the
     1195     user that -q is saying 'something to do'; the exit status for a random
    11021196     error is 2.  */
    11031197  if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
     
    11071201      free (argv);
    11081202#endif
    1109       child->file->update_status = 1;
    1110       notice_finished_file (child->file);
    1111       return;
     1203#ifdef VMS
     1204      /* On VMS, argv[0] can be a null string here */
     1205      if (argv[0] != 0)
     1206        {
     1207#endif
     1208          child->file->update_status = us_question;
     1209          notice_finished_file (child->file);
     1210          return;
     1211#ifdef VMS
     1212        }
     1213#endif
    11121214    }
    11131215
     
    11151217    {
    11161218      /* Go on to the next command.  It might be the recursive one.
    1117         We construct ARGV only to find the end of the command line.  */
     1219        We construct ARGV only to find the end of the command line.  */
    11181220#ifndef VMS
    11191221      if (argv)
     
    11341236      /* This line has no commands.  Go to the next.  */
    11351237      if (job_next_command (child))
    1136         start_job_command (child);
     1238        start_job_command (child);
    11371239      else
    1138         {
    1139           /* No more commands.  Make sure we're "running"; we might not be if
     1240        {
     1241          /* No more commands.  Make sure we're "running"; we might not be if
    11401242             (e.g.) all commands were skipped due to -n.  */
    11411243          set_command_state (child->file, cs_running);
    1142           child->file->update_status = 0;
    1143           notice_finished_file (child->file);
    1144         }
     1244          child->file->update_status = us_success;
     1245          notice_finished_file (child->file);
     1246        }
     1247
     1248      OUTPUT_UNSET();
    11451249      return;
    11461250    }
    11471251
    1148   /* Print out the command.  If silent, we call `message' with null so it
    1149      can log the working directory before the command's own error messages
    1150      appear.  */
    1151 
    1152   message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
    1153            ? "%s" : (char *) 0, p);
     1252  /* Are we going to synchronize this command's output?  Do so if either we're
     1253     in SYNC_RECURSE mode or this command is not recursive.  We'll also check
     1254     output_sync separately below in case it changes due to error.  */
     1255  child->output.syncout = output_sync && (output_sync == OUTPUT_SYNC_RECURSE
     1256                                          || !(flags & COMMANDS_RECURSE));
     1257
     1258  OUTPUT_SET (&child->output);
     1259
     1260#ifndef NO_OUTPUT_SYNC
     1261  if (! child->output.syncout)
     1262    /* We don't want to sync this command: to avoid misordered
     1263       output ensure any already-synced content is written.  */
     1264    output_dump (&child->output);
     1265#endif
     1266
     1267  /* Print the command if appropriate.  */
     1268  if (just_print_flag || trace_flag
     1269      || (!(flags & COMMANDS_SILENT) && !silent_flag))
     1270    OS (message, 0, "%s", p);
    11541271
    11551272  /* Tell update_goal_chain that a command has been started on behalf of
     
    11711288  if (
    11721289#if defined __MSDOS__ || defined (__EMX__)
    1173       unixy_shell       /* the test is complicated and we already did it */
     1290      unixy_shell       /* the test is complicated and we already did it */
    11741291#else
    1175       (argv[0] && is_bourne_compatible_shell(argv[0]))
     1292      (argv[0] && is_bourne_compatible_shell (argv[0]))
    11761293#endif
    11771294      && (argv[1] && argv[1][0] == '-'
    1178         &&
    1179             ((argv[1][1] == 'c' && argv[1][2] == '\0')
    1180           ||
    1181              (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
     1295        &&
     1296            ((argv[1][1] == 'c' && argv[1][2] == '\0')
     1297          ||
     1298             (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
    11821299      && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
    11831300      && argv[3] == NULL)
     
    12001317    }
    12011318
     1319  /* We're sure we're going to invoke a command: set up the output.  */
     1320  output_start ();
     1321
    12021322  /* Flush the output streams so they won't have things written twice.  */
    12031323
     
    12051325  fflush (stderr);
    12061326
    1207 #ifndef VMS
    1208 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
    1209 
    1210   /* Set up a bad standard input that reads from a broken pipe.  */
    1211 
    1212   if (bad_stdin == -1)
    1213     {
    1214       /* Make a file descriptor that is the read end of a broken pipe.
    1215          This will be used for some children's standard inputs.  */
    1216       int pd[2];
    1217       if (pipe (pd) == 0)
    1218         {
    1219           /* Close the write side.  */
    1220           (void) close (pd[1]);
    1221           /* Save the read side.  */
    1222           bad_stdin = pd[0];
    1223 
    1224           /* Set the descriptor to close on exec, so it does not litter any
    1225              child's descriptor table.  When it is dup2'd onto descriptor 0,
    1226              that descriptor will not close on exec.  */
    1227           CLOSE_ON_EXEC (bad_stdin);
    1228         }
    1229     }
    1230 
    1231 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
    1232 
    1233   /* Decide whether to give this child the `good' standard input
    1234      (one that points to the terminal or whatever), or the `bad' one
     1327  /* Decide whether to give this child the 'good' standard input
     1328     (one that points to the terminal or whatever), or the 'bad' one
    12351329     that points to the read side of a broken pipe.  */
    12361330
     
    12381332  if (child->good_stdin)
    12391333    good_stdin_used = 1;
    1240 
    1241 #endif /* !VMS */
    12421334
    12431335  child->deleted = 0;
     
    12571349      int is_remote, id, used_stdin;
    12581350      if (start_remote_job (argv, child->environment,
    1259                             child->good_stdin ? 0 : bad_stdin,
    1260                             &is_remote, &id, &used_stdin))
     1351                            child->good_stdin ? 0 : get_bad_stdin (),
     1352                            &is_remote, &id, &used_stdin))
    12611353        /* Don't give up; remote execution may fail for various reasons.  If
    12621354           so, simply run the job locally.  */
    1263         goto run_local;
     1355        goto run_local;
    12641356      else
    1265         {
    1266           if (child->good_stdin && !used_stdin)
    1267             {
    1268               child->good_stdin = 0;
    1269               good_stdin_used = 0;
    1270             }
    1271           child->remote = is_remote;
    1272           child->pid = id;
    1273         }
     1357        {
     1358          if (child->good_stdin && !used_stdin)
     1359            {
     1360              child->good_stdin = 0;
     1361              good_stdin_used = 0;
     1362            }
     1363          child->remote = is_remote;
     1364          child->pid = id;
     1365        }
    12741366    }
    12751367  else
     
    12861378
    12871379#ifdef VMS
    1288       if (!child_execute_job (argv, child)) {
    1289         /* Fork failed!  */
    1290         perror_with_name ("vfork", "");
    1291         goto error;
    1292       }
     1380      if (!child_execute_job (child, argv))
     1381        {
     1382          /* Fork failed!  */
     1383          perror_with_name ("fork", "");
     1384          goto error;
     1385        }
    12931386
    12941387#else
     
    12961389      parent_environ = environ;
    12971390
    1298 # ifdef __EMX__
    1299       /* If we aren't running a recursive command and we have a jobserver
    1300          pipe, close it before exec'ing.  */
    1301       if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
    1302         {
    1303           CLOSE_ON_EXEC (job_fds[0]);
    1304           CLOSE_ON_EXEC (job_fds[1]);
    1305         }
    1306       if (job_rfd >= 0)
    1307         CLOSE_ON_EXEC (job_rfd);
    1308 
    1309       /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
    1310       child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
    1311                                       argv, child->environment);
     1391      jobserver_pre_child (flags & COMMANDS_RECURSE);
     1392
     1393      child->pid = child_execute_job (&child->output, child->good_stdin, argv, child->environment);
     1394
     1395      environ = parent_environ; /* Restore value child may have clobbered.  */
     1396      jobserver_post_child (flags & COMMANDS_RECURSE);
     1397
    13121398      if (child->pid < 0)
    1313         {
    1314           /* spawn failed!  */
    1315           unblock_sigs ();
    1316           perror_with_name ("spawn", "");
    1317           goto error;
    1318         }
    1319 
    1320       /* undo CLOSE_ON_EXEC() after the child process has been started */
    1321       if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
    1322         {
    1323           fcntl (job_fds[0], F_SETFD, 0);
    1324           fcntl (job_fds[1], F_SETFD, 0);
    1325         }
    1326       if (job_rfd >= 0)
    1327         fcntl (job_rfd, F_SETFD, 0);
    1328 
    1329 #else  /* !__EMX__ */
    1330 
    1331       child->pid = vfork ();
    1332       environ = parent_environ; /* Restore value child may have clobbered.  */
    1333       if (child->pid == 0)
    1334         {
    1335           /* We are the child side.  */
    1336           unblock_sigs ();
    1337 
    1338           /* If we aren't running a recursive command and we have a jobserver
    1339              pipe, close it before exec'ing.  */
    1340           if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
    1341             {
    1342               close (job_fds[0]);
    1343               close (job_fds[1]);
    1344             }
    1345           if (job_rfd >= 0)
    1346             close (job_rfd);
    1347 
    1348 #ifdef SET_STACK_SIZE
    1349           /* Reset limits, if necessary.  */
    1350           if (stack_limit.rlim_cur)
    1351             setrlimit (RLIMIT_STACK, &stack_limit);
    1352 #endif
    1353 
    1354           child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
    1355                              argv, child->environment);
    1356         }
    1357       else if (child->pid < 0)
    1358         {
    1359           /* Fork failed!  */
    1360           unblock_sigs ();
    1361           perror_with_name ("vfork", "");
    1362           goto error;
    1363         }
    1364 # endif  /* !__EMX__ */
     1399        {
     1400          /* Fork failed!  */
     1401          unblock_sigs ();
     1402          perror_with_name ("fork", "");
     1403          goto error;
     1404        }
    13651405#endif /* !VMS */
    13661406    }
    13671407
    1368 #else   /* __MSDOS__ or Amiga or WINDOWS32 */
     1408#else   /* __MSDOS__ or Amiga or WINDOWS32 */
    13691409#ifdef __MSDOS__
    13701410  {
     
    13741414    dos_status = 0;
    13751415
    1376     /* We call `system' to do the job of the SHELL, since stock DOS
    1377        shell is too dumb.  Our `system' knows how to handle long
     1416    /* We call 'system' to do the job of the SHELL, since stock DOS
     1417       shell is too dumb.  Our 'system' knows how to handle long
    13781418       command lines even if pipes/redirection is needed; it will only
    13791419       call COMMAND.COM when its internal commands are used.  */
    13801420    if (execute_by_shell)
    13811421      {
    1382         char *cmdline = argv[0];
    1383         /* We don't have a way to pass environment to `system',
    1384            so we need to save and restore ours, sigh...  */
    1385         char **parent_environ = environ;
    1386 
    1387         environ = child->environment;
    1388 
    1389         /* If we have a *real* shell, tell `system' to call
    1390            it to do everything for us.  */
    1391         if (unixy_shell)
    1392           {
    1393             /* A *real* shell on MSDOS may not support long
    1394                command lines the DJGPP way, so we must use `system'.  */
    1395             cmdline = argv[2];  /* get past "shell -c" */
    1396           }
    1397 
    1398         dos_command_running = 1;
    1399         proc_return = system (cmdline);
    1400         environ = parent_environ;
    1401         execute_by_shell = 0;   /* for the next time */
     1422        char *cmdline = argv[0];
     1423        /* We don't have a way to pass environment to 'system',
     1424           so we need to save and restore ours, sigh...  */
     1425        char **parent_environ = environ;
     1426
     1427        environ = child->environment;
     1428
     1429        /* If we have a *real* shell, tell 'system' to call
     1430           it to do everything for us.  */
     1431        if (unixy_shell)
     1432          {
     1433            /* A *real* shell on MSDOS may not support long
     1434               command lines the DJGPP way, so we must use 'system'.  */
     1435            cmdline = argv[2];  /* get past "shell -c" */
     1436          }
     1437
     1438        dos_command_running = 1;
     1439        proc_return = system (cmdline);
     1440        environ = parent_environ;
     1441        execute_by_shell = 0;   /* for the next time */
    14021442      }
    14031443    else
    14041444      {
    1405         dos_command_running = 1;
    1406         proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
     1445        dos_command_running = 1;
     1446        proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
    14071447      }
    14081448
     
    14331473     DeleteFile (amiga_bname);        /* Ignore errors.  */
    14341474  }
    1435 #endif  /* Amiga */
     1475#endif  /* Amiga */
    14361476#ifdef WINDOWS32
    14371477  {
    14381478      HANDLE hPID;
    14391479      char* arg0;
     1480      int outfd = FD_STDOUT;
     1481      int errfd = FD_STDERR;
    14401482
    14411483      /* make UNC paths safe for CreateProcess -- backslash format */
     
    14471489
    14481490      /* make sure CreateProcess() has Path it needs */
    1449       sync_Path_environment();
    1450 
    1451       hPID = process_easy(argv, child->environment);
     1491      sync_Path_environment ();
     1492
     1493#ifndef NO_OUTPUT_SYNC
     1494      /* Divert child output if output_sync in use.  */
     1495      if (child->output.syncout)
     1496        {
     1497          if (child->output.out >= 0)
     1498            outfd = child->output.out;
     1499          if (child->output.err >= 0)
     1500            errfd = child->output.err;
     1501        }
     1502#else
     1503      outfd = errfd = -1;
     1504#endif
     1505      hPID = process_easy (argv, child->environment, outfd, errfd);
    14521506
    14531507      if (hPID != INVALID_HANDLE_VALUE)
    14541508        child->pid = (pid_t) hPID;
    1455       else {
    1456         int i;
    1457         unblock_sigs();
    1458         fprintf(stderr,
    1459                 _("process_easy() failed to launch process (e=%ld)\n"),
    1460                 process_last_err(hPID));
    1461         for (i = 0; argv[i]; i++)
    1462           fprintf(stderr, "%s ", argv[i]);
    1463         fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
    1464         goto error;
    1465       }
     1509      else
     1510        {
     1511          int i;
     1512          unblock_sigs ();
     1513          fprintf (stderr,
     1514                   _("process_easy() failed to launch process (e=%ld)\n"),
     1515                   process_last_err (hPID));
     1516          for (i = 0; argv[i]; i++)
     1517            fprintf (stderr, "%s ", argv[i]);
     1518          fprintf (stderr, _("\nCounted %d args in failed launch\n"), i);
     1519          goto error;
     1520        }
    14661521  }
    14671522#endif /* WINDOWS32 */
    1468 #endif  /* __MSDOS__ or Amiga or WINDOWS32 */
     1523#endif  /* __MSDOS__ or Amiga or WINDOWS32 */
    14691524
    14701525  /* Bump the number of jobs started in this second.  */
     
    14821537#endif
    14831538
     1539  OUTPUT_UNSET();
    14841540  return;
    14851541
    14861542 error:
    1487   child->file->update_status = 2;
     1543  child->file->update_status = us_failed;
    14881544  notice_finished_file (child->file);
    1489   return;
     1545  OUTPUT_UNSET();
    14901546}
    14911547
    14921548/* Try to start a child running.
    14931549   Returns nonzero if the child was started (and maybe finished), or zero if
    1494    the load was too high and the child was put on the `waiting_jobs' chain.  */
     1550   the load was too high and the child was put on the 'waiting_jobs' chain.  */
    14951551
    14961552static int
     
    15101566      && ((job_slots_used > 0 && load_too_high ())
    15111567#ifdef WINDOWS32
    1512           || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
    1513 #endif
    1514           ))
     1568          || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
     1569#endif
     1570          ))
    15151571    {
    15161572      /* Put this child on the chain of children waiting for the load average
     
    15401596    case cs_not_started:
    15411597      /* All the command lines turned out to be empty.  */
    1542       f->update_status = 0;
     1598      f->update_status = us_success;
    15431599      /* FALLTHROUGH */
    15441600
     
    15561612}
    15571613
    1558 /* Create a `struct child' for FILE and start its commands running.  */
     1614/* Create a 'struct child' for FILE and start its commands running.  */
    15591615
    15601616void
     
    15761632  chop_commands (cmds);
    15771633
     1634  /* Start the command sequence, record it in a new
     1635     'struct child', and add that to the chain.  */
     1636
     1637  c = xcalloc (sizeof (struct child));
     1638  output_init (&c->output);
     1639
     1640  c->file = file;
     1641  c->sh_batch_file = NULL;
     1642
     1643  /* Cache dontcare flag because file->dontcare can be changed once we
     1644     return. Check dontcare inheritance mechanism for details.  */
     1645  c->dontcare = file->dontcare;
     1646
     1647  /* Start saving output in case the expansion uses $(info ...) etc.  */
     1648  OUTPUT_SET (&c->output);
     1649
    15781650  /* Expand the command lines and store the results in LINES.  */
    15791651  lines = xmalloc (cmds->ncommand_lines * sizeof (char *));
     
    15811653    {
    15821654      /* Collapse backslash-newline combinations that are inside variable
    1583         or function references.  These are left alone by the parser so
    1584         that they will appear in the echoing of commands (where they look
    1585         nice); and collapsed by construct_command_argv when it tokenizes.
    1586         But letting them survive inside function invocations loses because
    1587         we don't want the functions to see them as part of the text.  */
     1655        or function references.  These are left alone by the parser so
     1656        that they will appear in the echoing of commands (where they look
     1657        nice); and collapsed by construct_command_argv when it tokenizes.
     1658        But letting them survive inside function invocations loses because
     1659        we don't want the functions to see them as part of the text.  */
    15881660
    15891661      char *in, *out, *ref;
    15901662
    15911663      /* IN points to where in the line we are scanning.
    1592         OUT points to where in the line we are writing.
    1593         When we collapse a backslash-newline combination,
    1594         IN gets ahead of OUT.  */
     1664        OUT points to where in the line we are writing.
     1665        When we collapse a backslash-newline combination,
     1666        IN gets ahead of OUT.  */
    15951667
    15961668      in = out = cmds->command_lines[i];
    15971669      while ((ref = strchr (in, '$')) != 0)
    1598         {
    1599           ++ref;                /* Move past the $.  */
    1600 
    1601           if (out != in)
    1602             /* Copy the text between the end of the last chunk
    1603                we processed (where IN points) and the new chunk
    1604                we are about to process (where REF points).  */
    1605             memmove (out, in, ref - in);
    1606 
    1607           /* Move both pointers past the boring stuff.  */
    1608           out += ref - in;
    1609           in = ref;
    1610 
    1611           if (*ref == '(' || *ref == '{')
    1612             {
    1613               char openparen = *ref;
    1614               char closeparen = openparen == '(' ? ')' : '}';
    1615               int count;
    1616               char *p;
    1617 
    1618               *out++ = *in++;   /* Copy OPENPAREN.  */
    1619               /* IN now points past the opening paren or brace.
    1620                  Count parens or braces until it is matched.  */
    1621               count = 0;
    1622               while (*in != '\0')
    1623                 {
    1624                   if (*in == closeparen && --count < 0)
    1625                     break;
    1626                   else if (*in == '\\' && in[1] == '\n')
    1627                     {
    1628                       /* We have found a backslash-newline inside a
    1629                          variable or function reference.  Eat it and
    1630                          any following whitespace.  */
    1631 
    1632                       int quoted = 0;
    1633                       for (p = in - 1; p > ref && *p == '\\'; --p)
    1634                         quoted = !quoted;
    1635 
    1636                       if (quoted)
    1637                         /* There were two or more backslashes, so this is
    1638                            not really a continuation line.  We don't collapse
    1639                            the quoting backslashes here as is done in
    1640                            collapse_continuations, because the line will
    1641                            be collapsed again after expansion.  */
    1642                         *out++ = *in++;
    1643                       else
    1644                         {
    1645                           /* Skip the backslash, newline and
    1646                              any following whitespace.  */
    1647                           in = next_token (in + 2);
    1648 
    1649                           /* Discard any preceding whitespace that has
    1650                              already been written to the output.  */
    1651                           while (out > ref
    1652                                  && isblank ((unsigned char)out[-1]))
    1653                             --out;
    1654 
    1655                           /* Replace it all with a single space.  */
    1656                           *out++ = ' ';
    1657                         }
    1658                     }
    1659                   else
    1660                     {
    1661                       if (*in == openparen)
    1662                         ++count;
    1663 
    1664                       *out++ = *in++;
    1665                     }
    1666                 }
    1667             }
    1668         }
     1670        {
     1671          ++ref;                /* Move past the $.  */
     1672
     1673          if (out != in)
     1674            /* Copy the text between the end of the last chunk
     1675               we processed (where IN points) and the new chunk
     1676               we are about to process (where REF points).  */
     1677            memmove (out, in, ref - in);
     1678
     1679          /* Move both pointers past the boring stuff.  */
     1680          out += ref - in;
     1681          in = ref;
     1682
     1683          if (*ref == '(' || *ref == '{')
     1684            {
     1685              char openparen = *ref;
     1686              char closeparen = openparen == '(' ? ')' : '}';
     1687              char *outref;
     1688              int count;
     1689              char *p;
     1690
     1691              *out++ = *in++;   /* Copy OPENPAREN.  */
     1692              outref = out;
     1693              /* IN now points past the opening paren or brace.
     1694                 Count parens or braces until it is matched.  */
     1695              count = 0;
     1696              while (*in != '\0')
     1697                {
     1698                  if (*in == closeparen && --count < 0)
     1699                    break;
     1700                  else if (*in == '\\' && in[1] == '\n')
     1701                    {
     1702                      /* We have found a backslash-newline inside a
     1703                         variable or function reference.  Eat it and
     1704                         any following whitespace.  */
     1705
     1706                      int quoted = 0;
     1707                      for (p = in - 1; p > ref && *p == '\\'; --p)
     1708                        quoted = !quoted;
     1709
     1710                      if (quoted)
     1711                        /* There were two or more backslashes, so this is
     1712                           not really a continuation line.  We don't collapse
     1713                           the quoting backslashes here as is done in
     1714                           collapse_continuations, because the line will
     1715                           be collapsed again after expansion.  */
     1716                        *out++ = *in++;
     1717                      else
     1718                        {
     1719                          /* Skip the backslash, newline, and whitespace.  */
     1720                          in += 2;
     1721                          NEXT_TOKEN (in);
     1722
     1723                          /* Discard any preceding whitespace that has
     1724                             already been written to the output.  */
     1725                          while (out > outref && ISBLANK (out[-1]))
     1726                            --out;
     1727
     1728                          /* Replace it all with a single space.  */
     1729                          *out++ = ' ';
     1730                        }
     1731                    }
     1732                  else
     1733                    {
     1734                      if (*in == openparen)
     1735                        ++count;
     1736
     1737                      *out++ = *in++;
     1738                    }
     1739                }
     1740            }
     1741        }
    16691742
    16701743      /* There are no more references in this line to worry about.
    1671         Copy the remaining uninteresting text to the output.  */
     1744        Copy the remaining uninteresting text to the output.  */
    16721745      if (out != in)
    1673         memmove (out, in, strlen (in) + 1);
     1746        memmove (out, in, strlen (in) + 1);
    16741747
    16751748      /* Finally, expand the line.  */
     1749      cmds->fileinfo.offset = i;
    16761750      lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
    1677                                                      file);
    1678     }
    1679 
    1680   /* Start the command sequence, record it in a new
    1681      `struct child', and add that to the chain.  */
    1682 
    1683   c = xcalloc (sizeof (struct child));
    1684   c->file = file;
     1751                                                     file);
     1752    }
     1753
     1754  cmds->fileinfo.offset = 0;
    16851755  c->command_lines = lines;
    1686   c->sh_batch_file = NULL;
    1687 
    1688   /* Cache dontcare flag because file->dontcare can be changed once we
    1689      return. Check dontcare inheritance mechanism for details.  */
    1690   c->dontcare = file->dontcare;
    16911756
    16921757  /* Fetch the first command line to be run.  */
     
    17131778     this is where the old parallel job code waits, so...  */
    17141779
    1715   else if (job_fds[0] >= 0)
     1780  else if (jobserver_enabled ())
    17161781    while (1)
    17171782      {
    1718         char token;
    1719         int got_token;
    1720         int saved_errno;
     1783        int got_token;
    17211784
    17221785        DB (DB_JOBS, ("Need a job token; we %shave children\n",
     
    17271790          break;
    17281791
    1729         /* Read a token.  As long as there's no token available we'll block.
    1730            We enable interruptible system calls before the read(2) so that if
    1731            we get a SIGCHLD while we're waiting, we'll return with EINTR and
    1732            we can process the death(s) and return tokens to the free pool.
    1733 
    1734            Once we return from the read, we immediately reinstate restartable
    1735            system calls.  This allows us to not worry about checking for
    1736            EINTR on all the other system calls in the program.
    1737 
    1738            There is one other twist: there is a span between the time
    1739            reap_children() does its last check for dead children and the time
    1740            the read(2) call is entered, below, where if a child dies we won't
    1741            notice.  This is extremely serious as it could cause us to
    1742            deadlock, given the right set of events.
    1743 
    1744            To avoid this, we do the following: before we reap_children(), we
    1745            dup(2) the read FD on the jobserver pipe.  The read(2) call below
    1746            uses that new FD.  In the signal handler, we close that FD.  That
    1747            way, if a child dies during the section mentioned above, the
    1748            read(2) will be invoked with an invalid FD and will return
    1749            immediately with EBADF.  */
    1750 
    1751         /* Make sure we have a dup'd FD.  */
    1752         if (job_rfd < 0)
    1753           {
    1754             DB (DB_JOBS, ("Duplicate the job FD\n"));
    1755             job_rfd = dup (job_fds[0]);
    1756           }
     1792        /* Prepare for jobserver token acquisition.  */
     1793        jobserver_pre_acquire ();
    17571794
    17581795        /* Reap anything that's currently waiting.  */
     
    17601797
    17611798        /* Kick off any jobs we have waiting for an opportunity that
    1762            can run now (ie waiting for load). */
     1799           can run now (i.e., waiting for load). */
    17631800        start_waiting_jobs ();
    17641801
    1765         /* If our "free" slot has become available, use it; we don't need an
    1766            actual token.  */
     1802        /* If our "free" slot is available, use it; we don't need a token.  */
    17671803        if (!jobserver_tokens)
    17681804          break;
     
    17711807           waiting for a token. */
    17721808        if (!children)
    1773           fatal (NILF, "INTERNAL: no children as we go to sleep on read\n");
    1774 
    1775         /* Set interruptible system calls, and read() for a job token.  */
    1776         set_child_handler_action_flags (1, waiting_jobs != NULL);
    1777         got_token = read (job_rfd, &token, 1);
    1778         saved_errno = errno;
    1779         set_child_handler_action_flags (0, waiting_jobs != NULL);
     1809          O (fatal, NILF, "INTERNAL: no children as we go to sleep on read\n");
     1810
     1811        /* Get a token.  */
     1812        got_token = jobserver_acquire (waiting_jobs != NULL);
    17801813
    17811814        /* If we got one, we're done here.  */
    1782         if (got_token == 1)
     1815        if (got_token == 1)
    17831816          {
    17841817            DB (DB_JOBS, (_("Obtained token for child %p (%s).\n"),
     
    17861819            break;
    17871820          }
    1788 
    1789         /* If the error _wasn't_ expected (EINTR or EBADF), punt.  Otherwise,
    1790            go back and reap_children(), and try again.  */
    1791         errno = saved_errno;
    1792         if (errno != EINTR && errno != EBADF)
    1793           pfatal_with_name (_("read jobs pipe"));
    1794         if (errno == EBADF)
    1795           DB (DB_JOBS, ("Read returned EBADF.\n"));
    17961821      }
    17971822#endif
    17981823
    17991824  ++jobserver_tokens;
     1825
     1826  /* Trace the build.
     1827     Use message here so that changes to working directories are logged.  */
     1828  if (trace_flag)
     1829    {
     1830      char *newer = allocated_variable_expand_for_file ("$?", c->file);
     1831      const char *nm;
     1832
     1833      if (! cmds->fileinfo.filenm)
     1834        nm = _("<builtin>");
     1835      else
     1836        {
     1837          char *n = alloca (strlen (cmds->fileinfo.filenm) + 1 + 11 + 1);
     1838          sprintf (n, "%s:%lu", cmds->fileinfo.filenm, cmds->fileinfo.lineno);
     1839          nm = n;
     1840        }
     1841
     1842      if (newer[0] == '\0')
     1843        OSS (message, 0,
     1844             _("%s: target '%s' does not exist"), nm, c->file->name);
     1845      else
     1846        OSSS (message, 0,
     1847              _("%s: update target '%s' due to: %s"), nm, c->file->name, newer);
     1848
     1849      free (newer);
     1850    }
    18001851
    18011852  /* The job is now primed.  Start it running.
    18021853     (This will notice if there is in fact no recipe.)  */
    1803   if (cmds->fileinfo.filenm)
    1804     DB (DB_BASIC, (_("Invoking recipe from %s:%lu to update target `%s'.\n"),
    1805                    cmds->fileinfo.filenm, cmds->fileinfo.lineno,
    1806                    c->file->name));
    1807   else
    1808     DB (DB_BASIC, (_("Invoking builtin recipe to update target `%s'.\n"),
    1809                    c->file->name));
    1810 
    1811 
    18121854  start_waiting_job (c);
    18131855
    18141856  if (job_slots == 1 || not_parallel)
    18151857    /* Since there is only one job slot, make things run linearly.
    1816        Wait for the child to die, setting the state to `cs_finished'.  */
     1858       Wait for the child to die, setting the state to 'cs_finished'.  */
    18171859    while (file->command_state == cs_running)
    18181860      reap_children (1, 0);
    18191861
     1862  OUTPUT_UNSET ();
    18201863  return;
    18211864}
     
    18321875      /* There are no more lines in the expansion of this line.  */
    18331876      if (child->command_line == child->file->cmds->ncommand_lines)
    1834         {
    1835           /* There are no more lines to be expanded.  */
    1836           child->command_ptr = 0;
    1837           return 0;
    1838         }
     1877        {
     1878          /* There are no more lines to be expanded.  */
     1879          child->command_ptr = 0;
     1880          child->file->cmds->fileinfo.offset = 0;
     1881          return 0;
     1882        }
    18391883      else
    1840         /* Get the next line to run.  */
    1841         child->command_ptr = child->command_lines[child->command_line++];
    1842     }
     1884        /* Get the next line to run.  */
     1885        child->command_ptr = child->command_lines[child->command_line++];
     1886    }
     1887
     1888  child->file->cmds->fileinfo.offset = child->command_line - 1;
    18431889  return 1;
    18441890}
     
    19111957      /* Complain only once for the same error.  */
    19121958      if (lossage == -1 || errno != lossage)
    1913         {
    1914           if (errno == 0)
    1915             /* An errno value of zero means getloadavg is just unsupported.  */
    1916             error (NILF,
    1917                    _("cannot enforce load limits on this operating system"));
    1918           else
    1919             perror_with_name (_("cannot enforce load limit: "), "getloadavg");
    1920         }
     1959        {
     1960          if (errno == 0)
     1961            /* An errno value of zero means getloadavg is just unsupported.  */
     1962            O (error, NILF,
     1963               _("cannot enforce load limits on this operating system"));
     1964          else
     1965            perror_with_name (_("cannot enforce load limit: "), "getloadavg");
     1966        }
    19211967      lossage = errno;
    19221968      load = 0;
     
    19682014
    19692015      /* Try to start that job.  We break out of the loop as soon
    1970         as start_waiting_job puts one back on the waiting list.  */
     2016        as start_waiting_job puts one back on the waiting list.  */
    19712017    }
    19722018  while (start_waiting_job (job) && waiting_jobs != 0);
     
    19812027# if defined __EMX__
    19822028int
    1983 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
     2029child_execute_job (struct output *out, int good_stdin, char **argv, char **envp)
    19842030{
    19852031  int pid;
    1986   /* stdin_fd == 0 means: nothing to do for stdin;
    1987      stdout_fd == 1 means: nothing to do for stdout */
    1988   int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
    1989   int save_stdout = (stdout_fd != 1) ? dup (1): 1;
    1990 
    1991   /* < 0 only if dup() failed */
    1992   if (save_stdin < 0)
    1993     fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
    1994   if (save_stdout < 0)
    1995     fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
    1996 
    1997   /* Close unnecessary file handles for the child.  */
    1998   if (save_stdin != 0)
    1999     CLOSE_ON_EXEC (save_stdin);
    2000   if (save_stdout != 1)
    2001     CLOSE_ON_EXEC (save_stdout);
    2002 
    2003   /* Connect the pipes to the child process.  */
    2004   if (stdin_fd != 0)
    2005     (void) dup2 (stdin_fd, 0);
    2006   if (stdout_fd != 1)
    2007     (void) dup2 (stdout_fd, 1);
    2008 
    2009   /* stdin_fd and stdout_fd must be closed on exit because we are
    2010      still in the parent process */
    2011   if (stdin_fd != 0)
    2012     CLOSE_ON_EXEC (stdin_fd);
    2013   if (stdout_fd != 1)
    2014     CLOSE_ON_EXEC (stdout_fd);
     2032  int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
     2033  int fdout = FD_STDOUT;
     2034  int fderr = FD_STDERR;
     2035  int save_fdin = -1;
     2036  int save_fdout = -1;
     2037  int save_fderr = -1;
     2038
     2039  /* Divert child output if we want to capture output.  */
     2040  if (out && out->syncout)
     2041    {
     2042      if (out->out >= 0)
     2043        fdout = out->out;
     2044      if (out->err >= 0)
     2045        fderr = out->err;
     2046    }
     2047
     2048  /* For each FD which needs to be redirected first make a dup of the standard
     2049     FD to save and mark it close on exec so our child won't see it.  Then
     2050     dup2() the standard FD to the redirect FD, and also mark the redirect FD
     2051     as close on exec. */
     2052  if (fdin != FD_STDIN)
     2053    {
     2054      save_fdin = dup (FD_STDIN);
     2055      if (save_fdin < 0)
     2056        O (fatal, NILF, _("no more file handles: could not duplicate stdin\n"));
     2057      CLOSE_ON_EXEC (save_fdin);
     2058
     2059      dup2 (fdin, FD_STDIN);
     2060      CLOSE_ON_EXEC (fdin);
     2061    }
     2062
     2063  if (fdout != FD_STDOUT)
     2064    {
     2065      save_fdout = dup (FD_STDOUT);
     2066      if (save_fdout < 0)
     2067        O (fatal, NILF,
     2068           _("no more file handles: could not duplicate stdout\n"));
     2069      CLOSE_ON_EXEC (save_fdout);
     2070
     2071      dup2 (fdout, FD_STDOUT);
     2072      CLOSE_ON_EXEC (fdout);
     2073    }
     2074
     2075  if (fderr != FD_STDERR)
     2076    {
     2077      if (fderr != fdout)
     2078        {
     2079          save_fderr = dup (FD_STDERR);
     2080          if (save_fderr < 0)
     2081            O (fatal, NILF,
     2082               _("no more file handles: could not duplicate stderr\n"));
     2083          CLOSE_ON_EXEC (save_fderr);
     2084        }
     2085
     2086      dup2 (fderr, FD_STDERR);
     2087      CLOSE_ON_EXEC (fderr);
     2088    }
    20152089
    20162090  /* Run the command.  */
    20172091  pid = exec_command (argv, envp);
    20182092
    2019   /* Restore stdout/stdin of the parent and close temporary FDs.  */
    2020   if (stdin_fd != 0)
    2021     {
    2022       if (dup2 (save_stdin, 0) != 0)
    2023         fatal (NILF, _("Could not restore stdin\n"));
     2093  /* Restore stdout/stdin/stderr of the parent and close temporary FDs.  */
     2094  if (save_fdin >= 0)
     2095    {
     2096      if (dup2 (save_fdin, FD_STDIN) != FD_STDIN)
     2097        O (fatal, NILF, _("Could not restore stdin\n"));
    20242098      else
    2025         close (save_stdin);
    2026     }
    2027 
    2028   if (stdout_fd != 1)
    2029     {
    2030       if (dup2 (save_stdout, 1) != 1)
    2031         fatal (NILF, _("Could not restore stdout\n"));
     2099        close (save_fdin);
     2100    }
     2101
     2102  if (save_fdout >= 0)
     2103    {
     2104      if (dup2 (save_fdout, FD_STDOUT) != FD_STDOUT)
     2105        O (fatal, NILF, _("Could not restore stdout\n"));
    20322106      else
    2033         close (save_stdout);
     2107        close (save_fdout);
     2108    }
     2109
     2110  if (save_fderr >= 0)
     2111    {
     2112      if (dup2 (save_fderr, FD_STDERR) != FD_STDERR)
     2113        O (fatal, NILF, _("Could not restore stderr\n"));
     2114      else
     2115        close (save_fderr);
    20342116    }
    20352117
     
    20392121#elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
    20402122
    2041 /* UNIX:
    2042    Replace the current process with one executing the command in ARGV.
    2043    STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
    2044    the environment of the new program.  This function does not return.  */
    2045 void
    2046 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
     2123/* POSIX:
     2124   Create a child process executing the command in ARGV.
     2125   ENVP is the environment of the new program.  Returns the PID or -1.  */
     2126int
     2127child_execute_job (struct output *out, int good_stdin, char **argv, char **envp)
    20472128{
    2048   if (stdin_fd != 0)
    2049     (void) dup2 (stdin_fd, 0);
    2050   if (stdout_fd != 1)
    2051     (void) dup2 (stdout_fd, 1);
    2052   if (stdin_fd != 0)
    2053     (void) close (stdin_fd);
    2054   if (stdout_fd != 1)
    2055     (void) close (stdout_fd);
     2129  int r;
     2130  int pid;
     2131  int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
     2132  int fdout = FD_STDOUT;
     2133  int fderr = FD_STDERR;
     2134
     2135  /* Divert child output if we want to capture it.  */
     2136  if (out && out->syncout)
     2137    {
     2138      if (out->out >= 0)
     2139        fdout = out->out;
     2140      if (out->err >= 0)
     2141        fderr = out->err;
     2142    }
     2143
     2144  pid = vfork();
     2145  if (pid != 0)
     2146    return pid;
     2147
     2148  /* We are the child.  */
     2149  unblock_sigs ();
     2150
     2151#ifdef SET_STACK_SIZE
     2152  /* Reset limits, if necessary.  */
     2153  if (stack_limit.rlim_cur)
     2154    setrlimit (RLIMIT_STACK, &stack_limit);
     2155#endif
     2156
     2157  /* For any redirected FD, dup2() it to the standard FD.
     2158     They are all marked close-on-exec already.  */
     2159  if (fdin != FD_STDIN)
     2160    EINTRLOOP (r, dup2 (fdin, FD_STDIN));
     2161  if (fdout != FD_STDOUT)
     2162    EINTRLOOP (r, dup2 (fdout, FD_STDOUT));
     2163  if (fderr != FD_STDERR)
     2164    EINTRLOOP (r, dup2 (fderr, FD_STDERR));
    20562165
    20572166  /* Run the command.  */
     
    20872196  HANDLE hPID;
    20882197  HANDLE hWaitPID;
    2089   int err = 0;
    20902198  int exit_code = EXIT_FAILURE;
    20912199
    20922200  /* make sure CreateProcess() has Path it needs */
    2093   sync_Path_environment();
     2201  sync_Path_environment ();
    20942202
    20952203  /* launch command */
    2096   hPID = process_easy(argv, envp);
     2204  hPID = process_easy (argv, envp, -1, -1);
    20972205
    20982206  /* make sure launch ok */
     
    21002208    {
    21012209      int i;
    2102       fprintf(stderr,
    2103               _("process_easy() failed to launch process (e=%ld)\n"),
    2104               process_last_err(hPID));
     2210      fprintf (stderr, _("process_easy() failed to launch process (e=%ld)\n"),
     2211               process_last_err (hPID));
    21052212      for (i = 0; argv[i]; i++)
    2106           fprintf(stderr, "%s ", argv[i]);
    2107       fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
    2108       exit(EXIT_FAILURE);
     2213          fprintf (stderr, "%s ", argv[i]);
     2214      fprintf (stderr, _("\nCounted %d args in failed launch\n"), i);
     2215      exit (EXIT_FAILURE);
    21092216    }
    21102217
    21112218  /* wait and reap last child */
    2112   hWaitPID = process_wait_for_any();
     2219  hWaitPID = process_wait_for_any (1, 0);
    21132220  while (hWaitPID)
    21142221    {
    21152222      /* was an error found on this process? */
    2116       err = process_last_err(hWaitPID);
     2223      int err = process_last_err (hWaitPID);
    21172224
    21182225      /* get exit data */
    2119       exit_code = process_exit_code(hWaitPID);
     2226      exit_code = process_exit_code (hWaitPID);
    21202227
    21212228      if (err)
    2122           fprintf(stderr, "make (e=%d, rc=%d): %s",
    2123                   err, exit_code, map_windows32_error_to_string(err));
     2229          fprintf (stderr, "make (e=%d, rc=%d): %s",
     2230                   err, exit_code, map_windows32_error_to_string (err));
    21242231
    21252232      /* cleanup process */
    2126       process_cleanup(hWaitPID);
     2233      process_cleanup (hWaitPID);
    21272234
    21282235      /* expect to find only last pid, warn about other pids reaped */
     
    21302237          break;
    21312238      else
    2132         {
    2133           char *pidstr = xstrdup (pid2str ((pid_t)hWaitPID));
    2134 
    2135           fprintf(stderr,
    2136                   _("make reaped child pid %s, still waiting for pid %s\n"),
    2137                   pidstr, pid2str ((pid_t)hPID));
    2138           free (pidstr);
    2139         }
     2239        {
     2240          char *pidstr = xstrdup (pid2str ((pid_t)hWaitPID));
     2241
     2242          fprintf (stderr,
     2243                   _("make reaped child pid %s, still waiting for pid %s\n"),
     2244                   pidstr, pid2str ((pid_t)hPID));
     2245          free (pidstr);
     2246        }
    21402247    }
    21412248
    21422249  /* return child's exit code as our exit code */
    2143   exit(exit_code);
     2250  exit (exit_code);
    21442251
    21452252#else  /* !WINDOWS32 */
     
    21532260
    21542261# ifdef __EMX__
    2155 
    21562262  /* Run the program.  */
    21572263  pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
    2158 
    21592264  if (pid >= 0)
    21602265    return pid;
     
    21652270
    21662271# else
    2167 
    21682272  /* Run the program.  */
    21692273  environ = envp;
     
    21752279    {
    21762280    case ENOENT:
    2177       error (NILF, _("%s: Command not found"), argv[0]);
     2281      /* We are in the child: don't use the output buffer.
     2282         It's not right to run fprintf() here!  */
     2283      if (makelevel == 0)
     2284        fprintf (stderr, _("%s: %s: Command not found\n"), program, argv[0]);
     2285      else
     2286        fprintf (stderr, _("%s[%u]: %s: Command not found\n"),
     2287                 program, makelevel, argv[0]);
    21782288      break;
    21792289    case ENOEXEC:
    21802290      {
    2181         /* The file is not executable.  Try it as a shell script.  */
    2182         extern char *getenv ();
    2183         char *shell;
    2184         char **new_argv;
    2185         int argc;
     2291        /* The file is not executable.  Try it as a shell script.  */
     2292        const char *shell;
     2293        char **new_argv;
     2294        int argc;
    21862295        int i=1;
    21872296
    21882297# ifdef __EMX__
    21892298        /* Do not use $SHELL from the environment */
    2190         struct variable *p = lookup_variable ("SHELL", 5);
    2191         if (p)
    2192           shell = p->value;
     2299        struct variable *p = lookup_variable ("SHELL", 5);
     2300        if (p)
     2301          shell = p->value;
    21932302        else
    21942303          shell = 0;
    21952304# else
    2196         shell = getenv ("SHELL");
     2305        shell = getenv ("SHELL");
    21972306# endif
    2198         if (shell == 0)
    2199           shell = default_shell;
    2200 
    2201         argc = 1;
    2202         while (argv[argc] != 0)
    2203           ++argc;
     2307        if (shell == 0)
     2308          shell = default_shell;
     2309
     2310        argc = 1;
     2311        while (argv[argc] != 0)
     2312          ++argc;
    22042313
    22052314# ifdef __EMX__
     
    22082317# endif
    22092318
    2210         new_argv = alloca ((1 + argc + 1) * sizeof (char *));
    2211         new_argv[0] = shell;
     2319        new_argv = alloca ((1 + argc + 1) * sizeof (char *));
     2320        new_argv[0] = (char *)shell;
    22122321
    22132322# ifdef __EMX__
     
    22212330
    22222331        new_argv[i] = argv[0];
    2223         while (argc > 0)
    2224           {
    2225             new_argv[i + argc] = argv[argc];
    2226             --argc;
    2227           }
     2332        while (argc > 0)
     2333          {
     2334            new_argv[i + argc] = argv[argc];
     2335            --argc;
     2336          }
    22282337
    22292338# ifdef __EMX__
    2230         pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
    2231         if (pid >= 0)
     2339        pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
     2340        if (pid >= 0)
    22322341          break;
    22332342# else
    2234         execvp (shell, new_argv);
     2343        execvp (shell, new_argv);
    22352344# endif
    2236         if (errno == ENOENT)
    2237           error (NILF, _("%s: Shell program not found"), shell);
    2238         else
    2239           perror_with_name ("execvp: ", shell);
    2240         break;
     2345        if (errno == ENOENT)
     2346          OS (error, NILF, _("%s: Shell program not found"), shell);
     2347        else
     2348          perror_with_name ("execvp: ", shell);
     2349        break;
    22412350      }
    22422351
     
    22442353    case EINVAL:
    22452354      /* this nasty error was driving me nuts :-( */
    2246       error (NILF, _("spawnvpe: environment space might be exhausted"));
     2355      O (error, NILF, _("spawnvpe: environment space might be exhausted"));
    22472356      /* FALLTHROUGH */
    22482357# endif
     
    22622371}
    22632372#else /* On Amiga */
    2264 void exec_command (char **argv)
     2373void
     2374exec_command (char **argv)
    22652375{
    22662376  MyExecute (argv);
     
    22782388/* Figure out the argument list necessary to run LINE as a command.  Try to
    22792389   avoid using a shell.  This routine handles only ' quoting, and " quoting
    2280    when no backslash, $ or ` characters are seen in the quotes.  Starting
     2390   when no backslash, $ or ' characters are seen in the quotes.  Starting
    22812391   quotes may be escaped with a backslash.  If any of the characters in
    2282    sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
     2392   sh_chars is seen, or any of the builtin commands listed in sh_cmds
    22832393   is the first word of a line, the shell is used.
    22842394
     
    22952405
    22962406static char **
    2297 construct_command_argv_internal (char *line, char **restp, char *shell,
    2298                                  char *shellflags, char *ifs, int flags,
    2299                                  char **batch_filename_ptr)
     2407construct_command_argv_internal (char *line, char **restp, const char *shell,
     2408                                 const char *shellflags, const char *ifs,
     2409                                 int flags, char **batch_filename UNUSED)
    23002410{
    23012411#ifdef __MSDOS__
    23022412  /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
    2303      We call `system' for anything that requires ``slow'' processing,
     2413     We call 'system' for anything that requires ''slow'' processing,
    23042414     because DOS shells are too dumb.  When $SHELL points to a real
    2305      (unix-style) shell, `system' just calls it to do everything.  When
    2306      $SHELL points to a DOS shell, `system' does most of the work
     2415     (unix-style) shell, 'system' just calls it to do everything.  When
     2416     $SHELL points to a DOS shell, 'system' does most of the work
    23072417     internally, calling the shell only for its internal commands.
    23082418     However, it looks on the $PATH first, so you can e.g. have an
    2309      external command named `mkdir'.
    2310 
    2311      Since we call `system', certain characters and commands below are
     2419     external command named 'mkdir'.
     2420
     2421     Since we call 'system', certain characters and commands below are
    23122422     actually not specific to COMMAND.COM, but to the DJGPP implementation
    2313      of `system'.  In particular:
     2423     of 'system'.  In particular:
    23142424
    23152425       The shell wildcard characters are in DOS_CHARS because they will
    2316        not be expanded if we call the child via `spawnXX'.
    2317 
    2318        The `;' is in DOS_CHARS, because our `system' knows how to run
     2426       not be expanded if we call the child via 'spawnXX'.
     2427
     2428       The ';' is in DOS_CHARS, because our 'system' knows how to run
    23192429       multiple commands on a single line.
    23202430
     
    23222432       won't have to tell one from another and have one more set of
    23232433       commands and special characters.  */
    2324   static char sh_chars_dos[] = "*?[];|<>%^&()";
    2325   static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
    2326                                  "copy", "ctty", "date", "del", "dir", "echo",
    2327                                  "erase", "exit", "for", "goto", "if", "md",
    2328                                  "mkdir", "path", "pause", "prompt", "rd",
    2329                                  "rmdir", "rem", "ren", "rename", "set",
    2330                                  "shift", "time", "type", "ver", "verify",
    2331                                  "vol", ":", 0 };
    2332 
    2333   static char sh_chars_sh[]  = "#;\"*?[]&|<>(){}$`^";
    2334   static char *sh_cmds_sh[]  = { "cd", "echo", "eval", "exec", "exit", "login",
    2335                                  "logout", "set", "umask", "wait", "while",
    2336                                  "for", "case", "if", ":", ".", "break",
    2337                                  "continue", "export", "read", "readonly",
    2338                                  "shift", "times", "trap", "switch", "unset",
    2339                                  "ulimit", 0 };
    2340 
    2341   char *sh_chars;
    2342   char **sh_cmds;
     2434  static const char *sh_chars_dos = "*?[];|<>%^&()";
     2435  static const char *sh_cmds_dos[] =
     2436    { "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty", "date",
     2437      "del", "dir", "echo", "erase", "exit", "for", "goto", "if", "md",
     2438      "mkdir", "path", "pause", "prompt", "rd", "rmdir", "rem", "ren",
     2439      "rename", "set", "shift", "time", "type", "ver", "verify", "vol", ":",
     2440      0 };
     2441
     2442  static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^";
     2443  static const char *sh_cmds_sh[] =
     2444    { "cd", "echo", "eval", "exec", "exit", "login", "logout", "set", "umask",
     2445      "wait", "while", "for", "case", "if", ":", ".", "break", "continue",
     2446      "export", "read", "readonly", "shift", "times", "trap", "switch",
     2447      "unset", "ulimit", 0 };
     2448
     2449  const char *sh_chars;
     2450  const char **sh_cmds;
     2451
    23432452#elif defined (__EMX__)
    2344   static char sh_chars_dos[] = "*?[];|<>%^&()";
    2345   static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
    2346                                  "copy", "ctty", "date", "del", "dir", "echo",
    2347                                  "erase", "exit", "for", "goto", "if", "md",
    2348                                  "mkdir", "path", "pause", "prompt", "rd",
    2349                                  "rmdir", "rem", "ren", "rename", "set",
    2350                                  "shift", "time", "type", "ver", "verify",
    2351                                  "vol", ":", 0 };
    2352 
    2353   static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
    2354   static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
    2355                              "date", "del", "detach", "dir", "echo",
    2356                              "endlocal", "erase", "exit", "for", "goto", "if",
    2357                              "keys", "md", "mkdir", "move", "path", "pause",
    2358                              "prompt", "rd", "rem", "ren", "rename", "rmdir",
    2359                              "set", "setlocal", "shift", "start", "time",
    2360                              "type", "ver", "verify", "vol", ":", 0 };
    2361 
    2362   static char sh_chars_sh[]  = "#;\"*?[]&|<>(){}$`^~'";
    2363   static char *sh_cmds_sh[]  = { "echo", "cd", "eval", "exec", "exit", "login",
    2364                                  "logout", "set", "umask", "wait", "while",
    2365                                  "for", "case", "if", ":", ".", "break",
    2366                                  "continue", "export", "read", "readonly",
    2367                                  "shift", "times", "trap", "switch", "unset",
    2368                                  0 };
    2369   char *sh_chars;
    2370   char **sh_cmds;
     2453  static const char *sh_chars_dos = "*?[];|<>%^&()";
     2454  static const char *sh_cmds_dos[] =
     2455    { "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty", "date",
     2456      "del", "dir", "echo", "erase", "exit", "for", "goto", "if", "md",
     2457      "mkdir", "path", "pause", "prompt", "rd", "rmdir", "rem", "ren",
     2458      "rename", "set", "shift", "time", "type", "ver", "verify", "vol", ":",
     2459      0 };
     2460
     2461  static const char *sh_chars_os2 = "*?[];|<>%^()\"'&";
     2462  static const char *sh_cmds_os2[] =
     2463    { "call", "cd", "chcp", "chdir", "cls", "copy", "date", "del", "detach",
     2464      "dir", "echo", "endlocal", "erase", "exit", "for", "goto", "if", "keys",
     2465      "md", "mkdir", "move", "path", "pause", "prompt", "rd", "rem", "ren",
     2466      "rename", "rmdir", "set", "setlocal", "shift", "start", "time", "type",
     2467      "ver", "verify", "vol", ":", 0 };
     2468
     2469  static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^~'";
     2470  static const char *sh_cmds_sh[] =
     2471    { "echo", "cd", "eval", "exec", "exit", "login", "logout", "set", "umask",
     2472      "wait", "while", "for", "case", "if", ":", ".", "break", "continue",
     2473      "export", "read", "readonly", "shift", "times", "trap", "switch",
     2474      "unset", 0 };
     2475
     2476  const char *sh_chars;
     2477  const char **sh_cmds;
    23712478
    23722479#elif defined (_AMIGA)
    2373   static char sh_chars[] = "#;\"|<>()?*$`";
    2374   static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
    2375                              "rename", "set", "setenv", "date", "makedir",
    2376                              "skip", "else", "endif", "path", "prompt",
    2377                              "unset", "unsetenv", "version",
    2378                              0 };
     2480  static const char *sh_chars = "#;\"|<>()?*$`";
     2481  static const char *sh_cmds[] =
     2482    { "cd", "eval", "if", "delete", "echo", "copy", "rename", "set", "setenv",
     2483      "date", "makedir", "skip", "else", "endif", "path", "prompt", "unset",
     2484      "unsetenv", "version", 0 };
     2485
    23792486#elif defined (WINDOWS32)
    2380   static char sh_chars_dos[] = "\"|&<>";
    2381   static char *sh_cmds_dos[] = { "assoc", "break", "call", "cd", "chcp",
    2382                                  "chdir", "cls", "color", "copy", "ctty",
    2383                                  "date", "del", "dir", "echo", "echo.",
    2384                                  "endlocal", "erase", "exit", "for", "ftype",
    2385                                  "goto", "if", "if", "md", "mkdir", "path",
    2386                                  "pause", "prompt", "rd", "rem", "ren",
    2387                                  "rename", "rmdir", "set", "setlocal",
    2388                                  "shift", "time", "title", "type", "ver",
    2389                                  "verify", "vol", ":", 0 };
    2390   static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
    2391   static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
    2392                              "logout", "set", "umask", "wait", "while", "for",
    2393                              "case", "if", ":", ".", "break", "continue",
    2394                              "export", "read", "readonly", "shift", "times",
    2395                              "trap", "switch", "test",
     2487  /* We used to have a double quote (") in sh_chars_dos[] below, but
     2488     that caused any command line with quoted file names be run
     2489     through a temporary batch file, which introduces command-line
     2490     limit of 4K charcaters imposed by cmd.exe.  Since CreateProcess
     2491     can handle quoted file names just fine, removing the quote lifts
     2492     the limit from a very frequent use case, because using quoted
     2493     file names is commonplace on MS-Windows.  */
     2494  static const char *sh_chars_dos = "|&<>";
     2495  static const char *sh_cmds_dos[] =
     2496    { "assoc", "break", "call", "cd", "chcp", "chdir", "cls", "color", "copy",
     2497      "ctty", "date", "del", "dir", "echo", "echo.", "endlocal", "erase",
     2498      "exit", "for", "ftype", "goto", "if", "if", "md", "mkdir", "move",
     2499      "path", "pause", "prompt", "rd", "rem", "ren", "rename", "rmdir",
     2500      "set", "setlocal", "shift", "time", "title", "type", "ver", "verify",
     2501      "vol", ":", 0 };
     2502
     2503  static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^";
     2504  static const char *sh_cmds_sh[] =
     2505    { "cd", "eval", "exec", "exit", "login", "logout", "set", "umask", "wait",
     2506      "while", "for", "case", "if", ":", ".", "break", "continue", "export",
     2507      "read", "readonly", "shift", "times", "trap", "switch", "test",
    23962508#ifdef BATCH_MODE_ONLY_SHELL
    2397                  "echo",
    2398 #endif
    2399                  0 };
    2400   char*  sh_chars;
    2401   char** sh_cmds;
     2509      "echo",
     2510#endif
     2511      0 };
     2512
     2513  const char *sh_chars;
     2514  const char **sh_cmds;
    24022515#elif defined(__riscos__)
    2403   static char sh_chars[] = "";
    2404   static char *sh_cmds[] = { 0 };
     2516  static const char *sh_chars = "";
     2517  static const char *sh_cmds[] = { 0 };
    24052518#else  /* must be UNIX-ish */
    2406   static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~!";
    2407   static char *sh_cmds[] = { ".", ":", "break", "case", "cd", "continue",
    2408                              "eval", "exec", "exit", "export", "for", "if",
    2409                              "login", "logout", "read", "readonly", "set",
    2410                              "shift", "switch", "test", "times", "trap",
    2411                              "ulimit", "umask", "unset", "wait", "while", 0 };
     2519  static const char *sh_chars = "#;\"*?[]&|<>(){}$`^~!";
     2520  static const char *sh_cmds[] =
     2521    { ".", ":", "break", "case", "cd", "continue", "eval", "exec", "exit",
     2522      "export", "for", "if", "login", "logout", "read", "readonly", "set",
     2523      "shift", "switch", "test", "times", "trap", "ulimit", "umask", "unset",
     2524      "wait", "while", 0 };
     2525
    24122526# ifdef HAVE_DOS_PATHS
    24132527  /* This is required if the MSYS/Cygwin ports (which do not define
    24142528     WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
    2415      sh_chars_sh[] directly (see below).  */
    2416   static char *sh_chars_sh = sh_chars;
    2417 # endif  /* HAVE_DOS_PATHS */
     2529     sh_chars_sh directly (see below).  The value must be identical
     2530     to that of sh_chars immediately above.  */
     2531  static const char *sh_chars_sh =  "#;\"*?[]&|<>(){}$`^~!";
     2532# endif  /* HAVE_DOS_PATHS */
    24182533#endif
    24192534  int i;
    24202535  char *p;
     2536#ifndef NDEBUG
     2537  char *end;
     2538#endif
    24212539  char *ap;
    2422   char *end;
     2540  const char *cap;
     2541  const char *cp;
    24232542  int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
    24242543  char **new_argv = 0;
     
    24272546  int slow_flag = 0;
    24282547
    2429   if (!unixy_shell) {
    2430     sh_cmds = sh_cmds_dos;
    2431     sh_chars = sh_chars_dos;
    2432   } else {
    2433     sh_cmds = sh_cmds_sh;
    2434     sh_chars = sh_chars_sh;
    2435   }
     2548  if (!unixy_shell)
     2549    {
     2550      sh_cmds = sh_cmds_dos;
     2551      sh_chars = sh_chars_dos;
     2552    }
     2553  else
     2554    {
     2555      sh_cmds = sh_cmds_sh;
     2556      sh_chars = sh_chars_sh;
     2557    }
    24362558#endif /* WINDOWS32 */
    24372559
     
    24392561    *restp = NULL;
    24402562
    2441   /* Make sure not to bother processing an empty line.  */
    2442   while (isblank ((unsigned char)*line))
     2563  /* Make sure not to bother processing an empty line but stop at newline.  */
     2564  while (ISBLANK (*line))
    24432565    ++line;
    24442566  if (*line == '\0')
    24452567    return 0;
     2568
     2569  if (shellflags == 0)
     2570    shellflags = posix_pedantic ? "-ec" : "-c";
    24462571
    24472572  /* See if it is safe to parse commands internally.  */
     
    24562581    slow_flag = strcmp ((s1 ? s1 : ""), (s2 ? s2 : ""));
    24572582
    2458     if (s1)
    2459       free (s1);
    2460     if (s2)
    2461       free (s2);
     2583    free (s1);
     2584    free (s2);
    24622585  }
    24632586  if (slow_flag)
     
    24692592      extern int _is_unixy_shell (const char *_path);
    24702593
    2471       DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
     2594      DB (DB_BASIC, (_("$SHELL changed (was '%s', now '%s')\n"),
    24722595                     default_shell, shell));
    24732596      unixy_shell = _is_unixy_shell (shell);
     
    24992622#endif /* not WINDOWS32 */
    25002623
    2501   if (ifs != 0)
    2502     for (ap = ifs; *ap != '\0'; ++ap)
    2503       if (*ap != ' ' && *ap != '\t' && *ap != '\n')
    2504         goto slow;
    2505 
    2506   if (shellflags != 0)
     2624  if (ifs)
     2625    for (cap = ifs; *cap != '\0'; ++cap)
     2626      if (*cap != ' ' && *cap != '\t' && *cap != '\n')
     2627        goto slow;
     2628
     2629  if (shellflags)
    25072630    if (shellflags[0] != '-'
    25082631        || ((shellflags[1] != 'c' || shellflags[2] != '\0')
     
    25172640  /* All the args can fit in a buffer as big as LINE is.   */
    25182641  ap = new_argv[0] = argstr = xmalloc (i);
     2642#ifndef NDEBUG
    25192643  end = ap + i;
     2644#endif
    25202645
    25212646  /* I is how many complete arguments have been found.  */
     
    25272652
    25282653      if (instring)
    2529         {
    2530           /* Inside a string, just copy any char except a closing quote
    2531              or a backslash-newline combination.  */
    2532           if (*p == instring)
    2533             {
    2534               instring = 0;
    2535               if (ap == new_argv[0] || *(ap-1) == '\0')
    2536                 last_argument_was_empty = 1;
    2537             }
    2538           else if (*p == '\\' && p[1] == '\n')
     2654        {
     2655          /* Inside a string, just copy any char except a closing quote
     2656             or a backslash-newline combination.  */
     2657          if (*p == instring)
     2658            {
     2659              instring = 0;
     2660              if (ap == new_argv[0] || *(ap-1) == '\0')
     2661                last_argument_was_empty = 1;
     2662            }
     2663          else if (*p == '\\' && p[1] == '\n')
    25392664            {
    25402665              /* Backslash-newline is handled differently depending on what
    25412666                 kind of string we're in: inside single-quoted strings you
    2542                  keep them; in double-quoted strings they disappear.
    2543                  For DOS/Windows/OS2, if we don't have a POSIX shell,
    2544                  we keep the pre-POSIX behavior of removing the
    2545                  backslash-newline.  */
     2667                 keep them; in double-quoted strings they disappear.  For
     2668                 DOS/Windows/OS2, if we don't have a POSIX shell, we keep the
     2669                 pre-POSIX behavior of removing the backslash-newline.  */
    25462670              if (instring == '"'
    25472671#if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
    2548                   || !unixy_shell
    2549 #endif
    2550                   )
     2672                  || !unixy_shell
     2673#endif
     2674                  )
    25512675                ++p;
    25522676              else
     
    25562680                }
    25572681            }
    2558           else if (*p == '\n' && restp != NULL)
    2559             {
    2560               /* End of the command line.  */
    2561               *restp = p;
    2562               goto end_of_line;
    2563             }
    2564           /* Backslash, $, and ` are special inside double quotes.
    2565              If we see any of those, punt.
    2566              But on MSDOS, if we use COMMAND.COM, double and single
    2567              quotes have the same effect.  */
    2568           else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
    2569             goto slow;
    2570           else
    2571             *ap++ = *p;
    2572         }
     2682          else if (*p == '\n' && restp != NULL)
     2683            {
     2684              /* End of the command line.  */
     2685              *restp = p;
     2686              goto end_of_line;
     2687            }
     2688          /* Backslash, $, and ` are special inside double quotes.
     2689             If we see any of those, punt.
     2690             But on MSDOS, if we use COMMAND.COM, double and single
     2691             quotes have the same effect.  */
     2692          else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
     2693            goto slow;
     2694#ifdef WINDOWS32
     2695          /* Quoted wildcard characters must be passed quoted to the
     2696             command, so give up the fast route.  */
     2697          else if (instring == '"' && strchr ("*?", *p) != 0 && !unixy_shell)
     2698            goto slow;
     2699          else if (instring == '"' && strncmp (p, "\\\"", 2) == 0)
     2700            *ap++ = *++p;
     2701#endif
     2702          else
     2703            *ap++ = *p;
     2704        }
    25732705      else if (strchr (sh_chars, *p) != 0)
    2574         /* Not inside a string, but it's a special char.  */
    2575         goto slow;
     2706        /* Not inside a string, but it's a special char.  */
     2707        goto slow;
    25762708      else if (one_shell && *p == '\n')
    2577         /* In .ONESHELL mode \n is a separator like ; or && */
    2578         goto slow;
     2709        /* In .ONESHELL mode \n is a separator like ; or && */
     2710        goto slow;
    25792711#ifdef  __MSDOS__
    25802712      else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
    2581         /* `...' is a wildcard in DJGPP.  */
    2582         goto slow;
     2713        /* '...' is a wildcard in DJGPP.  */
     2714        goto slow;
    25832715#endif
    25842716      else
    2585         /* Not a special char.  */
    2586         switch (*p)
    2587           {
    2588           case '=':
    2589             /* Equals is a special character in leading words before the
    2590                first word with no equals sign in it.  This is not the case
    2591                with sh -k, but we never get here when using nonstandard
    2592                shell flags.  */
    2593             if (! seen_nonequals && unixy_shell)
    2594               goto slow;
    2595             word_has_equals = 1;
    2596             *ap++ = '=';
    2597             break;
    2598 
    2599           case '\\':
    2600             /* Backslash-newline has special case handling, ref POSIX.
     2717        /* Not a special char.  */
     2718        switch (*p)
     2719          {
     2720          case '=':
     2721            /* Equals is a special character in leading words before the
     2722               first word with no equals sign in it.  This is not the case
     2723               with sh -k, but we never get here when using nonstandard
     2724               shell flags.  */
     2725            if (! seen_nonequals && unixy_shell)
     2726              goto slow;
     2727            word_has_equals = 1;
     2728            *ap++ = '=';
     2729            break;
     2730
     2731          case '\\':
     2732            /* Backslash-newline has special case handling, ref POSIX.
    26012733               We're in the fastpath, so emulate what the shell would do.  */
    2602             if (p[1] == '\n')
    2603               {
    2604                 /* Throw out the backslash and newline.  */
     2734            if (p[1] == '\n')
     2735              {
     2736                /* Throw out the backslash and newline.  */
    26052737                ++p;
    26062738
    2607                 /* If there's nothing in this argument yet, skip any
    2608                    whitespace before the start of the next word.  */
     2739                /* At the beginning of the argument, skip any whitespace other
     2740                   than newline before the start of the next word.  */
    26092741                if (ap == new_argv[i])
    2610                   p = next_token (p + 1) - 1;
    2611               }
    2612             else if (p[1] != '\0')
     2742                  while (ISBLANK (p[1]))
     2743                    ++p;
     2744              }
     2745#ifdef WINDOWS32
     2746            /* Backslash before whitespace is not special if our shell
     2747               is not Unixy.  */
     2748            else if (ISSPACE (p[1]) && !unixy_shell)
     2749              {
     2750                *ap++ = *p;
     2751                break;
     2752              }
     2753#endif
     2754            else if (p[1] != '\0')
    26132755              {
    26142756#ifdef HAVE_DOS_PATHS
     
    26312773#endif
    26322774                  if (p[1] != '\\' && p[1] != '\''
    2633                       && !isspace ((unsigned char)p[1])
     2775                      && !ISSPACE (p[1])
    26342776                      && strchr (sh_chars_sh, p[1]) == 0)
    26352777                    /* back up one notch, to copy the backslash */
     
    26402782                *ap++ = *++p;
    26412783              }
    2642             break;
    2643 
    2644           case '\'':
    2645           case '"':
    2646             instring = *p;
    2647             break;
    2648 
    2649           case '\n':
    2650             if (restp != NULL)
    2651               {
    2652                 /* End of the command line.  */
    2653                 *restp = p;
    2654                 goto end_of_line;
    2655               }
    2656             else
    2657               /* Newlines are not special.  */
    2658               *ap++ = '\n';
    2659             break;
    2660 
    2661           case ' ':
    2662           case '\t':
    2663             /* We have the end of an argument.
    2664                Terminate the text of the argument.  */
    2665             *ap++ = '\0';
    2666             new_argv[++i] = ap;
    2667             last_argument_was_empty = 0;
    2668 
    2669             /* Update SEEN_NONEQUALS, which tells us if every word
    2670                heretofore has contained an `='.  */
    2671             seen_nonequals |= ! word_has_equals;
    2672             if (word_has_equals && ! seen_nonequals)
    2673               /* An `=' in a word before the first
    2674                 word without one is magical.  */
    2675               goto slow;
    2676             word_has_equals = 0; /* Prepare for the next word.  */
    2677 
    2678             /* If this argument is the command name,
    2679                see if it is a built-in shell command.
    2680                If so, have the shell handle it.  */
    2681             if (i == 1)
    2682               {
    2683                 register int j;
    2684                 for (j = 0; sh_cmds[j] != 0; ++j)
     2784            break;
     2785
     2786          case '\'':
     2787          case '"':
     2788            instring = *p;
     2789            break;
     2790
     2791          case '\n':
     2792            if (restp != NULL)
     2793              {
     2794                /* End of the command line.  */
     2795                *restp = p;
     2796                goto end_of_line;
     2797              }
     2798            else
     2799              /* Newlines are not special.  */
     2800              *ap++ = '\n';
     2801            break;
     2802
     2803          case ' ':
     2804          case '\t':
     2805            /* We have the end of an argument.
     2806               Terminate the text of the argument.  */
     2807            *ap++ = '\0';
     2808            new_argv[++i] = ap;
     2809            last_argument_was_empty = 0;
     2810
     2811            /* Update SEEN_NONEQUALS, which tells us if every word
     2812               heretofore has contained an '='.  */
     2813            seen_nonequals |= ! word_has_equals;
     2814            if (word_has_equals && ! seen_nonequals)
     2815              /* An '=' in a word before the first
     2816                word without one is magical.  */
     2817              goto slow;
     2818            word_has_equals = 0; /* Prepare for the next word.  */
     2819
     2820            /* If this argument is the command name,
     2821               see if it is a built-in shell command.
     2822               If so, have the shell handle it.  */
     2823            if (i == 1)
     2824              {
     2825                register int j;
     2826                for (j = 0; sh_cmds[j] != 0; ++j)
    26852827                  {
    26862828                    if (streq (sh_cmds[j], new_argv[0]))
    26872829                      goto slow;
    2688 # ifdef __EMX__
     2830#if defined(__EMX__) || defined(WINDOWS32)
    26892831                    /* Non-Unix shells are case insensitive.  */
    26902832                    if (!unixy_shell
    26912833                        && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
    26922834                      goto slow;
    2693 # endif
     2835#endif
    26942836                  }
    2695               }
    2696 
    2697             /* Ignore multiple whitespace chars.  */
    2698             p = next_token (p) - 1;
    2699             break;
    2700 
    2701           default:
    2702             *ap++ = *p;
    2703             break;
    2704           }
     2837              }
     2838
     2839            /* Skip whitespace chars, but not newlines.  */
     2840            while (ISBLANK (p[1]))
     2841              ++p;
     2842            break;
     2843
     2844          default:
     2845            *ap++ = *p;
     2846            break;
     2847          }
    27052848    }
    27062849 end_of_line:
     
    27212864      register int j;
    27222865      for (j = 0; sh_cmds[j] != 0; ++j)
    2723         if (streq (sh_cmds[j], new_argv[0]))
    2724           goto slow;
     2866        if (streq (sh_cmds[j], new_argv[0]))
     2867          goto slow;
    27252868    }
    27262869
     
    27462889
    27472890#ifdef __MSDOS__
    2748   execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
     2891  execute_by_shell = 1; /* actually, call 'system' if shell isn't unixy */
    27492892#endif
    27502893
     
    27612904    {
    27622905      if (*ptr == '\\' && ptr[1] == '\n')
    2763         ptr += 2;
     2906        ptr += 2;
    27642907      else if (*ptr == '@') /* Kludge: multiline commands */
    27652908      {
    2766         ptr += 2;
    2767         *dptr++ = '\n';
     2909        ptr += 2;
     2910        *dptr++ = '\n';
    27682911      }
    27692912      else
    2770         *dptr++ = *ptr++;
     2913        *dptr++ = *ptr++;
    27712914    }
    27722915    *dptr = 0;
     
    27762919    new_argv[1] = 0;
    27772920  }
    2778 #else   /* Not Amiga  */
     2921#else   /* Not Amiga  */
    27792922#ifdef WINDOWS32
    27802923  /*
     
    27892932
    27902933  /* Make sure not to bother processing an empty line.  */
    2791   while (isspace ((unsigned char)*line))
    2792     ++line;
     2934  NEXT_TOKEN (line);
    27932935  if (*line == '\0')
    27942936    return 0;
     
    28012943       argument list.  */
    28022944
     2945    char *new_line;
    28032946    unsigned int shell_len = strlen (shell);
    28042947    unsigned int line_len = strlen (line);
    2805     unsigned int sflags_len = strlen (shellflags);
     2948    unsigned int sflags_len = shellflags ? strlen (shellflags) : 0;
     2949#ifdef WINDOWS32
    28062950    char *command_ptr = NULL; /* used for batch_mode_shell mode */
    2807     char *new_line;
     2951#endif
    28082952
    28092953# ifdef __EMX__ /* is this necessary? */
    2810     if (!unixy_shell)
     2954    if (!unixy_shell && shellflags)
    28112955      shellflags[0] = '/'; /* "/c" */
    28122956# endif
    28132957
    28142958    /* In .ONESHELL mode we are allowed to throw the entire current
    2815         recipe string at a single shell and trust that the user
    2816         has configured the shell and shell flags, and formatted
    2817         the string, appropriately. */
     2959        recipe string at a single shell and trust that the user
     2960        has configured the shell and shell flags, and formatted
     2961        the string, appropriately. */
    28182962    if (one_shell)
    28192963      {
    2820         /* If the shell is Bourne compatible, we must remove and ignore
    2821            interior special chars [@+-] because they're meaningless to
    2822            the shell itself. If, however, we're in .ONESHELL mode and
    2823            have changed SHELL to something non-standard, we should
    2824            leave those alone because they could be part of the
    2825            script. In this case we must also leave in place
    2826            any leading [@+-] for the same reason.  */
    2827 
    2828         /* Remove and ignore interior prefix chars [@+-] because they're
    2829              meaningless given a single shell. */
     2964        /* If the shell is Bourne compatible, we must remove and ignore
     2965           interior special chars [@+-] because they're meaningless to
     2966           the shell itself. If, however, we're in .ONESHELL mode and
     2967           have changed SHELL to something non-standard, we should
     2968           leave those alone because they could be part of the
     2969           script. In this case we must also leave in place
     2970           any leading [@+-] for the same reason.  */
     2971
     2972        /* Remove and ignore interior prefix chars [@+-] because they're
     2973             meaningless given a single shell. */
    28302974#if defined __MSDOS__ || defined (__EMX__)
    2831         if (unixy_shell)     /* the test is complicated and we already did it */
     2975        if (unixy_shell)     /* the test is complicated and we already did it */
    28322976#else
    2833         if (is_bourne_compatible_shell(shell))
     2977        if (is_bourne_compatible_shell (shell)
     2978#ifdef WINDOWS32
     2979            /* If we didn't find any sh.exe, don't behave is if we did!  */
     2980            && !no_default_sh_exe
     2981#endif
     2982            )
    28342983#endif
    28352984          {
     
    28432992                int esc = 0;
    28442993
    2845                 /* This is the start of a new recipe line.
    2846                    Skip whitespace and prefix characters.  */
    2847                 while (isblank (*f) || *f == '-' || *f == '@' || *f == '+')
     2994                /* This is the start of a new recipe line.  Skip whitespace
     2995                   and prefix characters but not newlines.  */
     2996                while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
    28482997                  ++f;
    28492998
     
    28673016            *t = '\0';
    28683017          }
    2869 
    2870         new_argv = xmalloc (4 * sizeof (char *));
    2871         new_argv[0] = xstrdup(shell);
    2872         new_argv[1] = xstrdup(shellflags);
    2873         new_argv[2] = line;
    2874         new_argv[3] = NULL;
    2875         return new_argv;
     3018#ifdef WINDOWS32
     3019        else    /* non-Posix shell (cmd.exe etc.) */
     3020          {
     3021            const char *f = line;
     3022            char *t = line;
     3023            char *tstart = t;
     3024            int temp_fd;
     3025            FILE* batch = NULL;
     3026            int id = GetCurrentProcessId ();
     3027            PATH_VAR(fbuf);
     3028
     3029            /* Generate a file name for the temporary batch file.  */
     3030            sprintf (fbuf, "make%d", id);
     3031            *batch_filename = create_batch_file (fbuf, 0, &temp_fd);
     3032            DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
     3033                          *batch_filename));
     3034
     3035            /* Create a FILE object for the batch file, and write to it the
     3036               commands to be executed.  Put the batch file in TEXT mode.  */
     3037            _setmode (temp_fd, _O_TEXT);
     3038            batch = _fdopen (temp_fd, "wt");
     3039            fputs ("@echo off\n", batch);
     3040            DB (DB_JOBS, (_("Batch file contents:\n\t@echo off\n")));
     3041
     3042            /* Copy the recipe, removing and ignoring interior prefix chars
     3043               [@+-]: they're meaningless in .ONESHELL mode.  */
     3044            while (*f != '\0')
     3045              {
     3046                /* This is the start of a new recipe line.  Skip whitespace
     3047                   and prefix characters but not newlines.  */
     3048                while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
     3049                  ++f;
     3050
     3051                /* Copy until we get to the next logical recipe line.  */
     3052                while (*f != '\0')
     3053                  {
     3054                    /* Remove the escaped newlines in the command, and the
     3055                       blanks that follow them.  Windows shells cannot handle
     3056                       escaped newlines.  */
     3057                    if (*f == '\\' && f[1] == '\n')
     3058                      {
     3059                        f += 2;
     3060                        while (ISBLANK (*f))
     3061                          ++f;
     3062                      }
     3063                    *(t++) = *(f++);
     3064                    /* On an unescaped newline, we're done with this
     3065                       line.  */
     3066                    if (f[-1] == '\n')
     3067                      break;
     3068                  }
     3069                /* Write another line into the batch file.  */
     3070                if (t > tstart)
     3071                  {
     3072                    char c = *t;
     3073                    *t = '\0';
     3074                    fputs (tstart, batch);
     3075                    DB (DB_JOBS, ("\t%s", tstart));
     3076                    tstart = t;
     3077                    *t = c;
     3078                  }
     3079              }
     3080            DB (DB_JOBS, ("\n"));
     3081            fclose (batch);
     3082
     3083            /* Create an argv list for the shell command line that
     3084               will run the batch file.  */
     3085            new_argv = xmalloc (2 * sizeof (char *));
     3086            new_argv[0] = xstrdup (*batch_filename);
     3087            new_argv[1] = NULL;
     3088            return new_argv;
     3089          }
     3090#endif /* WINDOWS32 */
     3091        /* Create an argv list for the shell command line.  */
     3092        {
     3093          int n = 0;
     3094
     3095          new_argv = xmalloc ((4 + sflags_len/2) * sizeof (char *));
     3096          new_argv[n++] = xstrdup (shell);
     3097
     3098          /* Chop up the shellflags (if any) and assign them.  */
     3099          if (! shellflags)
     3100            new_argv[n++] = xstrdup ("");
     3101          else
     3102            {
     3103              const char *s = shellflags;
     3104              char *t;
     3105              unsigned int len;
     3106              while ((t = find_next_token (&s, &len)) != 0)
     3107                new_argv[n++] = xstrndup (t, len);
     3108            }
     3109
     3110          /* Set the command to invoke.  */
     3111          new_argv[n++] = line;
     3112          new_argv[n++] = NULL;
     3113        }
     3114        return new_argv;
    28763115      }
    28773116
    2878     new_line = alloca (shell_len + 1 + sflags_len + 1
    2879                              + (line_len*2) + 1);
     3117    new_line = xmalloc ((shell_len*2) + 1 + sflags_len + 1
     3118                        + (line_len*2) + 1);
    28803119    ap = new_line;
    2881     memcpy (ap, shell, shell_len);
    2882     ap += shell_len;
     3120    /* Copy SHELL, escaping any characters special to the shell.  If
     3121       we don't escape them, construct_command_argv_internal will
     3122       recursively call itself ad nauseam, or until stack overflow,
     3123       whichever happens first.  */
     3124    for (cp = shell; *cp != '\0'; ++cp)
     3125      {
     3126        if (strchr (sh_chars, *cp) != 0)
     3127          *(ap++) = '\\';
     3128        *(ap++) = *cp;
     3129      }
    28833130    *(ap++) = ' ';
    2884     memcpy (ap, shellflags, sflags_len);
     3131    if (shellflags)
     3132      memcpy (ap, shellflags, sflags_len);
    28853133    ap += sflags_len;
    28863134    *(ap++) = ' ';
     3135#ifdef WINDOWS32
    28873136    command_ptr = ap;
     3137#endif
    28883138    for (p = line; *p != '\0'; ++p)
    28893139      {
    2890         if (restp != NULL && *p == '\n')
    2891           {
    2892             *restp = p;
    2893             break;
    2894           }
    2895         else if (*p == '\\' && p[1] == '\n')
    2896           {
    2897             /* POSIX says we keep the backslash-newline.  If we don't have a
     3140        if (restp != NULL && *p == '\n')
     3141          {
     3142            *restp = p;
     3143            break;
     3144          }
     3145        else if (*p == '\\' && p[1] == '\n')
     3146          {
     3147            /* POSIX says we keep the backslash-newline.  If we don't have a
    28983148               POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
    28993149               and remove the backslash/newline.  */
     
    29033153# define PRESERVE_BSNL  1
    29043154#endif
    2905             if (PRESERVE_BSNL)
    2906               {
    2907                 *(ap++) = '\\';
    2908                 /* Only non-batch execution needs another backslash,
    2909                    because it will be passed through a recursive
    2910                    invocation of this function.  */
    2911                 if (!batch_mode_shell)
    2912                   *(ap++) = '\\';
    2913                 *(ap++) = '\n';
    2914               }
    2915             ++p;
    2916             continue;
    2917           }
     3155            if (PRESERVE_BSNL)
     3156              {
     3157                *(ap++) = '\\';
     3158                /* Only non-batch execution needs another backslash,
     3159                   because it will be passed through a recursive
     3160                   invocation of this function.  */
     3161                if (!batch_mode_shell)
     3162                  *(ap++) = '\\';
     3163                *(ap++) = '\n';
     3164              }
     3165            ++p;
     3166            continue;
     3167          }
    29183168
    29193169        /* DOS shells don't know about backslash-escaping.  */
    2920         if (unixy_shell && !batch_mode_shell &&
     3170        if (unixy_shell && !batch_mode_shell &&
    29213171            (*p == '\\' || *p == '\'' || *p == '"'
    2922              || isspace ((unsigned char)*p)
     3172             || ISSPACE (*p)
    29233173             || strchr (sh_chars, *p) != 0))
    2924           *ap++ = '\\';
     3174          *ap++ = '\\';
    29253175#ifdef __MSDOS__
    29263176        else if (unixy_shell && strneq (p, "...", 3))
    29273177          {
    2928             /* The case of `...' wildcard again.  */
     3178            /* The case of '...' wildcard again.  */
    29293179            strcpy (ap, "\\.\\.\\");
    29303180            ap += 5;
     
    29323182          }
    29333183#endif
    2934         *ap++ = *p;
     3184        *ap++ = *p;
    29353185      }
    29363186    if (ap == new_line + shell_len + sflags_len + 2)
    2937       /* Line was empty.  */
    2938       return 0;
     3187      {
     3188        /* Line was empty.  */
     3189        free (new_line);
     3190        return 0;
     3191      }
    29393192    *ap = '\0';
    29403193
     
    29433196       command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems).  In these
    29443197       cases, run commands via a script file.  */
    2945     if (just_print_flag && !(flags & COMMANDS_RECURSE)) {
    2946       /* Need to allocate new_argv, although it's unused, because
    2947         start_job_command will want to free it and its 0'th element.  */
    2948       new_argv = xmalloc(2 * sizeof (char *));
    2949       new_argv[0] = xstrdup ("");
    2950       new_argv[1] = NULL;
    2951     } else if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
    2952       int temp_fd;
    2953       FILE* batch = NULL;
    2954       int id = GetCurrentProcessId();
    2955       PATH_VAR(fbuf);
    2956 
    2957       /* create a file name */
    2958       sprintf(fbuf, "make%d", id);
    2959       *batch_filename_ptr = create_batch_file (fbuf, unixy_shell, &temp_fd);
    2960 
    2961       DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
    2962                     *batch_filename_ptr));
    2963 
    2964       /* Create a FILE object for the batch file, and write to it the
    2965          commands to be executed.  Put the batch file in TEXT mode.  */
    2966       _setmode (temp_fd, _O_TEXT);
    2967       batch = _fdopen (temp_fd, "wt");
    2968       if (!unixy_shell)
    2969         fputs ("@echo off\n", batch);
    2970       fputs (command_ptr, batch);
    2971       fputc ('\n', batch);
    2972       fclose (batch);
    2973       DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
    2974                     !unixy_shell ? "\n\t@echo off" : "", command_ptr));
    2975 
    2976       /* create argv */
    2977       new_argv = xmalloc(3 * sizeof (char *));
    2978       if (unixy_shell) {
    2979         new_argv[0] = xstrdup (shell);
    2980         new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
    2981       } else {
    2982         new_argv[0] = xstrdup (*batch_filename_ptr);
     3198    if (just_print_flag && !(flags & COMMANDS_RECURSE))
     3199      {
     3200        /* Need to allocate new_argv, although it's unused, because
     3201           start_job_command will want to free it and its 0'th element.  */
     3202        new_argv = xmalloc (2 * sizeof (char *));
     3203        new_argv[0] = xstrdup ("");
    29833204        new_argv[1] = NULL;
    29843205      }
    2985       new_argv[2] = NULL;
    2986     } else
     3206    else if ((no_default_sh_exe || batch_mode_shell) && batch_filename)
     3207      {
     3208        int temp_fd;
     3209        FILE* batch = NULL;
     3210        int id = GetCurrentProcessId ();
     3211        PATH_VAR (fbuf);
     3212
     3213        /* create a file name */
     3214        sprintf (fbuf, "make%d", id);
     3215        *batch_filename = create_batch_file (fbuf, unixy_shell, &temp_fd);
     3216
     3217        DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
     3218                      *batch_filename));
     3219
     3220        /* Create a FILE object for the batch file, and write to it the
     3221           commands to be executed.  Put the batch file in TEXT mode.  */
     3222        _setmode (temp_fd, _O_TEXT);
     3223        batch = _fdopen (temp_fd, "wt");
     3224        if (!unixy_shell)
     3225          fputs ("@echo off\n", batch);
     3226        fputs (command_ptr, batch);
     3227        fputc ('\n', batch);
     3228        fclose (batch);
     3229        DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
     3230                      !unixy_shell ? "\n\t@echo off" : "", command_ptr));
     3231
     3232        /* create argv */
     3233        new_argv = xmalloc (3 * sizeof (char *));
     3234        if (unixy_shell)
     3235          {
     3236            new_argv[0] = xstrdup (shell);
     3237            new_argv[1] = *batch_filename; /* only argv[0] gets freed later */
     3238          }
     3239        else
     3240          {
     3241            new_argv[0] = xstrdup (*batch_filename);
     3242            new_argv[1] = NULL;
     3243          }
     3244        new_argv[2] = NULL;
     3245      }
     3246    else
    29873247#endif /* WINDOWS32 */
    29883248
    29893249    if (unixy_shell)
    2990       new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0, flags, 0);
     3250      new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0,
     3251                                                  flags, 0);
    29913252
    29923253#ifdef __EMX__
    29933254    else if (!unixy_shell)
    29943255      {
    2995         /* new_line is local, must not be freed therefore
     3256        /* new_line is local, must not be freed therefore
    29963257           We use line here instead of new_line because we run the shell
    29973258           manually.  */
     
    30733334#else
    30743335    else
    3075       fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
     3336      fatal (NILF, CSTRLEN (__FILE__) + INTSTR_LENGTH,
     3337             _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
    30763338            __FILE__, __LINE__);
    30773339#endif
     3340
     3341    free (new_line);
    30783342  }
    3079 #endif  /* ! AMIGA */
     3343#endif  /* ! AMIGA */
    30803344
    30813345  return new_argv;
     
    30853349/* Figure out the argument list necessary to run LINE as a command.  Try to
    30863350   avoid using a shell.  This routine handles only ' quoting, and " quoting
    3087    when no backslash, $ or ` characters are seen in the quotes.  Starting
     3351   when no backslash, $ or ' characters are seen in the quotes.  Starting
    30883352   quotes may be escaped with a backslash.  If any of the characters in
    3089    sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
     3353   sh_chars is seen, or any of the builtin commands listed in sh_cmds
    30903354   is the first word of a line, the shell is used.
    30913355
     
    30983362char **
    30993363construct_command_argv (char *line, char **restp, struct file *file,
    3100                         int cmd_flags, char **batch_filename_ptr)
     3364                        int cmd_flags, char **batch_filename)
    31013365{
    31023366  char *shell, *ifs, *shellflags;
     
    31113375  for (;;)
    31123376    {
    3113       while ((*cptr != 0)
    3114              && (isspace ((unsigned char)*cptr)))
    3115         cptr++;
     3377      while ((*cptr != 0) && (ISSPACE (*cptr)))
     3378        cptr++;
    31163379      if (*cptr == 0)
    3117         break;
    3118       while ((*cptr != 0)
    3119              && (!isspace((unsigned char)*cptr)))
    3120         cptr++;
     3380        break;
     3381      while ((*cptr != 0) && (!ISSPACE (*cptr)))
     3382        cptr++;
    31213383      argc++;
    31223384    }
     
    31303392  for (;;)
    31313393    {
    3132       while ((*cptr != 0)
    3133              && (isspace ((unsigned char)*cptr)))
    3134         cptr++;
     3394      while ((*cptr != 0) && (ISSPACE (*cptr)))
     3395        cptr++;
    31353396      if (*cptr == 0)
    3136         break;
     3397        break;
    31373398      DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
    31383399      argv[argc++] = cptr;
    3139       while ((*cptr != 0)
    3140              && (!isspace((unsigned char)*cptr)))
    3141         cptr++;
     3400      while ((*cptr != 0) && (!ISSPACE (*cptr)))
     3401        cptr++;
    31423402      if (*cptr != 0)
    3143         *cptr++ = 0;
     3403        *cptr++ = 0;
    31443404    }
    31453405#else
     
    31553415     * is not confused.
    31563416     */
    3157     if (shell) {
    3158       char *p = w32ify (shell, 0);
    3159       strcpy (shell, p);
    3160     }
     3417    if (shell)
     3418      {
     3419        char *p = w32ify (shell, 0);
     3420        strcpy (shell, p);
     3421      }
    31613422#endif
    31623423#ifdef __EMX__
     
    31663427      static int init = 0;
    31673428      if (init == 0)
    3168         {
    3169           unixroot = getenv ("UNIXROOT");
    3170           /* unixroot must be NULL or not empty */
    3171           if (unixroot && unixroot[0] == '\0') unixroot = NULL;
    3172           init = 1;
    3173         }
     3429        {
     3430          unixroot = getenv ("UNIXROOT");
     3431          /* unixroot must be NULL or not empty */
     3432          if (unixroot && unixroot[0] == '\0') unixroot = NULL;
     3433          init = 1;
     3434        }
    31743435
    31753436      /* if we have an unixroot drive and if shell is not default_shell
     
    31793440         "$UNIXROOT/bin/sh" instead.  */
    31803441      if (unixroot && shell && strcmp (shell, last_shell) != 0
    3181           && (shell[0] == '/' || shell[0] == '\\'))
    3182         {
    3183           /* trying a new shell, check whether it exists */
    3184           size_t size = strlen (shell);
    3185           char *buf = xmalloc (size + 7);
    3186           memcpy (buf, shell, size);
    3187           memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
     3442          && (shell[0] == '/' || shell[0] == '\\'))
     3443        {
     3444          /* trying a new shell, check whether it exists */
     3445          size_t size = strlen (shell);
     3446          char *buf = xmalloc (size + 7);
     3447          memcpy (buf, shell, size);
     3448          memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
    31883449          if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
    3189             {
    3190               /* try the same for the unixroot drive */
    3191               memmove (buf + 2, buf, size + 5);
    3192               buf[0] = unixroot[0];
    3193               buf[1] = unixroot[1];
    3194               if (access (buf, F_OK) == 0)
    3195                 /* we have found a shell! */
    3196                 /* free(shell); */
    3197                 shell = buf;
    3198               else
    3199                 free (buf);
    3200             }
    3201           else
     3450            {
     3451              /* try the same for the unixroot drive */
     3452              memmove (buf + 2, buf, size + 5);
     3453              buf[0] = unixroot[0];
     3454              buf[1] = unixroot[1];
     3455              if (access (buf, F_OK) == 0)
     3456                /* we have found a shell! */
     3457                /* free(shell); */
     3458                shell = buf;
     3459              else
     3460                free (buf);
     3461            }
     3462          else
    32023463            free (buf);
    3203         }
     3464        }
    32043465    }
    32053466#endif /* __EMX__ */
     
    32123473
    32133474  argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
    3214                                           cmd_flags, batch_filename_ptr);
     3475                                          cmd_flags, batch_filename);
    32153476
    32163477  free (shell);
     
    32293490
    32303491  (void) close (new);
    3231   fd = dup (old);
     3492  EINTRLOOP (fd, dup (old));
    32323493  if (fd != new)
    32333494    {
Note: See TracChangeset for help on using the changeset viewer.