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 Free Software
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 2, or (at your option) any later version.
11 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along with
16 GNU Make; see the file COPYING. If not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */
32 /* Default shell to use. */
36 char *default_shell
= "sh.exe";
37 int no_default_sh_exe
= 1;
38 int batch_mode_shell
= 1;
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;
64 char default_shell
[] = "";
65 int batch_mode_shell
= 0;
67 #elif defined (__riscos__)
69 char default_shell
[] = "";
70 int batch_mode_shell
= 0;
74 char default_shell
[] = "/bin/sh";
75 int batch_mode_shell
= 0;
81 static int execute_by_shell
;
82 static int dos_pid
= 123;
84 int dos_command_running
;
85 #endif /* __MSDOS__ */
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
;
97 # include <processes.h>
100 # include <lib$routines.h>
101 static void vmsWaitForChildren (int *);
105 # include <windows.h>
107 # include <process.h>
108 # include "sub_proc.h"
110 # include "pathstuff.h"
111 #endif /* WINDOWS32 */
114 # include <process.h>
117 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
118 # include <sys/wait.h>
122 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
123 #else /* Don't have waitpid. */
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)
136 #ifndef HAVE_UNION_WAIT
141 # define WTERMSIG(x) ((x) & 0x7f)
144 # define WCOREDUMP(x) ((x) & 0x80)
147 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
150 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
153 # define WIFEXITED(x) (WTERMSIG (x) == 0)
156 #else /* Have `union wait'. */
158 # define WAIT_T union wait
160 # define WTERMSIG(x) ((x).w_termsig)
163 # define WCOREDUMP(x) ((x).w_coredump)
166 # define WEXITSTATUS(x) ((x).w_retcode)
169 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
172 # define WIFEXITED(x) (WTERMSIG(x) == 0)
175 #endif /* Don't have `union wait'. */
177 #ifndef HAVE_UNISTD_H
189 int getloadavg (double loadavg
[], int nelem
);
190 int start_remote_job (char **argv
, char **envp
, int stdin_fd
, int *is_remote
,
191 int *id_ptr
, int *used_stdin
);
192 int start_remote_job_p (int);
193 int remote_status (int *exit_code_ptr
, int *signal_ptr
, int *coredump_ptr
,
196 RETSIGTYPE
child_handler (int);
197 static void free_child (struct child
*);
198 static void start_job_command (struct child
*child
);
199 static int load_too_high (void);
200 static int job_next_command (struct child
*);
201 static int start_waiting_job (struct child
*);
203 /* Chain of all live (or recently deceased) children. */
205 struct child
*children
= 0;
207 /* Number of children currently running. */
209 unsigned int job_slots_used
= 0;
211 /* Nonzero if the `good' standard input is in use. */
213 static int good_stdin_used
= 0;
215 /* Chain of children waiting to run until the load average goes down. */
217 static struct child
*waiting_jobs
= 0;
219 /* Non-zero if we use a *real* shell (always so on Unix). */
223 /* Number of jobs started in the current second. */
225 unsigned long job_counter
= 0;
227 /* Number of jobserver tokens this instance is currently using. */
229 unsigned int jobserver_tokens
= 0;
233 * The macro which references this function is defined in make.h.
236 w32_kill(int pid
, int sig
)
238 return ((process_kill((HANDLE
)pid
, sig
) == TRUE
) ? 0 : -1);
241 /* This function creates a temporary file name with an extension specified
243 * Return an xmalloc'ed string of a newly created temp file and its
244 * file descriptor, or die. */
246 create_batch_file (char const *base
, int unixy
, int *fd
)
248 const char *const ext
= unixy
? "sh" : "bat";
249 const char *error
= NULL
;
250 char temp_path
[MAXPATHLEN
]; /* need to know its length */
251 unsigned path_size
= GetTempPath(sizeof temp_path
, temp_path
);
254 const unsigned sizemax
= strlen (base
) + strlen (ext
) + 10;
258 path_size
= GetCurrentDirectory (sizeof temp_path
, temp_path
);
262 while (path_size
> 0 &&
263 path_size
+ sizemax
< sizeof temp_path
&&
266 unsigned size
= sprintf (temp_path
+ path_size
,
268 temp_path
[path_size
- 1] == '\\' ? "" : "\\",
270 HANDLE h
= CreateFile (temp_path
, /* file name */
271 GENERIC_READ
| GENERIC_WRITE
, /* desired access */
272 0, /* no share mode */
273 NULL
, /* default security attributes */
274 CREATE_NEW
, /* creation disposition */
275 FILE_ATTRIBUTE_NORMAL
| /* flags and attributes */
276 FILE_ATTRIBUTE_TEMPORARY
, /* we'll delete it */
277 NULL
); /* no template file */
279 if (h
== INVALID_HANDLE_VALUE
)
281 const DWORD er
= GetLastError();
283 if (er
== ERROR_FILE_EXISTS
|| er
== ERROR_ALREADY_EXISTS
)
286 /* the temporary path is not guaranteed to exist */
287 else if (path_is_dot
== 0)
289 path_size
= GetCurrentDirectory (sizeof temp_path
, temp_path
);
295 error
= map_windows32_error_to_string (er
);
301 const unsigned final_size
= path_size
+ size
+ 1;
302 char *const path
= xmalloc (final_size
);
303 memcpy (path
, temp_path
, final_size
);
304 *fd
= _open_osfhandle ((long)h
, 0);
309 for (p
= path
; (ch
= *p
) != 0; ++p
)
313 return path
; /* good return */
319 error
= _("Cannot create a temporary file\n");
325 #endif /* WINDOWS32 */
328 /* returns whether path is assumed to be a unix like shell. */
330 _is_unixy_shell (const char *path
)
332 /* list of non unix shells */
333 const char *known_os2shells
[] = {
345 /* find the rightmost '/' or '\\' */
346 const char *name
= strrchr (path
, '/');
347 const char *p
= strrchr (path
, '\\');
350 if (name
&& p
) /* take the max */
351 name
= (name
> p
) ? name
: p
;
352 else if (p
) /* name must be 0 */
354 else if (!name
) /* name and p must be 0 */
357 if (*name
== '/' || *name
== '\\') name
++;
360 while (known_os2shells
[i
] != NULL
) {
361 if (strcasecmp (name
, known_os2shells
[i
]) == 0)
362 return 0; /* not a unix shell */
366 /* in doubt assume a unix like shell */
372 /* Write an error message describing the exit status given in
373 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
374 Append "(ignored)" if IGNORED is nonzero. */
377 child_error (const char *target_name
,
378 int exit_code
, int exit_sig
, int coredump
, int ignored
)
380 if (ignored
&& silent_flag
)
384 if (!(exit_code
& 1))
386 (ignored
? _("*** [%s] Error 0x%x (ignored)")
387 : _("*** [%s] Error 0x%x")),
388 target_name
, exit_code
);
391 error (NILF
, ignored
? _("[%s] Error %d (ignored)") :
392 _("*** [%s] Error %d"),
393 target_name
, exit_code
);
395 error (NILF
, "*** [%s] %s%s",
396 target_name
, strsignal (exit_sig
),
397 coredump
? _(" (core dumped)") : "");
402 /* Handle a dead child. This handler may or may not ever be installed.
404 If we're using the jobserver feature, we need it. First, installing it
405 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
406 read FD to ensure we don't enter another blocking read without reaping all
407 the dead children. In this case we don't need the dead_children count.
409 If we don't have either waitpid or wait3, then make is unreliable, but we
410 use the dead_children count to reap children as best we can. */
412 static unsigned int dead_children
= 0;
415 child_handler (int sig UNUSED
)
426 /* The signal handler must called only once! */
427 signal (SIGCHLD
, SIG_DFL
);
430 /* This causes problems if the SIGCHLD interrupts a printf().
431 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
435 extern int shell_function_pid
, shell_function_completed
;
437 /* Reap all dead children, storing the returned status and the new command
438 state (`cs_finished') in the `file' member of the `struct child' for the
439 dead child, and removing the child from the chain. In addition, if BLOCK
440 nonzero, we block in this function until we've reaped at least one
441 complete child, waiting for it to die if necessary. If ERR is nonzero,
442 print an error message first. */
445 reap_children (int block
, int err
)
449 /* Initially, assume we have some. */
454 # define REAP_MORE reap_more
456 # define REAP_MORE dead_children
461 We have at least one child outstanding OR a shell function in progress,
463 We're blocking for a complete child OR there are more children to reap
465 we'll keep reaping children. */
467 while ((children
!= 0 || shell_function_pid
!= 0)
468 && (block
|| REAP_MORE
))
472 int exit_code
, exit_sig
, coredump
;
473 register struct child
*lastc
, *c
;
475 int any_remote
, any_local
;
480 static int printed
= 0;
482 /* We might block for a while, so let the user know why.
483 Only print this message once no matter how many jobs are left. */
486 error (NILF
, _("*** Waiting for unfinished jobs...."));
490 /* We have one less dead child to reap. As noted in
491 child_handler() above, this count is completely unimportant for
492 all modern, POSIX-y systems that support wait3() or waitpid().
493 The rest of this comment below applies only to early, broken
494 pre-POSIX systems. We keep the count only because... it's there...
496 The test and decrement are not atomic; if it is compiled into:
497 register = dead_children - 1;
498 dead_children = register;
499 a SIGCHLD could come between the two instructions.
500 child_handler increments dead_children.
501 The second instruction here would lose that increment. But the
502 only effect of dead_children being wrong is that we might wait
503 longer than necessary to reap a child, and lose some parallelism;
504 and we might print the "Waiting for unfinished jobs" message above
505 when not necessary. */
507 if (dead_children
> 0)
511 any_local
= shell_function_pid
!= 0;
512 for (c
= children
; c
!= 0; c
= c
->next
)
514 any_remote
|= c
->remote
;
515 any_local
|= ! c
->remote
;
516 DB (DB_JOBS
, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
517 (unsigned long int) c
, c
->file
->name
,
518 (long) c
->pid
, c
->remote
? _(" (remote)") : ""));
524 /* First, check for remote children. */
526 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 0);
531 /* We got a remote child. */
535 /* A remote status command failed miserably. Punt. */
537 pfatal_with_name ("remote_status");
541 /* No remote children. Check for local children. */
542 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
546 vmsWaitForChildren (&status
);
551 pid
= WAIT_NOHANG (&status
);
554 pid
= wait (&status
);
562 /* The wait*() failed miserably. Punt. */
563 pfatal_with_name ("wait");
567 /* We got a child exit; chop the status word up. */
568 exit_code
= WEXITSTATUS (status
);
569 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
570 coredump
= WCOREDUMP (status
);
572 /* If we have started jobs in this second, remove one. */
578 /* No local children are dead. */
581 if (!block
|| !any_remote
)
584 /* Now try a blocking wait for a remote child. */
585 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 1);
587 goto remote_status_lose
;
589 /* No remote children either. Finally give up. */
592 /* We got a remote child. */
595 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
598 /* Life is very different on MSDOS. */
601 exit_code
= WEXITSTATUS (status
);
602 if (exit_code
== 0xff)
604 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
606 #endif /* __MSDOS__ */
610 status
= amiga_status
;
611 exit_code
= amiga_status
;
624 /* Record the thread ID of the main process, so that we
625 could suspend it in the signal handler. */
628 hcTID
= GetCurrentThread ();
629 hcPID
= GetCurrentProcess ();
630 if (!DuplicateHandle (hcPID
, hcTID
, hcPID
, &main_thread
, 0,
631 FALSE
, DUPLICATE_SAME_ACCESS
))
633 DWORD e
= GetLastError ();
635 "Determine main thread ID (Error %ld: %s)\n",
636 e
, map_windows32_error_to_string(e
));
639 DB (DB_VERBOSE
, ("Main thread handle = 0x%08lx\n",
640 (unsigned long)main_thread
));
643 /* wait for anything to finish */
644 hPID
= process_wait_for_any();
648 /* was an error found on this process? */
649 werr
= process_last_err(hPID
);
652 exit_code
= process_exit_code(hPID
);
655 fprintf(stderr
, "make (e=%d): %s",
656 exit_code
, map_windows32_error_to_string(exit_code
));
659 exit_sig
= process_signal(hPID
);
661 /* cleanup process */
662 process_cleanup(hPID
);
668 #endif /* WINDOWS32 */
671 /* Check if this is the child of the `shell' function. */
672 if (!remote
&& pid
== shell_function_pid
)
674 /* It is. Leave an indicator for the `shell' function. */
675 if (exit_sig
== 0 && exit_code
== 127)
676 shell_function_completed
= -1;
678 shell_function_completed
= 1;
682 child_failed
= exit_sig
!= 0 || exit_code
!= 0;
684 /* Search for a child matching the deceased one. */
686 for (c
= children
; c
!= 0; lastc
= c
, c
= c
->next
)
687 if (c
->remote
== remote
&& c
->pid
== pid
)
691 /* An unknown child died.
692 Ignore it; it was inherited from our invoker. */
695 DB (DB_JOBS
, (child_failed
696 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
697 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
698 (unsigned long int) c
, (long) c
->pid
,
699 c
->remote
? _(" (remote)") : ""));
701 if (c
->sh_batch_file
) {
702 DB (DB_JOBS
, (_("Cleaning up temp batch file %s\n"),
705 /* just try and remove, don't care if this fails */
706 remove (c
->sh_batch_file
);
708 /* all done with memory */
709 free (c
->sh_batch_file
);
710 c
->sh_batch_file
= NULL
;
713 /* If this child had the good stdin, say it is now free. */
717 dontcare
= c
->dontcare
;
719 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
721 /* The commands failed. Write an error message,
722 delete non-precious targets, and abort. */
723 static int delete_on_error
= -1;
726 child_error (c
->file
->name
, exit_code
, exit_sig
, coredump
, 0);
728 c
->file
->update_status
= 2;
729 if (delete_on_error
== -1)
731 struct file
*f
= lookup_file (".DELETE_ON_ERROR");
732 delete_on_error
= f
!= 0 && f
->is_target
;
734 if (exit_sig
!= 0 || delete_on_error
)
735 delete_child_targets (c
);
741 /* The commands failed, but we don't care. */
742 child_error (c
->file
->name
,
743 exit_code
, exit_sig
, coredump
, 1);
747 /* If there are more commands to run, try to start them. */
748 if (job_next_command (c
))
750 if (handling_fatal_signal
)
752 /* Never start new commands while we are dying.
753 Since there are more commands that wanted to be run,
754 the target was not completely remade. So we treat
755 this as if a command had failed. */
756 c
->file
->update_status
= 2;
760 /* Check again whether to start remotely.
761 Whether or not we want to changes over time.
762 Also, start_remote_job may need state set up
763 by start_remote_job_p. */
764 c
->remote
= start_remote_job_p (0);
765 start_job_command (c
);
766 /* Fatal signals are left blocked in case we were
767 about to put that child on the chain. But it is
768 already there, so it is safe for a fatal signal to
769 arrive now; it will clean up this child's targets. */
771 if (c
->file
->command_state
== cs_running
)
772 /* We successfully started the new command.
773 Loop to reap more children. */
777 if (c
->file
->update_status
!= 0)
778 /* We failed to start the commands. */
779 delete_child_targets (c
);
782 /* There are no more commands. We got through them all
783 without an unignored error. Now the target has been
784 successfully updated. */
785 c
->file
->update_status
= 0;
788 /* When we get here, all the commands for C->file are finished
789 (or aborted) and C->file->update_status contains 0 or 2. But
790 C->file->command_state is still cs_running if all the commands
791 ran; notice_finish_file looks for cs_running to tell it that
792 it's interesting to check the file's modtime again now. */
794 if (! handling_fatal_signal
)
795 /* Notice if the target of the commands has been changed.
796 This also propagates its values for command_state and
797 update_status to its also_make files. */
798 notice_finished_file (c
->file
);
800 DB (DB_JOBS
, (_("Removing child 0x%08lx PID %ld%s from chain.\n"),
801 (unsigned long int) c
, (long) c
->pid
,
802 c
->remote
? _(" (remote)") : ""));
804 /* Block fatal signals while frobnicating the list, so that
805 children and job_slots_used are always consistent. Otherwise
806 a fatal signal arriving after the child is off the chain and
807 before job_slots_used is decremented would believe a child was
808 live and call reap_children again. */
811 /* There is now another slot open. */
812 if (job_slots_used
> 0)
815 /* Remove the child from the chain and free it. */
819 lastc
->next
= c
->next
;
825 /* If the job failed, and the -k flag was not given, die,
826 unless we are already in the process of dying. */
827 if (!err
&& child_failed
&& !dontcare
&& !keep_going_flag
&&
828 /* fatal_error_signal will die with the right signal. */
829 !handling_fatal_signal
)
832 /* Only block for one child. */
839 /* Free the storage allocated for CHILD. */
842 free_child (struct child
*child
)
844 if (!jobserver_tokens
)
845 fatal (NILF
, "INTERNAL: Freeing child 0x%08lx (%s) but no tokens left!\n",
846 (unsigned long int) child
, child
->file
->name
);
848 /* If we're using the jobserver and this child is not the only outstanding
849 job, put a token back into the pipe for it. */
851 if (job_fds
[1] >= 0 && jobserver_tokens
> 1)
856 /* Write a job token back to the pipe. */
858 EINTRLOOP (r
, write (job_fds
[1], &token
, 1));
860 pfatal_with_name (_("write jobserver"));
862 DB (DB_JOBS
, (_("Released token for child 0x%08lx (%s).\n"),
863 (unsigned long int) child
, child
->file
->name
));
868 if (handling_fatal_signal
) /* Don't bother free'ing if about to die. */
871 if (child
->command_lines
!= 0)
873 register unsigned int i
;
874 for (i
= 0; i
< child
->file
->cmds
->ncommand_lines
; ++i
)
875 free (child
->command_lines
[i
]);
876 free (child
->command_lines
);
879 if (child
->environment
!= 0)
881 register char **ep
= child
->environment
;
884 free (child
->environment
);
891 extern sigset_t fatal_signal_set
;
898 (void) sigprocmask (SIG_BLOCK
, &fatal_signal_set
, (sigset_t
*) 0);
900 # ifdef HAVE_SIGSETMASK
901 (void) sigblock (fatal_signal_mask
);
911 sigemptyset (&empty
);
912 sigprocmask (SIG_SETMASK
, &empty
, (sigset_t
*) 0);
916 #ifdef MAKE_JOBSERVER
918 job_noop (int sig UNUSED
)
921 /* Set the child handler action flags to FLAGS. */
923 set_child_handler_action_flags (int set_handler
, int set_alarm
)
928 /* The child handler must be turned off here. */
929 signal (SIGCHLD
, SIG_DFL
);
932 memset (&sa
, '\0', sizeof sa
);
933 sa
.sa_handler
= child_handler
;
934 sa
.sa_flags
= set_handler
? 0 : SA_RESTART
;
936 sigaction (SIGCHLD
, &sa
, NULL
);
938 #if defined SIGCLD && SIGCLD != SIGCHLD
939 sigaction (SIGCLD
, &sa
, NULL
);
944 /* If we're about to enter the read(), set an alarm to wake up in a
945 second so we can check if the load has dropped and we can start more
946 work. On the way out, turn off the alarm and set SIG_DFL. */
947 alarm (set_handler
? 1 : 0);
948 sa
.sa_handler
= set_handler
? job_noop
: SIG_DFL
;
950 sigaction (SIGALRM
, &sa
, NULL
);
957 /* Start a job to run the commands specified in CHILD.
958 CHILD is updated to reflect the commands and ID of the child process.
960 NOTE: On return fatal signals are blocked! The caller is responsible
961 for calling `unblock_sigs', once the new child is safely on the chain so
962 it can be cleaned up in the event of a fatal signal. */
965 start_job_command (struct child
*child
)
967 #if !defined(_AMIGA) && !defined(WINDOWS32)
968 static int bad_stdin
= -1;
978 /* If we have a completely empty commandset, stop now. */
979 if (!child
->command_ptr
)
982 /* Combine the flags parsed for the line itself with
983 the flags specified globally for this target. */
984 flags
= (child
->file
->command_flags
985 | child
->file
->cmds
->lines_flags
[child
->command_line
- 1]);
987 p
= child
->command_ptr
;
988 child
->noerror
= ((flags
& COMMANDS_NOERROR
) != 0);
993 flags
|= COMMANDS_SILENT
;
995 flags
|= COMMANDS_RECURSE
;
998 else if (!isblank ((unsigned char)*p
))
1003 /* Update the file's command flags with any new ones we found. We only
1004 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
1005 now marking more commands recursive than should be in the case of
1006 multiline define/endef scripts where only one line is marked "+". In
1007 order to really fix this, we'll have to keep a lines_flags for every
1008 actual line, after expansion. */
1009 child
->file
->cmds
->lines_flags
[child
->command_line
- 1]
1010 |= flags
& COMMANDS_RECURSE
;
1012 /* Figure out an argument list from this command line. */
1019 argv
= construct_command_argv (p
, &end
, child
->file
, &child
->sh_batch_file
);
1022 child
->command_ptr
= NULL
;
1026 child
->command_ptr
= end
;
1030 /* If -q was given, say that updating `failed' if there was any text on the
1031 command line, or `succeeded' otherwise. The exit status of 1 tells the
1032 user that -q is saying `something to do'; the exit status for a random
1034 if (argv
!= 0 && question_flag
&& !(flags
& COMMANDS_RECURSE
))
1040 child
->file
->update_status
= 1;
1041 notice_finished_file (child
->file
);
1045 if (touch_flag
&& !(flags
& COMMANDS_RECURSE
))
1047 /* Go on to the next command. It might be the recursive one.
1048 We construct ARGV only to find the end of the command line. */
1063 execute_by_shell
= 0; /* in case construct_command_argv sets it */
1065 /* This line has no commands. Go to the next. */
1066 if (job_next_command (child
))
1067 start_job_command (child
);
1070 /* No more commands. Make sure we're "running"; we might not be if
1071 (e.g.) all commands were skipped due to -n. */
1072 set_command_state (child
->file
, cs_running
);
1073 child
->file
->update_status
= 0;
1074 notice_finished_file (child
->file
);
1079 /* Print out the command. If silent, we call `message' with null so it
1080 can log the working directory before the command's own error messages
1083 message (0, (just_print_flag
|| (!(flags
& COMMANDS_SILENT
) && !silent_flag
))
1084 ? "%s" : (char *) 0, p
);
1086 /* Tell update_goal_chain that a command has been started on behalf of
1087 this target. It is important that this happens here and not in
1088 reap_children (where we used to do it), because reap_children might be
1089 reaping children from a different target. We want this increment to
1090 guaranteedly indicate that a command was started for the dependency
1091 chain (i.e., update_file recursion chain) we are processing. */
1095 /* Optimize an empty command. People use this for timestamp rules,
1096 so avoid forking a useless shell. Do this after we increment
1097 commands_started so make still treats this special case as if it
1098 performed some action (makes a difference as to what messages are
1101 #if !defined(VMS) && !defined(_AMIGA)
1103 #if defined __MSDOS__ || defined (__EMX__)
1104 unixy_shell
/* the test is complicated and we already did it */
1106 (argv
[0] && !strcmp (argv
[0], "/bin/sh"))
1109 && argv
[1][0] == '-' && argv
[1][1] == 'c' && argv
[1][2] == '\0')
1110 && (argv
[2] && argv
[2][0] == ':' && argv
[2][1] == '\0')
1117 #endif /* !VMS && !_AMIGA */
1119 /* If -n was given, recurse to get the next line in the sequence. */
1121 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
))
1130 /* Flush the output streams so they won't have things written twice. */
1136 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1138 /* Set up a bad standard input that reads from a broken pipe. */
1140 if (bad_stdin
== -1)
1142 /* Make a file descriptor that is the read end of a broken pipe.
1143 This will be used for some children's standard inputs. */
1147 /* Close the write side. */
1148 (void) close (pd
[1]);
1149 /* Save the read side. */
1152 /* Set the descriptor to close on exec, so it does not litter any
1153 child's descriptor table. When it is dup2'd onto descriptor 0,
1154 that descriptor will not close on exec. */
1155 CLOSE_ON_EXEC (bad_stdin
);
1159 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1161 /* Decide whether to give this child the `good' standard input
1162 (one that points to the terminal or whatever), or the `bad' one
1163 that points to the read side of a broken pipe. */
1165 child
->good_stdin
= !good_stdin_used
;
1166 if (child
->good_stdin
)
1167 good_stdin_used
= 1;
1174 /* Set up the environment for the child. */
1175 if (child
->environment
== 0)
1176 child
->environment
= target_environment (child
->file
);
1179 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1182 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1185 int is_remote
, id
, used_stdin
;
1186 if (start_remote_job (argv
, child
->environment
,
1187 child
->good_stdin
? 0 : bad_stdin
,
1188 &is_remote
, &id
, &used_stdin
))
1189 /* Don't give up; remote execution may fail for various reasons. If
1190 so, simply run the job locally. */
1194 if (child
->good_stdin
&& !used_stdin
)
1196 child
->good_stdin
= 0;
1197 good_stdin_used
= 0;
1199 child
->remote
= is_remote
;
1206 /* Fork the child process. */
1208 char **parent_environ
;
1216 if (!child_execute_job (argv
, child
)) {
1218 perror_with_name ("vfork", "");
1224 parent_environ
= environ
;
1227 /* If we aren't running a recursive command and we have a jobserver
1228 pipe, close it before exec'ing. */
1229 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1231 CLOSE_ON_EXEC (job_fds
[0]);
1232 CLOSE_ON_EXEC (job_fds
[1]);
1235 CLOSE_ON_EXEC (job_rfd
);
1237 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1238 child
->pid
= child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1239 argv
, child
->environment
);
1244 perror_with_name ("spawn", "");
1248 /* undo CLOSE_ON_EXEC() after the child process has been started */
1249 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1251 fcntl (job_fds
[0], F_SETFD
, 0);
1252 fcntl (job_fds
[1], F_SETFD
, 0);
1255 fcntl (job_rfd
, F_SETFD
, 0);
1257 #else /* !__EMX__ */
1259 child
->pid
= vfork ();
1260 environ
= parent_environ
; /* Restore value child may have clobbered. */
1261 if (child
->pid
== 0)
1263 /* We are the child side. */
1266 /* If we aren't running a recursive command and we have a jobserver
1267 pipe, close it before exec'ing. */
1268 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1276 child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1277 argv
, child
->environment
);
1279 else if (child
->pid
< 0)
1283 perror_with_name ("vfork", "");
1286 # endif /* !__EMX__ */
1290 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1298 /* We call `system' to do the job of the SHELL, since stock DOS
1299 shell is too dumb. Our `system' knows how to handle long
1300 command lines even if pipes/redirection is needed; it will only
1301 call COMMAND.COM when its internal commands are used. */
1302 if (execute_by_shell
)
1304 char *cmdline
= argv
[0];
1305 /* We don't have a way to pass environment to `system',
1306 so we need to save and restore ours, sigh... */
1307 char **parent_environ
= environ
;
1309 environ
= child
->environment
;
1311 /* If we have a *real* shell, tell `system' to call
1312 it to do everything for us. */
1315 /* A *real* shell on MSDOS may not support long
1316 command lines the DJGPP way, so we must use `system'. */
1317 cmdline
= argv
[2]; /* get past "shell -c" */
1320 dos_command_running
= 1;
1321 proc_return
= system (cmdline
);
1322 environ
= parent_environ
;
1323 execute_by_shell
= 0; /* for the next time */
1327 dos_command_running
= 1;
1328 proc_return
= spawnvpe (P_WAIT
, argv
[0], argv
, child
->environment
);
1331 /* Need to unblock signals before turning off
1332 dos_command_running, so that child's signals
1333 will be treated as such (see fatal_error_signal). */
1335 dos_command_running
= 0;
1337 /* If the child got a signal, dos_status has its
1338 high 8 bits set, so be careful not to alter them. */
1339 if (proc_return
== -1)
1342 dos_status
|= (proc_return
& 0xff);
1344 child
->pid
= dos_pid
++;
1346 #endif /* __MSDOS__ */
1348 amiga_status
= MyExecute (argv
);
1351 child
->pid
= amiga_pid
++;
1352 if (amiga_batch_file
)
1354 amiga_batch_file
= 0;
1355 DeleteFile (amiga_bname
); /* Ignore errors. */
1363 /* make UNC paths safe for CreateProcess -- backslash format */
1365 if (arg0
&& arg0
[0] == '/' && arg0
[1] == '/')
1366 for ( ; arg0
&& *arg0
; arg0
++)
1370 /* make sure CreateProcess() has Path it needs */
1371 sync_Path_environment();
1373 hPID
= process_easy(argv
, child
->environment
);
1375 if (hPID
!= INVALID_HANDLE_VALUE
)
1376 child
->pid
= (int) hPID
;
1381 _("process_easy() failed to launch process (e=%ld)\n"),
1382 process_last_err(hPID
));
1383 for (i
= 0; argv
[i
]; i
++)
1384 fprintf(stderr
, "%s ", argv
[i
]);
1385 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
1389 #endif /* WINDOWS32 */
1390 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1392 /* Bump the number of jobs started in this second. */
1395 /* We are the parent side. Set the state to
1396 say the commands are running and return. */
1398 set_command_state (child
->file
, cs_running
);
1400 /* Free the storage used by the child's argument list. */
1409 child
->file
->update_status
= 2;
1410 notice_finished_file (child
->file
);
1414 /* Try to start a child running.
1415 Returns nonzero if the child was started (and maybe finished), or zero if
1416 the load was too high and the child was put on the `waiting_jobs' chain. */
1419 start_waiting_job (struct child
*c
)
1421 struct file
*f
= c
->file
;
1423 /* If we can start a job remotely, we always want to, and don't care about
1424 the local load average. We record that the job should be started
1425 remotely in C->remote for start_job_command to test. */
1427 c
->remote
= start_remote_job_p (1);
1429 /* If we are running at least one job already and the load average
1430 is too high, make this one wait. */
1432 && ((job_slots_used
> 0 && load_too_high ())
1434 || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS
)
1438 /* Put this child on the chain of children waiting for the load average
1440 set_command_state (f
, cs_running
);
1441 c
->next
= waiting_jobs
;
1446 /* Start the first command; reap_children will run later command lines. */
1447 start_job_command (c
);
1449 switch (f
->command_state
)
1453 DB (DB_JOBS
, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1454 (unsigned long int) c
, c
->file
->name
,
1455 (long) c
->pid
, c
->remote
? _(" (remote)") : ""));
1457 /* One more job slot is in use. */
1462 case cs_not_started
:
1463 /* All the command lines turned out to be empty. */
1464 f
->update_status
= 0;
1468 notice_finished_file (f
);
1473 assert (f
->command_state
== cs_finished
);
1480 /* Create a `struct child' for FILE and start its commands running. */
1483 new_job (struct file
*file
)
1485 struct commands
*cmds
= file
->cmds
;
1490 /* Let any previously decided-upon jobs that are waiting
1491 for the load to go down start before this new one. */
1492 start_waiting_jobs ();
1494 /* Reap any children that might have finished recently. */
1495 reap_children (0, 0);
1497 /* Chop the commands up into lines if they aren't already. */
1498 chop_commands (cmds
);
1500 /* Expand the command lines and store the results in LINES. */
1501 lines
= xmalloc (cmds
->ncommand_lines
* sizeof (char *));
1502 for (i
= 0; i
< cmds
->ncommand_lines
; ++i
)
1504 /* Collapse backslash-newline combinations that are inside variable
1505 or function references. These are left alone by the parser so
1506 that they will appear in the echoing of commands (where they look
1507 nice); and collapsed by construct_command_argv when it tokenizes.
1508 But letting them survive inside function invocations loses because
1509 we don't want the functions to see them as part of the text. */
1511 char *in
, *out
, *ref
;
1513 /* IN points to where in the line we are scanning.
1514 OUT points to where in the line we are writing.
1515 When we collapse a backslash-newline combination,
1516 IN gets ahead of OUT. */
1518 in
= out
= cmds
->command_lines
[i
];
1519 while ((ref
= strchr (in
, '$')) != 0)
1521 ++ref
; /* Move past the $. */
1524 /* Copy the text between the end of the last chunk
1525 we processed (where IN points) and the new chunk
1526 we are about to process (where REF points). */
1527 memmove (out
, in
, ref
- in
);
1529 /* Move both pointers past the boring stuff. */
1533 if (*ref
== '(' || *ref
== '{')
1535 char openparen
= *ref
;
1536 char closeparen
= openparen
== '(' ? ')' : '}';
1540 *out
++ = *in
++; /* Copy OPENPAREN. */
1541 /* IN now points past the opening paren or brace.
1542 Count parens or braces until it is matched. */
1546 if (*in
== closeparen
&& --count
< 0)
1548 else if (*in
== '\\' && in
[1] == '\n')
1550 /* We have found a backslash-newline inside a
1551 variable or function reference. Eat it and
1552 any following whitespace. */
1555 for (p
= in
- 1; p
> ref
&& *p
== '\\'; --p
)
1559 /* There were two or more backslashes, so this is
1560 not really a continuation line. We don't collapse
1561 the quoting backslashes here as is done in
1562 collapse_continuations, because the line will
1563 be collapsed again after expansion. */
1567 /* Skip the backslash, newline and
1568 any following whitespace. */
1569 in
= next_token (in
+ 2);
1571 /* Discard any preceding whitespace that has
1572 already been written to the output. */
1574 && isblank ((unsigned char)out
[-1]))
1577 /* Replace it all with a single space. */
1583 if (*in
== openparen
)
1592 /* There are no more references in this line to worry about.
1593 Copy the remaining uninteresting text to the output. */
1597 /* Finally, expand the line. */
1598 lines
[i
] = allocated_variable_expand_for_file (cmds
->command_lines
[i
],
1602 /* Start the command sequence, record it in a new
1603 `struct child', and add that to the chain. */
1605 c
= xmalloc (sizeof (struct child
));
1606 memset (c
, '\0', sizeof (struct child
));
1608 c
->command_lines
= lines
;
1609 c
->sh_batch_file
= NULL
;
1611 /* Cache dontcare flag because file->dontcare can be changed once we
1612 return. Check dontcare inheritance mechanism for details. */
1613 c
->dontcare
= file
->dontcare
;
1615 /* Fetch the first command line to be run. */
1616 job_next_command (c
);
1618 /* Wait for a job slot to be freed up. If we allow an infinite number
1619 don't bother; also job_slots will == 0 if we're using the jobserver. */
1622 while (job_slots_used
== job_slots
)
1623 reap_children (1, 0);
1625 #ifdef MAKE_JOBSERVER
1626 /* If we are controlling multiple jobs make sure we have a token before
1627 starting the child. */
1629 /* This can be inefficient. There's a decent chance that this job won't
1630 actually have to run any subprocesses: the command script may be empty
1631 or otherwise optimized away. It would be nice if we could defer
1632 obtaining a token until just before we need it, in start_job_command.
1633 To do that we'd need to keep track of whether we'd already obtained a
1634 token (since start_job_command is called for each line of the job, not
1635 just once). Also more thought needs to go into the entire algorithm;
1636 this is where the old parallel job code waits, so... */
1638 else if (job_fds
[0] >= 0)
1645 DB (DB_JOBS
, ("Need a job token; we %shave children\n",
1646 children
? "" : "don't "));
1648 /* If we don't already have a job started, use our "free" token. */
1649 if (!jobserver_tokens
)
1652 /* Read a token. As long as there's no token available we'll block.
1653 We enable interruptible system calls before the read(2) so that if
1654 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1655 we can process the death(s) and return tokens to the free pool.
1657 Once we return from the read, we immediately reinstate restartable
1658 system calls. This allows us to not worry about checking for
1659 EINTR on all the other system calls in the program.
1661 There is one other twist: there is a span between the time
1662 reap_children() does its last check for dead children and the time
1663 the read(2) call is entered, below, where if a child dies we won't
1664 notice. This is extremely serious as it could cause us to
1665 deadlock, given the right set of events.
1667 To avoid this, we do the following: before we reap_children(), we
1668 dup(2) the read FD on the jobserver pipe. The read(2) call below
1669 uses that new FD. In the signal handler, we close that FD. That
1670 way, if a child dies during the section mentioned above, the
1671 read(2) will be invoked with an invalid FD and will return
1672 immediately with EBADF. */
1674 /* Make sure we have a dup'd FD. */
1677 DB (DB_JOBS
, ("Duplicate the job FD\n"));
1678 job_rfd
= dup (job_fds
[0]);
1681 /* Reap anything that's currently waiting. */
1682 reap_children (0, 0);
1684 /* Kick off any jobs we have waiting for an opportunity that
1685 can run now (ie waiting for load). */
1686 start_waiting_jobs ();
1688 /* If our "free" slot has become available, use it; we don't need an
1690 if (!jobserver_tokens
)
1693 /* There must be at least one child already, or we have no business
1694 waiting for a token. */
1696 fatal (NILF
, "INTERNAL: no children as we go to sleep on read\n");
1698 /* Set interruptible system calls, and read() for a job token. */
1699 set_child_handler_action_flags (1, waiting_jobs
!= NULL
);
1700 got_token
= read (job_rfd
, &token
, 1);
1701 saved_errno
= errno
;
1702 set_child_handler_action_flags (0, waiting_jobs
!= NULL
);
1704 /* If we got one, we're done here. */
1707 DB (DB_JOBS
, (_("Obtained token for child 0x%08lx (%s).\n"),
1708 (unsigned long int) c
, c
->file
->name
));
1712 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1713 go back and reap_children(), and try again. */
1714 errno
= saved_errno
;
1715 if (errno
!= EINTR
&& errno
!= EBADF
)
1716 pfatal_with_name (_("read jobs pipe"));
1718 DB (DB_JOBS
, ("Read returned EBADF.\n"));
1724 /* The job is now primed. Start it running.
1725 (This will notice if there are in fact no commands.) */
1726 if (cmds
->fileinfo
.filenm
)
1727 DB (DB_BASIC
, (_("Invoking commands from %s:%lu to update target `%s'.\n"),
1728 cmds
->fileinfo
.filenm
, cmds
->fileinfo
.lineno
,
1731 DB (DB_BASIC
, (_("Invoking builtin commands to update target `%s'.\n"),
1735 start_waiting_job (c
);
1737 if (job_slots
== 1 || not_parallel
)
1738 /* Since there is only one job slot, make things run linearly.
1739 Wait for the child to die, setting the state to `cs_finished'. */
1740 while (file
->command_state
== cs_running
)
1741 reap_children (1, 0);
1746 /* Move CHILD's pointers to the next command for it to execute.
1747 Returns nonzero if there is another command. */
1750 job_next_command (struct child
*child
)
1752 while (child
->command_ptr
== 0 || *child
->command_ptr
== '\0')
1754 /* There are no more lines in the expansion of this line. */
1755 if (child
->command_line
== child
->file
->cmds
->ncommand_lines
)
1757 /* There are no more lines to be expanded. */
1758 child
->command_ptr
= 0;
1762 /* Get the next line to run. */
1763 child
->command_ptr
= child
->command_lines
[child
->command_line
++];
1768 /* Determine if the load average on the system is too high to start a new job.
1769 The real system load average is only recomputed once a second. However, a
1770 very parallel make can easily start tens or even hundreds of jobs in a
1771 second, which brings the system to its knees for a while until that first
1772 batch of jobs clears out.
1774 To avoid this we use a weighted algorithm to try to account for jobs which
1775 have been started since the last second, and guess what the load average
1776 would be now if it were computed.
1778 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1781 ! calculate something load-oid and add to the observed sys.load,
1782 ! so that latter can catch up:
1783 ! - every job started increases jobctr;
1784 ! - every dying job decreases a positive jobctr;
1785 ! - the jobctr value gets zeroed every change of seconds,
1786 ! after its value*weight_b is stored into the 'backlog' value last_sec
1787 ! - weight_a times the sum of jobctr and last_sec gets
1788 ! added to the observed sys.load.
1790 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1791 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1792 ! sub-shelled commands (rm, echo, sed...) for tests.
1793 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1794 ! resulted in significant excession of the load limit, raising it
1795 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1796 ! reach the limit in most test cases.
1798 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1799 ! exceeding the limit for longer-running stuff (compile jobs in
1800 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1801 ! small jobs' effects.
1805 #define LOAD_WEIGHT_A 0.25
1806 #define LOAD_WEIGHT_B 0.25
1809 load_too_high (void)
1811 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
1814 static double last_sec
;
1815 static time_t last_now
;
1820 /* sub_proc.c cannot wait for more than MAXIMUM_WAIT_OBJECTS children */
1821 if (process_used_slots () >= MAXIMUM_WAIT_OBJECTS
)
1825 if (max_load_average
< 0)
1828 /* Find the real system load average. */
1830 if (getloadavg (&load
, 1) != 1)
1832 static int lossage
= -1;
1833 /* Complain only once for the same error. */
1834 if (lossage
== -1 || errno
!= lossage
)
1837 /* An errno value of zero means getloadavg is just unsupported. */
1839 _("cannot enforce load limits on this operating system"));
1841 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1848 /* If we're in a new second zero the counter and correct the backlog
1849 value. Only keep the backlog for one extra second; after that it's 0. */
1853 if (last_now
== now
- 1)
1854 last_sec
= LOAD_WEIGHT_B
* job_counter
;
1862 /* Try to guess what the load would be right now. */
1863 guess
= load
+ (LOAD_WEIGHT_A
* (job_counter
+ last_sec
));
1865 DB (DB_JOBS
, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1866 guess
, load
, max_load_average
));
1868 return guess
>= max_load_average
;
1872 /* Start jobs that are waiting for the load to be lower. */
1875 start_waiting_jobs (void)
1879 if (waiting_jobs
== 0)
1884 /* Check for recently deceased descendants. */
1885 reap_children (0, 0);
1887 /* Take a job off the waiting list. */
1889 waiting_jobs
= job
->next
;
1891 /* Try to start that job. We break out of the loop as soon
1892 as start_waiting_job puts one back on the waiting list. */
1894 while (start_waiting_job (job
) && waiting_jobs
!= 0);
1901 /* EMX: Start a child process. This function returns the new pid. */
1902 # if defined __MSDOS__ || defined __EMX__
1904 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
1907 /* stdin_fd == 0 means: nothing to do for stdin;
1908 stdout_fd == 1 means: nothing to do for stdout */
1909 int save_stdin
= (stdin_fd
!= 0) ? dup (0) : 0;
1910 int save_stdout
= (stdout_fd
!= 1) ? dup (1): 1;
1912 /* < 0 only if dup() failed */
1914 fatal (NILF
, _("no more file handles: could not duplicate stdin\n"));
1915 if (save_stdout
< 0)
1916 fatal (NILF
, _("no more file handles: could not duplicate stdout\n"));
1918 /* Close unnecessary file handles for the child. */
1919 if (save_stdin
!= 0)
1920 CLOSE_ON_EXEC (save_stdin
);
1921 if (save_stdout
!= 1)
1922 CLOSE_ON_EXEC (save_stdout
);
1924 /* Connect the pipes to the child process. */
1926 (void) dup2 (stdin_fd
, 0);
1928 (void) dup2 (stdout_fd
, 1);
1930 /* stdin_fd and stdout_fd must be closed on exit because we are
1931 still in the parent process */
1933 CLOSE_ON_EXEC (stdin_fd
);
1935 CLOSE_ON_EXEC (stdout_fd
);
1937 /* Run the command. */
1938 pid
= exec_command (argv
, envp
);
1940 /* Restore stdout/stdin of the parent and close temporary FDs. */
1943 if (dup2 (save_stdin
, 0) != 0)
1944 fatal (NILF
, _("Could not restore stdin\n"));
1951 if (dup2 (save_stdout
, 1) != 1)
1952 fatal (NILF
, _("Could not restore stdout\n"));
1954 close (save_stdout
);
1960 #elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
1963 Replace the current process with one executing the command in ARGV.
1964 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1965 the environment of the new program. This function does not return. */
1967 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
1970 (void) dup2 (stdin_fd
, 0);
1972 (void) dup2 (stdout_fd
, 1);
1974 (void) close (stdin_fd
);
1976 (void) close (stdout_fd
);
1978 /* Run the command. */
1979 exec_command (argv
, envp
);
1981 #endif /* !AMIGA && !__MSDOS__ && !VMS */
1982 #endif /* !WINDOWS32 */
1985 /* Replace the current process with one running the command in ARGV,
1986 with environment ENVP. This function does not return. */
1988 /* EMX: This function returns the pid of the child process. */
1994 exec_command (char **argv
, char **envp
)
1997 /* to work around a problem with signals and execve: ignore them */
1999 signal (SIGCHLD
,SIG_IGN
);
2001 /* Run the program. */
2002 execve (argv
[0], argv
, envp
);
2003 perror_with_name ("execve: ", argv
[0]);
2004 _exit (EXIT_FAILURE
);
2010 int exit_code
= EXIT_FAILURE
;
2012 /* make sure CreateProcess() has Path it needs */
2013 sync_Path_environment();
2015 /* launch command */
2016 hPID
= process_easy(argv
, envp
);
2018 /* make sure launch ok */
2019 if (hPID
== INVALID_HANDLE_VALUE
)
2023 _("process_easy() failed failed to launch process (e=%ld)\n"),
2024 process_last_err(hPID
));
2025 for (i
= 0; argv
[i
]; i
++)
2026 fprintf(stderr
, "%s ", argv
[i
]);
2027 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
2031 /* wait and reap last child */
2032 hWaitPID
= process_wait_for_any();
2035 /* was an error found on this process? */
2036 err
= process_last_err(hWaitPID
);
2039 exit_code
= process_exit_code(hWaitPID
);
2042 fprintf(stderr
, "make (e=%d, rc=%d): %s",
2043 err
, exit_code
, map_windows32_error_to_string(err
));
2045 /* cleanup process */
2046 process_cleanup(hWaitPID
);
2048 /* expect to find only last pid, warn about other pids reaped */
2049 if (hWaitPID
== hPID
)
2053 _("make reaped child pid %ld, still waiting for pid %ld\n"),
2054 (DWORD
)hWaitPID
, (DWORD
)hPID
);
2057 /* return child's exit code as our exit code */
2060 #else /* !WINDOWS32 */
2066 /* Be the user, permanently. */
2071 /* Run the program. */
2072 pid
= spawnvpe (P_NOWAIT
, argv
[0], argv
, envp
);
2077 /* the file might have a strange shell extension */
2078 if (errno
== ENOENT
)
2083 /* Run the program. */
2085 execvp (argv
[0], argv
);
2087 # endif /* !__EMX__ */
2092 error (NILF
, _("%s: Command not found"), argv
[0]);
2096 /* The file is not executable. Try it as a shell script. */
2097 extern char *getenv ();
2104 /* Do not use $SHELL from the environment */
2105 struct variable
*p
= lookup_variable ("SHELL", 5);
2111 shell
= getenv ("SHELL");
2114 shell
= default_shell
;
2117 while (argv
[argc
] != 0)
2125 new_argv
= alloca ((1 + argc
+ 1) * sizeof (char *));
2126 new_argv
[0] = shell
;
2137 new_argv
[i
] = argv
[0];
2140 new_argv
[i
+ argc
] = argv
[argc
];
2145 pid
= spawnvpe (P_NOWAIT
, shell
, new_argv
, envp
);
2149 execvp (shell
, new_argv
);
2151 if (errno
== ENOENT
)
2152 error (NILF
, _("%s: Shell program not found"), shell
);
2154 perror_with_name ("execvp: ", shell
);
2160 /* this nasty error was driving me nuts :-( */
2161 error (NILF
, _("spawnvpe: environment space might be exhausted"));
2166 perror_with_name ("execvp: ", argv
[0]);
2175 #endif /* !WINDOWS32 */
2178 #else /* On Amiga */
2179 void exec_command (char **argv
)
2184 void clean_tmp (void)
2186 DeleteFile (amiga_bname
);
2189 #endif /* On Amiga */
2192 /* Figure out the argument list necessary to run LINE as a command. Try to
2193 avoid using a shell. This routine handles only ' quoting, and " quoting
2194 when no backslash, $ or ` characters are seen in the quotes. Starting
2195 quotes may be escaped with a backslash. If any of the characters in
2196 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2197 is the first word of a line, the shell is used.
2199 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2200 If *RESTP is NULL, newlines will be ignored.
2202 SHELL is the shell to use, or nil to use the default shell.
2203 IFS is the value of $IFS, or nil (meaning the default). */
2206 construct_command_argv_internal (char *line
, char **restp
, char *shell
,
2207 char *ifs
, char **batch_filename_ptr
)
2210 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2211 We call `system' for anything that requires ``slow'' processing,
2212 because DOS shells are too dumb. When $SHELL points to a real
2213 (unix-style) shell, `system' just calls it to do everything. When
2214 $SHELL points to a DOS shell, `system' does most of the work
2215 internally, calling the shell only for its internal commands.
2216 However, it looks on the $PATH first, so you can e.g. have an
2217 external command named `mkdir'.
2219 Since we call `system', certain characters and commands below are
2220 actually not specific to COMMAND.COM, but to the DJGPP implementation
2221 of `system'. In particular:
2223 The shell wildcard characters are in DOS_CHARS because they will
2224 not be expanded if we call the child via `spawnXX'.
2226 The `;' is in DOS_CHARS, because our `system' knows how to run
2227 multiple commands on a single line.
2229 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2230 won't have to tell one from another and have one more set of
2231 commands and special characters. */
2232 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2233 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2234 "copy", "ctty", "date", "del", "dir", "echo",
2235 "erase", "exit", "for", "goto", "if", "md",
2236 "mkdir", "path", "pause", "prompt", "rd",
2237 "rmdir", "rem", "ren", "rename", "set",
2238 "shift", "time", "type", "ver", "verify",
2241 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2242 static char *sh_cmds_sh
[] = { "cd", "echo", "eval", "exec", "exit", "login",
2243 "logout", "set", "umask", "wait", "while",
2244 "for", "case", "if", ":", ".", "break",
2245 "continue", "export", "read", "readonly",
2246 "shift", "times", "trap", "switch", "unset",
2251 #elif defined (__EMX__)
2252 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2253 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2254 "copy", "ctty", "date", "del", "dir", "echo",
2255 "erase", "exit", "for", "goto", "if", "md",
2256 "mkdir", "path", "pause", "prompt", "rd",
2257 "rmdir", "rem", "ren", "rename", "set",
2258 "shift", "time", "type", "ver", "verify",
2261 static char sh_chars_os2
[] = "*?[];|<>%^()\"'&";
2262 static char *sh_cmds_os2
[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2263 "date", "del", "detach", "dir", "echo",
2264 "endlocal", "erase", "exit", "for", "goto", "if",
2265 "keys", "md", "mkdir", "move", "path", "pause",
2266 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2267 "set", "setlocal", "shift", "start", "time",
2268 "type", "ver", "verify", "vol", ":", 0 };
2270 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^~'";
2271 static char *sh_cmds_sh
[] = { "echo", "cd", "eval", "exec", "exit", "login",
2272 "logout", "set", "umask", "wait", "while",
2273 "for", "case", "if", ":", ".", "break",
2274 "continue", "export", "read", "readonly",
2275 "shift", "times", "trap", "switch", "unset",
2280 #elif defined (_AMIGA)
2281 static char sh_chars
[] = "#;\"|<>()?*$`";
2282 static char *sh_cmds
[] = { "cd", "eval", "if", "delete", "echo", "copy",
2283 "rename", "set", "setenv", "date", "makedir",
2284 "skip", "else", "endif", "path", "prompt",
2285 "unset", "unsetenv", "version",
2287 #elif defined (WINDOWS32)
2288 static char sh_chars_dos
[] = "\"|&<>";
2289 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2290 "copy", "ctty", "date", "del", "dir", "echo",
2291 "erase", "exit", "for", "goto", "if", "if", "md",
2292 "mkdir", "path", "pause", "prompt", "rd", "rem",
2293 "ren", "rename", "rmdir", "set", "shift", "time",
2294 "type", "ver", "verify", "vol", ":", 0 };
2295 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2296 static char *sh_cmds_sh
[] = { "cd", "eval", "exec", "exit", "login",
2297 "logout", "set", "umask", "wait", "while", "for",
2298 "case", "if", ":", ".", "break", "continue",
2299 "export", "read", "readonly", "shift", "times",
2300 "trap", "switch", "test",
2301 #ifdef BATCH_MODE_ONLY_SHELL
2307 #elif defined(__riscos__)
2308 static char sh_chars
[] = "";
2309 static char *sh_cmds
[] = { 0 };
2310 #else /* must be UNIX-ish */
2311 static char sh_chars
[] = "#;\"*?[]&|<>(){}$`^~!";
2312 static char *sh_cmds
[] = { ".", ":", "break", "case", "cd", "continue",
2313 "eval", "exec", "exit", "export", "for", "if",
2314 "login", "logout", "read", "readonly", "set",
2315 "shift", "switch", "test", "times", "trap",
2316 "umask", "wait", "while", 0 };
2317 # ifdef HAVE_DOS_PATHS
2318 /* This is required if the MSYS/Cygwin ports (which do not define
2319 WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
2320 sh_chars_sh[] directly (see below). */
2321 static char *sh_chars_sh
= sh_chars
;
2322 # endif /* HAVE_DOS_PATHS */
2328 int instring
, word_has_equals
, seen_nonequals
, last_argument_was_empty
;
2329 char **new_argv
= 0;
2335 sh_cmds
= sh_cmds_dos
;
2336 sh_chars
= sh_chars_dos
;
2338 sh_cmds
= sh_cmds_sh
;
2339 sh_chars
= sh_chars_sh
;
2341 #endif /* WINDOWS32 */
2346 /* Make sure not to bother processing an empty line. */
2347 while (isblank ((unsigned char)*line
))
2352 /* See if it is safe to parse commands internally. */
2354 shell
= default_shell
;
2356 else if (strcmp (shell
, default_shell
))
2358 char *s1
= _fullpath (NULL
, shell
, 0);
2359 char *s2
= _fullpath (NULL
, default_shell
, 0);
2361 slow_flag
= strcmp ((s1
? s1
: ""), (s2
? s2
: ""));
2370 #else /* not WINDOWS32 */
2371 #if defined (__MSDOS__) || defined (__EMX__)
2372 else if (strcasecmp (shell
, default_shell
))
2374 extern int _is_unixy_shell (const char *_path
);
2376 DB (DB_BASIC
, (_("$SHELL changed (was `%s', now `%s')\n"),
2377 default_shell
, shell
));
2378 unixy_shell
= _is_unixy_shell (shell
);
2379 /* we must allocate a copy of shell: construct_command_argv() will free
2380 * shell after this function returns. */
2381 default_shell
= xstrdup (shell
);
2385 sh_chars
= sh_chars_sh
;
2386 sh_cmds
= sh_cmds_sh
;
2390 sh_chars
= sh_chars_dos
;
2391 sh_cmds
= sh_cmds_dos
;
2393 if (_osmode
== OS2_MODE
)
2395 sh_chars
= sh_chars_os2
;
2396 sh_cmds
= sh_cmds_os2
;
2400 #else /* !__MSDOS__ */
2401 else if (strcmp (shell
, default_shell
))
2403 #endif /* !__MSDOS__ && !__EMX__ */
2404 #endif /* not WINDOWS32 */
2407 for (ap
= ifs
; *ap
!= '\0'; ++ap
)
2408 if (*ap
!= ' ' && *ap
!= '\t' && *ap
!= '\n')
2411 i
= strlen (line
) + 1;
2413 /* More than 1 arg per character is impossible. */
2414 new_argv
= xmalloc (i
* sizeof (char *));
2416 /* All the args can fit in a buffer as big as LINE is. */
2417 ap
= new_argv
[0] = argstr
= xmalloc (i
);
2420 /* I is how many complete arguments have been found. */
2422 instring
= word_has_equals
= seen_nonequals
= last_argument_was_empty
= 0;
2423 for (p
= line
; *p
!= '\0'; ++p
)
2429 /* Inside a string, just copy any char except a closing quote
2430 or a backslash-newline combination. */
2434 if (ap
== new_argv
[0] || *(ap
-1) == '\0')
2435 last_argument_was_empty
= 1;
2437 else if (*p
== '\\' && p
[1] == '\n')
2439 /* Backslash-newline is handled differently depending on what
2440 kind of string we're in: inside single-quoted strings you
2441 keep them; in double-quoted strings they disappear.
2442 For DOS/Windows/OS2, if we don't have a POSIX shell,
2443 we keep the pre-POSIX behavior of removing the
2444 backslash-newline. */
2446 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2456 /* If there's a command prefix char here, skip it. */
2457 if (p
[1] == cmd_prefix
)
2460 else if (*p
== '\n' && restp
!= NULL
)
2462 /* End of the command line. */
2466 /* Backslash, $, and ` are special inside double quotes.
2467 If we see any of those, punt.
2468 But on MSDOS, if we use COMMAND.COM, double and single
2469 quotes have the same effect. */
2470 else if (instring
== '"' && strchr ("\\$`", *p
) != 0 && unixy_shell
)
2475 else if (strchr (sh_chars
, *p
) != 0)
2476 /* Not inside a string, but it's a special char. */
2479 else if (*p
== '.' && p
[1] == '.' && p
[2] == '.' && p
[3] != '.')
2480 /* `...' is a wildcard in DJGPP. */
2484 /* Not a special char. */
2488 /* Equals is a special character in leading words before the
2489 first word with no equals sign in it. This is not the case
2490 with sh -k, but we never get here when using nonstandard
2492 if (! seen_nonequals
&& unixy_shell
)
2494 word_has_equals
= 1;
2499 /* Backslash-newline has special case handling, ref POSIX.
2500 We're in the fastpath, so emulate what the shell would do. */
2503 /* Throw out the backslash and newline. */
2506 /* If there is a command prefix after a backslash-newline,
2508 if (p
[1] == cmd_prefix
)
2511 /* If there's nothing in this argument yet, skip any
2512 whitespace before the start of the next word. */
2513 if (ap
== new_argv
[i
])
2514 p
= next_token (p
+ 1) - 1;
2516 else if (p
[1] != '\0')
2518 #ifdef HAVE_DOS_PATHS
2519 /* Only remove backslashes before characters special to Unixy
2520 shells. All other backslashes are copied verbatim, since
2521 they are probably DOS-style directory separators. This
2522 still leaves a small window for problems, but at least it
2523 should work for the vast majority of naive users. */
2526 /* A dot is only special as part of the "..."
2528 if (strneq (p
+ 1, ".\\.\\.", 5))
2536 if (p
[1] != '\\' && p
[1] != '\''
2537 && !isspace ((unsigned char)p
[1])
2538 && strchr (sh_chars_sh
, p
[1]) == 0)
2539 /* back up one notch, to copy the backslash */
2541 #endif /* HAVE_DOS_PATHS */
2543 /* Copy and skip the following char. */
2556 /* End of the command line. */
2561 /* Newlines are not special. */
2567 /* We have the end of an argument.
2568 Terminate the text of the argument. */
2571 last_argument_was_empty
= 0;
2573 /* Update SEEN_NONEQUALS, which tells us if every word
2574 heretofore has contained an `='. */
2575 seen_nonequals
|= ! word_has_equals
;
2576 if (word_has_equals
&& ! seen_nonequals
)
2577 /* An `=' in a word before the first
2578 word without one is magical. */
2580 word_has_equals
= 0; /* Prepare for the next word. */
2582 /* If this argument is the command name,
2583 see if it is a built-in shell command.
2584 If so, have the shell handle it. */
2588 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2590 if (streq (sh_cmds
[j
], new_argv
[0]))
2593 /* Non-Unix shells are case insensitive. */
2595 && strcasecmp (sh_cmds
[j
], new_argv
[0]) == 0)
2601 /* Ignore multiple whitespace chars. */
2602 p
= next_token (p
) - 1;
2613 /* Let the shell deal with an unterminated quote. */
2616 /* Terminate the last argument and the argument list. */
2619 if (new_argv
[i
][0] != '\0' || last_argument_was_empty
)
2626 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2627 if (streq (sh_cmds
[j
], new_argv
[0]))
2631 if (new_argv
[0] == 0)
2633 /* Line was empty. */
2642 /* We must use the shell. */
2646 /* Free the old argument list we were working on. */
2652 execute_by_shell
= 1; /* actually, call `system' if shell isn't unixy */
2661 buffer
= xmalloc (strlen (line
)+1);
2664 for (dptr
=buffer
; *ptr
; )
2666 if (*ptr
== '\\' && ptr
[1] == '\n')
2668 else if (*ptr
== '@') /* Kludge: multiline commands */
2678 new_argv
= xmalloc (2 * sizeof (char *));
2679 new_argv
[0] = buffer
;
2682 #else /* Not Amiga */
2685 * Not eating this whitespace caused things like
2689 * which gave the shell fits. I think we have to eat
2690 * whitespace here, but this code should be considered
2691 * suspicious if things start failing....
2694 /* Make sure not to bother processing an empty line. */
2695 while (isspace ((unsigned char)*line
))
2699 #endif /* WINDOWS32 */
2701 /* SHELL may be a multi-word command. Construct a command line
2702 "SHELL -c LINE", with all special chars in LINE escaped.
2703 Then recurse, expanding this command line to get the final
2706 unsigned int shell_len
= strlen (shell
);
2708 static char minus_c
[] = " -c ";
2710 static char minus_c
[] = "";
2712 unsigned int line_len
= strlen (line
);
2714 char *new_line
= alloca (shell_len
+ (sizeof (minus_c
)-1)
2715 + (line_len
*2) + 1);
2716 char *command_ptr
= NULL
; /* used for batch_mode_shell mode */
2718 # ifdef __EMX__ /* is this necessary? */
2720 minus_c
[1] = '/'; /* " /c " */
2724 memcpy (ap
, shell
, shell_len
);
2726 memcpy (ap
, minus_c
, sizeof (minus_c
) - 1);
2727 ap
+= sizeof (minus_c
) - 1;
2729 for (p
= line
; *p
!= '\0'; ++p
)
2731 if (restp
!= NULL
&& *p
== '\n')
2736 else if (*p
== '\\' && p
[1] == '\n')
2738 /* POSIX says we keep the backslash-newline, but throw out
2739 the next char if it's a TAB. If we don't have a POSIX
2740 shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
2741 and remove the backslash/newline. */
2742 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2743 # define PRESERVE_BSNL unixy_shell
2745 # define PRESERVE_BSNL 1
2755 if (p
[1] == cmd_prefix
)
2761 /* DOS shells don't know about backslash-escaping. */
2762 if (unixy_shell
&& !batch_mode_shell
&&
2763 (*p
== '\\' || *p
== '\'' || *p
== '"'
2764 || isspace ((unsigned char)*p
)
2765 || strchr (sh_chars
, *p
) != 0))
2768 else if (unixy_shell
&& strneq (p
, "...", 3))
2770 /* The case of `...' wildcard again. */
2771 strcpy (ap
, "\\.\\.\\");
2778 if (ap
== new_line
+ shell_len
+ sizeof (minus_c
) - 1)
2779 /* Line was empty. */
2784 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2785 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2786 cases, run commands via a script file. */
2787 if (just_print_flag
) {
2788 /* Need to allocate new_argv, although it's unused, because
2789 start_job_command will want to free it and its 0'th element. */
2790 new_argv
= xmalloc(2 * sizeof (char *));
2791 new_argv
[0] = xstrdup ("");
2793 } else if ((no_default_sh_exe
|| batch_mode_shell
) && batch_filename_ptr
) {
2796 int id
= GetCurrentProcessId();
2799 /* create a file name */
2800 sprintf(fbuf
, "make%d", id
);
2801 *batch_filename_ptr
= create_batch_file (fbuf
, unixy_shell
, &temp_fd
);
2803 DB (DB_JOBS
, (_("Creating temporary batch file %s\n"),
2804 *batch_filename_ptr
));
2806 /* Create a FILE object for the batch file, and write to it the
2807 commands to be executed. Put the batch file in TEXT mode. */
2808 _setmode (temp_fd
, _O_TEXT
);
2809 batch
= _fdopen (temp_fd
, "wt");
2811 fputs ("@echo off\n", batch
);
2812 fputs (command_ptr
, batch
);
2813 fputc ('\n', batch
);
2817 new_argv
= xmalloc(3 * sizeof (char *));
2819 new_argv
[0] = xstrdup (shell
);
2820 new_argv
[1] = *batch_filename_ptr
; /* only argv[0] gets freed later */
2822 new_argv
[0] = xstrdup (*batch_filename_ptr
);
2827 #endif /* WINDOWS32 */
2829 new_argv
= construct_command_argv_internal (new_line
, 0, 0, 0, 0);
2831 else if (!unixy_shell
)
2833 /* new_line is local, must not be freed therefore
2834 We use line here instead of new_line because we run the shell
2836 size_t line_len
= strlen (line
);
2839 memcpy (new_line
, line
, line_len
+ 1);
2840 /* replace all backslash-newline combination and also following tabs */
2843 if (q
[0] == '\\' && q
[1] == '\n')
2845 q
+= 2; /* remove '\\' and '\n' */
2846 /* Remove any command prefix in the next line */
2847 if (q
[0] == cmd_prefix
)
2855 # ifndef NO_CMD_DEFAULT
2856 if (strnicmp (new_line
, "echo", 4) == 0
2857 && (new_line
[4] == ' ' || new_line
[4] == '\t'))
2859 /* the builtin echo command: handle it separately */
2860 size_t echo_len
= line_len
- 5;
2861 char *echo_line
= new_line
+ 5;
2863 /* special case: echo 'x="y"'
2864 cmd works this way: a string is printed as is, i.e., no quotes
2865 are removed. But autoconf uses a command like echo 'x="y"' to
2866 determine whether make works. autoconf expects the output x="y"
2867 so we will do exactly that.
2868 Note: if we do not allow cmd to be the default shell
2869 we do not need this kind of voodoo */
2870 if (echo_line
[0] == '\''
2871 && echo_line
[echo_len
- 1] == '\''
2872 && strncmp (echo_line
+ 1, "ac_maketemp=",
2873 strlen ("ac_maketemp=")) == 0)
2875 /* remove the enclosing quotes */
2876 memmove (echo_line
, echo_line
+ 1, echo_len
- 2);
2877 echo_line
[echo_len
- 2] = '\0';
2883 /* Let the shell decide what to do. Put the command line into the
2884 2nd command line argument and hope for the best ;-) */
2885 size_t sh_len
= strlen (shell
);
2887 /* exactly 3 arguments + NULL */
2888 new_argv
= xmalloc (4 * sizeof (char *));
2889 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
2890 the trailing '\0' */
2891 new_argv
[0] = xmalloc (sh_len
+ line_len
+ 5);
2892 memcpy (new_argv
[0], shell
, sh_len
+ 1);
2893 new_argv
[1] = new_argv
[0] + sh_len
+ 1;
2894 memcpy (new_argv
[1], "/c", 3);
2895 new_argv
[2] = new_argv
[1] + 3;
2896 memcpy (new_argv
[2], new_line
, line_len
+ 1);
2900 #elif defined(__MSDOS__)
2903 /* With MSDOS shells, we must construct the command line here
2904 instead of recursively calling ourselves, because we
2905 cannot backslash-escape the special characters (see above). */
2906 new_argv
= xmalloc (sizeof (char *));
2907 line_len
= strlen (new_line
) - shell_len
- sizeof (minus_c
) + 1;
2908 new_argv
[0] = xmalloc (line_len
+ 1);
2909 strncpy (new_argv
[0],
2910 new_line
+ shell_len
+ sizeof (minus_c
) - 1, line_len
);
2911 new_argv
[0][line_len
] = '\0';
2915 fatal (NILF
, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2916 __FILE__
, __LINE__
);
2919 #endif /* ! AMIGA */
2925 /* Figure out the argument list necessary to run LINE as a command. Try to
2926 avoid using a shell. This routine handles only ' quoting, and " quoting
2927 when no backslash, $ or ` characters are seen in the quotes. Starting
2928 quotes may be escaped with a backslash. If any of the characters in
2929 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2930 is the first word of a line, the shell is used.
2932 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2933 If *RESTP is NULL, newlines will be ignored.
2935 FILE is the target whose commands these are. It is used for
2936 variable expansion for $(SHELL) and $(IFS). */
2939 construct_command_argv (char *line
, char **restp
, struct file
*file
,
2940 char **batch_filename_ptr
)
2954 && (isspace ((unsigned char)*cptr
)))
2959 && (!isspace((unsigned char)*cptr
)))
2964 argv
= xmalloc (argc
* sizeof (char *));
2973 && (isspace ((unsigned char)*cptr
)))
2977 DB (DB_JOBS
, ("argv[%d] = [%s]\n", argc
, cptr
));
2978 argv
[argc
++] = cptr
;
2980 && (!isspace((unsigned char)*cptr
)))
2987 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2988 int save
= warn_undefined_variables_flag
;
2989 warn_undefined_variables_flag
= 0;
2991 shell
= allocated_variable_expand_for_file ("$(SHELL)", file
);
2994 * Convert to forward slashes so that construct_command_argv_internal()
2998 char *p
= w32ify (shell
, 0);
3004 static const char *unixroot
= NULL
;
3005 static const char *last_shell
= "";
3006 static int init
= 0;
3009 unixroot
= getenv ("UNIXROOT");
3010 /* unixroot must be NULL or not empty */
3011 if (unixroot
&& unixroot
[0] == '\0') unixroot
= NULL
;
3015 /* if we have an unixroot drive and if shell is not default_shell
3016 (which means it's either cmd.exe or the test has already been
3017 performed) and if shell is an absolute path without drive letter,
3018 try whether it exists e.g.: if "/bin/sh" does not exist use
3019 "$UNIXROOT/bin/sh" instead. */
3020 if (unixroot
&& shell
&& strcmp (shell
, last_shell
) != 0
3021 && (shell
[0] == '/' || shell
[0] == '\\'))
3023 /* trying a new shell, check whether it exists */
3024 size_t size
= strlen (shell
);
3025 char *buf
= xmalloc (size
+ 7);
3026 memcpy (buf
, shell
, size
);
3027 memcpy (buf
+ size
, ".exe", 5); /* including the trailing '\0' */
3028 if (access (shell
, F_OK
) != 0 && access (buf
, F_OK
) != 0)
3030 /* try the same for the unixroot drive */
3031 memmove (buf
+ 2, buf
, size
+ 5);
3032 buf
[0] = unixroot
[0];
3033 buf
[1] = unixroot
[1];
3034 if (access (buf
, F_OK
) == 0)
3035 /* we have found a shell! */
3045 #endif /* __EMX__ */
3047 ifs
= allocated_variable_expand_for_file ("$(IFS)", file
);
3049 warn_undefined_variables_flag
= save
;
3052 argv
= construct_command_argv_internal (line
, restp
, shell
, ifs
, batch_filename_ptr
);
3060 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3062 dup2 (int old
, int new)
3077 #endif /* !HAPE_DUP2 && !_AMIGA */
3079 /* On VMS systems, include special VMS functions. */
3082 #include "vmsjobs.c"