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


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

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

Location:
trunk/src/kmk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/kmk

  • trunk/src/kmk/job.c

    r3065 r3140  
    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#ifdef CONFIG_WITH_KMK_BUILTIN
    3028# include "kmkbuiltin.h"
     
    4139#include <windows.h>
    4240
    43 char *default_shell = "sh.exe";
     41const char *default_shell = "sh.exe";
    4442int no_default_sh_exe = 1;
    4543int batch_mode_shell = 1;
     
    4846#elif defined (_AMIGA)
    4947
    50 char default_shell[] = "";
     48const char *default_shell = "";
    5149extern int MyExecute (char **);
    5250int batch_mode_shell = 0;
     
    5856   to search the $PATH for it (since MSDOS doesn't have standard
    5957   directories we could trust).  */
    60 char *default_shell = "command.com";
     58const char *default_shell = "command.com";
    6159int batch_mode_shell = 0;
    6260
    6361#elif defined (__EMX__)
    6462
    65 char *default_shell = "sh.exe"; /* bird changed this from "/bin/sh" as that doesn't make sense on OS/2. */
     63const char *default_shell = "sh.exe"; /* bird changed this from "/bin/sh" as that doesn't make sense on OS/2. */
    6664int batch_mode_shell = 0;
    6765
     
    6967
    7068# include <descrip.h>
    71 char default_shell[] = "";
     69# include <stsdef.h>
     70const char *default_shell = "";
    7271int batch_mode_shell = 0;
    7372
    74 #elif defined (__riscos__)
    75 
    76 char default_shell[] = "";
    77 int batch_mode_shell = 0;
     73#define strsignal vms_strsignal
     74char * vms_strsignal (int status);
     75
     76#ifndef C_FACILITY_NO
     77# define C_FACILITY_NO 0x350000
     78#endif
     79#ifndef VMS_POSIX_EXIT_MASK
     80# define VMS_POSIX_EXIT_MASK (C_FACILITY_NO | 0xA000)
     81#endif
    7882
    7983#else
    8084
    81 char default_shell[] = "/bin/sh";
     85const char *default_shell = "/bin/sh";
    8286int batch_mode_shell = 0;
    8387
     
    116120# include "w32err.h"
    117121# include "pathstuff.h"
     122# define WAIT_NOHANG 1
    118123#endif /* WINDOWS32 */
    119124
     
    127132
    128133#ifdef HAVE_WAITPID
    129 # define WAIT_NOHANG(status)    waitpid (-1, (status), WNOHANG)
    130 #else   /* Don't have waitpid.  */
     134# define WAIT_NOHANG(status)    waitpid (-1, (status), WNOHANG)
     135#else   /* Don't have waitpid.  */
    131136# ifdef HAVE_WAIT3
    132137#  ifndef wait3
    133138extern int wait3 ();
    134139#  endif
    135 #  define WAIT_NOHANG(status)   wait3 ((status), WNOHANG, (struct rusage *) 0)
     140#  define WAIT_NOHANG(status)   wait3 ((status), WNOHANG, (struct rusage *) 0)
    136141# endif /* Have wait3.  */
    137142#endif /* Have waitpid.  */
     
    141146#endif
    142147
    143 #ifndef HAVE_UNION_WAIT
     148#ifndef HAVE_UNION_WAIT
    144149
    145150# define WAIT_T int
     
    161166# endif
    162167
    163 #else   /* Have `union wait'.  */
     168#else   /* Have 'union wait'.  */
    164169
    165170# define WAIT_T union wait
     
    180185# endif
    181186
    182 #endif  /* Don't have `union wait'.  */
     187#endif  /* Don't have 'union wait'.  */
    183188
    184189#if !defined(HAVE_UNISTD_H) && !defined(WINDOWS32)
     
    212217}
    213218
     219#ifndef HAVE_GETLOADAVG
    214220int getloadavg (double loadavg[], int nelem);
    215 int start_remote_job (char **argv, char **envp, int stdin_fd, int *is_remote,
    216                       int *id_ptr, int *used_stdin);
    217 int start_remote_job_p (int);
    218 int remote_status (int *exit_code_ptr, int *signal_ptr, int *coredump_ptr,
    219                    int block);
    220 
    221 RETSIGTYPE child_handler (int);
     221#endif
     222
    222223static void free_child (struct child *);
    223224static void start_job_command (struct child *child);
     
    238239unsigned int job_slots_used = 0;
    239240
    240 /* Nonzero if the `good' standard input is in use.  */
     241/* Nonzero if the 'good' standard input is in use.  */
    241242
    242243static int good_stdin_used = 0;
     
    257258
    258259unsigned int jobserver_tokens = 0;
     260
    259261
    260262
    261263#ifdef WINDOWS32
    262264/*
    263  * The macro which references this function is defined in make.h.
     265 * The macro which references this function is defined in makeint.h.
    264266 */
    265267int
    266 w32_kill(pid_t pid, int sig)
     268w32_kill (pid_t pid, int sig)
    267269{
    268   return ((process_kill((HANDLE)pid, sig) == TRUE) ? 0 : -1);
     270  return ((process_kill ((HANDLE)pid, sig) == TRUE) ? 0 : -1);
    269271}
    270272
     
    279281  const char *error_string = NULL;
    280282  char temp_path[MAXPATHLEN]; /* need to know its length */
    281   unsigned path_size = GetTempPath(sizeof temp_path, temp_path);
     283  unsigned path_size = GetTempPath (sizeof temp_path, temp_path);
    282284  int path_is_dot = 0;
    283   unsigned uniq = 1;
     285  /* The following variable is static so we won't try to reuse a name
     286     that was generated a little while ago, because that file might
     287     not be on disk yet, since we use FILE_ATTRIBUTE_TEMPORARY below,
     288     which tells the OS it doesn't need to flush the cache to disk.
     289     If the file is not yet on disk, we might think the name is
     290     available, while it really isn't.  This happens in parallel
     291     builds, where Make doesn't wait for one job to finish before it
     292     launches the next one.  */
     293  static unsigned uniq = 0;
     294  static int second_loop = 0;
    284295  const unsigned sizemax = strlen (base) + strlen (ext) + 10;
    285296
     
    290301    }
    291302
     303  ++uniq;
     304  if (uniq >= 0x10000 && !second_loop)
     305    {
     306      /* If we already had 64K batch files in this
     307         process, make a second loop through the numbers,
     308         looking for free slots, i.e. files that were
     309         deleted in the meantime.  */
     310      second_loop = 1;
     311      uniq = 1;
     312    }
    292313  while (path_size > 0 &&
    293314         path_size + sizemax < sizeof temp_path &&
    294          uniq < 0x10000)
     315         !(uniq >= 0x10000 && second_loop))
    295316    {
    296317      unsigned size = sprintf (temp_path + path_size,
     
    309330      if (h == INVALID_HANDLE_VALUE)
    310331        {
    311           const DWORD er = GetLastError();
     332          const DWORD er = GetLastError ();
    312333
    313334          if (er == ERROR_FILE_EXISTS || er == ERROR_ALREADY_EXISTS)
    314             ++uniq;
     335            {
     336              ++uniq;
     337              if (uniq == 0x10000 && !second_loop)
     338                {
     339                  second_loop = 1;
     340                  uniq = 1;
     341                }
     342            }
    315343
    316344          /* the temporary path is not guaranteed to exist */
     
    348376  if (error_string == NULL)
    349377    error_string = _("Cannot create a temporary file\n");
    350   fatal (NILF, error_string);
     378  O (fatal, NILF, error_string);
    351379
    352380  /* not reached */
     
    388416
    389417  i = 0;
    390   while (known_os2shells[i] != NULL) {
    391     if (strcasecmp (name, known_os2shells[i]) == 0)
    392       return 0; /* not a unix shell */
    393     i++;
    394   }
     418  while (known_os2shells[i] != NULL)
     419    {
     420      if (strcasecmp (name, known_os2shells[i]) == 0)
     421        return 0; /* not a unix shell */
     422      i++;
     423    }
    395424
    396425  /* in doubt assume a unix like shell */
     
    403432is_bourne_compatible_shell (const char *path)
    404433{
    405   /* list of known unix (Bourne-like) shells */
    406   const char *unix_shells[] = {
     434  /* List of known POSIX (or POSIX-ish) shells. */
     435  static const char *unix_shells[] = {
    407436    "sh",
    408437    "bash",
     
    414443    NULL
    415444  };
    416   unsigned i, len;
     445  const char **s;
    417446
    418447  /* find the rightmost '/' or '\\' */
     
    427456    name = path;
    428457
    429   if (*name == '/' || *name == '\\') name++;
     458  if (*name == '/' || *name == '\\')
     459    ++name;
    430460
    431461  /* this should be able to deal with extensions on Windows-like systems */
    432   for (i = 0; unix_shells[i] != NULL; i++) {
    433     len = strlen(unix_shells[i]);
     462  for (s = unix_shells; *s != NULL; ++s)
     463    {
    434464#if defined(WINDOWS32) || defined(__MSDOS__)
    435     if ((strncasecmp (name, unix_shells[i], len) == 0) &&
    436       (strlen(name) >= len && (name[len] == '\0' || name[len] == '.')))
     465      unsigned int len = strlen (*s);
     466      if ((strlen (name) >= len && STOP_SET (name[len], MAP_DOT|MAP_NUL))
     467          && strncasecmp (name, *s, len) == 0)
    437468#else
    438     if ((strncmp (name, unix_shells[i], len) == 0) &&
    439       (strlen(name) >= len && name[len] == '\0'))
    440 #endif
    441         return 1; /* a known unix-style shell */
    442   }
     469      if (strcmp (name, *s) == 0)
     470#endif
     471        return 1; /* a known unix-style shell */
     472    }
    443473
    444474  /* if not on the list, assume it's not a Bourne-like shell */
     
    453483
    454484static void
    455 child_error (const char *target_name,
     485child_error (struct child *child,
    456486             int exit_code, int exit_sig, int coredump, int ignored)
    457487{
     488  const char *pre = "*** ";
     489  const char *post = "";
     490  const char *dump = "";
     491  const struct file *f = child->file;
     492  const floc *flocp = &f->cmds->fileinfo;
     493  const char *nm;
     494  size_t l;
     495
    458496  if (ignored && silent_flag)
    459497    return;
    460498
    461 #ifdef VMS
    462   if (!(exit_code & 1))
    463       error (NILF,
    464              (ignored ? _("*** [%s] Error 0x%x (ignored)")
    465               : _("*** [%s] Error 0x%x")),
    466              target_name, exit_code);
    467 #else
     499  if (exit_sig && coredump)
     500    dump = _(" (core dumped)");
     501
     502  if (ignored)
     503    {
     504      pre = "";
     505      post = _(" (ignored)");
     506    }
     507
     508  if (! flocp->filenm)
     509    nm = _("<builtin>");
     510  else
     511    {
     512      char *a = alloca (strlen (flocp->filenm) + 1 + 11 + 1);
     513      sprintf (a, "%s:%lu", flocp->filenm, flocp->lineno + flocp->offset);
     514      nm = a;
     515    }
     516
     517  l = strlen (pre) + strlen (nm) + strlen (f->name) + strlen (post);
     518
     519  OUTPUT_SET (&child->output);
     520
     521  show_goal_error ();
     522
    468523  if (exit_sig == 0)
    469524# if defined(KMK) && defined(KBUILD_OS_WINDOWS)
    470525    {
    471       const char *name = NULL;
     526      const char *exit_name = NULL;
    472527      switch ((unsigned)exit_code)
    473528        {
    474         case 0xc0000005U: name = "STATUS_ACCESS_VIOLATION"; break;
    475         case 0xc000013aU: name = "STATUS_CONTROL_C_EXIT"; break;
    476         case 0xc0000374U: name = "STATUS_HEAP_CORRUPTION"; break;
    477         case 0xc0000409U: name = "STATUS_STACK_BUFFER_OVERRUN"; break;
    478         case 0xc0000417U: name = "STATUS_INVALID_CRUNTIME_PARAMETER"; break;
    479         case 0x80000003U: name = "STATUS_BREAKPOINT"; break;
    480         case 0x40000015U: name = "STATUS_FATAL_APP_EXIT"; break;
    481         case 0x40010004U: name = "DBG_TERMINATE_PROCESS"; break;
    482         case 0x40010005U: name = "DBG_CONTROL_C"; break;
    483         case 0x40010008U: name = "DBG_CONTROL_BREAK"; break;
     529        case 0xc0000005U: exit_name = "STATUS_ACCESS_VIOLATION"; break;
     530        case 0xc000013aU: exit_name = "STATUS_CONTROL_C_EXIT"; break;
     531        case 0xc0000374U: exit_name = "STATUS_HEAP_CORRUPTION"; break;
     532        case 0xc0000409U: exit_name = "STATUS_STACK_BUFFER_OVERRUN"; break;
     533        case 0xc0000417U: exit_name = "STATUS_INVALID_CRUNTIME_PARAMETER"; break;
     534        case 0x80000003U: exit_name = "STATUS_BREAKPOINT"; break;
     535        case 0x40000015U: exit_name = "STATUS_FATAL_APP_EXIT"; break;
     536        case 0x40010004U: exit_name = "DBG_TERMINATE_PROCESS"; break;
     537        case 0x40010005U: exit_name = "DBG_CONTROL_C"; break;
     538        case 0x40010008U: exit_name = "DBG_CONTROL_BREAK"; break;
    484539        }
    485       if (name)
    486         error(NILF, ignored ? _("[%s] Error %d (%s) (ignored)") :
    487                _("*** [%s] Error %d (%s)"),
    488                target_name, exit_code, name);
     540      if (exit_name)
     541        error (NILF, l + strlen (exit_name) + INTSTR_LENGTH,
     542               _("%s[%s: %s] Error %d (%s)%s"),
     543               pre, nm, f->name, exit_code, exit_name, post);
    489544      else
    490         error(NILF, ignored ? _("[%s] Error %d (%#x) (ignored)") :
    491                _("*** [%s] Error %d (%#x)"),
    492                target_name, exit_code, exit_code);
     545        error (NILF, l + INTSTR_LENGTH + INTSTR_LENGTH,
     546               _("%s[%s: %s] Error %d (%#x)%s"),
     547               pre, nm, f->name, exit_code, exit_code, post);
    493548    }
    494549# else
    495     error (NILF, ignored ? _("[%s] Error %d (ignored)") :
    496            _("*** [%s] Error %d"),
    497            target_name, exit_code);
     550    error (NILF, l + INTSTR_LENGTH,
     551           _("%s[%s: %s] Error %d%s"), pre, nm, f->name, exit_code, post);
    498552# endif
    499553  else
    500     error (NILF, "*** [%s] %s%s",
    501            target_name, strsignal (exit_sig),
    502            coredump ? _(" (core dumped)") : "");
    503 #endif /* VMS */
     554    {
     555      const char *s = strsignal (exit_sig);
     556      error (NILF, l + strlen (s) + strlen (dump),
     557             "%s[%s: %s] %s%s%s", pre, nm, f->name, s, dump, post);
     558    }
     559
     560  OUTPUT_UNSET ();
    504561}
    505562
     
    508565/* Handle a dead child.  This handler may or may not ever be installed.
    509566
    510    If we're using the jobserver feature, we need it.  First, installing it
    511    ensures the read will interrupt on SIGCHLD.  Second, we close the dup'd
    512    read FD to ensure we don't enter another blocking read without reaping all
    513    the dead children.  In this case we don't need the dead_children count.
     567   If we're using the jobserver feature without pselect(), we need it.
     568   First, installing it ensures the read will interrupt on SIGCHLD.  Second,
     569   we close the dup'd read FD to ensure we don't enter another blocking read
     570   without reaping all the dead children.  In this case we don't need the
     571   dead_children count.
    514572
    515573   If we don't have either waitpid or wait3, then make is unreliable, but we
     
    523581  ++dead_children;
    524582
    525   if (job_rfd >= 0)
    526     {
    527       close (job_rfd);
    528       job_rfd = -1;
    529     }
     583  jobserver_signal ();
    530584
    531585#if defined __EMX__ && !defined(__INNOTEK_LIBC__) /* bird */
     
    533587  signal (SIGCHLD, SIG_DFL);
    534588#endif
    535 
    536   /* This causes problems if the SIGCHLD interrupts a printf().
    537   DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
    538   */
    539589}
    540590
    541 extern int shell_function_pid, shell_function_completed;
     591extern pid_t shell_function_pid;
    542592
    543593/* Reap all dead children, storing the returned status and the new command
    544    state (`cs_finished') in the `file' member of the `struct child' for the
     594   state ('cs_finished') in the 'file' member of the 'struct child' for the
    545595   dead child, and removing the child from the chain.  In addition, if BLOCK
    546596   nonzero, we block in this function until we've reaped at least one
     
    553603#ifndef WINDOWS32
    554604  WAIT_T status;
     605#endif
    555606  /* Initially, assume we have some.  */
    556607  int reap_more = 1;
    557 #endif
    558608
    559609#ifdef WAIT_NOHANG
     
    574624         && (block || REAP_MORE))
    575625    {
    576       int remote = 0;
     626      unsigned int remote = 0;
    577627      pid_t pid;
    578628      int exit_code, exit_sig, coredump;
    579       register struct child *lastc, *c;
     629      struct child *lastc, *c;
    580630      int child_failed;
    581631      int any_remote, any_local;
     
    586636
    587637      if (err && block)
    588         {
     638        {
    589639          static int printed = 0;
    590640
    591           /* We might block for a while, so let the user know why.
     641          /* We might block for a while, so let the user know why.
    592642             Only print this message once no matter how many jobs are left.  */
    593           fflush (stdout);
     643          fflush (stdout);
    594644          if (!printed)
    595             error (NILF, _("*** Waiting for unfinished jobs...."));
     645            O (error, NILF, _("*** Waiting for unfinished jobs...."));
    596646          printed = 1;
    597         }
     647        }
    598648
    599649      /* We have one less dead child to reap.  As noted in
    600         child_handler() above, this count is completely unimportant for
    601         all modern, POSIX-y systems that support wait3() or waitpid().
    602         The rest of this comment below applies only to early, broken
    603         pre-POSIX systems.  We keep the count only because... it's there...
    604 
    605         The test and decrement are not atomic; if it is compiled into:
    606                 register = dead_children - 1;
    607                 dead_children = register;
    608         a SIGCHLD could come between the two instructions.
    609         child_handler increments dead_children.
    610         The second instruction here would lose that increment.  But the
    611         only effect of dead_children being wrong is that we might wait
    612         longer than necessary to reap a child, and lose some parallelism;
    613         and we might print the "Waiting for unfinished jobs" message above
    614         when not necessary.  */
     650        child_handler() above, this count is completely unimportant for
     651        all modern, POSIX-y systems that support wait3() or waitpid().
     652        The rest of this comment below applies only to early, broken
     653        pre-POSIX systems.  We keep the count only because... it's there...
     654
     655        The test and decrement are not atomic; if it is compiled into:
     656                register = dead_children - 1;
     657                dead_children = register;
     658        a SIGCHLD could come between the two instructions.
     659        child_handler increments dead_children.
     660        The second instruction here would lose that increment.  But the
     661        only effect of dead_children being wrong is that we might wait
     662        longer than necessary to reap a child, and lose some parallelism;
     663        and we might print the "Waiting for unfinished jobs" message above
     664        when not necessary.  */
    615665
    616666      if (dead_children > 0)
    617         --dead_children;
     667        --dead_children;
    618668
    619669      any_remote = 0;
    620670      any_local = shell_function_pid != 0;
    621671      for (c = children; c != 0; c = c->next)
    622         {
    623           any_remote |= c->remote;
    624           any_local |= ! c->remote;
     672        {
     673          any_remote |= c->remote;
     674          any_local |= ! c->remote;
    625675#ifdef CONFIG_WITH_KMK_BUILTIN
    626676          if (c->has_status)
     
    634684          else
    635685#endif
    636           DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
    637                         (void *)c, c->file->name, pid2str (c->pid),
    638                         c->remote ? _(" (remote)") : ""));
     686            DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
     687                          (void *)c, c->file->name, pid2str (c->pid),
     688                          c->remote ? _(" (remote)") : ""));
    639689#ifdef VMS
    640           break;
    641 #endif
    642         }
     690          break;
     691#endif
     692        }
    643693
    644694      /* First, check for remote children.  */
    645695      if (any_remote)
    646         pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
     696        pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
    647697      else
    648         pid = 0;
     698        pid = 0;
    649699
    650700      if (pid > 0)
    651         /* We got a remote child.  */
    652         remote = 1;
     701        /* We got a remote child.  */
     702        remote = 1;
    653703      else if (pid < 0)
    654         {
     704        {
    655705          /* A remote status command failed miserably.  Punt.  */
    656         remote_status_lose:
    657           pfatal_with_name ("remote_status");
    658         }
     706        remote_status_lose:
     707          pfatal_with_name ("remote_status");
     708        }
    659709      else
    660         {
    661           /* No remote children.  Check for local children.  */
     710        {
     711          /* No remote children.  Check for local children.  */
    662712#ifdef CONFIG_WITH_KMK_BUILTIN
    663713          if (completed_child)
     
    675725#endif /* CONFIG_WITH_KMK_BUILTIN */
    676726#if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
    677           if (any_local)
    678             {
     727          if (any_local)
     728            {
    679729#ifdef VMS
    680               vmsWaitForChildren (&status);
    681               pid = c->pid;
     730              /* Todo: This needs more untangling multi-process support */
     731              /* Just do single child process support now */
     732              vmsWaitForChildren (&status);
     733              pid = c->pid;
     734
     735              /* VMS failure status can not be fully translated */
     736              status = $VMS_STATUS_SUCCESS (c->cstatus) ? 0 : (1 << 8);
     737
     738              /* A Posix failure can be exactly translated */
     739              if ((c->cstatus & VMS_POSIX_EXIT_MASK) == VMS_POSIX_EXIT_MASK)
     740                status = (c->cstatus >> 3 & 255) << 8;
    682741#else
    683742#ifdef WAIT_NOHANG
    684               if (!block)
    685                 pid = WAIT_NOHANG (&status);
    686               else
    687 #endif
    688                 EINTRLOOP(pid, wait (&status));
     743              if (!block)
     744                pid = WAIT_NOHANG (&status);
     745              else
     746#endif
     747                EINTRLOOP (pid, wait (&status));
    689748#endif /* !VMS */
    690             }
    691           else
    692             pid = 0;
    693 
    694           if (pid < 0)
    695             {
     749            }
     750          else
     751            pid = 0;
     752
     753          if (pid < 0)
     754            {
    696755              /* The wait*() failed miserably.  Punt.  */
    697               pfatal_with_name ("wait");
    698             }
    699           else if (pid > 0)
    700             {
    701               /* We got a child exit; chop the status word up.  */
    702               exit_code = WEXITSTATUS (status);
    703               exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
    704               coredump = WCOREDUMP (status);
     756              pfatal_with_name ("wait");
     757            }
     758          else if (pid > 0)
     759            {
     760              /* We got a child exit; chop the status word up.  */
     761              exit_code = WEXITSTATUS (status);
     762              exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
     763              coredump = WCOREDUMP (status);
    705764
    706765              /* If we have started jobs in this second, remove one.  */
    707766              if (job_counter)
    708767                --job_counter;
    709             }
    710           else
    711             {
    712               /* No local children are dead.  */
     768            }
     769          else
     770            {
     771              /* No local children are dead.  */
    713772              reap_more = 0;
    714773
    715               if (!block || !any_remote)
     774              if (!block || !any_remote)
    716775                break;
    717776
     
    726785              /* We got a remote child.  */
    727786              remote = 1;
    728             }
     787            }
    729788#endif /* !__MSDOS__, !Amiga, !WINDOWS32.  */
    730789
    731790#ifdef __MSDOS__
    732           /* Life is very different on MSDOS.  */
    733           pid = dos_pid - 1;
    734           status = dos_status;
    735           exit_code = WEXITSTATUS (status);
    736           if (exit_code == 0xff)
    737             exit_code = -1;
    738           exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
    739           coredump = 0;
     791          /* Life is very different on MSDOS.  */
     792          pid = dos_pid - 1;
     793          status = dos_status;
     794          exit_code = WEXITSTATUS (status);
     795          if (exit_code == 0xff)
     796            exit_code = -1;
     797          exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
     798          coredump = 0;
    740799#endif /* __MSDOS__ */
    741800#ifdef _AMIGA
    742           /* Same on Amiga */
    743           pid = amiga_pid - 1;
    744           status = amiga_status;
    745           exit_code = amiga_status;
    746           exit_sig = 0;
    747           coredump = 0;
     801          /* Same on Amiga */
     802          pid = amiga_pid - 1;
     803          status = amiga_status;
     804          exit_code = amiga_status;
     805          exit_sig = 0;
     806          coredump = 0;
    748807#endif /* _AMIGA */
    749808#ifdef WINDOWS32
    750809          {
    751810            HANDLE hPID;
    752             int werr;
    753811            HANDLE hcTID, hcPID;
     812            DWORD dwWaitStatus = 0;
    754813            exit_code = 0;
    755814            exit_sig = 0;
     
    768827                    fprintf (stderr,
    769828                             "Determine main thread ID (Error %ld: %s)\n",
    770                              e, map_windows32_error_to_string(e));
     829                             e, map_windows32_error_to_string (e));
    771830                  }
    772831                else
     
    775834
    776835            /* wait for anything to finish */
    777             hPID = process_wait_for_any();
     836            hPID = process_wait_for_any (block, &dwWaitStatus);
    778837            if (hPID)
    779838              {
    780 
    781839                /* was an error found on this process? */
    782                 werr = process_last_err(hPID);
     840                int werr = process_last_err (hPID);
    783841
    784842                /* get exit data */
    785                 exit_code = process_exit_code(hPID);
     843                exit_code = process_exit_code (hPID);
    786844
    787845                if (werr)
    788                   fprintf(stderr, "make (e=%d): %s",
    789                           exit_code, map_windows32_error_to_string(exit_code));
     846                  fprintf (stderr, "make (e=%d): %s", exit_code,
     847                           map_windows32_error_to_string (exit_code));
    790848
    791849                /* signal */
    792                 exit_sig = process_signal(hPID);
     850                exit_sig = process_signal (hPID);
    793851
    794852                /* cleanup process */
    795                 process_cleanup(hPID);
     853                process_cleanup (hPID);
    796854
    797855                coredump = 0;
    798856              }
    799             else if (!process_used_slots())
     857            else if (dwWaitStatus == WAIT_FAILED)
    800858              {
    801                 /* The wait*() failed miserably.  Punt.  */
    802                 errno = ECHILD;
    803                 pfatal_with_name ("wait");
     859                /* The WaitForMultipleObjects() failed miserably.  Punt.  */
     860                pfatal_with_name ("WaitForMultipleObjects");
     861              }
     862            else if (dwWaitStatus == WAIT_TIMEOUT)
     863              {
     864                /* No child processes are finished.  Give up waiting. */
     865                reap_more = 0;
     866                break;
    804867              }
    805868
     
    807870          }
    808871#endif /* WINDOWS32 */
    809         }
    810 
    811       /* Check if this is the child of the `shell' function.  */
     872        }
     873
     874      /* Check if this is the child of the 'shell' function.  */
    812875      if (!remote && pid == shell_function_pid)
    813         {
    814           /* It is.  Leave an indicator for the `shell' function.  */
    815           if (exit_sig == 0 && exit_code == 127)
    816             shell_function_completed = -1;
    817           else
    818             shell_function_completed = 1;
    819           break;
    820         }
    821 
    822       child_failed = exit_sig != 0 || exit_code != 0;
     876        {
     877          shell_completed (exit_code, exit_sig);
     878          break;
     879        }
    823880
    824881      /* Search for a child matching the deceased one.  */
    825882      lastc = 0;
    826883      for (c = children; c != 0; lastc = c, c = c->next)
    827         if (c->remote == remote && c->pid == pid)
    828           break;
     884        if (c->pid == pid && c->remote == remote)
     885          break;
    829886
    830887      if (c == 0)
     
    833890        continue;
    834891
     892      /* Determine the failure status: 0 for success, 1 for updating target in
     893         question mode, 2 for anything else.  */
     894      if (exit_sig == 0 && exit_code == 0)
     895        child_failed = MAKE_SUCCESS;
     896      else if (exit_sig == 0 && exit_code == 1 && question_flag && c->recursive)
     897        child_failed = MAKE_TROUBLE;
     898      else
     899        child_failed = MAKE_FAILURE;
     900
    835901      DB (DB_JOBS, (child_failed
    836902                    ? _("Reaping losing child %p PID %s %s\n")
     
    838904                    (void *)c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
    839905
    840       if (c->sh_batch_file) {
    841         DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
    842                       c->sh_batch_file));
    843 
    844         /* just try and remove, don't care if this fails */
    845         remove (c->sh_batch_file);
    846 
    847         /* all done with memory */
    848         free (c->sh_batch_file);
    849         c->sh_batch_file = NULL;
    850       }
     906      if (c->sh_batch_file)
     907        {
     908          int rm_status;
     909
     910          DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
     911                        c->sh_batch_file));
     912
     913          errno = 0;
     914          rm_status = remove (c->sh_batch_file);
     915          if (rm_status)
     916            DB (DB_JOBS, (_("Cleaning up temp batch file %s failed (%d)\n"),
     917                          c->sh_batch_file, errno));
     918
     919          /* all done with memory */
     920          free (c->sh_batch_file);
     921          c->sh_batch_file = NULL;
     922        }
    851923
    852924      /* If this child had the good stdin, say it is now free.  */
     
    862934          static int delete_on_error = -1;
    863935
    864           if (!dontcare)
     936          if (!dontcare && child_failed == MAKE_FAILURE)
    865937#ifdef KMK
    866938            {
    867               child_error (c->file->name, exit_code, exit_sig, coredump, 0);
     939              child_error (c, exit_code, exit_sig, coredump, 0);
    868940              if (   (  c->file->cmds->lines_flags[c->command_line - 1]
    869941                      & (COMMANDS_SILENT | COMMANDS_RECURSE))
     
    873945# endif
    874946                  || exit_sig != 0)
    875                 message (0, "The failing command:\n%s", c->file->cmds->command_lines[c->command_line - 1]);
     947                OS (message, 0, "The failing command:\n%s", c->file->cmds->command_lines[c->command_line - 1]);
    876948            }
    877949#else  /* !KMK */
    878             child_error (c->file->name, exit_code, exit_sig, coredump, 0);
     950            child_error (c, exit_code, exit_sig, coredump, 0);
    879951#endif /* !KMK */
    880952
    881           c->file->update_status = 2;
     953          c->file->update_status = child_failed == MAKE_FAILURE ? us_failed : us_question;
    882954          if (delete_on_error == -1)
    883955            {
     
    893965            {
    894966              /* The commands failed, but we don't care.  */
    895               child_error (c->file->name,
    896                            exit_code, exit_sig, coredump, 1);
     967              child_error (c, exit_code, exit_sig, coredump, 1);
    897968              child_failed = 0;
    898969            }
     
    907978                     the target was not completely remade.  So we treat
    908979                     this as if a command had failed.  */
    909                   c->file->update_status = 2;
     980                  c->file->update_status = us_failed;
    910981                }
    911982              else
    912983                {
     984#ifndef NO_OUTPUT_SYNC
     985                  /* If we're sync'ing per line, write the previous line's
     986                     output before starting the next one.  */
     987                  if (output_sync == OUTPUT_SYNC_LINE)
     988                    output_dump (&c->output);
     989#endif
    913990                  /* Check again whether to start remotely.
    914991                     Whether or not we want to changes over time.
     
    9281005                }
    9291006
    930               if (c->file->update_status != 0)
     1007              if (c->file->update_status != us_success)
    9311008                /* We failed to start the commands.  */
    9321009                delete_child_targets (c);
     
    9361013               without an unignored error.  Now the target has been
    9371014               successfully updated.  */
    938             c->file->update_status = 0;
     1015            c->file->update_status = us_success;
    9391016        }
    9401017
    941       /* When we get here, all the commands for C->file are finished
    942          (or aborted) and C->file->update_status contains 0 or 2.  But
    943          C->file->command_state is still cs_running if all the commands
     1018      /* When we get here, all the commands for c->file are finished.  */
     1019
     1020#ifndef NO_OUTPUT_SYNC
     1021      /* Synchronize any remaining parallel output.  */
     1022      output_dump (&c->output);
     1023#endif
     1024
     1025      /* At this point c->file->update_status is success or failed.  But
     1026         c->file->command_state is still cs_running if all the commands
    9441027         ran; notice_finish_file looks for cs_running to tell it that
    9451028         it's interesting to check the file's modtime again now.  */
     
    9801063          /* fatal_error_signal will die with the right signal.  */
    9811064          !handling_fatal_signal)
    982         die (2);
     1065        die (child_failed);
    9831066
    9841067      /* Only block for one child.  */
     
    9981081  print_job_time (child);
    9991082#endif
     1083  output_close (&child->output);
     1084
    10001085  if (!jobserver_tokens)
    1001     fatal (NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
    1002            (void *)child, child->file->name);
     1086    ONS (fatal, NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
     1087         child, child->file->name);
    10031088
    10041089  /* If we're using the jobserver and this child is not the only outstanding
    10051090     job, put a token back into the pipe for it.  */
    10061091
    1007   if (job_fds[1] >= 0 && jobserver_tokens > 1)
    1008     {
    1009       char token = '+';
    1010       int r;
    1011 
    1012       /* Write a job token back to the pipe.  */
    1013 
    1014       EINTRLOOP (r, write (job_fds[1], &token, 1));
    1015       if (r != 1)
    1016         pfatal_with_name (_("write jobserver"));
    1017 
     1092  if (jobserver_enabled () && jobserver_tokens > 1)
     1093    {
     1094      jobserver_release (1);
    10181095      DB (DB_JOBS, (_("Released token for child %p (%s).\n"),
    10191096                    (void *)child, child->file->name));
     
    10291106      register unsigned int i;
    10301107      for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
    1031         free (child->command_lines[i]);
     1108        free (child->command_lines[i]);
    10321109      free (child->command_lines);
    10331110    }
     
    10371114      register char **ep = child->environment;
    10381115      while (*ep != 0)
    1039         free (*ep++);
     1116        free (*ep++);
    10401117      free (child->environment);
    10411118    }
     
    10811158#endif
    10821159
    1083 #ifdef MAKE_JOBSERVER
    1084 RETSIGTYPE
    1085 job_noop (int sig UNUSED)
    1086 {
    1087 }
    1088 /* Set the child handler action flags to FLAGS.  */
    1089 static void
    1090 set_child_handler_action_flags (int set_handler, int set_alarm)
    1091 {
    1092   struct sigaction sa;
    1093   int rval = 0;
    1094 
    1095 #if defined(__EMX__) && !defined(__KLIBC__) /* bird */
    1096   /* The child handler must be turned off here.  */
    1097   signal (SIGCHLD, SIG_DFL);
    1098 #endif
    1099 
    1100   memset (&sa, '\0', sizeof sa);
    1101   sa.sa_handler = child_handler;
    1102   sa.sa_flags = set_handler ? 0 : SA_RESTART;
    1103 #if defined SIGCHLD
    1104   rval = sigaction (SIGCHLD, &sa, NULL);
    1105 #endif
    1106 #if defined SIGCLD && SIGCLD != SIGCHLD
    1107   rval = sigaction (SIGCLD, &sa, NULL);
    1108 #endif
    1109   if (rval != 0)
    1110     fprintf (stderr, "sigaction: %s (%d)\n", strerror (errno), errno);
    1111 #if defined SIGALRM
    1112   if (set_alarm)
    1113     {
    1114       /* If we're about to enter the read(), set an alarm to wake up in a
    1115          second so we can check if the load has dropped and we can start more
    1116          work.  On the way out, turn off the alarm and set SIG_DFL.  */
    1117       alarm (set_handler ? 1 : 0);
    1118       sa.sa_handler = set_handler ? job_noop : SIG_DFL;
    1119       sa.sa_flags = 0;
    1120       sigaction (SIGALRM, &sa, NULL);
    1121     }
    1122 #endif
    1123 }
    1124 #endif
    1125 
    1126 
    11271160/* Start a job to run the commands specified in CHILD.
    11281161   CHILD is updated to reflect the commands and ID of the child process.
    11291162
    11301163   NOTE: On return fatal signals are blocked!  The caller is responsible
    1131    for calling `unblock_sigs', once the new child is safely on the chain so
     1164   for calling 'unblock_sigs', once the new child is safely on the chain so
    11321165   it can be cleaned up in the event of a fatal signal.  */
    11331166
     
    11351168start_job_command (struct child *child)
    11361169{
    1137 #if !defined(_AMIGA) && !defined(WINDOWS32)
    1138   static int bad_stdin = -1;
    1139 #endif
     1170  int flags;
    11401171  char *p;
    1141   /* Must be volatile to silence bogus GCC warning about longjmp/vfork.  */
    1142   /*volatile*/ int flags;
    11431172#ifdef VMS
    11441173  char *argv;
     
    11631192     the flags specified globally for this target.  */
    11641193  flags = (child->file->command_flags
    1165            | child->file->cmds->lines_flags[child->command_line - 1]);
     1194           | child->file->cmds->lines_flags[child->command_line - 1]);
    11661195
    11671196  p = child->command_ptr;
     
    11711200    {
    11721201      if (*p == '@')
    1173         flags |= COMMANDS_SILENT;
     1202        flags |= COMMANDS_SILENT;
    11741203      else if (*p == '+')
    1175         flags |= COMMANDS_RECURSE;
     1204        flags |= COMMANDS_RECURSE;
    11761205      else if (*p == '-')
    1177         child->noerror = 1;
     1206        child->noerror = 1;
    11781207#ifdef CONFIG_WITH_COMMANDS_FUNC
    11791208      else if (*p == '%')
    11801209        flags |= COMMAND_GETTER_SKIP_IT;
    11811210#endif
    1182       else if (!isblank ((unsigned char)*p))
     1211      /* Don't skip newlines.  */
     1212      else if (!ISBLANK (*p))
    11831213#ifndef CONFIG_WITH_KMK_BUILTIN
    11841214        break;
     
    11951225    }
    11961226
     1227  child->recursive = ((flags & COMMANDS_RECURSE) != 0);
     1228
    11971229  /* Update the file's command flags with any new ones we found.  We only
    11981230     keep the COMMANDS_RECURSE setting.  Even this isn't 100% correct; we are
     
    12011233     order to really fix this, we'll have to keep a lines_flags for every
    12021234     actual line, after expansion.  */
    1203   child->file->cmds->lines_flags[child->command_line - 1]
    1204     |= flags & COMMANDS_RECURSE;
     1235  child->file->cmds->lines_flags[child->command_line - 1] |= flags & COMMANDS_RECURSE;
     1236
     1237  /* POSIX requires that a recipe prefix after a backslash-newline should
     1238     be ignored.  Remove it now so the output is correct.  */
     1239  {
     1240    char prefix = child->file->cmds->recipe_prefix;
     1241    char *p1, *p2;
     1242    p1 = p2 = p;
     1243    while (*p1 != '\0')
     1244      {
     1245        *(p2++) = *p1;
     1246        if (p1[0] == '\n' && p1[1] == prefix)
     1247          ++p1;
     1248        ++p1;
     1249      }
     1250    *p2 = *p1;
     1251  }
    12051252
    12061253  /* Figure out an argument list from this command line.  */
    1207 
    12081254  {
    12091255    char *end = 0;
    12101256#ifdef VMS
     1257    /* Skip any leading whitespace */
     1258    while (*p)
     1259      {
     1260        if (!ISSPACE (*p))
     1261          {
     1262            if (*p != '\\')
     1263              break;
     1264            if ((p[1] != '\n') && (p[1] != 'n') && (p[1] != 't'))
     1265              break;
     1266          }
     1267        p++;
     1268      }
     1269
    12111270    argv = p;
     1271    /* Although construct_command_argv contains some code for VMS, it was/is
     1272       not called/used.  Please note, for VMS argv is a string (not an array
     1273       of strings) which contains the complete command line, which for
     1274       multi-line variables still includes the newlines.  So detect newlines
     1275       and set 'end' (which is used for child->command_ptr) instead of
     1276       (re-)writing construct_command_argv */
     1277    if (!one_shell)
     1278      {
     1279        char *s = p;
     1280        int instring = 0;
     1281        while (*s)
     1282          {
     1283            if (*s == '"')
     1284              instring = !instring;
     1285            else if (*s == '\\' && !instring && *(s+1) != 0)
     1286              s++;
     1287            else if (*s == '\n' && !instring)
     1288              {
     1289                end = s;
     1290                break;
     1291              }
     1292            ++s;
     1293          }
     1294      }
    12121295#else
    12131296    argv = construct_command_argv (p, &end, child->file,
    1214                                    child->file->cmds->lines_flags[child->command_line - 1],
    1215                                    &child->sh_batch_file);
     1297                                   child->file->cmds->lines_flags[child->command_line - 1],
     1298                                   &child->sh_batch_file);
    12161299#endif
    12171300    if (end == NULL)
     
    12191302    else
    12201303      {
    1221         *end++ = '\0';
    1222         child->command_ptr = end;
     1304        *end++ = '\0';
     1305        child->command_ptr = end;
    12231306      }
    12241307  }
    12251308
    1226   /* If -q was given, say that updating `failed' if there was any text on the
    1227      command line, or `succeeded' otherwise.  The exit status of 1 tells the
    1228      user that -q is saying `something to do'; the exit status for a random
     1309  /* If -q was given, say that updating 'failed' if there was any text on the
     1310     command line, or 'succeeded' otherwise.  The exit status of 1 tells the
     1311     user that -q is saying 'something to do'; the exit status for a random
    12291312     error is 2.  */
    12301313  if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
     
    12341317      free (argv);
    12351318#endif
    1236       child->file->update_status = 1;
    1237       notice_finished_file (child->file);
    1238       return;
     1319#ifdef VMS
     1320      /* On VMS, argv[0] can be a null string here */
     1321      if (argv[0] != 0)
     1322        {
     1323#endif
     1324          child->file->update_status = us_question;
     1325          notice_finished_file (child->file);
     1326          return;
     1327#ifdef VMS
     1328        }
     1329#endif
    12391330    }
    12401331
     
    12421333    {
    12431334      /* Go on to the next command.  It might be the recursive one.
    1244         We construct ARGV only to find the end of the command line.  */
     1335        We construct ARGV only to find the end of the command line.  */
    12451336#ifndef VMS
    12461337      if (argv)
     
    12611352      /* This line has no commands.  Go to the next.  */
    12621353      if (job_next_command (child))
    1263         start_job_command (child);
     1354        start_job_command (child);
    12641355      else
    1265         {
    1266           /* No more commands.  Make sure we're "running"; we might not be if
     1356        {
     1357          /* No more commands.  Make sure we're "running"; we might not be if
    12671358             (e.g.) all commands were skipped due to -n.  */
    12681359          set_command_state (child->file, cs_running);
    1269           child->file->update_status = 0;
    1270           notice_finished_file (child->file);
    1271         }
     1360          child->file->update_status = us_success;
     1361          notice_finished_file (child->file);
     1362        }
     1363
     1364      OUTPUT_UNSET();
    12721365      return;
    12731366    }
    12741367
    1275   /* Print out the command.  If silent, we call `message' with null so it
    1276      can log the working directory before the command's own error messages
    1277      appear.  */
     1368  /* Are we going to synchronize this command's output?  Do so if either we're
     1369     in SYNC_RECURSE mode or this command is not recursive.  We'll also check
     1370     output_sync separately below in case it changes due to error.  */
     1371  child->output.syncout = output_sync && (output_sync == OUTPUT_SYNC_RECURSE
     1372                                          || !(flags & COMMANDS_RECURSE));
     1373  OUTPUT_SET (&child->output);
     1374
     1375#ifndef NO_OUTPUT_SYNC
     1376  if (! child->output.syncout)
     1377    /* We don't want to sync this command: to avoid misordered
     1378       output ensure any already-synced content is written.  */
     1379    output_dump (&child->output);
     1380#endif
     1381
     1382  /* Print the command if appropriate.  */
    12781383#ifdef CONFIG_PRETTY_COMMAND_PRINTING
    12791384  if (   pretty_command_printing
     
    12831388      unsigned i;
    12841389      for (i = 0; argv[i]; i++)
    1285         message (0, "%s'%s'%s", i ? "\t" : "> ", argv[i], argv[i + 1] ? " \\" : "");
     1390        OSSS ( message, 0, "%s'%s'%s", i ? "\t" : "> ", argv[i], argv[i + 1] ? " \\" : "");
    12861391    }
    12871392  else
    12881393#endif /* CONFIG_PRETTY_COMMAND_PRINTING */
    1289     message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
    1290              ? "%s" : (char *) 0, p);
     1394  if (just_print_flag || trace_flag
     1395      || (!(flags & COMMANDS_SILENT) && !silent_flag))
     1396    OS (message, 0, "%s", p);
    12911397
    12921398  /* Tell update_goal_chain that a command has been started on behalf of
     
    13081414  if (
    13091415#if defined __MSDOS__ || defined (__EMX__)
    1310       unixy_shell       /* the test is complicated and we already did it */
     1416      unixy_shell       /* the test is complicated and we already did it */
    13111417#else
    1312       (argv[0] && is_bourne_compatible_shell(argv[0]))
     1418      (argv[0] && is_bourne_compatible_shell (argv[0]))
    13131419#endif
    13141420      && (argv[1] && argv[1][0] == '-'
    1315         &&
    1316             ((argv[1][1] == 'c' && argv[1][2] == '\0')
    1317           ||
    1318              (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
     1421        &&
     1422            ((argv[1][1] == 'c' && argv[1][2] == '\0')
     1423          ||
     1424             (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
    13191425      && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
    13201426      && argv[3] == NULL)
     
    13951501#endif /* CONFIG_WITH_KMK_BUILTIN */
    13961502
     1503  /* We're sure we're going to invoke a command: set up the output.  */
     1504  output_start ();
     1505
    13971506  /* Flush the output streams so they won't have things written twice.  */
    13981507
     
    14001509  fflush (stderr);
    14011510
    1402 #ifndef VMS
    1403 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
    1404 
    1405   /* Set up a bad standard input that reads from a broken pipe.  */
    1406 
    1407   if (bad_stdin == -1)
    1408     {
    1409       /* Make a file descriptor that is the read end of a broken pipe.
    1410          This will be used for some children's standard inputs.  */
    1411       int pd[2];
    1412       if (pipe (pd) == 0)
    1413         {
    1414           /* Close the write side.  */
    1415           (void) close (pd[1]);
    1416           /* Save the read side.  */
    1417           bad_stdin = pd[0];
    1418 
    1419           /* Set the descriptor to close on exec, so it does not litter any
    1420              child's descriptor table.  When it is dup2'd onto descriptor 0,
    1421              that descriptor will not close on exec.  */
    1422           CLOSE_ON_EXEC (bad_stdin);
    1423         }
    1424     }
    1425 
    1426 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
    1427 
    1428   /* Decide whether to give this child the `good' standard input
    1429      (one that points to the terminal or whatever), or the `bad' one
     1511  /* Decide whether to give this child the 'good' standard input
     1512     (one that points to the terminal or whatever), or the 'bad' one
    14301513     that points to the read side of a broken pipe.  */
    14311514
     
    14331516  if (child->good_stdin)
    14341517    good_stdin_used = 1;
    1435 
    1436 #endif /* !VMS */
    14371518
    14381519  child->deleted = 0;
     
    14521533      int is_remote, id, used_stdin;
    14531534      if (start_remote_job (argv, child->environment,
    1454                             child->good_stdin ? 0 : bad_stdin,
    1455                             &is_remote, &id, &used_stdin))
     1535                            child->good_stdin ? 0 : get_bad_stdin (),
     1536                            &is_remote, &id, &used_stdin))
    14561537        /* Don't give up; remote execution may fail for various reasons.  If
    14571538           so, simply run the job locally.  */
    1458         goto run_local;
     1539        goto run_local;
    14591540      else
    1460         {
    1461           if (child->good_stdin && !used_stdin)
    1462             {
    1463               child->good_stdin = 0;
    1464               good_stdin_used = 0;
    1465             }
    1466           child->remote = is_remote;
    1467           child->pid = id;
    1468         }
     1541        {
     1542          if (child->good_stdin && !used_stdin)
     1543            {
     1544              child->good_stdin = 0;
     1545              good_stdin_used = 0;
     1546            }
     1547          child->remote = is_remote;
     1548          child->pid = id;
     1549        }
    14691550    }
    14701551  else
     
    14811562
    14821563#ifdef VMS
    1483       if (!child_execute_job (argv, child)) {
    1484         /* Fork failed!  */
    1485         perror_with_name ("vfork", "");
    1486         goto error;
    1487       }
     1564      if (!child_execute_job (child, argv))
     1565        {
     1566          /* Fork failed!  */
     1567          perror_with_name ("fork", "");
     1568          goto error;
     1569        }
    14881570
    14891571#else
     
    14911573      parent_environ = environ;
    14921574
    1493 # ifdef __EMX__
    1494       /* If we aren't running a recursive command and we have a jobserver
    1495          pipe, close it before exec'ing.  */
    1496       if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
    1497         {
    1498           CLOSE_ON_EXEC (job_fds[0]);
    1499           CLOSE_ON_EXEC (job_fds[1]);
    1500         }
    1501       if (job_rfd >= 0)
    1502         CLOSE_ON_EXEC (job_rfd);
    1503 
    1504       /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
    1505       child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
    1506                                       argv, child->environment);
     1575      jobserver_pre_child (flags & COMMANDS_RECURSE);
     1576
     1577      child->pid = child_execute_job (&child->output, child->good_stdin, argv, child->environment);
     1578
     1579      environ = parent_environ; /* Restore value child may have clobbered.  */
     1580      jobserver_post_child (flags & COMMANDS_RECURSE);
     1581
    15071582      if (child->pid < 0)
    1508         {
    1509           /* spawn failed!  */
    1510           unblock_sigs ();
    1511           perror_with_name ("spawn", "");
    1512           goto error;
    1513         }
    1514 
    1515       /* undo CLOSE_ON_EXEC() after the child process has been started */
    1516       if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
    1517         {
    1518           fcntl (job_fds[0], F_SETFD, 0);
    1519           fcntl (job_fds[1], F_SETFD, 0);
    1520         }
    1521       if (job_rfd >= 0)
    1522         fcntl (job_rfd, F_SETFD, 0);
    1523 
    1524 #else  /* !__EMX__ */
    1525       volatile_argv  = argv;            /* shut up gcc */
    1526       volatile_flags = flags;           /* ditto */
    1527 
    1528       child->pid = vfork ();
    1529       environ = parent_environ; /* Restore value child may have clobbered.  */
    1530       argv = volatile_argv;             /* shut up gcc */
    1531       if (child->pid == 0)
    1532         {
    1533           /* We are the child side.  */
    1534           unblock_sigs ();
    1535 
    1536           /* If we aren't running a recursive command and we have a jobserver
    1537              pipe, close it before exec'ing.  */
    1538           if (!(volatile_flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
    1539             {
    1540               close (job_fds[0]);
    1541               close (job_fds[1]);
    1542             }
    1543           if (job_rfd >= 0)
    1544             close (job_rfd);
    1545 
    1546 #ifdef SET_STACK_SIZE
    1547           /* Reset limits, if necessary.  */
    1548           if (stack_limit.rlim_cur)
    1549             setrlimit (RLIMIT_STACK, &stack_limit);
    1550 #endif
    1551 
    1552           child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
    1553                              argv, child->environment);
    1554         }
    1555       else if (child->pid < 0)
    1556         {
    1557           /* Fork failed!  */
    1558           unblock_sigs ();
    1559           perror_with_name ("vfork", "");
    1560           goto error;
    1561         }
    1562 # endif  /* !__EMX__ */
     1583        {
     1584          /* Fork failed!  */
     1585          unblock_sigs ();
     1586          perror_with_name ("fork", "");
     1587          goto error;
     1588        }
    15631589#endif /* !VMS */
    15641590    }
    15651591
    1566 #else   /* __MSDOS__ or Amiga or WINDOWS32 */
     1592#else   /* __MSDOS__ or Amiga or WINDOWS32 */
    15671593#ifdef __MSDOS__
    15681594  {
     
    15721598    dos_status = 0;
    15731599
    1574     /* We call `system' to do the job of the SHELL, since stock DOS
    1575        shell is too dumb.  Our `system' knows how to handle long
     1600    /* We call 'system' to do the job of the SHELL, since stock DOS
     1601       shell is too dumb.  Our 'system' knows how to handle long
    15761602       command lines even if pipes/redirection is needed; it will only
    15771603       call COMMAND.COM when its internal commands are used.  */
    15781604    if (execute_by_shell)
    15791605      {
    1580         char *cmdline = argv[0];
    1581         /* We don't have a way to pass environment to `system',
    1582            so we need to save and restore ours, sigh...  */
    1583         char **parent_environ = environ;
    1584 
    1585         environ = child->environment;
    1586 
    1587         /* If we have a *real* shell, tell `system' to call
    1588            it to do everything for us.  */
    1589         if (unixy_shell)
    1590           {
    1591             /* A *real* shell on MSDOS may not support long
    1592                command lines the DJGPP way, so we must use `system'.  */
    1593             cmdline = argv[2];  /* get past "shell -c" */
    1594           }
    1595 
    1596         dos_command_running = 1;
    1597         proc_return = system (cmdline);
    1598         environ = parent_environ;
    1599         execute_by_shell = 0;   /* for the next time */
     1606        char *cmdline = argv[0];
     1607        /* We don't have a way to pass environment to 'system',
     1608           so we need to save and restore ours, sigh...  */
     1609        char **parent_environ = environ;
     1610
     1611        environ = child->environment;
     1612
     1613        /* If we have a *real* shell, tell 'system' to call
     1614           it to do everything for us.  */
     1615        if (unixy_shell)
     1616          {
     1617            /* A *real* shell on MSDOS may not support long
     1618               command lines the DJGPP way, so we must use 'system'.  */
     1619            cmdline = argv[2];  /* get past "shell -c" */
     1620          }
     1621
     1622        dos_command_running = 1;
     1623        proc_return = system (cmdline);
     1624        environ = parent_environ;
     1625        execute_by_shell = 0;   /* for the next time */
    16001626      }
    16011627    else
    16021628      {
    1603         dos_command_running = 1;
    1604         proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
     1629        dos_command_running = 1;
     1630        proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
    16051631      }
    16061632
     
    16311657     DeleteFile (amiga_bname);        /* Ignore errors.  */
    16321658  }
    1633 #endif  /* Amiga */
     1659#endif  /* Amiga */
    16341660#ifdef WINDOWS32
    16351661  {
    16361662      HANDLE hPID;
    16371663      char* arg0;
     1664      int outfd = FD_STDOUT;
     1665      int errfd = FD_STDERR;
    16381666
    16391667      /* make UNC paths safe for CreateProcess -- backslash format */
     
    16451673
    16461674      /* make sure CreateProcess() has Path it needs */
    1647       sync_Path_environment();
    1648 
    1649       hPID = process_easy(argv, child->environment);
     1675      sync_Path_environment ();
     1676
     1677#ifndef NO_OUTPUT_SYNC
     1678      /* Divert child output if output_sync in use.  */
     1679      if (child->output.syncout)
     1680        {
     1681          if (child->output.out >= 0)
     1682            outfd = child->output.out;
     1683          if (child->output.err >= 0)
     1684            errfd = child->output.err;
     1685        }
     1686#else
     1687      outfd = errfd = -1;
     1688#endif
     1689      hPID = process_easy (argv, child->environment, outfd, errfd);
    16501690
    16511691      if (hPID != INVALID_HANDLE_VALUE)
    16521692        child->pid = (pid_t) hPID;
    1653       else {
    1654         int i;
    1655         unblock_sigs();
    1656         fprintf(stderr,
    1657                 _("process_easy() failed to launch process (e=%ld)\n"),
    1658                 process_last_err(hPID));
    1659         for (i = 0; argv[i]; i++)
    1660           fprintf(stderr, "%s ", argv[i]);
    1661         fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
    1662         goto error;
    1663       }
     1693      else
     1694        {
     1695          int i;
     1696          unblock_sigs ();
     1697          fprintf (stderr,
     1698                   _("process_easy() failed to launch process (e=%ld)\n"),
     1699                   process_last_err (hPID));
     1700          for (i = 0; argv[i]; i++)
     1701            fprintf (stderr, "%s ", argv[i]);
     1702          fprintf (stderr, _("\nCounted %d args in failed launch\n"), i);
     1703          goto error;
     1704        }
    16641705  }
    16651706#endif /* WINDOWS32 */
    1666 #endif  /* __MSDOS__ or Amiga or WINDOWS32 */
     1707#endif  /* __MSDOS__ or Amiga or WINDOWS32 */
    16671708
    16681709  /* Bump the number of jobs started in this second.  */
     
    16831724#endif
    16841725
     1726  OUTPUT_UNSET();
    16851727  return;
    16861728
    16871729 error:
    1688   child->file->update_status = 2;
     1730  child->file->update_status = us_failed;
    16891731  notice_finished_file (child->file);
    16901732#ifdef KMK /* fix leak */
    16911733  goto cleanup_argv;
    16921734#else
    1693   return;
     1735  OUTPUT_UNSET();
    16941736#endif
    16951737}
     
    16971739/* Try to start a child running.
    16981740   Returns nonzero if the child was started (and maybe finished), or zero if
    1699    the load was too high and the child was put on the `waiting_jobs' chain.  */
     1741   the load was too high and the child was put on the 'waiting_jobs' chain.  */
    17001742
    17011743static int
     
    17331775#endif
    17341776#ifdef WINDOWS32
    1735           || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
    1736 #endif
    1737           ))
     1777          || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
     1778#endif
     1779          ))
    17381780    {
    17391781#ifndef CONFIG_WITH_EXTENDED_NOTPARALLEL
     
    17831825    case cs_not_started:
    17841826      /* All the command lines turned out to be empty.  */
    1785       f->update_status = 0;
     1827      f->update_status = us_success;
    17861828      /* FALLTHROUGH */
    17871829
     
    17991841}
    18001842
    1801 /* Create a `struct child' for FILE and start its commands running.  */
     1843/* Create a 'struct child' for FILE and start its commands running.  */
    18021844
    18031845void
     
    18221864#endif
    18231865
     1866  /* Start the command sequence, record it in a new
     1867     'struct child', and add that to the chain.  */
     1868
     1869  c = xcalloc (sizeof (struct child));
     1870  output_init (&c->output);
     1871
     1872  c->file = file;
     1873  c->sh_batch_file = NULL;
     1874
     1875  /* Cache dontcare flag because file->dontcare can be changed once we
     1876     return. Check dontcare inheritance mechanism for details.  */
     1877  c->dontcare = file->dontcare;
     1878
     1879  /* Start saving output in case the expansion uses $(info ...) etc.  */
     1880  OUTPUT_SET (&c->output);
     1881
    18241882  /* Expand the command lines and store the results in LINES.  */
    18251883  lines = xmalloc (cmds->ncommand_lines * sizeof (char *));
     
    18271885    {
    18281886      /* Collapse backslash-newline combinations that are inside variable
    1829         or function references.  These are left alone by the parser so
    1830         that they will appear in the echoing of commands (where they look
    1831         nice); and collapsed by construct_command_argv when it tokenizes.
    1832         But letting them survive inside function invocations loses because
    1833         we don't want the functions to see them as part of the text.  */
     1887        or function references.  These are left alone by the parser so
     1888        that they will appear in the echoing of commands (where they look
     1889        nice); and collapsed by construct_command_argv when it tokenizes.
     1890        But letting them survive inside function invocations loses because
     1891        we don't want the functions to see them as part of the text.  */
    18341892
    18351893      char *in, *out, *ref;
    18361894
    18371895      /* IN points to where in the line we are scanning.
    1838         OUT points to where in the line we are writing.
    1839         When we collapse a backslash-newline combination,
    1840         IN gets ahead of OUT.  */
     1896        OUT points to where in the line we are writing.
     1897        When we collapse a backslash-newline combination,
     1898        IN gets ahead of OUT.  */
    18411899
    18421900      in = out = cmds->command_lines[i];
    18431901      while ((ref = strchr (in, '$')) != 0)
    1844         {
    1845           ++ref;                /* Move past the $.  */
    1846 
    1847           if (out != in)
    1848             /* Copy the text between the end of the last chunk
    1849                we processed (where IN points) and the new chunk
    1850                we are about to process (where REF points).  */
    1851             memmove (out, in, ref - in);
    1852 
    1853           /* Move both pointers past the boring stuff.  */
    1854           out += ref - in;
    1855           in = ref;
    1856 
    1857           if (*ref == '(' || *ref == '{')
    1858             {
    1859               char openparen = *ref;
    1860               char closeparen = openparen == '(' ? ')' : '}';
    1861               int count;
    1862               char *p;
    1863 
    1864               *out++ = *in++;   /* Copy OPENPAREN.  */
    1865               /* IN now points past the opening paren or brace.
    1866                  Count parens or braces until it is matched.  */
    1867               count = 0;
    1868               while (*in != '\0')
    1869                 {
    1870                   if (*in == closeparen && --count < 0)
    1871                     break;
    1872                   else if (*in == '\\' && in[1] == '\n')
    1873                     {
    1874                       /* We have found a backslash-newline inside a
    1875                          variable or function reference.  Eat it and
    1876                          any following whitespace.  */
    1877 
    1878                       int quoted = 0;
    1879                       for (p = in - 1; p > ref && *p == '\\'; --p)
    1880                         quoted = !quoted;
    1881 
    1882                       if (quoted)
    1883                         /* There were two or more backslashes, so this is
    1884                            not really a continuation line.  We don't collapse
    1885                            the quoting backslashes here as is done in
    1886                            collapse_continuations, because the line will
    1887                            be collapsed again after expansion.  */
    1888                         *out++ = *in++;
    1889                       else
    1890                         {
    1891                           /* Skip the backslash, newline and
    1892                              any following whitespace.  */
    1893                           in = next_token (in + 2);
    1894 
    1895                           /* Discard any preceding whitespace that has
    1896                              already been written to the output.  */
    1897                           while (out > ref
    1898                                  && isblank ((unsigned char)out[-1]))
    1899                             --out;
    1900 
    1901                           /* Replace it all with a single space.  */
    1902                           *out++ = ' ';
    1903                         }
    1904                     }
    1905                   else
    1906                     {
    1907                       if (*in == openparen)
    1908                         ++count;
    1909 
    1910                       *out++ = *in++;
    1911                     }
    1912                 }
    1913             }
    1914         }
     1902        {
     1903          ++ref;                /* Move past the $.  */
     1904
     1905          if (out != in)
     1906            /* Copy the text between the end of the last chunk
     1907               we processed (where IN points) and the new chunk
     1908               we are about to process (where REF points).  */
     1909            memmove (out, in, ref - in);
     1910
     1911          /* Move both pointers past the boring stuff.  */
     1912          out += ref - in;
     1913          in = ref;
     1914
     1915          if (*ref == '(' || *ref == '{')
     1916            {
     1917              char openparen = *ref;
     1918              char closeparen = openparen == '(' ? ')' : '}';
     1919              char *outref;
     1920              int count;
     1921              char *p;
     1922
     1923              *out++ = *in++;   /* Copy OPENPAREN.  */
     1924              outref = out;
     1925              /* IN now points past the opening paren or brace.
     1926                 Count parens or braces until it is matched.  */
     1927              count = 0;
     1928              while (*in != '\0')
     1929                {
     1930                  if (*in == closeparen && --count < 0)
     1931                    break;
     1932                  else if (*in == '\\' && in[1] == '\n')
     1933                    {
     1934                      /* We have found a backslash-newline inside a
     1935                         variable or function reference.  Eat it and
     1936                         any following whitespace.  */
     1937
     1938                      int quoted = 0;
     1939                      for (p = in - 1; p > ref && *p == '\\'; --p)
     1940                        quoted = !quoted;
     1941
     1942                      if (quoted)
     1943                        /* There were two or more backslashes, so this is
     1944                           not really a continuation line.  We don't collapse
     1945                           the quoting backslashes here as is done in
     1946                           collapse_continuations, because the line will
     1947                           be collapsed again after expansion.  */
     1948                        *out++ = *in++;
     1949                      else
     1950                        {
     1951                          /* Skip the backslash, newline, and whitespace.  */
     1952                          in += 2;
     1953                          NEXT_TOKEN (in);
     1954
     1955                          /* Discard any preceding whitespace that has
     1956                             already been written to the output.  */
     1957                          while (out > outref && ISBLANK (out[-1]))
     1958                            --out;
     1959
     1960                          /* Replace it all with a single space.  */
     1961                          *out++ = ' ';
     1962                        }
     1963                    }
     1964                  else
     1965                    {
     1966                      if (*in == openparen)
     1967                        ++count;
     1968
     1969                      *out++ = *in++;
     1970                    }
     1971                }
     1972            }
     1973        }
    19151974
    19161975      /* There are no more references in this line to worry about.
    1917         Copy the remaining uninteresting text to the output.  */
     1976        Copy the remaining uninteresting text to the output.  */
    19181977      if (out != in)
    1919         memmove (out, in, strlen (in) + 1);
     1978        memmove (out, in, strlen (in) + 1);
    19201979
    19211980      /* Finally, expand the line.  */
     1981      cmds->fileinfo.offset = i;
    19221982      lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
    1923                                                      file);
    1924     }
    1925 
    1926   /* Start the command sequence, record it in a new
    1927      `struct child', and add that to the chain.  */
    1928 
    1929   c = xcalloc (sizeof (struct child));
    1930   c->file = file;
     1983                                                     file);
     1984    }
     1985
     1986  cmds->fileinfo.offset = 0;
    19311987  c->command_lines = lines;
    1932   c->sh_batch_file = NULL;
    19331988#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
    19341989  c->start_ts = -1;
    19351990#endif
    1936 
    1937   /* Cache dontcare flag because file->dontcare can be changed once we
    1938      return. Check dontcare inheritance mechanism for details.  */
    1939   c->dontcare = file->dontcare;
    19401991
    19411992  /* Fetch the first command line to be run.  */
     
    19622013     this is where the old parallel job code waits, so...  */
    19632014
    1964   else if (job_fds[0] >= 0)
     2015  else if (jobserver_enabled ())
    19652016    while (1)
    19662017      {
    1967         char token;
    1968         int got_token;
    1969         int saved_errno;
     2018        int got_token;
    19702019
    19712020        DB (DB_JOBS, ("Need a job token; we %shave children\n",
     
    19762025          break;
    19772026
    1978         /* Read a token.  As long as there's no token available we'll block.
    1979            We enable interruptible system calls before the read(2) so that if
    1980            we get a SIGCHLD while we're waiting, we'll return with EINTR and
    1981            we can process the death(s) and return tokens to the free pool.
    1982 
    1983            Once we return from the read, we immediately reinstate restartable
    1984            system calls.  This allows us to not worry about checking for
    1985            EINTR on all the other system calls in the program.
    1986 
    1987            There is one other twist: there is a span between the time
    1988            reap_children() does its last check for dead children and the time
    1989            the read(2) call is entered, below, where if a child dies we won't
    1990            notice.  This is extremely serious as it could cause us to
    1991            deadlock, given the right set of events.
    1992 
    1993            To avoid this, we do the following: before we reap_children(), we
    1994            dup(2) the read FD on the jobserver pipe.  The read(2) call below
    1995            uses that new FD.  In the signal handler, we close that FD.  That
    1996            way, if a child dies during the section mentioned above, the
    1997            read(2) will be invoked with an invalid FD and will return
    1998            immediately with EBADF.  */
    1999 
    2000         /* Make sure we have a dup'd FD.  */
    2001         if (job_rfd < 0)
    2002           {
    2003             DB (DB_JOBS, ("Duplicate the job FD\n"));
    2004             job_rfd = dup (job_fds[0]);
    2005           }
     2027        /* Prepare for jobserver token acquisition.  */
     2028        jobserver_pre_acquire ();
    20062029
    20072030        /* Reap anything that's currently waiting.  */
     
    20092032
    20102033        /* Kick off any jobs we have waiting for an opportunity that
    2011            can run now (ie waiting for load). */
     2034           can run now (i.e., waiting for load). */
    20122035        start_waiting_jobs ();
    20132036
    2014         /* If our "free" slot has become available, use it; we don't need an
    2015            actual token.  */
     2037        /* If our "free" slot is available, use it; we don't need a token.  */
    20162038        if (!jobserver_tokens)
    20172039          break;
     
    20202042           waiting for a token. */
    20212043        if (!children)
    2022           fatal (NILF, "INTERNAL: no children as we go to sleep on read\n");
    2023 
    2024         /* Set interruptible system calls, and read() for a job token.  */
    2025         set_child_handler_action_flags (1, waiting_jobs != NULL);
    2026         got_token = read (job_rfd, &token, 1);
    2027         saved_errno = errno;
    2028         set_child_handler_action_flags (0, waiting_jobs != NULL);
     2044          O (fatal, NILF, "INTERNAL: no children as we go to sleep on read\n");
     2045
     2046        /* Get a token.  */
     2047        got_token = jobserver_acquire (waiting_jobs != NULL);
    20292048
    20302049        /* If we got one, we're done here.  */
    2031         if (got_token == 1)
     2050        if (got_token == 1)
    20322051          {
    20332052            DB (DB_JOBS, (_("Obtained token for child %p (%s).\n"),
     
    20352054            break;
    20362055          }
    2037 
    2038         /* If the error _wasn't_ expected (EINTR or EBADF), punt.  Otherwise,
    2039            go back and reap_children(), and try again.  */
    2040         errno = saved_errno;
    2041         if (errno != EINTR && errno != EBADF)
    2042           pfatal_with_name (_("read jobs pipe"));
    2043         if (errno == EBADF)
    2044           DB (DB_JOBS, ("Read returned EBADF.\n"));
    20452056      }
    20462057#endif
    20472058
    20482059  ++jobserver_tokens;
     2060
     2061  /* Trace the build.
     2062     Use message here so that changes to working directories are logged.  */
     2063  if (trace_flag)
     2064    {
     2065      char *newer = allocated_variable_expand_for_file ("$?", c->file);
     2066      const char *nm;
     2067
     2068      if (! cmds->fileinfo.filenm)
     2069        nm = _("<builtin>");
     2070      else
     2071        {
     2072          char *n = alloca (strlen (cmds->fileinfo.filenm) + 1 + 11 + 1);
     2073          sprintf (n, "%s:%lu", cmds->fileinfo.filenm, cmds->fileinfo.lineno);
     2074          nm = n;
     2075        }
     2076
     2077      if (newer[0] == '\0')
     2078        OSS (message, 0,
     2079             _("%s: target '%s' does not exist"), nm, c->file->name);
     2080      else
     2081        OSSS (message, 0,
     2082              _("%s: update target '%s' due to: %s"), nm, c->file->name, newer);
     2083
     2084      free (newer);
     2085    }
    20492086
    20502087  /* The job is now primed.  Start it running.
    20512088     (This will notice if there is in fact no recipe.)  */
    2052   if (cmds->fileinfo.filenm)
    2053     DB (DB_BASIC, (_("Invoking recipe from %s:%lu to update target `%s'.\n"),
    2054                    cmds->fileinfo.filenm, cmds->fileinfo.lineno,
    2055                    c->file->name));
    2056   else
    2057     DB (DB_BASIC, (_("Invoking builtin recipe to update target `%s'.\n"),
    2058                    c->file->name));
    2059 
    2060 
    20612089  start_waiting_job (c);
    20622090
     
    20642092  if (job_slots == 1 || not_parallel)
    20652093    /* Since there is only one job slot, make things run linearly.
    2066        Wait for the child to die, setting the state to `cs_finished'.  */
     2094       Wait for the child to die, setting the state to 'cs_finished'.  */
    20672095    while (file->command_state == cs_running)
    20682096      reap_children (1, 0);
     
    20882116#endif /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
    20892117
     2118  OUTPUT_UNSET ();
    20902119  return;
    20912120}
     
    21022131      /* There are no more lines in the expansion of this line.  */
    21032132      if (child->command_line == child->file->cmds->ncommand_lines)
    2104         {
    2105           /* There are no more lines to be expanded.  */
    2106           child->command_ptr = 0;
    2107           return 0;
    2108         }
     2133        {
     2134          /* There are no more lines to be expanded.  */
     2135          child->command_ptr = 0;
     2136          child->file->cmds->fileinfo.offset = 0;
     2137          return 0;
     2138        }
    21092139      else
    2110         /* Get the next line to run.  */
    2111         child->command_ptr = child->command_lines[child->command_line++];
    2112     }
     2140        /* Get the next line to run.  */
     2141        child->command_ptr = child->command_lines[child->command_line++];
     2142    }
     2143
     2144  child->file->cmds->fileinfo.offset = child->command_line - 1;
    21132145  return 1;
    21142146}
     
    21812213      /* Complain only once for the same error.  */
    21822214      if (lossage == -1 || errno != lossage)
    2183         {
    2184           if (errno == 0)
    2185             /* An errno value of zero means getloadavg is just unsupported.  */
    2186             error (NILF,
    2187                    _("cannot enforce load limits on this operating system"));
    2188           else
    2189             perror_with_name (_("cannot enforce load limit: "), "getloadavg");
    2190         }
     2215        {
     2216          if (errno == 0)
     2217            /* An errno value of zero means getloadavg is just unsupported.  */
     2218            O (error, NILF,
     2219               _("cannot enforce load limits on this operating system"));
     2220          else
     2221            perror_with_name (_("cannot enforce load limit: "), "getloadavg");
     2222        }
    21912223      lossage = errno;
    21922224      load = 0;
     
    22512283
    22522284      /* Try to start that job.  We break out of the loop as soon
    2253         as start_waiting_job puts one back on the waiting list.  */
     2285        as start_waiting_job puts one back on the waiting list.  */
    22542286    }
    22552287  while (start_waiting_job (job) && waiting_jobs != 0);
     
    22642296# if defined __EMX__
    22652297int
    2266 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
     2298child_execute_job (struct output *out, int good_stdin, char **argv, char **envp)
    22672299{
    22682300  int pid;
    2269   /* stdin_fd == 0 means: nothing to do for stdin;
    2270      stdout_fd == 1 means: nothing to do for stdout */
    2271   int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
    2272   int save_stdout = (stdout_fd != 1) ? dup (1): 1;
    2273 
    2274   /* < 0 only if dup() failed */
    2275   if (save_stdin < 0)
    2276     fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
    2277   if (save_stdout < 0)
    2278     fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
    2279 
    2280   /* Close unnecessary file handles for the child.  */
    2281   if (save_stdin != 0)
    2282     CLOSE_ON_EXEC (save_stdin);
    2283   if (save_stdout != 1)
    2284     CLOSE_ON_EXEC (save_stdout);
    2285 
    2286   /* Connect the pipes to the child process.  */
    2287   if (stdin_fd != 0)
    2288     (void) dup2 (stdin_fd, 0);
    2289   if (stdout_fd != 1)
    2290     (void) dup2 (stdout_fd, 1);
    2291 
    2292   /* stdin_fd and stdout_fd must be closed on exit because we are
    2293      still in the parent process */
    2294   if (stdin_fd != 0)
    2295     CLOSE_ON_EXEC (stdin_fd);
    2296   if (stdout_fd != 1)
    2297     CLOSE_ON_EXEC (stdout_fd);
     2301  int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
     2302  int fdout = FD_STDOUT;
     2303  int fderr = FD_STDERR;
     2304  int save_fdin = -1;
     2305  int save_fdout = -1;
     2306  int save_fderr = -1;
     2307
     2308  /* Divert child output if we want to capture output.  */
     2309  if (out && out->syncout)
     2310    {
     2311      if (out->out >= 0)
     2312        fdout = out->out;
     2313      if (out->err >= 0)
     2314        fderr = out->err;
     2315    }
     2316
     2317  /* For each FD which needs to be redirected first make a dup of the standard
     2318     FD to save and mark it close on exec so our child won't see it.  Then
     2319     dup2() the standard FD to the redirect FD, and also mark the redirect FD
     2320     as close on exec. */
     2321  if (fdin != FD_STDIN)
     2322    {
     2323      save_fdin = dup (FD_STDIN);
     2324      if (save_fdin < 0)
     2325        O (fatal, NILF, _("no more file handles: could not duplicate stdin\n"));
     2326      CLOSE_ON_EXEC (save_fdin);
     2327
     2328      dup2 (fdin, FD_STDIN);
     2329      CLOSE_ON_EXEC (fdin);
     2330    }
     2331
     2332  if (fdout != FD_STDOUT)
     2333    {
     2334      save_fdout = dup (FD_STDOUT);
     2335      if (save_fdout < 0)
     2336        O (fatal, NILF,
     2337           _("no more file handles: could not duplicate stdout\n"));
     2338      CLOSE_ON_EXEC (save_fdout);
     2339
     2340      dup2 (fdout, FD_STDOUT);
     2341      CLOSE_ON_EXEC (fdout);
     2342    }
     2343
     2344  if (fderr != FD_STDERR)
     2345    {
     2346      if (fderr != fdout)
     2347        {
     2348          save_fderr = dup (FD_STDERR);
     2349          if (save_fderr < 0)
     2350            O (fatal, NILF,
     2351               _("no more file handles: could not duplicate stderr\n"));
     2352          CLOSE_ON_EXEC (save_fderr);
     2353        }
     2354
     2355      dup2 (fderr, FD_STDERR);
     2356      CLOSE_ON_EXEC (fderr);
     2357    }
    22982358
    22992359  /* Run the command.  */
    23002360  pid = exec_command (argv, envp);
    23012361
    2302   /* Restore stdout/stdin of the parent and close temporary FDs.  */
    2303   if (stdin_fd != 0)
    2304     {
    2305       if (dup2 (save_stdin, 0) != 0)
    2306         fatal (NILF, _("Could not restore stdin\n"));
     2362  /* Restore stdout/stdin/stderr of the parent and close temporary FDs.  */
     2363  if (save_fdin >= 0)
     2364    {
     2365      if (dup2 (save_fdin, FD_STDIN) != FD_STDIN)
     2366        O (fatal, NILF, _("Could not restore stdin\n"));
    23072367      else
    2308         close (save_stdin);
    2309     }
    2310 
    2311   if (stdout_fd != 1)
    2312     {
    2313       if (dup2 (save_stdout, 1) != 1)
    2314         fatal (NILF, _("Could not restore stdout\n"));
     2368        close (save_fdin);
     2369    }
     2370
     2371  if (save_fdout >= 0)
     2372    {
     2373      if (dup2 (save_fdout, FD_STDOUT) != FD_STDOUT)
     2374        O (fatal, NILF, _("Could not restore stdout\n"));
    23152375      else
    2316         close (save_stdout);
     2376        close (save_fdout);
     2377    }
     2378
     2379  if (save_fderr >= 0)
     2380    {
     2381      if (dup2 (save_fderr, FD_STDERR) != FD_STDERR)
     2382        O (fatal, NILF, _("Could not restore stderr\n"));
     2383      else
     2384        close (save_fderr);
    23172385    }
    23182386
     
    23222390#elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
    23232391
    2324 /* UNIX:
    2325    Replace the current process with one executing the command in ARGV.
    2326    STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
    2327    the environment of the new program.  This function does not return.  */
    2328 void
    2329 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
     2392/* POSIX:
     2393   Create a child process executing the command in ARGV.
     2394   ENVP is the environment of the new program.  Returns the PID or -1.  */
     2395int
     2396child_execute_job (struct output *out, int good_stdin, char **argv, char **envp)
    23302397{
    2331   if (stdin_fd != 0)
    2332     (void) dup2 (stdin_fd, 0);
    2333   if (stdout_fd != 1)
    2334     (void) dup2 (stdout_fd, 1);
    2335   if (stdin_fd != 0)
    2336     (void) close (stdin_fd);
    2337   if (stdout_fd != 1)
    2338     (void) close (stdout_fd);
     2398  int r;
     2399  int pid;
     2400  int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
     2401  int fdout = FD_STDOUT;
     2402  int fderr = FD_STDERR;
     2403
     2404  /* Divert child output if we want to capture it.  */
     2405  if (out && out->syncout)
     2406    {
     2407      if (out->out >= 0)
     2408        fdout = out->out;
     2409      if (out->err >= 0)
     2410        fderr = out->err;
     2411    }
     2412
     2413  pid = vfork();
     2414  if (pid != 0)
     2415    return pid;
     2416
     2417  /* We are the child.  */
     2418  unblock_sigs ();
     2419
     2420#ifdef SET_STACK_SIZE
     2421  /* Reset limits, if necessary.  */
     2422  if (stack_limit.rlim_cur)
     2423    setrlimit (RLIMIT_STACK, &stack_limit);
     2424#endif
     2425
     2426  /* For any redirected FD, dup2() it to the standard FD.
     2427     They are all marked close-on-exec already.  */
     2428  if (fdin != FD_STDIN)
     2429    EINTRLOOP (r, dup2 (fdin, FD_STDIN));
     2430  if (fdout != FD_STDOUT)
     2431    EINTRLOOP (r, dup2 (fdout, FD_STDOUT));
     2432  if (fderr != FD_STDERR)
     2433    EINTRLOOP (r, dup2 (fderr, FD_STDERR));
    23392434
    23402435  /* Run the command.  */
     
    23702465  HANDLE hPID;
    23712466  HANDLE hWaitPID;
    2372   int err = 0;
    23732467  int exit_code = EXIT_FAILURE;
    23742468
    23752469  /* make sure CreateProcess() has Path it needs */
    2376   sync_Path_environment();
     2470  sync_Path_environment ();
    23772471
    23782472  /* launch command */
    2379   hPID = process_easy(argv, envp);
     2473  hPID = process_easy (argv, envp, -1, -1);
    23802474
    23812475  /* make sure launch ok */
     
    23832477    {
    23842478      int i;
    2385       fprintf(stderr,
    2386               _("process_easy() failed to launch process (e=%ld)\n"),
    2387               process_last_err(hPID));
     2479      fprintf (stderr, _("process_easy() failed to launch process (e=%ld)\n"),
     2480               process_last_err (hPID));
    23882481      for (i = 0; argv[i]; i++)
    2389           fprintf(stderr, "%s ", argv[i]);
    2390       fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
    2391       exit(EXIT_FAILURE);
     2482          fprintf (stderr, "%s ", argv[i]);
     2483      fprintf (stderr, _("\nCounted %d args in failed launch\n"), i);
     2484      exit (EXIT_FAILURE);
    23922485    }
    23932486
    23942487  /* wait and reap last child */
    2395   hWaitPID = process_wait_for_any();
     2488  hWaitPID = process_wait_for_any (1, 0);
    23962489  while (hWaitPID)
    23972490    {
    23982491      /* was an error found on this process? */
    2399       err = process_last_err(hWaitPID);
     2492      int err = process_last_err (hWaitPID);
    24002493
    24012494      /* get exit data */
    2402       exit_code = process_exit_code(hWaitPID);
     2495      exit_code = process_exit_code (hWaitPID);
    24032496
    24042497      if (err)
    2405           fprintf(stderr, "make (e=%d, rc=%d): %s",
    2406                   err, exit_code, map_windows32_error_to_string(err));
     2498          fprintf (stderr, "make (e=%d, rc=%d): %s",
     2499                   err, exit_code, map_windows32_error_to_string (err));
    24072500
    24082501      /* cleanup process */
    2409       process_cleanup(hWaitPID);
     2502      process_cleanup (hWaitPID);
    24102503
    24112504      /* expect to find only last pid, warn about other pids reaped */
     
    24132506          break;
    24142507      else
    2415         {
    2416           char *pidstr = xstrdup (pid2str ((pid_t)hWaitPID));
    2417 
    2418           fprintf(stderr,
    2419                   _("make reaped child pid %s, still waiting for pid %s\n"),
    2420                   pidstr, pid2str ((pid_t)hPID));
    2421           free (pidstr);
    2422         }
     2508        {
     2509          char *pidstr = xstrdup (pid2str ((pid_t)hWaitPID));
     2510
     2511          fprintf (stderr,
     2512                   _("make reaped child pid %s, still waiting for pid %s\n"),
     2513                   pidstr, pid2str ((pid_t)hPID));
     2514          free (pidstr);
     2515        }
    24232516    }
    24242517
    24252518  /* return child's exit code as our exit code */
    2426   exit(exit_code);
     2519  exit (exit_code);
    24272520
    24282521#else  /* !WINDOWS32 */
     
    24362529
    24372530# ifdef __EMX__
    2438 
    24392531  /* Run the program.  */
    24402532  pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
    2441 
    24422533  if (pid >= 0)
    24432534    return pid;
     
    24482539
    24492540# else
    2450 
    24512541  /* Run the program.  */
    24522542  environ = envp;
     
    24582548    {
    24592549    case ENOENT:
    2460       error (NILF, _("%s: Command not found"), argv[0]);
     2550      /* We are in the child: don't use the output buffer.
     2551         It's not right to run fprintf() here!  */
     2552      if (makelevel == 0)
     2553        fprintf (stderr, _("%s: %s: Command not found\n"), program, argv[0]);
     2554      else
     2555        fprintf (stderr, _("%s[%u]: %s: Command not found\n"),
     2556                 program, makelevel, argv[0]);
    24612557      break;
    24622558    case ENOEXEC:
    24632559      {
    2464         /* The file is not executable.  Try it as a shell script.  */
    2465         extern char *getenv ();
    2466         char *shell;
    2467         char **new_argv;
    2468         int argc;
     2560        /* The file is not executable.  Try it as a shell script.  */
     2561        const char *shell;
     2562        char **new_argv;
     2563        int argc;
    24692564        int i=1;
    24702565
    24712566# ifdef __EMX__
    24722567        /* Do not use $SHELL from the environment */
    2473         struct variable *p = lookup_variable ("SHELL", 5);
    2474         if (p)
    2475           shell = p->value;
     2568        struct variable *p = lookup_variable ("SHELL", 5);
     2569        if (p)
     2570          shell = p->value;
    24762571        else
    24772572          shell = 0;
    24782573# else
    2479         shell = getenv ("SHELL");
     2574        shell = getenv ("SHELL");
    24802575# endif
    2481         if (shell == 0)
    2482           shell = default_shell;
    2483 
    2484         argc = 1;
    2485         while (argv[argc] != 0)
    2486           ++argc;
     2576        if (shell == 0)
     2577          shell = default_shell;
     2578
     2579        argc = 1;
     2580        while (argv[argc] != 0)
     2581          ++argc;
    24872582
    24882583# ifdef __EMX__
     
    24912586# endif
    24922587
    2493         new_argv = alloca ((1 + argc + 1) * sizeof (char *));
    2494         new_argv[0] = shell;
     2588        new_argv = alloca ((1 + argc + 1) * sizeof (char *));
     2589        new_argv[0] = (char *)shell;
    24952590
    24962591# ifdef __EMX__
     
    25042599
    25052600        new_argv[i] = argv[0];
    2506         while (argc > 0)
    2507           {
    2508             new_argv[i + argc] = argv[argc];
    2509             --argc;
    2510           }
     2601        while (argc > 0)
     2602          {
     2603            new_argv[i + argc] = argv[argc];
     2604            --argc;
     2605          }
    25112606
    25122607# ifdef __EMX__
    2513         pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
    2514         if (pid >= 0)
     2608        pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
     2609        if (pid >= 0)
    25152610          break;
    25162611# else
    2517         execvp (shell, new_argv);
     2612        execvp (shell, new_argv);
    25182613# endif
    2519         if (errno == ENOENT)
    2520           error (NILF, _("%s: Shell program not found"), shell);
    2521         else
    2522           perror_with_name ("execvp: ", shell);
    2523         break;
     2614        if (errno == ENOENT)
     2615          OS (error, NILF, _("%s: Shell program not found"), shell);
     2616        else
     2617          perror_with_name ("execvp: ", shell);
     2618        break;
    25242619      }
    25252620
     
    25272622    case EINVAL:
    25282623      /* this nasty error was driving me nuts :-( */
    2529       error (NILF, _("spawnvpe: environment space might be exhausted"));
     2624      O (error, NILF, _("spawnvpe: environment space might be exhausted"));
    25302625      /* FALLTHROUGH */
    25312626# endif
     
    25452640}
    25462641#else /* On Amiga */
    2547 void exec_command (char **argv)
     2642void
     2643exec_command (char **argv)
    25482644{
    25492645  MyExecute (argv);
     
    25612657/* Figure out the argument list necessary to run LINE as a command.  Try to
    25622658   avoid using a shell.  This routine handles only ' quoting, and " quoting
    2563    when no backslash, $ or ` characters are seen in the quotes.  Starting
     2659   when no backslash, $ or ' characters are seen in the quotes.  Starting
    25642660   quotes may be escaped with a backslash.  If any of the characters in
    2565    sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
     2661   sh_chars is seen, or any of the builtin commands listed in sh_cmds
    25662662   is the first word of a line, the shell is used.
    25672663
     
    25782674
    25792675static char **
    2580 construct_command_argv_internal (char *line, char **restp, char *shell,
    2581                                  char *shellflags, char *ifs, int flags,
    2582                                  char **batch_filename_ptr)
     2676construct_command_argv_internal (char *line, char **restp, const char *shell,
     2677                                 const char *shellflags, const char *ifs,
     2678                                 int flags, char **batch_filename UNUSED)
    25832679{
    25842680#ifdef __MSDOS__
    25852681  /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
    2586      We call `system' for anything that requires ``slow'' processing,
     2682     We call 'system' for anything that requires ''slow'' processing,
    25872683     because DOS shells are too dumb.  When $SHELL points to a real
    2588      (unix-style) shell, `system' just calls it to do everything.  When
    2589      $SHELL points to a DOS shell, `system' does most of the work
     2684     (unix-style) shell, 'system' just calls it to do everything.  When
     2685     $SHELL points to a DOS shell, 'system' does most of the work
    25902686     internally, calling the shell only for its internal commands.
    25912687     However, it looks on the $PATH first, so you can e.g. have an
    2592      external command named `mkdir'.
    2593 
    2594      Since we call `system', certain characters and commands below are
     2688     external command named 'mkdir'.
     2689
     2690     Since we call 'system', certain characters and commands below are
    25952691     actually not specific to COMMAND.COM, but to the DJGPP implementation
    2596      of `system'.  In particular:
     2692     of 'system'.  In particular:
    25972693
    25982694       The shell wildcard characters are in DOS_CHARS because they will
    2599        not be expanded if we call the child via `spawnXX'.
    2600 
    2601        The `;' is in DOS_CHARS, because our `system' knows how to run
     2695       not be expanded if we call the child via 'spawnXX'.
     2696
     2697       The ';' is in DOS_CHARS, because our 'system' knows how to run
    26022698       multiple commands on a single line.
    26032699
     
    26052701       won't have to tell one from another and have one more set of
    26062702       commands and special characters.  */
    2607   static char sh_chars_dos[] = "*?[];|<>%^&()";
    2608   static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
    2609                                  "copy", "ctty", "date", "del", "dir", "echo",
    2610                                  "erase", "exit", "for", "goto", "if", "md",
    2611                                  "mkdir", "path", "pause", "prompt", "rd",
    2612                                  "rmdir", "rem", "ren", "rename", "set",
    2613                                  "shift", "time", "type", "ver", "verify",
    2614                                  "vol", ":", 0 };
    2615 
    2616   static char sh_chars_sh[]  = "#;\"*?[]&|<>(){}$`^";
    2617   static char *sh_cmds_sh[]  = { "cd", "echo", "eval", "exec", "exit", "login",
    2618                                  "logout", "set", "umask", "wait", "while",
    2619                                  "for", "case", "if", ":", ".", "break",
    2620                                  "continue", "export", "read", "readonly",
    2621                                  "shift", "times", "trap", "switch", "unset",
    2622                                  "ulimit", 0 };
    2623 
    2624   char *sh_chars;
    2625   char **sh_cmds;
     2703  static const char *sh_chars_dos = "*?[];|<>%^&()";
     2704  static const char *sh_cmds_dos[] =
     2705    { "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty", "date",
     2706      "del", "dir", "echo", "erase", "exit", "for", "goto", "if", "md",
     2707      "mkdir", "path", "pause", "prompt", "rd", "rmdir", "rem", "ren",
     2708      "rename", "set", "shift", "time", "type", "ver", "verify", "vol", ":",
     2709      0 };
     2710
     2711  static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^";
     2712  static const char *sh_cmds_sh[] =
     2713    { "cd", "echo", "eval", "exec", "exit", "login", "logout", "set", "umask",
     2714      "wait", "while", "for", "case", "if", ":", ".", "break", "continue",
     2715      "export", "read", "readonly", "shift", "times", "trap", "switch",
     2716      "unset", "ulimit", 0 };
     2717
     2718  const char *sh_chars;
     2719  const char **sh_cmds;
     2720
    26262721#elif defined (__EMX__)
    2627   static char sh_chars_dos[] = "*?[];|<>%^&()";
    2628   static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
    2629                                  "copy", "ctty", "date", "del", "dir", "echo",
    2630                                  "erase", "exit", "for", "goto", "if", "md",
    2631                                  "mkdir", "path", "pause", "prompt", "rd",
    2632                                  "rmdir", "rem", "ren", "rename", "set",
    2633                                  "shift", "time", "type", "ver", "verify",
    2634                                  "vol", ":", 0 };
    2635 
    2636   static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
    2637   static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
    2638                              "date", "del", "detach", "dir", "echo",
    2639                              "endlocal", "erase", "exit", "for", "goto", "if",
    2640                              "keys", "md", "mkdir", "move", "path", "pause",
    2641                              "prompt", "rd", "rem", "ren", "rename", "rmdir",
    2642                              "set", "setlocal", "shift", "start", "time",
    2643                              "type", "ver", "verify", "vol", ":", 0 };
    2644 
    2645   static char sh_chars_sh[]  = "#;\"*?[]&|<>(){}$`^~'";
    2646   static char *sh_cmds_sh[]  = { "echo", "cd", "eval", "exec", "exit", "login",
    2647                                  "logout", "set", "umask", "wait", "while",
    2648                                  "for", "case", "if", ":", ".", "break",
    2649                                  "continue", "export", "read", "readonly",
    2650                                  "shift", "times", "trap", "switch", "unset",
    2651                                  0 };
    2652   char *sh_chars;
    2653   char **sh_cmds;
     2722  static const char *sh_chars_dos = "*?[];|<>%^&()";
     2723  static const char *sh_cmds_dos[] =
     2724    { "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty", "date",
     2725      "del", "dir", "echo", "erase", "exit", "for", "goto", "if", "md",
     2726      "mkdir", "path", "pause", "prompt", "rd", "rmdir", "rem", "ren",
     2727      "rename", "set", "shift", "time", "type", "ver", "verify", "vol", ":",
     2728      0 };
     2729
     2730  static const char *sh_chars_os2 = "*?[];|<>%^()\"'&";
     2731  static const char *sh_cmds_os2[] =
     2732    { "call", "cd", "chcp", "chdir", "cls", "copy", "date", "del", "detach",
     2733      "dir", "echo", "endlocal", "erase", "exit", "for", "goto", "if", "keys",
     2734      "md", "mkdir", "move", "path", "pause", "prompt", "rd", "rem", "ren",
     2735      "rename", "rmdir", "set", "setlocal", "shift", "start", "time", "type",
     2736      "ver", "verify", "vol", ":", 0 };
     2737
     2738  static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^~'";
     2739  static const char *sh_cmds_sh[] =
     2740    { "echo", "cd", "eval", "exec", "exit", "login", "logout", "set", "umask",
     2741      "wait", "while", "for", "case", "if", ":", ".", "break", "continue",
     2742      "export", "read", "readonly", "shift", "times", "trap", "switch",
     2743      "unset", 0 };
     2744
     2745  const char *sh_chars;
     2746  const char **sh_cmds;
    26542747
    26552748#elif defined (_AMIGA)
    2656   static char sh_chars[] = "#;\"|<>()?*$`";
    2657   static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
    2658                              "rename", "set", "setenv", "date", "makedir",
    2659                              "skip", "else", "endif", "path", "prompt",
    2660                              "unset", "unsetenv", "version",
    2661                              0 };
     2749  static const char *sh_chars = "#;\"|<>()?*$`";
     2750  static const char *sh_cmds[] =
     2751    { "cd", "eval", "if", "delete", "echo", "copy", "rename", "set", "setenv",
     2752      "date", "makedir", "skip", "else", "endif", "path", "prompt", "unset",
     2753      "unsetenv", "version", 0 };
     2754
    26622755#elif defined (WINDOWS32)
    2663   static char sh_chars_dos[] = "\"|&<>";
    2664   static char *sh_cmds_dos[] = { "assoc", "break", "call", "cd", "chcp",
    2665                                  "chdir", "cls", "color", "copy", "ctty",
    2666                                  "date", "del", "dir", "echo", "echo.",
    2667                                  "endlocal", "erase", "exit", "for", "ftype",
    2668                                  "goto", "if", "if", "md", "mkdir", "path",
    2669                                  "pause", "prompt", "rd", "rem", "ren",
    2670                                  "rename", "rmdir", "set", "setlocal",
    2671                                  "shift", "time", "title", "type", "ver",
    2672                                  "verify", "vol", ":", 0 };
    2673   static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
    2674   static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
    2675                              "logout", "set", "umask", "wait", "while", "for",
    2676                              "case", "if", ":", ".", "break", "continue",
    2677                              "export", "read", "readonly", "shift", "times",
    2678                              "trap", "switch", "test",
     2756  /* We used to have a double quote (") in sh_chars_dos[] below, but
     2757     that caused any command line with quoted file names be run
     2758     through a temporary batch file, which introduces command-line
     2759     limit of 4K charcaters imposed by cmd.exe.  Since CreateProcess
     2760     can handle quoted file names just fine, removing the quote lifts
     2761     the limit from a very frequent use case, because using quoted
     2762     file names is commonplace on MS-Windows.  */
     2763  static const char *sh_chars_dos = "|&<>";
     2764  static const char *sh_cmds_dos[] =
     2765    { "assoc", "break", "call", "cd", "chcp", "chdir", "cls", "color", "copy",
     2766      "ctty", "date", "del", "dir", "echo", "echo.", "endlocal", "erase",
     2767      "exit", "for", "ftype", "goto", "if", "if", "md", "mkdir", "move",
     2768      "path", "pause", "prompt", "rd", "rem", "ren", "rename", "rmdir",
     2769      "set", "setlocal", "shift", "time", "title", "type", "ver", "verify",
     2770      "vol", ":", 0 };
     2771
     2772  static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^";
     2773  static const char *sh_cmds_sh[] =
     2774    { "cd", "eval", "exec", "exit", "login", "logout", "set", "umask", "wait",
     2775      "while", "for", "case", "if", ":", ".", "break", "continue", "export",
     2776      "read", "readonly", "shift", "times", "trap", "switch", "test",
    26792777#ifdef BATCH_MODE_ONLY_SHELL
    2680                  "echo",
    2681 #endif
    2682                  0 };
    2683   char*  sh_chars;
    2684   char** sh_cmds;
     2778      "echo",
     2779#endif
     2780      0 };
     2781
     2782  const char *sh_chars;
     2783  const char **sh_cmds;
    26852784#elif defined(__riscos__)
    2686   static char sh_chars[] = "";
    2687   static char *sh_cmds[] = { 0 };
     2785  static const char *sh_chars = "";
     2786  static const char *sh_cmds[] = { 0 };
    26882787#else  /* must be UNIX-ish */
    2689   static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~!";                          /* kmk: +_sh */
    2690   static char *sh_cmds_sh[] = { ".", ":", "break", "case", "cd", "continue",    /* kmk: +_sh */
    2691                              "eval", "exec", "exit", "export", "for", "if",
    2692                              "login", "logout", "read", "readonly", "set",
    2693                              "shift", "switch", "test", "times", "trap",
    2694                              "ulimit", "umask", "unset", "wait", "while", 0 };
    2695 # ifdef HAVE_DOS_PATHS
     2788  static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^~!";                     /* kmk: +_sh */
     2789  static const char *sh_cmds_sh[] =                                             /* kmk: +_sh */
     2790  { ".", ":", "break", "case", "cd", "continue", "eval", "exec", "exit",
     2791    "export", "for", "if", "login", "logout", "read", "readonly", "set",
     2792    "shift", "switch", "test", "times", "trap", "ulimit", "umask", "unset",
     2793    "wait", "while", 0 };
     2794
     2795# if 0 /*def HAVE_DOS_PATHS - kmk */
    26962796  /* This is required if the MSYS/Cygwin ports (which do not define
    26972797     WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
    2698      sh_chars_sh[] directly (see below).  */
    2699   static char *sh_chars_sh = sh_chars;
    2700 # endif  /* HAVE_DOS_PATHS */
     2798     sh_chars_sh directly (see below).  The value must be identical
     2799     to that of sh_chars immediately above.  */
     2800  static const char *sh_chars_sh =  "#;\"*?[]&|<>(){}$`^~!";
     2801# endif  /* HAVE_DOS_PATHS */
    27012802  char*  sh_chars = sh_chars_sh;                                                /* kmk: +_sh */
    27022803  char** sh_cmds = sh_cmds_sh;                                                  /* kmk: +_sh */
     
    27052806  static char sh_chars_kash[] = "#;*?[]&|<>(){}$`^~!";                          /* note: no \" - good idea? */
    27062807  static char *sh_cmds_kash[] = {
    2707       ".", ":", "break", "case", "cd", "continue",
    2708       "echo", "eval", "exec", "exit", "export", "for", "if",
    2709       "login", "logout", "read", "readonly", "set",
    2710       "shift", "switch", "test", "times", "trap",
    2711       "umask", "wait", "while", 0
     2808      ".", ":", "break", "case", "cd", "continue", "echo", "eval", "exec", "exit",
     2809      "export", "for", "if", "login", "logout", "read", "readonly", "set",
     2810      "shift", "switch", "test", "times", "trap", "umask", "wait", "while", 0 /* +echo, -ulimit, -unset */
    27122811  };
    27132812  int is_kmk_shell = 0;
     
    27152814  int i;
    27162815  char *p;
    2717   char *ap;
    27182816#ifndef NDEBUG
    27192817  char *end;
    27202818#endif
     2819  char *ap;
     2820  const char *cap;
     2821  const char *cp;
    27212822  int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
    27222823  char **new_argv = 0;
     
    27252826  int slow_flag = 0;
    27262827
    2727   if (!unixy_shell) {
    2728     sh_cmds = sh_cmds_dos;
    2729     sh_chars = sh_chars_dos;
    2730   } else {
    2731     sh_cmds = sh_cmds_sh;
    2732     sh_chars = sh_chars_sh;
    2733   }
     2828  if (!unixy_shell)
     2829    {
     2830      sh_cmds = sh_cmds_dos;
     2831      sh_chars = sh_chars_dos;
     2832    }
     2833  else
     2834    {
     2835      sh_cmds = sh_cmds_sh;
     2836      sh_chars = sh_chars_sh;
     2837    }
    27342838#endif /* WINDOWS32 */
    27352839
     
    27372841    *restp = NULL;
    27382842
    2739   /* Make sure not to bother processing an empty line.  */
    2740   while (isblank ((unsigned char)*line))
     2843  /* Make sure not to bother processing an empty line but stop at newline.  */
     2844  while (ISBLANK (*line))
    27412845    ++line;
    27422846  if (*line == '\0')
    27432847    return 0;
     2848
     2849  if (shellflags == 0)
     2850    shellflags = posix_pedantic ? "-ec" : "-c";
    27442851
    27452852  /* See if it is safe to parse commands internally.  */
     
    27862893    slow_flag = strcmp ((s1 ? s1 : ""), (s2 ? s2 : ""));
    27872894
    2788     if (s1)
    2789       free (s1);
    2790     if (s2)
    2791       free (s2);
     2895    free (s1);
     2896    free (s2);
    27922897  }
    27932898  if (slow_flag)
     
    27992904      extern int _is_unixy_shell (const char *_path);
    28002905
    2801       DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
     2906      DB (DB_BASIC, (_("$SHELL changed (was '%s', now '%s')\n"),
    28022907                     default_shell, shell));
    28032908      unixy_shell = _is_unixy_shell (shell);
     
    28342939#endif /* not WINDOWS32 */
    28352940
    2836   if (ifs != 0)
    2837     for (ap = ifs; *ap != '\0'; ++ap)
    2838       if (*ap != ' ' && *ap != '\t' && *ap != '\n')
    2839         goto slow;
    2840 
    2841   if (shellflags != 0)
     2941  if (ifs)
     2942    for (cap = ifs; *cap != '\0'; ++cap)
     2943      if (*cap != ' ' && *cap != '\t' && *cap != '\n')
     2944        goto slow;
     2945
     2946  if (shellflags)
    28422947    if (shellflags[0] != '-'
    28432948        || ((shellflags[1] != 'c' || shellflags[2] != '\0')
     
    28642969
    28652970      if (instring)
    2866         {
    2867           /* Inside a string, just copy any char except a closing quote
    2868              or a backslash-newline combination.  */
    2869           if (*p == instring)
    2870             {
    2871               instring = 0;
    2872               if (ap == new_argv[0] || *(ap-1) == '\0')
    2873                 last_argument_was_empty = 1;
    2874             }
    2875           else if (*p == '\\' && p[1] == '\n')
     2971        {
     2972          /* Inside a string, just copy any char except a closing quote
     2973             or a backslash-newline combination.  */
     2974          if (*p == instring)
     2975            {
     2976              instring = 0;
     2977              if (ap == new_argv[0] || *(ap-1) == '\0')
     2978                last_argument_was_empty = 1;
     2979            }
     2980          else if (*p == '\\' && p[1] == '\n')
    28762981            {
    28772982              /* Backslash-newline is handled differently depending on what
    28782983                 kind of string we're in: inside single-quoted strings you
    2879                  keep them; in double-quoted strings they disappear.
    2880                  For DOS/Windows/OS2, if we don't have a POSIX shell,
    2881                  we keep the pre-POSIX behavior of removing the
    2882                  backslash-newline.  */
     2984                 keep them; in double-quoted strings they disappear.  For
     2985                 DOS/Windows/OS2, if we don't have a POSIX shell, we keep the
     2986                 pre-POSIX behavior of removing the backslash-newline.  */
    28832987              if (instring == '"'
    28842988#if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
    2885                   || !unixy_shell
    2886 #endif
    2887                   )
     2989                  || !unixy_shell
     2990#endif
     2991                  )
    28882992                ++p;
    28892993              else
     
    28932997                }
    28942998            }
    2895           else if (*p == '\n' && restp != NULL)
    2896             {
    2897               /* End of the command line.  */
    2898               *restp = p;
    2899               goto end_of_line;
    2900             }
    2901           /* Backslash, $, and ` are special inside double quotes.
    2902              If we see any of those, punt.
    2903              But on MSDOS, if we use COMMAND.COM, double and single
    2904              quotes have the same effect.  */
    2905           else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
    2906             goto slow;
    2907           else
    2908             *ap++ = *p;
    2909         }
     2999          else if (*p == '\n' && restp != NULL)
     3000            {
     3001              /* End of the command line.  */
     3002              *restp = p;
     3003              goto end_of_line;
     3004            }
     3005          /* Backslash, $, and ` are special inside double quotes.
     3006             If we see any of those, punt.
     3007             But on MSDOS, if we use COMMAND.COM, double and single
     3008             quotes have the same effect.  */
     3009          else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
     3010            goto slow;
     3011#ifdef WINDOWS32
     3012          /* Quoted wildcard characters must be passed quoted to the
     3013             command, so give up the fast route.  */
     3014          else if (instring == '"' && strchr ("*?", *p) != 0 && !unixy_shell)
     3015            goto slow;
     3016          else if (instring == '"' && strncmp (p, "\\\"", 2) == 0)
     3017            *ap++ = *++p;
     3018#endif
     3019          else
     3020            *ap++ = *p;
     3021        }
    29103022      else if (strchr (sh_chars, *p) != 0)
    29113023#ifdef KMK
     
    29153027          if (   *p == '~'
    29163028              && p > line
    2917               && !isspace (p[-1])
     3029              && !ISSPACE (p[-1])
    29183030              && p[-1] != '='
    29193031              && p[-1] != ':'
     
    29263038        }
    29273039#else  /* !KMK */
    2928         /* Not inside a string, but it's a special char.  */
    2929         goto slow;
     3040        /* Not inside a string, but it's a special char.  */
     3041        goto slow;
    29303042#endif /* !KMK */
    29313043      else if (one_shell && *p == '\n')
    2932         /* In .ONESHELL mode \n is a separator like ; or && */
    2933         goto slow;
     3044        /* In .ONESHELL mode \n is a separator like ; or && */
     3045        goto slow;
    29343046#ifdef  __MSDOS__
    29353047      else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
    2936         /* `...' is a wildcard in DJGPP.  */
    2937         goto slow;
     3048        /* '...' is a wildcard in DJGPP.  */
     3049        goto slow;
    29383050#endif
    29393051      else
    2940         /* Not a special char.  */
    2941         switch (*p)
    2942           {
    2943           case '=':
    2944             /* Equals is a special character in leading words before the
    2945                first word with no equals sign in it.  This is not the case
    2946                with sh -k, but we never get here when using nonstandard
    2947                shell flags.  */
    2948             if (! seen_nonequals && unixy_shell)
    2949               goto slow;
    2950             word_has_equals = 1;
    2951             *ap++ = '=';
    2952             break;
    2953 
    2954           case '\\':
    2955             /* Backslash-newline has special case handling, ref POSIX.
     3052        /* Not a special char.  */
     3053        switch (*p)
     3054          {
     3055          case '=':
     3056            /* Equals is a special character in leading words before the
     3057               first word with no equals sign in it.  This is not the case
     3058               with sh -k, but we never get here when using nonstandard
     3059               shell flags.  */
     3060            if (! seen_nonequals && unixy_shell)
     3061              goto slow;
     3062            word_has_equals = 1;
     3063            *ap++ = '=';
     3064            break;
     3065
     3066          case '\\':
     3067            /* Backslash-newline has special case handling, ref POSIX.
    29563068               We're in the fastpath, so emulate what the shell would do.  */
    2957             if (p[1] == '\n')
    2958               {
    2959                 /* Throw out the backslash and newline.  */
     3069            if (p[1] == '\n')
     3070              {
     3071                /* Throw out the backslash and newline.  */
    29603072                ++p;
    29613073
    2962                 /* If there's nothing in this argument yet, skip any
    2963                    whitespace before the start of the next word.  */
     3074                /* At the beginning of the argument, skip any whitespace other
     3075                   than newline before the start of the next word.  */
    29643076                if (ap == new_argv[i])
    2965                   p = next_token (p + 1) - 1;
    2966               }
    2967             else if (p[1] != '\0')
     3077                  while (ISBLANK (p[1]))
     3078                    ++p;
     3079              }
     3080#ifdef WINDOWS32
     3081            /* Backslash before whitespace is not special if our shell
     3082               is not Unixy.  */
     3083            else if (ISSPACE (p[1]) && !unixy_shell)
     3084              {
     3085                *ap++ = *p;
     3086                break;
     3087              }
     3088#endif
     3089            else if (p[1] != '\0')
    29683090              {
    29693091#ifdef HAVE_DOS_PATHS
     
    29863108#endif
    29873109                  if (p[1] != '\\' && p[1] != '\''
    2988                       && !isspace ((unsigned char)p[1])
     3110                      && !ISSPACE (p[1])
    29893111# ifdef KMK
    29903112                      && strchr (sh_chars, p[1]) == 0
     
    30003122                *ap++ = *++p;
    30013123              }
    3002             break;
    3003 
    3004           case '\'':
    3005           case '"':
    3006             instring = *p;
    3007             break;
    3008 
    3009           case '\n':
    3010             if (restp != NULL)
    3011               {
    3012                 /* End of the command line.  */
    3013                 *restp = p;
    3014                 goto end_of_line;
    3015               }
    3016             else
    3017               /* Newlines are not special.  */
    3018               *ap++ = '\n';
    3019             break;
    3020 
    3021           case ' ':
    3022           case '\t':
    3023             /* We have the end of an argument.
    3024                Terminate the text of the argument.  */
    3025             *ap++ = '\0';
    3026             new_argv[++i] = ap;
    3027             last_argument_was_empty = 0;
    3028 
    3029             /* Update SEEN_NONEQUALS, which tells us if every word
    3030                heretofore has contained an `='.  */
    3031             seen_nonequals |= ! word_has_equals;
    3032             if (word_has_equals && ! seen_nonequals)
    3033               /* An `=' in a word before the first
    3034                 word without one is magical.  */
    3035               goto slow;
    3036             word_has_equals = 0; /* Prepare for the next word.  */
    3037 
    3038             /* If this argument is the command name,
    3039                see if it is a built-in shell command.
    3040                If so, have the shell handle it.  */
    3041             if (i == 1)
    3042               {
    3043                 register int j;
    3044                 for (j = 0; sh_cmds[j] != 0; ++j)
     3124            break;
     3125
     3126          case '\'':
     3127          case '"':
     3128            instring = *p;
     3129            break;
     3130
     3131          case '\n':
     3132            if (restp != NULL)
     3133              {
     3134                /* End of the command line.  */
     3135                *restp = p;
     3136                goto end_of_line;
     3137              }
     3138            else
     3139              /* Newlines are not special.  */
     3140              *ap++ = '\n';
     3141            break;
     3142
     3143          case ' ':
     3144          case '\t':
     3145            /* We have the end of an argument.
     3146               Terminate the text of the argument.  */
     3147            *ap++ = '\0';
     3148            new_argv[++i] = ap;
     3149            last_argument_was_empty = 0;
     3150
     3151            /* Update SEEN_NONEQUALS, which tells us if every word
     3152               heretofore has contained an '='.  */
     3153            seen_nonequals |= ! word_has_equals;
     3154            if (word_has_equals && ! seen_nonequals)
     3155              /* An '=' in a word before the first
     3156                word without one is magical.  */
     3157              goto slow;
     3158            word_has_equals = 0; /* Prepare for the next word.  */
     3159
     3160            /* If this argument is the command name,
     3161               see if it is a built-in shell command.
     3162               If so, have the shell handle it.  */
     3163            if (i == 1)
     3164              {
     3165                register int j;
     3166                for (j = 0; sh_cmds[j] != 0; ++j)
    30453167                  {
    30463168                    if (streq (sh_cmds[j], new_argv[0]))
    30473169                      goto slow;
    3048 # ifdef __EMX__
     3170#if defined(__EMX__) || defined(WINDOWS32)
    30493171                    /* Non-Unix shells are case insensitive.  */
    30503172                    if (!unixy_shell
    30513173                        && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
    30523174                      goto slow;
    3053 # endif
     3175#endif
    30543176                  }
    3055               }
    3056 
    3057             /* Ignore multiple whitespace chars.  */
    3058             p = next_token (p) - 1;
    3059             break;
    3060 
    3061           default:
    3062             *ap++ = *p;
    3063             break;
    3064           }
     3177              }
     3178
     3179            /* Skip whitespace chars, but not newlines.  */
     3180            while (ISBLANK (p[1]))
     3181              ++p;
     3182            break;
     3183
     3184          default:
     3185            *ap++ = *p;
     3186            break;
     3187          }
    30653188    }
    30663189 end_of_line:
     
    30813204      register int j;
    30823205      for (j = 0; sh_cmds[j] != 0; ++j)
    3083         if (streq (sh_cmds[j], new_argv[0]))
    3084           goto slow;
     3206        if (streq (sh_cmds[j], new_argv[0]))
     3207          goto slow;
    30853208    }
    30863209
     
    31063229
    31073230#ifdef __MSDOS__
    3108   execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
     3231  execute_by_shell = 1; /* actually, call 'system' if shell isn't unixy */
    31093232#endif
    31103233
     
    31213244    {
    31223245      if (*ptr == '\\' && ptr[1] == '\n')
    3123         ptr += 2;
     3246        ptr += 2;
    31243247      else if (*ptr == '@') /* Kludge: multiline commands */
    31253248      {
    3126         ptr += 2;
    3127         *dptr++ = '\n';
     3249        ptr += 2;
     3250        *dptr++ = '\n';
    31283251      }
    31293252      else
    3130         *dptr++ = *ptr++;
     3253        *dptr++ = *ptr++;
    31313254    }
    31323255    *dptr = 0;
     
    31363259    new_argv[1] = 0;
    31373260  }
    3138 #else   /* Not Amiga  */
     3261#else   /* Not Amiga  */
    31393262#ifdef WINDOWS32
    31403263  /*
     
    31493272
    31503273  /* Make sure not to bother processing an empty line.  */
    3151   while (isspace ((unsigned char)*line))
    3152     ++line;
     3274  NEXT_TOKEN (line);
    31533275  if (*line == '\0')
    31543276    return 0;
     
    31613283       argument list.  */
    31623284
     3285    char *new_line;
    31633286    unsigned int shell_len = strlen (shell);
    31643287    unsigned int line_len = strlen (line);
    3165     unsigned int sflags_len = strlen (shellflags);
    3166 # ifdef WINDOWS32
     3288    unsigned int sflags_len = shellflags ? strlen (shellflags) : 0;
     3289#ifdef WINDOWS32
    31673290    char *command_ptr = NULL; /* used for batch_mode_shell mode */
    3168 # endif
    3169     char *new_line;
     3291#endif
    31703292
    31713293# ifdef __EMX__ /* is this necessary? */
    3172     if (!unixy_shell)
     3294    if (!unixy_shell && shellflags)
    31733295      shellflags[0] = '/'; /* "/c" */
    31743296# endif
    31753297
    31763298    /* In .ONESHELL mode we are allowed to throw the entire current
    3177         recipe string at a single shell and trust that the user
    3178         has configured the shell and shell flags, and formatted
    3179         the string, appropriately. */
     3299        recipe string at a single shell and trust that the user
     3300        has configured the shell and shell flags, and formatted
     3301        the string, appropriately. */
    31803302    if (one_shell)
    31813303      {
    3182         /* If the shell is Bourne compatible, we must remove and ignore
    3183            interior special chars [@+-] because they're meaningless to
    3184            the shell itself. If, however, we're in .ONESHELL mode and
    3185            have changed SHELL to something non-standard, we should
    3186            leave those alone because they could be part of the
    3187            script. In this case we must also leave in place
    3188            any leading [@+-] for the same reason.  */
    3189 
    3190         /* Remove and ignore interior prefix chars [@+-] because they're
    3191              meaningless given a single shell. */
     3304        /* If the shell is Bourne compatible, we must remove and ignore
     3305           interior special chars [@+-] because they're meaningless to
     3306           the shell itself. If, however, we're in .ONESHELL mode and
     3307           have changed SHELL to something non-standard, we should
     3308           leave those alone because they could be part of the
     3309           script. In this case we must also leave in place
     3310           any leading [@+-] for the same reason.  */
     3311
     3312        /* Remove and ignore interior prefix chars [@+-] because they're
     3313             meaningless given a single shell. */
    31923314#if defined __MSDOS__ || defined (__EMX__)
    3193         if (unixy_shell)     /* the test is complicated and we already did it */
     3315        if (unixy_shell)     /* the test is complicated and we already did it */
    31943316#else
    3195         if (is_bourne_compatible_shell(shell))
     3317        if (is_bourne_compatible_shell (shell)
     3318#ifdef WINDOWS32
     3319            /* If we didn't find any sh.exe, don't behave is if we did!  */
     3320            && !no_default_sh_exe
     3321#endif
     3322            )
    31963323#endif
    31973324          {
     
    32053332                int esc = 0;
    32063333
    3207                 /* This is the start of a new recipe line.
    3208                    Skip whitespace and prefix characters.  */
    3209                 while (isblank (*f) || *f == '-' || *f == '@' || *f == '+')
     3334                /* This is the start of a new recipe line.  Skip whitespace
     3335                   and prefix characters but not newlines.  */
     3336                while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
    32103337                  ++f;
    32113338
     
    32293356            *t = '\0';
    32303357          }
    3231 
    3232         new_argv = xmalloc (4 * sizeof (char *));
    3233         new_argv[0] = xstrdup(shell);
    3234         new_argv[1] = xstrdup(shellflags);
    3235         new_argv[2] = line;
    3236         new_argv[3] = NULL;
    3237         return new_argv;
     3358#ifdef WINDOWS32
     3359        else    /* non-Posix shell (cmd.exe etc.) */
     3360          {
     3361            const char *f = line;
     3362            char *t = line;
     3363            char *tstart = t;
     3364            int temp_fd;
     3365            FILE* batch = NULL;
     3366            int id = GetCurrentProcessId ();
     3367            PATH_VAR(fbuf);
     3368
     3369            /* Generate a file name for the temporary batch file.  */
     3370            sprintf (fbuf, "make%d", id);
     3371            *batch_filename = create_batch_file (fbuf, 0, &temp_fd);
     3372            DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
     3373                          *batch_filename));
     3374
     3375            /* Create a FILE object for the batch file, and write to it the
     3376               commands to be executed.  Put the batch file in TEXT mode.  */
     3377            _setmode (temp_fd, _O_TEXT);
     3378            batch = _fdopen (temp_fd, "wt");
     3379            fputs ("@echo off\n", batch);
     3380            DB (DB_JOBS, (_("Batch file contents:\n\t@echo off\n")));
     3381
     3382            /* Copy the recipe, removing and ignoring interior prefix chars
     3383               [@+-]: they're meaningless in .ONESHELL mode.  */
     3384            while (*f != '\0')
     3385              {
     3386                /* This is the start of a new recipe line.  Skip whitespace
     3387                   and prefix characters but not newlines.  */
     3388                while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
     3389                  ++f;
     3390
     3391                /* Copy until we get to the next logical recipe line.  */
     3392                while (*f != '\0')
     3393                  {
     3394                    /* Remove the escaped newlines in the command, and the
     3395                       blanks that follow them.  Windows shells cannot handle
     3396                       escaped newlines.  */
     3397                    if (*f == '\\' && f[1] == '\n')
     3398                      {
     3399                        f += 2;
     3400                        while (ISBLANK (*f))
     3401                          ++f;
     3402                      }
     3403                    *(t++) = *(f++);
     3404                    /* On an unescaped newline, we're done with this
     3405                       line.  */
     3406                    if (f[-1] == '\n')
     3407                      break;
     3408                  }
     3409                /* Write another line into the batch file.  */
     3410                if (t > tstart)
     3411                  {
     3412                    char c = *t;
     3413                    *t = '\0';
     3414                    fputs (tstart, batch);
     3415                    DB (DB_JOBS, ("\t%s", tstart));
     3416                    tstart = t;
     3417                    *t = c;
     3418                  }
     3419              }
     3420            DB (DB_JOBS, ("\n"));
     3421            fclose (batch);
     3422
     3423            /* Create an argv list for the shell command line that
     3424               will run the batch file.  */
     3425            new_argv = xmalloc (2 * sizeof (char *));
     3426            new_argv[0] = xstrdup (*batch_filename);
     3427            new_argv[1] = NULL;
     3428            return new_argv;
     3429          }
     3430#endif /* WINDOWS32 */
     3431        /* Create an argv list for the shell command line.  */
     3432        {
     3433          int n = 0;
     3434
     3435          new_argv = xmalloc ((4 + sflags_len/2) * sizeof (char *));
     3436          new_argv[n++] = xstrdup (shell);
     3437
     3438          /* Chop up the shellflags (if any) and assign them.  */
     3439          if (! shellflags)
     3440            new_argv[n++] = xstrdup ("");
     3441          else
     3442            {
     3443              const char *s = shellflags;
     3444              char *t;
     3445              unsigned int len;
     3446              while ((t = find_next_token (&s, &len)) != 0)
     3447                new_argv[n++] = xstrndup (t, len);
     3448            }
     3449
     3450          /* Set the command to invoke.  */
     3451          new_argv[n++] = line;
     3452          new_argv[n++] = NULL;
     3453        }
     3454        return new_argv;
    32383455      }
    32393456
    3240     new_line = alloca (shell_len + 1 + sflags_len + 1
    3241                              + (line_len*2) + 1);
     3457    new_line = xmalloc ((shell_len*2) + 1 + sflags_len + 1
     3458                        + (line_len*2) + 1);
    32423459    ap = new_line;
    3243     memcpy (ap, shell, shell_len);
    3244     ap += shell_len;
     3460    /* Copy SHELL, escaping any characters special to the shell.  If
     3461       we don't escape them, construct_command_argv_internal will
     3462       recursively call itself ad nauseam, or until stack overflow,
     3463       whichever happens first.  */
     3464    for (cp = shell; *cp != '\0'; ++cp)
     3465      {
     3466        if (strchr (sh_chars, *cp) != 0)
     3467          *(ap++) = '\\';
     3468        *(ap++) = *cp;
     3469      }
    32453470    *(ap++) = ' ';
    3246     memcpy (ap, shellflags, sflags_len);
     3471    if (shellflags)
     3472      memcpy (ap, shellflags, sflags_len);
    32473473    ap += sflags_len;
    32483474    *(ap++) = ' ';
     
    32523478    for (p = line; *p != '\0'; ++p)
    32533479      {
    3254         if (restp != NULL && *p == '\n')
    3255           {
    3256             *restp = p;
    3257             break;
    3258           }
    3259         else if (*p == '\\' && p[1] == '\n')
    3260           {
    3261             /* POSIX says we keep the backslash-newline.  If we don't have a
     3480        if (restp != NULL && *p == '\n')
     3481          {
     3482            *restp = p;
     3483            break;
     3484          }
     3485        else if (*p == '\\' && p[1] == '\n')
     3486          {
     3487            /* POSIX says we keep the backslash-newline.  If we don't have a
    32623488               POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
    32633489               and remove the backslash/newline.  */
     
    32673493# define PRESERVE_BSNL  1
    32683494#endif
    3269             if (PRESERVE_BSNL)
    3270               {
    3271                 *(ap++) = '\\';
    3272                 /* Only non-batch execution needs another backslash,
    3273                    because it will be passed through a recursive
    3274                    invocation of this function.  */
    3275                 if (!batch_mode_shell)
    3276                   *(ap++) = '\\';
    3277                 *(ap++) = '\n';
    3278               }
    3279             ++p;
    3280             continue;
    3281           }
     3495            if (PRESERVE_BSNL)
     3496              {
     3497                *(ap++) = '\\';
     3498                /* Only non-batch execution needs another backslash,
     3499                   because it will be passed through a recursive
     3500                   invocation of this function.  */
     3501                if (!batch_mode_shell)
     3502                  *(ap++) = '\\';
     3503                *(ap++) = '\n';
     3504              }
     3505            ++p;
     3506            continue;
     3507          }
    32823508
    32833509        /* DOS shells don't know about backslash-escaping.  */
    3284         if (unixy_shell && !batch_mode_shell &&
     3510        if (unixy_shell && !batch_mode_shell &&
    32853511            (*p == '\\' || *p == '\'' || *p == '"'
    3286              || isspace ((unsigned char)*p)
     3512             || ISSPACE (*p)
    32873513             || strchr (sh_chars, *p) != 0))
    3288           *ap++ = '\\';
     3514          *ap++ = '\\';
    32893515#ifdef __MSDOS__
    32903516        else if (unixy_shell && strneq (p, "...", 3))
    32913517          {
    3292             /* The case of `...' wildcard again.  */
     3518            /* The case of '...' wildcard again.  */
    32933519            strcpy (ap, "\\.\\.\\");
    32943520            ap += 5;
     
    32963522          }
    32973523#endif
    3298         *ap++ = *p;
     3524        *ap++ = *p;
    32993525      }
    33003526    if (ap == new_line + shell_len + sflags_len + 2)
    3301       /* Line was empty.  */
    3302       return 0;
     3527      {
     3528        /* Line was empty.  */
     3529        free (new_line);
     3530        return 0;
     3531      }
    33033532    *ap = '\0';
    33043533
     
    33073536       command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems).  In these
    33083537       cases, run commands via a script file.  */
    3309     if (just_print_flag && !(flags & COMMANDS_RECURSE)) {
    3310       /* Need to allocate new_argv, although it's unused, because
    3311         start_job_command will want to free it and its 0'th element.  */
    3312       new_argv = xmalloc(2 * sizeof (char *));
    3313       new_argv[0] = xstrdup ("");
    3314       new_argv[1] = NULL;
    3315     } else if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
    3316       int temp_fd;
    3317       FILE* batch = NULL;
    3318       int id = GetCurrentProcessId();
    3319       PATH_VAR(fbuf);
    3320 
    3321       /* create a file name */
    3322       sprintf(fbuf, "make%d", id);
    3323       *batch_filename_ptr = create_batch_file (fbuf, unixy_shell, &temp_fd);
    3324 
    3325       DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
    3326                     *batch_filename_ptr));
    3327 
    3328       /* Create a FILE object for the batch file, and write to it the
    3329          commands to be executed.  Put the batch file in TEXT mode.  */
    3330       _setmode (temp_fd, _O_TEXT);
    3331       batch = _fdopen (temp_fd, "wt");
    3332       if (!unixy_shell)
    3333         fputs ("@echo off\n", batch);
    3334       fputs (command_ptr, batch);
    3335       fputc ('\n', batch);
    3336       fclose (batch);
    3337       DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
    3338                     !unixy_shell ? "\n\t@echo off" : "", command_ptr));
    3339 
    3340       /* create argv */
    3341       new_argv = xmalloc(3 * sizeof (char *));
    3342       if (unixy_shell) {
    3343         new_argv[0] = xstrdup (shell);
    3344         new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
    3345       } else {
    3346         new_argv[0] = xstrdup (*batch_filename_ptr);
     3538    if (just_print_flag && !(flags & COMMANDS_RECURSE))
     3539      {
     3540        /* Need to allocate new_argv, although it's unused, because
     3541           start_job_command will want to free it and its 0'th element.  */
     3542        new_argv = xmalloc (2 * sizeof (char *));
     3543        new_argv[0] = xstrdup ("");
    33473544        new_argv[1] = NULL;
    33483545      }
    3349       new_argv[2] = NULL;
    3350     } else
     3546    else if ((no_default_sh_exe || batch_mode_shell) && batch_filename)
     3547      {
     3548        int temp_fd;
     3549        FILE* batch = NULL;
     3550        int id = GetCurrentProcessId ();
     3551        PATH_VAR (fbuf);
     3552
     3553        /* create a file name */
     3554        sprintf (fbuf, "make%d", id);
     3555        *batch_filename = create_batch_file (fbuf, unixy_shell, &temp_fd);
     3556
     3557        DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
     3558                      *batch_filename));
     3559
     3560        /* Create a FILE object for the batch file, and write to it the
     3561           commands to be executed.  Put the batch file in TEXT mode.  */
     3562        _setmode (temp_fd, _O_TEXT);
     3563        batch = _fdopen (temp_fd, "wt");
     3564        if (!unixy_shell)
     3565          fputs ("@echo off\n", batch);
     3566        fputs (command_ptr, batch);
     3567        fputc ('\n', batch);
     3568        fclose (batch);
     3569        DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
     3570                      !unixy_shell ? "\n\t@echo off" : "", command_ptr));
     3571
     3572        /* create argv */
     3573        new_argv = xmalloc (3 * sizeof (char *));
     3574        if (unixy_shell)
     3575          {
     3576            new_argv[0] = xstrdup (shell);
     3577            new_argv[1] = *batch_filename; /* only argv[0] gets freed later */
     3578          }
     3579        else
     3580          {
     3581            new_argv[0] = xstrdup (*batch_filename);
     3582            new_argv[1] = NULL;
     3583          }
     3584        new_argv[2] = NULL;
     3585      }
     3586    else
    33513587#endif /* WINDOWS32 */
    33523588
    33533589    if (unixy_shell)
    3354       new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0, flags, 0);
     3590      new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0,
     3591                                                  flags, 0);
    33553592
    33563593#ifdef __EMX__
    33573594    else if (!unixy_shell)
    33583595      {
    3359         /* new_line is local, must not be freed therefore
     3596        /* new_line is local, must not be freed therefore
    33603597           We use line here instead of new_line because we run the shell
    33613598           manually.  */
     
    34373674#else
    34383675    else
    3439       fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
     3676      fatal (NILF, CSTRLEN (__FILE__) + INTSTR_LENGTH,
     3677             _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
    34403678            __FILE__, __LINE__);
    34413679#endif
     3680
     3681    free (new_line);
    34423682  }
    3443 #endif  /* ! AMIGA */
     3683#endif  /* ! AMIGA */
    34443684
    34453685  return new_argv;
     
    34493689/* Figure out the argument list necessary to run LINE as a command.  Try to
    34503690   avoid using a shell.  This routine handles only ' quoting, and " quoting
    3451    when no backslash, $ or ` characters are seen in the quotes.  Starting
     3691   when no backslash, $ or ' characters are seen in the quotes.  Starting
    34523692   quotes may be escaped with a backslash.  If any of the characters in
    3453    sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
     3693   sh_chars is seen, or any of the builtin commands listed in sh_cmds
    34543694   is the first word of a line, the shell is used.
    34553695
     
    34623702char **
    34633703construct_command_argv (char *line, char **restp, struct file *file,
    3464                         int cmd_flags, char **batch_filename_ptr)
     3704                        int cmd_flags, char **batch_filename)
    34653705{
    34663706  char *shell, *ifs, *shellflags;
     
    34753715  for (;;)
    34763716    {
    3477       while ((*cptr != 0)
    3478              && (isspace ((unsigned char)*cptr)))
    3479         cptr++;
     3717      while ((*cptr != 0) && (ISSPACE (*cptr)))
     3718        cptr++;
    34803719      if (*cptr == 0)
    3481         break;
    3482       while ((*cptr != 0)
    3483              && (!isspace((unsigned char)*cptr)))
    3484         cptr++;
     3720        break;
     3721      while ((*cptr != 0) && (!ISSPACE (*cptr)))
     3722        cptr++;
    34853723      argc++;
    34863724    }
     
    34943732  for (;;)
    34953733    {
    3496       while ((*cptr != 0)
    3497              && (isspace ((unsigned char)*cptr)))
    3498         cptr++;
     3734      while ((*cptr != 0) && (ISSPACE (*cptr)))
     3735        cptr++;
    34993736      if (*cptr == 0)
    3500         break;
     3737        break;
    35013738      DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
    35023739      argv[argc++] = cptr;
    3503       while ((*cptr != 0)
    3504              && (!isspace((unsigned char)*cptr)))
    3505         cptr++;
     3740      while ((*cptr != 0) && (!ISSPACE (*cptr)))
     3741        cptr++;
    35063742      if (*cptr != 0)
    3507         *cptr++ = 0;
     3743        *cptr++ = 0;
    35083744    }
    35093745#else
     
    35193755     * is not confused.
    35203756     */
    3521     if (shell) {
    3522       char *p = w32ify (shell, 0);
    3523       strcpy (shell, p);
    3524     }
     3757    if (shell)
     3758      {
     3759        char *p = w32ify (shell, 0);
     3760        strcpy (shell, p);
     3761      }
    35253762#endif
    35263763#ifdef __EMX__
     
    35303767      static int init = 0;
    35313768      if (init == 0)
    3532         {
    3533           unixroot = getenv ("UNIXROOT");
    3534           /* unixroot must be NULL or not empty */
    3535           if (unixroot && unixroot[0] == '\0') unixroot = NULL;
    3536           init = 1;
    3537         }
     3769        {
     3770          unixroot = getenv ("UNIXROOT");
     3771          /* unixroot must be NULL or not empty */
     3772          if (unixroot && unixroot[0] == '\0') unixroot = NULL;
     3773          init = 1;
     3774        }
    35383775
    35393776      /* if we have an unixroot drive and if shell is not default_shell
     
    35433780         "$UNIXROOT/bin/sh" instead.  */
    35443781      if (unixroot && shell && strcmp (shell, last_shell) != 0
    3545           && (shell[0] == '/' || shell[0] == '\\'))
    3546         {
    3547           /* trying a new shell, check whether it exists */
    3548           size_t size = strlen (shell);
    3549           char *buf = xmalloc (size + 7);
    3550           memcpy (buf, shell, size);
    3551           memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
     3782          && (shell[0] == '/' || shell[0] == '\\'))
     3783        {
     3784          /* trying a new shell, check whether it exists */
     3785          size_t size = strlen (shell);
     3786          char *buf = xmalloc (size + 7);
     3787          memcpy (buf, shell, size);
     3788          memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
    35523789          if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
    3553             {
    3554               /* try the same for the unixroot drive */
    3555               memmove (buf + 2, buf, size + 5);
    3556               buf[0] = unixroot[0];
    3557               buf[1] = unixroot[1];
    3558               if (access (buf, F_OK) == 0)
    3559                 /* we have found a shell! */
    3560                 /* free(shell); */
    3561                 shell = buf;
    3562               else
    3563                 free (buf);
    3564             }
    3565           else
     3790            {
     3791              /* try the same for the unixroot drive */
     3792              memmove (buf + 2, buf, size + 5);
     3793              buf[0] = unixroot[0];
     3794              buf[1] = unixroot[1];
     3795              if (access (buf, F_OK) == 0)
     3796                /* we have found a shell! */
     3797                /* free(shell); */
     3798                shell = buf;
     3799              else
     3800                free (buf);
     3801            }
     3802          else
    35663803            free (buf);
    3567         }
     3804        }
    35683805    }
    35693806#endif /* __EMX__ */
     
    35753812  }
    35763813
    3577 #ifdef CONFIG_WITH_KMK_BUILTIN
     3814# ifdef CONFIG_WITH_KMK_BUILTIN
    35783815  /* If it's a kmk_builtin command, make sure we're treated like a
    35793816     unix shell and and don't get batch files. */
    35803817  if (   (  !unixy_shell
    35813818          || batch_mode_shell
    3582 # ifdef WINDOWS32
     3819#  ifdef WINDOWS32
    35833820          || no_default_sh_exe
    3584 # endif
     3821#  endif
    35853822         )
    35863823      && line
    3587       && !strncmp(line, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
     3824      && !strncmp (line, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
    35883825  {
    35893826    int saved_batch_mode_shell = batch_mode_shell;
    35903827    int saved_unixy_shell = unixy_shell;
    3591 # ifdef WINDOWS32
     3828#  ifdef WINDOWS32
    35923829    int saved_no_default_sh_exe = no_default_sh_exe;
    35933830    no_default_sh_exe = 0;
    3594 # endif
     3831#  endif
    35953832    unixy_shell = 1;
    35963833    batch_mode_shell = 0;
    35973834    argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
    3598                                             cmd_flags, batch_filename_ptr);
     3835                                            cmd_flags, batch_filename);
    35993836    batch_mode_shell = saved_batch_mode_shell;
    36003837    unixy_shell = saved_unixy_shell;
    3601 # ifdef WINDOWS32
     3838#  ifdef WINDOWS32
    36023839    no_default_sh_exe = saved_no_default_sh_exe;
    3603 # endif
     3840#  endif
    36043841  }
    36053842  else
    3606 #endif /* CONFIG_WITH_KMK_BUILTIN */
     3843# endif /* CONFIG_WITH_KMK_BUILTIN */
    36073844  argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
    3608                                           cmd_flags, batch_filename_ptr);
     3845                                          cmd_flags, batch_filename);
    36093846
    36103847  free (shell);
     
    36233860
    36243861  (void) close (new);
    3625   fd = dup (old);
     3862  EINTRLOOP (fd, dup (old));
    36263863  if (fd != new)
    36273864    {
     
    36503887          if (len > print_time_width)
    36513888            print_time_width = len;
    3652           message (1, _("%*s - %s"), print_time_width, buf, c ->file->name);
     3889          message (1, print_time_width + strlen (c->file->name),
     3890                   _("%*s - %s"), print_time_width, buf, c->file->name);
    36533891        }
    36543892    }
Note: See TracChangeset for help on using the changeset viewer.