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