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 /* 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 #if !defined(HAVE_UNISTD_H) && !defined(WINDOWS32)
189 /* Different systems have different requirements for pid_t.
190 Plus we have to support gettext string translation... Argh. */
194 static char pidstring
[100];
196 sprintf (pidstring
, "%Id", pid
);
198 sprintf (pidstring
, "%lu", (unsigned long) pid
);
203 int getloadavg (double loadavg
[], int nelem
);
204 int start_remote_job (char **argv
, char **envp
, int stdin_fd
, int *is_remote
,
205 int *id_ptr
, int *used_stdin
);
206 int start_remote_job_p (int);
207 int remote_status (int *exit_code_ptr
, int *signal_ptr
, int *coredump_ptr
,
210 RETSIGTYPE
child_handler (int);
211 static void free_child (struct child
*);
212 static void start_job_command (struct child
*child
);
213 static int load_too_high (void);
214 static int job_next_command (struct child
*);
215 static int start_waiting_job (struct child
*);
217 /* Chain of all live (or recently deceased) children. */
219 struct child
*children
= 0;
221 /* Number of children currently running. */
223 unsigned int job_slots_used
= 0;
225 /* Nonzero if the `good' standard input is in use. */
227 static int good_stdin_used
= 0;
229 /* Chain of children waiting to run until the load average goes down. */
231 static struct child
*waiting_jobs
= 0;
233 /* Non-zero if we use a *real* shell (always so on Unix). */
237 /* Number of jobs started in the current second. */
239 unsigned long job_counter
= 0;
241 /* Number of jobserver tokens this instance is currently using. */
243 unsigned int jobserver_tokens
= 0;
247 * The macro which references this function is defined in make.h.
250 w32_kill(pid_t pid
, int sig
)
252 return ((process_kill((HANDLE
)pid
, sig
) == TRUE
) ? 0 : -1);
255 /* This function creates a temporary file name with an extension specified
257 * Return an xmalloc'ed string of a newly created temp file and its
258 * file descriptor, or die. */
260 create_batch_file (char const *base
, int unixy
, int *fd
)
262 const char *const ext
= unixy
? "sh" : "bat";
263 const char *error_string
= NULL
;
264 char temp_path
[MAXPATHLEN
]; /* need to know its length */
265 unsigned path_size
= GetTempPath(sizeof temp_path
, temp_path
);
268 const unsigned sizemax
= strlen (base
) + strlen (ext
) + 10;
272 path_size
= GetCurrentDirectory (sizeof temp_path
, temp_path
);
276 while (path_size
> 0 &&
277 path_size
+ sizemax
< sizeof temp_path
&&
280 unsigned size
= sprintf (temp_path
+ path_size
,
282 temp_path
[path_size
- 1] == '\\' ? "" : "\\",
284 HANDLE h
= CreateFile (temp_path
, /* file name */
285 GENERIC_READ
| GENERIC_WRITE
, /* desired access */
286 0, /* no share mode */
287 NULL
, /* default security attributes */
288 CREATE_NEW
, /* creation disposition */
289 FILE_ATTRIBUTE_NORMAL
| /* flags and attributes */
290 FILE_ATTRIBUTE_TEMPORARY
, /* we'll delete it */
291 NULL
); /* no template file */
293 if (h
== INVALID_HANDLE_VALUE
)
295 const DWORD er
= GetLastError();
297 if (er
== ERROR_FILE_EXISTS
|| er
== ERROR_ALREADY_EXISTS
)
300 /* the temporary path is not guaranteed to exist */
301 else if (path_is_dot
== 0)
303 path_size
= GetCurrentDirectory (sizeof temp_path
, temp_path
);
309 error_string
= map_windows32_error_to_string (er
);
315 const unsigned final_size
= path_size
+ size
+ 1;
316 char *const path
= xmalloc (final_size
);
317 memcpy (path
, temp_path
, final_size
);
318 *fd
= _open_osfhandle ((intptr_t)h
, 0);
323 for (p
= path
; (ch
= *p
) != 0; ++p
)
327 return path
; /* good return */
332 if (error_string
== NULL
)
333 error_string
= _("Cannot create a temporary file\n");
334 fatal (NILF
, error_string
);
339 #endif /* WINDOWS32 */
342 /* returns whether path is assumed to be a unix like shell. */
344 _is_unixy_shell (const char *path
)
346 /* list of non unix shells */
347 const char *known_os2shells
[] = {
359 /* find the rightmost '/' or '\\' */
360 const char *name
= strrchr (path
, '/');
361 const char *p
= strrchr (path
, '\\');
364 if (name
&& p
) /* take the max */
365 name
= (name
> p
) ? name
: p
;
366 else if (p
) /* name must be 0 */
368 else if (!name
) /* name and p must be 0 */
371 if (*name
== '/' || *name
== '\\') name
++;
374 while (known_os2shells
[i
] != NULL
) {
375 if (strcasecmp (name
, known_os2shells
[i
]) == 0)
376 return 0; /* not a unix shell */
380 /* in doubt assume a unix like shell */
385 /* determines whether path looks to be a Bourne-like shell. */
387 is_bourne_compatible_shell (const char *path
)
389 /* list of known unix (Bourne-like) shells */
390 const char *unix_shells
[] = {
402 /* find the rightmost '/' or '\\' */
403 const char *name
= strrchr (path
, '/');
404 char *p
= strrchr (path
, '\\');
406 if (name
&& p
) /* take the max */
407 name
= (name
> p
) ? name
: p
;
408 else if (p
) /* name must be 0 */
410 else if (!name
) /* name and p must be 0 */
413 if (*name
== '/' || *name
== '\\') name
++;
415 /* this should be able to deal with extensions on Windows-like systems */
416 for (i
= 0; unix_shells
[i
] != NULL
; i
++) {
417 len
= strlen(unix_shells
[i
]);
418 #if defined(WINDOWS32) || defined(__MSDOS__)
419 if ((strncasecmp (name
, unix_shells
[i
], len
) == 0) &&
420 (strlen(name
) >= len
&& (name
[len
] == '\0' || name
[len
] == '.')))
422 if ((strncmp (name
, unix_shells
[i
], len
) == 0) &&
423 (strlen(name
) >= len
&& name
[len
] == '\0'))
425 return 1; /* a known unix-style shell */
428 /* if not on the list, assume it's not a Bourne-like shell */
433 /* Write an error message describing the exit status given in
434 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
435 Append "(ignored)" if IGNORED is nonzero. */
438 child_error (const char *target_name
,
439 int exit_code
, int exit_sig
, int coredump
, int ignored
)
441 if (ignored
&& silent_flag
)
445 if (!(exit_code
& 1))
447 (ignored
? _("*** [%s] Error 0x%x (ignored)")
448 : _("*** [%s] Error 0x%x")),
449 target_name
, exit_code
);
452 error (NILF
, ignored
? _("[%s] Error %d (ignored)") :
453 _("*** [%s] Error %d"),
454 target_name
, exit_code
);
456 error (NILF
, "*** [%s] %s%s",
457 target_name
, strsignal (exit_sig
),
458 coredump
? _(" (core dumped)") : "");
463 /* Handle a dead child. This handler may or may not ever be installed.
465 If we're using the jobserver feature, we need it. First, installing it
466 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
467 read FD to ensure we don't enter another blocking read without reaping all
468 the dead children. In this case we don't need the dead_children count.
470 If we don't have either waitpid or wait3, then make is unreliable, but we
471 use the dead_children count to reap children as best we can. */
473 static unsigned int dead_children
= 0;
476 child_handler (int sig UNUSED
)
487 /* The signal handler must called only once! */
488 signal (SIGCHLD
, SIG_DFL
);
491 /* This causes problems if the SIGCHLD interrupts a printf().
492 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
496 extern int shell_function_pid
, shell_function_completed
;
498 /* Reap all dead children, storing the returned status and the new command
499 state (`cs_finished') in the `file' member of the `struct child' for the
500 dead child, and removing the child from the chain. In addition, if BLOCK
501 nonzero, we block in this function until we've reaped at least one
502 complete child, waiting for it to die if necessary. If ERR is nonzero,
503 print an error message first. */
506 reap_children (int block
, int err
)
510 /* Initially, assume we have some. */
515 # define REAP_MORE reap_more
517 # define REAP_MORE dead_children
522 We have at least one child outstanding OR a shell function in progress,
524 We're blocking for a complete child OR there are more children to reap
526 we'll keep reaping children. */
528 while ((children
!= 0 || shell_function_pid
!= 0)
529 && (block
|| REAP_MORE
))
533 int exit_code
, exit_sig
, coredump
;
534 register struct child
*lastc
, *c
;
536 int any_remote
, any_local
;
541 static int printed
= 0;
543 /* We might block for a while, so let the user know why.
544 Only print this message once no matter how many jobs are left. */
547 error (NILF
, _("*** Waiting for unfinished jobs...."));
551 /* We have one less dead child to reap. As noted in
552 child_handler() above, this count is completely unimportant for
553 all modern, POSIX-y systems that support wait3() or waitpid().
554 The rest of this comment below applies only to early, broken
555 pre-POSIX systems. We keep the count only because... it's there...
557 The test and decrement are not atomic; if it is compiled into:
558 register = dead_children - 1;
559 dead_children = register;
560 a SIGCHLD could come between the two instructions.
561 child_handler increments dead_children.
562 The second instruction here would lose that increment. But the
563 only effect of dead_children being wrong is that we might wait
564 longer than necessary to reap a child, and lose some parallelism;
565 and we might print the "Waiting for unfinished jobs" message above
566 when not necessary. */
568 if (dead_children
> 0)
572 any_local
= shell_function_pid
!= 0;
573 for (c
= children
; c
!= 0; c
= c
->next
)
575 any_remote
|= c
->remote
;
576 any_local
|= ! c
->remote
;
577 DB (DB_JOBS
, (_("Live child %p (%s) PID %s %s\n"),
578 c
, c
->file
->name
, pid2str (c
->pid
),
579 c
->remote
? _(" (remote)") : ""));
585 /* First, check for remote children. */
587 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 0);
592 /* We got a remote child. */
596 /* A remote status command failed miserably. Punt. */
598 pfatal_with_name ("remote_status");
602 /* No remote children. Check for local children. */
603 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
607 vmsWaitForChildren (&status
);
612 pid
= WAIT_NOHANG (&status
);
615 EINTRLOOP(pid
, wait (&status
));
623 /* The wait*() failed miserably. Punt. */
624 pfatal_with_name ("wait");
628 /* We got a child exit; chop the status word up. */
629 exit_code
= WEXITSTATUS (status
);
630 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
631 coredump
= WCOREDUMP (status
);
633 /* If we have started jobs in this second, remove one. */
639 /* No local children are dead. */
642 if (!block
|| !any_remote
)
645 /* Now try a blocking wait for a remote child. */
646 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 1);
648 goto remote_status_lose
;
650 /* No remote children either. Finally give up. */
653 /* We got a remote child. */
656 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
659 /* Life is very different on MSDOS. */
662 exit_code
= WEXITSTATUS (status
);
663 if (exit_code
== 0xff)
665 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
667 #endif /* __MSDOS__ */
671 status
= amiga_status
;
672 exit_code
= amiga_status
;
685 /* Record the thread ID of the main process, so that we
686 could suspend it in the signal handler. */
689 hcTID
= GetCurrentThread ();
690 hcPID
= GetCurrentProcess ();
691 if (!DuplicateHandle (hcPID
, hcTID
, hcPID
, &main_thread
, 0,
692 FALSE
, DUPLICATE_SAME_ACCESS
))
694 DWORD e
= GetLastError ();
696 "Determine main thread ID (Error %ld: %s)\n",
697 e
, map_windows32_error_to_string(e
));
700 DB (DB_VERBOSE
, ("Main thread handle = %p\n", main_thread
));
703 /* wait for anything to finish */
704 hPID
= process_wait_for_any();
708 /* was an error found on this process? */
709 werr
= process_last_err(hPID
);
712 exit_code
= process_exit_code(hPID
);
715 fprintf(stderr
, "make (e=%d): %s",
716 exit_code
, map_windows32_error_to_string(exit_code
));
719 exit_sig
= process_signal(hPID
);
721 /* cleanup process */
722 process_cleanup(hPID
);
728 #endif /* WINDOWS32 */
731 /* Check if this is the child of the `shell' function. */
732 if (!remote
&& pid
== shell_function_pid
)
734 /* It is. Leave an indicator for the `shell' function. */
735 if (exit_sig
== 0 && exit_code
== 127)
736 shell_function_completed
= -1;
738 shell_function_completed
= 1;
742 child_failed
= exit_sig
!= 0 || exit_code
!= 0;
744 /* Search for a child matching the deceased one. */
746 for (c
= children
; c
!= 0; lastc
= c
, c
= c
->next
)
747 if (c
->remote
== remote
&& c
->pid
== pid
)
751 /* An unknown child died.
752 Ignore it; it was inherited from our invoker. */
755 DB (DB_JOBS
, (child_failed
756 ? _("Reaping losing child %p PID %s %s\n")
757 : _("Reaping winning child %p PID %s %s\n"),
758 c
, pid2str (c
->pid
), c
->remote
? _(" (remote)") : ""));
760 if (c
->sh_batch_file
) {
761 DB (DB_JOBS
, (_("Cleaning up temp batch file %s\n"),
764 /* just try and remove, don't care if this fails */
765 remove (c
->sh_batch_file
);
767 /* all done with memory */
768 free (c
->sh_batch_file
);
769 c
->sh_batch_file
= NULL
;
772 /* If this child had the good stdin, say it is now free. */
776 dontcare
= c
->dontcare
;
778 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
780 /* The commands failed. Write an error message,
781 delete non-precious targets, and abort. */
782 static int delete_on_error
= -1;
785 child_error (c
->file
->name
, exit_code
, exit_sig
, coredump
, 0);
787 c
->file
->update_status
= 2;
788 if (delete_on_error
== -1)
790 struct file
*f
= lookup_file (".DELETE_ON_ERROR");
791 delete_on_error
= f
!= 0 && f
->is_target
;
793 if (exit_sig
!= 0 || delete_on_error
)
794 delete_child_targets (c
);
800 /* The commands failed, but we don't care. */
801 child_error (c
->file
->name
,
802 exit_code
, exit_sig
, coredump
, 1);
806 /* If there are more commands to run, try to start them. */
807 if (job_next_command (c
))
809 if (handling_fatal_signal
)
811 /* Never start new commands while we are dying.
812 Since there are more commands that wanted to be run,
813 the target was not completely remade. So we treat
814 this as if a command had failed. */
815 c
->file
->update_status
= 2;
819 /* Check again whether to start remotely.
820 Whether or not we want to changes over time.
821 Also, start_remote_job may need state set up
822 by start_remote_job_p. */
823 c
->remote
= start_remote_job_p (0);
824 start_job_command (c
);
825 /* Fatal signals are left blocked in case we were
826 about to put that child on the chain. But it is
827 already there, so it is safe for a fatal signal to
828 arrive now; it will clean up this child's targets. */
830 if (c
->file
->command_state
== cs_running
)
831 /* We successfully started the new command.
832 Loop to reap more children. */
836 if (c
->file
->update_status
!= 0)
837 /* We failed to start the commands. */
838 delete_child_targets (c
);
841 /* There are no more commands. We got through them all
842 without an unignored error. Now the target has been
843 successfully updated. */
844 c
->file
->update_status
= 0;
847 /* When we get here, all the commands for C->file are finished
848 (or aborted) and C->file->update_status contains 0 or 2. But
849 C->file->command_state is still cs_running if all the commands
850 ran; notice_finish_file looks for cs_running to tell it that
851 it's interesting to check the file's modtime again now. */
853 if (! handling_fatal_signal
)
854 /* Notice if the target of the commands has been changed.
855 This also propagates its values for command_state and
856 update_status to its also_make files. */
857 notice_finished_file (c
->file
);
859 DB (DB_JOBS
, (_("Removing child %p PID %s%s from chain.\n"),
860 c
, pid2str (c
->pid
), c
->remote
? _(" (remote)") : ""));
862 /* Block fatal signals while frobnicating the list, so that
863 children and job_slots_used are always consistent. Otherwise
864 a fatal signal arriving after the child is off the chain and
865 before job_slots_used is decremented would believe a child was
866 live and call reap_children again. */
869 /* There is now another slot open. */
870 if (job_slots_used
> 0)
873 /* Remove the child from the chain and free it. */
877 lastc
->next
= c
->next
;
883 /* If the job failed, and the -k flag was not given, die,
884 unless we are already in the process of dying. */
885 if (!err
&& child_failed
&& !dontcare
&& !keep_going_flag
&&
886 /* fatal_error_signal will die with the right signal. */
887 !handling_fatal_signal
)
890 /* Only block for one child. */
897 /* Free the storage allocated for CHILD. */
900 free_child (struct child
*child
)
902 if (!jobserver_tokens
)
903 fatal (NILF
, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
904 child
, child
->file
->name
);
906 /* If we're using the jobserver and this child is not the only outstanding
907 job, put a token back into the pipe for it. */
909 if (job_fds
[1] >= 0 && jobserver_tokens
> 1)
914 /* Write a job token back to the pipe. */
916 EINTRLOOP (r
, write (job_fds
[1], &token
, 1));
918 pfatal_with_name (_("write jobserver"));
920 DB (DB_JOBS
, (_("Released token for child %p (%s).\n"),
921 child
, child
->file
->name
));
926 if (handling_fatal_signal
) /* Don't bother free'ing if about to die. */
929 if (child
->command_lines
!= 0)
931 register unsigned int i
;
932 for (i
= 0; i
< child
->file
->cmds
->ncommand_lines
; ++i
)
933 free (child
->command_lines
[i
]);
934 free (child
->command_lines
);
937 if (child
->environment
!= 0)
939 register char **ep
= child
->environment
;
942 free (child
->environment
);
949 extern sigset_t fatal_signal_set
;
956 (void) sigprocmask (SIG_BLOCK
, &fatal_signal_set
, (sigset_t
*) 0);
958 # ifdef HAVE_SIGSETMASK
959 (void) sigblock (fatal_signal_mask
);
969 sigemptyset (&empty
);
970 sigprocmask (SIG_SETMASK
, &empty
, (sigset_t
*) 0);
974 #ifdef MAKE_JOBSERVER
976 job_noop (int sig UNUSED
)
979 /* Set the child handler action flags to FLAGS. */
981 set_child_handler_action_flags (int set_handler
, int set_alarm
)
986 /* The child handler must be turned off here. */
987 signal (SIGCHLD
, SIG_DFL
);
990 memset (&sa
, '\0', sizeof sa
);
991 sa
.sa_handler
= child_handler
;
992 sa
.sa_flags
= set_handler
? 0 : SA_RESTART
;
994 sigaction (SIGCHLD
, &sa
, NULL
);
996 #if defined SIGCLD && SIGCLD != SIGCHLD
997 sigaction (SIGCLD
, &sa
, NULL
);
1002 /* If we're about to enter the read(), set an alarm to wake up in a
1003 second so we can check if the load has dropped and we can start more
1004 work. On the way out, turn off the alarm and set SIG_DFL. */
1005 alarm (set_handler
? 1 : 0);
1006 sa
.sa_handler
= set_handler
? job_noop
: SIG_DFL
;
1008 sigaction (SIGALRM
, &sa
, NULL
);
1015 /* Start a job to run the commands specified in CHILD.
1016 CHILD is updated to reflect the commands and ID of the child process.
1018 NOTE: On return fatal signals are blocked! The caller is responsible
1019 for calling `unblock_sigs', once the new child is safely on the chain so
1020 it can be cleaned up in the event of a fatal signal. */
1023 start_job_command (struct child
*child
)
1025 #if !defined(_AMIGA) && !defined(WINDOWS32)
1026 static int bad_stdin
= -1;
1029 /* Must be volatile to silence bogus GCC warning about longjmp/vfork. */
1037 /* If we have a completely empty commandset, stop now. */
1038 if (!child
->command_ptr
)
1041 /* Combine the flags parsed for the line itself with
1042 the flags specified globally for this target. */
1043 flags
= (child
->file
->command_flags
1044 | child
->file
->cmds
->lines_flags
[child
->command_line
- 1]);
1046 p
= child
->command_ptr
;
1047 child
->noerror
= ((flags
& COMMANDS_NOERROR
) != 0);
1052 flags
|= COMMANDS_SILENT
;
1054 flags
|= COMMANDS_RECURSE
;
1057 else if (!isblank ((unsigned char)*p
))
1062 /* Update the file's command flags with any new ones we found. We only
1063 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
1064 now marking more commands recursive than should be in the case of
1065 multiline define/endef scripts where only one line is marked "+". In
1066 order to really fix this, we'll have to keep a lines_flags for every
1067 actual line, after expansion. */
1068 child
->file
->cmds
->lines_flags
[child
->command_line
- 1]
1069 |= flags
& COMMANDS_RECURSE
;
1071 /* Figure out an argument list from this command line. */
1078 argv
= construct_command_argv (p
, &end
, child
->file
,
1079 child
->file
->cmds
->lines_flags
[child
->command_line
- 1],
1080 &child
->sh_batch_file
);
1083 child
->command_ptr
= NULL
;
1087 child
->command_ptr
= end
;
1091 /* If -q was given, say that updating `failed' if there was any text on the
1092 command line, or `succeeded' otherwise. The exit status of 1 tells the
1093 user that -q is saying `something to do'; the exit status for a random
1095 if (argv
!= 0 && question_flag
&& !(flags
& COMMANDS_RECURSE
))
1101 child
->file
->update_status
= 1;
1102 notice_finished_file (child
->file
);
1106 if (touch_flag
&& !(flags
& COMMANDS_RECURSE
))
1108 /* Go on to the next command. It might be the recursive one.
1109 We construct ARGV only to find the end of the command line. */
1124 execute_by_shell
= 0; /* in case construct_command_argv sets it */
1126 /* This line has no commands. Go to the next. */
1127 if (job_next_command (child
))
1128 start_job_command (child
);
1131 /* No more commands. Make sure we're "running"; we might not be if
1132 (e.g.) all commands were skipped due to -n. */
1133 set_command_state (child
->file
, cs_running
);
1134 child
->file
->update_status
= 0;
1135 notice_finished_file (child
->file
);
1140 /* Print out the command. If silent, we call `message' with null so it
1141 can log the working directory before the command's own error messages
1144 message (0, (just_print_flag
|| (!(flags
& COMMANDS_SILENT
) && !silent_flag
))
1145 ? "%s" : (char *) 0, p
);
1147 /* Tell update_goal_chain that a command has been started on behalf of
1148 this target. It is important that this happens here and not in
1149 reap_children (where we used to do it), because reap_children might be
1150 reaping children from a different target. We want this increment to
1151 guaranteedly indicate that a command was started for the dependency
1152 chain (i.e., update_file recursion chain) we are processing. */
1156 /* Optimize an empty command. People use this for timestamp rules,
1157 so avoid forking a useless shell. Do this after we increment
1158 commands_started so make still treats this special case as if it
1159 performed some action (makes a difference as to what messages are
1162 #if !defined(VMS) && !defined(_AMIGA)
1164 #if defined __MSDOS__ || defined (__EMX__)
1165 unixy_shell
/* the test is complicated and we already did it */
1167 (argv
[0] && is_bourne_compatible_shell(argv
[0]))
1169 && (argv
[1] && argv
[1][0] == '-'
1171 ((argv
[1][1] == 'c' && argv
[1][2] == '\0')
1173 (argv
[1][1] == 'e' && argv
[1][2] == 'c' && argv
[1][3] == '\0')))
1174 && (argv
[2] && argv
[2][0] == ':' && argv
[2][1] == '\0')
1181 #endif /* !VMS && !_AMIGA */
1183 /* If -n was given, recurse to get the next line in the sequence. */
1185 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
))
1194 /* Flush the output streams so they won't have things written twice. */
1200 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1202 /* Set up a bad standard input that reads from a broken pipe. */
1204 if (bad_stdin
== -1)
1206 /* Make a file descriptor that is the read end of a broken pipe.
1207 This will be used for some children's standard inputs. */
1211 /* Close the write side. */
1212 (void) close (pd
[1]);
1213 /* Save the read side. */
1216 /* Set the descriptor to close on exec, so it does not litter any
1217 child's descriptor table. When it is dup2'd onto descriptor 0,
1218 that descriptor will not close on exec. */
1219 CLOSE_ON_EXEC (bad_stdin
);
1223 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1225 /* Decide whether to give this child the `good' standard input
1226 (one that points to the terminal or whatever), or the `bad' one
1227 that points to the read side of a broken pipe. */
1229 child
->good_stdin
= !good_stdin_used
;
1230 if (child
->good_stdin
)
1231 good_stdin_used
= 1;
1238 /* Set up the environment for the child. */
1239 if (child
->environment
== 0)
1240 child
->environment
= target_environment (child
->file
);
1243 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1246 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1249 int is_remote
, id
, used_stdin
;
1250 if (start_remote_job (argv
, child
->environment
,
1251 child
->good_stdin
? 0 : bad_stdin
,
1252 &is_remote
, &id
, &used_stdin
))
1253 /* Don't give up; remote execution may fail for various reasons. If
1254 so, simply run the job locally. */
1258 if (child
->good_stdin
&& !used_stdin
)
1260 child
->good_stdin
= 0;
1261 good_stdin_used
= 0;
1263 child
->remote
= is_remote
;
1270 /* Fork the child process. */
1272 char **parent_environ
;
1280 if (!child_execute_job (argv
, child
)) {
1282 perror_with_name ("vfork", "");
1288 parent_environ
= environ
;
1291 /* If we aren't running a recursive command and we have a jobserver
1292 pipe, close it before exec'ing. */
1293 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1295 CLOSE_ON_EXEC (job_fds
[0]);
1296 CLOSE_ON_EXEC (job_fds
[1]);
1299 CLOSE_ON_EXEC (job_rfd
);
1301 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1302 child
->pid
= child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1303 argv
, child
->environment
);
1308 perror_with_name ("spawn", "");
1312 /* undo CLOSE_ON_EXEC() after the child process has been started */
1313 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1315 fcntl (job_fds
[0], F_SETFD
, 0);
1316 fcntl (job_fds
[1], F_SETFD
, 0);
1319 fcntl (job_rfd
, F_SETFD
, 0);
1321 #else /* !__EMX__ */
1323 child
->pid
= vfork ();
1324 environ
= parent_environ
; /* Restore value child may have clobbered. */
1325 if (child
->pid
== 0)
1327 /* We are the child side. */
1330 /* If we aren't running a recursive command and we have a jobserver
1331 pipe, close it before exec'ing. */
1332 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1340 #ifdef SET_STACK_SIZE
1341 /* Reset limits, if necessary. */
1342 if (stack_limit
.rlim_cur
)
1343 setrlimit (RLIMIT_STACK
, &stack_limit
);
1346 child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1347 argv
, child
->environment
);
1349 else if (child
->pid
< 0)
1353 perror_with_name ("vfork", "");
1356 # endif /* !__EMX__ */
1360 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1368 /* We call `system' to do the job of the SHELL, since stock DOS
1369 shell is too dumb. Our `system' knows how to handle long
1370 command lines even if pipes/redirection is needed; it will only
1371 call COMMAND.COM when its internal commands are used. */
1372 if (execute_by_shell
)
1374 char *cmdline
= argv
[0];
1375 /* We don't have a way to pass environment to `system',
1376 so we need to save and restore ours, sigh... */
1377 char **parent_environ
= environ
;
1379 environ
= child
->environment
;
1381 /* If we have a *real* shell, tell `system' to call
1382 it to do everything for us. */
1385 /* A *real* shell on MSDOS may not support long
1386 command lines the DJGPP way, so we must use `system'. */
1387 cmdline
= argv
[2]; /* get past "shell -c" */
1390 dos_command_running
= 1;
1391 proc_return
= system (cmdline
);
1392 environ
= parent_environ
;
1393 execute_by_shell
= 0; /* for the next time */
1397 dos_command_running
= 1;
1398 proc_return
= spawnvpe (P_WAIT
, argv
[0], argv
, child
->environment
);
1401 /* Need to unblock signals before turning off
1402 dos_command_running, so that child's signals
1403 will be treated as such (see fatal_error_signal). */
1405 dos_command_running
= 0;
1407 /* If the child got a signal, dos_status has its
1408 high 8 bits set, so be careful not to alter them. */
1409 if (proc_return
== -1)
1412 dos_status
|= (proc_return
& 0xff);
1414 child
->pid
= dos_pid
++;
1416 #endif /* __MSDOS__ */
1418 amiga_status
= MyExecute (argv
);
1421 child
->pid
= amiga_pid
++;
1422 if (amiga_batch_file
)
1424 amiga_batch_file
= 0;
1425 DeleteFile (amiga_bname
); /* Ignore errors. */
1433 /* make UNC paths safe for CreateProcess -- backslash format */
1435 if (arg0
&& arg0
[0] == '/' && arg0
[1] == '/')
1436 for ( ; arg0
&& *arg0
; arg0
++)
1440 /* make sure CreateProcess() has Path it needs */
1441 sync_Path_environment();
1443 hPID
= process_easy(argv
, child
->environment
);
1445 if (hPID
!= INVALID_HANDLE_VALUE
)
1446 child
->pid
= (pid_t
) hPID
;
1451 _("process_easy() failed to launch process (e=%ld)\n"),
1452 process_last_err(hPID
));
1453 for (i
= 0; argv
[i
]; i
++)
1454 fprintf(stderr
, "%s ", argv
[i
]);
1455 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
1459 #endif /* WINDOWS32 */
1460 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1462 /* Bump the number of jobs started in this second. */
1465 /* We are the parent side. Set the state to
1466 say the commands are running and return. */
1468 set_command_state (child
->file
, cs_running
);
1470 /* Free the storage used by the child's argument list. */
1479 child
->file
->update_status
= 2;
1480 notice_finished_file (child
->file
);
1484 /* Try to start a child running.
1485 Returns nonzero if the child was started (and maybe finished), or zero if
1486 the load was too high and the child was put on the `waiting_jobs' chain. */
1489 start_waiting_job (struct child
*c
)
1491 struct file
*f
= c
->file
;
1493 /* If we can start a job remotely, we always want to, and don't care about
1494 the local load average. We record that the job should be started
1495 remotely in C->remote for start_job_command to test. */
1497 c
->remote
= start_remote_job_p (1);
1499 /* If we are running at least one job already and the load average
1500 is too high, make this one wait. */
1502 && ((job_slots_used
> 0 && load_too_high ())
1504 || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS
)
1508 /* Put this child on the chain of children waiting for the load average
1510 set_command_state (f
, cs_running
);
1511 c
->next
= waiting_jobs
;
1516 /* Start the first command; reap_children will run later command lines. */
1517 start_job_command (c
);
1519 switch (f
->command_state
)
1523 DB (DB_JOBS
, (_("Putting child %p (%s) PID %s%s on the chain.\n"),
1524 c
, c
->file
->name
, pid2str (c
->pid
),
1525 c
->remote
? _(" (remote)") : ""));
1527 /* One more job slot is in use. */
1532 case cs_not_started
:
1533 /* All the command lines turned out to be empty. */
1534 f
->update_status
= 0;
1538 notice_finished_file (f
);
1543 assert (f
->command_state
== cs_finished
);
1550 /* Create a `struct child' for FILE and start its commands running. */
1553 new_job (struct file
*file
)
1555 struct commands
*cmds
= file
->cmds
;
1560 /* Let any previously decided-upon jobs that are waiting
1561 for the load to go down start before this new one. */
1562 start_waiting_jobs ();
1564 /* Reap any children that might have finished recently. */
1565 reap_children (0, 0);
1567 /* Chop the commands up into lines if they aren't already. */
1568 chop_commands (cmds
);
1570 /* Expand the command lines and store the results in LINES. */
1571 lines
= xmalloc (cmds
->ncommand_lines
* sizeof (char *));
1572 for (i
= 0; i
< cmds
->ncommand_lines
; ++i
)
1574 /* Collapse backslash-newline combinations that are inside variable
1575 or function references. These are left alone by the parser so
1576 that they will appear in the echoing of commands (where they look
1577 nice); and collapsed by construct_command_argv when it tokenizes.
1578 But letting them survive inside function invocations loses because
1579 we don't want the functions to see them as part of the text. */
1581 char *in
, *out
, *ref
;
1583 /* IN points to where in the line we are scanning.
1584 OUT points to where in the line we are writing.
1585 When we collapse a backslash-newline combination,
1586 IN gets ahead of OUT. */
1588 in
= out
= cmds
->command_lines
[i
];
1589 while ((ref
= strchr (in
, '$')) != 0)
1591 ++ref
; /* Move past the $. */
1594 /* Copy the text between the end of the last chunk
1595 we processed (where IN points) and the new chunk
1596 we are about to process (where REF points). */
1597 memmove (out
, in
, ref
- in
);
1599 /* Move both pointers past the boring stuff. */
1603 if (*ref
== '(' || *ref
== '{')
1605 char openparen
= *ref
;
1606 char closeparen
= openparen
== '(' ? ')' : '}';
1610 *out
++ = *in
++; /* Copy OPENPAREN. */
1611 /* IN now points past the opening paren or brace.
1612 Count parens or braces until it is matched. */
1616 if (*in
== closeparen
&& --count
< 0)
1618 else if (*in
== '\\' && in
[1] == '\n')
1620 /* We have found a backslash-newline inside a
1621 variable or function reference. Eat it and
1622 any following whitespace. */
1625 for (p
= in
- 1; p
> ref
&& *p
== '\\'; --p
)
1629 /* There were two or more backslashes, so this is
1630 not really a continuation line. We don't collapse
1631 the quoting backslashes here as is done in
1632 collapse_continuations, because the line will
1633 be collapsed again after expansion. */
1637 /* Skip the backslash, newline and
1638 any following whitespace. */
1639 in
= next_token (in
+ 2);
1641 /* Discard any preceding whitespace that has
1642 already been written to the output. */
1644 && isblank ((unsigned char)out
[-1]))
1647 /* Replace it all with a single space. */
1653 if (*in
== openparen
)
1662 /* There are no more references in this line to worry about.
1663 Copy the remaining uninteresting text to the output. */
1665 memmove (out
, in
, strlen (in
) + 1);
1667 /* Finally, expand the line. */
1668 lines
[i
] = allocated_variable_expand_for_file (cmds
->command_lines
[i
],
1672 /* Start the command sequence, record it in a new
1673 `struct child', and add that to the chain. */
1675 c
= xcalloc (sizeof (struct child
));
1677 c
->command_lines
= lines
;
1678 c
->sh_batch_file
= NULL
;
1680 /* Cache dontcare flag because file->dontcare can be changed once we
1681 return. Check dontcare inheritance mechanism for details. */
1682 c
->dontcare
= file
->dontcare
;
1684 /* Fetch the first command line to be run. */
1685 job_next_command (c
);
1687 /* Wait for a job slot to be freed up. If we allow an infinite number
1688 don't bother; also job_slots will == 0 if we're using the jobserver. */
1691 while (job_slots_used
== job_slots
)
1692 reap_children (1, 0);
1694 #ifdef MAKE_JOBSERVER
1695 /* If we are controlling multiple jobs make sure we have a token before
1696 starting the child. */
1698 /* This can be inefficient. There's a decent chance that this job won't
1699 actually have to run any subprocesses: the command script may be empty
1700 or otherwise optimized away. It would be nice if we could defer
1701 obtaining a token until just before we need it, in start_job_command.
1702 To do that we'd need to keep track of whether we'd already obtained a
1703 token (since start_job_command is called for each line of the job, not
1704 just once). Also more thought needs to go into the entire algorithm;
1705 this is where the old parallel job code waits, so... */
1707 else if (job_fds
[0] >= 0)
1714 DB (DB_JOBS
, ("Need a job token; we %shave children\n",
1715 children
? "" : "don't "));
1717 /* If we don't already have a job started, use our "free" token. */
1718 if (!jobserver_tokens
)
1721 /* Read a token. As long as there's no token available we'll block.
1722 We enable interruptible system calls before the read(2) so that if
1723 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1724 we can process the death(s) and return tokens to the free pool.
1726 Once we return from the read, we immediately reinstate restartable
1727 system calls. This allows us to not worry about checking for
1728 EINTR on all the other system calls in the program.
1730 There is one other twist: there is a span between the time
1731 reap_children() does its last check for dead children and the time
1732 the read(2) call is entered, below, where if a child dies we won't
1733 notice. This is extremely serious as it could cause us to
1734 deadlock, given the right set of events.
1736 To avoid this, we do the following: before we reap_children(), we
1737 dup(2) the read FD on the jobserver pipe. The read(2) call below
1738 uses that new FD. In the signal handler, we close that FD. That
1739 way, if a child dies during the section mentioned above, the
1740 read(2) will be invoked with an invalid FD and will return
1741 immediately with EBADF. */
1743 /* Make sure we have a dup'd FD. */
1746 DB (DB_JOBS
, ("Duplicate the job FD\n"));
1747 job_rfd
= dup (job_fds
[0]);
1750 /* Reap anything that's currently waiting. */
1751 reap_children (0, 0);
1753 /* Kick off any jobs we have waiting for an opportunity that
1754 can run now (ie waiting for load). */
1755 start_waiting_jobs ();
1757 /* If our "free" slot has become available, use it; we don't need an
1759 if (!jobserver_tokens
)
1762 /* There must be at least one child already, or we have no business
1763 waiting for a token. */
1765 fatal (NILF
, "INTERNAL: no children as we go to sleep on read\n");
1767 /* Set interruptible system calls, and read() for a job token. */
1768 set_child_handler_action_flags (1, waiting_jobs
!= NULL
);
1769 got_token
= read (job_rfd
, &token
, 1);
1770 saved_errno
= errno
;
1771 set_child_handler_action_flags (0, waiting_jobs
!= NULL
);
1773 /* If we got one, we're done here. */
1776 DB (DB_JOBS
, (_("Obtained token for child %p (%s).\n"),
1781 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1782 go back and reap_children(), and try again. */
1783 errno
= saved_errno
;
1784 if (errno
!= EINTR
&& errno
!= EBADF
)
1785 pfatal_with_name (_("read jobs pipe"));
1787 DB (DB_JOBS
, ("Read returned EBADF.\n"));
1793 /* The job is now primed. Start it running.
1794 (This will notice if there is in fact no recipe.) */
1795 if (cmds
->fileinfo
.filenm
)
1796 DB (DB_BASIC
, (_("Invoking recipe from %s:%lu to update target `%s'.\n"),
1797 cmds
->fileinfo
.filenm
, cmds
->fileinfo
.lineno
,
1800 DB (DB_BASIC
, (_("Invoking builtin recipe to update target `%s'.\n"),
1804 start_waiting_job (c
);
1806 if (job_slots
== 1 || not_parallel
)
1807 /* Since there is only one job slot, make things run linearly.
1808 Wait for the child to die, setting the state to `cs_finished'. */
1809 while (file
->command_state
== cs_running
)
1810 reap_children (1, 0);
1815 /* Move CHILD's pointers to the next command for it to execute.
1816 Returns nonzero if there is another command. */
1819 job_next_command (struct child
*child
)
1821 while (child
->command_ptr
== 0 || *child
->command_ptr
== '\0')
1823 /* There are no more lines in the expansion of this line. */
1824 if (child
->command_line
== child
->file
->cmds
->ncommand_lines
)
1826 /* There are no more lines to be expanded. */
1827 child
->command_ptr
= 0;
1831 /* Get the next line to run. */
1832 child
->command_ptr
= child
->command_lines
[child
->command_line
++];
1837 /* Determine if the load average on the system is too high to start a new job.
1838 The real system load average is only recomputed once a second. However, a
1839 very parallel make can easily start tens or even hundreds of jobs in a
1840 second, which brings the system to its knees for a while until that first
1841 batch of jobs clears out.
1843 To avoid this we use a weighted algorithm to try to account for jobs which
1844 have been started since the last second, and guess what the load average
1845 would be now if it were computed.
1847 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1850 ! calculate something load-oid and add to the observed sys.load,
1851 ! so that latter can catch up:
1852 ! - every job started increases jobctr;
1853 ! - every dying job decreases a positive jobctr;
1854 ! - the jobctr value gets zeroed every change of seconds,
1855 ! after its value*weight_b is stored into the 'backlog' value last_sec
1856 ! - weight_a times the sum of jobctr and last_sec gets
1857 ! added to the observed sys.load.
1859 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1860 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1861 ! sub-shelled commands (rm, echo, sed...) for tests.
1862 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1863 ! resulted in significant excession of the load limit, raising it
1864 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1865 ! reach the limit in most test cases.
1867 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1868 ! exceeding the limit for longer-running stuff (compile jobs in
1869 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1870 ! small jobs' effects.
1874 #define LOAD_WEIGHT_A 0.25
1875 #define LOAD_WEIGHT_B 0.25
1878 load_too_high (void)
1880 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
1883 static double last_sec
;
1884 static time_t last_now
;
1889 /* sub_proc.c cannot wait for more than MAXIMUM_WAIT_OBJECTS children */
1890 if (process_used_slots () >= MAXIMUM_WAIT_OBJECTS
)
1894 if (max_load_average
< 0)
1897 /* Find the real system load average. */
1899 if (getloadavg (&load
, 1) != 1)
1901 static int lossage
= -1;
1902 /* Complain only once for the same error. */
1903 if (lossage
== -1 || errno
!= lossage
)
1906 /* An errno value of zero means getloadavg is just unsupported. */
1908 _("cannot enforce load limits on this operating system"));
1910 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1917 /* If we're in a new second zero the counter and correct the backlog
1918 value. Only keep the backlog for one extra second; after that it's 0. */
1922 if (last_now
== now
- 1)
1923 last_sec
= LOAD_WEIGHT_B
* job_counter
;
1931 /* Try to guess what the load would be right now. */
1932 guess
= load
+ (LOAD_WEIGHT_A
* (job_counter
+ last_sec
));
1934 DB (DB_JOBS
, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1935 guess
, load
, max_load_average
));
1937 return guess
>= max_load_average
;
1941 /* Start jobs that are waiting for the load to be lower. */
1944 start_waiting_jobs (void)
1948 if (waiting_jobs
== 0)
1953 /* Check for recently deceased descendants. */
1954 reap_children (0, 0);
1956 /* Take a job off the waiting list. */
1958 waiting_jobs
= job
->next
;
1960 /* Try to start that job. We break out of the loop as soon
1961 as start_waiting_job puts one back on the waiting list. */
1963 while (start_waiting_job (job
) && waiting_jobs
!= 0);
1970 /* EMX: Start a child process. This function returns the new pid. */
1971 # if defined __EMX__
1973 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
1976 /* stdin_fd == 0 means: nothing to do for stdin;
1977 stdout_fd == 1 means: nothing to do for stdout */
1978 int save_stdin
= (stdin_fd
!= 0) ? dup (0) : 0;
1979 int save_stdout
= (stdout_fd
!= 1) ? dup (1): 1;
1981 /* < 0 only if dup() failed */
1983 fatal (NILF
, _("no more file handles: could not duplicate stdin\n"));
1984 if (save_stdout
< 0)
1985 fatal (NILF
, _("no more file handles: could not duplicate stdout\n"));
1987 /* Close unnecessary file handles for the child. */
1988 if (save_stdin
!= 0)
1989 CLOSE_ON_EXEC (save_stdin
);
1990 if (save_stdout
!= 1)
1991 CLOSE_ON_EXEC (save_stdout
);
1993 /* Connect the pipes to the child process. */
1995 (void) dup2 (stdin_fd
, 0);
1997 (void) dup2 (stdout_fd
, 1);
1999 /* stdin_fd and stdout_fd must be closed on exit because we are
2000 still in the parent process */
2002 CLOSE_ON_EXEC (stdin_fd
);
2004 CLOSE_ON_EXEC (stdout_fd
);
2006 /* Run the command. */
2007 pid
= exec_command (argv
, envp
);
2009 /* Restore stdout/stdin of the parent and close temporary FDs. */
2012 if (dup2 (save_stdin
, 0) != 0)
2013 fatal (NILF
, _("Could not restore stdin\n"));
2020 if (dup2 (save_stdout
, 1) != 1)
2021 fatal (NILF
, _("Could not restore stdout\n"));
2023 close (save_stdout
);
2029 #elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
2032 Replace the current process with one executing the command in ARGV.
2033 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2034 the environment of the new program. This function does not return. */
2036 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2039 (void) dup2 (stdin_fd
, 0);
2041 (void) dup2 (stdout_fd
, 1);
2043 (void) close (stdin_fd
);
2045 (void) close (stdout_fd
);
2047 /* Run the command. */
2048 exec_command (argv
, envp
);
2050 #endif /* !AMIGA && !__MSDOS__ && !VMS */
2051 #endif /* !WINDOWS32 */
2054 /* Replace the current process with one running the command in ARGV,
2055 with environment ENVP. This function does not return. */
2057 /* EMX: This function returns the pid of the child process. */
2063 exec_command (char **argv
, char **envp
)
2066 /* to work around a problem with signals and execve: ignore them */
2068 signal (SIGCHLD
,SIG_IGN
);
2070 /* Run the program. */
2071 execve (argv
[0], argv
, envp
);
2072 perror_with_name ("execve: ", argv
[0]);
2073 _exit (EXIT_FAILURE
);
2079 int exit_code
= EXIT_FAILURE
;
2081 /* make sure CreateProcess() has Path it needs */
2082 sync_Path_environment();
2084 /* launch command */
2085 hPID
= process_easy(argv
, envp
);
2087 /* make sure launch ok */
2088 if (hPID
== INVALID_HANDLE_VALUE
)
2092 _("process_easy() failed to launch process (e=%ld)\n"),
2093 process_last_err(hPID
));
2094 for (i
= 0; argv
[i
]; i
++)
2095 fprintf(stderr
, "%s ", argv
[i
]);
2096 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
2100 /* wait and reap last child */
2101 hWaitPID
= process_wait_for_any();
2104 /* was an error found on this process? */
2105 err
= process_last_err(hWaitPID
);
2108 exit_code
= process_exit_code(hWaitPID
);
2111 fprintf(stderr
, "make (e=%d, rc=%d): %s",
2112 err
, exit_code
, map_windows32_error_to_string(err
));
2114 /* cleanup process */
2115 process_cleanup(hWaitPID
);
2117 /* expect to find only last pid, warn about other pids reaped */
2118 if (hWaitPID
== hPID
)
2122 char *pidstr
= xstrdup (pid2str ((pid_t
)hWaitPID
));
2125 _("make reaped child pid %s, still waiting for pid %s\n"),
2126 pidstr
, pid2str ((pid_t
)hPID
));
2131 /* return child's exit code as our exit code */
2134 #else /* !WINDOWS32 */
2140 /* Be the user, permanently. */
2145 /* Run the program. */
2146 pid
= spawnvpe (P_NOWAIT
, argv
[0], argv
, envp
);
2151 /* the file might have a strange shell extension */
2152 if (errno
== ENOENT
)
2157 /* Run the program. */
2159 execvp (argv
[0], argv
);
2161 # endif /* !__EMX__ */
2166 error (NILF
, _("%s: Command not found"), argv
[0]);
2170 /* The file is not executable. Try it as a shell script. */
2171 extern char *getenv ();
2178 /* Do not use $SHELL from the environment */
2179 struct variable
*p
= lookup_variable ("SHELL", 5);
2185 shell
= getenv ("SHELL");
2188 shell
= default_shell
;
2191 while (argv
[argc
] != 0)
2199 new_argv
= alloca ((1 + argc
+ 1) * sizeof (char *));
2200 new_argv
[0] = shell
;
2211 new_argv
[i
] = argv
[0];
2214 new_argv
[i
+ argc
] = argv
[argc
];
2219 pid
= spawnvpe (P_NOWAIT
, shell
, new_argv
, envp
);
2223 execvp (shell
, new_argv
);
2225 if (errno
== ENOENT
)
2226 error (NILF
, _("%s: Shell program not found"), shell
);
2228 perror_with_name ("execvp: ", shell
);
2234 /* this nasty error was driving me nuts :-( */
2235 error (NILF
, _("spawnvpe: environment space might be exhausted"));
2240 perror_with_name ("execvp: ", argv
[0]);
2249 #endif /* !WINDOWS32 */
2252 #else /* On Amiga */
2253 void exec_command (char **argv
)
2258 void clean_tmp (void)
2260 DeleteFile (amiga_bname
);
2263 #endif /* On Amiga */
2266 /* Figure out the argument list necessary to run LINE as a command. Try to
2267 avoid using a shell. This routine handles only ' quoting, and " quoting
2268 when no backslash, $ or ` characters are seen in the quotes. Starting
2269 quotes may be escaped with a backslash. If any of the characters in
2270 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2271 is the first word of a line, the shell is used.
2273 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2274 If *RESTP is NULL, newlines will be ignored.
2276 SHELL is the shell to use, or nil to use the default shell.
2277 IFS is the value of $IFS, or nil (meaning the default).
2279 FLAGS is the value of lines_flags for this command line. It is
2280 used in the WINDOWS32 port to check whether + or $(MAKE) were found
2281 in this command line, in which case the effect of just_print_flag
2285 construct_command_argv_internal (char *line
, char **restp
, char *shell
,
2286 char *shellflags
, char *ifs
, int flags
,
2287 char **batch_filename_ptr
)
2290 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2291 We call `system' for anything that requires ``slow'' processing,
2292 because DOS shells are too dumb. When $SHELL points to a real
2293 (unix-style) shell, `system' just calls it to do everything. When
2294 $SHELL points to a DOS shell, `system' does most of the work
2295 internally, calling the shell only for its internal commands.
2296 However, it looks on the $PATH first, so you can e.g. have an
2297 external command named `mkdir'.
2299 Since we call `system', certain characters and commands below are
2300 actually not specific to COMMAND.COM, but to the DJGPP implementation
2301 of `system'. In particular:
2303 The shell wildcard characters are in DOS_CHARS because they will
2304 not be expanded if we call the child via `spawnXX'.
2306 The `;' is in DOS_CHARS, because our `system' knows how to run
2307 multiple commands on a single line.
2309 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2310 won't have to tell one from another and have one more set of
2311 commands and special characters. */
2312 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2313 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2314 "copy", "ctty", "date", "del", "dir", "echo",
2315 "erase", "exit", "for", "goto", "if", "md",
2316 "mkdir", "path", "pause", "prompt", "rd",
2317 "rmdir", "rem", "ren", "rename", "set",
2318 "shift", "time", "type", "ver", "verify",
2321 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2322 static char *sh_cmds_sh
[] = { "cd", "echo", "eval", "exec", "exit", "login",
2323 "logout", "set", "umask", "wait", "while",
2324 "for", "case", "if", ":", ".", "break",
2325 "continue", "export", "read", "readonly",
2326 "shift", "times", "trap", "switch", "unset",
2331 #elif defined (__EMX__)
2332 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2333 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2334 "copy", "ctty", "date", "del", "dir", "echo",
2335 "erase", "exit", "for", "goto", "if", "md",
2336 "mkdir", "path", "pause", "prompt", "rd",
2337 "rmdir", "rem", "ren", "rename", "set",
2338 "shift", "time", "type", "ver", "verify",
2341 static char sh_chars_os2
[] = "*?[];|<>%^()\"'&";
2342 static char *sh_cmds_os2
[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2343 "date", "del", "detach", "dir", "echo",
2344 "endlocal", "erase", "exit", "for", "goto", "if",
2345 "keys", "md", "mkdir", "move", "path", "pause",
2346 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2347 "set", "setlocal", "shift", "start", "time",
2348 "type", "ver", "verify", "vol", ":", 0 };
2350 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^~'";
2351 static char *sh_cmds_sh
[] = { "echo", "cd", "eval", "exec", "exit", "login",
2352 "logout", "set", "umask", "wait", "while",
2353 "for", "case", "if", ":", ".", "break",
2354 "continue", "export", "read", "readonly",
2355 "shift", "times", "trap", "switch", "unset",
2360 #elif defined (_AMIGA)
2361 static char sh_chars
[] = "#;\"|<>()?*$`";
2362 static char *sh_cmds
[] = { "cd", "eval", "if", "delete", "echo", "copy",
2363 "rename", "set", "setenv", "date", "makedir",
2364 "skip", "else", "endif", "path", "prompt",
2365 "unset", "unsetenv", "version",
2367 #elif defined (WINDOWS32)
2368 static char sh_chars_dos
[] = "\"|&<>";
2369 static char *sh_cmds_dos
[] = { "assoc", "break", "call", "cd", "chcp",
2370 "chdir", "cls", "color", "copy", "ctty",
2371 "date", "del", "dir", "echo", "echo.",
2372 "endlocal", "erase", "exit", "for", "ftype",
2373 "goto", "if", "if", "md", "mkdir", "path",
2374 "pause", "prompt", "rd", "rem", "ren",
2375 "rename", "rmdir", "set", "setlocal",
2376 "shift", "time", "title", "type", "ver",
2377 "verify", "vol", ":", 0 };
2378 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2379 static char *sh_cmds_sh
[] = { "cd", "eval", "exec", "exit", "login",
2380 "logout", "set", "umask", "wait", "while", "for",
2381 "case", "if", ":", ".", "break", "continue",
2382 "export", "read", "readonly", "shift", "times",
2383 "trap", "switch", "test",
2384 #ifdef BATCH_MODE_ONLY_SHELL
2390 #elif defined(__riscos__)
2391 static char sh_chars
[] = "";
2392 static char *sh_cmds
[] = { 0 };
2393 #else /* must be UNIX-ish */
2394 static char sh_chars
[] = "#;\"*?[]&|<>(){}$`^~!";
2395 static char *sh_cmds
[] = { ".", ":", "break", "case", "cd", "continue",
2396 "eval", "exec", "exit", "export", "for", "if",
2397 "login", "logout", "read", "readonly", "set",
2398 "shift", "switch", "test", "times", "trap",
2399 "ulimit", "umask", "unset", "wait", "while", 0 };
2400 # ifdef HAVE_DOS_PATHS
2401 /* This is required if the MSYS/Cygwin ports (which do not define
2402 WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
2403 sh_chars_sh[] directly (see below). */
2404 static char *sh_chars_sh
= sh_chars
;
2405 # endif /* HAVE_DOS_PATHS */
2411 int instring
, word_has_equals
, seen_nonequals
, last_argument_was_empty
;
2412 char **new_argv
= 0;
2418 sh_cmds
= sh_cmds_dos
;
2419 sh_chars
= sh_chars_dos
;
2421 sh_cmds
= sh_cmds_sh
;
2422 sh_chars
= sh_chars_sh
;
2424 #endif /* WINDOWS32 */
2429 /* Make sure not to bother processing an empty line. */
2430 while (isblank ((unsigned char)*line
))
2435 /* See if it is safe to parse commands internally. */
2437 shell
= default_shell
;
2439 else if (strcmp (shell
, default_shell
))
2441 char *s1
= _fullpath (NULL
, shell
, 0);
2442 char *s2
= _fullpath (NULL
, default_shell
, 0);
2444 slow_flag
= strcmp ((s1
? s1
: ""), (s2
? s2
: ""));
2453 #else /* not WINDOWS32 */
2454 #if defined (__MSDOS__) || defined (__EMX__)
2455 else if (strcasecmp (shell
, default_shell
))
2457 extern int _is_unixy_shell (const char *_path
);
2459 DB (DB_BASIC
, (_("$SHELL changed (was `%s', now `%s')\n"),
2460 default_shell
, shell
));
2461 unixy_shell
= _is_unixy_shell (shell
);
2462 /* we must allocate a copy of shell: construct_command_argv() will free
2463 * shell after this function returns. */
2464 default_shell
= xstrdup (shell
);
2468 sh_chars
= sh_chars_sh
;
2469 sh_cmds
= sh_cmds_sh
;
2473 sh_chars
= sh_chars_dos
;
2474 sh_cmds
= sh_cmds_dos
;
2476 if (_osmode
== OS2_MODE
)
2478 sh_chars
= sh_chars_os2
;
2479 sh_cmds
= sh_cmds_os2
;
2483 #else /* !__MSDOS__ */
2484 else if (strcmp (shell
, default_shell
))
2486 #endif /* !__MSDOS__ && !__EMX__ */
2487 #endif /* not WINDOWS32 */
2490 for (ap
= ifs
; *ap
!= '\0'; ++ap
)
2491 if (*ap
!= ' ' && *ap
!= '\t' && *ap
!= '\n')
2494 if (shellflags
!= 0)
2495 if (shellflags
[0] != '-'
2496 || ((shellflags
[1] != 'c' || shellflags
[2] != '\0')
2497 && (shellflags
[1] != 'e' || shellflags
[2] != 'c' || shellflags
[3] != '\0')))
2500 i
= strlen (line
) + 1;
2502 /* More than 1 arg per character is impossible. */
2503 new_argv
= xmalloc (i
* sizeof (char *));
2505 /* All the args can fit in a buffer as big as LINE is. */
2506 ap
= new_argv
[0] = argstr
= xmalloc (i
);
2509 /* I is how many complete arguments have been found. */
2511 instring
= word_has_equals
= seen_nonequals
= last_argument_was_empty
= 0;
2512 for (p
= line
; *p
!= '\0'; ++p
)
2518 /* Inside a string, just copy any char except a closing quote
2519 or a backslash-newline combination. */
2523 if (ap
== new_argv
[0] || *(ap
-1) == '\0')
2524 last_argument_was_empty
= 1;
2526 else if (*p
== '\\' && p
[1] == '\n')
2528 /* Backslash-newline is handled differently depending on what
2529 kind of string we're in: inside single-quoted strings you
2530 keep them; in double-quoted strings they disappear.
2531 For DOS/Windows/OS2, if we don't have a POSIX shell,
2532 we keep the pre-POSIX behavior of removing the
2533 backslash-newline. */
2535 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2546 else if (*p
== '\n' && restp
!= NULL
)
2548 /* End of the command line. */
2552 /* Backslash, $, and ` are special inside double quotes.
2553 If we see any of those, punt.
2554 But on MSDOS, if we use COMMAND.COM, double and single
2555 quotes have the same effect. */
2556 else if (instring
== '"' && strchr ("\\$`", *p
) != 0 && unixy_shell
)
2561 else if (strchr (sh_chars
, *p
) != 0)
2562 /* Not inside a string, but it's a special char. */
2564 else if (one_shell
&& *p
== '\n')
2565 /* In .ONESHELL mode \n is a separator like ; or && */
2568 else if (*p
== '.' && p
[1] == '.' && p
[2] == '.' && p
[3] != '.')
2569 /* `...' is a wildcard in DJGPP. */
2573 /* Not a special char. */
2577 /* Equals is a special character in leading words before the
2578 first word with no equals sign in it. This is not the case
2579 with sh -k, but we never get here when using nonstandard
2581 if (! seen_nonequals
&& unixy_shell
)
2583 word_has_equals
= 1;
2588 /* Backslash-newline has special case handling, ref POSIX.
2589 We're in the fastpath, so emulate what the shell would do. */
2592 /* Throw out the backslash and newline. */
2595 /* If there's nothing in this argument yet, skip any
2596 whitespace before the start of the next word. */
2597 if (ap
== new_argv
[i
])
2598 p
= next_token (p
+ 1) - 1;
2600 else if (p
[1] != '\0')
2602 #ifdef HAVE_DOS_PATHS
2603 /* Only remove backslashes before characters special to Unixy
2604 shells. All other backslashes are copied verbatim, since
2605 they are probably DOS-style directory separators. This
2606 still leaves a small window for problems, but at least it
2607 should work for the vast majority of naive users. */
2610 /* A dot is only special as part of the "..."
2612 if (strneq (p
+ 1, ".\\.\\.", 5))
2620 if (p
[1] != '\\' && p
[1] != '\''
2621 && !isspace ((unsigned char)p
[1])
2622 && strchr (sh_chars_sh
, p
[1]) == 0)
2623 /* back up one notch, to copy the backslash */
2625 #endif /* HAVE_DOS_PATHS */
2627 /* Copy and skip the following char. */
2640 /* End of the command line. */
2645 /* Newlines are not special. */
2651 /* We have the end of an argument.
2652 Terminate the text of the argument. */
2655 last_argument_was_empty
= 0;
2657 /* Update SEEN_NONEQUALS, which tells us if every word
2658 heretofore has contained an `='. */
2659 seen_nonequals
|= ! word_has_equals
;
2660 if (word_has_equals
&& ! seen_nonequals
)
2661 /* An `=' in a word before the first
2662 word without one is magical. */
2664 word_has_equals
= 0; /* Prepare for the next word. */
2666 /* If this argument is the command name,
2667 see if it is a built-in shell command.
2668 If so, have the shell handle it. */
2672 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2674 if (streq (sh_cmds
[j
], new_argv
[0]))
2677 /* Non-Unix shells are case insensitive. */
2679 && strcasecmp (sh_cmds
[j
], new_argv
[0]) == 0)
2685 /* Ignore multiple whitespace chars. */
2686 p
= next_token (p
) - 1;
2697 /* Let the shell deal with an unterminated quote. */
2700 /* Terminate the last argument and the argument list. */
2703 if (new_argv
[i
][0] != '\0' || last_argument_was_empty
)
2710 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2711 if (streq (sh_cmds
[j
], new_argv
[0]))
2715 if (new_argv
[0] == 0)
2717 /* Line was empty. */
2726 /* We must use the shell. */
2730 /* Free the old argument list we were working on. */
2736 execute_by_shell
= 1; /* actually, call `system' if shell isn't unixy */
2745 buffer
= xmalloc (strlen (line
)+1);
2748 for (dptr
=buffer
; *ptr
; )
2750 if (*ptr
== '\\' && ptr
[1] == '\n')
2752 else if (*ptr
== '@') /* Kludge: multiline commands */
2762 new_argv
= xmalloc (2 * sizeof (char *));
2763 new_argv
[0] = buffer
;
2766 #else /* Not Amiga */
2769 * Not eating this whitespace caused things like
2773 * which gave the shell fits. I think we have to eat
2774 * whitespace here, but this code should be considered
2775 * suspicious if things start failing....
2778 /* Make sure not to bother processing an empty line. */
2779 while (isspace ((unsigned char)*line
))
2783 #endif /* WINDOWS32 */
2786 /* SHELL may be a multi-word command. Construct a command line
2787 "$(SHELL) $(.SHELLFLAGS) LINE", with all special chars in LINE escaped.
2788 Then recurse, expanding this command line to get the final
2791 unsigned int shell_len
= strlen (shell
);
2792 unsigned int line_len
= strlen (line
);
2793 unsigned int sflags_len
= strlen (shellflags
);
2794 char *command_ptr
= NULL
; /* used for batch_mode_shell mode */
2797 # ifdef __EMX__ /* is this necessary? */
2799 shellflags
[0] = '/'; /* "/c" */
2802 /* In .ONESHELL mode we are allowed to throw the entire current
2803 recipe string at a single shell and trust that the user
2804 has configured the shell and shell flags, and formatted
2805 the string, appropriately. */
2808 /* If the shell is Bourne compatible, we must remove and ignore
2809 interior special chars [@+-] because they're meaningless to
2810 the shell itself. If, however, we're in .ONESHELL mode and
2811 have changed SHELL to something non-standard, we should
2812 leave those alone because they could be part of the
2813 script. In this case we must also leave in place
2814 any leading [@+-] for the same reason. */
2816 /* Remove and ignore interior prefix chars [@+-] because they're
2817 meaningless given a single shell. */
2818 #if defined __MSDOS__ || defined (__EMX__)
2819 if (unixy_shell
) /* the test is complicated and we already did it */
2821 if (is_bourne_compatible_shell(shell
))
2824 const char *f
= line
;
2827 /* Copy the recipe, removing and ignoring interior prefix chars
2828 [@+-]: they're meaningless in .ONESHELL mode. */
2829 while (f
[0] != '\0')
2833 /* This is the start of a new recipe line.
2834 Skip whitespace and prefix characters. */
2835 while (isblank (*f
) || *f
== '-' || *f
== '@' || *f
== '+')
2838 /* Copy until we get to the next logical recipe line. */
2846 /* On unescaped newline, we're done with this line. */
2847 if (f
[-1] == '\n' && ! esc
)
2850 /* Something else: reset the escape sequence. */
2858 new_argv
= xmalloc (4 * sizeof (char *));
2859 new_argv
[0] = xstrdup(shell
);
2860 new_argv
[1] = xstrdup(shellflags
);
2866 new_line
= alloca (shell_len
+ 1 + sflags_len
+ 1
2867 + (line_len
*2) + 1);
2869 memcpy (ap
, shell
, shell_len
);
2872 memcpy (ap
, shellflags
, sflags_len
);
2876 for (p
= line
; *p
!= '\0'; ++p
)
2878 if (restp
!= NULL
&& *p
== '\n')
2883 else if (*p
== '\\' && p
[1] == '\n')
2885 /* POSIX says we keep the backslash-newline. If we don't have a
2886 POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
2887 and remove the backslash/newline. */
2888 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2889 # define PRESERVE_BSNL unixy_shell
2891 # define PRESERVE_BSNL 1
2896 /* Only non-batch execution needs another backslash,
2897 because it will be passed through a recursive
2898 invocation of this function. */
2899 if (!batch_mode_shell
)
2907 /* DOS shells don't know about backslash-escaping. */
2908 if (unixy_shell
&& !batch_mode_shell
&&
2909 (*p
== '\\' || *p
== '\'' || *p
== '"'
2910 || isspace ((unsigned char)*p
)
2911 || strchr (sh_chars
, *p
) != 0))
2914 else if (unixy_shell
&& strneq (p
, "...", 3))
2916 /* The case of `...' wildcard again. */
2917 strcpy (ap
, "\\.\\.\\");
2924 if (ap
== new_line
+ shell_len
+ sflags_len
+ 2)
2925 /* Line was empty. */
2930 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2931 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2932 cases, run commands via a script file. */
2933 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
)) {
2934 /* Need to allocate new_argv, although it's unused, because
2935 start_job_command will want to free it and its 0'th element. */
2936 new_argv
= xmalloc(2 * sizeof (char *));
2937 new_argv
[0] = xstrdup ("");
2939 } else if ((no_default_sh_exe
|| batch_mode_shell
) && batch_filename_ptr
) {
2942 int id
= GetCurrentProcessId();
2945 /* create a file name */
2946 sprintf(fbuf
, "make%d", id
);
2947 *batch_filename_ptr
= create_batch_file (fbuf
, unixy_shell
, &temp_fd
);
2949 DB (DB_JOBS
, (_("Creating temporary batch file %s\n"),
2950 *batch_filename_ptr
));
2952 /* Create a FILE object for the batch file, and write to it the
2953 commands to be executed. Put the batch file in TEXT mode. */
2954 _setmode (temp_fd
, _O_TEXT
);
2955 batch
= _fdopen (temp_fd
, "wt");
2957 fputs ("@echo off\n", batch
);
2958 fputs (command_ptr
, batch
);
2959 fputc ('\n', batch
);
2961 DB (DB_JOBS
, (_("Batch file contents:%s\n\t%s\n"),
2962 !unixy_shell
? "\n\t@echo off" : "", command_ptr
));
2965 new_argv
= xmalloc(3 * sizeof (char *));
2967 new_argv
[0] = xstrdup (shell
);
2968 new_argv
[1] = *batch_filename_ptr
; /* only argv[0] gets freed later */
2970 new_argv
[0] = xstrdup (*batch_filename_ptr
);
2975 #endif /* WINDOWS32 */
2978 new_argv
= construct_command_argv_internal (new_line
, 0, 0, 0, 0, flags
, 0);
2981 else if (!unixy_shell
)
2983 /* new_line is local, must not be freed therefore
2984 We use line here instead of new_line because we run the shell
2986 size_t line_len
= strlen (line
);
2989 memcpy (new_line
, line
, line_len
+ 1);
2990 /* Replace all backslash-newline combination and also following tabs.
2991 Important: stop at the first '\n' because that's what the loop above
2992 did. The next line starting at restp[0] will be executed during the
2993 next call of this function. */
2994 while (*q
!= '\0' && *q
!= '\n')
2996 if (q
[0] == '\\' && q
[1] == '\n')
2997 q
+= 2; /* remove '\\' and '\n' */
3003 # ifndef NO_CMD_DEFAULT
3004 if (strnicmp (new_line
, "echo", 4) == 0
3005 && (new_line
[4] == ' ' || new_line
[4] == '\t'))
3007 /* the builtin echo command: handle it separately */
3008 size_t echo_len
= line_len
- 5;
3009 char *echo_line
= new_line
+ 5;
3011 /* special case: echo 'x="y"'
3012 cmd works this way: a string is printed as is, i.e., no quotes
3013 are removed. But autoconf uses a command like echo 'x="y"' to
3014 determine whether make works. autoconf expects the output x="y"
3015 so we will do exactly that.
3016 Note: if we do not allow cmd to be the default shell
3017 we do not need this kind of voodoo */
3018 if (echo_line
[0] == '\''
3019 && echo_line
[echo_len
- 1] == '\''
3020 && strncmp (echo_line
+ 1, "ac_maketemp=",
3021 strlen ("ac_maketemp=")) == 0)
3023 /* remove the enclosing quotes */
3024 memmove (echo_line
, echo_line
+ 1, echo_len
- 2);
3025 echo_line
[echo_len
- 2] = '\0';
3031 /* Let the shell decide what to do. Put the command line into the
3032 2nd command line argument and hope for the best ;-) */
3033 size_t sh_len
= strlen (shell
);
3035 /* exactly 3 arguments + NULL */
3036 new_argv
= xmalloc (4 * sizeof (char *));
3037 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3038 the trailing '\0' */
3039 new_argv
[0] = xmalloc (sh_len
+ line_len
+ 5);
3040 memcpy (new_argv
[0], shell
, sh_len
+ 1);
3041 new_argv
[1] = new_argv
[0] + sh_len
+ 1;
3042 memcpy (new_argv
[1], "/c", 3);
3043 new_argv
[2] = new_argv
[1] + 3;
3044 memcpy (new_argv
[2], new_line
, line_len
+ 1);
3048 #elif defined(__MSDOS__)
3051 /* With MSDOS shells, we must construct the command line here
3052 instead of recursively calling ourselves, because we
3053 cannot backslash-escape the special characters (see above). */
3054 new_argv
= xmalloc (sizeof (char *));
3055 line_len
= strlen (new_line
) - shell_len
- sflags_len
- 2;
3056 new_argv
[0] = xmalloc (line_len
+ 1);
3057 strncpy (new_argv
[0],
3058 new_line
+ shell_len
+ sflags_len
+ 2, line_len
);
3059 new_argv
[0][line_len
] = '\0';
3063 fatal (NILF
, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3064 __FILE__
, __LINE__
);
3067 #endif /* ! AMIGA */
3073 /* Figure out the argument list necessary to run LINE as a command. Try to
3074 avoid using a shell. This routine handles only ' quoting, and " quoting
3075 when no backslash, $ or ` characters are seen in the quotes. Starting
3076 quotes may be escaped with a backslash. If any of the characters in
3077 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3078 is the first word of a line, the shell is used.
3080 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3081 If *RESTP is NULL, newlines will be ignored.
3083 FILE is the target whose commands these are. It is used for
3084 variable expansion for $(SHELL) and $(IFS). */
3087 construct_command_argv (char *line
, char **restp
, struct file
*file
,
3088 int cmd_flags
, char **batch_filename_ptr
)
3090 char *shell
, *ifs
, *shellflags
;
3102 && (isspace ((unsigned char)*cptr
)))
3107 && (!isspace((unsigned char)*cptr
)))
3112 argv
= xmalloc (argc
* sizeof (char *));
3121 && (isspace ((unsigned char)*cptr
)))
3125 DB (DB_JOBS
, ("argv[%d] = [%s]\n", argc
, cptr
));
3126 argv
[argc
++] = cptr
;
3128 && (!isspace((unsigned char)*cptr
)))
3135 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3136 int save
= warn_undefined_variables_flag
;
3137 warn_undefined_variables_flag
= 0;
3139 shell
= allocated_variable_expand_for_file ("$(SHELL)", file
);
3142 * Convert to forward slashes so that construct_command_argv_internal()
3146 char *p
= w32ify (shell
, 0);
3152 static const char *unixroot
= NULL
;
3153 static const char *last_shell
= "";
3154 static int init
= 0;
3157 unixroot
= getenv ("UNIXROOT");
3158 /* unixroot must be NULL or not empty */
3159 if (unixroot
&& unixroot
[0] == '\0') unixroot
= NULL
;
3163 /* if we have an unixroot drive and if shell is not default_shell
3164 (which means it's either cmd.exe or the test has already been
3165 performed) and if shell is an absolute path without drive letter,
3166 try whether it exists e.g.: if "/bin/sh" does not exist use
3167 "$UNIXROOT/bin/sh" instead. */
3168 if (unixroot
&& shell
&& strcmp (shell
, last_shell
) != 0
3169 && (shell
[0] == '/' || shell
[0] == '\\'))
3171 /* trying a new shell, check whether it exists */
3172 size_t size
= strlen (shell
);
3173 char *buf
= xmalloc (size
+ 7);
3174 memcpy (buf
, shell
, size
);
3175 memcpy (buf
+ size
, ".exe", 5); /* including the trailing '\0' */
3176 if (access (shell
, F_OK
) != 0 && access (buf
, F_OK
) != 0)
3178 /* try the same for the unixroot drive */
3179 memmove (buf
+ 2, buf
, size
+ 5);
3180 buf
[0] = unixroot
[0];
3181 buf
[1] = unixroot
[1];
3182 if (access (buf
, F_OK
) == 0)
3183 /* we have found a shell! */
3193 #endif /* __EMX__ */
3195 shellflags
= allocated_variable_expand_for_file ("$(.SHELLFLAGS)", file
);
3196 ifs
= allocated_variable_expand_for_file ("$(IFS)", file
);
3198 warn_undefined_variables_flag
= save
;
3201 argv
= construct_command_argv_internal (line
, restp
, shell
, shellflags
, ifs
,
3202 cmd_flags
, batch_filename_ptr
);
3211 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3213 dup2 (int old
, int new)
3228 #endif /* !HAVE_DUP2 && !_AMIGA */
3230 /* On VMS systems, include special VMS functions. */
3233 #include "vmsjobs.c"