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