Fixes to build_w32.bat for building with MSVC 64bit.
[make.git] / job.c
blob741114da61efc72ae66922390b21ff9fbb8ff6bd
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 #if !(defined(_MSC_VER) && defined(_WIN64))
180 int execve ();
181 #endif
182 void _exit ();
183 # ifndef VMS
184 int geteuid ();
185 int getegid ();
186 int setgid ();
187 int getgid ();
188 # endif
189 #endif
191 /* Different systems have different requirements for pid_t.
192 Plus we have to support gettext string translation... Argh. */
193 static const char *
194 pid2str (pid_t pid)
196 static char pidstring[100];
197 #if defined(WINDOWS32) && __GNUC__ > 3
198 sprintf (pidstring, "%Id", pid);
199 #else
200 sprintf (pidstring, "%lu", (unsigned long) pid);
201 #endif
202 return pidstring;
205 int getloadavg (double loadavg[], int nelem);
206 int start_remote_job (char **argv, char **envp, int stdin_fd, int *is_remote,
207 int *id_ptr, int *used_stdin);
208 int start_remote_job_p (int);
209 int remote_status (int *exit_code_ptr, int *signal_ptr, int *coredump_ptr,
210 int block);
212 RETSIGTYPE child_handler (int);
213 static void free_child (struct child *);
214 static void start_job_command (struct child *child);
215 static int load_too_high (void);
216 static int job_next_command (struct child *);
217 static int start_waiting_job (struct child *);
219 /* Chain of all live (or recently deceased) children. */
221 struct child *children = 0;
223 /* Number of children currently running. */
225 unsigned int job_slots_used = 0;
227 /* Nonzero if the `good' standard input is in use. */
229 static int good_stdin_used = 0;
231 /* Chain of children waiting to run until the load average goes down. */
233 static struct child *waiting_jobs = 0;
235 /* Non-zero if we use a *real* shell (always so on Unix). */
237 int unixy_shell = 1;
239 /* Number of jobs started in the current second. */
241 unsigned long job_counter = 0;
243 /* Number of jobserver tokens this instance is currently using. */
245 unsigned int jobserver_tokens = 0;
247 #ifdef WINDOWS32
249 * The macro which references this function is defined in make.h.
252 w32_kill(pid_t pid, int sig)
254 return ((process_kill((HANDLE)pid, sig) == TRUE) ? 0 : -1);
257 /* This function creates a temporary file name with an extension specified
258 * by the unixy arg.
259 * Return an xmalloc'ed string of a newly created temp file and its
260 * file descriptor, or die. */
261 static char *
262 create_batch_file (char const *base, int unixy, int *fd)
264 const char *const ext = unixy ? "sh" : "bat";
265 const char *error_string = NULL;
266 char temp_path[MAXPATHLEN]; /* need to know its length */
267 unsigned path_size = GetTempPath(sizeof temp_path, temp_path);
268 int path_is_dot = 0;
269 unsigned uniq = 1;
270 const unsigned sizemax = strlen (base) + strlen (ext) + 10;
272 if (path_size == 0)
274 path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
275 path_is_dot = 1;
278 while (path_size > 0 &&
279 path_size + sizemax < sizeof temp_path &&
280 uniq < 0x10000)
282 unsigned size = sprintf (temp_path + path_size,
283 "%s%s-%x.%s",
284 temp_path[path_size - 1] == '\\' ? "" : "\\",
285 base, uniq, ext);
286 HANDLE h = CreateFile (temp_path, /* file name */
287 GENERIC_READ | GENERIC_WRITE, /* desired access */
288 0, /* no share mode */
289 NULL, /* default security attributes */
290 CREATE_NEW, /* creation disposition */
291 FILE_ATTRIBUTE_NORMAL | /* flags and attributes */
292 FILE_ATTRIBUTE_TEMPORARY, /* we'll delete it */
293 NULL); /* no template file */
295 if (h == INVALID_HANDLE_VALUE)
297 const DWORD er = GetLastError();
299 if (er == ERROR_FILE_EXISTS || er == ERROR_ALREADY_EXISTS)
300 ++uniq;
302 /* the temporary path is not guaranteed to exist */
303 else if (path_is_dot == 0)
305 path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
306 path_is_dot = 1;
309 else
311 error_string = map_windows32_error_to_string (er);
312 break;
315 else
317 const unsigned final_size = path_size + size + 1;
318 char *const path = xmalloc (final_size);
319 memcpy (path, temp_path, final_size);
320 *fd = _open_osfhandle ((intptr_t)h, 0);
321 if (unixy)
323 char *p;
324 int ch;
325 for (p = path; (ch = *p) != 0; ++p)
326 if (ch == '\\')
327 *p = '/';
329 return path; /* good return */
333 *fd = -1;
334 if (error_string == NULL)
335 error_string = _("Cannot create a temporary file\n");
336 fatal (NILF, error_string);
338 /* not reached */
339 return NULL;
341 #endif /* WINDOWS32 */
343 #ifdef __EMX__
344 /* returns whether path is assumed to be a unix like shell. */
346 _is_unixy_shell (const char *path)
348 /* list of non unix shells */
349 const char *known_os2shells[] = {
350 "cmd.exe",
351 "cmd",
352 "4os2.exe",
353 "4os2",
354 "4dos.exe",
355 "4dos",
356 "command.com",
357 "command",
358 NULL
361 /* find the rightmost '/' or '\\' */
362 const char *name = strrchr (path, '/');
363 const char *p = strrchr (path, '\\');
364 unsigned i;
366 if (name && p) /* take the max */
367 name = (name > p) ? name : p;
368 else if (p) /* name must be 0 */
369 name = p;
370 else if (!name) /* name and p must be 0 */
371 name = path;
373 if (*name == '/' || *name == '\\') name++;
375 i = 0;
376 while (known_os2shells[i] != NULL) {
377 if (strcasecmp (name, known_os2shells[i]) == 0)
378 return 0; /* not a unix shell */
379 i++;
382 /* in doubt assume a unix like shell */
383 return 1;
385 #endif /* __EMX__ */
387 /* determines whether path looks to be a Bourne-like shell. */
389 is_bourne_compatible_shell (const char *path)
391 /* list of known unix (Bourne-like) shells */
392 const char *unix_shells[] = {
393 "sh",
394 "bash",
395 "ksh",
396 "rksh",
397 "zsh",
398 "ash",
399 "dash",
400 NULL
402 unsigned i, len;
404 /* find the rightmost '/' or '\\' */
405 const char *name = strrchr (path, '/');
406 char *p = strrchr (path, '\\');
408 if (name && p) /* take the max */
409 name = (name > p) ? name : p;
410 else if (p) /* name must be 0 */
411 name = p;
412 else if (!name) /* name and p must be 0 */
413 name = path;
415 if (*name == '/' || *name == '\\') name++;
417 /* this should be able to deal with extensions on Windows-like systems */
418 for (i = 0; unix_shells[i] != NULL; i++) {
419 len = strlen(unix_shells[i]);
420 #if defined(WINDOWS32) || defined(__MSDOS__)
421 if ((strncasecmp (name, unix_shells[i], len) == 0) &&
422 (strlen(name) >= len && (name[len] == '\0' || name[len] == '.')))
423 #else
424 if ((strncmp (name, unix_shells[i], len) == 0) &&
425 (strlen(name) >= len && name[len] == '\0'))
426 #endif
427 return 1; /* a known unix-style shell */
430 /* if not on the list, assume it's not a Bourne-like shell */
431 return 0;
435 /* Write an error message describing the exit status given in
436 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
437 Append "(ignored)" if IGNORED is nonzero. */
439 static void
440 child_error (const char *target_name,
441 int exit_code, int exit_sig, int coredump, int ignored)
443 if (ignored && silent_flag)
444 return;
446 #ifdef VMS
447 if (!(exit_code & 1))
448 error (NILF,
449 (ignored ? _("*** [%s] Error 0x%x (ignored)")
450 : _("*** [%s] Error 0x%x")),
451 target_name, exit_code);
452 #else
453 if (exit_sig == 0)
454 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
455 _("*** [%s] Error %d"),
456 target_name, exit_code);
457 else
458 error (NILF, "*** [%s] %s%s",
459 target_name, strsignal (exit_sig),
460 coredump ? _(" (core dumped)") : "");
461 #endif /* VMS */
465 /* Handle a dead child. This handler may or may not ever be installed.
467 If we're using the jobserver feature, we need it. First, installing it
468 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
469 read FD to ensure we don't enter another blocking read without reaping all
470 the dead children. In this case we don't need the dead_children count.
472 If we don't have either waitpid or wait3, then make is unreliable, but we
473 use the dead_children count to reap children as best we can. */
475 static unsigned int dead_children = 0;
477 RETSIGTYPE
478 child_handler (int sig UNUSED)
480 ++dead_children;
482 if (job_rfd >= 0)
484 close (job_rfd);
485 job_rfd = -1;
488 #ifdef __EMX__
489 /* The signal handler must called only once! */
490 signal (SIGCHLD, SIG_DFL);
491 #endif
493 /* This causes problems if the SIGCHLD interrupts a printf().
494 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
498 extern int shell_function_pid, shell_function_completed;
500 /* Reap all dead children, storing the returned status and the new command
501 state (`cs_finished') in the `file' member of the `struct child' for the
502 dead child, and removing the child from the chain. In addition, if BLOCK
503 nonzero, we block in this function until we've reaped at least one
504 complete child, waiting for it to die if necessary. If ERR is nonzero,
505 print an error message first. */
507 void
508 reap_children (int block, int err)
510 #ifndef WINDOWS32
511 WAIT_T status;
512 /* Initially, assume we have some. */
513 int reap_more = 1;
514 #endif
516 #ifdef WAIT_NOHANG
517 # define REAP_MORE reap_more
518 #else
519 # define REAP_MORE dead_children
520 #endif
522 /* As long as:
524 We have at least one child outstanding OR a shell function in progress,
526 We're blocking for a complete child OR there are more children to reap
528 we'll keep reaping children. */
530 while ((children != 0 || shell_function_pid != 0)
531 && (block || REAP_MORE))
533 int remote = 0;
534 pid_t pid;
535 int exit_code, exit_sig, coredump;
536 register struct child *lastc, *c;
537 int child_failed;
538 int any_remote, any_local;
539 int dontcare;
541 if (err && block)
543 static int printed = 0;
545 /* We might block for a while, so let the user know why.
546 Only print this message once no matter how many jobs are left. */
547 fflush (stdout);
548 if (!printed)
549 error (NILF, _("*** Waiting for unfinished jobs...."));
550 printed = 1;
553 /* We have one less dead child to reap. As noted in
554 child_handler() above, this count is completely unimportant for
555 all modern, POSIX-y systems that support wait3() or waitpid().
556 The rest of this comment below applies only to early, broken
557 pre-POSIX systems. We keep the count only because... it's there...
559 The test and decrement are not atomic; if it is compiled into:
560 register = dead_children - 1;
561 dead_children = register;
562 a SIGCHLD could come between the two instructions.
563 child_handler increments dead_children.
564 The second instruction here would lose that increment. But the
565 only effect of dead_children being wrong is that we might wait
566 longer than necessary to reap a child, and lose some parallelism;
567 and we might print the "Waiting for unfinished jobs" message above
568 when not necessary. */
570 if (dead_children > 0)
571 --dead_children;
573 any_remote = 0;
574 any_local = shell_function_pid != 0;
575 for (c = children; c != 0; c = c->next)
577 any_remote |= c->remote;
578 any_local |= ! c->remote;
579 DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
580 c, c->file->name, pid2str (c->pid),
581 c->remote ? _(" (remote)") : ""));
582 #ifdef VMS
583 break;
584 #endif
587 /* First, check for remote children. */
588 if (any_remote)
589 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
590 else
591 pid = 0;
593 if (pid > 0)
594 /* We got a remote child. */
595 remote = 1;
596 else if (pid < 0)
598 /* A remote status command failed miserably. Punt. */
599 remote_status_lose:
600 pfatal_with_name ("remote_status");
602 else
604 /* No remote children. Check for local children. */
605 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
606 if (any_local)
608 #ifdef VMS
609 vmsWaitForChildren (&status);
610 pid = c->pid;
611 #else
612 #ifdef WAIT_NOHANG
613 if (!block)
614 pid = WAIT_NOHANG (&status);
615 else
616 #endif
617 EINTRLOOP(pid, wait (&status));
618 #endif /* !VMS */
620 else
621 pid = 0;
623 if (pid < 0)
625 /* The wait*() failed miserably. Punt. */
626 pfatal_with_name ("wait");
628 else if (pid > 0)
630 /* We got a child exit; chop the status word up. */
631 exit_code = WEXITSTATUS (status);
632 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
633 coredump = WCOREDUMP (status);
635 /* If we have started jobs in this second, remove one. */
636 if (job_counter)
637 --job_counter;
639 else
641 /* No local children are dead. */
642 reap_more = 0;
644 if (!block || !any_remote)
645 break;
647 /* Now try a blocking wait for a remote child. */
648 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
649 if (pid < 0)
650 goto remote_status_lose;
651 else if (pid == 0)
652 /* No remote children either. Finally give up. */
653 break;
655 /* We got a remote child. */
656 remote = 1;
658 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
660 #ifdef __MSDOS__
661 /* Life is very different on MSDOS. */
662 pid = dos_pid - 1;
663 status = dos_status;
664 exit_code = WEXITSTATUS (status);
665 if (exit_code == 0xff)
666 exit_code = -1;
667 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
668 coredump = 0;
669 #endif /* __MSDOS__ */
670 #ifdef _AMIGA
671 /* Same on Amiga */
672 pid = amiga_pid - 1;
673 status = amiga_status;
674 exit_code = amiga_status;
675 exit_sig = 0;
676 coredump = 0;
677 #endif /* _AMIGA */
678 #ifdef WINDOWS32
680 HANDLE hPID;
681 int werr;
682 HANDLE hcTID, hcPID;
683 exit_code = 0;
684 exit_sig = 0;
685 coredump = 0;
687 /* Record the thread ID of the main process, so that we
688 could suspend it in the signal handler. */
689 if (!main_thread)
691 hcTID = GetCurrentThread ();
692 hcPID = GetCurrentProcess ();
693 if (!DuplicateHandle (hcPID, hcTID, hcPID, &main_thread, 0,
694 FALSE, DUPLICATE_SAME_ACCESS))
696 DWORD e = GetLastError ();
697 fprintf (stderr,
698 "Determine main thread ID (Error %ld: %s)\n",
699 e, map_windows32_error_to_string(e));
701 else
702 DB (DB_VERBOSE, ("Main thread handle = %p\n", main_thread));
705 /* wait for anything to finish */
706 hPID = process_wait_for_any();
707 if (hPID)
710 /* was an error found on this process? */
711 werr = process_last_err(hPID);
713 /* get exit data */
714 exit_code = process_exit_code(hPID);
716 if (werr)
717 fprintf(stderr, "make (e=%d): %s",
718 exit_code, map_windows32_error_to_string(exit_code));
720 /* signal */
721 exit_sig = process_signal(hPID);
723 /* cleanup process */
724 process_cleanup(hPID);
726 coredump = 0;
728 pid = (pid_t) hPID;
730 #endif /* WINDOWS32 */
733 /* Check if this is the child of the `shell' function. */
734 if (!remote && pid == shell_function_pid)
736 /* It is. Leave an indicator for the `shell' function. */
737 if (exit_sig == 0 && exit_code == 127)
738 shell_function_completed = -1;
739 else
740 shell_function_completed = 1;
741 break;
744 child_failed = exit_sig != 0 || exit_code != 0;
746 /* Search for a child matching the deceased one. */
747 lastc = 0;
748 for (c = children; c != 0; lastc = c, c = c->next)
749 if (c->remote == remote && c->pid == pid)
750 break;
752 if (c == 0)
753 /* An unknown child died.
754 Ignore it; it was inherited from our invoker. */
755 continue;
757 DB (DB_JOBS, (child_failed
758 ? _("Reaping losing child %p PID %s %s\n")
759 : _("Reaping winning child %p PID %s %s\n"),
760 c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
762 if (c->sh_batch_file) {
763 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
764 c->sh_batch_file));
766 /* just try and remove, don't care if this fails */
767 remove (c->sh_batch_file);
769 /* all done with memory */
770 free (c->sh_batch_file);
771 c->sh_batch_file = NULL;
774 /* If this child had the good stdin, say it is now free. */
775 if (c->good_stdin)
776 good_stdin_used = 0;
778 dontcare = c->dontcare;
780 if (child_failed && !c->noerror && !ignore_errors_flag)
782 /* The commands failed. Write an error message,
783 delete non-precious targets, and abort. */
784 static int delete_on_error = -1;
786 if (!dontcare)
787 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
789 c->file->update_status = 2;
790 if (delete_on_error == -1)
792 struct file *f = lookup_file (".DELETE_ON_ERROR");
793 delete_on_error = f != 0 && f->is_target;
795 if (exit_sig != 0 || delete_on_error)
796 delete_child_targets (c);
798 else
800 if (child_failed)
802 /* The commands failed, but we don't care. */
803 child_error (c->file->name,
804 exit_code, exit_sig, coredump, 1);
805 child_failed = 0;
808 /* If there are more commands to run, try to start them. */
809 if (job_next_command (c))
811 if (handling_fatal_signal)
813 /* Never start new commands while we are dying.
814 Since there are more commands that wanted to be run,
815 the target was not completely remade. So we treat
816 this as if a command had failed. */
817 c->file->update_status = 2;
819 else
821 /* Check again whether to start remotely.
822 Whether or not we want to changes over time.
823 Also, start_remote_job may need state set up
824 by start_remote_job_p. */
825 c->remote = start_remote_job_p (0);
826 start_job_command (c);
827 /* Fatal signals are left blocked in case we were
828 about to put that child on the chain. But it is
829 already there, so it is safe for a fatal signal to
830 arrive now; it will clean up this child's targets. */
831 unblock_sigs ();
832 if (c->file->command_state == cs_running)
833 /* We successfully started the new command.
834 Loop to reap more children. */
835 continue;
838 if (c->file->update_status != 0)
839 /* We failed to start the commands. */
840 delete_child_targets (c);
842 else
843 /* There are no more commands. We got through them all
844 without an unignored error. Now the target has been
845 successfully updated. */
846 c->file->update_status = 0;
849 /* When we get here, all the commands for C->file are finished
850 (or aborted) and C->file->update_status contains 0 or 2. But
851 C->file->command_state is still cs_running if all the commands
852 ran; notice_finish_file looks for cs_running to tell it that
853 it's interesting to check the file's modtime again now. */
855 if (! handling_fatal_signal)
856 /* Notice if the target of the commands has been changed.
857 This also propagates its values for command_state and
858 update_status to its also_make files. */
859 notice_finished_file (c->file);
861 DB (DB_JOBS, (_("Removing child %p PID %s%s from chain.\n"),
862 c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
864 /* Block fatal signals while frobnicating the list, so that
865 children and job_slots_used are always consistent. Otherwise
866 a fatal signal arriving after the child is off the chain and
867 before job_slots_used is decremented would believe a child was
868 live and call reap_children again. */
869 block_sigs ();
871 /* There is now another slot open. */
872 if (job_slots_used > 0)
873 --job_slots_used;
875 /* Remove the child from the chain and free it. */
876 if (lastc == 0)
877 children = c->next;
878 else
879 lastc->next = c->next;
881 free_child (c);
883 unblock_sigs ();
885 /* If the job failed, and the -k flag was not given, die,
886 unless we are already in the process of dying. */
887 if (!err && child_failed && !dontcare && !keep_going_flag &&
888 /* fatal_error_signal will die with the right signal. */
889 !handling_fatal_signal)
890 die (2);
892 /* Only block for one child. */
893 block = 0;
896 return;
899 /* Free the storage allocated for CHILD. */
901 static void
902 free_child (struct child *child)
904 if (!jobserver_tokens)
905 fatal (NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
906 child, child->file->name);
908 /* If we're using the jobserver and this child is not the only outstanding
909 job, put a token back into the pipe for it. */
911 if (job_fds[1] >= 0 && jobserver_tokens > 1)
913 char token = '+';
914 int r;
916 /* Write a job token back to the pipe. */
918 EINTRLOOP (r, write (job_fds[1], &token, 1));
919 if (r != 1)
920 pfatal_with_name (_("write jobserver"));
922 DB (DB_JOBS, (_("Released token for child %p (%s).\n"),
923 child, child->file->name));
926 --jobserver_tokens;
928 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
929 return;
931 if (child->command_lines != 0)
933 register unsigned int i;
934 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
935 free (child->command_lines[i]);
936 free (child->command_lines);
939 if (child->environment != 0)
941 register char **ep = child->environment;
942 while (*ep != 0)
943 free (*ep++);
944 free (child->environment);
947 free (child);
950 #ifdef POSIX
951 extern sigset_t fatal_signal_set;
952 #endif
954 void
955 block_sigs (void)
957 #ifdef POSIX
958 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
959 #else
960 # ifdef HAVE_SIGSETMASK
961 (void) sigblock (fatal_signal_mask);
962 # endif
963 #endif
966 #ifdef POSIX
967 void
968 unblock_sigs (void)
970 sigset_t empty;
971 sigemptyset (&empty);
972 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
974 #endif
976 #ifdef MAKE_JOBSERVER
977 RETSIGTYPE
978 job_noop (int sig UNUSED)
981 /* Set the child handler action flags to FLAGS. */
982 static void
983 set_child_handler_action_flags (int set_handler, int set_alarm)
985 struct sigaction sa;
987 #ifdef __EMX__
988 /* The child handler must be turned off here. */
989 signal (SIGCHLD, SIG_DFL);
990 #endif
992 memset (&sa, '\0', sizeof sa);
993 sa.sa_handler = child_handler;
994 sa.sa_flags = set_handler ? 0 : SA_RESTART;
995 #if defined SIGCHLD
996 sigaction (SIGCHLD, &sa, NULL);
997 #endif
998 #if defined SIGCLD && SIGCLD != SIGCHLD
999 sigaction (SIGCLD, &sa, NULL);
1000 #endif
1001 #if defined SIGALRM
1002 if (set_alarm)
1004 /* If we're about to enter the read(), set an alarm to wake up in a
1005 second so we can check if the load has dropped and we can start more
1006 work. On the way out, turn off the alarm and set SIG_DFL. */
1007 alarm (set_handler ? 1 : 0);
1008 sa.sa_handler = set_handler ? job_noop : SIG_DFL;
1009 sa.sa_flags = 0;
1010 sigaction (SIGALRM, &sa, NULL);
1012 #endif
1014 #endif
1017 /* Start a job to run the commands specified in CHILD.
1018 CHILD is updated to reflect the commands and ID of the child process.
1020 NOTE: On return fatal signals are blocked! The caller is responsible
1021 for calling `unblock_sigs', once the new child is safely on the chain so
1022 it can be cleaned up in the event of a fatal signal. */
1024 static void
1025 start_job_command (struct child *child)
1027 #if !defined(_AMIGA) && !defined(WINDOWS32)
1028 static int bad_stdin = -1;
1029 #endif
1030 char *p;
1031 /* Must be volatile to silence bogus GCC warning about longjmp/vfork. */
1032 volatile int flags;
1033 #ifdef VMS
1034 char *argv;
1035 #else
1036 char **argv;
1037 #endif
1039 /* If we have a completely empty commandset, stop now. */
1040 if (!child->command_ptr)
1041 goto next_command;
1043 /* Combine the flags parsed for the line itself with
1044 the flags specified globally for this target. */
1045 flags = (child->file->command_flags
1046 | child->file->cmds->lines_flags[child->command_line - 1]);
1048 p = child->command_ptr;
1049 child->noerror = ((flags & COMMANDS_NOERROR) != 0);
1051 while (*p != '\0')
1053 if (*p == '@')
1054 flags |= COMMANDS_SILENT;
1055 else if (*p == '+')
1056 flags |= COMMANDS_RECURSE;
1057 else if (*p == '-')
1058 child->noerror = 1;
1059 else if (!isblank ((unsigned char)*p))
1060 break;
1061 ++p;
1064 /* Update the file's command flags with any new ones we found. We only
1065 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
1066 now marking more commands recursive than should be in the case of
1067 multiline define/endef scripts where only one line is marked "+". In
1068 order to really fix this, we'll have to keep a lines_flags for every
1069 actual line, after expansion. */
1070 child->file->cmds->lines_flags[child->command_line - 1]
1071 |= flags & COMMANDS_RECURSE;
1073 /* Figure out an argument list from this command line. */
1076 char *end = 0;
1077 #ifdef VMS
1078 argv = p;
1079 #else
1080 argv = construct_command_argv (p, &end, child->file,
1081 child->file->cmds->lines_flags[child->command_line - 1],
1082 &child->sh_batch_file);
1083 #endif
1084 if (end == NULL)
1085 child->command_ptr = NULL;
1086 else
1088 *end++ = '\0';
1089 child->command_ptr = end;
1093 /* If -q was given, say that updating `failed' if there was any text on the
1094 command line, or `succeeded' otherwise. The exit status of 1 tells the
1095 user that -q is saying `something to do'; the exit status for a random
1096 error is 2. */
1097 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
1099 #ifndef VMS
1100 free (argv[0]);
1101 free (argv);
1102 #endif
1103 child->file->update_status = 1;
1104 notice_finished_file (child->file);
1105 return;
1108 if (touch_flag && !(flags & COMMANDS_RECURSE))
1110 /* Go on to the next command. It might be the recursive one.
1111 We construct ARGV only to find the end of the command line. */
1112 #ifndef VMS
1113 if (argv)
1115 free (argv[0]);
1116 free (argv);
1118 #endif
1119 argv = 0;
1122 if (argv == 0)
1124 next_command:
1125 #ifdef __MSDOS__
1126 execute_by_shell = 0; /* in case construct_command_argv sets it */
1127 #endif
1128 /* This line has no commands. Go to the next. */
1129 if (job_next_command (child))
1130 start_job_command (child);
1131 else
1133 /* No more commands. Make sure we're "running"; we might not be if
1134 (e.g.) all commands were skipped due to -n. */
1135 set_command_state (child->file, cs_running);
1136 child->file->update_status = 0;
1137 notice_finished_file (child->file);
1139 return;
1142 /* Print out the command. If silent, we call `message' with null so it
1143 can log the working directory before the command's own error messages
1144 appear. */
1146 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
1147 ? "%s" : (char *) 0, p);
1149 /* Tell update_goal_chain that a command has been started on behalf of
1150 this target. It is important that this happens here and not in
1151 reap_children (where we used to do it), because reap_children might be
1152 reaping children from a different target. We want this increment to
1153 guaranteedly indicate that a command was started for the dependency
1154 chain (i.e., update_file recursion chain) we are processing. */
1156 ++commands_started;
1158 /* Optimize an empty command. People use this for timestamp rules,
1159 so avoid forking a useless shell. Do this after we increment
1160 commands_started so make still treats this special case as if it
1161 performed some action (makes a difference as to what messages are
1162 printed, etc. */
1164 #if !defined(VMS) && !defined(_AMIGA)
1165 if (
1166 #if defined __MSDOS__ || defined (__EMX__)
1167 unixy_shell /* the test is complicated and we already did it */
1168 #else
1169 (argv[0] && is_bourne_compatible_shell(argv[0]))
1170 #endif
1171 && (argv[1] && argv[1][0] == '-'
1173 ((argv[1][1] == 'c' && argv[1][2] == '\0')
1175 (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
1176 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1177 && argv[3] == NULL)
1179 free (argv[0]);
1180 free (argv);
1181 goto next_command;
1183 #endif /* !VMS && !_AMIGA */
1185 /* If -n was given, recurse to get the next line in the sequence. */
1187 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1189 #ifndef VMS
1190 free (argv[0]);
1191 free (argv);
1192 #endif
1193 goto next_command;
1196 /* Flush the output streams so they won't have things written twice. */
1198 fflush (stdout);
1199 fflush (stderr);
1201 #ifndef VMS
1202 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1204 /* Set up a bad standard input that reads from a broken pipe. */
1206 if (bad_stdin == -1)
1208 /* Make a file descriptor that is the read end of a broken pipe.
1209 This will be used for some children's standard inputs. */
1210 int pd[2];
1211 if (pipe (pd) == 0)
1213 /* Close the write side. */
1214 (void) close (pd[1]);
1215 /* Save the read side. */
1216 bad_stdin = pd[0];
1218 /* Set the descriptor to close on exec, so it does not litter any
1219 child's descriptor table. When it is dup2'd onto descriptor 0,
1220 that descriptor will not close on exec. */
1221 CLOSE_ON_EXEC (bad_stdin);
1225 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1227 /* Decide whether to give this child the `good' standard input
1228 (one that points to the terminal or whatever), or the `bad' one
1229 that points to the read side of a broken pipe. */
1231 child->good_stdin = !good_stdin_used;
1232 if (child->good_stdin)
1233 good_stdin_used = 1;
1235 #endif /* !VMS */
1237 child->deleted = 0;
1239 #ifndef _AMIGA
1240 /* Set up the environment for the child. */
1241 if (child->environment == 0)
1242 child->environment = target_environment (child->file);
1243 #endif
1245 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1247 #ifndef VMS
1248 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1249 if (child->remote)
1251 int is_remote, id, used_stdin;
1252 if (start_remote_job (argv, child->environment,
1253 child->good_stdin ? 0 : bad_stdin,
1254 &is_remote, &id, &used_stdin))
1255 /* Don't give up; remote execution may fail for various reasons. If
1256 so, simply run the job locally. */
1257 goto run_local;
1258 else
1260 if (child->good_stdin && !used_stdin)
1262 child->good_stdin = 0;
1263 good_stdin_used = 0;
1265 child->remote = is_remote;
1266 child->pid = id;
1269 else
1270 #endif /* !VMS */
1272 /* Fork the child process. */
1274 char **parent_environ;
1276 run_local:
1277 block_sigs ();
1279 child->remote = 0;
1281 #ifdef VMS
1282 if (!child_execute_job (argv, child)) {
1283 /* Fork failed! */
1284 perror_with_name ("vfork", "");
1285 goto error;
1288 #else
1290 parent_environ = environ;
1292 # ifdef __EMX__
1293 /* If we aren't running a recursive command and we have a jobserver
1294 pipe, close it before exec'ing. */
1295 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1297 CLOSE_ON_EXEC (job_fds[0]);
1298 CLOSE_ON_EXEC (job_fds[1]);
1300 if (job_rfd >= 0)
1301 CLOSE_ON_EXEC (job_rfd);
1303 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1304 child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1305 argv, child->environment);
1306 if (child->pid < 0)
1308 /* spawn failed! */
1309 unblock_sigs ();
1310 perror_with_name ("spawn", "");
1311 goto error;
1314 /* undo CLOSE_ON_EXEC() after the child process has been started */
1315 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1317 fcntl (job_fds[0], F_SETFD, 0);
1318 fcntl (job_fds[1], F_SETFD, 0);
1320 if (job_rfd >= 0)
1321 fcntl (job_rfd, F_SETFD, 0);
1323 #else /* !__EMX__ */
1325 child->pid = vfork ();
1326 environ = parent_environ; /* Restore value child may have clobbered. */
1327 if (child->pid == 0)
1329 /* We are the child side. */
1330 unblock_sigs ();
1332 /* If we aren't running a recursive command and we have a jobserver
1333 pipe, close it before exec'ing. */
1334 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1336 close (job_fds[0]);
1337 close (job_fds[1]);
1339 if (job_rfd >= 0)
1340 close (job_rfd);
1342 #ifdef SET_STACK_SIZE
1343 /* Reset limits, if necessary. */
1344 if (stack_limit.rlim_cur)
1345 setrlimit (RLIMIT_STACK, &stack_limit);
1346 #endif
1348 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1349 argv, child->environment);
1351 else if (child->pid < 0)
1353 /* Fork failed! */
1354 unblock_sigs ();
1355 perror_with_name ("vfork", "");
1356 goto error;
1358 # endif /* !__EMX__ */
1359 #endif /* !VMS */
1362 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1363 #ifdef __MSDOS__
1365 int proc_return;
1367 block_sigs ();
1368 dos_status = 0;
1370 /* We call `system' to do the job of the SHELL, since stock DOS
1371 shell is too dumb. Our `system' knows how to handle long
1372 command lines even if pipes/redirection is needed; it will only
1373 call COMMAND.COM when its internal commands are used. */
1374 if (execute_by_shell)
1376 char *cmdline = argv[0];
1377 /* We don't have a way to pass environment to `system',
1378 so we need to save and restore ours, sigh... */
1379 char **parent_environ = environ;
1381 environ = child->environment;
1383 /* If we have a *real* shell, tell `system' to call
1384 it to do everything for us. */
1385 if (unixy_shell)
1387 /* A *real* shell on MSDOS may not support long
1388 command lines the DJGPP way, so we must use `system'. */
1389 cmdline = argv[2]; /* get past "shell -c" */
1392 dos_command_running = 1;
1393 proc_return = system (cmdline);
1394 environ = parent_environ;
1395 execute_by_shell = 0; /* for the next time */
1397 else
1399 dos_command_running = 1;
1400 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1403 /* Need to unblock signals before turning off
1404 dos_command_running, so that child's signals
1405 will be treated as such (see fatal_error_signal). */
1406 unblock_sigs ();
1407 dos_command_running = 0;
1409 /* If the child got a signal, dos_status has its
1410 high 8 bits set, so be careful not to alter them. */
1411 if (proc_return == -1)
1412 dos_status |= 0xff;
1413 else
1414 dos_status |= (proc_return & 0xff);
1415 ++dead_children;
1416 child->pid = dos_pid++;
1418 #endif /* __MSDOS__ */
1419 #ifdef _AMIGA
1420 amiga_status = MyExecute (argv);
1422 ++dead_children;
1423 child->pid = amiga_pid++;
1424 if (amiga_batch_file)
1426 amiga_batch_file = 0;
1427 DeleteFile (amiga_bname); /* Ignore errors. */
1429 #endif /* Amiga */
1430 #ifdef WINDOWS32
1432 HANDLE hPID;
1433 char* arg0;
1435 /* make UNC paths safe for CreateProcess -- backslash format */
1436 arg0 = argv[0];
1437 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1438 for ( ; arg0 && *arg0; arg0++)
1439 if (*arg0 == '/')
1440 *arg0 = '\\';
1442 /* make sure CreateProcess() has Path it needs */
1443 sync_Path_environment();
1445 hPID = process_easy(argv, child->environment);
1447 if (hPID != INVALID_HANDLE_VALUE)
1448 child->pid = (pid_t) hPID;
1449 else {
1450 int i;
1451 unblock_sigs();
1452 fprintf(stderr,
1453 _("process_easy() failed to launch process (e=%ld)\n"),
1454 process_last_err(hPID));
1455 for (i = 0; argv[i]; i++)
1456 fprintf(stderr, "%s ", argv[i]);
1457 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1458 goto error;
1461 #endif /* WINDOWS32 */
1462 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1464 /* Bump the number of jobs started in this second. */
1465 ++job_counter;
1467 /* We are the parent side. Set the state to
1468 say the commands are running and return. */
1470 set_command_state (child->file, cs_running);
1472 /* Free the storage used by the child's argument list. */
1473 #ifndef VMS
1474 free (argv[0]);
1475 free (argv);
1476 #endif
1478 return;
1480 error:
1481 child->file->update_status = 2;
1482 notice_finished_file (child->file);
1483 return;
1486 /* Try to start a child running.
1487 Returns nonzero if the child was started (and maybe finished), or zero if
1488 the load was too high and the child was put on the `waiting_jobs' chain. */
1490 static int
1491 start_waiting_job (struct child *c)
1493 struct file *f = c->file;
1495 /* If we can start a job remotely, we always want to, and don't care about
1496 the local load average. We record that the job should be started
1497 remotely in C->remote for start_job_command to test. */
1499 c->remote = start_remote_job_p (1);
1501 /* If we are running at least one job already and the load average
1502 is too high, make this one wait. */
1503 if (!c->remote
1504 && ((job_slots_used > 0 && load_too_high ())
1505 #ifdef WINDOWS32
1506 || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
1507 #endif
1510 /* Put this child on the chain of children waiting for the load average
1511 to go down. */
1512 set_command_state (f, cs_running);
1513 c->next = waiting_jobs;
1514 waiting_jobs = c;
1515 return 0;
1518 /* Start the first command; reap_children will run later command lines. */
1519 start_job_command (c);
1521 switch (f->command_state)
1523 case cs_running:
1524 c->next = children;
1525 DB (DB_JOBS, (_("Putting child %p (%s) PID %s%s on the chain.\n"),
1526 c, c->file->name, pid2str (c->pid),
1527 c->remote ? _(" (remote)") : ""));
1528 children = c;
1529 /* One more job slot is in use. */
1530 ++job_slots_used;
1531 unblock_sigs ();
1532 break;
1534 case cs_not_started:
1535 /* All the command lines turned out to be empty. */
1536 f->update_status = 0;
1537 /* FALLTHROUGH */
1539 case cs_finished:
1540 notice_finished_file (f);
1541 free_child (c);
1542 break;
1544 default:
1545 assert (f->command_state == cs_finished);
1546 break;
1549 return 1;
1552 /* Create a `struct child' for FILE and start its commands running. */
1554 void
1555 new_job (struct file *file)
1557 struct commands *cmds = file->cmds;
1558 struct child *c;
1559 char **lines;
1560 unsigned int i;
1562 /* Let any previously decided-upon jobs that are waiting
1563 for the load to go down start before this new one. */
1564 start_waiting_jobs ();
1566 /* Reap any children that might have finished recently. */
1567 reap_children (0, 0);
1569 /* Chop the commands up into lines if they aren't already. */
1570 chop_commands (cmds);
1572 /* Expand the command lines and store the results in LINES. */
1573 lines = xmalloc (cmds->ncommand_lines * sizeof (char *));
1574 for (i = 0; i < cmds->ncommand_lines; ++i)
1576 /* Collapse backslash-newline combinations that are inside variable
1577 or function references. These are left alone by the parser so
1578 that they will appear in the echoing of commands (where they look
1579 nice); and collapsed by construct_command_argv when it tokenizes.
1580 But letting them survive inside function invocations loses because
1581 we don't want the functions to see them as part of the text. */
1583 char *in, *out, *ref;
1585 /* IN points to where in the line we are scanning.
1586 OUT points to where in the line we are writing.
1587 When we collapse a backslash-newline combination,
1588 IN gets ahead of OUT. */
1590 in = out = cmds->command_lines[i];
1591 while ((ref = strchr (in, '$')) != 0)
1593 ++ref; /* Move past the $. */
1595 if (out != in)
1596 /* Copy the text between the end of the last chunk
1597 we processed (where IN points) and the new chunk
1598 we are about to process (where REF points). */
1599 memmove (out, in, ref - in);
1601 /* Move both pointers past the boring stuff. */
1602 out += ref - in;
1603 in = ref;
1605 if (*ref == '(' || *ref == '{')
1607 char openparen = *ref;
1608 char closeparen = openparen == '(' ? ')' : '}';
1609 int count;
1610 char *p;
1612 *out++ = *in++; /* Copy OPENPAREN. */
1613 /* IN now points past the opening paren or brace.
1614 Count parens or braces until it is matched. */
1615 count = 0;
1616 while (*in != '\0')
1618 if (*in == closeparen && --count < 0)
1619 break;
1620 else if (*in == '\\' && in[1] == '\n')
1622 /* We have found a backslash-newline inside a
1623 variable or function reference. Eat it and
1624 any following whitespace. */
1626 int quoted = 0;
1627 for (p = in - 1; p > ref && *p == '\\'; --p)
1628 quoted = !quoted;
1630 if (quoted)
1631 /* There were two or more backslashes, so this is
1632 not really a continuation line. We don't collapse
1633 the quoting backslashes here as is done in
1634 collapse_continuations, because the line will
1635 be collapsed again after expansion. */
1636 *out++ = *in++;
1637 else
1639 /* Skip the backslash, newline and
1640 any following whitespace. */
1641 in = next_token (in + 2);
1643 /* Discard any preceding whitespace that has
1644 already been written to the output. */
1645 while (out > ref
1646 && isblank ((unsigned char)out[-1]))
1647 --out;
1649 /* Replace it all with a single space. */
1650 *out++ = ' ';
1653 else
1655 if (*in == openparen)
1656 ++count;
1658 *out++ = *in++;
1664 /* There are no more references in this line to worry about.
1665 Copy the remaining uninteresting text to the output. */
1666 if (out != in)
1667 memmove (out, in, strlen (in) + 1);
1669 /* Finally, expand the line. */
1670 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1671 file);
1674 /* Start the command sequence, record it in a new
1675 `struct child', and add that to the chain. */
1677 c = xcalloc (sizeof (struct child));
1678 c->file = file;
1679 c->command_lines = lines;
1680 c->sh_batch_file = NULL;
1682 /* Cache dontcare flag because file->dontcare can be changed once we
1683 return. Check dontcare inheritance mechanism for details. */
1684 c->dontcare = file->dontcare;
1686 /* Fetch the first command line to be run. */
1687 job_next_command (c);
1689 /* Wait for a job slot to be freed up. If we allow an infinite number
1690 don't bother; also job_slots will == 0 if we're using the jobserver. */
1692 if (job_slots != 0)
1693 while (job_slots_used == job_slots)
1694 reap_children (1, 0);
1696 #ifdef MAKE_JOBSERVER
1697 /* If we are controlling multiple jobs make sure we have a token before
1698 starting the child. */
1700 /* This can be inefficient. There's a decent chance that this job won't
1701 actually have to run any subprocesses: the command script may be empty
1702 or otherwise optimized away. It would be nice if we could defer
1703 obtaining a token until just before we need it, in start_job_command.
1704 To do that we'd need to keep track of whether we'd already obtained a
1705 token (since start_job_command is called for each line of the job, not
1706 just once). Also more thought needs to go into the entire algorithm;
1707 this is where the old parallel job code waits, so... */
1709 else if (job_fds[0] >= 0)
1710 while (1)
1712 char token;
1713 int got_token;
1714 int saved_errno;
1716 DB (DB_JOBS, ("Need a job token; we %shave children\n",
1717 children ? "" : "don't "));
1719 /* If we don't already have a job started, use our "free" token. */
1720 if (!jobserver_tokens)
1721 break;
1723 /* Read a token. As long as there's no token available we'll block.
1724 We enable interruptible system calls before the read(2) so that if
1725 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1726 we can process the death(s) and return tokens to the free pool.
1728 Once we return from the read, we immediately reinstate restartable
1729 system calls. This allows us to not worry about checking for
1730 EINTR on all the other system calls in the program.
1732 There is one other twist: there is a span between the time
1733 reap_children() does its last check for dead children and the time
1734 the read(2) call is entered, below, where if a child dies we won't
1735 notice. This is extremely serious as it could cause us to
1736 deadlock, given the right set of events.
1738 To avoid this, we do the following: before we reap_children(), we
1739 dup(2) the read FD on the jobserver pipe. The read(2) call below
1740 uses that new FD. In the signal handler, we close that FD. That
1741 way, if a child dies during the section mentioned above, the
1742 read(2) will be invoked with an invalid FD and will return
1743 immediately with EBADF. */
1745 /* Make sure we have a dup'd FD. */
1746 if (job_rfd < 0)
1748 DB (DB_JOBS, ("Duplicate the job FD\n"));
1749 job_rfd = dup (job_fds[0]);
1752 /* Reap anything that's currently waiting. */
1753 reap_children (0, 0);
1755 /* Kick off any jobs we have waiting for an opportunity that
1756 can run now (ie waiting for load). */
1757 start_waiting_jobs ();
1759 /* If our "free" slot has become available, use it; we don't need an
1760 actual token. */
1761 if (!jobserver_tokens)
1762 break;
1764 /* There must be at least one child already, or we have no business
1765 waiting for a token. */
1766 if (!children)
1767 fatal (NILF, "INTERNAL: no children as we go to sleep on read\n");
1769 /* Set interruptible system calls, and read() for a job token. */
1770 set_child_handler_action_flags (1, waiting_jobs != NULL);
1771 got_token = read (job_rfd, &token, 1);
1772 saved_errno = errno;
1773 set_child_handler_action_flags (0, waiting_jobs != NULL);
1775 /* If we got one, we're done here. */
1776 if (got_token == 1)
1778 DB (DB_JOBS, (_("Obtained token for child %p (%s).\n"),
1779 c, c->file->name));
1780 break;
1783 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1784 go back and reap_children(), and try again. */
1785 errno = saved_errno;
1786 if (errno != EINTR && errno != EBADF)
1787 pfatal_with_name (_("read jobs pipe"));
1788 if (errno == EBADF)
1789 DB (DB_JOBS, ("Read returned EBADF.\n"));
1791 #endif
1793 ++jobserver_tokens;
1795 /* The job is now primed. Start it running.
1796 (This will notice if there is in fact no recipe.) */
1797 if (cmds->fileinfo.filenm)
1798 DB (DB_BASIC, (_("Invoking recipe from %s:%lu to update target `%s'.\n"),
1799 cmds->fileinfo.filenm, cmds->fileinfo.lineno,
1800 c->file->name));
1801 else
1802 DB (DB_BASIC, (_("Invoking builtin recipe to update target `%s'.\n"),
1803 c->file->name));
1806 start_waiting_job (c);
1808 if (job_slots == 1 || not_parallel)
1809 /* Since there is only one job slot, make things run linearly.
1810 Wait for the child to die, setting the state to `cs_finished'. */
1811 while (file->command_state == cs_running)
1812 reap_children (1, 0);
1814 return;
1817 /* Move CHILD's pointers to the next command for it to execute.
1818 Returns nonzero if there is another command. */
1820 static int
1821 job_next_command (struct child *child)
1823 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1825 /* There are no more lines in the expansion of this line. */
1826 if (child->command_line == child->file->cmds->ncommand_lines)
1828 /* There are no more lines to be expanded. */
1829 child->command_ptr = 0;
1830 return 0;
1832 else
1833 /* Get the next line to run. */
1834 child->command_ptr = child->command_lines[child->command_line++];
1836 return 1;
1839 /* Determine if the load average on the system is too high to start a new job.
1840 The real system load average is only recomputed once a second. However, a
1841 very parallel make can easily start tens or even hundreds of jobs in a
1842 second, which brings the system to its knees for a while until that first
1843 batch of jobs clears out.
1845 To avoid this we use a weighted algorithm to try to account for jobs which
1846 have been started since the last second, and guess what the load average
1847 would be now if it were computed.
1849 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1850 who writes:
1852 ! calculate something load-oid and add to the observed sys.load,
1853 ! so that latter can catch up:
1854 ! - every job started increases jobctr;
1855 ! - every dying job decreases a positive jobctr;
1856 ! - the jobctr value gets zeroed every change of seconds,
1857 ! after its value*weight_b is stored into the 'backlog' value last_sec
1858 ! - weight_a times the sum of jobctr and last_sec gets
1859 ! added to the observed sys.load.
1861 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1862 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1863 ! sub-shelled commands (rm, echo, sed...) for tests.
1864 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1865 ! resulted in significant excession of the load limit, raising it
1866 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1867 ! reach the limit in most test cases.
1869 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1870 ! exceeding the limit for longer-running stuff (compile jobs in
1871 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1872 ! small jobs' effects.
1876 #define LOAD_WEIGHT_A 0.25
1877 #define LOAD_WEIGHT_B 0.25
1879 static int
1880 load_too_high (void)
1882 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
1883 return 1;
1884 #else
1885 static double last_sec;
1886 static time_t last_now;
1887 double load, guess;
1888 time_t now;
1890 #ifdef WINDOWS32
1891 /* sub_proc.c cannot wait for more than MAXIMUM_WAIT_OBJECTS children */
1892 if (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
1893 return 1;
1894 #endif
1896 if (max_load_average < 0)
1897 return 0;
1899 /* Find the real system load average. */
1900 make_access ();
1901 if (getloadavg (&load, 1) != 1)
1903 static int lossage = -1;
1904 /* Complain only once for the same error. */
1905 if (lossage == -1 || errno != lossage)
1907 if (errno == 0)
1908 /* An errno value of zero means getloadavg is just unsupported. */
1909 error (NILF,
1910 _("cannot enforce load limits on this operating system"));
1911 else
1912 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1914 lossage = errno;
1915 load = 0;
1917 user_access ();
1919 /* If we're in a new second zero the counter and correct the backlog
1920 value. Only keep the backlog for one extra second; after that it's 0. */
1921 now = time (NULL);
1922 if (last_now < now)
1924 if (last_now == now - 1)
1925 last_sec = LOAD_WEIGHT_B * job_counter;
1926 else
1927 last_sec = 0.0;
1929 job_counter = 0;
1930 last_now = now;
1933 /* Try to guess what the load would be right now. */
1934 guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
1936 DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1937 guess, load, max_load_average));
1939 return guess >= max_load_average;
1940 #endif
1943 /* Start jobs that are waiting for the load to be lower. */
1945 void
1946 start_waiting_jobs (void)
1948 struct child *job;
1950 if (waiting_jobs == 0)
1951 return;
1955 /* Check for recently deceased descendants. */
1956 reap_children (0, 0);
1958 /* Take a job off the waiting list. */
1959 job = waiting_jobs;
1960 waiting_jobs = job->next;
1962 /* Try to start that job. We break out of the loop as soon
1963 as start_waiting_job puts one back on the waiting list. */
1965 while (start_waiting_job (job) && waiting_jobs != 0);
1967 return;
1970 #ifndef WINDOWS32
1972 /* EMX: Start a child process. This function returns the new pid. */
1973 # if defined __EMX__
1975 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
1977 int pid;
1978 /* stdin_fd == 0 means: nothing to do for stdin;
1979 stdout_fd == 1 means: nothing to do for stdout */
1980 int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
1981 int save_stdout = (stdout_fd != 1) ? dup (1): 1;
1983 /* < 0 only if dup() failed */
1984 if (save_stdin < 0)
1985 fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
1986 if (save_stdout < 0)
1987 fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
1989 /* Close unnecessary file handles for the child. */
1990 if (save_stdin != 0)
1991 CLOSE_ON_EXEC (save_stdin);
1992 if (save_stdout != 1)
1993 CLOSE_ON_EXEC (save_stdout);
1995 /* Connect the pipes to the child process. */
1996 if (stdin_fd != 0)
1997 (void) dup2 (stdin_fd, 0);
1998 if (stdout_fd != 1)
1999 (void) dup2 (stdout_fd, 1);
2001 /* stdin_fd and stdout_fd must be closed on exit because we are
2002 still in the parent process */
2003 if (stdin_fd != 0)
2004 CLOSE_ON_EXEC (stdin_fd);
2005 if (stdout_fd != 1)
2006 CLOSE_ON_EXEC (stdout_fd);
2008 /* Run the command. */
2009 pid = exec_command (argv, envp);
2011 /* Restore stdout/stdin of the parent and close temporary FDs. */
2012 if (stdin_fd != 0)
2014 if (dup2 (save_stdin, 0) != 0)
2015 fatal (NILF, _("Could not restore stdin\n"));
2016 else
2017 close (save_stdin);
2020 if (stdout_fd != 1)
2022 if (dup2 (save_stdout, 1) != 1)
2023 fatal (NILF, _("Could not restore stdout\n"));
2024 else
2025 close (save_stdout);
2028 return pid;
2031 #elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
2033 /* UNIX:
2034 Replace the current process with one executing the command in ARGV.
2035 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2036 the environment of the new program. This function does not return. */
2037 void
2038 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2040 if (stdin_fd != 0)
2041 (void) dup2 (stdin_fd, 0);
2042 if (stdout_fd != 1)
2043 (void) dup2 (stdout_fd, 1);
2044 if (stdin_fd != 0)
2045 (void) close (stdin_fd);
2046 if (stdout_fd != 1)
2047 (void) close (stdout_fd);
2049 /* Run the command. */
2050 exec_command (argv, envp);
2052 #endif /* !AMIGA && !__MSDOS__ && !VMS */
2053 #endif /* !WINDOWS32 */
2055 #ifndef _AMIGA
2056 /* Replace the current process with one running the command in ARGV,
2057 with environment ENVP. This function does not return. */
2059 /* EMX: This function returns the pid of the child process. */
2060 # ifdef __EMX__
2062 # else
2063 void
2064 # endif
2065 exec_command (char **argv, char **envp)
2067 #ifdef VMS
2068 /* to work around a problem with signals and execve: ignore them */
2069 #ifdef SIGCHLD
2070 signal (SIGCHLD,SIG_IGN);
2071 #endif
2072 /* Run the program. */
2073 execve (argv[0], argv, envp);
2074 perror_with_name ("execve: ", argv[0]);
2075 _exit (EXIT_FAILURE);
2076 #else
2077 #ifdef WINDOWS32
2078 HANDLE hPID;
2079 HANDLE hWaitPID;
2080 int err = 0;
2081 int exit_code = EXIT_FAILURE;
2083 /* make sure CreateProcess() has Path it needs */
2084 sync_Path_environment();
2086 /* launch command */
2087 hPID = process_easy(argv, envp);
2089 /* make sure launch ok */
2090 if (hPID == INVALID_HANDLE_VALUE)
2092 int i;
2093 fprintf(stderr,
2094 _("process_easy() failed to launch process (e=%ld)\n"),
2095 process_last_err(hPID));
2096 for (i = 0; argv[i]; i++)
2097 fprintf(stderr, "%s ", argv[i]);
2098 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2099 exit(EXIT_FAILURE);
2102 /* wait and reap last child */
2103 hWaitPID = process_wait_for_any();
2104 while (hWaitPID)
2106 /* was an error found on this process? */
2107 err = process_last_err(hWaitPID);
2109 /* get exit data */
2110 exit_code = process_exit_code(hWaitPID);
2112 if (err)
2113 fprintf(stderr, "make (e=%d, rc=%d): %s",
2114 err, exit_code, map_windows32_error_to_string(err));
2116 /* cleanup process */
2117 process_cleanup(hWaitPID);
2119 /* expect to find only last pid, warn about other pids reaped */
2120 if (hWaitPID == hPID)
2121 break;
2122 else
2124 char *pidstr = xstrdup (pid2str ((DWORD_PTR)hWaitPID));
2126 fprintf(stderr,
2127 _("make reaped child pid %s, still waiting for pid %s\n"),
2128 pidstr, pid2str ((DWORD_PTR)hPID));
2129 free (pidstr);
2133 /* return child's exit code as our exit code */
2134 exit(exit_code);
2136 #else /* !WINDOWS32 */
2138 # ifdef __EMX__
2139 int pid;
2140 # endif
2142 /* Be the user, permanently. */
2143 child_access ();
2145 # ifdef __EMX__
2147 /* Run the program. */
2148 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2150 if (pid >= 0)
2151 return pid;
2153 /* the file might have a strange shell extension */
2154 if (errno == ENOENT)
2155 errno = ENOEXEC;
2157 # else
2159 /* Run the program. */
2160 environ = envp;
2161 execvp (argv[0], argv);
2163 # endif /* !__EMX__ */
2165 switch (errno)
2167 case ENOENT:
2168 error (NILF, _("%s: Command not found"), argv[0]);
2169 break;
2170 case ENOEXEC:
2172 /* The file is not executable. Try it as a shell script. */
2173 extern char *getenv ();
2174 char *shell;
2175 char **new_argv;
2176 int argc;
2177 int i=1;
2179 # ifdef __EMX__
2180 /* Do not use $SHELL from the environment */
2181 struct variable *p = lookup_variable ("SHELL", 5);
2182 if (p)
2183 shell = p->value;
2184 else
2185 shell = 0;
2186 # else
2187 shell = getenv ("SHELL");
2188 # endif
2189 if (shell == 0)
2190 shell = default_shell;
2192 argc = 1;
2193 while (argv[argc] != 0)
2194 ++argc;
2196 # ifdef __EMX__
2197 if (!unixy_shell)
2198 ++argc;
2199 # endif
2201 new_argv = alloca ((1 + argc + 1) * sizeof (char *));
2202 new_argv[0] = shell;
2204 # ifdef __EMX__
2205 if (!unixy_shell)
2207 new_argv[1] = "/c";
2208 ++i;
2209 --argc;
2211 # endif
2213 new_argv[i] = argv[0];
2214 while (argc > 0)
2216 new_argv[i + argc] = argv[argc];
2217 --argc;
2220 # ifdef __EMX__
2221 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2222 if (pid >= 0)
2223 break;
2224 # else
2225 execvp (shell, new_argv);
2226 # endif
2227 if (errno == ENOENT)
2228 error (NILF, _("%s: Shell program not found"), shell);
2229 else
2230 perror_with_name ("execvp: ", shell);
2231 break;
2234 # ifdef __EMX__
2235 case EINVAL:
2236 /* this nasty error was driving me nuts :-( */
2237 error (NILF, _("spawnvpe: environment space might be exhausted"));
2238 /* FALLTHROUGH */
2239 # endif
2241 default:
2242 perror_with_name ("execvp: ", argv[0]);
2243 break;
2246 # ifdef __EMX__
2247 return pid;
2248 # else
2249 _exit (127);
2250 # endif
2251 #endif /* !WINDOWS32 */
2252 #endif /* !VMS */
2254 #else /* On Amiga */
2255 void exec_command (char **argv)
2257 MyExecute (argv);
2260 void clean_tmp (void)
2262 DeleteFile (amiga_bname);
2265 #endif /* On Amiga */
2267 #ifndef VMS
2268 /* Figure out the argument list necessary to run LINE as a command. Try to
2269 avoid using a shell. This routine handles only ' quoting, and " quoting
2270 when no backslash, $ or ` characters are seen in the quotes. Starting
2271 quotes may be escaped with a backslash. If any of the characters in
2272 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2273 is the first word of a line, the shell is used.
2275 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2276 If *RESTP is NULL, newlines will be ignored.
2278 SHELL is the shell to use, or nil to use the default shell.
2279 IFS is the value of $IFS, or nil (meaning the default).
2281 FLAGS is the value of lines_flags for this command line. It is
2282 used in the WINDOWS32 port to check whether + or $(MAKE) were found
2283 in this command line, in which case the effect of just_print_flag
2284 is overridden. */
2286 static char **
2287 construct_command_argv_internal (char *line, char **restp, char *shell,
2288 char *shellflags, char *ifs, int flags,
2289 char **batch_filename_ptr)
2291 #ifdef __MSDOS__
2292 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2293 We call `system' for anything that requires ``slow'' processing,
2294 because DOS shells are too dumb. When $SHELL points to a real
2295 (unix-style) shell, `system' just calls it to do everything. When
2296 $SHELL points to a DOS shell, `system' does most of the work
2297 internally, calling the shell only for its internal commands.
2298 However, it looks on the $PATH first, so you can e.g. have an
2299 external command named `mkdir'.
2301 Since we call `system', certain characters and commands below are
2302 actually not specific to COMMAND.COM, but to the DJGPP implementation
2303 of `system'. In particular:
2305 The shell wildcard characters are in DOS_CHARS because they will
2306 not be expanded if we call the child via `spawnXX'.
2308 The `;' is in DOS_CHARS, because our `system' knows how to run
2309 multiple commands on a single line.
2311 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2312 won't have to tell one from another and have one more set of
2313 commands and special characters. */
2314 static char sh_chars_dos[] = "*?[];|<>%^&()";
2315 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2316 "copy", "ctty", "date", "del", "dir", "echo",
2317 "erase", "exit", "for", "goto", "if", "md",
2318 "mkdir", "path", "pause", "prompt", "rd",
2319 "rmdir", "rem", "ren", "rename", "set",
2320 "shift", "time", "type", "ver", "verify",
2321 "vol", ":", 0 };
2323 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2324 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2325 "logout", "set", "umask", "wait", "while",
2326 "for", "case", "if", ":", ".", "break",
2327 "continue", "export", "read", "readonly",
2328 "shift", "times", "trap", "switch", "unset",
2329 "ulimit", 0 };
2331 char *sh_chars;
2332 char **sh_cmds;
2333 #elif defined (__EMX__)
2334 static char sh_chars_dos[] = "*?[];|<>%^&()";
2335 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2336 "copy", "ctty", "date", "del", "dir", "echo",
2337 "erase", "exit", "for", "goto", "if", "md",
2338 "mkdir", "path", "pause", "prompt", "rd",
2339 "rmdir", "rem", "ren", "rename", "set",
2340 "shift", "time", "type", "ver", "verify",
2341 "vol", ":", 0 };
2343 static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
2344 static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2345 "date", "del", "detach", "dir", "echo",
2346 "endlocal", "erase", "exit", "for", "goto", "if",
2347 "keys", "md", "mkdir", "move", "path", "pause",
2348 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2349 "set", "setlocal", "shift", "start", "time",
2350 "type", "ver", "verify", "vol", ":", 0 };
2352 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~'";
2353 static char *sh_cmds_sh[] = { "echo", "cd", "eval", "exec", "exit", "login",
2354 "logout", "set", "umask", "wait", "while",
2355 "for", "case", "if", ":", ".", "break",
2356 "continue", "export", "read", "readonly",
2357 "shift", "times", "trap", "switch", "unset",
2358 0 };
2359 char *sh_chars;
2360 char **sh_cmds;
2362 #elif defined (_AMIGA)
2363 static char sh_chars[] = "#;\"|<>()?*$`";
2364 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2365 "rename", "set", "setenv", "date", "makedir",
2366 "skip", "else", "endif", "path", "prompt",
2367 "unset", "unsetenv", "version",
2368 0 };
2369 #elif defined (WINDOWS32)
2370 static char sh_chars_dos[] = "\"|&<>";
2371 static char *sh_cmds_dos[] = { "assoc", "break", "call", "cd", "chcp",
2372 "chdir", "cls", "color", "copy", "ctty",
2373 "date", "del", "dir", "echo", "echo.",
2374 "endlocal", "erase", "exit", "for", "ftype",
2375 "goto", "if", "if", "md", "mkdir", "path",
2376 "pause", "prompt", "rd", "rem", "ren",
2377 "rename", "rmdir", "set", "setlocal",
2378 "shift", "time", "title", "type", "ver",
2379 "verify", "vol", ":", 0 };
2380 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2381 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2382 "logout", "set", "umask", "wait", "while", "for",
2383 "case", "if", ":", ".", "break", "continue",
2384 "export", "read", "readonly", "shift", "times",
2385 "trap", "switch", "test",
2386 #ifdef BATCH_MODE_ONLY_SHELL
2387 "echo",
2388 #endif
2389 0 };
2390 char* sh_chars;
2391 char** sh_cmds;
2392 #elif defined(__riscos__)
2393 static char sh_chars[] = "";
2394 static char *sh_cmds[] = { 0 };
2395 #else /* must be UNIX-ish */
2396 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~!";
2397 static char *sh_cmds[] = { ".", ":", "break", "case", "cd", "continue",
2398 "eval", "exec", "exit", "export", "for", "if",
2399 "login", "logout", "read", "readonly", "set",
2400 "shift", "switch", "test", "times", "trap",
2401 "ulimit", "umask", "unset", "wait", "while", 0 };
2402 # ifdef HAVE_DOS_PATHS
2403 /* This is required if the MSYS/Cygwin ports (which do not define
2404 WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
2405 sh_chars_sh[] directly (see below). */
2406 static char *sh_chars_sh = sh_chars;
2407 # endif /* HAVE_DOS_PATHS */
2408 #endif
2409 int i;
2410 char *p;
2411 char *ap;
2412 char *end;
2413 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2414 char **new_argv = 0;
2415 char *argstr = 0;
2416 #ifdef WINDOWS32
2417 int slow_flag = 0;
2419 if (!unixy_shell) {
2420 sh_cmds = sh_cmds_dos;
2421 sh_chars = sh_chars_dos;
2422 } else {
2423 sh_cmds = sh_cmds_sh;
2424 sh_chars = sh_chars_sh;
2426 #endif /* WINDOWS32 */
2428 if (restp != NULL)
2429 *restp = NULL;
2431 /* Make sure not to bother processing an empty line. */
2432 while (isblank ((unsigned char)*line))
2433 ++line;
2434 if (*line == '\0')
2435 return 0;
2437 /* See if it is safe to parse commands internally. */
2438 if (shell == 0)
2439 shell = default_shell;
2440 #ifdef WINDOWS32
2441 else if (strcmp (shell, default_shell))
2443 char *s1 = _fullpath (NULL, shell, 0);
2444 char *s2 = _fullpath (NULL, default_shell, 0);
2446 slow_flag = strcmp ((s1 ? s1 : ""), (s2 ? s2 : ""));
2448 if (s1)
2449 free (s1);
2450 if (s2)
2451 free (s2);
2453 if (slow_flag)
2454 goto slow;
2455 #else /* not WINDOWS32 */
2456 #if defined (__MSDOS__) || defined (__EMX__)
2457 else if (strcasecmp (shell, default_shell))
2459 extern int _is_unixy_shell (const char *_path);
2461 DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
2462 default_shell, shell));
2463 unixy_shell = _is_unixy_shell (shell);
2464 /* we must allocate a copy of shell: construct_command_argv() will free
2465 * shell after this function returns. */
2466 default_shell = xstrdup (shell);
2468 if (unixy_shell)
2470 sh_chars = sh_chars_sh;
2471 sh_cmds = sh_cmds_sh;
2473 else
2475 sh_chars = sh_chars_dos;
2476 sh_cmds = sh_cmds_dos;
2477 # ifdef __EMX__
2478 if (_osmode == OS2_MODE)
2480 sh_chars = sh_chars_os2;
2481 sh_cmds = sh_cmds_os2;
2483 # endif
2485 #else /* !__MSDOS__ */
2486 else if (strcmp (shell, default_shell))
2487 goto slow;
2488 #endif /* !__MSDOS__ && !__EMX__ */
2489 #endif /* not WINDOWS32 */
2491 if (ifs != 0)
2492 for (ap = ifs; *ap != '\0'; ++ap)
2493 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2494 goto slow;
2496 if (shellflags != 0)
2497 if (shellflags[0] != '-'
2498 || ((shellflags[1] != 'c' || shellflags[2] != '\0')
2499 && (shellflags[1] != 'e' || shellflags[2] != 'c' || shellflags[3] != '\0')))
2500 goto slow;
2502 i = strlen (line) + 1;
2504 /* More than 1 arg per character is impossible. */
2505 new_argv = xmalloc (i * sizeof (char *));
2507 /* All the args can fit in a buffer as big as LINE is. */
2508 ap = new_argv[0] = argstr = xmalloc (i);
2509 end = ap + i;
2511 /* I is how many complete arguments have been found. */
2512 i = 0;
2513 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2514 for (p = line; *p != '\0'; ++p)
2516 assert (ap <= end);
2518 if (instring)
2520 /* Inside a string, just copy any char except a closing quote
2521 or a backslash-newline combination. */
2522 if (*p == instring)
2524 instring = 0;
2525 if (ap == new_argv[0] || *(ap-1) == '\0')
2526 last_argument_was_empty = 1;
2528 else if (*p == '\\' && p[1] == '\n')
2530 /* Backslash-newline is handled differently depending on what
2531 kind of string we're in: inside single-quoted strings you
2532 keep them; in double-quoted strings they disappear.
2533 For DOS/Windows/OS2, if we don't have a POSIX shell,
2534 we keep the pre-POSIX behavior of removing the
2535 backslash-newline. */
2536 if (instring == '"'
2537 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2538 || !unixy_shell
2539 #endif
2541 ++p;
2542 else
2544 *(ap++) = *(p++);
2545 *(ap++) = *p;
2548 else if (*p == '\n' && restp != NULL)
2550 /* End of the command line. */
2551 *restp = p;
2552 goto end_of_line;
2554 /* Backslash, $, and ` are special inside double quotes.
2555 If we see any of those, punt.
2556 But on MSDOS, if we use COMMAND.COM, double and single
2557 quotes have the same effect. */
2558 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2559 goto slow;
2560 else
2561 *ap++ = *p;
2563 else if (strchr (sh_chars, *p) != 0)
2564 /* Not inside a string, but it's a special char. */
2565 goto slow;
2566 else if (one_shell && *p == '\n')
2567 /* In .ONESHELL mode \n is a separator like ; or && */
2568 goto slow;
2569 #ifdef __MSDOS__
2570 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2571 /* `...' is a wildcard in DJGPP. */
2572 goto slow;
2573 #endif
2574 else
2575 /* Not a special char. */
2576 switch (*p)
2578 case '=':
2579 /* Equals is a special character in leading words before the
2580 first word with no equals sign in it. This is not the case
2581 with sh -k, but we never get here when using nonstandard
2582 shell flags. */
2583 if (! seen_nonequals && unixy_shell)
2584 goto slow;
2585 word_has_equals = 1;
2586 *ap++ = '=';
2587 break;
2589 case '\\':
2590 /* Backslash-newline has special case handling, ref POSIX.
2591 We're in the fastpath, so emulate what the shell would do. */
2592 if (p[1] == '\n')
2594 /* Throw out the backslash and newline. */
2595 ++p;
2597 /* If there's nothing in this argument yet, skip any
2598 whitespace before the start of the next word. */
2599 if (ap == new_argv[i])
2600 p = next_token (p + 1) - 1;
2602 else if (p[1] != '\0')
2604 #ifdef HAVE_DOS_PATHS
2605 /* Only remove backslashes before characters special to Unixy
2606 shells. All other backslashes are copied verbatim, since
2607 they are probably DOS-style directory separators. This
2608 still leaves a small window for problems, but at least it
2609 should work for the vast majority of naive users. */
2611 #ifdef __MSDOS__
2612 /* A dot is only special as part of the "..."
2613 wildcard. */
2614 if (strneq (p + 1, ".\\.\\.", 5))
2616 *ap++ = '.';
2617 *ap++ = '.';
2618 p += 4;
2620 else
2621 #endif
2622 if (p[1] != '\\' && p[1] != '\''
2623 && !isspace ((unsigned char)p[1])
2624 && strchr (sh_chars_sh, p[1]) == 0)
2625 /* back up one notch, to copy the backslash */
2626 --p;
2627 #endif /* HAVE_DOS_PATHS */
2629 /* Copy and skip the following char. */
2630 *ap++ = *++p;
2632 break;
2634 case '\'':
2635 case '"':
2636 instring = *p;
2637 break;
2639 case '\n':
2640 if (restp != NULL)
2642 /* End of the command line. */
2643 *restp = p;
2644 goto end_of_line;
2646 else
2647 /* Newlines are not special. */
2648 *ap++ = '\n';
2649 break;
2651 case ' ':
2652 case '\t':
2653 /* We have the end of an argument.
2654 Terminate the text of the argument. */
2655 *ap++ = '\0';
2656 new_argv[++i] = ap;
2657 last_argument_was_empty = 0;
2659 /* Update SEEN_NONEQUALS, which tells us if every word
2660 heretofore has contained an `='. */
2661 seen_nonequals |= ! word_has_equals;
2662 if (word_has_equals && ! seen_nonequals)
2663 /* An `=' in a word before the first
2664 word without one is magical. */
2665 goto slow;
2666 word_has_equals = 0; /* Prepare for the next word. */
2668 /* If this argument is the command name,
2669 see if it is a built-in shell command.
2670 If so, have the shell handle it. */
2671 if (i == 1)
2673 register int j;
2674 for (j = 0; sh_cmds[j] != 0; ++j)
2676 if (streq (sh_cmds[j], new_argv[0]))
2677 goto slow;
2678 # ifdef __EMX__
2679 /* Non-Unix shells are case insensitive. */
2680 if (!unixy_shell
2681 && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
2682 goto slow;
2683 # endif
2687 /* Ignore multiple whitespace chars. */
2688 p = next_token (p) - 1;
2689 break;
2691 default:
2692 *ap++ = *p;
2693 break;
2696 end_of_line:
2698 if (instring)
2699 /* Let the shell deal with an unterminated quote. */
2700 goto slow;
2702 /* Terminate the last argument and the argument list. */
2704 *ap = '\0';
2705 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2706 ++i;
2707 new_argv[i] = 0;
2709 if (i == 1)
2711 register int j;
2712 for (j = 0; sh_cmds[j] != 0; ++j)
2713 if (streq (sh_cmds[j], new_argv[0]))
2714 goto slow;
2717 if (new_argv[0] == 0)
2719 /* Line was empty. */
2720 free (argstr);
2721 free (new_argv);
2722 return 0;
2725 return new_argv;
2727 slow:;
2728 /* We must use the shell. */
2730 if (new_argv != 0)
2732 /* Free the old argument list we were working on. */
2733 free (argstr);
2734 free (new_argv);
2737 #ifdef __MSDOS__
2738 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2739 #endif
2741 #ifdef _AMIGA
2743 char *ptr;
2744 char *buffer;
2745 char *dptr;
2747 buffer = xmalloc (strlen (line)+1);
2749 ptr = line;
2750 for (dptr=buffer; *ptr; )
2752 if (*ptr == '\\' && ptr[1] == '\n')
2753 ptr += 2;
2754 else if (*ptr == '@') /* Kludge: multiline commands */
2756 ptr += 2;
2757 *dptr++ = '\n';
2759 else
2760 *dptr++ = *ptr++;
2762 *dptr = 0;
2764 new_argv = xmalloc (2 * sizeof (char *));
2765 new_argv[0] = buffer;
2766 new_argv[1] = 0;
2768 #else /* Not Amiga */
2769 #ifdef WINDOWS32
2771 * Not eating this whitespace caused things like
2773 * sh -c "\n"
2775 * which gave the shell fits. I think we have to eat
2776 * whitespace here, but this code should be considered
2777 * suspicious if things start failing....
2780 /* Make sure not to bother processing an empty line. */
2781 while (isspace ((unsigned char)*line))
2782 ++line;
2783 if (*line == '\0')
2784 return 0;
2785 #endif /* WINDOWS32 */
2788 /* SHELL may be a multi-word command. Construct a command line
2789 "$(SHELL) $(.SHELLFLAGS) LINE", with all special chars in LINE escaped.
2790 Then recurse, expanding this command line to get the final
2791 argument list. */
2793 unsigned int shell_len = strlen (shell);
2794 unsigned int line_len = strlen (line);
2795 unsigned int sflags_len = strlen (shellflags);
2796 char *command_ptr = NULL; /* used for batch_mode_shell mode */
2797 char *new_line;
2799 # ifdef __EMX__ /* is this necessary? */
2800 if (!unixy_shell)
2801 shellflags[0] = '/'; /* "/c" */
2802 # endif
2804 /* In .ONESHELL mode we are allowed to throw the entire current
2805 recipe string at a single shell and trust that the user
2806 has configured the shell and shell flags, and formatted
2807 the string, appropriately. */
2808 if (one_shell)
2810 /* If the shell is Bourne compatible, we must remove and ignore
2811 interior special chars [@+-] because they're meaningless to
2812 the shell itself. If, however, we're in .ONESHELL mode and
2813 have changed SHELL to something non-standard, we should
2814 leave those alone because they could be part of the
2815 script. In this case we must also leave in place
2816 any leading [@+-] for the same reason. */
2818 /* Remove and ignore interior prefix chars [@+-] because they're
2819 meaningless given a single shell. */
2820 #if defined __MSDOS__ || defined (__EMX__)
2821 if (unixy_shell) /* the test is complicated and we already did it */
2822 #else
2823 if (is_bourne_compatible_shell(shell))
2824 #endif
2826 const char *f = line;
2827 char *t = line;
2829 /* Copy the recipe, removing and ignoring interior prefix chars
2830 [@+-]: they're meaningless in .ONESHELL mode. */
2831 while (f[0] != '\0')
2833 int esc = 0;
2835 /* This is the start of a new recipe line.
2836 Skip whitespace and prefix characters. */
2837 while (isblank (*f) || *f == '-' || *f == '@' || *f == '+')
2838 ++f;
2840 /* Copy until we get to the next logical recipe line. */
2841 while (*f != '\0')
2843 *(t++) = *(f++);
2844 if (f[-1] == '\\')
2845 esc = !esc;
2846 else
2848 /* On unescaped newline, we're done with this line. */
2849 if (f[-1] == '\n' && ! esc)
2850 break;
2852 /* Something else: reset the escape sequence. */
2853 esc = 0;
2857 *t = '\0';
2860 new_argv = xmalloc (4 * sizeof (char *));
2861 new_argv[0] = xstrdup(shell);
2862 new_argv[1] = xstrdup(shellflags);
2863 new_argv[2] = line;
2864 new_argv[3] = NULL;
2865 return new_argv;
2868 new_line = alloca (shell_len + 1 + sflags_len + 1
2869 + (line_len*2) + 1);
2870 ap = new_line;
2871 memcpy (ap, shell, shell_len);
2872 ap += shell_len;
2873 *(ap++) = ' ';
2874 memcpy (ap, shellflags, sflags_len);
2875 ap += sflags_len;
2876 *(ap++) = ' ';
2877 command_ptr = ap;
2878 for (p = line; *p != '\0'; ++p)
2880 if (restp != NULL && *p == '\n')
2882 *restp = p;
2883 break;
2885 else if (*p == '\\' && p[1] == '\n')
2887 /* POSIX says we keep the backslash-newline. If we don't have a
2888 POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
2889 and remove the backslash/newline. */
2890 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2891 # define PRESERVE_BSNL unixy_shell
2892 #else
2893 # define PRESERVE_BSNL 1
2894 #endif
2895 if (PRESERVE_BSNL)
2897 *(ap++) = '\\';
2898 /* Only non-batch execution needs another backslash,
2899 because it will be passed through a recursive
2900 invocation of this function. */
2901 if (!batch_mode_shell)
2902 *(ap++) = '\\';
2903 *(ap++) = '\n';
2905 ++p;
2906 continue;
2909 /* DOS shells don't know about backslash-escaping. */
2910 if (unixy_shell && !batch_mode_shell &&
2911 (*p == '\\' || *p == '\'' || *p == '"'
2912 || isspace ((unsigned char)*p)
2913 || strchr (sh_chars, *p) != 0))
2914 *ap++ = '\\';
2915 #ifdef __MSDOS__
2916 else if (unixy_shell && strneq (p, "...", 3))
2918 /* The case of `...' wildcard again. */
2919 strcpy (ap, "\\.\\.\\");
2920 ap += 5;
2921 p += 2;
2923 #endif
2924 *ap++ = *p;
2926 if (ap == new_line + shell_len + sflags_len + 2)
2927 /* Line was empty. */
2928 return 0;
2929 *ap = '\0';
2931 #ifdef WINDOWS32
2932 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2933 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2934 cases, run commands via a script file. */
2935 if (just_print_flag && !(flags & COMMANDS_RECURSE)) {
2936 /* Need to allocate new_argv, although it's unused, because
2937 start_job_command will want to free it and its 0'th element. */
2938 new_argv = xmalloc(2 * sizeof (char *));
2939 new_argv[0] = xstrdup ("");
2940 new_argv[1] = NULL;
2941 } else if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2942 int temp_fd;
2943 FILE* batch = NULL;
2944 int id = GetCurrentProcessId();
2945 PATH_VAR(fbuf);
2947 /* create a file name */
2948 sprintf(fbuf, "make%d", id);
2949 *batch_filename_ptr = create_batch_file (fbuf, unixy_shell, &temp_fd);
2951 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
2952 *batch_filename_ptr));
2954 /* Create a FILE object for the batch file, and write to it the
2955 commands to be executed. Put the batch file in TEXT mode. */
2956 _setmode (temp_fd, _O_TEXT);
2957 batch = _fdopen (temp_fd, "wt");
2958 if (!unixy_shell)
2959 fputs ("@echo off\n", batch);
2960 fputs (command_ptr, batch);
2961 fputc ('\n', batch);
2962 fclose (batch);
2963 DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
2964 !unixy_shell ? "\n\t@echo off" : "", command_ptr));
2966 /* create argv */
2967 new_argv = xmalloc(3 * sizeof (char *));
2968 if (unixy_shell) {
2969 new_argv[0] = xstrdup (shell);
2970 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2971 } else {
2972 new_argv[0] = xstrdup (*batch_filename_ptr);
2973 new_argv[1] = NULL;
2975 new_argv[2] = NULL;
2976 } else
2977 #endif /* WINDOWS32 */
2979 if (unixy_shell)
2980 new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0, flags, 0);
2982 #ifdef __EMX__
2983 else if (!unixy_shell)
2985 /* new_line is local, must not be freed therefore
2986 We use line here instead of new_line because we run the shell
2987 manually. */
2988 size_t line_len = strlen (line);
2989 char *p = new_line;
2990 char *q = new_line;
2991 memcpy (new_line, line, line_len + 1);
2992 /* Replace all backslash-newline combination and also following tabs.
2993 Important: stop at the first '\n' because that's what the loop above
2994 did. The next line starting at restp[0] will be executed during the
2995 next call of this function. */
2996 while (*q != '\0' && *q != '\n')
2998 if (q[0] == '\\' && q[1] == '\n')
2999 q += 2; /* remove '\\' and '\n' */
3000 else
3001 *p++ = *q++;
3003 *p = '\0';
3005 # ifndef NO_CMD_DEFAULT
3006 if (strnicmp (new_line, "echo", 4) == 0
3007 && (new_line[4] == ' ' || new_line[4] == '\t'))
3009 /* the builtin echo command: handle it separately */
3010 size_t echo_len = line_len - 5;
3011 char *echo_line = new_line + 5;
3013 /* special case: echo 'x="y"'
3014 cmd works this way: a string is printed as is, i.e., no quotes
3015 are removed. But autoconf uses a command like echo 'x="y"' to
3016 determine whether make works. autoconf expects the output x="y"
3017 so we will do exactly that.
3018 Note: if we do not allow cmd to be the default shell
3019 we do not need this kind of voodoo */
3020 if (echo_line[0] == '\''
3021 && echo_line[echo_len - 1] == '\''
3022 && strncmp (echo_line + 1, "ac_maketemp=",
3023 strlen ("ac_maketemp=")) == 0)
3025 /* remove the enclosing quotes */
3026 memmove (echo_line, echo_line + 1, echo_len - 2);
3027 echo_line[echo_len - 2] = '\0';
3030 # endif
3033 /* Let the shell decide what to do. Put the command line into the
3034 2nd command line argument and hope for the best ;-) */
3035 size_t sh_len = strlen (shell);
3037 /* exactly 3 arguments + NULL */
3038 new_argv = xmalloc (4 * sizeof (char *));
3039 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3040 the trailing '\0' */
3041 new_argv[0] = xmalloc (sh_len + line_len + 5);
3042 memcpy (new_argv[0], shell, sh_len + 1);
3043 new_argv[1] = new_argv[0] + sh_len + 1;
3044 memcpy (new_argv[1], "/c", 3);
3045 new_argv[2] = new_argv[1] + 3;
3046 memcpy (new_argv[2], new_line, line_len + 1);
3047 new_argv[3] = NULL;
3050 #elif defined(__MSDOS__)
3051 else
3053 /* With MSDOS shells, we must construct the command line here
3054 instead of recursively calling ourselves, because we
3055 cannot backslash-escape the special characters (see above). */
3056 new_argv = xmalloc (sizeof (char *));
3057 line_len = strlen (new_line) - shell_len - sflags_len - 2;
3058 new_argv[0] = xmalloc (line_len + 1);
3059 strncpy (new_argv[0],
3060 new_line + shell_len + sflags_len + 2, line_len);
3061 new_argv[0][line_len] = '\0';
3063 #else
3064 else
3065 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3066 __FILE__, __LINE__);
3067 #endif
3069 #endif /* ! AMIGA */
3071 return new_argv;
3073 #endif /* !VMS */
3075 /* Figure out the argument list necessary to run LINE as a command. Try to
3076 avoid using a shell. This routine handles only ' quoting, and " quoting
3077 when no backslash, $ or ` characters are seen in the quotes. Starting
3078 quotes may be escaped with a backslash. If any of the characters in
3079 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3080 is the first word of a line, the shell is used.
3082 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3083 If *RESTP is NULL, newlines will be ignored.
3085 FILE is the target whose commands these are. It is used for
3086 variable expansion for $(SHELL) and $(IFS). */
3088 char **
3089 construct_command_argv (char *line, char **restp, struct file *file,
3090 int cmd_flags, char **batch_filename_ptr)
3092 char *shell, *ifs, *shellflags;
3093 char **argv;
3095 #ifdef VMS
3096 char *cptr;
3097 int argc;
3099 argc = 0;
3100 cptr = line;
3101 for (;;)
3103 while ((*cptr != 0)
3104 && (isspace ((unsigned char)*cptr)))
3105 cptr++;
3106 if (*cptr == 0)
3107 break;
3108 while ((*cptr != 0)
3109 && (!isspace((unsigned char)*cptr)))
3110 cptr++;
3111 argc++;
3114 argv = xmalloc (argc * sizeof (char *));
3115 if (argv == 0)
3116 abort ();
3118 cptr = line;
3119 argc = 0;
3120 for (;;)
3122 while ((*cptr != 0)
3123 && (isspace ((unsigned char)*cptr)))
3124 cptr++;
3125 if (*cptr == 0)
3126 break;
3127 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3128 argv[argc++] = cptr;
3129 while ((*cptr != 0)
3130 && (!isspace((unsigned char)*cptr)))
3131 cptr++;
3132 if (*cptr != 0)
3133 *cptr++ = 0;
3135 #else
3137 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3138 int save = warn_undefined_variables_flag;
3139 warn_undefined_variables_flag = 0;
3141 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3142 #ifdef WINDOWS32
3144 * Convert to forward slashes so that construct_command_argv_internal()
3145 * is not confused.
3147 if (shell) {
3148 char *p = w32ify (shell, 0);
3149 strcpy (shell, p);
3151 #endif
3152 #ifdef __EMX__
3154 static const char *unixroot = NULL;
3155 static const char *last_shell = "";
3156 static int init = 0;
3157 if (init == 0)
3159 unixroot = getenv ("UNIXROOT");
3160 /* unixroot must be NULL or not empty */
3161 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3162 init = 1;
3165 /* if we have an unixroot drive and if shell is not default_shell
3166 (which means it's either cmd.exe or the test has already been
3167 performed) and if shell is an absolute path without drive letter,
3168 try whether it exists e.g.: if "/bin/sh" does not exist use
3169 "$UNIXROOT/bin/sh" instead. */
3170 if (unixroot && shell && strcmp (shell, last_shell) != 0
3171 && (shell[0] == '/' || shell[0] == '\\'))
3173 /* trying a new shell, check whether it exists */
3174 size_t size = strlen (shell);
3175 char *buf = xmalloc (size + 7);
3176 memcpy (buf, shell, size);
3177 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3178 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3180 /* try the same for the unixroot drive */
3181 memmove (buf + 2, buf, size + 5);
3182 buf[0] = unixroot[0];
3183 buf[1] = unixroot[1];
3184 if (access (buf, F_OK) == 0)
3185 /* we have found a shell! */
3186 /* free(shell); */
3187 shell = buf;
3188 else
3189 free (buf);
3191 else
3192 free (buf);
3195 #endif /* __EMX__ */
3197 shellflags = allocated_variable_expand_for_file ("$(.SHELLFLAGS)", file);
3198 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3200 warn_undefined_variables_flag = save;
3203 argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
3204 cmd_flags, batch_filename_ptr);
3206 free (shell);
3207 free (shellflags);
3208 free (ifs);
3209 #endif /* !VMS */
3210 return argv;
3213 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3215 dup2 (int old, int new)
3217 int fd;
3219 (void) close (new);
3220 fd = dup (old);
3221 if (fd != new)
3223 (void) close (fd);
3224 errno = EMFILE;
3225 return -1;
3228 return fd;
3230 #endif /* !HAVE_DUP2 && !_AMIGA */
3232 /* On VMS systems, include special VMS functions. */
3234 #ifdef VMS
3235 #include "vmsjobs.c"
3236 #endif