ae1f18b9b8a3f2729e5033d859baa5b1e394a16e
[platform/upstream/make.git] / src / job.c
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988-2020 Free Software Foundation, Inc.
3 This file is part of GNU Make.
4
5 GNU Make is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
8 version.
9
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License along with
15 this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include "makeint.h"
18
19 #include <assert.h>
20 #include <string.h>
21
22 #include "job.h"
23 #include "debug.h"
24 #include "filedef.h"
25 #include "commands.h"
26 #include "variable.h"
27 #include "os.h"
28
29 /* Default shell to use.  */
30 #ifdef WINDOWS32
31 # ifdef HAVE_STRINGS_H
32 #  include <strings.h>  /* for strcasecmp, strncasecmp */
33 # endif
34 # include <windows.h>
35
36 const char *default_shell = "sh.exe";
37 int no_default_sh_exe = 1;
38 int batch_mode_shell = 1;
39 HANDLE main_thread;
40
41 #elif defined (_AMIGA)
42
43 const char *default_shell = "";
44 extern int MyExecute (char **);
45 int batch_mode_shell = 0;
46
47 #elif defined (__MSDOS__)
48
49 /* The default shell is a pointer so we can change it if Makefile
50    says so.  It is without an explicit path so we get a chance
51    to search the $PATH for it (since MSDOS doesn't have standard
52    directories we could trust).  */
53 const char *default_shell = "command.com";
54 int batch_mode_shell = 0;
55
56 #elif defined (__EMX__)
57
58 const char *default_shell = "/bin/sh";
59 int batch_mode_shell = 0;
60
61 #elif defined (VMS)
62
63 # include <descrip.h>
64 # include <stsdef.h>
65 const char *default_shell = "";
66 int batch_mode_shell = 0;
67
68 #define strsignal vms_strsignal
69 char * vms_strsignal (int status);
70
71 #ifndef C_FACILITY_NO
72 # define C_FACILITY_NO 0x350000
73 #endif
74 #ifndef VMS_POSIX_EXIT_MASK
75 # define VMS_POSIX_EXIT_MASK (C_FACILITY_NO | 0xA000)
76 #endif
77
78 #else
79
80 const char *default_shell = "/bin/sh";
81 int batch_mode_shell = 0;
82
83 #endif
84
85 #ifdef __MSDOS__
86 # include <process.h>
87 static int execute_by_shell;
88 static int dos_pid = 123;
89 int dos_status;
90 int dos_command_running;
91 #endif /* __MSDOS__ */
92
93 #ifdef _AMIGA
94 # include <proto/dos.h>
95 static int amiga_pid = 123;
96 static int amiga_status;
97 static char amiga_bname[32];
98 static int amiga_batch_file;
99 #endif /* Amiga.  */
100
101 #ifdef VMS
102 # ifndef __GNUC__
103 #   include <processes.h>
104 # endif
105 # include <starlet.h>
106 # include <lib$routines.h>
107 static void vmsWaitForChildren (int *);
108 #endif
109
110 #ifdef WINDOWS32
111 # include <windows.h>
112 # include <io.h>
113 # include <process.h>
114 # include "sub_proc.h"
115 # include "w32err.h"
116 # include "pathstuff.h"
117 # define WAIT_NOHANG 1
118 #endif /* WINDOWS32 */
119
120 #ifdef __EMX__
121 # include <process.h>
122 #endif
123
124 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
125 # include <sys/wait.h>
126 #endif
127
128 #ifdef HAVE_WAITPID
129 # define WAIT_NOHANG(status)    waitpid (-1, (status), WNOHANG)
130 #else   /* Don't have waitpid.  */
131 # ifdef HAVE_WAIT3
132 #  ifndef wait3
133 extern int wait3 ();
134 #  endif
135 #  define WAIT_NOHANG(status)   wait3 ((status), WNOHANG, (struct rusage *) 0)
136 # endif /* Have wait3.  */
137 #endif /* Have waitpid.  */
138
139 #ifdef USE_POSIX_SPAWN
140 # include <spawn.h>
141 # include "findprog.h"
142 #endif
143
144 #if !defined (wait) && !defined (POSIX)
145 int wait ();
146 #endif
147
148 #ifndef HAVE_UNION_WAIT
149
150 # define WAIT_T int
151
152 # ifndef WTERMSIG
153 #  define WTERMSIG(x) ((x) & 0x7f)
154 # endif
155 # ifndef WCOREDUMP
156 #  define WCOREDUMP(x) ((x) & 0x80)
157 # endif
158 # ifndef WEXITSTATUS
159 #  define WEXITSTATUS(x) (((x) >> 8) & 0xff)
160 # endif
161 # ifndef WIFSIGNALED
162 #  define WIFSIGNALED(x) (WTERMSIG (x) != 0)
163 # endif
164 # ifndef WIFEXITED
165 #  define WIFEXITED(x) (WTERMSIG (x) == 0)
166 # endif
167
168 #else   /* Have 'union wait'.  */
169
170 # define WAIT_T union wait
171 # ifndef WTERMSIG
172 #  define WTERMSIG(x) ((x).w_termsig)
173 # endif
174 # ifndef WCOREDUMP
175 #  define WCOREDUMP(x) ((x).w_coredump)
176 # endif
177 # ifndef WEXITSTATUS
178 #  define WEXITSTATUS(x) ((x).w_retcode)
179 # endif
180 # ifndef WIFSIGNALED
181 #  define WIFSIGNALED(x) (WTERMSIG(x) != 0)
182 # endif
183 # ifndef WIFEXITED
184 #  define WIFEXITED(x) (WTERMSIG(x) == 0)
185 # endif
186
187 #endif  /* Don't have 'union wait'.  */
188
189 #if !defined(HAVE_UNISTD_H) && !defined(WINDOWS32)
190 int dup2 ();
191 int execve ();
192 void _exit ();
193 # ifndef VMS
194 int geteuid ();
195 int getegid ();
196 int setgid ();
197 int getgid ();
198 # endif
199 #endif
200
201 /* Different systems have different requirements for pid_t.
202    Plus we have to support gettext string translation... Argh.  */
203 static const char *
204 pid2str (pid_t pid)
205 {
206   static char pidstring[100];
207 #if defined(WINDOWS32) && (__GNUC__ > 3 || _MSC_VER > 1300)
208   /* %Id is only needed for 64-builds, which were not supported by
209       older versions of Windows compilers.  */
210   sprintf (pidstring, "%Id", pid);
211 #else
212   sprintf (pidstring, "%lu", (unsigned long) pid);
213 #endif
214   return pidstring;
215 }
216
217 #ifndef HAVE_GETLOADAVG
218 int getloadavg (double loadavg[], int nelem);
219 #endif
220
221 static void free_child (struct child *);
222 static void start_job_command (struct child *child);
223 static int load_too_high (void);
224 static int job_next_command (struct child *);
225 static int start_waiting_job (struct child *);
226 \f
227 /* Chain of all live (or recently deceased) children.  */
228
229 struct child *children = 0;
230
231 /* Number of children currently running.  */
232
233 unsigned int job_slots_used = 0;
234
235 /* Nonzero if the 'good' standard input is in use.  */
236
237 static int good_stdin_used = 0;
238
239 /* Chain of children waiting to run until the load average goes down.  */
240
241 static struct child *waiting_jobs = 0;
242
243 /* Non-zero if we use a *real* shell (always so on Unix).  */
244
245 int unixy_shell = 1;
246
247 /* Number of jobs started in the current second.  */
248
249 unsigned long job_counter = 0;
250
251 /* Number of jobserver tokens this instance is currently using.  */
252
253 unsigned int jobserver_tokens = 0;
254 \f
255
256 #ifdef WINDOWS32
257 /*
258  * The macro which references this function is defined in makeint.h.
259  */
260 int
261 w32_kill (pid_t pid, int sig)
262 {
263   return ((process_kill ((HANDLE)pid, sig) == TRUE) ? 0 : -1);
264 }
265
266 /* This function creates a temporary file name with an extension specified
267  * by the unixy arg.
268  * Return an xmalloc'ed string of a newly created temp file and its
269  * file descriptor, or die.  */
270 static char *
271 create_batch_file (char const *base, int unixy, int *fd)
272 {
273   const char *const ext = unixy ? "sh" : "bat";
274   const char *error_string = NULL;
275   char temp_path[MAXPATHLEN]; /* need to know its length */
276   unsigned path_size = GetTempPath (sizeof temp_path, temp_path);
277   int path_is_dot = 0;
278   /* The following variable is static so we won't try to reuse a name
279      that was generated a little while ago, because that file might
280      not be on disk yet, since we use FILE_ATTRIBUTE_TEMPORARY below,
281      which tells the OS it doesn't need to flush the cache to disk.
282      If the file is not yet on disk, we might think the name is
283      available, while it really isn't.  This happens in parallel
284      builds, where Make doesn't wait for one job to finish before it
285      launches the next one.  */
286   static unsigned uniq = 0;
287   static int second_loop = 0;
288   const size_t sizemax = strlen (base) + strlen (ext) + 10;
289
290   if (path_size == 0)
291     {
292       path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
293       path_is_dot = 1;
294     }
295
296   ++uniq;
297   if (uniq >= 0x10000 && !second_loop)
298     {
299       /* If we already had 64K batch files in this
300          process, make a second loop through the numbers,
301          looking for free slots, i.e. files that were
302          deleted in the meantime.  */
303       second_loop = 1;
304       uniq = 1;
305     }
306   while (path_size > 0 &&
307          path_size + sizemax < sizeof temp_path &&
308          !(uniq >= 0x10000 && second_loop))
309     {
310       unsigned size = sprintf (temp_path + path_size,
311                                "%s%s-%x.%s",
312                                temp_path[path_size - 1] == '\\' ? "" : "\\",
313                                base, uniq, ext);
314       HANDLE h = CreateFile (temp_path,  /* file name */
315                              GENERIC_READ | GENERIC_WRITE, /* desired access */
316                              0,                            /* no share mode */
317                              NULL,                         /* default security attributes */
318                              CREATE_NEW,                   /* creation disposition */
319                              FILE_ATTRIBUTE_NORMAL |       /* flags and attributes */
320                              FILE_ATTRIBUTE_TEMPORARY,     /* we'll delete it */
321                              NULL);                        /* no template file */
322
323       if (h == INVALID_HANDLE_VALUE)
324         {
325           const DWORD er = GetLastError ();
326
327           if (er == ERROR_FILE_EXISTS || er == ERROR_ALREADY_EXISTS)
328             {
329               ++uniq;
330               if (uniq == 0x10000 && !second_loop)
331                 {
332                   second_loop = 1;
333                   uniq = 1;
334                 }
335             }
336
337           /* the temporary path is not guaranteed to exist */
338           else if (path_is_dot == 0)
339             {
340               path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
341               path_is_dot = 1;
342             }
343
344           else
345             {
346               error_string = map_windows32_error_to_string (er);
347               break;
348             }
349         }
350       else
351         {
352           const unsigned final_size = path_size + size + 1;
353           char *const path = xmalloc (final_size);
354           memcpy (path, temp_path, final_size);
355           *fd = _open_osfhandle ((intptr_t)h, 0);
356           if (unixy)
357             {
358               char *p;
359               int ch;
360               for (p = path; (ch = *p) != 0; ++p)
361                 if (ch == '\\')
362                   *p = '/';
363             }
364           return path; /* good return */
365         }
366     }
367
368   *fd = -1;
369   if (error_string == NULL)
370     error_string = _("Cannot create a temporary file\n");
371   O (fatal, NILF, error_string);
372
373   /* not reached */
374   return NULL;
375 }
376 #endif /* WINDOWS32 */
377
378 #ifdef __EMX__
379 /* returns whether path is assumed to be a unix like shell. */
380 int
381 _is_unixy_shell (const char *path)
382 {
383   /* list of non unix shells */
384   const char *known_os2shells[] = {
385     "cmd.exe",
386     "cmd",
387     "4os2.exe",
388     "4os2",
389     "4dos.exe",
390     "4dos",
391     "command.com",
392     "command",
393     NULL
394   };
395
396   /* find the rightmost '/' or '\\' */
397   const char *name = strrchr (path, '/');
398   const char *p = strrchr (path, '\\');
399   unsigned i;
400
401   if (name && p)    /* take the max */
402     name = (name > p) ? name : p;
403   else if (p)       /* name must be 0 */
404     name = p;
405   else if (!name)   /* name and p must be 0 */
406     name = path;
407
408   if (*name == '/' || *name == '\\') name++;
409
410   i = 0;
411   while (known_os2shells[i] != NULL)
412     {
413       if (strcasecmp (name, known_os2shells[i]) == 0)
414         return 0; /* not a unix shell */
415       i++;
416     }
417
418   /* in doubt assume a unix like shell */
419   return 1;
420 }
421 #endif /* __EMX__ */
422
423 /* determines whether path looks to be a Bourne-like shell. */
424 int
425 is_bourne_compatible_shell (const char *path)
426 {
427   /* List of known POSIX (or POSIX-ish) shells.  */
428   static const char *unix_shells[] = {
429     "sh",
430     "bash",
431     "ksh",
432     "rksh",
433     "zsh",
434     "ash",
435     "dash",
436     NULL
437   };
438   const char **s;
439
440   /* find the rightmost '/' or '\\' */
441   const char *name = strrchr (path, '/');
442   char *p = strrchr (path, '\\');
443
444   if (name && p)    /* take the max */
445     name = (name > p) ? name : p;
446   else if (p)       /* name must be 0 */
447     name = p;
448   else if (!name)   /* name and p must be 0 */
449     name = path;
450
451   if (*name == '/' || *name == '\\')
452     ++name;
453
454   /* this should be able to deal with extensions on Windows-like systems */
455   for (s = unix_shells; *s != NULL; ++s)
456     {
457 #if defined(WINDOWS32) || defined(__MSDOS__)
458       size_t len = strlen (*s);
459       if ((strlen (name) >= len && STOP_SET (name[len], MAP_DOT|MAP_NUL))
460           && strncasecmp (name, *s, len) == 0)
461 #else
462       if (strcmp (name, *s) == 0)
463 #endif
464         return 1; /* a known unix-style shell */
465     }
466
467   /* if not on the list, assume it's not a Bourne-like shell */
468   return 0;
469 }
470
471 #ifdef POSIX
472 extern sigset_t fatal_signal_set;
473
474 static void
475 block_sigs ()
476 {
477   sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
478 }
479
480 static void
481 unblock_sigs ()
482 {
483   sigprocmask (SIG_UNBLOCK, &fatal_signal_set, (sigset_t *) 0);
484 }
485
486 void
487 unblock_all_sigs ()
488 {
489   sigset_t empty;
490   sigemptyset (&empty);
491   sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
492 }
493
494 #elif defined(HAVE_SIGSETMASK)
495
496 extern int fatal_signal_mask;
497
498 static void
499 block_sigs ()
500 {
501   sigblock (fatal_signal_mask);
502 }
503
504 static void
505 unblock_sigs ()
506 {
507   sigsetmask (siggetmask (0) & ~fatal_signal_mask)
508 }
509
510 void
511 unblock_all_sigs ()
512 {
513   sigsetmask (0);
514 }
515
516 #else
517
518 #define block_sigs()
519 #define unblock_sigs()
520
521 void
522 unblock_all_sigs ()
523 {
524 }
525
526 #endif
527 \f
528 /* Write an error message describing the exit status given in
529    EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
530    Append "(ignored)" if IGNORED is nonzero.  */
531
532 static void
533 child_error (struct child *child,
534              int exit_code, int exit_sig, int coredump, int ignored)
535 {
536   const char *pre = "*** ";
537   const char *post = "";
538   const char *dump = "";
539   const struct file *f = child->file;
540   const floc *flocp = &f->cmds->fileinfo;
541   const char *nm;
542   size_t l;
543
544   if (ignored && run_silent)
545     return;
546
547   if (exit_sig && coredump)
548     dump = _(" (core dumped)");
549
550   if (ignored)
551     {
552       pre = "";
553       post = _(" (ignored)");
554     }
555
556   if (! flocp->filenm)
557     nm = _("<builtin>");
558   else
559     {
560       char *a = alloca (strlen (flocp->filenm) + 6 + INTSTR_LENGTH + 1);
561       sprintf (a, "%s:%lu", flocp->filenm, flocp->lineno + flocp->offset);
562       nm = a;
563     }
564
565   l = strlen (pre) + strlen (nm) + strlen (f->name) + strlen (post);
566
567   OUTPUT_SET (&child->output);
568
569   show_goal_error ();
570
571   if (exit_sig == 0)
572     error (NILF, l + INTSTR_LENGTH,
573            _("%s[%s: %s] Error %d%s"), pre, nm, f->name, exit_code, post);
574   else
575     {
576       const char *s = strsignal (exit_sig);
577       error (NILF, l + strlen (s) + strlen (dump),
578              "%s[%s: %s] %s%s%s", pre, nm, f->name, s, dump, post);
579     }
580
581   OUTPUT_UNSET ();
582 }
583 \f
584
585 /* Handle a dead child.  This handler may or may not ever be installed.
586
587    If we're using the jobserver feature without pselect(), we need it.
588    First, installing it ensures the read will interrupt on SIGCHLD.  Second,
589    we close the dup'd read FD to ensure we don't enter another blocking read
590    without reaping all the dead children.  In this case we don't need the
591    dead_children count.
592
593    If we don't have either waitpid or wait3, then make is unreliable, but we
594    use the dead_children count to reap children as best we can.  */
595
596 static unsigned int dead_children = 0;
597
598 RETSIGTYPE
599 child_handler (int sig UNUSED)
600 {
601   ++dead_children;
602
603   jobserver_signal ();
604
605 #ifdef __EMX__
606   /* The signal handler must called only once! */
607   signal (SIGCHLD, SIG_DFL);
608 #endif
609 }
610
611 extern pid_t shell_function_pid;
612
613 /* Reap all dead children, storing the returned status and the new command
614    state ('cs_finished') in the 'file' member of the 'struct child' for the
615    dead child, and removing the child from the chain.  In addition, if BLOCK
616    nonzero, we block in this function until we've reaped at least one
617    complete child, waiting for it to die if necessary.  If ERR is nonzero,
618    print an error message first.  */
619
620 void
621 reap_children (int block, int err)
622 {
623 #ifndef WINDOWS32
624   WAIT_T status;
625 #endif
626   /* Initially, assume we have some.  */
627   int reap_more = 1;
628
629 #ifdef WAIT_NOHANG
630 # define REAP_MORE reap_more
631 #else
632 # define REAP_MORE dead_children
633 #endif
634
635   /* As long as:
636
637        We have at least one child outstanding OR a shell function in progress,
638          AND
639        We're blocking for a complete child OR there are more children to reap
640
641      we'll keep reaping children.  */
642
643   while ((children != 0 || shell_function_pid != 0)
644          && (block || REAP_MORE))
645     {
646       unsigned int remote = 0;
647       pid_t pid;
648       int exit_code, exit_sig, coredump;
649       struct child *lastc, *c;
650       int child_failed;
651       int any_remote, any_local;
652       int dontcare;
653
654       if (err && block)
655         {
656           static int printed = 0;
657
658           /* We might block for a while, so let the user know why.
659              Only print this message once no matter how many jobs are left.  */
660           fflush (stdout);
661           if (!printed)
662             O (error, NILF, _("*** Waiting for unfinished jobs...."));
663           printed = 1;
664         }
665
666       /* We have one less dead child to reap.  As noted in
667          child_handler() above, this count is completely unimportant for
668          all modern, POSIX-y systems that support wait3() or waitpid().
669          The rest of this comment below applies only to early, broken
670          pre-POSIX systems.  We keep the count only because... it's there...
671
672          The test and decrement are not atomic; if it is compiled into:
673                 register = dead_children - 1;
674                 dead_children = register;
675          a SIGCHLD could come between the two instructions.
676          child_handler increments dead_children.
677          The second instruction here would lose that increment.  But the
678          only effect of dead_children being wrong is that we might wait
679          longer than necessary to reap a child, and lose some parallelism;
680          and we might print the "Waiting for unfinished jobs" message above
681          when not necessary.  */
682
683       if (dead_children > 0)
684         --dead_children;
685
686       any_remote = 0;
687       any_local = shell_function_pid != 0;
688       lastc = 0;
689       for (c = children; c != 0; lastc = c, c = c->next)
690         {
691           any_remote |= c->remote;
692           any_local |= ! c->remote;
693
694           /* If pid < 0, this child never even started.  Handle it.  */
695           if (c->pid < 0)
696             {
697               exit_sig = 0;
698               coredump = 0;
699               /* According to POSIX, 127 is used for command not found.  */
700               exit_code = 127;
701               goto process_child;
702             }
703
704           DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
705                         c, c->file->name, pid2str (c->pid),
706                         c->remote ? _(" (remote)") : ""));
707 #ifdef VMS
708           break;
709 #endif
710         }
711
712       /* First, check for remote children.  */
713       if (any_remote)
714         pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
715       else
716         pid = 0;
717
718       if (pid > 0)
719         /* We got a remote child.  */
720         remote = 1;
721       else if (pid < 0)
722         {
723           /* A remote status command failed miserably.  Punt.  */
724 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
725         remote_status_lose:
726 #endif
727           pfatal_with_name ("remote_status");
728         }
729       else
730         {
731           /* No remote children.  Check for local children.  */
732 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
733           if (any_local)
734             {
735 #ifdef VMS
736               /* Todo: This needs more untangling multi-process support */
737               /* Just do single child process support now */
738               vmsWaitForChildren (&status);
739               pid = c->pid;
740
741               /* VMS failure status can not be fully translated */
742               status = $VMS_STATUS_SUCCESS (c->cstatus) ? 0 : (1 << 8);
743
744               /* A Posix failure can be exactly translated */
745               if ((c->cstatus & VMS_POSIX_EXIT_MASK) == VMS_POSIX_EXIT_MASK)
746                 status = (c->cstatus >> 3 & 255) << 8;
747 #else
748 #ifdef WAIT_NOHANG
749               if (!block)
750                 pid = WAIT_NOHANG (&status);
751               else
752 #endif
753                 EINTRLOOP (pid, wait (&status));
754 #endif /* !VMS */
755             }
756           else
757             pid = 0;
758
759           if (pid < 0)
760             {
761               /* The wait*() failed miserably.  Punt.  */
762               pfatal_with_name ("wait");
763             }
764           else if (pid > 0)
765             {
766               /* We got a child exit; chop the status word up.  */
767               exit_code = WEXITSTATUS (status);
768               exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
769               coredump = WCOREDUMP (status);
770             }
771           else
772             {
773               /* No local children are dead.  */
774               reap_more = 0;
775
776               if (!block || !any_remote)
777                 break;
778
779               /* Now try a blocking wait for a remote child.  */
780               pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
781               if (pid < 0)
782                 goto remote_status_lose;
783               else if (pid == 0)
784                 /* No remote children either.  Finally give up.  */
785                 break;
786
787               /* We got a remote child.  */
788               remote = 1;
789             }
790 #endif /* !__MSDOS__, !Amiga, !WINDOWS32.  */
791
792 #ifdef __MSDOS__
793           /* Life is very different on MSDOS.  */
794           pid = dos_pid - 1;
795           status = dos_status;
796           exit_code = WEXITSTATUS (status);
797           if (exit_code == 0xff)
798             exit_code = -1;
799           exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
800           coredump = 0;
801 #endif /* __MSDOS__ */
802 #ifdef _AMIGA
803           /* Same on Amiga */
804           pid = amiga_pid - 1;
805           status = amiga_status;
806           exit_code = amiga_status;
807           exit_sig = 0;
808           coredump = 0;
809 #endif /* _AMIGA */
810 #ifdef WINDOWS32
811           {
812             HANDLE hPID;
813             HANDLE hcTID, hcPID;
814             DWORD dwWaitStatus = 0;
815             exit_code = 0;
816             exit_sig = 0;
817             coredump = 0;
818
819             /* Record the thread ID of the main process, so that we
820                could suspend it in the signal handler.  */
821             if (!main_thread)
822               {
823                 hcTID = GetCurrentThread ();
824                 hcPID = GetCurrentProcess ();
825                 if (!DuplicateHandle (hcPID, hcTID, hcPID, &main_thread, 0,
826                                       FALSE, DUPLICATE_SAME_ACCESS))
827                   {
828                     DWORD e = GetLastError ();
829                     fprintf (stderr,
830                              "Determine main thread ID (Error %ld: %s)\n",
831                              e, map_windows32_error_to_string (e));
832                   }
833                 else
834                   DB (DB_VERBOSE, ("Main thread handle = %p\n", main_thread));
835               }
836
837             /* wait for anything to finish */
838             hPID = process_wait_for_any (block, &dwWaitStatus);
839             if (hPID)
840               {
841                 /* was an error found on this process? */
842                 int werr = process_last_err (hPID);
843
844                 /* get exit data */
845                 exit_code = process_exit_code (hPID);
846
847                 /* the extra tests of exit_code are here to prevent
848                    map_windows32_error_to_string from calling 'fatal',
849                    which will then call reap_children again */
850                 if (werr && exit_code > 0 && exit_code < WSABASEERR)
851                   fprintf (stderr, "make (e=%d): %s", exit_code,
852                            map_windows32_error_to_string (exit_code));
853
854                 /* signal */
855                 exit_sig = process_signal (hPID);
856
857                 /* cleanup process */
858                 process_cleanup (hPID);
859
860                 coredump = 0;
861               }
862             else if (dwWaitStatus == WAIT_FAILED)
863               {
864                 /* The WaitForMultipleObjects() failed miserably.  Punt.  */
865                 pfatal_with_name ("WaitForMultipleObjects");
866               }
867             else if (dwWaitStatus == WAIT_TIMEOUT)
868               {
869                 /* No child processes are finished.  Give up waiting. */
870                 reap_more = 0;
871                 break;
872               }
873
874             pid = (pid_t) hPID;
875           }
876 #endif /* WINDOWS32 */
877         }
878
879       /* Check if this is the child of the 'shell' function.  */
880       if (!remote && pid == shell_function_pid)
881         {
882           shell_completed (exit_code, exit_sig);
883           break;
884         }
885
886       /* Search for a child matching the deceased one.  */
887       lastc = 0;
888       for (c = children; c != 0; lastc = c, c = c->next)
889         if (c->pid == pid && c->remote == remote)
890           break;
891
892       if (c == 0)
893         /* An unknown child died.
894            Ignore it; it was inherited from our invoker.  */
895         continue;
896
897       DB (DB_JOBS, (exit_sig == 0 && exit_code == 0
898                     ? _("Reaping winning child %p PID %s %s\n")
899                     : _("Reaping losing child %p PID %s %s\n"),
900                     c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
901
902       /* If we have started jobs in this second, remove one.  */
903       if (job_counter)
904         --job_counter;
905
906     process_child:
907
908 #if defined(USE_POSIX_SPAWN)
909       /* Some versions of posix_spawn() do not detect errors such as command
910          not found until after they fork.  In that case they will exit with a
911          code of 127.  Try to detect that and provide a useful error message.
912          Otherwise we'll just show the error below, as normal.  */
913       if (exit_sig == 0 && exit_code == 127 && c->cmd_name)
914         {
915           const char *e = NULL;
916           struct stat st;
917           int r;
918
919           /* There are various ways that this will show a different error than
920              fork/exec.  To really get the right error we'd have to fall back
921              to fork/exec but I don't want to bother with that.  Just do the
922              best we can.  */
923
924           EINTRLOOP(r, stat(c->cmd_name, &st));
925           if (r < 0)
926             e = strerror (errno);
927           else if (S_ISDIR(st.st_mode) || !(st.st_mode & S_IXUSR))
928             e = strerror (EACCES);
929           else if (st.st_size == 0)
930             e = strerror (ENOEXEC);
931
932           if (e)
933             OSS(error, NILF, "%s: %s", c->cmd_name, e);
934         }
935 #endif
936
937       /* Determine the failure status: 0 for success, 1 for updating target in
938          question mode, 2 for anything else.  */
939       if (exit_sig == 0 && exit_code == 0)
940         child_failed = MAKE_SUCCESS;
941       else if (exit_sig == 0 && exit_code == 1 && question_flag && c->recursive)
942         child_failed = MAKE_TROUBLE;
943       else
944         child_failed = MAKE_FAILURE;
945
946       if (c->sh_batch_file)
947         {
948           int rm_status;
949
950           DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
951                         c->sh_batch_file));
952
953           errno = 0;
954           rm_status = remove (c->sh_batch_file);
955           if (rm_status)
956             DB (DB_JOBS, (_("Cleaning up temp batch file %s failed (%d)\n"),
957                           c->sh_batch_file, errno));
958
959           /* all done with memory */
960           free (c->sh_batch_file);
961           c->sh_batch_file = NULL;
962         }
963
964       /* If this child had the good stdin, say it is now free.  */
965       if (c->good_stdin)
966         good_stdin_used = 0;
967
968       dontcare = c->dontcare;
969
970       if (child_failed && !c->noerror && !ignore_errors_flag)
971         {
972           /* The commands failed.  Write an error message,
973              delete non-precious targets, and abort.  */
974           static int delete_on_error = -1;
975
976           if (!dontcare && child_failed == MAKE_FAILURE)
977             child_error (c, exit_code, exit_sig, coredump, 0);
978
979           c->file->update_status = child_failed == MAKE_FAILURE ? us_failed : us_question;
980           if (delete_on_error == -1)
981             {
982               struct file *f = lookup_file (".DELETE_ON_ERROR");
983               delete_on_error = f != 0 && f->is_target;
984             }
985           if (exit_sig != 0 || delete_on_error)
986             delete_child_targets (c);
987         }
988       else
989         {
990           if (child_failed)
991             {
992               /* The commands failed, but we don't care.  */
993               child_error (c, exit_code, exit_sig, coredump, 1);
994               child_failed = 0;
995             }
996
997           /* If there are more commands to run, try to start them.  */
998           if (job_next_command (c))
999             {
1000               if (handling_fatal_signal)
1001                 {
1002                   /* Never start new commands while we are dying.
1003                      Since there are more commands that wanted to be run,
1004                      the target was not completely remade.  So we treat
1005                      this as if a command had failed.  */
1006                   c->file->update_status = us_failed;
1007                 }
1008               else
1009                 {
1010 #ifndef NO_OUTPUT_SYNC
1011                   /* If we're sync'ing per line, write the previous line's
1012                      output before starting the next one.  */
1013                   if (output_sync == OUTPUT_SYNC_LINE)
1014                     output_dump (&c->output);
1015 #endif
1016                   /* Check again whether to start remotely.
1017                      Whether or not we want to changes over time.
1018                      Also, start_remote_job may need state set up
1019                      by start_remote_job_p.  */
1020                   c->remote = start_remote_job_p (0);
1021                   start_job_command (c);
1022                   /* Fatal signals are left blocked in case we were
1023                      about to put that child on the chain.  But it is
1024                      already there, so it is safe for a fatal signal to
1025                      arrive now; it will clean up this child's targets.  */
1026                   unblock_sigs ();
1027                   if (c->file->command_state == cs_running)
1028                     /* We successfully started the new command.
1029                        Loop to reap more children.  */
1030                     continue;
1031                 }
1032
1033               if (c->file->update_status != us_success)
1034                 /* We failed to start the commands.  */
1035                 delete_child_targets (c);
1036             }
1037           else
1038             /* There are no more commands.  We got through them all
1039                without an unignored error.  Now the target has been
1040                successfully updated.  */
1041             c->file->update_status = us_success;
1042         }
1043
1044       /* When we get here, all the commands for c->file are finished.  */
1045
1046 #ifndef NO_OUTPUT_SYNC
1047       /* Synchronize any remaining parallel output.  */
1048       output_dump (&c->output);
1049 #endif
1050
1051       /* At this point c->file->update_status is success or failed.  But
1052          c->file->command_state is still cs_running if all the commands
1053          ran; notice_finished_file looks for cs_running to tell it that
1054          it's interesting to check the file's modtime again now.  */
1055
1056       if (! handling_fatal_signal)
1057         /* Notice if the target of the commands has been changed.
1058            This also propagates its values for command_state and
1059            update_status to its also_make files.  */
1060         notice_finished_file (c->file);
1061
1062       /* Block fatal signals while frobnicating the list, so that
1063          children and job_slots_used are always consistent.  Otherwise
1064          a fatal signal arriving after the child is off the chain and
1065          before job_slots_used is decremented would believe a child was
1066          live and call reap_children again.  */
1067       block_sigs ();
1068
1069       if (c->pid > 0)
1070         {
1071           DB (DB_JOBS, (_("Removing child %p PID %s%s from chain.\n"),
1072                         c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
1073         }
1074
1075       /* There is now another slot open.  */
1076       if (job_slots_used > 0)
1077         job_slots_used -= c->jobslot;
1078
1079       /* Remove the child from the chain and free it.  */
1080       if (lastc == 0)
1081         children = c->next;
1082       else
1083         lastc->next = c->next;
1084
1085       free_child (c);
1086
1087       unblock_sigs ();
1088
1089       /* If the job failed, and the -k flag was not given, die,
1090          unless we are already in the process of dying.  */
1091       if (!err && child_failed && !dontcare && !keep_going_flag &&
1092           /* fatal_error_signal will die with the right signal.  */
1093           !handling_fatal_signal)
1094         die (child_failed);
1095
1096       /* Only block for one child.  */
1097       block = 0;
1098     }
1099
1100   return;
1101 }
1102 \f
1103 /* Free the storage allocated for CHILD.  */
1104
1105 static void
1106 free_child (struct child *child)
1107 {
1108   output_close (&child->output);
1109
1110   if (!jobserver_tokens)
1111     ONS (fatal, NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
1112          child, child->file->name);
1113
1114   /* If we're using the jobserver and this child is not the only outstanding
1115      job, put a token back into the pipe for it.  */
1116
1117   if (jobserver_enabled () && jobserver_tokens > 1)
1118     {
1119       jobserver_release (1);
1120       DB (DB_JOBS, (_("Released token for child %p (%s).\n"),
1121                     child, child->file->name));
1122     }
1123
1124   --jobserver_tokens;
1125
1126   if (handling_fatal_signal) /* Don't bother free'ing if about to die.  */
1127     return;
1128
1129   if (child->command_lines != 0)
1130     {
1131       unsigned int i;
1132       for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
1133         free (child->command_lines[i]);
1134       free (child->command_lines);
1135     }
1136
1137   if (child->environment != 0)
1138     {
1139       char **ep = child->environment;
1140       while (*ep != 0)
1141         free (*ep++);
1142       free (child->environment);
1143     }
1144
1145   free (child->cmd_name);
1146   free (child);
1147 }
1148 \f
1149
1150 /* Start a job to run the commands specified in CHILD.
1151    CHILD is updated to reflect the commands and ID of the child process.
1152
1153    NOTE: On return fatal signals are blocked!  The caller is responsible
1154    for calling 'unblock_sigs', once the new child is safely on the chain so
1155    it can be cleaned up in the event of a fatal signal.  */
1156
1157 static void
1158 start_job_command (struct child *child)
1159 {
1160   int flags;
1161   char *p;
1162 #ifdef VMS
1163 # define FREE_ARGV(_a)
1164   char *argv;
1165 #else
1166 # define FREE_ARGV(_a) do{ if (_a) { free ((_a)[0]); free (_a); } }while(0)
1167   char **argv;
1168 #endif
1169
1170   /* If we have a completely empty commandset, stop now.  */
1171   if (!child->command_ptr)
1172     goto next_command;
1173
1174   /* Combine the flags parsed for the line itself with
1175      the flags specified globally for this target.  */
1176   flags = (child->file->command_flags
1177            | child->file->cmds->lines_flags[child->command_line - 1]);
1178
1179   p = child->command_ptr;
1180   child->noerror = ((flags & COMMANDS_NOERROR) != 0);
1181
1182   while (*p != '\0')
1183     {
1184       if (*p == '@')
1185         flags |= COMMANDS_SILENT;
1186       else if (*p == '+')
1187         flags |= COMMANDS_RECURSE;
1188       else if (*p == '-')
1189         child->noerror = 1;
1190       /* Don't skip newlines.  */
1191       else if (!ISBLANK (*p))
1192         break;
1193       ++p;
1194     }
1195
1196   child->recursive = ((flags & COMMANDS_RECURSE) != 0);
1197
1198   /* Update the file's command flags with any new ones we found.  We only
1199      keep the COMMANDS_RECURSE setting.  Even this isn't 100% correct; we are
1200      now marking more commands recursive than should be in the case of
1201      multiline define/endef scripts where only one line is marked "+".  In
1202      order to really fix this, we'll have to keep a lines_flags for every
1203      actual line, after expansion.  */
1204   child->file->cmds->lines_flags[child->command_line - 1] |= flags & COMMANDS_RECURSE;
1205
1206   /* POSIX requires that a recipe prefix after a backslash-newline should
1207      be ignored.  Remove it now so the output is correct.  */
1208   {
1209     char prefix = child->file->cmds->recipe_prefix;
1210     char *p1, *p2;
1211     p1 = p2 = p;
1212     while (*p1 != '\0')
1213       {
1214         *(p2++) = *p1;
1215         if (p1[0] == '\n' && p1[1] == prefix)
1216           ++p1;
1217         ++p1;
1218       }
1219     *p2 = *p1;
1220   }
1221
1222   /* Figure out an argument list from this command line.  */
1223   {
1224     char *end = 0;
1225 #ifdef VMS
1226     /* Skip any leading whitespace */
1227     while (*p)
1228       {
1229         if (!ISSPACE (*p))
1230           {
1231             if (*p != '\\')
1232               break;
1233             if ((p[1] != '\n') && (p[1] != 'n') && (p[1] != 't'))
1234               break;
1235           }
1236         p++;
1237       }
1238
1239     argv = p;
1240     /* Please note, for VMS argv is a string (not an array of strings) which
1241        contains the complete command line, which for multi-line variables
1242        still includes the newlines.  So detect newlines and set 'end' (which
1243        is used for child->command_ptr) instead of (re-)writing
1244        construct_command_argv */
1245     if (!one_shell)
1246       {
1247         char *s = p;
1248         int instring = 0;
1249         while (*s)
1250           {
1251             if (*s == '"')
1252               instring = !instring;
1253             else if (*s == '\\' && !instring && *(s+1) != 0)
1254               s++;
1255             else if (*s == '\n' && !instring)
1256               {
1257                 end = s;
1258                 break;
1259               }
1260             ++s;
1261           }
1262       }
1263 #else
1264     argv = construct_command_argv (p, &end, child->file,
1265                                    child->file->cmds->lines_flags[child->command_line - 1],
1266                                    &child->sh_batch_file);
1267 #endif
1268     if (end == NULL)
1269       child->command_ptr = NULL;
1270     else
1271       {
1272         *end++ = '\0';
1273         child->command_ptr = end;
1274       }
1275   }
1276
1277   /* If -q was given, say that updating 'failed' if there was any text on the
1278      command line, or 'succeeded' otherwise.  The exit status of 1 tells the
1279      user that -q is saying 'something to do'; the exit status for a random
1280      error is 2.  */
1281   if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
1282     {
1283       FREE_ARGV (argv);
1284 #ifdef VMS
1285       /* On VMS, argv[0] can be a null string here */
1286       if (argv[0] != 0)
1287         {
1288 #endif
1289           child->file->update_status = us_question;
1290           notice_finished_file (child->file);
1291           return;
1292 #ifdef VMS
1293         }
1294 #endif
1295     }
1296
1297   if (touch_flag && !(flags & COMMANDS_RECURSE))
1298     {
1299       /* Go on to the next command.  It might be the recursive one.
1300          We construct ARGV only to find the end of the command line.  */
1301       FREE_ARGV (argv);
1302       argv = 0;
1303     }
1304
1305   if (argv == 0)
1306     {
1307     next_command:
1308 #ifdef __MSDOS__
1309       execute_by_shell = 0;   /* in case construct_command_argv sets it */
1310 #endif
1311       /* This line has no commands.  Go to the next.  */
1312       if (job_next_command (child))
1313         start_job_command (child);
1314       else
1315         {
1316           /* No more commands.  Make sure we're "running"; we might not be if
1317              (e.g.) all commands were skipped due to -n.  */
1318           set_command_state (child->file, cs_running);
1319           child->file->update_status = us_success;
1320           notice_finished_file (child->file);
1321         }
1322
1323       OUTPUT_UNSET();
1324       return;
1325     }
1326
1327   /* Are we going to synchronize this command's output?  Do so if either we're
1328      in SYNC_RECURSE mode or this command is not recursive.  We'll also check
1329      output_sync separately below in case it changes due to error.  */
1330   child->output.syncout = output_sync && (output_sync == OUTPUT_SYNC_RECURSE
1331                                           || !(flags & COMMANDS_RECURSE));
1332
1333   OUTPUT_SET (&child->output);
1334
1335 #ifndef NO_OUTPUT_SYNC
1336   if (! child->output.syncout)
1337     /* We don't want to sync this command: to avoid misordered
1338        output ensure any already-synced content is written.  */
1339     output_dump (&child->output);
1340 #endif
1341
1342   /* Print the command if appropriate.  */
1343   if (just_print_flag || trace_flag
1344       || (!(flags & COMMANDS_SILENT) && !run_silent))
1345     OS (message, 0, "%s", p);
1346
1347   /* Tell update_goal_chain that a command has been started on behalf of
1348      this target.  It is important that this happens here and not in
1349      reap_children (where we used to do it), because reap_children might be
1350      reaping children from a different target.  We want this increment to
1351      guaranteedly indicate that a command was started for the dependency
1352      chain (i.e., update_file recursion chain) we are processing.  */
1353
1354   ++commands_started;
1355
1356   /* Optimize an empty command.  People use this for timestamp rules,
1357      so avoid forking a useless shell.  Do this after we increment
1358      commands_started so make still treats this special case as if it
1359      performed some action (makes a difference as to what messages are
1360      printed, etc.  */
1361
1362 #if !defined(VMS) && !defined(_AMIGA)
1363   if (
1364 #if defined __MSDOS__ || defined (__EMX__)
1365       unixy_shell       /* the test is complicated and we already did it */
1366 #else
1367       (argv[0] && is_bourne_compatible_shell (argv[0]))
1368 #endif
1369       && (argv[1] && argv[1][0] == '-'
1370         &&
1371             ((argv[1][1] == 'c' && argv[1][2] == '\0')
1372           ||
1373              (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
1374       && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1375       && argv[3] == NULL)
1376     {
1377       FREE_ARGV (argv);
1378       goto next_command;
1379     }
1380 #endif  /* !VMS && !_AMIGA */
1381
1382   /* If -n was given, recurse to get the next line in the sequence.  */
1383
1384   if (just_print_flag && !(flags & COMMANDS_RECURSE))
1385     {
1386       FREE_ARGV (argv);
1387       goto next_command;
1388     }
1389
1390   /* We're sure we're going to invoke a command: set up the output.  */
1391   output_start ();
1392
1393   /* Flush the output streams so they won't have things written twice.  */
1394
1395   fflush (stdout);
1396   fflush (stderr);
1397
1398   /* Decide whether to give this child the 'good' standard input
1399      (one that points to the terminal or whatever), or the 'bad' one
1400      that points to the read side of a broken pipe.  */
1401
1402   child->good_stdin = !good_stdin_used;
1403   if (child->good_stdin)
1404     good_stdin_used = 1;
1405
1406   child->deleted = 0;
1407
1408 #ifndef _AMIGA
1409   /* Set up the environment for the child.  */
1410   if (child->environment == 0)
1411     child->environment = target_environment (child->file);
1412 #endif
1413
1414 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1415
1416 #ifndef VMS
1417   /* start_waiting_job has set CHILD->remote if we can start a remote job.  */
1418   if (child->remote)
1419     {
1420       int is_remote, used_stdin;
1421       pid_t id;
1422       if (start_remote_job (argv, child->environment,
1423                             child->good_stdin ? 0 : get_bad_stdin (),
1424                             &is_remote, &id, &used_stdin))
1425         /* Don't give up; remote execution may fail for various reasons.  If
1426            so, simply run the job locally.  */
1427         goto run_local;
1428       else
1429         {
1430           if (child->good_stdin && !used_stdin)
1431             {
1432               child->good_stdin = 0;
1433               good_stdin_used = 0;
1434             }
1435           child->remote = is_remote;
1436           child->pid = id;
1437         }
1438     }
1439   else
1440 #endif /* !VMS */
1441     {
1442       /* Fork the child process.  */
1443
1444       char **parent_environ;
1445
1446     run_local:
1447       block_sigs ();
1448
1449       child->remote = 0;
1450
1451 #ifdef VMS
1452       child->pid = child_execute_job ((struct childbase *)child, 1, argv);
1453
1454 #else
1455
1456       parent_environ = environ;
1457
1458       jobserver_pre_child (flags & COMMANDS_RECURSE);
1459
1460       child->pid = child_execute_job ((struct childbase *)child,
1461                                       child->good_stdin, argv);
1462
1463       environ = parent_environ; /* Restore value child may have clobbered.  */
1464       jobserver_post_child (flags & COMMANDS_RECURSE);
1465
1466 #endif /* !VMS */
1467     }
1468
1469 #else   /* __MSDOS__ or Amiga or WINDOWS32 */
1470 #ifdef __MSDOS__
1471   {
1472     int proc_return;
1473
1474     block_sigs ();
1475     dos_status = 0;
1476
1477     /* We call 'system' to do the job of the SHELL, since stock DOS
1478        shell is too dumb.  Our 'system' knows how to handle long
1479        command lines even if pipes/redirection is needed; it will only
1480        call COMMAND.COM when its internal commands are used.  */
1481     if (execute_by_shell)
1482       {
1483         char *cmdline = argv[0];
1484         /* We don't have a way to pass environment to 'system',
1485            so we need to save and restore ours, sigh...  */
1486         char **parent_environ = environ;
1487
1488         environ = child->environment;
1489
1490         /* If we have a *real* shell, tell 'system' to call
1491            it to do everything for us.  */
1492         if (unixy_shell)
1493           {
1494             /* A *real* shell on MSDOS may not support long
1495                command lines the DJGPP way, so we must use 'system'.  */
1496             cmdline = argv[2];  /* get past "shell -c" */
1497           }
1498
1499         dos_command_running = 1;
1500         proc_return = system (cmdline);
1501         environ = parent_environ;
1502         execute_by_shell = 0;   /* for the next time */
1503       }
1504     else
1505       {
1506         dos_command_running = 1;
1507         proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1508       }
1509
1510     /* Need to unblock signals before turning off
1511        dos_command_running, so that child's signals
1512        will be treated as such (see fatal_error_signal).  */
1513     unblock_sigs ();
1514     dos_command_running = 0;
1515
1516     /* If the child got a signal, dos_status has its
1517        high 8 bits set, so be careful not to alter them.  */
1518     if (proc_return == -1)
1519       dos_status |= 0xff;
1520     else
1521       dos_status |= (proc_return & 0xff);
1522     ++dead_children;
1523     child->pid = dos_pid++;
1524   }
1525 #endif /* __MSDOS__ */
1526 #ifdef _AMIGA
1527   amiga_status = MyExecute (argv);
1528
1529   ++dead_children;
1530   child->pid = amiga_pid++;
1531   if (amiga_batch_file)
1532   {
1533      amiga_batch_file = 0;
1534      DeleteFile (amiga_bname);        /* Ignore errors.  */
1535   }
1536 #endif  /* Amiga */
1537 #ifdef WINDOWS32
1538   {
1539       HANDLE hPID;
1540       char* arg0;
1541       int outfd = FD_STDOUT;
1542       int errfd = FD_STDERR;
1543
1544       /* make UNC paths safe for CreateProcess -- backslash format */
1545       arg0 = argv[0];
1546       if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1547         for ( ; arg0 && *arg0; arg0++)
1548           if (*arg0 == '/')
1549             *arg0 = '\\';
1550
1551       /* make sure CreateProcess() has Path it needs */
1552       sync_Path_environment ();
1553
1554 #ifndef NO_OUTPUT_SYNC
1555       /* Divert child output if output_sync in use.  */
1556       if (child->output.syncout)
1557         {
1558           if (child->output.out >= 0)
1559             outfd = child->output.out;
1560           if (child->output.err >= 0)
1561             errfd = child->output.err;
1562         }
1563 #else
1564       outfd = errfd = -1;
1565 #endif
1566       hPID = process_easy (argv, child->environment, outfd, errfd);
1567
1568       if (hPID != INVALID_HANDLE_VALUE)
1569         child->pid = (pid_t) hPID;
1570       else
1571         {
1572           int i;
1573           unblock_sigs ();
1574           fprintf (stderr,
1575                    _("process_easy() failed to launch process (e=%ld)\n"),
1576                    process_last_err (hPID));
1577           for (i = 0; argv[i]; i++)
1578             fprintf (stderr, "%s ", argv[i]);
1579           fprintf (stderr, _("\nCounted %d args in failed launch\n"), i);
1580           child->pid = -1;
1581         }
1582   }
1583 #endif /* WINDOWS32 */
1584 #endif  /* __MSDOS__ or Amiga or WINDOWS32 */
1585
1586   /* Bump the number of jobs started in this second.  */
1587   if (child->pid >= 0)
1588     ++job_counter;
1589
1590   /* Set the state to running.  */
1591   set_command_state (child->file, cs_running);
1592
1593   /* Free the storage used by the child's argument list.  */
1594   FREE_ARGV (argv);
1595
1596   OUTPUT_UNSET();
1597
1598 #undef FREE_ARGV
1599 }
1600
1601 /* Try to start a child running.
1602    Returns nonzero if the child was started (and maybe finished), or zero if
1603    the load was too high and the child was put on the 'waiting_jobs' chain.  */
1604
1605 static int
1606 start_waiting_job (struct child *c)
1607 {
1608   struct file *f = c->file;
1609
1610   /* If we can start a job remotely, we always want to, and don't care about
1611      the local load average.  We record that the job should be started
1612      remotely in C->remote for start_job_command to test.  */
1613
1614   c->remote = start_remote_job_p (1);
1615
1616   /* If we are running at least one job already and the load average
1617      is too high, make this one wait.  */
1618   if (!c->remote
1619       && ((job_slots_used > 0 && load_too_high ())
1620 #ifdef WINDOWS32
1621           || process_table_full ()
1622 #endif
1623           ))
1624     {
1625       /* Put this child on the chain of children waiting for the load average
1626          to go down.  */
1627       set_command_state (f, cs_running);
1628       c->next = waiting_jobs;
1629       waiting_jobs = c;
1630       return 0;
1631     }
1632
1633   /* Start the first command; reap_children will run later command lines.  */
1634   start_job_command (c);
1635
1636   switch (f->command_state)
1637     {
1638     case cs_running:
1639       c->next = children;
1640       if (c->pid > 0)
1641         {
1642           DB (DB_JOBS, (_("Putting child %p (%s) PID %s%s on the chain.\n"),
1643                         c, c->file->name, pid2str (c->pid),
1644                         c->remote ? _(" (remote)") : ""));
1645           /* One more job slot is in use.  */
1646           ++job_slots_used;
1647           assert (c->jobslot == 0);
1648           c->jobslot = 1;
1649         }
1650       children = c;
1651       unblock_sigs ();
1652       break;
1653
1654     case cs_not_started:
1655       /* All the command lines turned out to be empty.  */
1656       f->update_status = us_success;
1657       /* FALLTHROUGH */
1658
1659     case cs_finished:
1660       notice_finished_file (f);
1661       free_child (c);
1662       break;
1663
1664     default:
1665       assert (f->command_state == cs_finished);
1666       break;
1667     }
1668
1669   return 1;
1670 }
1671
1672 /* Create a 'struct child' for FILE and start its commands running.  */
1673
1674 void
1675 new_job (struct file *file)
1676 {
1677   struct commands *cmds = file->cmds;
1678   struct child *c;
1679   char **lines;
1680   unsigned int i;
1681
1682   /* Let any previously decided-upon jobs that are waiting
1683      for the load to go down start before this new one.  */
1684   start_waiting_jobs ();
1685
1686   /* Reap any children that might have finished recently.  */
1687   reap_children (0, 0);
1688
1689   /* Chop the commands up into lines if they aren't already.  */
1690   chop_commands (cmds);
1691
1692   /* Start the command sequence, record it in a new
1693      'struct child', and add that to the chain.  */
1694
1695   c = xcalloc (sizeof (struct child));
1696   output_init (&c->output);
1697
1698   c->file = file;
1699   c->sh_batch_file = NULL;
1700
1701   /* Cache dontcare flag because file->dontcare can be changed once we
1702      return. Check dontcare inheritance mechanism for details.  */
1703   c->dontcare = file->dontcare;
1704
1705   /* Start saving output in case the expansion uses $(info ...) etc.  */
1706   OUTPUT_SET (&c->output);
1707
1708   /* Expand the command lines and store the results in LINES.  */
1709   lines = xmalloc (cmds->ncommand_lines * sizeof (char *));
1710   for (i = 0; i < cmds->ncommand_lines; ++i)
1711     {
1712       /* Collapse backslash-newline combinations that are inside variable
1713          or function references.  These are left alone by the parser so
1714          that they will appear in the echoing of commands (where they look
1715          nice); and collapsed by construct_command_argv when it tokenizes.
1716          But letting them survive inside function invocations loses because
1717          we don't want the functions to see them as part of the text.  */
1718
1719       char *in, *out, *ref;
1720
1721       /* IN points to where in the line we are scanning.
1722          OUT points to where in the line we are writing.
1723          When we collapse a backslash-newline combination,
1724          IN gets ahead of OUT.  */
1725
1726       in = out = cmds->command_lines[i];
1727       while ((ref = strchr (in, '$')) != 0)
1728         {
1729           ++ref;                /* Move past the $.  */
1730
1731           if (out != in)
1732             /* Copy the text between the end of the last chunk
1733                we processed (where IN points) and the new chunk
1734                we are about to process (where REF points).  */
1735             memmove (out, in, ref - in);
1736
1737           /* Move both pointers past the boring stuff.  */
1738           out += ref - in;
1739           in = ref;
1740
1741           if (*ref == '(' || *ref == '{')
1742             {
1743               char openparen = *ref;
1744               char closeparen = openparen == '(' ? ')' : '}';
1745               char *outref;
1746               int count;
1747               char *p;
1748
1749               *out++ = *in++;   /* Copy OPENPAREN.  */
1750               outref = out;
1751               /* IN now points past the opening paren or brace.
1752                  Count parens or braces until it is matched.  */
1753               count = 0;
1754               while (*in != '\0')
1755                 {
1756                   if (*in == closeparen && --count < 0)
1757                     break;
1758                   else if (*in == '\\' && in[1] == '\n')
1759                     {
1760                       /* We have found a backslash-newline inside a
1761                          variable or function reference.  Eat it and
1762                          any following whitespace.  */
1763
1764                       int quoted = 0;
1765                       for (p = in - 1; p > ref && *p == '\\'; --p)
1766                         quoted = !quoted;
1767
1768                       if (quoted)
1769                         /* There were two or more backslashes, so this is
1770                            not really a continuation line.  We don't collapse
1771                            the quoting backslashes here as is done in
1772                            collapse_continuations, because the line will
1773                            be collapsed again after expansion.  */
1774                         *out++ = *in++;
1775                       else
1776                         {
1777                           /* Skip the backslash, newline, and whitespace.  */
1778                           in += 2;
1779                           NEXT_TOKEN (in);
1780
1781                           /* Discard any preceding whitespace that has
1782                              already been written to the output.  */
1783                           while (out > outref && ISBLANK (out[-1]))
1784                             --out;
1785
1786                           /* Replace it all with a single space.  */
1787                           *out++ = ' ';
1788                         }
1789                     }
1790                   else
1791                     {
1792                       if (*in == openparen)
1793                         ++count;
1794
1795                       *out++ = *in++;
1796                     }
1797                 }
1798             }
1799         }
1800
1801       /* There are no more references in this line to worry about.
1802          Copy the remaining uninteresting text to the output.  */
1803       if (out != in)
1804         memmove (out, in, strlen (in) + 1);
1805
1806       /* Finally, expand the line.  */
1807       cmds->fileinfo.offset = i;
1808       lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1809                                                      file);
1810     }
1811
1812   cmds->fileinfo.offset = 0;
1813   c->command_lines = lines;
1814
1815   /* Fetch the first command line to be run.  */
1816   job_next_command (c);
1817
1818   /* Wait for a job slot to be freed up.  If we allow an infinite number
1819      don't bother; also job_slots will == 0 if we're using the jobserver.  */
1820
1821   if (job_slots != 0)
1822     while (job_slots_used == job_slots)
1823       reap_children (1, 0);
1824
1825 #ifdef MAKE_JOBSERVER
1826   /* If we are controlling multiple jobs make sure we have a token before
1827      starting the child. */
1828
1829   /* This can be inefficient.  There's a decent chance that this job won't
1830      actually have to run any subprocesses: the command script may be empty
1831      or otherwise optimized away.  It would be nice if we could defer
1832      obtaining a token until just before we need it, in start_job_command.
1833      To do that we'd need to keep track of whether we'd already obtained a
1834      token (since start_job_command is called for each line of the job, not
1835      just once).  Also more thought needs to go into the entire algorithm;
1836      this is where the old parallel job code waits, so...  */
1837
1838   else if (jobserver_enabled ())
1839     while (1)
1840       {
1841         int got_token;
1842
1843         DB (DB_JOBS, ("Need a job token; we %shave children\n",
1844                       children ? "" : "don't "));
1845
1846         /* If we don't already have a job started, use our "free" token.  */
1847         if (!jobserver_tokens)
1848           break;
1849
1850         /* Prepare for jobserver token acquisition.  */
1851         jobserver_pre_acquire ();
1852
1853         /* Reap anything that's currently waiting.  */
1854         reap_children (0, 0);
1855
1856         /* Kick off any jobs we have waiting for an opportunity that
1857            can run now (i.e., waiting for load). */
1858         start_waiting_jobs ();
1859
1860         /* If our "free" slot is available, use it; we don't need a token.  */
1861         if (!jobserver_tokens)
1862           break;
1863
1864         /* There must be at least one child already, or we have no business
1865            waiting for a token. */
1866         if (!children)
1867           O (fatal, NILF, "INTERNAL: no children as we go to sleep on read\n");
1868
1869         /* Get a token.  */
1870         got_token = jobserver_acquire (waiting_jobs != NULL);
1871
1872         /* If we got one, we're done here.  */
1873         if (got_token == 1)
1874           {
1875             DB (DB_JOBS, (_("Obtained token for child %p (%s).\n"),
1876                           c, c->file->name));
1877             break;
1878           }
1879       }
1880 #endif
1881
1882   ++jobserver_tokens;
1883
1884   /* Trace the build.
1885      Use message here so that changes to working directories are logged.  */
1886   if (trace_flag)
1887     {
1888       char *newer = allocated_variable_expand_for_file ("$?", c->file);
1889       const char *nm;
1890
1891       if (! cmds->fileinfo.filenm)
1892         nm = _("<builtin>");
1893       else
1894         {
1895           char *n = alloca (strlen (cmds->fileinfo.filenm) + 1 + 11 + 1);
1896           sprintf (n, "%s:%lu", cmds->fileinfo.filenm, cmds->fileinfo.lineno);
1897           nm = n;
1898         }
1899
1900       if (newer[0] == '\0')
1901         OSS (message, 0,
1902              _("%s: target '%s' does not exist"), nm, c->file->name);
1903       else
1904         OSSS (message, 0,
1905               _("%s: update target '%s' due to: %s"), nm, c->file->name, newer);
1906
1907       free (newer);
1908     }
1909
1910   /* The job is now primed.  Start it running.
1911      (This will notice if there is in fact no recipe.)  */
1912   start_waiting_job (c);
1913
1914   if (job_slots == 1 || not_parallel)
1915     /* Since there is only one job slot, make things run linearly.
1916        Wait for the child to die, setting the state to 'cs_finished'.  */
1917     while (file->command_state == cs_running)
1918       reap_children (1, 0);
1919
1920   OUTPUT_UNSET ();
1921   return;
1922 }
1923 \f
1924 /* Move CHILD's pointers to the next command for it to execute.
1925    Returns nonzero if there is another command.  */
1926
1927 static int
1928 job_next_command (struct child *child)
1929 {
1930   while (child->command_ptr == 0 || *child->command_ptr == '\0')
1931     {
1932       /* There are no more lines in the expansion of this line.  */
1933       if (child->command_line == child->file->cmds->ncommand_lines)
1934         {
1935           /* There are no more lines to be expanded.  */
1936           child->command_ptr = 0;
1937           child->file->cmds->fileinfo.offset = 0;
1938           return 0;
1939         }
1940       else
1941         /* Get the next line to run.  */
1942         child->command_ptr = child->command_lines[child->command_line++];
1943     }
1944
1945   child->file->cmds->fileinfo.offset = child->command_line - 1;
1946   return 1;
1947 }
1948
1949 /* Determine if the load average on the system is too high to start a new job.
1950
1951    On systems which provide /proc/loadavg (e.g., Linux), we use an idea
1952    provided by Sven C. Dack <sven.c.dack@sky.com>: retrieve the current number
1953    of processes the kernel is running and, if it's greater than the requested
1954    load we don't allow another job to start.  We allow a job to start with
1955    equal processes since one of those will be for make itself, which will then
1956    pause waiting for jobs to clear.
1957
1958    Otherwise, we obtain the system load average and compare that.
1959
1960    The system load average is only recomputed once every N (N>=1) seconds.
1961    However, a very parallel make can easily start tens or even hundreds of
1962    jobs in a second, which brings the system to its knees for a while until
1963    that first batch of jobs clears out.
1964
1965    To avoid this we use a weighted algorithm to try to account for jobs which
1966    have been started since the last second, and guess what the load average
1967    would be now if it were computed.
1968
1969    This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1970    based on load average being recomputed once per second, which is
1971    (apparently) how Solaris operates.  Linux recomputes only once every 5
1972    seconds, but Linux is handled by the /proc/loadavg algorithm above.
1973
1974    Thomas writes:
1975
1976 !      calculate something load-oid and add to the observed sys.load,
1977 !      so that latter can catch up:
1978 !      - every job started increases jobctr;
1979 !      - every dying job decreases a positive jobctr;
1980 !      - the jobctr value gets zeroed every change of seconds,
1981 !        after its value*weight_b is stored into the 'backlog' value last_sec
1982 !      - weight_a times the sum of jobctr and last_sec gets
1983 !        added to the observed sys.load.
1984 !
1985 !      The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1986 !      machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1987 !      sub-shelled commands (rm, echo, sed...) for tests.
1988 !      lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1989 !      resulted in significant excession of the load limit, raising it
1990 !      (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1991 !      reach the limit in most test cases.
1992 !
1993 !      lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1994 !      exceeding the limit for longer-running stuff (compile jobs in
1995 !      the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1996 !      small jobs' effects.
1997
1998  */
1999
2000 #define LOAD_WEIGHT_A           0.25
2001 #define LOAD_WEIGHT_B           0.25
2002
2003 static int
2004 load_too_high (void)
2005 {
2006 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
2007   return 1;
2008 #else
2009   static double last_sec;
2010   static time_t last_now;
2011
2012   /* This is disabled by default for now, because it will behave badly if the
2013      user gives a value > the number of cores; in that situation the load will
2014      never be exceeded, this function always returns false, and we'll start
2015      all the jobs.  Also, it's not quite right to limit jobs to the number of
2016      cores not busy since a job takes some time to start etc.  Maybe that's
2017      OK, I'm not sure exactly how to handle that, but for sure we need to
2018      clamp this value at the number of cores before this can be enabled.
2019    */
2020 #define PROC_FD_INIT -1
2021   static int proc_fd = PROC_FD_INIT;
2022
2023   double load, guess;
2024   time_t now;
2025
2026 #ifdef WINDOWS32
2027   /* sub_proc.c is limited in the number of objects it can wait for. */
2028   if (process_table_full ())
2029     return 1;
2030 #endif
2031
2032   if (max_load_average < 0)
2033     return 0;
2034
2035   /* If we haven't tried to open /proc/loadavg, try now.  */
2036 #define LOADAVG "/proc/loadavg"
2037   if (proc_fd == -2)
2038     {
2039       EINTRLOOP (proc_fd, open (LOADAVG, O_RDONLY));
2040       if (proc_fd < 0)
2041         DB (DB_JOBS, ("Using system load detection method.\n"));
2042       else
2043         {
2044           DB (DB_JOBS, ("Using " LOADAVG " load detection method.\n"));
2045           fd_noinherit (proc_fd);
2046         }
2047     }
2048
2049   /* Try to read /proc/loadavg if we managed to open it.  */
2050   if (proc_fd >= 0)
2051     {
2052       int r;
2053
2054       EINTRLOOP (r, lseek (proc_fd, 0, SEEK_SET));
2055       if (r >= 0)
2056         {
2057 #define PROC_LOADAVG_SIZE 64
2058           char avg[PROC_LOADAVG_SIZE+1];
2059
2060           EINTRLOOP (r, read (proc_fd, avg, PROC_LOADAVG_SIZE));
2061           if (r >= 0)
2062             {
2063               const char *p;
2064
2065               /* The syntax of /proc/loadavg is:
2066                     <1m> <5m> <15m> <running>/<total> <pid>
2067                  The load is considered too high if there are more jobs
2068                  running than the requested average.  */
2069
2070               avg[r] = '\0';
2071               p = strchr (avg, ' ');
2072               if (p)
2073                 p = strchr (p+1, ' ');
2074               if (p)
2075                 p = strchr (p+1, ' ');
2076
2077               if (p && ISDIGIT(p[1]))
2078                 {
2079                   int cnt = atoi (p+1);
2080                   DB (DB_JOBS, ("Running: system = %d / make = %u (max requested = %f)\n",
2081                                 cnt, job_slots_used, max_load_average));
2082                   return (double)cnt > max_load_average;
2083                 }
2084
2085               DB (DB_JOBS, ("Failed to parse " LOADAVG ": %s\n", avg));
2086             }
2087         }
2088
2089       /* If we got here, something went wrong.  Give up on this method.  */
2090       if (r < 0)
2091         DB (DB_JOBS, ("Failed to read " LOADAVG ": %s\n", strerror (errno)));
2092
2093       close (proc_fd);
2094       proc_fd = -1;
2095     }
2096
2097   /* Find the real system load average.  */
2098   make_access ();
2099   if (getloadavg (&load, 1) != 1)
2100     {
2101       static int lossage = -1;
2102       /* Complain only once for the same error.  */
2103       if (lossage == -1 || errno != lossage)
2104         {
2105           if (errno == 0)
2106             /* An errno value of zero means getloadavg is just unsupported.  */
2107             O (error, NILF,
2108                _("cannot enforce load limits on this operating system"));
2109           else
2110             perror_with_name (_("cannot enforce load limit: "), "getloadavg");
2111         }
2112       lossage = errno;
2113       load = 0;
2114     }
2115   user_access ();
2116
2117   /* If we're in a new second zero the counter and correct the backlog
2118      value.  Only keep the backlog for one extra second; after that it's 0.  */
2119   now = time (NULL);
2120   if (last_now < now)
2121     {
2122       if (last_now == now - 1)
2123         last_sec = LOAD_WEIGHT_B * job_counter;
2124       else
2125         last_sec = 0.0;
2126
2127       job_counter = 0;
2128       last_now = now;
2129     }
2130
2131   /* Try to guess what the load would be right now.  */
2132   guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
2133
2134   DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
2135                 guess, load, max_load_average));
2136
2137   return guess >= max_load_average;
2138 #endif
2139 }
2140
2141 /* Start jobs that are waiting for the load to be lower.  */
2142
2143 void
2144 start_waiting_jobs (void)
2145 {
2146   struct child *job;
2147
2148   if (waiting_jobs == 0)
2149     return;
2150
2151   do
2152     {
2153       /* Check for recently deceased descendants.  */
2154       reap_children (0, 0);
2155
2156       /* Take a job off the waiting list.  */
2157       job = waiting_jobs;
2158       waiting_jobs = job->next;
2159
2160       /* Try to start that job.  We break out of the loop as soon
2161          as start_waiting_job puts one back on the waiting list.  */
2162     }
2163   while (start_waiting_job (job) && waiting_jobs != 0);
2164
2165   return;
2166 }
2167 \f
2168 #ifndef WINDOWS32
2169
2170 /* EMX: Start a child process. This function returns the new pid.  */
2171 # if defined __EMX__
2172 pid_t
2173 child_execute_job (struct childbase *child, int good_stdin, char **argv)
2174 {
2175   pid_t pid;
2176   int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
2177   int fdout = FD_STDOUT;
2178   int fderr = FD_STDERR;
2179   int save_fdin = -1;
2180   int save_fdout = -1;
2181   int save_fderr = -1;
2182
2183   /* Divert child output if we want to capture output.  */
2184   if (child->output.syncout)
2185     {
2186       if (child->output.out >= 0)
2187         fdout = child->output.out;
2188       if (child->output.err >= 0)
2189         fderr = child->output.err;
2190     }
2191
2192   /* For each FD which needs to be redirected first make a dup of the standard
2193      FD to save and mark it close on exec so our child won't see it.  Then
2194      dup2() the standard FD to the redirect FD, and also mark the redirect FD
2195      as close on exec. */
2196   if (fdin != FD_STDIN)
2197     {
2198       save_fdin = dup (FD_STDIN);
2199       if (save_fdin < 0)
2200         O (fatal, NILF, _("no more file handles: could not duplicate stdin\n"));
2201       fd_noinherit (save_fdin);
2202
2203       dup2 (fdin, FD_STDIN);
2204       fd_noinherit (fdin);
2205     }
2206
2207   if (fdout != FD_STDOUT)
2208     {
2209       save_fdout = dup (FD_STDOUT);
2210       if (save_fdout < 0)
2211         O (fatal, NILF,
2212            _("no more file handles: could not duplicate stdout\n"));
2213       fd_noinherit (save_fdout);
2214
2215       dup2 (fdout, FD_STDOUT);
2216       fd_noinherit (fdout);
2217     }
2218
2219   if (fderr != FD_STDERR)
2220     {
2221       if (fderr != fdout)
2222         {
2223           save_fderr = dup (FD_STDERR);
2224           if (save_fderr < 0)
2225             O (fatal, NILF,
2226                _("no more file handles: could not duplicate stderr\n"));
2227           fd_noinherit (save_fderr);
2228         }
2229
2230       dup2 (fderr, FD_STDERR);
2231       fd_noinherit (fderr);
2232     }
2233
2234   /* Run the command.  */
2235   pid = exec_command (argv, child->environment);
2236
2237   /* Restore stdout/stdin/stderr of the parent and close temporary FDs.  */
2238   if (save_fdin >= 0)
2239     {
2240       if (dup2 (save_fdin, FD_STDIN) != FD_STDIN)
2241         O (fatal, NILF, _("Could not restore stdin\n"));
2242       else
2243         close (save_fdin);
2244     }
2245
2246   if (save_fdout >= 0)
2247     {
2248       if (dup2 (save_fdout, FD_STDOUT) != FD_STDOUT)
2249         O (fatal, NILF, _("Could not restore stdout\n"));
2250       else
2251         close (save_fdout);
2252     }
2253
2254   if (save_fderr >= 0)
2255     {
2256       if (dup2 (save_fderr, FD_STDERR) != FD_STDERR)
2257         O (fatal, NILF, _("Could not restore stderr\n"));
2258       else
2259         close (save_fderr);
2260     }
2261
2262   if (pid < 0)
2263     OSS (error, NILF, "%s: %s", argv[0], strerror (errno));
2264
2265   return pid;
2266 }
2267
2268 #elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
2269
2270 /* POSIX:
2271    Create a child process executing the command in ARGV.
2272    Returns the PID or -1.  */
2273 pid_t
2274 child_execute_job (struct childbase *child, int good_stdin, char **argv)
2275 {
2276   const int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
2277   int fdout = FD_STDOUT;
2278   int fderr = FD_STDERR;
2279   pid_t pid;
2280   int r;
2281 #if defined(USE_POSIX_SPAWN)
2282   char *cmd;
2283   posix_spawnattr_t attr;
2284   posix_spawn_file_actions_t fa;
2285   short flags = 0;
2286 #endif
2287
2288   /* Divert child output if we want to capture it.  */
2289   if (child->output.syncout)
2290     {
2291       if (child->output.out >= 0)
2292         fdout = child->output.out;
2293       if (child->output.err >= 0)
2294         fderr = child->output.err;
2295     }
2296
2297 #if !defined(USE_POSIX_SPAWN)
2298
2299   pid = vfork();
2300   if (pid != 0)
2301     return pid;
2302
2303   /* We are the child.  */
2304   unblock_all_sigs ();
2305
2306 #ifdef SET_STACK_SIZE
2307   /* Reset limits, if necessary.  */
2308   if (stack_limit.rlim_cur)
2309     setrlimit (RLIMIT_STACK, &stack_limit);
2310 #endif
2311
2312   /* For any redirected FD, dup2() it to the standard FD.
2313      They are all marked close-on-exec already.  */
2314   if (fdin >= 0 && fdin != FD_STDIN)
2315     EINTRLOOP (r, dup2 (fdin, FD_STDIN));
2316   if (fdout != FD_STDOUT)
2317     EINTRLOOP (r, dup2 (fdout, FD_STDOUT));
2318   if (fderr != FD_STDERR)
2319     EINTRLOOP (r, dup2 (fderr, FD_STDERR));
2320
2321   /* Run the command.  */
2322   exec_command (argv, child->environment);
2323
2324 #else /* USE_POSIX_SPAWN */
2325
2326   if ((r = posix_spawnattr_init (&attr)) != 0)
2327     goto done;
2328
2329   if ((r = posix_spawn_file_actions_init (&fa)) != 0)
2330     {
2331       posix_spawnattr_destroy (&attr);
2332       goto done;
2333     }
2334
2335   /* Unblock all signals.  */
2336 #ifdef HAVE_POSIX_SPAWNATTR_SETSIGMASK
2337   {
2338     sigset_t mask;
2339     sigemptyset (&mask);
2340     r = posix_spawnattr_setsigmask (&attr, &mask);
2341     if (r != 0)
2342       goto cleanup;
2343     flags |= POSIX_SPAWN_SETSIGMASK;
2344   }
2345 #endif /* have posix_spawnattr_setsigmask() */
2346
2347   /* USEVFORK can give significant speedup on systems where it's available.  */
2348 #ifdef POSIX_SPAWN_USEVFORK
2349   flags |= POSIX_SPAWN_USEVFORK;
2350 #endif
2351
2352   /* For any redirected FD, dup2() it to the standard FD.
2353      They are all marked close-on-exec already.  */
2354   if (fdin >= 0 && fdin != FD_STDIN)
2355     if ((r = posix_spawn_file_actions_adddup2 (&fa, fdin, FD_STDIN)) != 0)
2356       goto cleanup;
2357   if (fdout != FD_STDOUT)
2358     if ((r = posix_spawn_file_actions_adddup2 (&fa, fdout, FD_STDOUT)) != 0)
2359       goto cleanup;
2360   if (fderr != FD_STDERR)
2361     if ((r = posix_spawn_file_actions_adddup2 (&fa, fderr, FD_STDERR)) != 0)
2362       goto cleanup;
2363
2364   /* Be the user, permanently.  */
2365   flags |= POSIX_SPAWN_RESETIDS;
2366
2367   /* Apply the spawn flags.  */
2368   if ((r = posix_spawnattr_setflags (&attr, flags)) != 0)
2369     goto cleanup;
2370
2371   /* Look up the program on the child's PATH, if needed.  */
2372   {
2373     const char *p = NULL;
2374     char **pp;
2375
2376     for (pp = child->environment; *pp != NULL; ++pp)
2377       if ((*pp)[0] == 'P' && (*pp)[1] == 'A' && (*pp)[2] == 'T'
2378           && (*pp)[3] == 'H' &&(*pp)[4] == '=')
2379         {
2380           p = (*pp) + 5;
2381           break;
2382         }
2383
2384     cmd = (char *)find_in_given_path (argv[0], p, 0);
2385   }
2386
2387   if (!cmd)
2388     {
2389       r = errno;
2390       goto cleanup;
2391     }
2392
2393   /* Start the program.  */
2394   while ((r = posix_spawn (&pid, cmd, &fa, &attr, argv,
2395                            child->environment)) == EINTR)
2396     ;
2397
2398   /* posix_spawn() doesn't provide sh fallback like exec() does; implement
2399      it here.  POSIX doesn't specify the path to sh so use the default.  */
2400
2401   if (r == ENOEXEC)
2402     {
2403       char **nargv;
2404       char **pp;
2405       size_t l = 0;
2406
2407       for (pp = argv; *pp != NULL; ++pp)
2408         ++l;
2409
2410       nargv = xmalloc (sizeof (char *) * (l + 3));
2411       nargv[0] = (char *)default_shell;
2412       nargv[1] = cmd;
2413       memcpy (&nargv[2], &argv[1], sizeof (char *) * l);
2414
2415       while ((r = posix_spawn (&pid, nargv[0], &fa, &attr, nargv,
2416                                child->environment)) == EINTR)
2417         ;
2418
2419       free (nargv);
2420     }
2421
2422   if (r == 0)
2423     {
2424       /* Spawn succeeded but may fail later: remember the command.  */
2425       free (child->cmd_name);
2426       if (cmd != argv[0])
2427         child->cmd_name = cmd;
2428       else
2429         child->cmd_name = xstrdup(cmd);
2430     }
2431
2432  cleanup:
2433   posix_spawn_file_actions_destroy (&fa);
2434   posix_spawnattr_destroy (&attr);
2435
2436  done:
2437   if (r != 0)
2438     pid = -1;
2439
2440 #endif /* USE_POSIX_SPAWN */
2441
2442   if (pid < 0)
2443     OSS (error, NILF, "%s: %s", argv[0], strerror (r));
2444
2445   return pid;
2446 }
2447 #endif /* !AMIGA && !__MSDOS__ && !VMS */
2448 #endif /* !WINDOWS32 */
2449 \f
2450 #ifndef _AMIGA
2451 /* Replace the current process with one running the command in ARGV,
2452    with environment ENVP.  This function does not return.  */
2453
2454 /* EMX: This function returns the pid of the child process.  */
2455 # ifdef __EMX__
2456 pid_t
2457 # else
2458 void
2459 # endif
2460 exec_command (char **argv, char **envp)
2461 {
2462 #ifdef VMS
2463   /* to work around a problem with signals and execve: ignore them */
2464 #ifdef SIGCHLD
2465   signal (SIGCHLD,SIG_IGN);
2466 #endif
2467   /* Run the program.  */
2468   execve (argv[0], argv, envp);
2469   OSS (error, NILF, "%s: %s", argv[0], strerror (errno));
2470   _exit (EXIT_FAILURE);
2471 #else
2472 #ifdef WINDOWS32
2473   HANDLE hPID;
2474   HANDLE hWaitPID;
2475   int exit_code = EXIT_FAILURE;
2476
2477   /* make sure CreateProcess() has Path it needs */
2478   sync_Path_environment ();
2479
2480   /* launch command */
2481   hPID = process_easy (argv, envp, -1, -1);
2482
2483   /* make sure launch ok */
2484   if (hPID == INVALID_HANDLE_VALUE)
2485     {
2486       int i;
2487       fprintf (stderr, _("process_easy() failed to launch process (e=%ld)\n"),
2488                process_last_err (hPID));
2489       for (i = 0; argv[i]; i++)
2490           fprintf (stderr, "%s ", argv[i]);
2491       fprintf (stderr, _("\nCounted %d args in failed launch\n"), i);
2492       exit (EXIT_FAILURE);
2493     }
2494
2495   /* wait and reap last child */
2496   hWaitPID = process_wait_for_any (1, 0);
2497   while (hWaitPID)
2498     {
2499       /* was an error found on this process? */
2500       int err = process_last_err (hWaitPID);
2501
2502       /* get exit data */
2503       exit_code = process_exit_code (hWaitPID);
2504
2505       if (err)
2506           fprintf (stderr, "make (e=%d, rc=%d): %s",
2507                    err, exit_code, map_windows32_error_to_string (err));
2508
2509       /* cleanup process */
2510       process_cleanup (hWaitPID);
2511
2512       /* expect to find only last pid, warn about other pids reaped */
2513       if (hWaitPID == hPID)
2514           break;
2515       else
2516         {
2517           char *pidstr = xstrdup (pid2str ((pid_t)hWaitPID));
2518
2519           fprintf (stderr,
2520                    _("make reaped child pid %s, still waiting for pid %s\n"),
2521                    pidstr, pid2str ((pid_t)hPID));
2522           free (pidstr);
2523         }
2524     }
2525
2526   /* return child's exit code as our exit code */
2527   exit (exit_code);
2528
2529 #else  /* !WINDOWS32 */
2530
2531 # ifdef __EMX__
2532   pid_t pid;
2533 # endif
2534
2535   /* Be the user, permanently.  */
2536   child_access ();
2537
2538 # ifdef __EMX__
2539   /* Run the program.  */
2540   pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2541   if (pid >= 0)
2542     return pid;
2543
2544   /* the file might have a strange shell extension */
2545   if (errno == ENOENT)
2546     errno = ENOEXEC;
2547
2548 # else
2549   /* Run the program.  */
2550   environ = envp;
2551   execvp (argv[0], argv);
2552
2553 # endif /* !__EMX__ */
2554
2555   switch (errno)
2556     {
2557     case ENOENT:
2558       OSS (error, NILF, "%s: %s", argv[0], strerror (errno));
2559       break;
2560     case ENOEXEC:
2561       {
2562         /* The file was not a program.  Try it as a shell script.  */
2563         const char *shell;
2564         char **new_argv;
2565         int argc;
2566         int i=1;
2567
2568 # ifdef __EMX__
2569         /* Do not use $SHELL from the environment */
2570         struct variable *p = lookup_variable ("SHELL", 5);
2571         if (p)
2572           shell = p->value;
2573         else
2574           shell = 0;
2575 # else
2576         shell = getenv ("SHELL");
2577 # endif
2578         if (shell == 0)
2579           shell = default_shell;
2580
2581         argc = 1;
2582         while (argv[argc] != 0)
2583           ++argc;
2584
2585 # ifdef __EMX__
2586         if (!unixy_shell)
2587           ++argc;
2588 # endif
2589
2590         new_argv = alloca ((1 + argc + 1) * sizeof (char *));
2591         new_argv[0] = (char *)shell;
2592
2593 # ifdef __EMX__
2594         if (!unixy_shell)
2595           {
2596             new_argv[1] = "/c";
2597             ++i;
2598             --argc;
2599           }
2600 # endif
2601
2602         new_argv[i] = argv[0];
2603         while (argc > 0)
2604           {
2605             new_argv[i + argc] = argv[argc];
2606             --argc;
2607           }
2608
2609 # ifdef __EMX__
2610         pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2611         if (pid >= 0)
2612           break;
2613 # else
2614         execvp (shell, new_argv);
2615 # endif
2616         OSS (error, NILF, "%s: %s", new_argv[0], strerror (errno));
2617         break;
2618       }
2619
2620 # ifdef __EMX__
2621     case EINVAL:
2622       /* this nasty error was driving me nuts :-( */
2623       O (error, NILF, _("spawnvpe: environment space might be exhausted"));
2624       /* FALLTHROUGH */
2625 # endif
2626
2627     default:
2628       OSS (error, NILF, "%s: %s", argv[0], strerror (errno));
2629       break;
2630     }
2631
2632 # ifdef __EMX__
2633   return pid;
2634 # else
2635   _exit (127);
2636 # endif
2637 #endif /* !WINDOWS32 */
2638 #endif /* !VMS */
2639 }
2640 #else /* On Amiga */
2641 void
2642 exec_command (char **argv)
2643 {
2644   MyExecute (argv);
2645 }
2646
2647 void clean_tmp (void)
2648 {
2649   DeleteFile (amiga_bname);
2650 }
2651
2652 #endif /* On Amiga */
2653 \f
2654 #ifndef VMS
2655 /* Figure out the argument list necessary to run LINE as a command.  Try to
2656    avoid using a shell.  This routine handles only ' quoting, and " quoting
2657    when no backslash, $ or ' characters are seen in the quotes.  Starting
2658    quotes may be escaped with a backslash.  If any of the characters in
2659    sh_chars is seen, or any of the builtin commands listed in sh_cmds
2660    is the first word of a line, the shell is used.
2661
2662    If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2663    If *RESTP is NULL, newlines will be ignored.
2664
2665    SHELL is the shell to use, or nil to use the default shell.
2666    IFS is the value of $IFS, or nil (meaning the default).
2667
2668    FLAGS is the value of lines_flags for this command line.  It is
2669    used in the WINDOWS32 port to check whether + or $(MAKE) were found
2670    in this command line, in which case the effect of just_print_flag
2671    is overridden.  */
2672
2673 static char **
2674 construct_command_argv_internal (char *line, char **restp, const char *shell,
2675                                  const char *shellflags, const char *ifs,
2676                                  int flags, char **batch_filename UNUSED)
2677 {
2678 #ifdef __MSDOS__
2679   /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2680      We call 'system' for anything that requires ''slow'' processing,
2681      because DOS shells are too dumb.  When $SHELL points to a real
2682      (unix-style) shell, 'system' just calls it to do everything.  When
2683      $SHELL points to a DOS shell, 'system' does most of the work
2684      internally, calling the shell only for its internal commands.
2685      However, it looks on the $PATH first, so you can e.g. have an
2686      external command named 'mkdir'.
2687
2688      Since we call 'system', certain characters and commands below are
2689      actually not specific to COMMAND.COM, but to the DJGPP implementation
2690      of 'system'.  In particular:
2691
2692        The shell wildcard characters are in DOS_CHARS because they will
2693        not be expanded if we call the child via 'spawnXX'.
2694
2695        The ';' is in DOS_CHARS, because our 'system' knows how to run
2696        multiple commands on a single line.
2697
2698        DOS_CHARS also include characters special to 4DOS/NDOS, so we
2699        won't have to tell one from another and have one more set of
2700        commands and special characters.  */
2701   static const char *sh_chars_dos = "*?[];|<>%^&()";
2702   static const char *sh_cmds_dos[] =
2703     { "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty", "date",
2704       "del", "dir", "echo", "erase", "exit", "for", "goto", "if", "md",
2705       "mkdir", "path", "pause", "prompt", "rd", "rmdir", "rem", "ren",
2706       "rename", "set", "shift", "time", "type", "ver", "verify", "vol", ":",
2707       0 };
2708
2709   static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^";
2710   static const char *sh_cmds_sh[] =
2711     { "cd", "echo", "eval", "exec", "exit", "login", "logout", "set", "umask",
2712       "wait", "while", "for", "case", "if", ":", ".", "break", "continue",
2713       "export", "read", "readonly", "shift", "times", "trap", "switch",
2714       "unset", "ulimit", "command", 0 };
2715
2716   const char *sh_chars;
2717   const char **sh_cmds;
2718
2719 #elif defined (__EMX__)
2720   static const char *sh_chars_dos = "*?[];|<>%^&()";
2721   static const char *sh_cmds_dos[] =
2722     { "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty", "date",
2723       "del", "dir", "echo", "erase", "exit", "for", "goto", "if", "md",
2724       "mkdir", "path", "pause", "prompt", "rd", "rmdir", "rem", "ren",
2725       "rename", "set", "shift", "time", "type", "ver", "verify", "vol", ":",
2726       0 };
2727
2728   static const char *sh_chars_os2 = "*?[];|<>%^()\"'&";
2729   static const char *sh_cmds_os2[] =
2730     { "call", "cd", "chcp", "chdir", "cls", "copy", "date", "del", "detach",
2731       "dir", "echo", "endlocal", "erase", "exit", "for", "goto", "if", "keys",
2732       "md", "mkdir", "move", "path", "pause", "prompt", "rd", "rem", "ren",
2733       "rename", "rmdir", "set", "setlocal", "shift", "start", "time", "type",
2734       "ver", "verify", "vol", ":", 0 };
2735
2736   static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^~'";
2737   static const char *sh_cmds_sh[] =
2738     { "echo", "cd", "eval", "exec", "exit", "login", "logout", "set", "umask",
2739       "wait", "while", "for", "case", "if", ":", ".", "break", "continue",
2740       "export", "read", "readonly", "shift", "times", "trap", "switch",
2741       "unset", "command", 0 };
2742
2743   const char *sh_chars;
2744   const char **sh_cmds;
2745
2746 #elif defined (_AMIGA)
2747   static const char *sh_chars = "#;\"|<>()?*$`";
2748   static const char *sh_cmds[] =
2749     { "cd", "eval", "if", "delete", "echo", "copy", "rename", "set", "setenv",
2750       "date", "makedir", "skip", "else", "endif", "path", "prompt", "unset",
2751       "unsetenv", "version", "command", 0 };
2752
2753 #elif defined (WINDOWS32)
2754   /* We used to have a double quote (") in sh_chars_dos[] below, but
2755      that caused any command line with quoted file names be run
2756      through a temporary batch file, which introduces command-line
2757      limit of 4K charcaters imposed by cmd.exe.  Since CreateProcess
2758      can handle quoted file names just fine, removing the quote lifts
2759      the limit from a very frequent use case, because using quoted
2760      file names is commonplace on MS-Windows.  */
2761   static const char *sh_chars_dos = "|&<>";
2762   static const char *sh_cmds_dos[] =
2763     { "assoc", "break", "call", "cd", "chcp", "chdir", "cls", "color", "copy",
2764       "ctty", "date", "del", "dir", "echo", "echo.", "endlocal", "erase",
2765       "exit", "for", "ftype", "goto", "if", "if", "md", "mkdir", "move",
2766       "path", "pause", "prompt", "rd", "rem", "ren", "rename", "rmdir",
2767       "set", "setlocal", "shift", "time", "title", "type", "ver", "verify",
2768       "vol", ":", 0 };
2769
2770   static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^";
2771   static const char *sh_cmds_sh[] =
2772     { "cd", "eval", "exec", "exit", "login", "logout", "set", "umask", "wait",
2773       "while", "for", "case", "if", ":", ".", "break", "continue", "export",
2774       "read", "readonly", "shift", "times", "trap", "switch", "test", "command",
2775 #ifdef BATCH_MODE_ONLY_SHELL
2776       "echo",
2777 #endif
2778       0 };
2779
2780   const char *sh_chars;
2781   const char **sh_cmds;
2782 #elif defined(__riscos__)
2783   static const char *sh_chars = "";
2784   static const char *sh_cmds[] = { 0 };
2785 #else  /* must be UNIX-ish */
2786   static const char *sh_chars = "#;\"*?[]&|<>(){}$`^~!";
2787   static const char *sh_cmds[] =
2788     { ".", ":", "alias", "bg", "break", "case", "cd", "command", "continue",
2789       "eval", "exec", "exit", "export", "fc", "fg", "for", "getopts", "hash",
2790       "if", "jobs", "login", "logout", "read", "readonly", "return", "set",
2791       "shift", "test", "times", "trap", "type", "ulimit", "umask", "unalias",
2792       "unset", "wait", "while", 0 };
2793
2794 # ifdef HAVE_DOS_PATHS
2795   /* This is required if the MSYS/Cygwin ports (which do not define
2796      WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
2797      sh_chars_sh directly (see below).  The value must be identical
2798      to that of sh_chars immediately above.  */
2799   static const char *sh_chars_sh =  "#;\"*?[]&|<>(){}$`^~!";
2800 # endif  /* HAVE_DOS_PATHS */
2801 #endif
2802   size_t i;
2803   char *p;
2804 #ifndef NDEBUG
2805   char *end;
2806 #endif
2807   char *ap;
2808   const char *cap;
2809   const char *cp;
2810   int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2811   char **new_argv = 0;
2812   char *argstr = 0;
2813 #ifdef WINDOWS32
2814   int slow_flag = 0;
2815
2816   if (!unixy_shell)
2817     {
2818       sh_cmds = sh_cmds_dos;
2819       sh_chars = sh_chars_dos;
2820     }
2821   else
2822     {
2823       sh_cmds = sh_cmds_sh;
2824       sh_chars = sh_chars_sh;
2825     }
2826 #endif /* WINDOWS32 */
2827
2828   if (restp != NULL)
2829     *restp = NULL;
2830
2831   /* Make sure not to bother processing an empty line but stop at newline.  */
2832   while (ISBLANK (*line))
2833     ++line;
2834   if (*line == '\0')
2835     return 0;
2836
2837   if (shellflags == 0)
2838     shellflags = posix_pedantic ? "-ec" : "-c";
2839
2840   /* See if it is safe to parse commands internally.  */
2841   if (shell == 0)
2842     shell = default_shell;
2843 #ifdef WINDOWS32
2844   else if (strcmp (shell, default_shell))
2845   {
2846     char *s1 = _fullpath (NULL, shell, 0);
2847     char *s2 = _fullpath (NULL, default_shell, 0);
2848
2849     slow_flag = strcmp ((s1 ? s1 : ""), (s2 ? s2 : ""));
2850
2851     free (s1);
2852     free (s2);
2853   }
2854   if (slow_flag)
2855     goto slow;
2856 #else  /* not WINDOWS32 */
2857 #if defined (__MSDOS__) || defined (__EMX__)
2858   else if (strcasecmp (shell, default_shell))
2859     {
2860       extern int _is_unixy_shell (const char *_path);
2861
2862       DB (DB_BASIC, (_("$SHELL changed (was '%s', now '%s')\n"),
2863                      default_shell, shell));
2864       unixy_shell = _is_unixy_shell (shell);
2865       /* we must allocate a copy of shell: construct_command_argv() will free
2866        * shell after this function returns.  */
2867       default_shell = xstrdup (shell);
2868     }
2869   if (unixy_shell)
2870     {
2871       sh_chars = sh_chars_sh;
2872       sh_cmds  = sh_cmds_sh;
2873     }
2874   else
2875     {
2876       sh_chars = sh_chars_dos;
2877       sh_cmds  = sh_cmds_dos;
2878 # ifdef __EMX__
2879       if (_osmode == OS2_MODE)
2880         {
2881           sh_chars = sh_chars_os2;
2882           sh_cmds = sh_cmds_os2;
2883         }
2884 # endif
2885     }
2886 #else  /* !__MSDOS__ */
2887   else if (strcmp (shell, default_shell))
2888     goto slow;
2889 #endif /* !__MSDOS__ && !__EMX__ */
2890 #endif /* not WINDOWS32 */
2891
2892   if (ifs)
2893     for (cap = ifs; *cap != '\0'; ++cap)
2894       if (*cap != ' ' && *cap != '\t' && *cap != '\n')
2895         goto slow;
2896
2897   if (shellflags)
2898     if (shellflags[0] != '-'
2899         || ((shellflags[1] != 'c' || shellflags[2] != '\0')
2900             && (shellflags[1] != 'e' || shellflags[2] != 'c' || shellflags[3] != '\0')))
2901       goto slow;
2902
2903   i = strlen (line) + 1;
2904
2905   /* More than 1 arg per character is impossible.  */
2906   new_argv = xmalloc (i * sizeof (char *));
2907
2908   /* All the args can fit in a buffer as big as LINE is.   */
2909   ap = new_argv[0] = argstr = xmalloc (i);
2910 #ifndef NDEBUG
2911   end = ap + i;
2912 #endif
2913
2914   /* I is how many complete arguments have been found.  */
2915   i = 0;
2916   instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2917   for (p = line; *p != '\0'; ++p)
2918     {
2919       assert (ap <= end);
2920
2921       if (instring)
2922         {
2923           /* Inside a string, just copy any char except a closing quote
2924              or a backslash-newline combination.  */
2925           if (*p == instring)
2926             {
2927               instring = 0;
2928               if (ap == new_argv[0] || *(ap-1) == '\0')
2929                 last_argument_was_empty = 1;
2930             }
2931           else if (*p == '\\' && p[1] == '\n')
2932             {
2933               /* Backslash-newline is handled differently depending on what
2934                  kind of string we're in: inside single-quoted strings you
2935                  keep them; in double-quoted strings they disappear.  For
2936                  DOS/Windows/OS2, if we don't have a POSIX shell, we keep the
2937                  pre-POSIX behavior of removing the backslash-newline.  */
2938               if (instring == '"'
2939 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2940                   || !unixy_shell
2941 #endif
2942                   )
2943                 ++p;
2944               else
2945                 {
2946                   *(ap++) = *(p++);
2947                   *(ap++) = *p;
2948                 }
2949             }
2950           else if (*p == '\n' && restp != NULL)
2951             {
2952               /* End of the command line.  */
2953               *restp = p;
2954               goto end_of_line;
2955             }
2956           /* Backslash, $, and ` are special inside double quotes.
2957              If we see any of those, punt.
2958              But on MSDOS, if we use COMMAND.COM, double and single
2959              quotes have the same effect.  */
2960           else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2961             goto slow;
2962 #ifdef WINDOWS32
2963           /* Quoted wildcard characters must be passed quoted to the
2964              command, so give up the fast route.  */
2965           else if (instring == '"' && strchr ("*?", *p) != 0 && !unixy_shell)
2966             goto slow;
2967           else if (instring == '"' && strncmp (p, "\\\"", 2) == 0)
2968             *ap++ = *++p;
2969 #endif
2970           else
2971             *ap++ = *p;
2972         }
2973       else if (strchr (sh_chars, *p) != 0)
2974         /* Not inside a string, but it's a special char.  */
2975         goto slow;
2976       else if (one_shell && *p == '\n')
2977         /* In .ONESHELL mode \n is a separator like ; or && */
2978         goto slow;
2979 #ifdef  __MSDOS__
2980       else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2981         /* '...' is a wildcard in DJGPP.  */
2982         goto slow;
2983 #endif
2984       else
2985         /* Not a special char.  */
2986         switch (*p)
2987           {
2988           case '=':
2989             /* Equals is a special character in leading words before the
2990                first word with no equals sign in it.  This is not the case
2991                with sh -k, but we never get here when using nonstandard
2992                shell flags.  */
2993             if (! seen_nonequals && unixy_shell)
2994               goto slow;
2995             word_has_equals = 1;
2996             *ap++ = '=';
2997             break;
2998
2999           case '\\':
3000             /* Backslash-newline has special case handling, ref POSIX.
3001                We're in the fastpath, so emulate what the shell would do.  */
3002             if (p[1] == '\n')
3003               {
3004                 /* Throw out the backslash and newline.  */
3005                 ++p;
3006
3007                 /* At the beginning of the argument, skip any whitespace other
3008                    than newline before the start of the next word.  */
3009                 if (ap == new_argv[i])
3010                   while (ISBLANK (p[1]))
3011                     ++p;
3012               }
3013 #ifdef WINDOWS32
3014             /* Backslash before whitespace is not special if our shell
3015                is not Unixy.  */
3016             else if (ISSPACE (p[1]) && !unixy_shell)
3017               {
3018                 *ap++ = *p;
3019                 break;
3020               }
3021 #endif
3022             else if (p[1] != '\0')
3023               {
3024 #ifdef HAVE_DOS_PATHS
3025                 /* Only remove backslashes before characters special to Unixy
3026                    shells.  All other backslashes are copied verbatim, since
3027                    they are probably DOS-style directory separators.  This
3028                    still leaves a small window for problems, but at least it
3029                    should work for the vast majority of naive users.  */
3030
3031 #ifdef __MSDOS__
3032                 /* A dot is only special as part of the "..."
3033                    wildcard.  */
3034                 if (strneq (p + 1, ".\\.\\.", 5))
3035                   {
3036                     *ap++ = '.';
3037                     *ap++ = '.';
3038                     p += 4;
3039                   }
3040                 else
3041 #endif
3042                   if (p[1] != '\\' && p[1] != '\''
3043                       && !ISSPACE (p[1])
3044                       && strchr (sh_chars_sh, p[1]) == 0)
3045                     /* back up one notch, to copy the backslash */
3046                     --p;
3047 #endif  /* HAVE_DOS_PATHS */
3048
3049                 /* Copy and skip the following char.  */
3050                 *ap++ = *++p;
3051               }
3052             break;
3053
3054           case '\'':
3055           case '"':
3056             instring = *p;
3057             break;
3058
3059           case '\n':
3060             if (restp != NULL)
3061               {
3062                 /* End of the command line.  */
3063                 *restp = p;
3064                 goto end_of_line;
3065               }
3066             else
3067               /* Newlines are not special.  */
3068               *ap++ = '\n';
3069             break;
3070
3071           case ' ':
3072           case '\t':
3073             /* We have the end of an argument.
3074                Terminate the text of the argument.  */
3075             *ap++ = '\0';
3076             new_argv[++i] = ap;
3077             last_argument_was_empty = 0;
3078
3079             /* Update SEEN_NONEQUALS, which tells us if every word
3080                heretofore has contained an '='.  */
3081             seen_nonequals |= ! word_has_equals;
3082             if (word_has_equals && ! seen_nonequals)
3083               /* An '=' in a word before the first
3084                  word without one is magical.  */
3085               goto slow;
3086             word_has_equals = 0; /* Prepare for the next word.  */
3087
3088             /* If this argument is the command name,
3089                see if it is a built-in shell command.
3090                If so, have the shell handle it.  */
3091             if (i == 1)
3092               {
3093                 int j;
3094                 for (j = 0; sh_cmds[j] != 0; ++j)
3095                   {
3096                     if (streq (sh_cmds[j], new_argv[0]))
3097                       goto slow;
3098 #if defined(__EMX__) || defined(WINDOWS32)
3099                     /* Non-Unix shells are case insensitive.  */
3100                     if (!unixy_shell
3101                         && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
3102                       goto slow;
3103 #endif
3104                   }
3105               }
3106
3107             /* Skip whitespace chars, but not newlines.  */
3108             while (ISBLANK (p[1]))
3109               ++p;
3110             break;
3111
3112           default:
3113             *ap++ = *p;
3114             break;
3115           }
3116     }
3117  end_of_line:
3118
3119   if (instring)
3120     /* Let the shell deal with an unterminated quote.  */
3121     goto slow;
3122
3123   /* Terminate the last argument and the argument list.  */
3124
3125   *ap = '\0';
3126   if (new_argv[i][0] != '\0' || last_argument_was_empty)
3127     ++i;
3128   new_argv[i] = 0;
3129
3130   if (i == 1)
3131     {
3132       int j;
3133       for (j = 0; sh_cmds[j] != 0; ++j)
3134         if (streq (sh_cmds[j], new_argv[0]))
3135           goto slow;
3136     }
3137
3138   if (new_argv[0] == 0)
3139     {
3140       /* Line was empty.  */
3141       free (argstr);
3142       free (new_argv);
3143       return 0;
3144     }
3145
3146   return new_argv;
3147
3148  slow:;
3149   /* We must use the shell.  */
3150
3151   if (new_argv != 0)
3152     {
3153       /* Free the old argument list we were working on.  */
3154       free (argstr);
3155       free (new_argv);
3156     }
3157
3158 #ifdef __MSDOS__
3159   execute_by_shell = 1; /* actually, call 'system' if shell isn't unixy */
3160 #endif
3161
3162 #ifdef _AMIGA
3163   {
3164     char *ptr;
3165     char *buffer;
3166     char *dptr;
3167
3168     buffer = xmalloc (strlen (line)+1);
3169
3170     ptr = line;
3171     for (dptr=buffer; *ptr; )
3172     {
3173       if (*ptr == '\\' && ptr[1] == '\n')
3174         ptr += 2;
3175       else if (*ptr == '@') /* Kludge: multiline commands */
3176       {
3177         ptr += 2;
3178         *dptr++ = '\n';
3179       }
3180       else
3181         *dptr++ = *ptr++;
3182     }
3183     *dptr = 0;
3184
3185     new_argv = xmalloc (2 * sizeof (char *));
3186     new_argv[0] = buffer;
3187     new_argv[1] = 0;
3188   }
3189 #else   /* Not Amiga  */
3190 #ifdef WINDOWS32
3191   /*
3192    * Not eating this whitespace caused things like
3193    *
3194    *    sh -c "\n"
3195    *
3196    * which gave the shell fits. I think we have to eat
3197    * whitespace here, but this code should be considered
3198    * suspicious if things start failing....
3199    */
3200
3201   /* Make sure not to bother processing an empty line.  */
3202   NEXT_TOKEN (line);
3203   if (*line == '\0')
3204     return 0;
3205 #endif /* WINDOWS32 */
3206
3207   {
3208     /* SHELL may be a multi-word command.  Construct a command line
3209        "$(SHELL) $(.SHELLFLAGS) LINE", with all special chars in LINE escaped.
3210        Then recurse, expanding this command line to get the final
3211        argument list.  */
3212
3213     char *new_line;
3214     size_t shell_len = strlen (shell);
3215     size_t line_len = strlen (line);
3216     size_t sflags_len = shellflags ? strlen (shellflags) : 0;
3217 #ifdef WINDOWS32
3218     char *command_ptr = NULL; /* used for batch_mode_shell mode */
3219 #endif
3220
3221 # ifdef __EMX__ /* is this necessary? */
3222     if (!unixy_shell && shellflags)
3223       shellflags[0] = '/'; /* "/c" */
3224 # endif
3225
3226     /* In .ONESHELL mode we are allowed to throw the entire current
3227         recipe string at a single shell and trust that the user
3228         has configured the shell and shell flags, and formatted
3229         the string, appropriately. */
3230     if (one_shell)
3231       {
3232         /* If the shell is Bourne compatible, we must remove and ignore
3233            interior special chars [@+-] because they're meaningless to
3234            the shell itself. If, however, we're in .ONESHELL mode and
3235            have changed SHELL to something non-standard, we should
3236            leave those alone because they could be part of the
3237            script. In this case we must also leave in place
3238            any leading [@+-] for the same reason.  */
3239
3240         /* Remove and ignore interior prefix chars [@+-] because they're
3241              meaningless given a single shell. */
3242 #if defined __MSDOS__ || defined (__EMX__)
3243         if (unixy_shell)     /* the test is complicated and we already did it */
3244 #else
3245         if (is_bourne_compatible_shell (shell)
3246 #ifdef WINDOWS32
3247             /* If we didn't find any sh.exe, don't behave is if we did!  */
3248             && !no_default_sh_exe
3249 #endif
3250             )
3251 #endif
3252           {
3253             const char *f = line;
3254             char *t = line;
3255
3256             /* Copy the recipe, removing and ignoring interior prefix chars
3257                [@+-]: they're meaningless in .ONESHELL mode.  */
3258             while (f[0] != '\0')
3259               {
3260                 int esc = 0;
3261
3262                 /* This is the start of a new recipe line.  Skip whitespace
3263                    and prefix characters but not newlines.  */
3264                 while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
3265                   ++f;
3266
3267                 /* Copy until we get to the next logical recipe line.  */
3268                 while (*f != '\0')
3269                   {
3270                     *(t++) = *(f++);
3271                     if (f[-1] == '\\')
3272                       esc = !esc;
3273                     else
3274                       {
3275                         /* On unescaped newline, we're done with this line.  */
3276                         if (f[-1] == '\n' && ! esc)
3277                           break;
3278
3279                         /* Something else: reset the escape sequence.  */
3280                         esc = 0;
3281                       }
3282                   }
3283               }
3284             *t = '\0';
3285           }
3286 #ifdef WINDOWS32
3287         else    /* non-Posix shell (cmd.exe etc.) */
3288           {
3289             const char *f = line;
3290             char *t = line;
3291             char *tstart = t;
3292             int temp_fd;
3293             FILE* batch = NULL;
3294             int id = GetCurrentProcessId ();
3295             PATH_VAR(fbuf);
3296
3297             /* Generate a file name for the temporary batch file.  */
3298             sprintf (fbuf, "make%d", id);
3299             *batch_filename = create_batch_file (fbuf, 0, &temp_fd);
3300             DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3301                           *batch_filename));
3302
3303             /* Create a FILE object for the batch file, and write to it the
3304                commands to be executed.  Put the batch file in TEXT mode.  */
3305             _setmode (temp_fd, _O_TEXT);
3306             batch = _fdopen (temp_fd, "wt");
3307             fputs ("@echo off\n", batch);
3308             DB (DB_JOBS, (_("Batch file contents:\n\t@echo off\n")));
3309
3310             /* Copy the recipe, removing and ignoring interior prefix chars
3311                [@+-]: they're meaningless in .ONESHELL mode.  */
3312             while (*f != '\0')
3313               {
3314                 /* This is the start of a new recipe line.  Skip whitespace
3315                    and prefix characters but not newlines.  */
3316                 while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
3317                   ++f;
3318
3319                 /* Copy until we get to the next logical recipe line.  */
3320                 while (*f != '\0')
3321                   {
3322                     /* Remove the escaped newlines in the command, and the
3323                        blanks that follow them.  Windows shells cannot handle
3324                        escaped newlines.  */
3325                     if (*f == '\\' && f[1] == '\n')
3326                       {
3327                         f += 2;
3328                         while (ISBLANK (*f))
3329                           ++f;
3330                       }
3331                     *(t++) = *(f++);
3332                     /* On an unescaped newline, we're done with this
3333                        line.  */
3334                     if (f[-1] == '\n')
3335                       break;
3336                   }
3337                 /* Write another line into the batch file.  */
3338                 if (t > tstart)
3339                   {
3340                     char c = *t;
3341                     *t = '\0';
3342                     fputs (tstart, batch);
3343                     DB (DB_JOBS, ("\t%s", tstart));
3344                     tstart = t;
3345                     *t = c;
3346                   }
3347               }
3348             DB (DB_JOBS, ("\n"));
3349             fclose (batch);
3350
3351             /* Create an argv list for the shell command line that
3352                will run the batch file.  */
3353             new_argv = xmalloc (2 * sizeof (char *));
3354             new_argv[0] = xstrdup (*batch_filename);
3355             new_argv[1] = NULL;
3356             return new_argv;
3357           }
3358 #endif /* WINDOWS32 */
3359         /* Create an argv list for the shell command line.  */
3360         {
3361           int n = 0;
3362
3363           new_argv = xmalloc ((4 + sflags_len/2) * sizeof (char *));
3364           new_argv[n++] = xstrdup (shell);
3365
3366           /* Chop up the shellflags (if any) and assign them.  */
3367           if (! shellflags)
3368             new_argv[n++] = xstrdup ("");
3369           else
3370             {
3371               const char *s = shellflags;
3372               char *t;
3373               size_t len;
3374               while ((t = find_next_token (&s, &len)) != 0)
3375                 new_argv[n++] = xstrndup (t, len);
3376             }
3377
3378           /* Set the command to invoke.  */
3379           new_argv[n++] = line;
3380           new_argv[n++] = NULL;
3381         }
3382         return new_argv;
3383       }
3384
3385     new_line = xmalloc ((shell_len*2) + 1 + sflags_len + 1
3386                         + (line_len*2) + 1);
3387     ap = new_line;
3388     /* Copy SHELL, escaping any characters special to the shell.  If
3389        we don't escape them, construct_command_argv_internal will
3390        recursively call itself ad nauseam, or until stack overflow,
3391        whichever happens first.  */
3392     for (cp = shell; *cp != '\0'; ++cp)
3393       {
3394         if (strchr (sh_chars, *cp) != 0)
3395           *(ap++) = '\\';
3396         *(ap++) = *cp;
3397       }
3398     *(ap++) = ' ';
3399     if (shellflags)
3400       memcpy (ap, shellflags, sflags_len);
3401     ap += sflags_len;
3402     *(ap++) = ' ';
3403 #ifdef WINDOWS32
3404     command_ptr = ap;
3405 #endif
3406     for (p = line; *p != '\0'; ++p)
3407       {
3408         if (restp != NULL && *p == '\n')
3409           {
3410             *restp = p;
3411             break;
3412           }
3413         else if (*p == '\\' && p[1] == '\n')
3414           {
3415             /* POSIX says we keep the backslash-newline.  If we don't have a
3416                POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
3417                and remove the backslash/newline.  */
3418 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
3419 # define PRESERVE_BSNL  unixy_shell
3420 #else
3421 # define PRESERVE_BSNL  1
3422 #endif
3423             if (PRESERVE_BSNL)
3424               {
3425                 *(ap++) = '\\';
3426                 /* Only non-batch execution needs another backslash,
3427                    because it will be passed through a recursive
3428                    invocation of this function.  */
3429                 if (!batch_mode_shell)
3430                   *(ap++) = '\\';
3431                 *(ap++) = '\n';
3432               }
3433             ++p;
3434             continue;
3435           }
3436
3437         /* DOS shells don't know about backslash-escaping.  */
3438         if (unixy_shell && !batch_mode_shell &&
3439             (*p == '\\' || *p == '\'' || *p == '"'
3440              || ISSPACE (*p)
3441              || strchr (sh_chars, *p) != 0))
3442           *ap++ = '\\';
3443 #ifdef __MSDOS__
3444         else if (unixy_shell && strneq (p, "...", 3))
3445           {
3446             /* The case of '...' wildcard again.  */
3447             strcpy (ap, "\\.\\.\\");
3448             ap += 5;
3449             p  += 2;
3450           }
3451 #endif
3452         *ap++ = *p;
3453       }
3454     if (ap == new_line + shell_len + sflags_len + 2)
3455       {
3456         /* Line was empty.  */
3457         free (new_line);
3458         return 0;
3459       }
3460     *ap = '\0';
3461
3462 #ifdef WINDOWS32
3463     /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3464        command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems).  In these
3465        cases, run commands via a script file.  */
3466     if (just_print_flag && !(flags & COMMANDS_RECURSE))
3467       {
3468         /* Need to allocate new_argv, although it's unused, because
3469            start_job_command will want to free it and its 0'th element.  */
3470         new_argv = xmalloc (2 * sizeof (char *));
3471         new_argv[0] = xstrdup ("");
3472         new_argv[1] = NULL;
3473       }
3474     else if ((no_default_sh_exe || batch_mode_shell) && batch_filename)
3475       {
3476         int temp_fd;
3477         FILE* batch = NULL;
3478         int id = GetCurrentProcessId ();
3479         PATH_VAR (fbuf);
3480
3481         /* create a file name */
3482         sprintf (fbuf, "make%d", id);
3483         *batch_filename = create_batch_file (fbuf, unixy_shell, &temp_fd);
3484
3485         DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3486                       *batch_filename));
3487
3488         /* Create a FILE object for the batch file, and write to it the
3489            commands to be executed.  Put the batch file in TEXT mode.  */
3490         _setmode (temp_fd, _O_TEXT);
3491         batch = _fdopen (temp_fd, "wt");
3492         if (!unixy_shell)
3493           fputs ("@echo off\n", batch);
3494         fputs (command_ptr, batch);
3495         fputc ('\n', batch);
3496         fclose (batch);
3497         DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
3498                       !unixy_shell ? "\n\t@echo off" : "", command_ptr));
3499
3500         /* create argv */
3501         new_argv = xmalloc (3 * sizeof (char *));
3502         if (unixy_shell)
3503           {
3504             new_argv[0] = xstrdup (shell);
3505             new_argv[1] = *batch_filename; /* only argv[0] gets freed later */
3506           }
3507         else
3508           {
3509             new_argv[0] = xstrdup (*batch_filename);
3510             new_argv[1] = NULL;
3511           }
3512         new_argv[2] = NULL;
3513       }
3514     else
3515 #endif /* WINDOWS32 */
3516
3517     if (unixy_shell)
3518       new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0,
3519                                                   flags, 0);
3520
3521 #ifdef __EMX__
3522     else if (!unixy_shell)
3523       {
3524         /* new_line is local, must not be freed therefore
3525            We use line here instead of new_line because we run the shell
3526            manually.  */
3527         size_t line_len = strlen (line);
3528         char *p = new_line;
3529         char *q = new_line;
3530         memcpy (new_line, line, line_len + 1);
3531         /* Replace all backslash-newline combination and also following tabs.
3532            Important: stop at the first '\n' because that's what the loop above
3533            did. The next line starting at restp[0] will be executed during the
3534            next call of this function. */
3535         while (*q != '\0' && *q != '\n')
3536           {
3537             if (q[0] == '\\' && q[1] == '\n')
3538               q += 2; /* remove '\\' and '\n' */
3539             else
3540               *p++ = *q++;
3541           }
3542         *p = '\0';
3543
3544 # ifndef NO_CMD_DEFAULT
3545         if (strnicmp (new_line, "echo", 4) == 0
3546             && (new_line[4] == ' ' || new_line[4] == '\t'))
3547           {
3548             /* the builtin echo command: handle it separately */
3549             size_t echo_len = line_len - 5;
3550             char *echo_line = new_line + 5;
3551
3552             /* special case: echo 'x="y"'
3553                cmd works this way: a string is printed as is, i.e., no quotes
3554                are removed. But autoconf uses a command like echo 'x="y"' to
3555                determine whether make works. autoconf expects the output x="y"
3556                so we will do exactly that.
3557                Note: if we do not allow cmd to be the default shell
3558                we do not need this kind of voodoo */
3559             if (echo_line[0] == '\''
3560                 && echo_line[echo_len - 1] == '\''
3561                 && strncmp (echo_line + 1, "ac_maketemp=",
3562                             strlen ("ac_maketemp=")) == 0)
3563               {
3564                 /* remove the enclosing quotes */
3565                 memmove (echo_line, echo_line + 1, echo_len - 2);
3566                 echo_line[echo_len - 2] = '\0';
3567               }
3568           }
3569 # endif
3570
3571         {
3572           /* Let the shell decide what to do. Put the command line into the
3573              2nd command line argument and hope for the best ;-)  */
3574           size_t sh_len = strlen (shell);
3575
3576           /* exactly 3 arguments + NULL */
3577           new_argv = xmalloc (4 * sizeof (char *));
3578           /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3579              the trailing '\0' */
3580           new_argv[0] = xmalloc (sh_len + line_len + 5);
3581           memcpy (new_argv[0], shell, sh_len + 1);
3582           new_argv[1] = new_argv[0] + sh_len + 1;
3583           memcpy (new_argv[1], "/c", 3);
3584           new_argv[2] = new_argv[1] + 3;
3585           memcpy (new_argv[2], new_line, line_len + 1);
3586           new_argv[3] = NULL;
3587         }
3588       }
3589 #elif defined(__MSDOS__)
3590     else
3591       {
3592         /* With MSDOS shells, we must construct the command line here
3593            instead of recursively calling ourselves, because we
3594            cannot backslash-escape the special characters (see above).  */
3595         new_argv = xmalloc (sizeof (char *));
3596         line_len = strlen (new_line) - shell_len - sflags_len - 2;
3597         new_argv[0] = xmalloc (line_len + 1);
3598         strncpy (new_argv[0],
3599                  new_line + shell_len + sflags_len + 2, line_len);
3600         new_argv[0][line_len] = '\0';
3601       }
3602 #else
3603     else
3604       fatal (NILF, CSTRLEN (__FILE__) + INTSTR_LENGTH,
3605              _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3606             __FILE__, __LINE__);
3607 #endif
3608
3609     free (new_line);
3610   }
3611 #endif  /* ! AMIGA */
3612
3613   return new_argv;
3614 }
3615 #endif /* !VMS */
3616
3617 /* Figure out the argument list necessary to run LINE as a command.  Try to
3618    avoid using a shell.  This routine handles only ' quoting, and " quoting
3619    when no backslash, $ or ' characters are seen in the quotes.  Starting
3620    quotes may be escaped with a backslash.  If any of the characters in
3621    sh_chars is seen, or any of the builtin commands listed in sh_cmds
3622    is the first word of a line, the shell is used.
3623
3624    If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3625    If *RESTP is NULL, newlines will be ignored.
3626
3627    FILE is the target whose commands these are.  It is used for
3628    variable expansion for $(SHELL) and $(IFS).  */
3629
3630 char **
3631 construct_command_argv (char *line, char **restp, struct file *file,
3632                         int cmd_flags, char **batch_filename)
3633 {
3634   char *shell, *ifs, *shellflags;
3635   char **argv;
3636
3637   {
3638     /* Turn off --warn-undefined-variables while we expand SHELL and IFS.  */
3639     int save = warn_undefined_variables_flag;
3640     warn_undefined_variables_flag = 0;
3641
3642     shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3643 #ifdef WINDOWS32
3644     /*
3645      * Convert to forward slashes so that construct_command_argv_internal()
3646      * is not confused.
3647      */
3648     if (shell)
3649       {
3650         char *p = w32ify (shell, 0);
3651         strcpy (shell, p);
3652       }
3653 #endif
3654 #ifdef __EMX__
3655     {
3656       static const char *unixroot = NULL;
3657       static const char *last_shell = "";
3658       static int init = 0;
3659       if (init == 0)
3660         {
3661           unixroot = getenv ("UNIXROOT");
3662           /* unixroot must be NULL or not empty */
3663           if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3664           init = 1;
3665         }
3666
3667       /* if we have an unixroot drive and if shell is not default_shell
3668          (which means it's either cmd.exe or the test has already been
3669          performed) and if shell is an absolute path without drive letter,
3670          try whether it exists e.g.: if "/bin/sh" does not exist use
3671          "$UNIXROOT/bin/sh" instead.  */
3672       if (unixroot && shell && strcmp (shell, last_shell) != 0
3673           && (shell[0] == '/' || shell[0] == '\\'))
3674         {
3675           /* trying a new shell, check whether it exists */
3676           size_t size = strlen (shell);
3677           char *buf = xmalloc (size + 7);
3678           memcpy (buf, shell, size);
3679           memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3680           if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3681             {
3682               /* try the same for the unixroot drive */
3683               memmove (buf + 2, buf, size + 5);
3684               buf[0] = unixroot[0];
3685               buf[1] = unixroot[1];
3686               if (access (buf, F_OK) == 0)
3687                 /* we have found a shell! */
3688                 /* free(shell); */
3689                 shell = buf;
3690               else
3691                 free (buf);
3692             }
3693           else
3694             free (buf);
3695         }
3696     }
3697 #endif /* __EMX__ */
3698
3699     shellflags = allocated_variable_expand_for_file ("$(.SHELLFLAGS)", file);
3700     ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3701
3702     warn_undefined_variables_flag = save;
3703   }
3704
3705   argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
3706                                           cmd_flags, batch_filename);
3707
3708   free (shell);
3709   free (shellflags);
3710   free (ifs);
3711
3712   return argv;
3713 }
3714 \f
3715 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3716 int
3717 dup2 (int old, int new)
3718 {
3719   int fd;
3720
3721   (void) close (new);
3722   EINTRLOOP (fd, dup (old));
3723   if (fd != new)
3724     {
3725       (void) close (fd);
3726       errno = EMFILE;
3727       return -1;
3728     }
3729
3730   return fd;
3731 }
3732 #endif /* !HAVE_DUP2 && !_AMIGA */
3733
3734 /* On VMS systems, include special VMS functions.  */
3735
3736 #ifdef VMS
3737 #include "vmsjobs.c"
3738 #endif