1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
4 2010 Free Software Foundation, Inc.
5 This file is part of GNU Make.
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
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/>. */
32 #if defined (HAVE_LINUX_BINFMTS_H) && defined (HAVE_SYS_USER_H)
34 #include <linux/binfmts.h>
36 #define PAGE_SIZE getpagesize()
40 /* Default shell to use. */
44 char *default_shell = "sh.exe";
45 int no_default_sh_exe = 1;
46 int batch_mode_shell = 1;
49 #elif defined (_AMIGA)
51 char default_shell[] = "";
52 extern int MyExecute (char **);
53 int batch_mode_shell = 0;
55 #elif defined (__MSDOS__)
57 /* The default shell is a pointer so we can change it if Makefile
58 says so. It is without an explicit path so we get a chance
59 to search the $PATH for it (since MSDOS doesn't have standard
60 directories we could trust). */
61 char *default_shell = "command.com";
62 int batch_mode_shell = 0;
64 #elif defined (__EMX__)
66 char *default_shell = "/bin/sh";
67 int batch_mode_shell = 0;
72 char default_shell[] = "";
73 int batch_mode_shell = 0;
75 #elif defined (__riscos__)
77 char default_shell[] = "";
78 int batch_mode_shell = 0;
82 char default_shell[] = "/bin/sh";
83 int batch_mode_shell = 0;
89 static int execute_by_shell;
90 static int dos_pid = 123;
92 int dos_command_running;
93 #endif /* __MSDOS__ */
96 # include <proto/dos.h>
97 static int amiga_pid = 123;
98 static int amiga_status;
99 static char amiga_bname[32];
100 static int amiga_batch_file;
105 # include <processes.h>
107 # include <starlet.h>
108 # include <lib$routines.h>
109 static void vmsWaitForChildren (int *);
113 # include <windows.h>
115 # include <process.h>
116 # include "sub_proc.h"
118 # include "pathstuff.h"
119 #endif /* WINDOWS32 */
122 # include <process.h>
125 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
126 # include <sys/wait.h>
130 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
131 #else /* Don't have waitpid. */
136 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
137 # endif /* Have wait3. */
138 #endif /* Have waitpid. */
140 #if !defined (wait) && !defined (POSIX)
144 #ifndef HAVE_UNION_WAIT
149 # define WTERMSIG(x) ((x) & 0x7f)
152 # define WCOREDUMP(x) ((x) & 0x80)
155 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
158 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
161 # define WIFEXITED(x) (WTERMSIG (x) == 0)
164 #else /* Have `union wait'. */
166 # define WAIT_T union wait
168 # define WTERMSIG(x) ((x).w_termsig)
171 # define WCOREDUMP(x) ((x).w_coredump)
174 # define WEXITSTATUS(x) ((x).w_retcode)
177 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
180 # define WIFEXITED(x) (WTERMSIG(x) == 0)
183 #endif /* Don't have `union wait'. */
185 #if !defined(HAVE_UNISTD_H) && !defined(WINDOWS32)
197 /* Different systems have different requirements for pid_t.
198 Plus we have to support gettext string translation... Argh. */
202 static char pidstring[100];
203 #if defined(WINDOWS32) && (__GNUC__ > 3 || _MSC_VER > 1300)
204 /* %Id is only needed for 64-builds, which were not supported by
205 older versions of Windows compilers. */
206 sprintf (pidstring, "%Id", pid);
208 sprintf (pidstring, "%lu", (unsigned long) pid);
213 int getloadavg (double loadavg[], int nelem);
214 int start_remote_job (char **argv, char **envp, int stdin_fd, int *is_remote,
215 int *id_ptr, int *used_stdin);
216 int start_remote_job_p (int);
217 int remote_status (int *exit_code_ptr, int *signal_ptr, int *coredump_ptr,
220 RETSIGTYPE child_handler (int);
221 static void free_child (struct child *);
222 static void start_job_command (struct child *child);
223 static int load_too_high (void);
224 static int job_next_command (struct child *);
225 static int start_waiting_job (struct child *);
227 /* Chain of all live (or recently deceased) children. */
229 struct child *children = 0;
231 /* Number of children currently running. */
233 unsigned int job_slots_used = 0;
235 /* Nonzero if the `good' standard input is in use. */
237 static int good_stdin_used = 0;
239 /* Chain of children waiting to run until the load average goes down. */
241 static struct child *waiting_jobs = 0;
243 /* Non-zero if we use a *real* shell (always so on Unix). */
247 /* Number of jobs started in the current second. */
249 unsigned long job_counter = 0;
251 /* Number of jobserver tokens this instance is currently using. */
253 unsigned int jobserver_tokens = 0;
257 * The macro which references this function is defined in make.h.
260 w32_kill(pid_t pid, int sig)
262 return ((process_kill((HANDLE)pid, sig) == TRUE) ? 0 : -1);
265 /* This function creates a temporary file name with an extension specified
267 * Return an xmalloc'ed string of a newly created temp file and its
268 * file descriptor, or die. */
270 create_batch_file (char const *base, int unixy, int *fd)
272 const char *const ext = unixy ? "sh" : "bat";
273 const char *error_string = NULL;
274 char temp_path[MAXPATHLEN]; /* need to know its length */
275 unsigned path_size = GetTempPath(sizeof temp_path, temp_path);
278 const unsigned sizemax = strlen (base) + strlen (ext) + 10;
282 path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
286 while (path_size > 0 &&
287 path_size + sizemax < sizeof temp_path &&
290 unsigned size = sprintf (temp_path + path_size,
292 temp_path[path_size - 1] == '\\' ? "" : "\\",
294 HANDLE h = CreateFile (temp_path, /* file name */
295 GENERIC_READ | GENERIC_WRITE, /* desired access */
296 0, /* no share mode */
297 NULL, /* default security attributes */
298 CREATE_NEW, /* creation disposition */
299 FILE_ATTRIBUTE_NORMAL | /* flags and attributes */
300 FILE_ATTRIBUTE_TEMPORARY, /* we'll delete it */
301 NULL); /* no template file */
303 if (h == INVALID_HANDLE_VALUE)
305 const DWORD er = GetLastError();
307 if (er == ERROR_FILE_EXISTS || er == ERROR_ALREADY_EXISTS)
310 /* the temporary path is not guaranteed to exist */
311 else if (path_is_dot == 0)
313 path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
319 error_string = map_windows32_error_to_string (er);
325 const unsigned final_size = path_size + size + 1;
326 char *const path = xmalloc (final_size);
327 memcpy (path, temp_path, final_size);
328 *fd = _open_osfhandle ((intptr_t)h, 0);
333 for (p = path; (ch = *p) != 0; ++p)
337 return path; /* good return */
342 if (error_string == NULL)
343 error_string = _("Cannot create a temporary file\n");
344 fatal (NILF, error_string);
349 #endif /* WINDOWS32 */
352 /* returns whether path is assumed to be a unix like shell. */
354 _is_unixy_shell (const char *path)
356 /* list of non unix shells */
357 const char *known_os2shells[] = {
369 /* find the rightmost '/' or '\\' */
370 const char *name = strrchr (path, '/');
371 const char *p = strrchr (path, '\\');
374 if (name && p) /* take the max */
375 name = (name > p) ? name : p;
376 else if (p) /* name must be 0 */
378 else if (!name) /* name and p must be 0 */
381 if (*name == '/' || *name == '\\') name++;
384 while (known_os2shells[i] != NULL) {
385 if (strcasecmp (name, known_os2shells[i]) == 0)
386 return 0; /* not a unix shell */
390 /* in doubt assume a unix like shell */
395 /* determines whether path looks to be a Bourne-like shell. */
397 is_bourne_compatible_shell (const char *path)
399 /* list of known unix (Bourne-like) shells */
400 const char *unix_shells[] = {
412 /* find the rightmost '/' or '\\' */
413 const char *name = strrchr (path, '/');
414 char *p = strrchr (path, '\\');
416 if (name && p) /* take the max */
417 name = (name > p) ? name : p;
418 else if (p) /* name must be 0 */
420 else if (!name) /* name and p must be 0 */
423 if (*name == '/' || *name == '\\') name++;
425 /* this should be able to deal with extensions on Windows-like systems */
426 for (i = 0; unix_shells[i] != NULL; i++) {
427 len = strlen(unix_shells[i]);
428 #if defined(WINDOWS32) || defined(__MSDOS__)
429 if ((strncasecmp (name, unix_shells[i], len) == 0) &&
430 (strlen(name) >= len && (name[len] == '\0' || name[len] == '.')))
432 if ((strncmp (name, unix_shells[i], len) == 0) &&
433 (strlen(name) >= len && name[len] == '\0'))
435 return 1; /* a known unix-style shell */
438 /* if not on the list, assume it's not a Bourne-like shell */
443 /* Write an error message describing the exit status given in
444 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
445 Append "(ignored)" if IGNORED is nonzero. */
448 child_error (const char *target_name,
449 int exit_code, int exit_sig, int coredump, int ignored)
451 if (ignored && silent_flag)
455 if (!(exit_code & 1))
457 (ignored ? _("*** [%s] Error 0x%x (ignored)")
458 : _("*** [%s] Error 0x%x")),
459 target_name, exit_code);
462 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
463 _("*** [%s] Error %d"),
464 target_name, exit_code);
466 error (NILF, "*** [%s] %s%s",
467 target_name, strsignal (exit_sig),
468 coredump ? _(" (core dumped)") : "");
473 /* Handle a dead child. This handler may or may not ever be installed.
475 If we're using the jobserver feature, we need it. First, installing it
476 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
477 read FD to ensure we don't enter another blocking read without reaping all
478 the dead children. In this case we don't need the dead_children count.
480 If we don't have either waitpid or wait3, then make is unreliable, but we
481 use the dead_children count to reap children as best we can. */
483 static unsigned int dead_children = 0;
486 child_handler (int sig UNUSED)
497 /* The signal handler must called only once! */
498 signal (SIGCHLD, SIG_DFL);
501 /* This causes problems if the SIGCHLD interrupts a printf().
502 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
506 extern int shell_function_pid, shell_function_completed;
508 /* Reap all dead children, storing the returned status and the new command
509 state (`cs_finished') in the `file' member of the `struct child' for the
510 dead child, and removing the child from the chain. In addition, if BLOCK
511 nonzero, we block in this function until we've reaped at least one
512 complete child, waiting for it to die if necessary. If ERR is nonzero,
513 print an error message first. */
516 reap_children (int block, int err)
520 /* Initially, assume we have some. */
525 # define REAP_MORE reap_more
527 # define REAP_MORE dead_children
532 We have at least one child outstanding OR a shell function in progress,
534 We're blocking for a complete child OR there are more children to reap
536 we'll keep reaping children. */
538 while ((children != 0 || shell_function_pid != 0)
539 && (block || REAP_MORE))
543 int exit_code, exit_sig, coredump;
544 register struct child *lastc, *c;
546 int any_remote, any_local;
551 static int printed = 0;
553 /* We might block for a while, so let the user know why.
554 Only print this message once no matter how many jobs are left. */
557 error (NILF, _("*** Waiting for unfinished jobs...."));
561 /* We have one less dead child to reap. As noted in
562 child_handler() above, this count is completely unimportant for
563 all modern, POSIX-y systems that support wait3() or waitpid().
564 The rest of this comment below applies only to early, broken
565 pre-POSIX systems. We keep the count only because... it's there...
567 The test and decrement are not atomic; if it is compiled into:
568 register = dead_children - 1;
569 dead_children = register;
570 a SIGCHLD could come between the two instructions.
571 child_handler increments dead_children.
572 The second instruction here would lose that increment. But the
573 only effect of dead_children being wrong is that we might wait
574 longer than necessary to reap a child, and lose some parallelism;
575 and we might print the "Waiting for unfinished jobs" message above
576 when not necessary. */
578 if (dead_children > 0)
582 any_local = shell_function_pid != 0;
583 for (c = children; c != 0; c = c->next)
585 any_remote |= c->remote;
586 any_local |= ! c->remote;
587 DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
588 c, c->file->name, pid2str (c->pid),
589 c->remote ? _(" (remote)") : ""));
595 /* First, check for remote children. */
597 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
602 /* We got a remote child. */
606 /* A remote status command failed miserably. Punt. */
608 pfatal_with_name ("remote_status");
612 /* No remote children. Check for local children. */
613 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
617 vmsWaitForChildren (&status);
622 pid = WAIT_NOHANG (&status);
625 EINTRLOOP(pid, wait (&status));
633 /* The wait*() failed miserably. Punt. */
634 pfatal_with_name ("wait");
638 /* We got a child exit; chop the status word up. */
639 exit_code = WEXITSTATUS (status);
640 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
641 coredump = WCOREDUMP (status);
643 /* If we have started jobs in this second, remove one. */
649 /* No local children are dead. */
652 if (!block || !any_remote)
655 /* Now try a blocking wait for a remote child. */
656 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
658 goto remote_status_lose;
660 /* No remote children either. Finally give up. */
663 /* We got a remote child. */
666 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
669 /* Life is very different on MSDOS. */
672 exit_code = WEXITSTATUS (status);
673 if (exit_code == 0xff)
675 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
677 #endif /* __MSDOS__ */
681 status = amiga_status;
682 exit_code = amiga_status;
695 /* Record the thread ID of the main process, so that we
696 could suspend it in the signal handler. */
699 hcTID = GetCurrentThread ();
700 hcPID = GetCurrentProcess ();
701 if (!DuplicateHandle (hcPID, hcTID, hcPID, &main_thread, 0,
702 FALSE, DUPLICATE_SAME_ACCESS))
704 DWORD e = GetLastError ();
706 "Determine main thread ID (Error %ld: %s)\n",
707 e, map_windows32_error_to_string(e));
710 DB (DB_VERBOSE, ("Main thread handle = %p\n", main_thread));
713 /* wait for anything to finish */
714 hPID = process_wait_for_any();
718 /* was an error found on this process? */
719 werr = process_last_err(hPID);
722 exit_code = process_exit_code(hPID);
725 fprintf(stderr, "make (e=%d): %s",
726 exit_code, map_windows32_error_to_string(exit_code));
729 exit_sig = process_signal(hPID);
731 /* cleanup process */
732 process_cleanup(hPID);
738 #endif /* WINDOWS32 */
741 /* Check if this is the child of the `shell' function. */
742 if (!remote && pid == shell_function_pid)
744 /* It is. Leave an indicator for the `shell' function. */
745 if (exit_sig == 0 && exit_code == 127)
746 shell_function_completed = -1;
748 shell_function_completed = 1;
752 child_failed = exit_sig != 0 || exit_code != 0;
754 /* Search for a child matching the deceased one. */
756 for (c = children; c != 0; lastc = c, c = c->next)
757 if (c->remote == remote && c->pid == pid)
761 /* An unknown child died.
762 Ignore it; it was inherited from our invoker. */
765 DB (DB_JOBS, (child_failed
766 ? _("Reaping losing child %p PID %s %s\n")
767 : _("Reaping winning child %p PID %s %s\n"),
768 c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
770 if (c->sh_batch_file) {
771 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
774 /* just try and remove, don't care if this fails */
775 remove (c->sh_batch_file);
777 /* all done with memory */
778 free (c->sh_batch_file);
779 c->sh_batch_file = NULL;
782 /* If this child had the good stdin, say it is now free. */
786 dontcare = c->dontcare;
788 if (child_failed && !c->noerror && !ignore_errors_flag)
790 /* The commands failed. Write an error message,
791 delete non-precious targets, and abort. */
792 static int delete_on_error = -1;
795 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
797 c->file->update_status = 2;
798 if (delete_on_error == -1)
800 struct file *f = lookup_file (".DELETE_ON_ERROR");
801 delete_on_error = f != 0 && f->is_target;
803 if (exit_sig != 0 || delete_on_error)
804 delete_child_targets (c);
810 /* The commands failed, but we don't care. */
811 child_error (c->file->name,
812 exit_code, exit_sig, coredump, 1);
816 /* If there are more commands to run, try to start them. */
817 if (job_next_command (c))
819 if (handling_fatal_signal)
821 /* Never start new commands while we are dying.
822 Since there are more commands that wanted to be run,
823 the target was not completely remade. So we treat
824 this as if a command had failed. */
825 c->file->update_status = 2;
829 /* Check again whether to start remotely.
830 Whether or not we want to changes over time.
831 Also, start_remote_job may need state set up
832 by start_remote_job_p. */
833 c->remote = start_remote_job_p (0);
834 start_job_command (c);
835 /* Fatal signals are left blocked in case we were
836 about to put that child on the chain. But it is
837 already there, so it is safe for a fatal signal to
838 arrive now; it will clean up this child's targets. */
840 if (c->file->command_state == cs_running)
841 /* We successfully started the new command.
842 Loop to reap more children. */
846 if (c->file->update_status != 0)
847 /* We failed to start the commands. */
848 delete_child_targets (c);
851 /* There are no more commands. We got through them all
852 without an unignored error. Now the target has been
853 successfully updated. */
854 c->file->update_status = 0;
857 /* When we get here, all the commands for C->file are finished
858 (or aborted) and C->file->update_status contains 0 or 2. But
859 C->file->command_state is still cs_running if all the commands
860 ran; notice_finish_file looks for cs_running to tell it that
861 it's interesting to check the file's modtime again now. */
863 if (! handling_fatal_signal)
864 /* Notice if the target of the commands has been changed.
865 This also propagates its values for command_state and
866 update_status to its also_make files. */
867 notice_finished_file (c->file);
869 DB (DB_JOBS, (_("Removing child %p PID %s%s from chain.\n"),
870 c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
872 /* Block fatal signals while frobnicating the list, so that
873 children and job_slots_used are always consistent. Otherwise
874 a fatal signal arriving after the child is off the chain and
875 before job_slots_used is decremented would believe a child was
876 live and call reap_children again. */
879 /* There is now another slot open. */
880 if (job_slots_used > 0)
883 /* Remove the child from the chain and free it. */
887 lastc->next = c->next;
893 /* If the job failed, and the -k flag was not given, die,
894 unless we are already in the process of dying. */
895 if (!err && child_failed && !dontcare && !keep_going_flag &&
896 /* fatal_error_signal will die with the right signal. */
897 !handling_fatal_signal)
900 /* Only block for one child. */
907 /* Free the storage allocated for CHILD. */
910 free_child (struct child *child)
912 if (!jobserver_tokens)
913 fatal (NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
914 child, child->file->name);
916 /* If we're using the jobserver and this child is not the only outstanding
917 job, put a token back into the pipe for it. */
919 if (job_fds[1] >= 0 && jobserver_tokens > 1)
924 /* Write a job token back to the pipe. */
926 EINTRLOOP (r, write (job_fds[1], &token, 1));
928 pfatal_with_name (_("write jobserver"));
930 DB (DB_JOBS, (_("Released token for child %p (%s).\n"),
931 child, child->file->name));
936 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
939 if (child->command_lines != 0)
941 register unsigned int i;
942 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
943 free (child->command_lines[i]);
944 free (child->command_lines);
947 if (child->environment != 0)
949 register char **ep = child->environment;
952 free (child->environment);
959 extern sigset_t fatal_signal_set;
966 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
968 # ifdef HAVE_SIGSETMASK
969 (void) sigblock (fatal_signal_mask);
979 sigemptyset (&empty);
980 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
984 #ifdef MAKE_JOBSERVER
986 job_noop (int sig UNUSED)
989 /* Set the child handler action flags to FLAGS. */
991 set_child_handler_action_flags (int set_handler, int set_alarm)
996 /* The child handler must be turned off here. */
997 signal (SIGCHLD, SIG_DFL);
1000 memset (&sa, '\0', sizeof sa);
1001 sa.sa_handler = child_handler;
1002 sa.sa_flags = set_handler ? 0 : SA_RESTART;
1004 sigaction (SIGCHLD, &sa, NULL);
1006 #if defined SIGCLD && SIGCLD != SIGCHLD
1007 sigaction (SIGCLD, &sa, NULL);
1012 /* If we're about to enter the read(), set an alarm to wake up in a
1013 second so we can check if the load has dropped and we can start more
1014 work. On the way out, turn off the alarm and set SIG_DFL. */
1015 alarm (set_handler ? 1 : 0);
1016 sa.sa_handler = set_handler ? job_noop : SIG_DFL;
1018 sigaction (SIGALRM, &sa, NULL);
1025 /* Start a job to run the commands specified in CHILD.
1026 CHILD is updated to reflect the commands and ID of the child process.
1028 NOTE: On return fatal signals are blocked! The caller is responsible
1029 for calling `unblock_sigs', once the new child is safely on the chain so
1030 it can be cleaned up in the event of a fatal signal. */
1033 start_job_command (struct child *child)
1035 #if !defined(_AMIGA) && !defined(WINDOWS32)
1036 static int bad_stdin = -1;
1039 /* Must be volatile to silence bogus GCC warning about longjmp/vfork. */
1047 /* If we have a completely empty commandset, stop now. */
1048 if (!child->command_ptr)
1051 /* Combine the flags parsed for the line itself with
1052 the flags specified globally for this target. */
1053 flags = (child->file->command_flags
1054 | child->file->cmds->lines_flags[child->command_line - 1]);
1056 p = child->command_ptr;
1057 child->noerror = ((flags & COMMANDS_NOERROR) != 0);
1062 flags |= COMMANDS_SILENT;
1064 flags |= COMMANDS_RECURSE;
1067 else if (!isblank ((unsigned char)*p))
1072 /* Update the file's command flags with any new ones we found. We only
1073 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
1074 now marking more commands recursive than should be in the case of
1075 multiline define/endef scripts where only one line is marked "+". In
1076 order to really fix this, we'll have to keep a lines_flags for every
1077 actual line, after expansion. */
1078 child->file->cmds->lines_flags[child->command_line - 1]
1079 |= flags & COMMANDS_RECURSE;
1081 /* Figure out an argument list from this command line. */
1088 argv = construct_command_argv (p, &end, child->file,
1089 child->file->cmds->lines_flags[child->command_line - 1],
1090 &child->sh_batch_file);
1093 child->command_ptr = NULL;
1097 child->command_ptr = end;
1101 /* If -q was given, say that updating `failed' if there was any text on the
1102 command line, or `succeeded' otherwise. The exit status of 1 tells the
1103 user that -q is saying `something to do'; the exit status for a random
1105 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
1111 child->file->update_status = 1;
1112 notice_finished_file (child->file);
1116 if (touch_flag && !(flags & COMMANDS_RECURSE))
1118 /* Go on to the next command. It might be the recursive one.
1119 We construct ARGV only to find the end of the command line. */
1134 execute_by_shell = 0; /* in case construct_command_argv sets it */
1136 /* This line has no commands. Go to the next. */
1137 if (job_next_command (child))
1138 start_job_command (child);
1141 /* No more commands. Make sure we're "running"; we might not be if
1142 (e.g.) all commands were skipped due to -n. */
1143 set_command_state (child->file, cs_running);
1144 child->file->update_status = 0;
1145 notice_finished_file (child->file);
1150 /* Print out the command. If silent, we call `message' with null so it
1151 can log the working directory before the command's own error messages
1154 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
1155 ? "%s" : (char *) 0, p);
1157 /* Tell update_goal_chain that a command has been started on behalf of
1158 this target. It is important that this happens here and not in
1159 reap_children (where we used to do it), because reap_children might be
1160 reaping children from a different target. We want this increment to
1161 guaranteedly indicate that a command was started for the dependency
1162 chain (i.e., update_file recursion chain) we are processing. */
1166 /* Optimize an empty command. People use this for timestamp rules,
1167 so avoid forking a useless shell. Do this after we increment
1168 commands_started so make still treats this special case as if it
1169 performed some action (makes a difference as to what messages are
1172 #if !defined(VMS) && !defined(_AMIGA)
1174 #if defined __MSDOS__ || defined (__EMX__)
1175 unixy_shell /* the test is complicated and we already did it */
1177 (argv[0] && is_bourne_compatible_shell(argv[0]))
1179 && (argv[1] && argv[1][0] == '-'
1181 ((argv[1][1] == 'c' && argv[1][2] == '\0')
1183 (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
1184 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1191 #endif /* !VMS && !_AMIGA */
1193 /* If -n was given, recurse to get the next line in the sequence. */
1195 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1204 /* Flush the output streams so they won't have things written twice. */
1210 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1212 /* Set up a bad standard input that reads from a broken pipe. */
1214 if (bad_stdin == -1)
1216 /* Make a file descriptor that is the read end of a broken pipe.
1217 This will be used for some children's standard inputs. */
1221 /* Close the write side. */
1222 (void) close (pd[1]);
1223 /* Save the read side. */
1226 /* Set the descriptor to close on exec, so it does not litter any
1227 child's descriptor table. When it is dup2'd onto descriptor 0,
1228 that descriptor will not close on exec. */
1229 CLOSE_ON_EXEC (bad_stdin);
1233 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1235 /* Decide whether to give this child the `good' standard input
1236 (one that points to the terminal or whatever), or the `bad' one
1237 that points to the read side of a broken pipe. */
1239 child->good_stdin = !good_stdin_used;
1240 if (child->good_stdin)
1241 good_stdin_used = 1;
1248 /* Set up the environment for the child. */
1249 if (child->environment == 0)
1250 child->environment = target_environment (child->file);
1253 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1256 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1259 int is_remote, id, used_stdin;
1260 if (start_remote_job (argv, child->environment,
1261 child->good_stdin ? 0 : bad_stdin,
1262 &is_remote, &id, &used_stdin))
1263 /* Don't give up; remote execution may fail for various reasons. If
1264 so, simply run the job locally. */
1268 if (child->good_stdin && !used_stdin)
1270 child->good_stdin = 0;
1271 good_stdin_used = 0;
1273 child->remote = is_remote;
1280 /* Fork the child process. */
1282 char **parent_environ;
1290 if (!child_execute_job (argv, child)) {
1292 perror_with_name ("vfork", "");
1298 parent_environ = environ;
1301 /* If we aren't running a recursive command and we have a jobserver
1302 pipe, close it before exec'ing. */
1303 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1305 CLOSE_ON_EXEC (job_fds[0]);
1306 CLOSE_ON_EXEC (job_fds[1]);
1309 CLOSE_ON_EXEC (job_rfd);
1311 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1312 child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1313 argv, child->environment);
1318 perror_with_name ("spawn", "");
1322 /* undo CLOSE_ON_EXEC() after the child process has been started */
1323 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1325 fcntl (job_fds[0], F_SETFD, 0);
1326 fcntl (job_fds[1], F_SETFD, 0);
1329 fcntl (job_rfd, F_SETFD, 0);
1331 #else /* !__EMX__ */
1333 child->pid = vfork ();
1334 environ = parent_environ; /* Restore value child may have clobbered. */
1335 if (child->pid == 0)
1337 /* We are the child side. */
1340 /* If we aren't running a recursive command and we have a jobserver
1341 pipe, close it before exec'ing. */
1342 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1350 #ifdef SET_STACK_SIZE
1351 /* Reset limits, if necessary. */
1352 if (stack_limit.rlim_cur)
1353 setrlimit (RLIMIT_STACK, &stack_limit);
1356 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1357 argv, child->environment);
1359 else if (child->pid < 0)
1363 perror_with_name ("vfork", "");
1366 # endif /* !__EMX__ */
1370 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1378 /* We call `system' to do the job of the SHELL, since stock DOS
1379 shell is too dumb. Our `system' knows how to handle long
1380 command lines even if pipes/redirection is needed; it will only
1381 call COMMAND.COM when its internal commands are used. */
1382 if (execute_by_shell)
1384 char *cmdline = argv[0];
1385 /* We don't have a way to pass environment to `system',
1386 so we need to save and restore ours, sigh... */
1387 char **parent_environ = environ;
1389 environ = child->environment;
1391 /* If we have a *real* shell, tell `system' to call
1392 it to do everything for us. */
1395 /* A *real* shell on MSDOS may not support long
1396 command lines the DJGPP way, so we must use `system'. */
1397 cmdline = argv[2]; /* get past "shell -c" */
1400 dos_command_running = 1;
1401 proc_return = system (cmdline);
1402 environ = parent_environ;
1403 execute_by_shell = 0; /* for the next time */
1407 dos_command_running = 1;
1408 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1411 /* Need to unblock signals before turning off
1412 dos_command_running, so that child's signals
1413 will be treated as such (see fatal_error_signal). */
1415 dos_command_running = 0;
1417 /* If the child got a signal, dos_status has its
1418 high 8 bits set, so be careful not to alter them. */
1419 if (proc_return == -1)
1422 dos_status |= (proc_return & 0xff);
1424 child->pid = dos_pid++;
1426 #endif /* __MSDOS__ */
1428 amiga_status = MyExecute (argv);
1431 child->pid = amiga_pid++;
1432 if (amiga_batch_file)
1434 amiga_batch_file = 0;
1435 DeleteFile (amiga_bname); /* Ignore errors. */
1443 /* make UNC paths safe for CreateProcess -- backslash format */
1445 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1446 for ( ; arg0 && *arg0; arg0++)
1450 /* make sure CreateProcess() has Path it needs */
1451 sync_Path_environment();
1453 hPID = process_easy(argv, child->environment);
1455 if (hPID != INVALID_HANDLE_VALUE)
1456 child->pid = (pid_t) hPID;
1461 _("process_easy() failed to launch process (e=%ld)\n"),
1462 process_last_err(hPID));
1463 for (i = 0; argv[i]; i++)
1464 fprintf(stderr, "%s ", argv[i]);
1465 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1469 #endif /* WINDOWS32 */
1470 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1472 /* Bump the number of jobs started in this second. */
1475 /* We are the parent side. Set the state to
1476 say the commands are running and return. */
1478 set_command_state (child->file, cs_running);
1480 /* Free the storage used by the child's argument list. */
1489 child->file->update_status = 2;
1490 notice_finished_file (child->file);
1494 /* Try to start a child running.
1495 Returns nonzero if the child was started (and maybe finished), or zero if
1496 the load was too high and the child was put on the `waiting_jobs' chain. */
1499 start_waiting_job (struct child *c)
1501 struct file *f = c->file;
1503 /* If we can start a job remotely, we always want to, and don't care about
1504 the local load average. We record that the job should be started
1505 remotely in C->remote for start_job_command to test. */
1507 c->remote = start_remote_job_p (1);
1509 /* If we are running at least one job already and the load average
1510 is too high, make this one wait. */
1512 && ((job_slots_used > 0 && load_too_high ())
1514 || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
1518 /* Put this child on the chain of children waiting for the load average
1520 set_command_state (f, cs_running);
1521 c->next = waiting_jobs;
1526 /* Start the first command; reap_children will run later command lines. */
1527 start_job_command (c);
1529 switch (f->command_state)
1533 DB (DB_JOBS, (_("Putting child %p (%s) PID %s%s on the chain.\n"),
1534 c, c->file->name, pid2str (c->pid),
1535 c->remote ? _(" (remote)") : ""));
1537 /* One more job slot is in use. */
1542 case cs_not_started:
1543 /* All the command lines turned out to be empty. */
1544 f->update_status = 0;
1548 notice_finished_file (f);
1553 assert (f->command_state == cs_finished);
1560 /* Create a `struct child' for FILE and start its commands running. */
1563 new_job (struct file *file)
1565 struct commands *cmds = file->cmds;
1570 /* Let any previously decided-upon jobs that are waiting
1571 for the load to go down start before this new one. */
1572 start_waiting_jobs ();
1574 /* Reap any children that might have finished recently. */
1575 reap_children (0, 0);
1577 /* Chop the commands up into lines if they aren't already. */
1578 chop_commands (cmds);
1580 /* Expand the command lines and store the results in LINES. */
1581 lines = xmalloc (cmds->ncommand_lines * sizeof (char *));
1582 for (i = 0; i < cmds->ncommand_lines; ++i)
1584 /* Collapse backslash-newline combinations that are inside variable
1585 or function references. These are left alone by the parser so
1586 that they will appear in the echoing of commands (where they look
1587 nice); and collapsed by construct_command_argv when it tokenizes.
1588 But letting them survive inside function invocations loses because
1589 we don't want the functions to see them as part of the text. */
1591 char *in, *out, *ref;
1593 /* IN points to where in the line we are scanning.
1594 OUT points to where in the line we are writing.
1595 When we collapse a backslash-newline combination,
1596 IN gets ahead of OUT. */
1598 in = out = cmds->command_lines[i];
1599 while ((ref = strchr (in, '$')) != 0)
1601 ++ref; /* Move past the $. */
1604 /* Copy the text between the end of the last chunk
1605 we processed (where IN points) and the new chunk
1606 we are about to process (where REF points). */
1607 memmove (out, in, ref - in);
1609 /* Move both pointers past the boring stuff. */
1613 if (*ref == '(' || *ref == '{')
1615 char openparen = *ref;
1616 char closeparen = openparen == '(' ? ')' : '}';
1620 *out++ = *in++; /* Copy OPENPAREN. */
1621 /* IN now points past the opening paren or brace.
1622 Count parens or braces until it is matched. */
1626 if (*in == closeparen && --count < 0)
1628 else if (*in == '\\' && in[1] == '\n')
1630 /* We have found a backslash-newline inside a
1631 variable or function reference. Eat it and
1632 any following whitespace. */
1635 for (p = in - 1; p > ref && *p == '\\'; --p)
1639 /* There were two or more backslashes, so this is
1640 not really a continuation line. We don't collapse
1641 the quoting backslashes here as is done in
1642 collapse_continuations, because the line will
1643 be collapsed again after expansion. */
1647 /* Skip the backslash, newline and
1648 any following whitespace. */
1649 in = next_token (in + 2);
1651 /* Discard any preceding whitespace that has
1652 already been written to the output. */
1654 && isblank ((unsigned char)out[-1]))
1657 /* Replace it all with a single space. */
1663 if (*in == openparen)
1672 /* There are no more references in this line to worry about.
1673 Copy the remaining uninteresting text to the output. */
1675 memmove (out, in, strlen (in) + 1);
1677 /* Finally, expand the line. */
1678 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1682 /* Start the command sequence, record it in a new
1683 `struct child', and add that to the chain. */
1685 c = xcalloc (sizeof (struct child));
1687 c->command_lines = lines;
1688 c->sh_batch_file = NULL;
1690 /* Cache dontcare flag because file->dontcare can be changed once we
1691 return. Check dontcare inheritance mechanism for details. */
1692 c->dontcare = file->dontcare;
1694 /* Fetch the first command line to be run. */
1695 job_next_command (c);
1697 /* Wait for a job slot to be freed up. If we allow an infinite number
1698 don't bother; also job_slots will == 0 if we're using the jobserver. */
1701 while (job_slots_used == job_slots)
1702 reap_children (1, 0);
1704 #ifdef MAKE_JOBSERVER
1705 /* If we are controlling multiple jobs make sure we have a token before
1706 starting the child. */
1708 /* This can be inefficient. There's a decent chance that this job won't
1709 actually have to run any subprocesses: the command script may be empty
1710 or otherwise optimized away. It would be nice if we could defer
1711 obtaining a token until just before we need it, in start_job_command.
1712 To do that we'd need to keep track of whether we'd already obtained a
1713 token (since start_job_command is called for each line of the job, not
1714 just once). Also more thought needs to go into the entire algorithm;
1715 this is where the old parallel job code waits, so... */
1717 else if (job_fds[0] >= 0)
1724 DB (DB_JOBS, ("Need a job token; we %shave children\n",
1725 children ? "" : "don't "));
1727 /* If we don't already have a job started, use our "free" token. */
1728 if (!jobserver_tokens)
1731 /* Read a token. As long as there's no token available we'll block.
1732 We enable interruptible system calls before the read(2) so that if
1733 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1734 we can process the death(s) and return tokens to the free pool.
1736 Once we return from the read, we immediately reinstate restartable
1737 system calls. This allows us to not worry about checking for
1738 EINTR on all the other system calls in the program.
1740 There is one other twist: there is a span between the time
1741 reap_children() does its last check for dead children and the time
1742 the read(2) call is entered, below, where if a child dies we won't
1743 notice. This is extremely serious as it could cause us to
1744 deadlock, given the right set of events.
1746 To avoid this, we do the following: before we reap_children(), we
1747 dup(2) the read FD on the jobserver pipe. The read(2) call below
1748 uses that new FD. In the signal handler, we close that FD. That
1749 way, if a child dies during the section mentioned above, the
1750 read(2) will be invoked with an invalid FD and will return
1751 immediately with EBADF. */
1753 /* Make sure we have a dup'd FD. */
1756 DB (DB_JOBS, ("Duplicate the job FD\n"));
1757 job_rfd = dup (job_fds[0]);
1760 /* Reap anything that's currently waiting. */
1761 reap_children (0, 0);
1763 /* Kick off any jobs we have waiting for an opportunity that
1764 can run now (ie waiting for load). */
1765 start_waiting_jobs ();
1767 /* If our "free" slot has become available, use it; we don't need an
1769 if (!jobserver_tokens)
1772 /* There must be at least one child already, or we have no business
1773 waiting for a token. */
1775 fatal (NILF, "INTERNAL: no children as we go to sleep on read\n");
1777 /* Set interruptible system calls, and read() for a job token. */
1778 set_child_handler_action_flags (1, waiting_jobs != NULL);
1779 got_token = read (job_rfd, &token, 1);
1780 saved_errno = errno;
1781 set_child_handler_action_flags (0, waiting_jobs != NULL);
1783 /* If we got one, we're done here. */
1786 DB (DB_JOBS, (_("Obtained token for child %p (%s).\n"),
1791 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1792 go back and reap_children(), and try again. */
1793 errno = saved_errno;
1794 if (errno != EINTR && errno != EBADF)
1795 pfatal_with_name (_("read jobs pipe"));
1797 DB (DB_JOBS, ("Read returned EBADF.\n"));
1803 /* The job is now primed. Start it running.
1804 (This will notice if there is in fact no recipe.) */
1805 if (cmds->fileinfo.filenm)
1806 DB (DB_BASIC, (_("Invoking recipe from %s:%lu to update target `%s'.\n"),
1807 cmds->fileinfo.filenm, cmds->fileinfo.lineno,
1810 DB (DB_BASIC, (_("Invoking builtin recipe to update target `%s'.\n"),
1814 start_waiting_job (c);
1816 if (job_slots == 1 || not_parallel)
1817 /* Since there is only one job slot, make things run linearly.
1818 Wait for the child to die, setting the state to `cs_finished'. */
1819 while (file->command_state == cs_running)
1820 reap_children (1, 0);
1825 /* Move CHILD's pointers to the next command for it to execute.
1826 Returns nonzero if there is another command. */
1829 job_next_command (struct child *child)
1831 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1833 /* There are no more lines in the expansion of this line. */
1834 if (child->command_line == child->file->cmds->ncommand_lines)
1836 /* There are no more lines to be expanded. */
1837 child->command_ptr = 0;
1841 /* Get the next line to run. */
1842 child->command_ptr = child->command_lines[child->command_line++];
1847 /* Determine if the load average on the system is too high to start a new job.
1848 The real system load average is only recomputed once a second. However, a
1849 very parallel make can easily start tens or even hundreds of jobs in a
1850 second, which brings the system to its knees for a while until that first
1851 batch of jobs clears out.
1853 To avoid this we use a weighted algorithm to try to account for jobs which
1854 have been started since the last second, and guess what the load average
1855 would be now if it were computed.
1857 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1860 ! calculate something load-oid and add to the observed sys.load,
1861 ! so that latter can catch up:
1862 ! - every job started increases jobctr;
1863 ! - every dying job decreases a positive jobctr;
1864 ! - the jobctr value gets zeroed every change of seconds,
1865 ! after its value*weight_b is stored into the 'backlog' value last_sec
1866 ! - weight_a times the sum of jobctr and last_sec gets
1867 ! added to the observed sys.load.
1869 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1870 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1871 ! sub-shelled commands (rm, echo, sed...) for tests.
1872 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1873 ! resulted in significant excession of the load limit, raising it
1874 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1875 ! reach the limit in most test cases.
1877 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1878 ! exceeding the limit for longer-running stuff (compile jobs in
1879 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1880 ! small jobs' effects.
1884 #define LOAD_WEIGHT_A 0.25
1885 #define LOAD_WEIGHT_B 0.25
1888 load_too_high (void)
1890 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
1893 static double last_sec;
1894 static time_t last_now;
1899 /* sub_proc.c cannot wait for more than MAXIMUM_WAIT_OBJECTS children */
1900 if (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
1904 if (max_load_average < 0)
1907 /* Find the real system load average. */
1909 if (getloadavg (&load, 1) != 1)
1911 static int lossage = -1;
1912 /* Complain only once for the same error. */
1913 if (lossage == -1 || errno != lossage)
1916 /* An errno value of zero means getloadavg is just unsupported. */
1918 _("cannot enforce load limits on this operating system"));
1920 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1927 /* If we're in a new second zero the counter and correct the backlog
1928 value. Only keep the backlog for one extra second; after that it's 0. */
1932 if (last_now == now - 1)
1933 last_sec = LOAD_WEIGHT_B * job_counter;
1941 /* Try to guess what the load would be right now. */
1942 guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
1944 DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1945 guess, load, max_load_average));
1947 return guess >= max_load_average;
1951 /* Start jobs that are waiting for the load to be lower. */
1954 start_waiting_jobs (void)
1958 if (waiting_jobs == 0)
1963 /* Check for recently deceased descendants. */
1964 reap_children (0, 0);
1966 /* Take a job off the waiting list. */
1968 waiting_jobs = job->next;
1970 /* Try to start that job. We break out of the loop as soon
1971 as start_waiting_job puts one back on the waiting list. */
1973 while (start_waiting_job (job) && waiting_jobs != 0);
1980 /* EMX: Start a child process. This function returns the new pid. */
1981 # if defined __EMX__
1983 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
1986 /* stdin_fd == 0 means: nothing to do for stdin;
1987 stdout_fd == 1 means: nothing to do for stdout */
1988 int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
1989 int save_stdout = (stdout_fd != 1) ? dup (1): 1;
1991 /* < 0 only if dup() failed */
1993 fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
1994 if (save_stdout < 0)
1995 fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
1997 /* Close unnecessary file handles for the child. */
1998 if (save_stdin != 0)
1999 CLOSE_ON_EXEC (save_stdin);
2000 if (save_stdout != 1)
2001 CLOSE_ON_EXEC (save_stdout);
2003 /* Connect the pipes to the child process. */
2005 (void) dup2 (stdin_fd, 0);
2007 (void) dup2 (stdout_fd, 1);
2009 /* stdin_fd and stdout_fd must be closed on exit because we are
2010 still in the parent process */
2012 CLOSE_ON_EXEC (stdin_fd);
2014 CLOSE_ON_EXEC (stdout_fd);
2016 /* Run the command. */
2017 pid = exec_command (argv, envp);
2019 /* Restore stdout/stdin of the parent and close temporary FDs. */
2022 if (dup2 (save_stdin, 0) != 0)
2023 fatal (NILF, _("Could not restore stdin\n"));
2030 if (dup2 (save_stdout, 1) != 1)
2031 fatal (NILF, _("Could not restore stdout\n"));
2033 close (save_stdout);
2039 #elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
2042 Replace the current process with one executing the command in ARGV.
2043 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2044 the environment of the new program. This function does not return. */
2046 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2049 (void) dup2 (stdin_fd, 0);
2051 (void) dup2 (stdout_fd, 1);
2053 (void) close (stdin_fd);
2055 (void) close (stdout_fd);
2057 /* Run the command. */
2058 exec_command (argv, envp);
2060 #endif /* !AMIGA && !__MSDOS__ && !VMS */
2061 #endif /* !WINDOWS32 */
2064 /* Replace the current process with one running the command in ARGV,
2065 with environment ENVP. This function does not return. */
2067 /* EMX: This function returns the pid of the child process. */
2073 exec_command (char **argv, char **envp)
2076 /* to work around a problem with signals and execve: ignore them */
2078 signal (SIGCHLD,SIG_IGN);
2080 /* Run the program. */
2081 execve (argv[0], argv, envp);
2082 perror_with_name ("execve: ", argv[0]);
2083 _exit (EXIT_FAILURE);
2089 int exit_code = EXIT_FAILURE;
2091 /* make sure CreateProcess() has Path it needs */
2092 sync_Path_environment();
2094 /* launch command */
2095 hPID = process_easy(argv, envp);
2097 /* make sure launch ok */
2098 if (hPID == INVALID_HANDLE_VALUE)
2102 _("process_easy() failed to launch process (e=%ld)\n"),
2103 process_last_err(hPID));
2104 for (i = 0; argv[i]; i++)
2105 fprintf(stderr, "%s ", argv[i]);
2106 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2110 /* wait and reap last child */
2111 hWaitPID = process_wait_for_any();
2114 /* was an error found on this process? */
2115 err = process_last_err(hWaitPID);
2118 exit_code = process_exit_code(hWaitPID);
2121 fprintf(stderr, "make (e=%d, rc=%d): %s",
2122 err, exit_code, map_windows32_error_to_string(err));
2124 /* cleanup process */
2125 process_cleanup(hWaitPID);
2127 /* expect to find only last pid, warn about other pids reaped */
2128 if (hWaitPID == hPID)
2132 char *pidstr = xstrdup (pid2str ((pid_t)hWaitPID));
2135 _("make reaped child pid %s, still waiting for pid %s\n"),
2136 pidstr, pid2str ((pid_t)hPID));
2141 /* return child's exit code as our exit code */
2144 #else /* !WINDOWS32 */
2150 /* Be the user, permanently. */
2155 /* Run the program. */
2156 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2161 /* the file might have a strange shell extension */
2162 if (errno == ENOENT)
2167 /* Run the program. */
2169 execvp (argv[0], argv);
2171 # endif /* !__EMX__ */
2176 error (NILF, _("%s: Command not found"), argv[0]);
2180 /* The file is not executable. Try it as a shell script. */
2181 extern char *getenv ();
2188 /* Do not use $SHELL from the environment */
2189 struct variable *p = lookup_variable ("SHELL", 5);
2195 shell = getenv ("SHELL");
2198 shell = default_shell;
2201 while (argv[argc] != 0)
2209 new_argv = alloca ((1 + argc + 1) * sizeof (char *));
2210 new_argv[0] = shell;
2221 new_argv[i] = argv[0];
2224 new_argv[i + argc] = argv[argc];
2229 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2233 execvp (shell, new_argv);
2235 if (errno == ENOENT)
2236 error (NILF, _("%s: Shell program not found"), shell);
2238 perror_with_name ("execvp: ", shell);
2244 /* this nasty error was driving me nuts :-( */
2245 error (NILF, _("spawnvpe: environment space might be exhausted"));
2250 perror_with_name ("execvp: ", argv[0]);
2259 #endif /* !WINDOWS32 */
2262 #else /* On Amiga */
2263 void exec_command (char **argv)
2268 void clean_tmp (void)
2270 DeleteFile (amiga_bname);
2273 #endif /* On Amiga */
2276 /* Figure out the argument list necessary to run LINE as a command. Try to
2277 avoid using a shell. This routine handles only ' quoting, and " quoting
2278 when no backslash, $ or ` characters are seen in the quotes. Starting
2279 quotes may be escaped with a backslash. If any of the characters in
2280 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2281 is the first word of a line, the shell is used.
2283 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2284 If *RESTP is NULL, newlines will be ignored.
2286 SHELL is the shell to use, or nil to use the default shell.
2287 IFS is the value of $IFS, or nil (meaning the default).
2289 FLAGS is the value of lines_flags for this command line. It is
2290 used in the WINDOWS32 port to check whether + or $(MAKE) were found
2291 in this command line, in which case the effect of just_print_flag
2295 construct_command_argv_internal (char *line, char **restp, char *shell,
2296 char *shellflags, char *ifs, int flags,
2297 char **batch_filename_ptr)
2300 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2301 We call `system' for anything that requires ``slow'' processing,
2302 because DOS shells are too dumb. When $SHELL points to a real
2303 (unix-style) shell, `system' just calls it to do everything. When
2304 $SHELL points to a DOS shell, `system' does most of the work
2305 internally, calling the shell only for its internal commands.
2306 However, it looks on the $PATH first, so you can e.g. have an
2307 external command named `mkdir'.
2309 Since we call `system', certain characters and commands below are
2310 actually not specific to COMMAND.COM, but to the DJGPP implementation
2311 of `system'. In particular:
2313 The shell wildcard characters are in DOS_CHARS because they will
2314 not be expanded if we call the child via `spawnXX'.
2316 The `;' is in DOS_CHARS, because our `system' knows how to run
2317 multiple commands on a single line.
2319 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2320 won't have to tell one from another and have one more set of
2321 commands and special characters. */
2322 static char sh_chars_dos[] = "*?[];|<>%^&()";
2323 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2324 "copy", "ctty", "date", "del", "dir", "echo",
2325 "erase", "exit", "for", "goto", "if", "md",
2326 "mkdir", "path", "pause", "prompt", "rd",
2327 "rmdir", "rem", "ren", "rename", "set",
2328 "shift", "time", "type", "ver", "verify",
2331 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2332 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2333 "logout", "set", "umask", "wait", "while",
2334 "for", "case", "if", ":", ".", "break",
2335 "continue", "export", "read", "readonly",
2336 "shift", "times", "trap", "switch", "unset",
2341 #elif defined (__EMX__)
2342 static char sh_chars_dos[] = "*?[];|<>%^&()";
2343 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2344 "copy", "ctty", "date", "del", "dir", "echo",
2345 "erase", "exit", "for", "goto", "if", "md",
2346 "mkdir", "path", "pause", "prompt", "rd",
2347 "rmdir", "rem", "ren", "rename", "set",
2348 "shift", "time", "type", "ver", "verify",
2351 static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
2352 static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2353 "date", "del", "detach", "dir", "echo",
2354 "endlocal", "erase", "exit", "for", "goto", "if",
2355 "keys", "md", "mkdir", "move", "path", "pause",
2356 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2357 "set", "setlocal", "shift", "start", "time",
2358 "type", "ver", "verify", "vol", ":", 0 };
2360 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~'";
2361 static char *sh_cmds_sh[] = { "echo", "cd", "eval", "exec", "exit", "login",
2362 "logout", "set", "umask", "wait", "while",
2363 "for", "case", "if", ":", ".", "break",
2364 "continue", "export", "read", "readonly",
2365 "shift", "times", "trap", "switch", "unset",
2370 #elif defined (_AMIGA)
2371 static char sh_chars[] = "#;\"|<>()?*$`";
2372 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2373 "rename", "set", "setenv", "date", "makedir",
2374 "skip", "else", "endif", "path", "prompt",
2375 "unset", "unsetenv", "version",
2377 #elif defined (WINDOWS32)
2378 static char sh_chars_dos[] = "\"|&<>";
2379 static char *sh_cmds_dos[] = { "assoc", "break", "call", "cd", "chcp",
2380 "chdir", "cls", "color", "copy", "ctty",
2381 "date", "del", "dir", "echo", "echo.",
2382 "endlocal", "erase", "exit", "for", "ftype",
2383 "goto", "if", "if", "md", "mkdir", "path",
2384 "pause", "prompt", "rd", "rem", "ren",
2385 "rename", "rmdir", "set", "setlocal",
2386 "shift", "time", "title", "type", "ver",
2387 "verify", "vol", ":", 0 };
2388 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2389 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2390 "logout", "set", "umask", "wait", "while", "for",
2391 "case", "if", ":", ".", "break", "continue",
2392 "export", "read", "readonly", "shift", "times",
2393 "trap", "switch", "test",
2394 #ifdef BATCH_MODE_ONLY_SHELL
2400 #elif defined(__riscos__)
2401 static char sh_chars[] = "";
2402 static char *sh_cmds[] = { 0 };
2403 #else /* must be UNIX-ish */
2404 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~!";
2405 static char *sh_cmds[] = { ".", ":", "break", "case", "cd", "continue",
2406 "eval", "exec", "exit", "export", "for", "if",
2407 "login", "logout", "read", "readonly", "set",
2408 "shift", "switch", "test", "times", "trap",
2409 "ulimit", "umask", "unset", "wait", "while", 0 };
2410 # ifdef HAVE_DOS_PATHS
2411 /* This is required if the MSYS/Cygwin ports (which do not define
2412 WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
2413 sh_chars_sh[] directly (see below). */
2414 static char *sh_chars_sh = sh_chars;
2415 # endif /* HAVE_DOS_PATHS */
2421 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2422 char **new_argv = 0;
2428 sh_cmds = sh_cmds_dos;
2429 sh_chars = sh_chars_dos;
2431 sh_cmds = sh_cmds_sh;
2432 sh_chars = sh_chars_sh;
2434 #endif /* WINDOWS32 */
2439 /* Make sure not to bother processing an empty line. */
2440 while (isblank ((unsigned char)*line))
2445 /* See if it is safe to parse commands internally. */
2447 shell = default_shell;
2449 else if (strcmp (shell, default_shell))
2451 char *s1 = _fullpath (NULL, shell, 0);
2452 char *s2 = _fullpath (NULL, default_shell, 0);
2454 slow_flag = strcmp ((s1 ? s1 : ""), (s2 ? s2 : ""));
2463 #else /* not WINDOWS32 */
2464 #if defined (__MSDOS__) || defined (__EMX__)
2465 else if (strcasecmp (shell, default_shell))
2467 extern int _is_unixy_shell (const char *_path);
2469 DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
2470 default_shell, shell));
2471 unixy_shell = _is_unixy_shell (shell);
2472 /* we must allocate a copy of shell: construct_command_argv() will free
2473 * shell after this function returns. */
2474 default_shell = xstrdup (shell);
2478 sh_chars = sh_chars_sh;
2479 sh_cmds = sh_cmds_sh;
2483 sh_chars = sh_chars_dos;
2484 sh_cmds = sh_cmds_dos;
2486 if (_osmode == OS2_MODE)
2488 sh_chars = sh_chars_os2;
2489 sh_cmds = sh_cmds_os2;
2493 #else /* !__MSDOS__ */
2494 else if (strcmp (shell, default_shell))
2496 #endif /* !__MSDOS__ && !__EMX__ */
2497 #endif /* not WINDOWS32 */
2500 for (ap = ifs; *ap != '\0'; ++ap)
2501 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2504 if (shellflags != 0)
2505 if (shellflags[0] != '-'
2506 || ((shellflags[1] != 'c' || shellflags[2] != '\0')
2507 && (shellflags[1] != 'e' || shellflags[2] != 'c' || shellflags[3] != '\0')))
2510 i = strlen (line) + 1;
2512 /* More than 1 arg per character is impossible. */
2513 new_argv = xmalloc (i * sizeof (char *));
2515 /* All the args can fit in a buffer as big as LINE is. */
2516 ap = new_argv[0] = argstr = xmalloc (i);
2519 /* I is how many complete arguments have been found. */
2521 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2522 for (p = line; *p != '\0'; ++p)
2528 /* Inside a string, just copy any char except a closing quote
2529 or a backslash-newline combination. */
2533 if (ap == new_argv[0] || *(ap-1) == '\0')
2534 last_argument_was_empty = 1;
2536 else if (*p == '\\' && p[1] == '\n')
2538 /* Backslash-newline is handled differently depending on what
2539 kind of string we're in: inside single-quoted strings you
2540 keep them; in double-quoted strings they disappear.
2541 For DOS/Windows/OS2, if we don't have a POSIX shell,
2542 we keep the pre-POSIX behavior of removing the
2543 backslash-newline. */
2545 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2556 else if (*p == '\n' && restp != NULL)
2558 /* End of the command line. */
2562 /* Backslash, $, and ` are special inside double quotes.
2563 If we see any of those, punt.
2564 But on MSDOS, if we use COMMAND.COM, double and single
2565 quotes have the same effect. */
2566 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2571 else if (strchr (sh_chars, *p) != 0)
2572 /* Not inside a string, but it's a special char. */
2574 else if (one_shell && *p == '\n')
2575 /* In .ONESHELL mode \n is a separator like ; or && */
2578 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2579 /* `...' is a wildcard in DJGPP. */
2583 /* Not a special char. */
2587 /* Equals is a special character in leading words before the
2588 first word with no equals sign in it. This is not the case
2589 with sh -k, but we never get here when using nonstandard
2591 if (! seen_nonequals && unixy_shell)
2593 word_has_equals = 1;
2598 /* Backslash-newline has special case handling, ref POSIX.
2599 We're in the fastpath, so emulate what the shell would do. */
2602 /* Throw out the backslash and newline. */
2605 /* If there's nothing in this argument yet, skip any
2606 whitespace before the start of the next word. */
2607 if (ap == new_argv[i])
2608 p = next_token (p + 1) - 1;
2610 else if (p[1] != '\0')
2612 #ifdef HAVE_DOS_PATHS
2613 /* Only remove backslashes before characters special to Unixy
2614 shells. All other backslashes are copied verbatim, since
2615 they are probably DOS-style directory separators. This
2616 still leaves a small window for problems, but at least it
2617 should work for the vast majority of naive users. */
2620 /* A dot is only special as part of the "..."
2622 if (strneq (p + 1, ".\\.\\.", 5))
2630 if (p[1] != '\\' && p[1] != '\''
2631 && !isspace ((unsigned char)p[1])
2632 && strchr (sh_chars_sh, p[1]) == 0)
2633 /* back up one notch, to copy the backslash */
2635 #endif /* HAVE_DOS_PATHS */
2637 /* Copy and skip the following char. */
2650 /* End of the command line. */
2655 /* Newlines are not special. */
2661 /* We have the end of an argument.
2662 Terminate the text of the argument. */
2665 last_argument_was_empty = 0;
2667 /* Update SEEN_NONEQUALS, which tells us if every word
2668 heretofore has contained an `='. */
2669 seen_nonequals |= ! word_has_equals;
2670 if (word_has_equals && ! seen_nonequals)
2671 /* An `=' in a word before the first
2672 word without one is magical. */
2674 word_has_equals = 0; /* Prepare for the next word. */
2676 /* If this argument is the command name,
2677 see if it is a built-in shell command.
2678 If so, have the shell handle it. */
2682 for (j = 0; sh_cmds[j] != 0; ++j)
2684 if (streq (sh_cmds[j], new_argv[0]))
2687 /* Non-Unix shells are case insensitive. */
2689 && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
2695 /* Ignore multiple whitespace chars. */
2696 p = next_token (p) - 1;
2707 /* Let the shell deal with an unterminated quote. */
2710 /* Terminate the last argument and the argument list. */
2713 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2720 for (j = 0; sh_cmds[j] != 0; ++j)
2721 if (streq (sh_cmds[j], new_argv[0]))
2725 if (new_argv[0] == 0)
2727 /* Line was empty. */
2736 /* We must use the shell. */
2740 /* Free the old argument list we were working on. */
2746 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2755 buffer = xmalloc (strlen (line)+1);
2758 for (dptr=buffer; *ptr; )
2760 if (*ptr == '\\' && ptr[1] == '\n')
2762 else if (*ptr == '@') /* Kludge: multiline commands */
2772 new_argv = xmalloc (2 * sizeof (char *));
2773 new_argv[0] = buffer;
2776 #else /* Not Amiga */
2779 * Not eating this whitespace caused things like
2783 * which gave the shell fits. I think we have to eat
2784 * whitespace here, but this code should be considered
2785 * suspicious if things start failing....
2788 /* Make sure not to bother processing an empty line. */
2789 while (isspace ((unsigned char)*line))
2793 #endif /* WINDOWS32 */
2796 /* SHELL may be a multi-word command. Construct a command line
2797 "$(SHELL) $(.SHELLFLAGS) LINE", with all special chars in LINE escaped.
2798 Then recurse, expanding this command line to get the final
2801 unsigned int shell_len = strlen (shell);
2802 unsigned int line_len = strlen (line);
2803 unsigned int sflags_len = strlen (shellflags);
2804 char *command_ptr = NULL; /* used for batch_mode_shell mode */
2808 # ifdef __EMX__ /* is this necessary? */
2810 shellflags[0] = '/'; /* "/c" */
2813 /* In .ONESHELL mode we are allowed to throw the entire current
2814 recipe string at a single shell and trust that the user
2815 has configured the shell and shell flags, and formatted
2816 the string, appropriately. */
2819 /* If the shell is Bourne compatible, we must remove and ignore
2820 interior special chars [@+-] because they're meaningless to
2821 the shell itself. If, however, we're in .ONESHELL mode and
2822 have changed SHELL to something non-standard, we should
2823 leave those alone because they could be part of the
2824 script. In this case we must also leave in place
2825 any leading [@+-] for the same reason. */
2827 /* Remove and ignore interior prefix chars [@+-] because they're
2828 meaningless given a single shell. */
2829 #if defined __MSDOS__ || defined (__EMX__)
2830 if (unixy_shell) /* the test is complicated and we already did it */
2832 if (is_bourne_compatible_shell(shell))
2835 const char *f = line;
2838 /* Copy the recipe, removing and ignoring interior prefix chars
2839 [@+-]: they're meaningless in .ONESHELL mode. */
2840 while (f[0] != '\0')
2844 /* This is the start of a new recipe line.
2845 Skip whitespace and prefix characters. */
2846 while (isblank (*f) || *f == '-' || *f == '@' || *f == '+')
2849 /* Copy until we get to the next logical recipe line. */
2857 /* On unescaped newline, we're done with this line. */
2858 if (f[-1] == '\n' && ! esc)
2861 /* Something else: reset the escape sequence. */
2869 new_argv = xmalloc (4 * sizeof (char *));
2870 new_argv[0] = xstrdup(shell);
2871 new_argv[1] = xstrdup(shellflags);
2877 #ifdef MAX_ARG_STRLEN
2878 static char eval_line[] = "eval\\ \\\"set\\ x\\;\\ shift\\;\\ ";
2879 #define ARG_NUMBER_DIGITS 5
2880 #define EVAL_LEN (sizeof(eval_line)-1 + shell_len + 4 \
2881 + (7 + ARG_NUMBER_DIGITS) * 2 * line_len / (MAX_ARG_STRLEN - 2))
2886 new_line = alloca (shell_len + 1 + sflags_len + 1
2887 + (line_len*2) + 1 + EVAL_LEN);
2889 memcpy (ap, shell, shell_len);
2892 memcpy (ap, shellflags, sflags_len);
2897 #if !defined (WINDOWS32) && defined (MAX_ARG_STRLEN)
2898 if (unixy_shell && line_len > MAX_ARG_STRLEN)
2901 memcpy (ap, eval_line, sizeof (eval_line) - 1);
2902 ap += sizeof (eval_line) - 1;
2903 for (j = 1; j <= 2 * line_len / (MAX_ARG_STRLEN - 2); j++)
2904 ap += sprintf (ap, "\\$\\{%u\\}", j);
2908 /* Copy only the first word of SHELL to $0. */
2909 for (p = shell; *p != '\0'; ++p)
2911 if (isspace ((unsigned char)*p))
2920 for (p = line; *p != '\0'; ++p)
2922 if (restp != NULL && *p == '\n')
2927 else if (*p == '\\' && p[1] == '\n')
2929 /* POSIX says we keep the backslash-newline. If we don't have a
2930 POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
2931 and remove the backslash/newline. */
2932 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2933 # define PRESERVE_BSNL unixy_shell
2935 # define PRESERVE_BSNL 1
2940 /* Only non-batch execution needs another backslash,
2941 because it will be passed through a recursive
2942 invocation of this function. */
2943 if (!batch_mode_shell)
2951 /* DOS shells don't know about backslash-escaping. */
2952 if (unixy_shell && !batch_mode_shell &&
2953 (*p == '\\' || *p == '\'' || *p == '"'
2954 || isspace ((unsigned char)*p)
2955 || strchr (sh_chars, *p) != 0))
2958 else if (unixy_shell && strneq (p, "...", 3))
2960 /* The case of `...' wildcard again. */
2961 strcpy (ap, "\\.\\.\\");
2968 #if !defined (WINDOWS32) && defined (MAX_ARG_STRLEN)
2969 if (unixy_shell && line_len > MAX_ARG_STRLEN && (ap - args_ptr > MAX_ARG_STRLEN - 2))
2976 if (ap == new_line + shell_len + sflags_len + 2)
2977 /* Line was empty. */
2982 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2983 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2984 cases, run commands via a script file. */
2985 if (just_print_flag && !(flags & COMMANDS_RECURSE)) {
2986 /* Need to allocate new_argv, although it's unused, because
2987 start_job_command will want to free it and its 0'th element. */
2988 new_argv = xmalloc(2 * sizeof (char *));
2989 new_argv[0] = xstrdup ("");
2991 } else if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2994 int id = GetCurrentProcessId();
2997 /* create a file name */
2998 sprintf(fbuf, "make%d", id);
2999 *batch_filename_ptr = create_batch_file (fbuf, unixy_shell, &temp_fd);
3001 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3002 *batch_filename_ptr));
3004 /* Create a FILE object for the batch file, and write to it the
3005 commands to be executed. Put the batch file in TEXT mode. */
3006 _setmode (temp_fd, _O_TEXT);
3007 batch = _fdopen (temp_fd, "wt");
3009 fputs ("@echo off\n", batch);
3010 fputs (command_ptr, batch);
3011 fputc ('\n', batch);
3013 DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
3014 !unixy_shell ? "\n\t@echo off" : "", command_ptr));
3017 new_argv = xmalloc(3 * sizeof (char *));
3019 new_argv[0] = xstrdup (shell);
3020 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
3022 new_argv[0] = xstrdup (*batch_filename_ptr);
3027 #endif /* WINDOWS32 */
3030 new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0, flags, 0);
3033 else if (!unixy_shell)
3035 /* new_line is local, must not be freed therefore
3036 We use line here instead of new_line because we run the shell
3038 size_t line_len = strlen (line);
3041 memcpy (new_line, line, line_len + 1);
3042 /* Replace all backslash-newline combination and also following tabs.
3043 Important: stop at the first '\n' because that's what the loop above
3044 did. The next line starting at restp[0] will be executed during the
3045 next call of this function. */
3046 while (*q != '\0' && *q != '\n')
3048 if (q[0] == '\\' && q[1] == '\n')
3049 q += 2; /* remove '\\' and '\n' */
3055 # ifndef NO_CMD_DEFAULT
3056 if (strnicmp (new_line, "echo", 4) == 0
3057 && (new_line[4] == ' ' || new_line[4] == '\t'))
3059 /* the builtin echo command: handle it separately */
3060 size_t echo_len = line_len - 5;
3061 char *echo_line = new_line + 5;
3063 /* special case: echo 'x="y"'
3064 cmd works this way: a string is printed as is, i.e., no quotes
3065 are removed. But autoconf uses a command like echo 'x="y"' to
3066 determine whether make works. autoconf expects the output x="y"
3067 so we will do exactly that.
3068 Note: if we do not allow cmd to be the default shell
3069 we do not need this kind of voodoo */
3070 if (echo_line[0] == '\''
3071 && echo_line[echo_len - 1] == '\''
3072 && strncmp (echo_line + 1, "ac_maketemp=",
3073 strlen ("ac_maketemp=")) == 0)
3075 /* remove the enclosing quotes */
3076 memmove (echo_line, echo_line + 1, echo_len - 2);
3077 echo_line[echo_len - 2] = '\0';
3083 /* Let the shell decide what to do. Put the command line into the
3084 2nd command line argument and hope for the best ;-) */
3085 size_t sh_len = strlen (shell);
3087 /* exactly 3 arguments + NULL */
3088 new_argv = xmalloc (4 * sizeof (char *));
3089 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3090 the trailing '\0' */
3091 new_argv[0] = xmalloc (sh_len + line_len + 5);
3092 memcpy (new_argv[0], shell, sh_len + 1);
3093 new_argv[1] = new_argv[0] + sh_len + 1;
3094 memcpy (new_argv[1], "/c", 3);
3095 new_argv[2] = new_argv[1] + 3;
3096 memcpy (new_argv[2], new_line, line_len + 1);
3100 #elif defined(__MSDOS__)
3103 /* With MSDOS shells, we must construct the command line here
3104 instead of recursively calling ourselves, because we
3105 cannot backslash-escape the special characters (see above). */
3106 new_argv = xmalloc (sizeof (char *));
3107 line_len = strlen (new_line) - shell_len - sflags_len - 2;
3108 new_argv[0] = xmalloc (line_len + 1);
3109 strncpy (new_argv[0],
3110 new_line + shell_len + sflags_len + 2, line_len);
3111 new_argv[0][line_len] = '\0';
3115 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3116 __FILE__, __LINE__);
3119 #endif /* ! AMIGA */
3125 /* Figure out the argument list necessary to run LINE as a command. Try to
3126 avoid using a shell. This routine handles only ' quoting, and " quoting
3127 when no backslash, $ or ` characters are seen in the quotes. Starting
3128 quotes may be escaped with a backslash. If any of the characters in
3129 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3130 is the first word of a line, the shell is used.
3132 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3133 If *RESTP is NULL, newlines will be ignored.
3135 FILE is the target whose commands these are. It is used for
3136 variable expansion for $(SHELL) and $(IFS). */
3139 construct_command_argv (char *line, char **restp, struct file *file,
3140 int cmd_flags, char **batch_filename_ptr)
3142 char *shell, *ifs, *shellflags;
3154 && (isspace ((unsigned char)*cptr)))
3159 && (!isspace((unsigned char)*cptr)))
3164 argv = xmalloc (argc * sizeof (char *));
3173 && (isspace ((unsigned char)*cptr)))
3177 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3178 argv[argc++] = cptr;
3180 && (!isspace((unsigned char)*cptr)))
3187 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3188 int save = warn_undefined_variables_flag;
3189 warn_undefined_variables_flag = 0;
3191 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3194 * Convert to forward slashes so that construct_command_argv_internal()
3198 char *p = w32ify (shell, 0);
3204 static const char *unixroot = NULL;
3205 static const char *last_shell = "";
3206 static int init = 0;
3209 unixroot = getenv ("UNIXROOT");
3210 /* unixroot must be NULL or not empty */
3211 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3215 /* if we have an unixroot drive and if shell is not default_shell
3216 (which means it's either cmd.exe or the test has already been
3217 performed) and if shell is an absolute path without drive letter,
3218 try whether it exists e.g.: if "/bin/sh" does not exist use
3219 "$UNIXROOT/bin/sh" instead. */
3220 if (unixroot && shell && strcmp (shell, last_shell) != 0
3221 && (shell[0] == '/' || shell[0] == '\\'))
3223 /* trying a new shell, check whether it exists */
3224 size_t size = strlen (shell);
3225 char *buf = xmalloc (size + 7);
3226 memcpy (buf, shell, size);
3227 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3228 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3230 /* try the same for the unixroot drive */
3231 memmove (buf + 2, buf, size + 5);
3232 buf[0] = unixroot[0];
3233 buf[1] = unixroot[1];
3234 if (access (buf, F_OK) == 0)
3235 /* we have found a shell! */
3245 #endif /* __EMX__ */
3247 shellflags = allocated_variable_expand_for_file ("$(.SHELLFLAGS)", file);
3248 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3250 warn_undefined_variables_flag = save;
3253 argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
3254 cmd_flags, batch_filename_ptr);
3263 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3265 dup2 (int old, int new)
3280 #endif /* !HAVE_DUP2 && !_AMIGA */
3282 /* On VMS systems, include special VMS functions. */
3285 #include "vmsjobs.c"