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