1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988-2012 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along with
15 this program. If not, see <http://www.gnu.org/licenses/>. */
30 /* Default shell to use. */
34 char *default_shell
= "sh.exe";
35 int no_default_sh_exe
= 1;
36 int batch_mode_shell
= 1;
39 #elif defined (_AMIGA)
41 char default_shell
[] = "";
42 extern int MyExecute (char **);
43 int batch_mode_shell
= 0;
45 #elif defined (__MSDOS__)
47 /* The default shell is a pointer so we can change it if Makefile
48 says so. It is without an explicit path so we get a chance
49 to search the $PATH for it (since MSDOS doesn't have standard
50 directories we could trust). */
51 char *default_shell
= "command.com";
52 int batch_mode_shell
= 0;
54 #elif defined (__EMX__)
56 char *default_shell
= "/bin/sh";
57 int batch_mode_shell
= 0;
62 char default_shell
[] = "";
63 int batch_mode_shell
= 0;
65 #elif defined (__riscos__)
67 char default_shell
[] = "";
68 int batch_mode_shell
= 0;
72 char default_shell
[] = "/bin/sh";
73 int batch_mode_shell
= 0;
79 static int execute_by_shell
;
80 static int dos_pid
= 123;
82 int dos_command_running
;
83 #endif /* __MSDOS__ */
86 # include <proto/dos.h>
87 static int amiga_pid
= 123;
88 static int amiga_status
;
89 static char amiga_bname
[32];
90 static int amiga_batch_file
;
95 # include <processes.h>
98 # include <lib$routines.h>
99 static void vmsWaitForChildren (int *);
103 # include <windows.h>
105 # include <process.h>
106 # include "sub_proc.h"
108 # include "pathstuff.h"
109 # define WAIT_NOHANG 1
110 #endif /* WINDOWS32 */
113 # include <process.h>
116 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
117 # include <sys/wait.h>
121 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
122 #else /* Don't have waitpid. */
127 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
128 # endif /* Have wait3. */
129 #endif /* Have waitpid. */
131 #if !defined (wait) && !defined (POSIX)
135 #ifndef HAVE_UNION_WAIT
140 # define WTERMSIG(x) ((x) & 0x7f)
143 # define WCOREDUMP(x) ((x) & 0x80)
146 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
149 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
152 # define WIFEXITED(x) (WTERMSIG (x) == 0)
155 #else /* Have 'union wait'. */
157 # define WAIT_T union wait
159 # define WTERMSIG(x) ((x).w_termsig)
162 # define WCOREDUMP(x) ((x).w_coredump)
165 # define WEXITSTATUS(x) ((x).w_retcode)
168 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
171 # define WIFEXITED(x) (WTERMSIG(x) == 0)
174 #endif /* Don't have 'union wait'. */
176 #if !defined(HAVE_UNISTD_H) && !defined(WINDOWS32)
188 /* Different systems have different requirements for pid_t.
189 Plus we have to support gettext string translation... Argh. */
193 static char pidstring
[100];
194 #if defined(WINDOWS32) && (__GNUC__ > 3 || _MSC_VER > 1300)
195 /* %Id is only needed for 64-builds, which were not supported by
196 older versions of Windows compilers. */
197 sprintf (pidstring
, "%Id", pid
);
199 sprintf (pidstring
, "%lu", (unsigned long) pid
);
204 int getloadavg (double loadavg
[], int nelem
);
205 int start_remote_job (char **argv
, char **envp
, int stdin_fd
, int *is_remote
,
206 int *id_ptr
, int *used_stdin
);
207 int start_remote_job_p (int);
208 int remote_status (int *exit_code_ptr
, int *signal_ptr
, int *coredump_ptr
,
211 RETSIGTYPE
child_handler (int);
212 static void free_child (struct child
*);
213 static void start_job_command (struct child
*child
);
214 static int load_too_high (void);
215 static int job_next_command (struct child
*);
216 static int start_waiting_job (struct child
*);
218 /* Chain of all live (or recently deceased) children. */
220 struct child
*children
= 0;
222 /* Number of children currently running. */
224 unsigned int job_slots_used
= 0;
226 /* Nonzero if the 'good' standard input is in use. */
228 static int good_stdin_used
= 0;
230 /* Chain of children waiting to run until the load average goes down. */
232 static struct child
*waiting_jobs
= 0;
234 /* Non-zero if we use a *real* shell (always so on Unix). */
238 /* Number of jobs started in the current second. */
240 unsigned long job_counter
= 0;
242 /* Number of jobserver tokens this instance is currently using. */
244 unsigned int jobserver_tokens
= 0;
248 * The macro which references this function is defined in make.h.
251 w32_kill(pid_t pid
, int sig
)
253 return ((process_kill((HANDLE
)pid
, sig
) == TRUE
) ? 0 : -1);
256 /* This function creates a temporary file name with an extension specified
258 * Return an xmalloc'ed string of a newly created temp file and its
259 * file descriptor, or die. */
261 create_batch_file (char const *base
, int unixy
, int *fd
)
263 const char *const ext
= unixy
? "sh" : "bat";
264 const char *error_string
= NULL
;
265 char temp_path
[MAXPATHLEN
]; /* need to know its length */
266 unsigned path_size
= GetTempPath(sizeof temp_path
, temp_path
);
268 /* The following variable is static so we won't try to reuse a name
269 that was generated a little while ago, because that file might
270 not be on disk yet, since we use FILE_ATTRIBUTE_TEMPORARY below,
271 which tells the OS it doesn't need to flush the cache to disk.
272 If the file is not yet on disk, we might think the name is
273 available, while it really isn't. This happens in parallel
274 builds, where Make doesn't wait for one job to finish before it
275 launches the next one. */
276 static unsigned uniq
= 0;
277 static int second_loop
= 0;
278 const unsigned sizemax
= strlen (base
) + strlen (ext
) + 10;
282 path_size
= GetCurrentDirectory (sizeof temp_path
, temp_path
);
287 if (uniq
>= 0x10000 && !second_loop
)
289 /* If we already had 64K batch files in this
290 process, make a second loop through the numbers,
291 looking for free slots, i.e. files that were
292 deleted in the meantime. */
296 while (path_size
> 0 &&
297 path_size
+ sizemax
< sizeof temp_path
&&
298 !(uniq
>= 0x10000 && second_loop
))
300 unsigned size
= sprintf (temp_path
+ path_size
,
302 temp_path
[path_size
- 1] == '\\' ? "" : "\\",
304 HANDLE h
= CreateFile (temp_path
, /* file name */
305 GENERIC_READ
| GENERIC_WRITE
, /* desired access */
306 0, /* no share mode */
307 NULL
, /* default security attributes */
308 CREATE_NEW
, /* creation disposition */
309 FILE_ATTRIBUTE_NORMAL
| /* flags and attributes */
310 FILE_ATTRIBUTE_TEMPORARY
, /* we'll delete it */
311 NULL
); /* no template file */
313 if (h
== INVALID_HANDLE_VALUE
)
315 const DWORD er
= GetLastError();
317 if (er
== ERROR_FILE_EXISTS
|| er
== ERROR_ALREADY_EXISTS
)
320 if (uniq
== 0x10000 && !second_loop
)
327 /* the temporary path is not guaranteed to exist */
328 else if (path_is_dot
== 0)
330 path_size
= GetCurrentDirectory (sizeof temp_path
, temp_path
);
336 error_string
= map_windows32_error_to_string (er
);
342 const unsigned final_size
= path_size
+ size
+ 1;
343 char *const path
= xmalloc (final_size
);
344 memcpy (path
, temp_path
, final_size
);
345 *fd
= _open_osfhandle ((intptr_t)h
, 0);
350 for (p
= path
; (ch
= *p
) != 0; ++p
)
354 return path
; /* good return */
359 if (error_string
== NULL
)
360 error_string
= _("Cannot create a temporary file\n");
361 fatal (NILF
, error_string
);
366 #endif /* WINDOWS32 */
369 /* returns whether path is assumed to be a unix like shell. */
371 _is_unixy_shell (const char *path
)
373 /* list of non unix shells */
374 const char *known_os2shells
[] = {
386 /* find the rightmost '/' or '\\' */
387 const char *name
= strrchr (path
, '/');
388 const char *p
= strrchr (path
, '\\');
391 if (name
&& p
) /* take the max */
392 name
= (name
> p
) ? name
: p
;
393 else if (p
) /* name must be 0 */
395 else if (!name
) /* name and p must be 0 */
398 if (*name
== '/' || *name
== '\\') name
++;
401 while (known_os2shells
[i
] != NULL
) {
402 if (strcasecmp (name
, known_os2shells
[i
]) == 0)
403 return 0; /* not a unix shell */
407 /* in doubt assume a unix like shell */
412 /* determines whether path looks to be a Bourne-like shell. */
414 is_bourne_compatible_shell (const char *path
)
416 /* list of known unix (Bourne-like) shells */
417 const char *unix_shells
[] = {
429 /* find the rightmost '/' or '\\' */
430 const char *name
= strrchr (path
, '/');
431 char *p
= strrchr (path
, '\\');
433 if (name
&& p
) /* take the max */
434 name
= (name
> p
) ? name
: p
;
435 else if (p
) /* name must be 0 */
437 else if (!name
) /* name and p must be 0 */
440 if (*name
== '/' || *name
== '\\') name
++;
442 /* this should be able to deal with extensions on Windows-like systems */
443 for (i
= 0; unix_shells
[i
] != NULL
; i
++) {
444 len
= strlen(unix_shells
[i
]);
445 #if defined(WINDOWS32) || defined(__MSDOS__)
446 if ((strncasecmp (name
, unix_shells
[i
], len
) == 0) &&
447 (strlen(name
) >= len
&& (name
[len
] == '\0' || name
[len
] == '.')))
449 if ((strncmp (name
, unix_shells
[i
], len
) == 0) &&
450 (strlen(name
) >= len
&& name
[len
] == '\0'))
452 return 1; /* a known unix-style shell */
455 /* if not on the list, assume it's not a Bourne-like shell */
460 /* Write an error message describing the exit status given in
461 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
462 Append "(ignored)" if IGNORED is nonzero. */
465 child_error (const struct file
*file
,
466 int exit_code
, int exit_sig
, int coredump
, int ignored
)
469 const char *pre
= "*** ";
470 const char *post
= "";
471 const char *dump
= "";
472 struct floc
*flocp
= &file
->cmds
->fileinfo
;
474 if (ignored
&& silent_flag
)
477 if (exit_sig
&& coredump
)
478 dump
= _(" (core dumped)");
483 post
= _(" (ignored)");
490 char *a
= alloca (strlen (flocp
->filenm
) + 1 + 11 + 1);
491 sprintf (a
, "%s:%lu", flocp
->filenm
, flocp
->lineno
);
494 message (0, _("%s: recipe for target '%s' failed"), nm
, file
->name
);
497 if (!(exit_code
& 1))
498 error (NILF
, _("%s[%s] Error 0x%x%s"), pre
, file
->name
, exit_code
, post
);
501 error (NILF
, _("%s[%s] Error %d%s"), pre
, file
->name
, exit_code
, post
);
503 error (NILF
, _("%s[%s] %s%s%s"),
504 pre
, file
->name
, strsignal (exit_sig
), dump
, post
);
509 /* Handle a dead child. This handler may or may not ever be installed.
511 If we're using the jobserver feature, we need it. First, installing it
512 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
513 read FD to ensure we don't enter another blocking read without reaping all
514 the dead children. In this case we don't need the dead_children count.
516 If we don't have either waitpid or wait3, then make is unreliable, but we
517 use the dead_children count to reap children as best we can. */
519 static unsigned int dead_children
= 0;
522 child_handler (int sig UNUSED
)
533 /* The signal handler must called only once! */
534 signal (SIGCHLD
, SIG_DFL
);
537 /* This causes problems if the SIGCHLD interrupts a printf().
538 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
542 extern int shell_function_pid
, shell_function_completed
;
544 /* Reap all dead children, storing the returned status and the new command
545 state ('cs_finished') in the 'file' member of the 'struct child' for the
546 dead child, and removing the child from the chain. In addition, if BLOCK
547 nonzero, we block in this function until we've reaped at least one
548 complete child, waiting for it to die if necessary. If ERR is nonzero,
549 print an error message first. */
552 reap_children (int block
, int err
)
557 /* Initially, assume we have some. */
561 # define REAP_MORE reap_more
563 # define REAP_MORE dead_children
568 We have at least one child outstanding OR a shell function in progress,
570 We're blocking for a complete child OR there are more children to reap
572 we'll keep reaping children. */
574 while ((children
!= 0 || shell_function_pid
!= 0)
575 && (block
|| REAP_MORE
))
579 int exit_code
, exit_sig
, coredump
;
580 struct child
*lastc
, *c
;
582 int any_remote
, any_local
;
587 static int printed
= 0;
589 /* We might block for a while, so let the user know why.
590 Only print this message once no matter how many jobs are left. */
593 error (NILF
, _("*** Waiting for unfinished jobs...."));
597 /* We have one less dead child to reap. As noted in
598 child_handler() above, this count is completely unimportant for
599 all modern, POSIX-y systems that support wait3() or waitpid().
600 The rest of this comment below applies only to early, broken
601 pre-POSIX systems. We keep the count only because... it's there...
603 The test and decrement are not atomic; if it is compiled into:
604 register = dead_children - 1;
605 dead_children = register;
606 a SIGCHLD could come between the two instructions.
607 child_handler increments dead_children.
608 The second instruction here would lose that increment. But the
609 only effect of dead_children being wrong is that we might wait
610 longer than necessary to reap a child, and lose some parallelism;
611 and we might print the "Waiting for unfinished jobs" message above
612 when not necessary. */
614 if (dead_children
> 0)
618 any_local
= shell_function_pid
!= 0;
619 for (c
= children
; c
!= 0; c
= c
->next
)
621 any_remote
|= c
->remote
;
622 any_local
|= ! c
->remote
;
623 DB (DB_JOBS
, (_("Live child %p (%s) PID %s %s\n"),
624 c
, c
->file
->name
, pid2str (c
->pid
),
625 c
->remote
? _(" (remote)") : ""));
631 /* First, check for remote children. */
633 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 0);
638 /* We got a remote child. */
642 /* A remote status command failed miserably. Punt. */
644 pfatal_with_name ("remote_status");
648 /* No remote children. Check for local children. */
649 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
653 vmsWaitForChildren (&status
);
658 pid
= WAIT_NOHANG (&status
);
661 EINTRLOOP(pid
, wait (&status
));
669 /* The wait*() failed miserably. Punt. */
670 pfatal_with_name ("wait");
674 /* We got a child exit; chop the status word up. */
675 exit_code
= WEXITSTATUS (status
);
676 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
677 coredump
= WCOREDUMP (status
);
679 /* If we have started jobs in this second, remove one. */
685 /* No local children are dead. */
688 if (!block
|| !any_remote
)
691 /* Now try a blocking wait for a remote child. */
692 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 1);
694 goto remote_status_lose
;
696 /* No remote children either. Finally give up. */
699 /* We got a remote child. */
702 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
705 /* Life is very different on MSDOS. */
708 exit_code
= WEXITSTATUS (status
);
709 if (exit_code
== 0xff)
711 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
713 #endif /* __MSDOS__ */
717 status
= amiga_status
;
718 exit_code
= amiga_status
;
727 DWORD dwWaitStatus
= 0;
732 /* Record the thread ID of the main process, so that we
733 could suspend it in the signal handler. */
736 hcTID
= GetCurrentThread ();
737 hcPID
= GetCurrentProcess ();
738 if (!DuplicateHandle (hcPID
, hcTID
, hcPID
, &main_thread
, 0,
739 FALSE
, DUPLICATE_SAME_ACCESS
))
741 DWORD e
= GetLastError ();
743 "Determine main thread ID (Error %ld: %s)\n",
744 e
, map_windows32_error_to_string(e
));
747 DB (DB_VERBOSE
, ("Main thread handle = %p\n", main_thread
));
750 /* wait for anything to finish */
751 hPID
= process_wait_for_any(block
, &dwWaitStatus
);
755 /* was an error found on this process? */
756 werr
= process_last_err(hPID
);
759 exit_code
= process_exit_code(hPID
);
762 fprintf(stderr
, "make (e=%d): %s",
763 exit_code
, map_windows32_error_to_string(exit_code
));
766 exit_sig
= process_signal(hPID
);
768 /* cleanup process */
769 process_cleanup(hPID
);
773 else if (dwWaitStatus
== WAIT_FAILED
)
775 /* The WaitForMultipleObjects() failed miserably. Punt. */
776 pfatal_with_name ("WaitForMultipleObjects");
778 else if (dwWaitStatus
== WAIT_TIMEOUT
)
780 /* No child processes are finished. Give up waiting. */
787 #endif /* WINDOWS32 */
790 /* Check if this is the child of the 'shell' function. */
791 if (!remote
&& pid
== shell_function_pid
)
793 /* It is. Leave an indicator for the 'shell' function. */
794 if (exit_sig
== 0 && exit_code
== 127)
795 shell_function_completed
= -1;
797 shell_function_completed
= 1;
801 child_failed
= exit_sig
!= 0 || exit_code
!= 0;
803 /* Search for a child matching the deceased one. */
805 for (c
= children
; c
!= 0; lastc
= c
, c
= c
->next
)
806 if (c
->remote
== remote
&& c
->pid
== pid
)
810 /* An unknown child died.
811 Ignore it; it was inherited from our invoker. */
814 DB (DB_JOBS
, (child_failed
815 ? _("Reaping losing child %p PID %s %s\n")
816 : _("Reaping winning child %p PID %s %s\n"),
817 c
, pid2str (c
->pid
), c
->remote
? _(" (remote)") : ""));
819 if (c
->sh_batch_file
) {
822 DB (DB_JOBS
, (_("Cleaning up temp batch file %s\n"),
826 rm_status
= remove (c
->sh_batch_file
);
828 DB (DB_JOBS
, (_("Cleaning up temp batch file %s failed (%d)\n"),
829 c
->sh_batch_file
, errno
));
831 /* all done with memory */
832 free (c
->sh_batch_file
);
833 c
->sh_batch_file
= NULL
;
836 /* If this child had the good stdin, say it is now free. */
840 dontcare
= c
->dontcare
;
842 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
844 /* The commands failed. Write an error message,
845 delete non-precious targets, and abort. */
846 static int delete_on_error
= -1;
849 child_error (c
->file
, exit_code
, exit_sig
, coredump
, 0);
851 c
->file
->update_status
= 2;
852 if (delete_on_error
== -1)
854 struct file
*f
= lookup_file (".DELETE_ON_ERROR");
855 delete_on_error
= f
!= 0 && f
->is_target
;
857 if (exit_sig
!= 0 || delete_on_error
)
858 delete_child_targets (c
);
864 /* The commands failed, but we don't care. */
865 child_error (c
->file
, exit_code
, exit_sig
, coredump
, 1);
869 /* If there are more commands to run, try to start them. */
870 if (job_next_command (c
))
872 if (handling_fatal_signal
)
874 /* Never start new commands while we are dying.
875 Since there are more commands that wanted to be run,
876 the target was not completely remade. So we treat
877 this as if a command had failed. */
878 c
->file
->update_status
= 2;
882 /* Check again whether to start remotely.
883 Whether or not we want to changes over time.
884 Also, start_remote_job may need state set up
885 by start_remote_job_p. */
886 c
->remote
= start_remote_job_p (0);
887 start_job_command (c
);
888 /* Fatal signals are left blocked in case we were
889 about to put that child on the chain. But it is
890 already there, so it is safe for a fatal signal to
891 arrive now; it will clean up this child's targets. */
893 if (c
->file
->command_state
== cs_running
)
894 /* We successfully started the new command.
895 Loop to reap more children. */
899 if (c
->file
->update_status
!= 0)
900 /* We failed to start the commands. */
901 delete_child_targets (c
);
904 /* There are no more commands. We got through them all
905 without an unignored error. Now the target has been
906 successfully updated. */
907 c
->file
->update_status
= 0;
910 /* When we get here, all the commands for C->file are finished
911 (or aborted) and C->file->update_status contains 0 or 2. But
912 C->file->command_state is still cs_running if all the commands
913 ran; notice_finish_file looks for cs_running to tell it that
914 it's interesting to check the file's modtime again now. */
916 if (! handling_fatal_signal
)
917 /* Notice if the target of the commands has been changed.
918 This also propagates its values for command_state and
919 update_status to its also_make files. */
920 notice_finished_file (c
->file
);
922 DB (DB_JOBS
, (_("Removing child %p PID %s%s from chain.\n"),
923 c
, pid2str (c
->pid
), c
->remote
? _(" (remote)") : ""));
925 /* Block fatal signals while frobnicating the list, so that
926 children and job_slots_used are always consistent. Otherwise
927 a fatal signal arriving after the child is off the chain and
928 before job_slots_used is decremented would believe a child was
929 live and call reap_children again. */
932 /* There is now another slot open. */
933 if (job_slots_used
> 0)
936 /* Remove the child from the chain and free it. */
940 lastc
->next
= c
->next
;
946 /* If the job failed, and the -k flag was not given, die,
947 unless we are already in the process of dying. */
948 if (!err
&& child_failed
&& !dontcare
&& !keep_going_flag
&&
949 /* fatal_error_signal will die with the right signal. */
950 !handling_fatal_signal
)
953 /* Only block for one child. */
960 /* Free the storage allocated for CHILD. */
963 free_child (struct child
*child
)
965 if (!jobserver_tokens
)
966 fatal (NILF
, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
967 child
, child
->file
->name
);
969 /* If we're using the jobserver and this child is not the only outstanding
970 job, put a token back into the pipe for it. */
973 if (has_jobserver_semaphore() && jobserver_tokens
> 1)
975 if (! release_jobserver_semaphore())
977 DWORD err
= GetLastError();
978 fatal (NILF
, _("release jobserver semaphore: (Error %ld: %s)"),
979 err
, map_windows32_error_to_string(err
));
982 DB (DB_JOBS
, (_("Released token for child %p (%s).\n"), child
, child
->file
->name
));
985 if (job_fds
[1] >= 0 && jobserver_tokens
> 1)
990 /* Write a job token back to the pipe. */
992 EINTRLOOP (r
, write (job_fds
[1], &token
, 1));
994 pfatal_with_name (_("write jobserver"));
996 DB (DB_JOBS
, (_("Released token for child %p (%s).\n"),
997 child
, child
->file
->name
));
1003 if (handling_fatal_signal
) /* Don't bother free'ing if about to die. */
1006 if (child
->command_lines
!= 0)
1008 register unsigned int i
;
1009 for (i
= 0; i
< child
->file
->cmds
->ncommand_lines
; ++i
)
1010 free (child
->command_lines
[i
]);
1011 free (child
->command_lines
);
1014 if (child
->environment
!= 0)
1016 register char **ep
= child
->environment
;
1019 free (child
->environment
);
1026 extern sigset_t fatal_signal_set
;
1033 (void) sigprocmask (SIG_BLOCK
, &fatal_signal_set
, (sigset_t
*) 0);
1035 # ifdef HAVE_SIGSETMASK
1036 (void) sigblock (fatal_signal_mask
);
1046 sigemptyset (&empty
);
1047 sigprocmask (SIG_SETMASK
, &empty
, (sigset_t
*) 0);
1051 #if defined(MAKE_JOBSERVER) && !defined(WINDOWS32)
1053 job_noop (int sig UNUSED
)
1056 /* Set the child handler action flags to FLAGS. */
1058 set_child_handler_action_flags (int set_handler
, int set_alarm
)
1060 struct sigaction sa
;
1063 /* The child handler must be turned off here. */
1064 signal (SIGCHLD
, SIG_DFL
);
1067 memset (&sa
, '\0', sizeof sa
);
1068 sa
.sa_handler
= child_handler
;
1069 sa
.sa_flags
= set_handler
? 0 : SA_RESTART
;
1071 sigaction (SIGCHLD
, &sa
, NULL
);
1073 #if defined SIGCLD && SIGCLD != SIGCHLD
1074 sigaction (SIGCLD
, &sa
, NULL
);
1079 /* If we're about to enter the read(), set an alarm to wake up in a
1080 second so we can check if the load has dropped and we can start more
1081 work. On the way out, turn off the alarm and set SIG_DFL. */
1082 alarm (set_handler
? 1 : 0);
1083 sa
.sa_handler
= set_handler
? job_noop
: SIG_DFL
;
1085 sigaction (SIGALRM
, &sa
, NULL
);
1092 /* Start a job to run the commands specified in CHILD.
1093 CHILD is updated to reflect the commands and ID of the child process.
1095 NOTE: On return fatal signals are blocked! The caller is responsible
1096 for calling 'unblock_sigs', once the new child is safely on the chain so
1097 it can be cleaned up in the event of a fatal signal. */
1100 start_job_command (struct child
*child
)
1102 #if !defined(_AMIGA) && !defined(WINDOWS32)
1103 static int bad_stdin
= -1;
1106 /* Must be volatile to silence bogus GCC warning about longjmp/vfork. */
1114 /* If we have a completely empty commandset, stop now. */
1115 if (!child
->command_ptr
)
1118 /* Combine the flags parsed for the line itself with
1119 the flags specified globally for this target. */
1120 flags
= (child
->file
->command_flags
1121 | child
->file
->cmds
->lines_flags
[child
->command_line
- 1]);
1123 p
= child
->command_ptr
;
1124 child
->noerror
= ((flags
& COMMANDS_NOERROR
) != 0);
1129 flags
|= COMMANDS_SILENT
;
1131 flags
|= COMMANDS_RECURSE
;
1134 else if (!isblank ((unsigned char)*p
))
1139 /* Update the file's command flags with any new ones we found. We only
1140 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
1141 now marking more commands recursive than should be in the case of
1142 multiline define/endef scripts where only one line is marked "+". In
1143 order to really fix this, we'll have to keep a lines_flags for every
1144 actual line, after expansion. */
1145 child
->file
->cmds
->lines_flags
[child
->command_line
- 1]
1146 |= flags
& COMMANDS_RECURSE
;
1148 /* POSIX requires that a recipe prefix after a backslash-newline should
1149 be ignored. Remove it now so the output is correct. */
1151 char prefix
= child
->file
->cmds
->recipe_prefix
;
1157 if (p1
[0] == '\n' && p1
[1] == prefix
)
1164 /* Figure out an argument list from this command line. */
1170 argv
= construct_command_argv (p
, &end
, child
->file
,
1171 child
->file
->cmds
->lines_flags
[child
->command_line
- 1],
1172 &child
->sh_batch_file
);
1175 child
->command_ptr
= NULL
;
1179 child
->command_ptr
= end
;
1183 /* If -q was given, say that updating 'failed' if there was any text on the
1184 command line, or 'succeeded' otherwise. The exit status of 1 tells the
1185 user that -q is saying 'something to do'; the exit status for a random
1187 if (argv
!= 0 && question_flag
&& !(flags
& COMMANDS_RECURSE
))
1193 child
->file
->update_status
= 1;
1194 notice_finished_file (child
->file
);
1198 if (touch_flag
&& !(flags
& COMMANDS_RECURSE
))
1200 /* Go on to the next command. It might be the recursive one.
1201 We construct ARGV only to find the end of the command line. */
1216 execute_by_shell
= 0; /* in case construct_command_argv sets it */
1218 /* This line has no commands. Go to the next. */
1219 if (job_next_command (child
))
1220 start_job_command (child
);
1223 /* No more commands. Make sure we're "running"; we might not be if
1224 (e.g.) all commands were skipped due to -n. */
1225 set_command_state (child
->file
, cs_running
);
1226 child
->file
->update_status
= 0;
1227 notice_finished_file (child
->file
);
1232 /* Print out the command. If silent, we call 'message' with null so it
1233 can log the working directory before the command's own error messages
1236 message (0, (just_print_flag
|| trace_flag
1237 || (!(flags
& COMMANDS_SILENT
) && !silent_flag
))
1238 ? "%s" : (char *) 0, p
);
1240 /* Tell update_goal_chain that a command has been started on behalf of
1241 this target. It is important that this happens here and not in
1242 reap_children (where we used to do it), because reap_children might be
1243 reaping children from a different target. We want this increment to
1244 guaranteedly indicate that a command was started for the dependency
1245 chain (i.e., update_file recursion chain) we are processing. */
1249 /* Optimize an empty command. People use this for timestamp rules,
1250 so avoid forking a useless shell. Do this after we increment
1251 commands_started so make still treats this special case as if it
1252 performed some action (makes a difference as to what messages are
1255 #if !defined(VMS) && !defined(_AMIGA)
1257 #if defined __MSDOS__ || defined (__EMX__)
1258 unixy_shell
/* the test is complicated and we already did it */
1260 (argv
[0] && is_bourne_compatible_shell(argv
[0]))
1262 && (argv
[1] && argv
[1][0] == '-'
1264 ((argv
[1][1] == 'c' && argv
[1][2] == '\0')
1266 (argv
[1][1] == 'e' && argv
[1][2] == 'c' && argv
[1][3] == '\0')))
1267 && (argv
[2] && argv
[2][0] == ':' && argv
[2][1] == '\0')
1274 #endif /* !VMS && !_AMIGA */
1276 /* If -n was given, recurse to get the next line in the sequence. */
1278 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
))
1287 /* Flush the output streams so they won't have things written twice. */
1293 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1295 /* Set up a bad standard input that reads from a broken pipe. */
1297 if (bad_stdin
== -1)
1299 /* Make a file descriptor that is the read end of a broken pipe.
1300 This will be used for some children's standard inputs. */
1304 /* Close the write side. */
1305 (void) close (pd
[1]);
1306 /* Save the read side. */
1309 /* Set the descriptor to close on exec, so it does not litter any
1310 child's descriptor table. When it is dup2'd onto descriptor 0,
1311 that descriptor will not close on exec. */
1312 CLOSE_ON_EXEC (bad_stdin
);
1316 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1318 /* Decide whether to give this child the 'good' standard input
1319 (one that points to the terminal or whatever), or the 'bad' one
1320 that points to the read side of a broken pipe. */
1322 child
->good_stdin
= !good_stdin_used
;
1323 if (child
->good_stdin
)
1324 good_stdin_used
= 1;
1331 /* Set up the environment for the child. */
1332 if (child
->environment
== 0)
1333 child
->environment
= target_environment (child
->file
);
1336 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1339 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1342 int is_remote
, id
, used_stdin
;
1343 if (start_remote_job (argv
, child
->environment
,
1344 child
->good_stdin
? 0 : bad_stdin
,
1345 &is_remote
, &id
, &used_stdin
))
1346 /* Don't give up; remote execution may fail for various reasons. If
1347 so, simply run the job locally. */
1351 if (child
->good_stdin
&& !used_stdin
)
1353 child
->good_stdin
= 0;
1354 good_stdin_used
= 0;
1356 child
->remote
= is_remote
;
1363 /* Fork the child process. */
1365 char **parent_environ
;
1373 if (!child_execute_job (argv
, child
)) {
1375 perror_with_name ("vfork", "");
1381 parent_environ
= environ
;
1384 /* If we aren't running a recursive command and we have a jobserver
1385 pipe, close it before exec'ing. */
1386 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1388 CLOSE_ON_EXEC (job_fds
[0]);
1389 CLOSE_ON_EXEC (job_fds
[1]);
1392 CLOSE_ON_EXEC (job_rfd
);
1394 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1395 child
->pid
= child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1396 argv
, child
->environment
);
1401 perror_with_name ("spawn", "");
1405 /* undo CLOSE_ON_EXEC() after the child process has been started */
1406 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1408 fcntl (job_fds
[0], F_SETFD
, 0);
1409 fcntl (job_fds
[1], F_SETFD
, 0);
1412 fcntl (job_rfd
, F_SETFD
, 0);
1414 #else /* !__EMX__ */
1416 child
->pid
= vfork ();
1417 environ
= parent_environ
; /* Restore value child may have clobbered. */
1418 if (child
->pid
== 0)
1420 /* We are the child side. */
1423 /* If we aren't running a recursive command and we have a jobserver
1424 pipe, close it before exec'ing. */
1425 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1433 #ifdef SET_STACK_SIZE
1434 /* Reset limits, if necessary. */
1435 if (stack_limit
.rlim_cur
)
1436 setrlimit (RLIMIT_STACK
, &stack_limit
);
1439 child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1440 argv
, child
->environment
);
1442 else if (child
->pid
< 0)
1446 perror_with_name ("vfork", "");
1449 # endif /* !__EMX__ */
1453 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1461 /* We call 'system' to do the job of the SHELL, since stock DOS
1462 shell is too dumb. Our 'system' knows how to handle long
1463 command lines even if pipes/redirection is needed; it will only
1464 call COMMAND.COM when its internal commands are used. */
1465 if (execute_by_shell
)
1467 char *cmdline
= argv
[0];
1468 /* We don't have a way to pass environment to 'system',
1469 so we need to save and restore ours, sigh... */
1470 char **parent_environ
= environ
;
1472 environ
= child
->environment
;
1474 /* If we have a *real* shell, tell 'system' to call
1475 it to do everything for us. */
1478 /* A *real* shell on MSDOS may not support long
1479 command lines the DJGPP way, so we must use 'system'. */
1480 cmdline
= argv
[2]; /* get past "shell -c" */
1483 dos_command_running
= 1;
1484 proc_return
= system (cmdline
);
1485 environ
= parent_environ
;
1486 execute_by_shell
= 0; /* for the next time */
1490 dos_command_running
= 1;
1491 proc_return
= spawnvpe (P_WAIT
, argv
[0], argv
, child
->environment
);
1494 /* Need to unblock signals before turning off
1495 dos_command_running, so that child's signals
1496 will be treated as such (see fatal_error_signal). */
1498 dos_command_running
= 0;
1500 /* If the child got a signal, dos_status has its
1501 high 8 bits set, so be careful not to alter them. */
1502 if (proc_return
== -1)
1505 dos_status
|= (proc_return
& 0xff);
1507 child
->pid
= dos_pid
++;
1509 #endif /* __MSDOS__ */
1511 amiga_status
= MyExecute (argv
);
1514 child
->pid
= amiga_pid
++;
1515 if (amiga_batch_file
)
1517 amiga_batch_file
= 0;
1518 DeleteFile (amiga_bname
); /* Ignore errors. */
1526 /* make UNC paths safe for CreateProcess -- backslash format */
1528 if (arg0
&& arg0
[0] == '/' && arg0
[1] == '/')
1529 for ( ; arg0
&& *arg0
; arg0
++)
1533 /* make sure CreateProcess() has Path it needs */
1534 sync_Path_environment();
1536 hPID
= process_easy(argv
, child
->environment
);
1538 if (hPID
!= INVALID_HANDLE_VALUE
)
1539 child
->pid
= (pid_t
) hPID
;
1544 _("process_easy() failed to launch process (e=%ld)\n"),
1545 process_last_err(hPID
));
1546 for (i
= 0; argv
[i
]; i
++)
1547 fprintf(stderr
, "%s ", argv
[i
]);
1548 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
1552 #endif /* WINDOWS32 */
1553 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1555 /* Bump the number of jobs started in this second. */
1558 /* We are the parent side. Set the state to
1559 say the commands are running and return. */
1561 set_command_state (child
->file
, cs_running
);
1563 /* Free the storage used by the child's argument list. */
1572 child
->file
->update_status
= 2;
1573 notice_finished_file (child
->file
);
1577 /* Try to start a child running.
1578 Returns nonzero if the child was started (and maybe finished), or zero if
1579 the load was too high and the child was put on the 'waiting_jobs' chain. */
1582 start_waiting_job (struct child
*c
)
1584 struct file
*f
= c
->file
;
1586 /* If we can start a job remotely, we always want to, and don't care about
1587 the local load average. We record that the job should be started
1588 remotely in C->remote for start_job_command to test. */
1590 c
->remote
= start_remote_job_p (1);
1592 /* If we are running at least one job already and the load average
1593 is too high, make this one wait. */
1595 && ((job_slots_used
> 0 && load_too_high ())
1597 || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS
)
1601 /* Put this child on the chain of children waiting for the load average
1603 set_command_state (f
, cs_running
);
1604 c
->next
= waiting_jobs
;
1609 /* Start the first command; reap_children will run later command lines. */
1610 start_job_command (c
);
1612 switch (f
->command_state
)
1616 DB (DB_JOBS
, (_("Putting child %p (%s) PID %s%s on the chain.\n"),
1617 c
, c
->file
->name
, pid2str (c
->pid
),
1618 c
->remote
? _(" (remote)") : ""));
1620 /* One more job slot is in use. */
1625 case cs_not_started
:
1626 /* All the command lines turned out to be empty. */
1627 f
->update_status
= 0;
1631 notice_finished_file (f
);
1636 assert (f
->command_state
== cs_finished
);
1643 /* Create a 'struct child' for FILE and start its commands running. */
1646 new_job (struct file
*file
)
1648 struct commands
*cmds
= file
->cmds
;
1653 /* Let any previously decided-upon jobs that are waiting
1654 for the load to go down start before this new one. */
1655 start_waiting_jobs ();
1657 /* Reap any children that might have finished recently. */
1658 reap_children (0, 0);
1660 /* Chop the commands up into lines if they aren't already. */
1661 chop_commands (cmds
);
1663 /* Expand the command lines and store the results in LINES. */
1664 lines
= xmalloc (cmds
->ncommand_lines
* sizeof (char *));
1665 for (i
= 0; i
< cmds
->ncommand_lines
; ++i
)
1667 /* Collapse backslash-newline combinations that are inside variable
1668 or function references. These are left alone by the parser so
1669 that they will appear in the echoing of commands (where they look
1670 nice); and collapsed by construct_command_argv when it tokenizes.
1671 But letting them survive inside function invocations loses because
1672 we don't want the functions to see them as part of the text. */
1674 char *in
, *out
, *ref
;
1676 /* IN points to where in the line we are scanning.
1677 OUT points to where in the line we are writing.
1678 When we collapse a backslash-newline combination,
1679 IN gets ahead of OUT. */
1681 in
= out
= cmds
->command_lines
[i
];
1682 while ((ref
= strchr (in
, '$')) != 0)
1684 ++ref
; /* Move past the $. */
1687 /* Copy the text between the end of the last chunk
1688 we processed (where IN points) and the new chunk
1689 we are about to process (where REF points). */
1690 memmove (out
, in
, ref
- in
);
1692 /* Move both pointers past the boring stuff. */
1696 if (*ref
== '(' || *ref
== '{')
1698 char openparen
= *ref
;
1699 char closeparen
= openparen
== '(' ? ')' : '}';
1703 *out
++ = *in
++; /* Copy OPENPAREN. */
1704 /* IN now points past the opening paren or brace.
1705 Count parens or braces until it is matched. */
1709 if (*in
== closeparen
&& --count
< 0)
1711 else if (*in
== '\\' && in
[1] == '\n')
1713 /* We have found a backslash-newline inside a
1714 variable or function reference. Eat it and
1715 any following whitespace. */
1718 for (p
= in
- 1; p
> ref
&& *p
== '\\'; --p
)
1722 /* There were two or more backslashes, so this is
1723 not really a continuation line. We don't collapse
1724 the quoting backslashes here as is done in
1725 collapse_continuations, because the line will
1726 be collapsed again after expansion. */
1730 /* Skip the backslash, newline and
1731 any following whitespace. */
1732 in
= next_token (in
+ 2);
1734 /* Discard any preceding whitespace that has
1735 already been written to the output. */
1737 && isblank ((unsigned char)out
[-1]))
1740 /* Replace it all with a single space. */
1746 if (*in
== openparen
)
1755 /* There are no more references in this line to worry about.
1756 Copy the remaining uninteresting text to the output. */
1758 memmove (out
, in
, strlen (in
) + 1);
1760 /* Finally, expand the line. */
1761 lines
[i
] = allocated_variable_expand_for_file (cmds
->command_lines
[i
],
1765 /* Start the command sequence, record it in a new
1766 'struct child', and add that to the chain. */
1768 c
= xcalloc (sizeof (struct child
));
1770 c
->command_lines
= lines
;
1771 c
->sh_batch_file
= NULL
;
1773 /* Cache dontcare flag because file->dontcare can be changed once we
1774 return. Check dontcare inheritance mechanism for details. */
1775 c
->dontcare
= file
->dontcare
;
1777 /* Fetch the first command line to be run. */
1778 job_next_command (c
);
1780 /* Wait for a job slot to be freed up. If we allow an infinite number
1781 don't bother; also job_slots will == 0 if we're using the jobserver. */
1784 while (job_slots_used
== job_slots
)
1785 reap_children (1, 0);
1787 #ifdef MAKE_JOBSERVER
1788 /* If we are controlling multiple jobs make sure we have a token before
1789 starting the child. */
1791 /* This can be inefficient. There's a decent chance that this job won't
1792 actually have to run any subprocesses: the command script may be empty
1793 or otherwise optimized away. It would be nice if we could defer
1794 obtaining a token until just before we need it, in start_job_command.
1795 To do that we'd need to keep track of whether we'd already obtained a
1796 token (since start_job_command is called for each line of the job, not
1797 just once). Also more thought needs to go into the entire algorithm;
1798 this is where the old parallel job code waits, so... */
1801 else if (has_jobserver_semaphore())
1803 else if (job_fds
[0] >= 0)
1813 DB (DB_JOBS
, ("Need a job token; we %shave children\n",
1814 children
? "" : "don't "));
1816 /* If we don't already have a job started, use our "free" token. */
1817 if (!jobserver_tokens
)
1821 /* Read a token. As long as there's no token available we'll block.
1822 We enable interruptible system calls before the read(2) so that if
1823 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1824 we can process the death(s) and return tokens to the free pool.
1826 Once we return from the read, we immediately reinstate restartable
1827 system calls. This allows us to not worry about checking for
1828 EINTR on all the other system calls in the program.
1830 There is one other twist: there is a span between the time
1831 reap_children() does its last check for dead children and the time
1832 the read(2) call is entered, below, where if a child dies we won't
1833 notice. This is extremely serious as it could cause us to
1834 deadlock, given the right set of events.
1836 To avoid this, we do the following: before we reap_children(), we
1837 dup(2) the read FD on the jobserver pipe. The read(2) call below
1838 uses that new FD. In the signal handler, we close that FD. That
1839 way, if a child dies during the section mentioned above, the
1840 read(2) will be invoked with an invalid FD and will return
1841 immediately with EBADF. */
1843 /* Make sure we have a dup'd FD. */
1846 DB (DB_JOBS
, ("Duplicate the job FD\n"));
1847 job_rfd
= dup (job_fds
[0]);
1851 /* Reap anything that's currently waiting. */
1852 reap_children (0, 0);
1854 /* Kick off any jobs we have waiting for an opportunity that
1855 can run now (ie waiting for load). */
1856 start_waiting_jobs ();
1858 /* If our "free" slot has become available, use it; we don't need an
1860 if (!jobserver_tokens
)
1863 /* There must be at least one child already, or we have no business
1864 waiting for a token. */
1866 fatal (NILF
, "INTERNAL: no children as we go to sleep on read\n");
1869 /* On Windows we simply wait for the jobserver semaphore to become
1870 * signalled or one of our child processes to terminate.
1872 got_token
= wait_for_semaphore_or_child_process();
1875 DWORD err
= GetLastError();
1876 fatal (NILF
, _("semaphore or child process wait: (Error %ld: %s)"),
1877 err
, map_windows32_error_to_string(err
));
1880 /* Set interruptible system calls, and read() for a job token. */
1881 set_child_handler_action_flags (1, waiting_jobs
!= NULL
);
1882 got_token
= read (job_rfd
, &token
, 1);
1883 saved_errno
= errno
;
1884 set_child_handler_action_flags (0, waiting_jobs
!= NULL
);
1887 /* If we got one, we're done here. */
1890 DB (DB_JOBS
, (_("Obtained token for child %p (%s).\n"),
1896 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1897 go back and reap_children(), and try again. */
1898 errno
= saved_errno
;
1899 if (errno
!= EINTR
&& errno
!= EBADF
)
1900 pfatal_with_name (_("read jobs pipe"));
1902 DB (DB_JOBS
, ("Read returned EBADF.\n"));
1910 Use message here so that changes to working directories are logged. */
1913 char *newer
= allocated_variable_expand_for_file ("$?", c
->file
);
1916 if (! cmds
->fileinfo
.filenm
)
1917 nm
= _("<builtin>");
1920 nm
= alloca (strlen (cmds
->fileinfo
.filenm
) + 1 + 11 + 1);
1921 sprintf (nm
, "%s:%lu", cmds
->fileinfo
.filenm
, cmds
->fileinfo
.lineno
);
1924 if (newer
[0] == '\0')
1925 message (0, _("%s: target '%s' does not exist"), nm
, c
->file
->name
);
1927 message (0, _("%s: update target '%s' due to: %s"), nm
,
1928 c
->file
->name
, newer
);
1934 /* The job is now primed. Start it running.
1935 (This will notice if there is in fact no recipe.) */
1936 start_waiting_job (c
);
1938 if (job_slots
== 1 || not_parallel
)
1939 /* Since there is only one job slot, make things run linearly.
1940 Wait for the child to die, setting the state to 'cs_finished'. */
1941 while (file
->command_state
== cs_running
)
1942 reap_children (1, 0);
1947 /* Move CHILD's pointers to the next command for it to execute.
1948 Returns nonzero if there is another command. */
1951 job_next_command (struct child
*child
)
1953 while (child
->command_ptr
== 0 || *child
->command_ptr
== '\0')
1955 /* There are no more lines in the expansion of this line. */
1956 if (child
->command_line
== child
->file
->cmds
->ncommand_lines
)
1958 /* There are no more lines to be expanded. */
1959 child
->command_ptr
= 0;
1963 /* Get the next line to run. */
1964 child
->command_ptr
= child
->command_lines
[child
->command_line
++];
1969 /* Determine if the load average on the system is too high to start a new job.
1970 The real system load average is only recomputed once a second. However, a
1971 very parallel make can easily start tens or even hundreds of jobs in a
1972 second, which brings the system to its knees for a while until that first
1973 batch of jobs clears out.
1975 To avoid this we use a weighted algorithm to try to account for jobs which
1976 have been started since the last second, and guess what the load average
1977 would be now if it were computed.
1979 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1982 ! calculate something load-oid and add to the observed sys.load,
1983 ! so that latter can catch up:
1984 ! - every job started increases jobctr;
1985 ! - every dying job decreases a positive jobctr;
1986 ! - the jobctr value gets zeroed every change of seconds,
1987 ! after its value*weight_b is stored into the 'backlog' value last_sec
1988 ! - weight_a times the sum of jobctr and last_sec gets
1989 ! added to the observed sys.load.
1991 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1992 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1993 ! sub-shelled commands (rm, echo, sed...) for tests.
1994 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1995 ! resulted in significant excession of the load limit, raising it
1996 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1997 ! reach the limit in most test cases.
1999 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
2000 ! exceeding the limit for longer-running stuff (compile jobs in
2001 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
2002 ! small jobs' effects.
2006 #define LOAD_WEIGHT_A 0.25
2007 #define LOAD_WEIGHT_B 0.25
2010 load_too_high (void)
2012 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
2015 static double last_sec
;
2016 static time_t last_now
;
2021 /* sub_proc.c cannot wait for more than MAXIMUM_WAIT_OBJECTS children */
2022 if (process_used_slots () >= MAXIMUM_WAIT_OBJECTS
)
2026 if (max_load_average
< 0)
2029 /* Find the real system load average. */
2031 if (getloadavg (&load
, 1) != 1)
2033 static int lossage
= -1;
2034 /* Complain only once for the same error. */
2035 if (lossage
== -1 || errno
!= lossage
)
2038 /* An errno value of zero means getloadavg is just unsupported. */
2040 _("cannot enforce load limits on this operating system"));
2042 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
2049 /* If we're in a new second zero the counter and correct the backlog
2050 value. Only keep the backlog for one extra second; after that it's 0. */
2054 if (last_now
== now
- 1)
2055 last_sec
= LOAD_WEIGHT_B
* job_counter
;
2063 /* Try to guess what the load would be right now. */
2064 guess
= load
+ (LOAD_WEIGHT_A
* (job_counter
+ last_sec
));
2066 DB (DB_JOBS
, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
2067 guess
, load
, max_load_average
));
2069 return guess
>= max_load_average
;
2073 /* Start jobs that are waiting for the load to be lower. */
2076 start_waiting_jobs (void)
2080 if (waiting_jobs
== 0)
2085 /* Check for recently deceased descendants. */
2086 reap_children (0, 0);
2088 /* Take a job off the waiting list. */
2090 waiting_jobs
= job
->next
;
2092 /* Try to start that job. We break out of the loop as soon
2093 as start_waiting_job puts one back on the waiting list. */
2095 while (start_waiting_job (job
) && waiting_jobs
!= 0);
2102 /* EMX: Start a child process. This function returns the new pid. */
2103 # if defined __EMX__
2105 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2108 /* stdin_fd == 0 means: nothing to do for stdin;
2109 stdout_fd == 1 means: nothing to do for stdout */
2110 int save_stdin
= (stdin_fd
!= 0) ? dup (0) : 0;
2111 int save_stdout
= (stdout_fd
!= 1) ? dup (1): 1;
2113 /* < 0 only if dup() failed */
2115 fatal (NILF
, _("no more file handles: could not duplicate stdin\n"));
2116 if (save_stdout
< 0)
2117 fatal (NILF
, _("no more file handles: could not duplicate stdout\n"));
2119 /* Close unnecessary file handles for the child. */
2120 if (save_stdin
!= 0)
2121 CLOSE_ON_EXEC (save_stdin
);
2122 if (save_stdout
!= 1)
2123 CLOSE_ON_EXEC (save_stdout
);
2125 /* Connect the pipes to the child process. */
2127 (void) dup2 (stdin_fd
, 0);
2129 (void) dup2 (stdout_fd
, 1);
2131 /* stdin_fd and stdout_fd must be closed on exit because we are
2132 still in the parent process */
2134 CLOSE_ON_EXEC (stdin_fd
);
2136 CLOSE_ON_EXEC (stdout_fd
);
2138 /* Run the command. */
2139 pid
= exec_command (argv
, envp
);
2141 /* Restore stdout/stdin of the parent and close temporary FDs. */
2144 if (dup2 (save_stdin
, 0) != 0)
2145 fatal (NILF
, _("Could not restore stdin\n"));
2152 if (dup2 (save_stdout
, 1) != 1)
2153 fatal (NILF
, _("Could not restore stdout\n"));
2155 close (save_stdout
);
2161 #elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
2164 Replace the current process with one executing the command in ARGV.
2165 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2166 the environment of the new program. This function does not return. */
2168 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2171 (void) dup2 (stdin_fd
, 0);
2173 (void) dup2 (stdout_fd
, 1);
2175 (void) close (stdin_fd
);
2177 (void) close (stdout_fd
);
2179 /* Run the command. */
2180 exec_command (argv
, envp
);
2182 #endif /* !AMIGA && !__MSDOS__ && !VMS */
2183 #endif /* !WINDOWS32 */
2186 /* Replace the current process with one running the command in ARGV,
2187 with environment ENVP. This function does not return. */
2189 /* EMX: This function returns the pid of the child process. */
2195 exec_command (char **argv
, char **envp
)
2198 /* to work around a problem with signals and execve: ignore them */
2200 signal (SIGCHLD
,SIG_IGN
);
2202 /* Run the program. */
2203 execve (argv
[0], argv
, envp
);
2204 perror_with_name ("execve: ", argv
[0]);
2205 _exit (EXIT_FAILURE
);
2211 int exit_code
= EXIT_FAILURE
;
2213 /* make sure CreateProcess() has Path it needs */
2214 sync_Path_environment();
2216 /* launch command */
2217 hPID
= process_easy(argv
, envp
);
2219 /* make sure launch ok */
2220 if (hPID
== INVALID_HANDLE_VALUE
)
2224 _("process_easy() failed to launch process (e=%ld)\n"),
2225 process_last_err(hPID
));
2226 for (i
= 0; argv
[i
]; i
++)
2227 fprintf(stderr
, "%s ", argv
[i
]);
2228 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
2232 /* wait and reap last child */
2233 hWaitPID
= process_wait_for_any(1, 0);
2236 /* was an error found on this process? */
2237 err
= process_last_err(hWaitPID
);
2240 exit_code
= process_exit_code(hWaitPID
);
2243 fprintf(stderr
, "make (e=%d, rc=%d): %s",
2244 err
, exit_code
, map_windows32_error_to_string(err
));
2246 /* cleanup process */
2247 process_cleanup(hWaitPID
);
2249 /* expect to find only last pid, warn about other pids reaped */
2250 if (hWaitPID
== hPID
)
2254 char *pidstr
= xstrdup (pid2str ((pid_t
)hWaitPID
));
2257 _("make reaped child pid %s, still waiting for pid %s\n"),
2258 pidstr
, pid2str ((pid_t
)hPID
));
2263 /* return child's exit code as our exit code */
2266 #else /* !WINDOWS32 */
2272 /* Be the user, permanently. */
2277 /* Run the program. */
2278 pid
= spawnvpe (P_NOWAIT
, argv
[0], argv
, envp
);
2283 /* the file might have a strange shell extension */
2284 if (errno
== ENOENT
)
2289 /* Run the program. */
2291 execvp (argv
[0], argv
);
2293 # endif /* !__EMX__ */
2298 error (NILF
, _("%s: Command not found"), argv
[0]);
2302 /* The file is not executable. Try it as a shell script. */
2303 extern char *getenv ();
2310 /* Do not use $SHELL from the environment */
2311 struct variable
*p
= lookup_variable ("SHELL", 5);
2317 shell
= getenv ("SHELL");
2320 shell
= default_shell
;
2323 while (argv
[argc
] != 0)
2331 new_argv
= alloca ((1 + argc
+ 1) * sizeof (char *));
2332 new_argv
[0] = shell
;
2343 new_argv
[i
] = argv
[0];
2346 new_argv
[i
+ argc
] = argv
[argc
];
2351 pid
= spawnvpe (P_NOWAIT
, shell
, new_argv
, envp
);
2355 execvp (shell
, new_argv
);
2357 if (errno
== ENOENT
)
2358 error (NILF
, _("%s: Shell program not found"), shell
);
2360 perror_with_name ("execvp: ", shell
);
2366 /* this nasty error was driving me nuts :-( */
2367 error (NILF
, _("spawnvpe: environment space might be exhausted"));
2372 perror_with_name ("execvp: ", argv
[0]);
2381 #endif /* !WINDOWS32 */
2384 #else /* On Amiga */
2385 void exec_command (char **argv
)
2390 void clean_tmp (void)
2392 DeleteFile (amiga_bname
);
2395 #endif /* On Amiga */
2398 /* Figure out the argument list necessary to run LINE as a command. Try to
2399 avoid using a shell. This routine handles only ' quoting, and " quoting
2400 when no backslash, $ or ' characters are seen in the quotes. Starting
2401 quotes may be escaped with a backslash. If any of the characters in
2402 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2403 is the first word of a line, the shell is used.
2405 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2406 If *RESTP is NULL, newlines will be ignored.
2408 SHELL is the shell to use, or nil to use the default shell.
2409 IFS is the value of $IFS, or nil (meaning the default).
2411 FLAGS is the value of lines_flags for this command line. It is
2412 used in the WINDOWS32 port to check whether + or $(MAKE) were found
2413 in this command line, in which case the effect of just_print_flag
2417 construct_command_argv_internal (char *line
, char **restp
, char *shell
,
2418 char *shellflags
, char *ifs
, int flags
,
2419 char **batch_filename UNUSED
)
2422 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2423 We call 'system' for anything that requires ''slow'' processing,
2424 because DOS shells are too dumb. When $SHELL points to a real
2425 (unix-style) shell, 'system' just calls it to do everything. When
2426 $SHELL points to a DOS shell, 'system' does most of the work
2427 internally, calling the shell only for its internal commands.
2428 However, it looks on the $PATH first, so you can e.g. have an
2429 external command named 'mkdir'.
2431 Since we call 'system', certain characters and commands below are
2432 actually not specific to COMMAND.COM, but to the DJGPP implementation
2433 of 'system'. In particular:
2435 The shell wildcard characters are in DOS_CHARS because they will
2436 not be expanded if we call the child via 'spawnXX'.
2438 The ';' is in DOS_CHARS, because our 'system' knows how to run
2439 multiple commands on a single line.
2441 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2442 won't have to tell one from another and have one more set of
2443 commands and special characters. */
2444 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2445 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2446 "copy", "ctty", "date", "del", "dir", "echo",
2447 "erase", "exit", "for", "goto", "if", "md",
2448 "mkdir", "path", "pause", "prompt", "rd",
2449 "rmdir", "rem", "ren", "rename", "set",
2450 "shift", "time", "type", "ver", "verify",
2453 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2454 static char *sh_cmds_sh
[] = { "cd", "echo", "eval", "exec", "exit", "login",
2455 "logout", "set", "umask", "wait", "while",
2456 "for", "case", "if", ":", ".", "break",
2457 "continue", "export", "read", "readonly",
2458 "shift", "times", "trap", "switch", "unset",
2463 #elif defined (__EMX__)
2464 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2465 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2466 "copy", "ctty", "date", "del", "dir", "echo",
2467 "erase", "exit", "for", "goto", "if", "md",
2468 "mkdir", "path", "pause", "prompt", "rd",
2469 "rmdir", "rem", "ren", "rename", "set",
2470 "shift", "time", "type", "ver", "verify",
2473 static char sh_chars_os2
[] = "*?[];|<>%^()\"'&";
2474 static char *sh_cmds_os2
[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2475 "date", "del", "detach", "dir", "echo",
2476 "endlocal", "erase", "exit", "for", "goto", "if",
2477 "keys", "md", "mkdir", "move", "path", "pause",
2478 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2479 "set", "setlocal", "shift", "start", "time",
2480 "type", "ver", "verify", "vol", ":", 0 };
2482 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^~'";
2483 static char *sh_cmds_sh
[] = { "echo", "cd", "eval", "exec", "exit", "login",
2484 "logout", "set", "umask", "wait", "while",
2485 "for", "case", "if", ":", ".", "break",
2486 "continue", "export", "read", "readonly",
2487 "shift", "times", "trap", "switch", "unset",
2492 #elif defined (_AMIGA)
2493 static char sh_chars
[] = "#;\"|<>()?*$`";
2494 static char *sh_cmds
[] = { "cd", "eval", "if", "delete", "echo", "copy",
2495 "rename", "set", "setenv", "date", "makedir",
2496 "skip", "else", "endif", "path", "prompt",
2497 "unset", "unsetenv", "version",
2499 #elif defined (WINDOWS32)
2500 /* We used to have a double quote (") in sh_chars_dos[] below, but
2501 that caused any command line with quoted file names be run
2502 through a temporary batch file, which introduces command-line
2503 limit of 4K charcaters imposed by cmd.exe. Since CreateProcess
2504 can handle quoted file names just fine, removing the quote lifts
2505 the limit from a very frequent use case, because using quoted
2506 file names is commonplace on MS-Windows. */
2507 static char sh_chars_dos
[] = "|&<>";
2508 static char *sh_cmds_dos
[] = { "assoc", "break", "call", "cd", "chcp",
2509 "chdir", "cls", "color", "copy", "ctty",
2510 "date", "del", "dir", "echo", "echo.",
2511 "endlocal", "erase", "exit", "for", "ftype",
2512 "goto", "if", "if", "md", "mkdir", "path",
2513 "pause", "prompt", "rd", "rem", "ren",
2514 "rename", "rmdir", "set", "setlocal",
2515 "shift", "time", "title", "type", "ver",
2516 "verify", "vol", ":", 0 };
2517 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2518 static char *sh_cmds_sh
[] = { "cd", "eval", "exec", "exit", "login",
2519 "logout", "set", "umask", "wait", "while", "for",
2520 "case", "if", ":", ".", "break", "continue",
2521 "export", "read", "readonly", "shift", "times",
2522 "trap", "switch", "test",
2523 #ifdef BATCH_MODE_ONLY_SHELL
2529 #elif defined(__riscos__)
2530 static char sh_chars
[] = "";
2531 static char *sh_cmds
[] = { 0 };
2532 #else /* must be UNIX-ish */
2533 static char sh_chars
[] = "#;\"*?[]&|<>(){}$`^~!";
2534 static char *sh_cmds
[] = { ".", ":", "break", "case", "cd", "continue",
2535 "eval", "exec", "exit", "export", "for", "if",
2536 "login", "logout", "read", "readonly", "set",
2537 "shift", "switch", "test", "times", "trap",
2538 "ulimit", "umask", "unset", "wait", "while", 0 };
2539 # ifdef HAVE_DOS_PATHS
2540 /* This is required if the MSYS/Cygwin ports (which do not define
2541 WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
2542 sh_chars_sh[] directly (see below). */
2543 static char *sh_chars_sh
= sh_chars
;
2544 # endif /* HAVE_DOS_PATHS */
2550 int instring
, word_has_equals
, seen_nonequals
, last_argument_was_empty
;
2551 char **new_argv
= 0;
2557 sh_cmds
= sh_cmds_dos
;
2558 sh_chars
= sh_chars_dos
;
2560 sh_cmds
= sh_cmds_sh
;
2561 sh_chars
= sh_chars_sh
;
2563 #endif /* WINDOWS32 */
2568 /* Make sure not to bother processing an empty line. */
2569 while (isblank ((unsigned char)*line
))
2574 if (shellflags
== 0)
2575 shellflags
= posix_pedantic
? "-ec" : "-c";
2577 /* See if it is safe to parse commands internally. */
2579 shell
= default_shell
;
2581 else if (strcmp (shell
, default_shell
))
2583 char *s1
= _fullpath (NULL
, shell
, 0);
2584 char *s2
= _fullpath (NULL
, default_shell
, 0);
2586 slow_flag
= strcmp ((s1
? s1
: ""), (s2
? s2
: ""));
2595 #else /* not WINDOWS32 */
2596 #if defined (__MSDOS__) || defined (__EMX__)
2597 else if (strcasecmp (shell
, default_shell
))
2599 extern int _is_unixy_shell (const char *_path
);
2601 DB (DB_BASIC
, (_("$SHELL changed (was '%s', now '%s')\n"),
2602 default_shell
, shell
));
2603 unixy_shell
= _is_unixy_shell (shell
);
2604 /* we must allocate a copy of shell: construct_command_argv() will free
2605 * shell after this function returns. */
2606 default_shell
= xstrdup (shell
);
2610 sh_chars
= sh_chars_sh
;
2611 sh_cmds
= sh_cmds_sh
;
2615 sh_chars
= sh_chars_dos
;
2616 sh_cmds
= sh_cmds_dos
;
2618 if (_osmode
== OS2_MODE
)
2620 sh_chars
= sh_chars_os2
;
2621 sh_cmds
= sh_cmds_os2
;
2625 #else /* !__MSDOS__ */
2626 else if (strcmp (shell
, default_shell
))
2628 #endif /* !__MSDOS__ && !__EMX__ */
2629 #endif /* not WINDOWS32 */
2632 for (ap
= ifs
; *ap
!= '\0'; ++ap
)
2633 if (*ap
!= ' ' && *ap
!= '\t' && *ap
!= '\n')
2636 if (shellflags
!= 0)
2637 if (shellflags
[0] != '-'
2638 || ((shellflags
[1] != 'c' || shellflags
[2] != '\0')
2639 && (shellflags
[1] != 'e' || shellflags
[2] != 'c' || shellflags
[3] != '\0')))
2642 i
= strlen (line
) + 1;
2644 /* More than 1 arg per character is impossible. */
2645 new_argv
= xmalloc (i
* sizeof (char *));
2647 /* All the args can fit in a buffer as big as LINE is. */
2648 ap
= new_argv
[0] = argstr
= xmalloc (i
);
2651 /* I is how many complete arguments have been found. */
2653 instring
= word_has_equals
= seen_nonequals
= last_argument_was_empty
= 0;
2654 for (p
= line
; *p
!= '\0'; ++p
)
2660 /* Inside a string, just copy any char except a closing quote
2661 or a backslash-newline combination. */
2665 if (ap
== new_argv
[0] || *(ap
-1) == '\0')
2666 last_argument_was_empty
= 1;
2668 else if (*p
== '\\' && p
[1] == '\n')
2670 /* Backslash-newline is handled differently depending on what
2671 kind of string we're in: inside single-quoted strings you
2672 keep them; in double-quoted strings they disappear. For
2673 DOS/Windows/OS2, if we don't have a POSIX shell, we keep the
2674 pre-POSIX behavior of removing the backslash-newline. */
2676 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2687 else if (*p
== '\n' && restp
!= NULL
)
2689 /* End of the command line. */
2693 /* Backslash, $, and ` are special inside double quotes.
2694 If we see any of those, punt.
2695 But on MSDOS, if we use COMMAND.COM, double and single
2696 quotes have the same effect. */
2697 else if (instring
== '"' && strchr ("\\$`", *p
) != 0 && unixy_shell
)
2700 else if (instring
== '"' && strncmp (p
, "\\\"", 2) == 0)
2706 else if (strchr (sh_chars
, *p
) != 0)
2707 /* Not inside a string, but it's a special char. */
2709 else if (one_shell
&& *p
== '\n')
2710 /* In .ONESHELL mode \n is a separator like ; or && */
2713 else if (*p
== '.' && p
[1] == '.' && p
[2] == '.' && p
[3] != '.')
2714 /* '...' is a wildcard in DJGPP. */
2718 /* Not a special char. */
2722 /* Equals is a special character in leading words before the
2723 first word with no equals sign in it. This is not the case
2724 with sh -k, but we never get here when using nonstandard
2726 if (! seen_nonequals
&& unixy_shell
)
2728 word_has_equals
= 1;
2733 /* Backslash-newline has special case handling, ref POSIX.
2734 We're in the fastpath, so emulate what the shell would do. */
2737 /* Throw out the backslash and newline. */
2740 /* If there's nothing in this argument yet, skip any
2741 whitespace before the start of the next word. */
2742 if (ap
== new_argv
[i
])
2743 p
= next_token (p
+ 1) - 1;
2745 else if (p
[1] != '\0')
2747 #ifdef HAVE_DOS_PATHS
2748 /* Only remove backslashes before characters special to Unixy
2749 shells. All other backslashes are copied verbatim, since
2750 they are probably DOS-style directory separators. This
2751 still leaves a small window for problems, but at least it
2752 should work for the vast majority of naive users. */
2755 /* A dot is only special as part of the "..."
2757 if (strneq (p
+ 1, ".\\.\\.", 5))
2765 if (p
[1] != '\\' && p
[1] != '\''
2766 && !isspace ((unsigned char)p
[1])
2767 && strchr (sh_chars_sh
, p
[1]) == 0)
2768 /* back up one notch, to copy the backslash */
2770 #endif /* HAVE_DOS_PATHS */
2772 /* Copy and skip the following char. */
2785 /* End of the command line. */
2790 /* Newlines are not special. */
2796 /* We have the end of an argument.
2797 Terminate the text of the argument. */
2800 last_argument_was_empty
= 0;
2802 /* Update SEEN_NONEQUALS, which tells us if every word
2803 heretofore has contained an '='. */
2804 seen_nonequals
|= ! word_has_equals
;
2805 if (word_has_equals
&& ! seen_nonequals
)
2806 /* An '=' in a word before the first
2807 word without one is magical. */
2809 word_has_equals
= 0; /* Prepare for the next word. */
2811 /* If this argument is the command name,
2812 see if it is a built-in shell command.
2813 If so, have the shell handle it. */
2817 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2819 if (streq (sh_cmds
[j
], new_argv
[0]))
2822 /* Non-Unix shells are case insensitive. */
2824 && strcasecmp (sh_cmds
[j
], new_argv
[0]) == 0)
2830 /* Ignore multiple whitespace chars. */
2831 p
= next_token (p
) - 1;
2842 /* Let the shell deal with an unterminated quote. */
2845 /* Terminate the last argument and the argument list. */
2848 if (new_argv
[i
][0] != '\0' || last_argument_was_empty
)
2855 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2856 if (streq (sh_cmds
[j
], new_argv
[0]))
2860 if (new_argv
[0] == 0)
2862 /* Line was empty. */
2871 /* We must use the shell. */
2875 /* Free the old argument list we were working on. */
2881 execute_by_shell
= 1; /* actually, call 'system' if shell isn't unixy */
2890 buffer
= xmalloc (strlen (line
)+1);
2893 for (dptr
=buffer
; *ptr
; )
2895 if (*ptr
== '\\' && ptr
[1] == '\n')
2897 else if (*ptr
== '@') /* Kludge: multiline commands */
2907 new_argv
= xmalloc (2 * sizeof (char *));
2908 new_argv
[0] = buffer
;
2911 #else /* Not Amiga */
2914 * Not eating this whitespace caused things like
2918 * which gave the shell fits. I think we have to eat
2919 * whitespace here, but this code should be considered
2920 * suspicious if things start failing....
2923 /* Make sure not to bother processing an empty line. */
2924 while (isspace ((unsigned char)*line
))
2928 #endif /* WINDOWS32 */
2931 /* SHELL may be a multi-word command. Construct a command line
2932 "$(SHELL) $(.SHELLFLAGS) LINE", with all special chars in LINE escaped.
2933 Then recurse, expanding this command line to get the final
2936 unsigned int shell_len
= strlen (shell
);
2937 unsigned int line_len
= strlen (line
);
2938 unsigned int sflags_len
= shellflags
? strlen (shellflags
) : 0;
2939 char *command_ptr
= NULL
; /* used for batch_mode_shell mode */
2942 # ifdef __EMX__ /* is this necessary? */
2943 if (!unixy_shell
&& shellflags
)
2944 shellflags
[0] = '/'; /* "/c" */
2947 /* In .ONESHELL mode we are allowed to throw the entire current
2948 recipe string at a single shell and trust that the user
2949 has configured the shell and shell flags, and formatted
2950 the string, appropriately. */
2953 /* If the shell is Bourne compatible, we must remove and ignore
2954 interior special chars [@+-] because they're meaningless to
2955 the shell itself. If, however, we're in .ONESHELL mode and
2956 have changed SHELL to something non-standard, we should
2957 leave those alone because they could be part of the
2958 script. In this case we must also leave in place
2959 any leading [@+-] for the same reason. */
2961 /* Remove and ignore interior prefix chars [@+-] because they're
2962 meaningless given a single shell. */
2963 #if defined __MSDOS__ || defined (__EMX__)
2964 if (unixy_shell
) /* the test is complicated and we already did it */
2966 if (is_bourne_compatible_shell(shell
))
2969 const char *f
= line
;
2972 /* Copy the recipe, removing and ignoring interior prefix chars
2973 [@+-]: they're meaningless in .ONESHELL mode. */
2974 while (f
[0] != '\0')
2978 /* This is the start of a new recipe line.
2979 Skip whitespace and prefix characters. */
2980 while (isblank (*f
) || *f
== '-' || *f
== '@' || *f
== '+')
2983 /* Copy until we get to the next logical recipe line. */
2991 /* On unescaped newline, we're done with this line. */
2992 if (f
[-1] == '\n' && ! esc
)
2995 /* Something else: reset the escape sequence. */
3003 /* Create an argv list for the shell command line. */
3007 new_argv
= xmalloc ((4 + sflags_len
/2) * sizeof (char *));
3008 new_argv
[n
++] = xstrdup (shell
);
3010 /* Chop up the shellflags (if any) and assign them. */
3012 new_argv
[n
++] = xstrdup ("");
3015 const char *s
= shellflags
;
3018 while ((t
= find_next_token (&s
, &len
)) != 0)
3019 new_argv
[n
++] = xstrndup (t
, len
);
3022 /* Set the command to invoke. */
3023 new_argv
[n
++] = line
;
3024 new_argv
[n
++] = NULL
;
3029 new_line
= xmalloc ((shell_len
*2) + 1 + sflags_len
+ 1
3030 + (line_len
*2) + 1);
3032 /* Copy SHELL, escaping any characters special to the shell. If
3033 we don't escape them, construct_command_argv_internal will
3034 recursively call itself ad nauseam, or until stack overflow,
3035 whichever happens first. */
3036 for (p
= shell
; *p
!= '\0'; ++p
)
3038 if (strchr (sh_chars
, *p
) != 0)
3044 memcpy (ap
, shellflags
, sflags_len
);
3048 for (p
= line
; *p
!= '\0'; ++p
)
3050 if (restp
!= NULL
&& *p
== '\n')
3055 else if (*p
== '\\' && p
[1] == '\n')
3057 /* POSIX says we keep the backslash-newline. If we don't have a
3058 POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
3059 and remove the backslash/newline. */
3060 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
3061 # define PRESERVE_BSNL unixy_shell
3063 # define PRESERVE_BSNL 1
3068 /* Only non-batch execution needs another backslash,
3069 because it will be passed through a recursive
3070 invocation of this function. */
3071 if (!batch_mode_shell
)
3079 /* DOS shells don't know about backslash-escaping. */
3080 if (unixy_shell
&& !batch_mode_shell
&&
3081 (*p
== '\\' || *p
== '\'' || *p
== '"'
3082 || isspace ((unsigned char)*p
)
3083 || strchr (sh_chars
, *p
) != 0))
3086 else if (unixy_shell
&& strneq (p
, "...", 3))
3088 /* The case of '...' wildcard again. */
3089 strcpy (ap
, "\\.\\.\\");
3096 if (ap
== new_line
+ shell_len
+ sflags_len
+ 2)
3098 /* Line was empty. */
3105 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3106 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3107 cases, run commands via a script file. */
3108 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
)) {
3109 /* Need to allocate new_argv, although it's unused, because
3110 start_job_command will want to free it and its 0'th element. */
3111 new_argv
= xmalloc(2 * sizeof (char *));
3112 new_argv
[0] = xstrdup ("");
3114 } else if ((no_default_sh_exe
|| batch_mode_shell
) && batch_filename
) {
3117 int id
= GetCurrentProcessId();
3120 /* create a file name */
3121 sprintf(fbuf
, "make%d", id
);
3122 *batch_filename
= create_batch_file (fbuf
, unixy_shell
, &temp_fd
);
3124 DB (DB_JOBS
, (_("Creating temporary batch file %s\n"),
3127 /* Create a FILE object for the batch file, and write to it the
3128 commands to be executed. Put the batch file in TEXT mode. */
3129 _setmode (temp_fd
, _O_TEXT
);
3130 batch
= _fdopen (temp_fd
, "wt");
3132 fputs ("@echo off\n", batch
);
3133 fputs (command_ptr
, batch
);
3134 fputc ('\n', batch
);
3136 DB (DB_JOBS
, (_("Batch file contents:%s\n\t%s\n"),
3137 !unixy_shell
? "\n\t@echo off" : "", command_ptr
));
3140 new_argv
= xmalloc(3 * sizeof (char *));
3142 new_argv
[0] = xstrdup (shell
);
3143 new_argv
[1] = *batch_filename
; /* only argv[0] gets freed later */
3145 new_argv
[0] = xstrdup (*batch_filename
);
3150 #endif /* WINDOWS32 */
3153 new_argv
= construct_command_argv_internal (new_line
, 0, 0, 0, 0,
3157 else if (!unixy_shell
)
3159 /* new_line is local, must not be freed therefore
3160 We use line here instead of new_line because we run the shell
3162 size_t line_len
= strlen (line
);
3165 memcpy (new_line
, line
, line_len
+ 1);
3166 /* Replace all backslash-newline combination and also following tabs.
3167 Important: stop at the first '\n' because that's what the loop above
3168 did. The next line starting at restp[0] will be executed during the
3169 next call of this function. */
3170 while (*q
!= '\0' && *q
!= '\n')
3172 if (q
[0] == '\\' && q
[1] == '\n')
3173 q
+= 2; /* remove '\\' and '\n' */
3179 # ifndef NO_CMD_DEFAULT
3180 if (strnicmp (new_line
, "echo", 4) == 0
3181 && (new_line
[4] == ' ' || new_line
[4] == '\t'))
3183 /* the builtin echo command: handle it separately */
3184 size_t echo_len
= line_len
- 5;
3185 char *echo_line
= new_line
+ 5;
3187 /* special case: echo 'x="y"'
3188 cmd works this way: a string is printed as is, i.e., no quotes
3189 are removed. But autoconf uses a command like echo 'x="y"' to
3190 determine whether make works. autoconf expects the output x="y"
3191 so we will do exactly that.
3192 Note: if we do not allow cmd to be the default shell
3193 we do not need this kind of voodoo */
3194 if (echo_line
[0] == '\''
3195 && echo_line
[echo_len
- 1] == '\''
3196 && strncmp (echo_line
+ 1, "ac_maketemp=",
3197 strlen ("ac_maketemp=")) == 0)
3199 /* remove the enclosing quotes */
3200 memmove (echo_line
, echo_line
+ 1, echo_len
- 2);
3201 echo_line
[echo_len
- 2] = '\0';
3207 /* Let the shell decide what to do. Put the command line into the
3208 2nd command line argument and hope for the best ;-) */
3209 size_t sh_len
= strlen (shell
);
3211 /* exactly 3 arguments + NULL */
3212 new_argv
= xmalloc (4 * sizeof (char *));
3213 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3214 the trailing '\0' */
3215 new_argv
[0] = xmalloc (sh_len
+ line_len
+ 5);
3216 memcpy (new_argv
[0], shell
, sh_len
+ 1);
3217 new_argv
[1] = new_argv
[0] + sh_len
+ 1;
3218 memcpy (new_argv
[1], "/c", 3);
3219 new_argv
[2] = new_argv
[1] + 3;
3220 memcpy (new_argv
[2], new_line
, line_len
+ 1);
3224 #elif defined(__MSDOS__)
3227 /* With MSDOS shells, we must construct the command line here
3228 instead of recursively calling ourselves, because we
3229 cannot backslash-escape the special characters (see above). */
3230 new_argv
= xmalloc (sizeof (char *));
3231 line_len
= strlen (new_line
) - shell_len
- sflags_len
- 2;
3232 new_argv
[0] = xmalloc (line_len
+ 1);
3233 strncpy (new_argv
[0],
3234 new_line
+ shell_len
+ sflags_len
+ 2, line_len
);
3235 new_argv
[0][line_len
] = '\0';
3239 fatal (NILF
, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3240 __FILE__
, __LINE__
);
3245 #endif /* ! AMIGA */
3251 /* Figure out the argument list necessary to run LINE as a command. Try to
3252 avoid using a shell. This routine handles only ' quoting, and " quoting
3253 when no backslash, $ or ' characters are seen in the quotes. Starting
3254 quotes may be escaped with a backslash. If any of the characters in
3255 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3256 is the first word of a line, the shell is used.
3258 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3259 If *RESTP is NULL, newlines will be ignored.
3261 FILE is the target whose commands these are. It is used for
3262 variable expansion for $(SHELL) and $(IFS). */
3265 construct_command_argv (char *line
, char **restp
, struct file
*file
,
3266 int cmd_flags
, char **batch_filename
)
3268 char *shell
, *ifs
, *shellflags
;
3280 && (isspace ((unsigned char)*cptr
)))
3285 && (!isspace((unsigned char)*cptr
)))
3290 argv
= xmalloc (argc
* sizeof (char *));
3299 && (isspace ((unsigned char)*cptr
)))
3303 DB (DB_JOBS
, ("argv[%d] = [%s]\n", argc
, cptr
));
3304 argv
[argc
++] = cptr
;
3306 && (!isspace((unsigned char)*cptr
)))
3313 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3314 int save
= warn_undefined_variables_flag
;
3315 warn_undefined_variables_flag
= 0;
3317 shell
= allocated_variable_expand_for_file ("$(SHELL)", file
);
3320 * Convert to forward slashes so that construct_command_argv_internal()
3324 char *p
= w32ify (shell
, 0);
3330 static const char *unixroot
= NULL
;
3331 static const char *last_shell
= "";
3332 static int init
= 0;
3335 unixroot
= getenv ("UNIXROOT");
3336 /* unixroot must be NULL or not empty */
3337 if (unixroot
&& unixroot
[0] == '\0') unixroot
= NULL
;
3341 /* if we have an unixroot drive and if shell is not default_shell
3342 (which means it's either cmd.exe or the test has already been
3343 performed) and if shell is an absolute path without drive letter,
3344 try whether it exists e.g.: if "/bin/sh" does not exist use
3345 "$UNIXROOT/bin/sh" instead. */
3346 if (unixroot
&& shell
&& strcmp (shell
, last_shell
) != 0
3347 && (shell
[0] == '/' || shell
[0] == '\\'))
3349 /* trying a new shell, check whether it exists */
3350 size_t size
= strlen (shell
);
3351 char *buf
= xmalloc (size
+ 7);
3352 memcpy (buf
, shell
, size
);
3353 memcpy (buf
+ size
, ".exe", 5); /* including the trailing '\0' */
3354 if (access (shell
, F_OK
) != 0 && access (buf
, F_OK
) != 0)
3356 /* try the same for the unixroot drive */
3357 memmove (buf
+ 2, buf
, size
+ 5);
3358 buf
[0] = unixroot
[0];
3359 buf
[1] = unixroot
[1];
3360 if (access (buf
, F_OK
) == 0)
3361 /* we have found a shell! */
3371 #endif /* __EMX__ */
3373 shellflags
= allocated_variable_expand_for_file ("$(.SHELLFLAGS)", file
);
3374 ifs
= allocated_variable_expand_for_file ("$(IFS)", file
);
3376 warn_undefined_variables_flag
= save
;
3379 argv
= construct_command_argv_internal (line
, restp
, shell
, shellflags
, ifs
,
3380 cmd_flags
, batch_filename
);
3389 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3391 dup2 (int old
, int new)
3406 #endif /* !HAVE_DUP2 && !_AMIGA */
3408 /* On VMS systems, include special VMS functions. */
3411 #include "vmsjobs.c"