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
= 1;
277 static int second_loop
= 0;
278 const unsigned sizemax
= strlen (base
) + strlen (ext
) + 10;
282 path_size
= GetCurrentDirectory (sizeof temp_path
, temp_path
);
286 while (path_size
> 0 &&
287 path_size
+ sizemax
< sizeof temp_path
&&
288 !(uniq
>= 0x10000 && second_loop
))
290 unsigned size
= sprintf (temp_path
+ path_size
,
292 temp_path
[path_size
- 1] == '\\' ? "" : "\\",
294 HANDLE h
= CreateFile (temp_path
, /* file name */
295 GENERIC_READ
| GENERIC_WRITE
, /* desired access */
296 0, /* no share mode */
297 NULL
, /* default security attributes */
298 CREATE_NEW
, /* creation disposition */
299 FILE_ATTRIBUTE_NORMAL
| /* flags and attributes */
300 FILE_ATTRIBUTE_TEMPORARY
, /* we'll delete it */
301 NULL
); /* no template file */
303 if (h
== INVALID_HANDLE_VALUE
)
305 const DWORD er
= GetLastError();
307 if (er
== ERROR_FILE_EXISTS
|| er
== ERROR_ALREADY_EXISTS
)
310 if (uniq
== 0x10000 && !second_loop
)
312 /* If we already had 64K batch files in this
313 process, make a second loop through the numbers,
314 looking for free slots, i.e. files that were
315 deleted in the meantime. */
321 /* the temporary path is not guaranteed to exist */
322 else if (path_is_dot
== 0)
324 path_size
= GetCurrentDirectory (sizeof temp_path
, temp_path
);
330 error_string
= map_windows32_error_to_string (er
);
336 const unsigned final_size
= path_size
+ size
+ 1;
337 char *const path
= xmalloc (final_size
);
338 memcpy (path
, temp_path
, final_size
);
339 *fd
= _open_osfhandle ((intptr_t)h
, 0);
344 for (p
= path
; (ch
= *p
) != 0; ++p
)
348 return path
; /* good return */
353 if (error_string
== NULL
)
354 error_string
= _("Cannot create a temporary file\n");
355 fatal (NILF
, error_string
);
360 #endif /* WINDOWS32 */
363 /* returns whether path is assumed to be a unix like shell. */
365 _is_unixy_shell (const char *path
)
367 /* list of non unix shells */
368 const char *known_os2shells
[] = {
380 /* find the rightmost '/' or '\\' */
381 const char *name
= strrchr (path
, '/');
382 const char *p
= strrchr (path
, '\\');
385 if (name
&& p
) /* take the max */
386 name
= (name
> p
) ? name
: p
;
387 else if (p
) /* name must be 0 */
389 else if (!name
) /* name and p must be 0 */
392 if (*name
== '/' || *name
== '\\') name
++;
395 while (known_os2shells
[i
] != NULL
) {
396 if (strcasecmp (name
, known_os2shells
[i
]) == 0)
397 return 0; /* not a unix shell */
401 /* in doubt assume a unix like shell */
406 /* determines whether path looks to be a Bourne-like shell. */
408 is_bourne_compatible_shell (const char *path
)
410 /* list of known unix (Bourne-like) shells */
411 const char *unix_shells
[] = {
423 /* find the rightmost '/' or '\\' */
424 const char *name
= strrchr (path
, '/');
425 char *p
= strrchr (path
, '\\');
427 if (name
&& p
) /* take the max */
428 name
= (name
> p
) ? name
: p
;
429 else if (p
) /* name must be 0 */
431 else if (!name
) /* name and p must be 0 */
434 if (*name
== '/' || *name
== '\\') name
++;
436 /* this should be able to deal with extensions on Windows-like systems */
437 for (i
= 0; unix_shells
[i
] != NULL
; i
++) {
438 len
= strlen(unix_shells
[i
]);
439 #if defined(WINDOWS32) || defined(__MSDOS__)
440 if ((strncasecmp (name
, unix_shells
[i
], len
) == 0) &&
441 (strlen(name
) >= len
&& (name
[len
] == '\0' || name
[len
] == '.')))
443 if ((strncmp (name
, unix_shells
[i
], len
) == 0) &&
444 (strlen(name
) >= len
&& name
[len
] == '\0'))
446 return 1; /* a known unix-style shell */
449 /* if not on the list, assume it's not a Bourne-like shell */
454 /* Write an error message describing the exit status given in
455 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
456 Append "(ignored)" if IGNORED is nonzero. */
459 child_error (const struct file
*file
,
460 int exit_code
, int exit_sig
, int coredump
, int ignored
)
463 const char *pre
= "*** ";
464 const char *post
= "";
465 const char *dump
= "";
466 struct floc
*flocp
= &file
->cmds
->fileinfo
;
468 if (ignored
&& silent_flag
)
471 if (exit_sig
&& coredump
)
472 dump
= _(" (core dumped)");
477 post
= _(" (ignored)");
484 char *a
= alloca (strlen (flocp
->filenm
) + 1 + 11 + 1);
485 sprintf (a
, "%s:%lu", flocp
->filenm
, flocp
->lineno
);
488 message (0, _("%s: recipe for target '%s' failed"), nm
, file
->name
);
491 if (!(exit_code
& 1))
492 error (NILF
, _("%s[%s] Error 0x%x%s"), pre
, file
->name
, exit_code
, post
);
495 error (NILF
, _("%s[%s] Error %d%s"), pre
, file
->name
, exit_code
, post
);
497 error (NILF
, _("%s[%s] %s%s%s"),
498 pre
, file
->name
, strsignal (exit_sig
), dump
, post
);
503 /* Handle a dead child. This handler may or may not ever be installed.
505 If we're using the jobserver feature, we need it. First, installing it
506 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
507 read FD to ensure we don't enter another blocking read without reaping all
508 the dead children. In this case we don't need the dead_children count.
510 If we don't have either waitpid or wait3, then make is unreliable, but we
511 use the dead_children count to reap children as best we can. */
513 static unsigned int dead_children
= 0;
516 child_handler (int sig UNUSED
)
527 /* The signal handler must called only once! */
528 signal (SIGCHLD
, SIG_DFL
);
531 /* This causes problems if the SIGCHLD interrupts a printf().
532 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
536 extern int shell_function_pid
, shell_function_completed
;
538 /* Reap all dead children, storing the returned status and the new command
539 state ('cs_finished') in the 'file' member of the 'struct child' for the
540 dead child, and removing the child from the chain. In addition, if BLOCK
541 nonzero, we block in this function until we've reaped at least one
542 complete child, waiting for it to die if necessary. If ERR is nonzero,
543 print an error message first. */
546 reap_children (int block
, int err
)
551 /* Initially, assume we have some. */
555 # define REAP_MORE reap_more
557 # define REAP_MORE dead_children
562 We have at least one child outstanding OR a shell function in progress,
564 We're blocking for a complete child OR there are more children to reap
566 we'll keep reaping children. */
568 while ((children
!= 0 || shell_function_pid
!= 0)
569 && (block
|| REAP_MORE
))
573 int exit_code
, exit_sig
, coredump
;
574 struct child
*lastc
, *c
;
576 int any_remote
, any_local
;
581 static int printed
= 0;
583 /* We might block for a while, so let the user know why.
584 Only print this message once no matter how many jobs are left. */
587 error (NILF
, _("*** Waiting for unfinished jobs...."));
591 /* We have one less dead child to reap. As noted in
592 child_handler() above, this count is completely unimportant for
593 all modern, POSIX-y systems that support wait3() or waitpid().
594 The rest of this comment below applies only to early, broken
595 pre-POSIX systems. We keep the count only because... it's there...
597 The test and decrement are not atomic; if it is compiled into:
598 register = dead_children - 1;
599 dead_children = register;
600 a SIGCHLD could come between the two instructions.
601 child_handler increments dead_children.
602 The second instruction here would lose that increment. But the
603 only effect of dead_children being wrong is that we might wait
604 longer than necessary to reap a child, and lose some parallelism;
605 and we might print the "Waiting for unfinished jobs" message above
606 when not necessary. */
608 if (dead_children
> 0)
612 any_local
= shell_function_pid
!= 0;
613 for (c
= children
; c
!= 0; c
= c
->next
)
615 any_remote
|= c
->remote
;
616 any_local
|= ! c
->remote
;
617 DB (DB_JOBS
, (_("Live child %p (%s) PID %s %s\n"),
618 c
, c
->file
->name
, pid2str (c
->pid
),
619 c
->remote
? _(" (remote)") : ""));
625 /* First, check for remote children. */
627 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 0);
632 /* We got a remote child. */
636 /* A remote status command failed miserably. Punt. */
638 pfatal_with_name ("remote_status");
642 /* No remote children. Check for local children. */
643 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
647 vmsWaitForChildren (&status
);
652 pid
= WAIT_NOHANG (&status
);
655 EINTRLOOP(pid
, wait (&status
));
663 /* The wait*() failed miserably. Punt. */
664 pfatal_with_name ("wait");
668 /* We got a child exit; chop the status word up. */
669 exit_code
= WEXITSTATUS (status
);
670 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
671 coredump
= WCOREDUMP (status
);
673 /* If we have started jobs in this second, remove one. */
679 /* No local children are dead. */
682 if (!block
|| !any_remote
)
685 /* Now try a blocking wait for a remote child. */
686 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 1);
688 goto remote_status_lose
;
690 /* No remote children either. Finally give up. */
693 /* We got a remote child. */
696 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
699 /* Life is very different on MSDOS. */
702 exit_code
= WEXITSTATUS (status
);
703 if (exit_code
== 0xff)
705 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
707 #endif /* __MSDOS__ */
711 status
= amiga_status
;
712 exit_code
= amiga_status
;
721 DWORD dwWaitStatus
= 0;
726 /* Record the thread ID of the main process, so that we
727 could suspend it in the signal handler. */
730 hcTID
= GetCurrentThread ();
731 hcPID
= GetCurrentProcess ();
732 if (!DuplicateHandle (hcPID
, hcTID
, hcPID
, &main_thread
, 0,
733 FALSE
, DUPLICATE_SAME_ACCESS
))
735 DWORD e
= GetLastError ();
737 "Determine main thread ID (Error %ld: %s)\n",
738 e
, map_windows32_error_to_string(e
));
741 DB (DB_VERBOSE
, ("Main thread handle = %p\n", main_thread
));
744 /* wait for anything to finish */
745 hPID
= process_wait_for_any(block
, &dwWaitStatus
);
749 /* was an error found on this process? */
750 werr
= process_last_err(hPID
);
753 exit_code
= process_exit_code(hPID
);
756 fprintf(stderr
, "make (e=%d): %s",
757 exit_code
, map_windows32_error_to_string(exit_code
));
760 exit_sig
= process_signal(hPID
);
762 /* cleanup process */
763 process_cleanup(hPID
);
767 else if (dwWaitStatus
== WAIT_FAILED
)
769 /* The WaitForMultipleObjects() failed miserably. Punt. */
770 pfatal_with_name ("WaitForMultipleObjects");
772 else if (dwWaitStatus
== WAIT_TIMEOUT
)
774 /* No child processes are finished. Give up waiting. */
781 #endif /* WINDOWS32 */
784 /* Check if this is the child of the 'shell' function. */
785 if (!remote
&& pid
== shell_function_pid
)
787 /* It is. Leave an indicator for the 'shell' function. */
788 if (exit_sig
== 0 && exit_code
== 127)
789 shell_function_completed
= -1;
791 shell_function_completed
= 1;
795 child_failed
= exit_sig
!= 0 || exit_code
!= 0;
797 /* Search for a child matching the deceased one. */
799 for (c
= children
; c
!= 0; lastc
= c
, c
= c
->next
)
800 if (c
->remote
== remote
&& c
->pid
== pid
)
804 /* An unknown child died.
805 Ignore it; it was inherited from our invoker. */
808 DB (DB_JOBS
, (child_failed
809 ? _("Reaping losing child %p PID %s %s\n")
810 : _("Reaping winning child %p PID %s %s\n"),
811 c
, pid2str (c
->pid
), c
->remote
? _(" (remote)") : ""));
813 if (c
->sh_batch_file
) {
816 DB (DB_JOBS
, (_("Cleaning up temp batch file %s\n"),
820 rm_status
= remove (c
->sh_batch_file
);
822 DB (DB_JOBS
, (_("Cleaning up temp batch file %s failed (%d)\n"),
823 c
->sh_batch_file
, errno
));
825 /* all done with memory */
826 free (c
->sh_batch_file
);
827 c
->sh_batch_file
= NULL
;
830 /* If this child had the good stdin, say it is now free. */
834 dontcare
= c
->dontcare
;
836 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
838 /* The commands failed. Write an error message,
839 delete non-precious targets, and abort. */
840 static int delete_on_error
= -1;
843 child_error (c
->file
, exit_code
, exit_sig
, coredump
, 0);
845 c
->file
->update_status
= 2;
846 if (delete_on_error
== -1)
848 struct file
*f
= lookup_file (".DELETE_ON_ERROR");
849 delete_on_error
= f
!= 0 && f
->is_target
;
851 if (exit_sig
!= 0 || delete_on_error
)
852 delete_child_targets (c
);
858 /* The commands failed, but we don't care. */
859 child_error (c
->file
, exit_code
, exit_sig
, coredump
, 1);
863 /* If there are more commands to run, try to start them. */
864 if (job_next_command (c
))
866 if (handling_fatal_signal
)
868 /* Never start new commands while we are dying.
869 Since there are more commands that wanted to be run,
870 the target was not completely remade. So we treat
871 this as if a command had failed. */
872 c
->file
->update_status
= 2;
876 /* Check again whether to start remotely.
877 Whether or not we want to changes over time.
878 Also, start_remote_job may need state set up
879 by start_remote_job_p. */
880 c
->remote
= start_remote_job_p (0);
881 start_job_command (c
);
882 /* Fatal signals are left blocked in case we were
883 about to put that child on the chain. But it is
884 already there, so it is safe for a fatal signal to
885 arrive now; it will clean up this child's targets. */
887 if (c
->file
->command_state
== cs_running
)
888 /* We successfully started the new command.
889 Loop to reap more children. */
893 if (c
->file
->update_status
!= 0)
894 /* We failed to start the commands. */
895 delete_child_targets (c
);
898 /* There are no more commands. We got through them all
899 without an unignored error. Now the target has been
900 successfully updated. */
901 c
->file
->update_status
= 0;
904 /* When we get here, all the commands for C->file are finished
905 (or aborted) and C->file->update_status contains 0 or 2. But
906 C->file->command_state is still cs_running if all the commands
907 ran; notice_finish_file looks for cs_running to tell it that
908 it's interesting to check the file's modtime again now. */
910 if (! handling_fatal_signal
)
911 /* Notice if the target of the commands has been changed.
912 This also propagates its values for command_state and
913 update_status to its also_make files. */
914 notice_finished_file (c
->file
);
916 DB (DB_JOBS
, (_("Removing child %p PID %s%s from chain.\n"),
917 c
, pid2str (c
->pid
), c
->remote
? _(" (remote)") : ""));
919 /* Block fatal signals while frobnicating the list, so that
920 children and job_slots_used are always consistent. Otherwise
921 a fatal signal arriving after the child is off the chain and
922 before job_slots_used is decremented would believe a child was
923 live and call reap_children again. */
926 /* There is now another slot open. */
927 if (job_slots_used
> 0)
930 /* Remove the child from the chain and free it. */
934 lastc
->next
= c
->next
;
940 /* If the job failed, and the -k flag was not given, die,
941 unless we are already in the process of dying. */
942 if (!err
&& child_failed
&& !dontcare
&& !keep_going_flag
&&
943 /* fatal_error_signal will die with the right signal. */
944 !handling_fatal_signal
)
947 /* Only block for one child. */
954 /* Free the storage allocated for CHILD. */
957 free_child (struct child
*child
)
959 if (!jobserver_tokens
)
960 fatal (NILF
, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
961 child
, child
->file
->name
);
963 /* If we're using the jobserver and this child is not the only outstanding
964 job, put a token back into the pipe for it. */
967 if (has_jobserver_semaphore() && jobserver_tokens
> 1)
969 if (! release_jobserver_semaphore())
971 DWORD err
= GetLastError();
972 fatal (NILF
, _("release jobserver semaphore: (Error %ld: %s)"),
973 err
, map_windows32_error_to_string(err
));
976 DB (DB_JOBS
, (_("Released token for child %p (%s).\n"), child
, child
->file
->name
));
979 if (job_fds
[1] >= 0 && jobserver_tokens
> 1)
984 /* Write a job token back to the pipe. */
986 EINTRLOOP (r
, write (job_fds
[1], &token
, 1));
988 pfatal_with_name (_("write jobserver"));
990 DB (DB_JOBS
, (_("Released token for child %p (%s).\n"),
991 child
, child
->file
->name
));
997 if (handling_fatal_signal
) /* Don't bother free'ing if about to die. */
1000 if (child
->command_lines
!= 0)
1002 register unsigned int i
;
1003 for (i
= 0; i
< child
->file
->cmds
->ncommand_lines
; ++i
)
1004 free (child
->command_lines
[i
]);
1005 free (child
->command_lines
);
1008 if (child
->environment
!= 0)
1010 register char **ep
= child
->environment
;
1013 free (child
->environment
);
1020 extern sigset_t fatal_signal_set
;
1027 (void) sigprocmask (SIG_BLOCK
, &fatal_signal_set
, (sigset_t
*) 0);
1029 # ifdef HAVE_SIGSETMASK
1030 (void) sigblock (fatal_signal_mask
);
1040 sigemptyset (&empty
);
1041 sigprocmask (SIG_SETMASK
, &empty
, (sigset_t
*) 0);
1045 #if defined(MAKE_JOBSERVER) && !defined(WINDOWS32)
1047 job_noop (int sig UNUSED
)
1050 /* Set the child handler action flags to FLAGS. */
1052 set_child_handler_action_flags (int set_handler
, int set_alarm
)
1054 struct sigaction sa
;
1057 /* The child handler must be turned off here. */
1058 signal (SIGCHLD
, SIG_DFL
);
1061 memset (&sa
, '\0', sizeof sa
);
1062 sa
.sa_handler
= child_handler
;
1063 sa
.sa_flags
= set_handler
? 0 : SA_RESTART
;
1065 sigaction (SIGCHLD
, &sa
, NULL
);
1067 #if defined SIGCLD && SIGCLD != SIGCHLD
1068 sigaction (SIGCLD
, &sa
, NULL
);
1073 /* If we're about to enter the read(), set an alarm to wake up in a
1074 second so we can check if the load has dropped and we can start more
1075 work. On the way out, turn off the alarm and set SIG_DFL. */
1076 alarm (set_handler
? 1 : 0);
1077 sa
.sa_handler
= set_handler
? job_noop
: SIG_DFL
;
1079 sigaction (SIGALRM
, &sa
, NULL
);
1086 /* Start a job to run the commands specified in CHILD.
1087 CHILD is updated to reflect the commands and ID of the child process.
1089 NOTE: On return fatal signals are blocked! The caller is responsible
1090 for calling 'unblock_sigs', once the new child is safely on the chain so
1091 it can be cleaned up in the event of a fatal signal. */
1094 start_job_command (struct child
*child
)
1096 #if !defined(_AMIGA) && !defined(WINDOWS32)
1097 static int bad_stdin
= -1;
1100 /* Must be volatile to silence bogus GCC warning about longjmp/vfork. */
1108 /* If we have a completely empty commandset, stop now. */
1109 if (!child
->command_ptr
)
1112 /* Combine the flags parsed for the line itself with
1113 the flags specified globally for this target. */
1114 flags
= (child
->file
->command_flags
1115 | child
->file
->cmds
->lines_flags
[child
->command_line
- 1]);
1117 p
= child
->command_ptr
;
1118 child
->noerror
= ((flags
& COMMANDS_NOERROR
) != 0);
1123 flags
|= COMMANDS_SILENT
;
1125 flags
|= COMMANDS_RECURSE
;
1128 else if (!isblank ((unsigned char)*p
))
1133 /* Update the file's command flags with any new ones we found. We only
1134 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
1135 now marking more commands recursive than should be in the case of
1136 multiline define/endef scripts where only one line is marked "+". In
1137 order to really fix this, we'll have to keep a lines_flags for every
1138 actual line, after expansion. */
1139 child
->file
->cmds
->lines_flags
[child
->command_line
- 1]
1140 |= flags
& COMMANDS_RECURSE
;
1142 /* POSIX requires that a recipe prefix after a backslash-newline should
1143 be ignored. Remove it now so the output is correct. */
1145 char prefix
= child
->file
->cmds
->recipe_prefix
;
1151 if (p1
[0] == '\n' && p1
[1] == prefix
)
1158 /* Figure out an argument list from this command line. */
1164 argv
= construct_command_argv (p
, &end
, child
->file
,
1165 child
->file
->cmds
->lines_flags
[child
->command_line
- 1],
1166 &child
->sh_batch_file
);
1169 child
->command_ptr
= NULL
;
1173 child
->command_ptr
= end
;
1177 /* If -q was given, say that updating 'failed' if there was any text on the
1178 command line, or 'succeeded' otherwise. The exit status of 1 tells the
1179 user that -q is saying 'something to do'; the exit status for a random
1181 if (argv
!= 0 && question_flag
&& !(flags
& COMMANDS_RECURSE
))
1187 child
->file
->update_status
= 1;
1188 notice_finished_file (child
->file
);
1192 if (touch_flag
&& !(flags
& COMMANDS_RECURSE
))
1194 /* Go on to the next command. It might be the recursive one.
1195 We construct ARGV only to find the end of the command line. */
1210 execute_by_shell
= 0; /* in case construct_command_argv sets it */
1212 /* This line has no commands. Go to the next. */
1213 if (job_next_command (child
))
1214 start_job_command (child
);
1217 /* No more commands. Make sure we're "running"; we might not be if
1218 (e.g.) all commands were skipped due to -n. */
1219 set_command_state (child
->file
, cs_running
);
1220 child
->file
->update_status
= 0;
1221 notice_finished_file (child
->file
);
1226 /* Print out the command. If silent, we call 'message' with null so it
1227 can log the working directory before the command's own error messages
1230 message (0, (just_print_flag
|| trace_flag
1231 || (!(flags
& COMMANDS_SILENT
) && !silent_flag
))
1232 ? "%s" : (char *) 0, p
);
1234 /* Tell update_goal_chain that a command has been started on behalf of
1235 this target. It is important that this happens here and not in
1236 reap_children (where we used to do it), because reap_children might be
1237 reaping children from a different target. We want this increment to
1238 guaranteedly indicate that a command was started for the dependency
1239 chain (i.e., update_file recursion chain) we are processing. */
1243 /* Optimize an empty command. People use this for timestamp rules,
1244 so avoid forking a useless shell. Do this after we increment
1245 commands_started so make still treats this special case as if it
1246 performed some action (makes a difference as to what messages are
1249 #if !defined(VMS) && !defined(_AMIGA)
1251 #if defined __MSDOS__ || defined (__EMX__)
1252 unixy_shell
/* the test is complicated and we already did it */
1254 (argv
[0] && is_bourne_compatible_shell(argv
[0]))
1256 && (argv
[1] && argv
[1][0] == '-'
1258 ((argv
[1][1] == 'c' && argv
[1][2] == '\0')
1260 (argv
[1][1] == 'e' && argv
[1][2] == 'c' && argv
[1][3] == '\0')))
1261 && (argv
[2] && argv
[2][0] == ':' && argv
[2][1] == '\0')
1268 #endif /* !VMS && !_AMIGA */
1270 /* If -n was given, recurse to get the next line in the sequence. */
1272 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
))
1281 /* Flush the output streams so they won't have things written twice. */
1287 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1289 /* Set up a bad standard input that reads from a broken pipe. */
1291 if (bad_stdin
== -1)
1293 /* Make a file descriptor that is the read end of a broken pipe.
1294 This will be used for some children's standard inputs. */
1298 /* Close the write side. */
1299 (void) close (pd
[1]);
1300 /* Save the read side. */
1303 /* Set the descriptor to close on exec, so it does not litter any
1304 child's descriptor table. When it is dup2'd onto descriptor 0,
1305 that descriptor will not close on exec. */
1306 CLOSE_ON_EXEC (bad_stdin
);
1310 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1312 /* Decide whether to give this child the 'good' standard input
1313 (one that points to the terminal or whatever), or the 'bad' one
1314 that points to the read side of a broken pipe. */
1316 child
->good_stdin
= !good_stdin_used
;
1317 if (child
->good_stdin
)
1318 good_stdin_used
= 1;
1325 /* Set up the environment for the child. */
1326 if (child
->environment
== 0)
1327 child
->environment
= target_environment (child
->file
);
1330 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1333 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1336 int is_remote
, id
, used_stdin
;
1337 if (start_remote_job (argv
, child
->environment
,
1338 child
->good_stdin
? 0 : bad_stdin
,
1339 &is_remote
, &id
, &used_stdin
))
1340 /* Don't give up; remote execution may fail for various reasons. If
1341 so, simply run the job locally. */
1345 if (child
->good_stdin
&& !used_stdin
)
1347 child
->good_stdin
= 0;
1348 good_stdin_used
= 0;
1350 child
->remote
= is_remote
;
1357 /* Fork the child process. */
1359 char **parent_environ
;
1367 if (!child_execute_job (argv
, child
)) {
1369 perror_with_name ("vfork", "");
1375 parent_environ
= environ
;
1378 /* If we aren't running a recursive command and we have a jobserver
1379 pipe, close it before exec'ing. */
1380 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1382 CLOSE_ON_EXEC (job_fds
[0]);
1383 CLOSE_ON_EXEC (job_fds
[1]);
1386 CLOSE_ON_EXEC (job_rfd
);
1388 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1389 child
->pid
= child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1390 argv
, child
->environment
);
1395 perror_with_name ("spawn", "");
1399 /* undo CLOSE_ON_EXEC() after the child process has been started */
1400 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1402 fcntl (job_fds
[0], F_SETFD
, 0);
1403 fcntl (job_fds
[1], F_SETFD
, 0);
1406 fcntl (job_rfd
, F_SETFD
, 0);
1408 #else /* !__EMX__ */
1410 child
->pid
= vfork ();
1411 environ
= parent_environ
; /* Restore value child may have clobbered. */
1412 if (child
->pid
== 0)
1414 /* We are the child side. */
1417 /* If we aren't running a recursive command and we have a jobserver
1418 pipe, close it before exec'ing. */
1419 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1427 #ifdef SET_STACK_SIZE
1428 /* Reset limits, if necessary. */
1429 if (stack_limit
.rlim_cur
)
1430 setrlimit (RLIMIT_STACK
, &stack_limit
);
1433 child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1434 argv
, child
->environment
);
1436 else if (child
->pid
< 0)
1440 perror_with_name ("vfork", "");
1443 # endif /* !__EMX__ */
1447 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1455 /* We call 'system' to do the job of the SHELL, since stock DOS
1456 shell is too dumb. Our 'system' knows how to handle long
1457 command lines even if pipes/redirection is needed; it will only
1458 call COMMAND.COM when its internal commands are used. */
1459 if (execute_by_shell
)
1461 char *cmdline
= argv
[0];
1462 /* We don't have a way to pass environment to 'system',
1463 so we need to save and restore ours, sigh... */
1464 char **parent_environ
= environ
;
1466 environ
= child
->environment
;
1468 /* If we have a *real* shell, tell 'system' to call
1469 it to do everything for us. */
1472 /* A *real* shell on MSDOS may not support long
1473 command lines the DJGPP way, so we must use 'system'. */
1474 cmdline
= argv
[2]; /* get past "shell -c" */
1477 dos_command_running
= 1;
1478 proc_return
= system (cmdline
);
1479 environ
= parent_environ
;
1480 execute_by_shell
= 0; /* for the next time */
1484 dos_command_running
= 1;
1485 proc_return
= spawnvpe (P_WAIT
, argv
[0], argv
, child
->environment
);
1488 /* Need to unblock signals before turning off
1489 dos_command_running, so that child's signals
1490 will be treated as such (see fatal_error_signal). */
1492 dos_command_running
= 0;
1494 /* If the child got a signal, dos_status has its
1495 high 8 bits set, so be careful not to alter them. */
1496 if (proc_return
== -1)
1499 dos_status
|= (proc_return
& 0xff);
1501 child
->pid
= dos_pid
++;
1503 #endif /* __MSDOS__ */
1505 amiga_status
= MyExecute (argv
);
1508 child
->pid
= amiga_pid
++;
1509 if (amiga_batch_file
)
1511 amiga_batch_file
= 0;
1512 DeleteFile (amiga_bname
); /* Ignore errors. */
1520 /* make UNC paths safe for CreateProcess -- backslash format */
1522 if (arg0
&& arg0
[0] == '/' && arg0
[1] == '/')
1523 for ( ; arg0
&& *arg0
; arg0
++)
1527 /* make sure CreateProcess() has Path it needs */
1528 sync_Path_environment();
1530 hPID
= process_easy(argv
, child
->environment
);
1532 if (hPID
!= INVALID_HANDLE_VALUE
)
1533 child
->pid
= (pid_t
) hPID
;
1538 _("process_easy() failed to launch process (e=%ld)\n"),
1539 process_last_err(hPID
));
1540 for (i
= 0; argv
[i
]; i
++)
1541 fprintf(stderr
, "%s ", argv
[i
]);
1542 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
1546 #endif /* WINDOWS32 */
1547 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1549 /* Bump the number of jobs started in this second. */
1552 /* We are the parent side. Set the state to
1553 say the commands are running and return. */
1555 set_command_state (child
->file
, cs_running
);
1557 /* Free the storage used by the child's argument list. */
1566 child
->file
->update_status
= 2;
1567 notice_finished_file (child
->file
);
1571 /* Try to start a child running.
1572 Returns nonzero if the child was started (and maybe finished), or zero if
1573 the load was too high and the child was put on the 'waiting_jobs' chain. */
1576 start_waiting_job (struct child
*c
)
1578 struct file
*f
= c
->file
;
1580 /* If we can start a job remotely, we always want to, and don't care about
1581 the local load average. We record that the job should be started
1582 remotely in C->remote for start_job_command to test. */
1584 c
->remote
= start_remote_job_p (1);
1586 /* If we are running at least one job already and the load average
1587 is too high, make this one wait. */
1589 && ((job_slots_used
> 0 && load_too_high ())
1591 || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS
)
1595 /* Put this child on the chain of children waiting for the load average
1597 set_command_state (f
, cs_running
);
1598 c
->next
= waiting_jobs
;
1603 /* Start the first command; reap_children will run later command lines. */
1604 start_job_command (c
);
1606 switch (f
->command_state
)
1610 DB (DB_JOBS
, (_("Putting child %p (%s) PID %s%s on the chain.\n"),
1611 c
, c
->file
->name
, pid2str (c
->pid
),
1612 c
->remote
? _(" (remote)") : ""));
1614 /* One more job slot is in use. */
1619 case cs_not_started
:
1620 /* All the command lines turned out to be empty. */
1621 f
->update_status
= 0;
1625 notice_finished_file (f
);
1630 assert (f
->command_state
== cs_finished
);
1637 /* Create a 'struct child' for FILE and start its commands running. */
1640 new_job (struct file
*file
)
1642 struct commands
*cmds
= file
->cmds
;
1647 /* Let any previously decided-upon jobs that are waiting
1648 for the load to go down start before this new one. */
1649 start_waiting_jobs ();
1651 /* Reap any children that might have finished recently. */
1652 reap_children (0, 0);
1654 /* Chop the commands up into lines if they aren't already. */
1655 chop_commands (cmds
);
1657 /* Expand the command lines and store the results in LINES. */
1658 lines
= xmalloc (cmds
->ncommand_lines
* sizeof (char *));
1659 for (i
= 0; i
< cmds
->ncommand_lines
; ++i
)
1661 /* Collapse backslash-newline combinations that are inside variable
1662 or function references. These are left alone by the parser so
1663 that they will appear in the echoing of commands (where they look
1664 nice); and collapsed by construct_command_argv when it tokenizes.
1665 But letting them survive inside function invocations loses because
1666 we don't want the functions to see them as part of the text. */
1668 char *in
, *out
, *ref
;
1670 /* IN points to where in the line we are scanning.
1671 OUT points to where in the line we are writing.
1672 When we collapse a backslash-newline combination,
1673 IN gets ahead of OUT. */
1675 in
= out
= cmds
->command_lines
[i
];
1676 while ((ref
= strchr (in
, '$')) != 0)
1678 ++ref
; /* Move past the $. */
1681 /* Copy the text between the end of the last chunk
1682 we processed (where IN points) and the new chunk
1683 we are about to process (where REF points). */
1684 memmove (out
, in
, ref
- in
);
1686 /* Move both pointers past the boring stuff. */
1690 if (*ref
== '(' || *ref
== '{')
1692 char openparen
= *ref
;
1693 char closeparen
= openparen
== '(' ? ')' : '}';
1697 *out
++ = *in
++; /* Copy OPENPAREN. */
1698 /* IN now points past the opening paren or brace.
1699 Count parens or braces until it is matched. */
1703 if (*in
== closeparen
&& --count
< 0)
1705 else if (*in
== '\\' && in
[1] == '\n')
1707 /* We have found a backslash-newline inside a
1708 variable or function reference. Eat it and
1709 any following whitespace. */
1712 for (p
= in
- 1; p
> ref
&& *p
== '\\'; --p
)
1716 /* There were two or more backslashes, so this is
1717 not really a continuation line. We don't collapse
1718 the quoting backslashes here as is done in
1719 collapse_continuations, because the line will
1720 be collapsed again after expansion. */
1724 /* Skip the backslash, newline and
1725 any following whitespace. */
1726 in
= next_token (in
+ 2);
1728 /* Discard any preceding whitespace that has
1729 already been written to the output. */
1731 && isblank ((unsigned char)out
[-1]))
1734 /* Replace it all with a single space. */
1740 if (*in
== openparen
)
1749 /* There are no more references in this line to worry about.
1750 Copy the remaining uninteresting text to the output. */
1752 memmove (out
, in
, strlen (in
) + 1);
1754 /* Finally, expand the line. */
1755 lines
[i
] = allocated_variable_expand_for_file (cmds
->command_lines
[i
],
1759 /* Start the command sequence, record it in a new
1760 'struct child', and add that to the chain. */
1762 c
= xcalloc (sizeof (struct child
));
1764 c
->command_lines
= lines
;
1765 c
->sh_batch_file
= NULL
;
1767 /* Cache dontcare flag because file->dontcare can be changed once we
1768 return. Check dontcare inheritance mechanism for details. */
1769 c
->dontcare
= file
->dontcare
;
1771 /* Fetch the first command line to be run. */
1772 job_next_command (c
);
1774 /* Wait for a job slot to be freed up. If we allow an infinite number
1775 don't bother; also job_slots will == 0 if we're using the jobserver. */
1778 while (job_slots_used
== job_slots
)
1779 reap_children (1, 0);
1781 #ifdef MAKE_JOBSERVER
1782 /* If we are controlling multiple jobs make sure we have a token before
1783 starting the child. */
1785 /* This can be inefficient. There's a decent chance that this job won't
1786 actually have to run any subprocesses: the command script may be empty
1787 or otherwise optimized away. It would be nice if we could defer
1788 obtaining a token until just before we need it, in start_job_command.
1789 To do that we'd need to keep track of whether we'd already obtained a
1790 token (since start_job_command is called for each line of the job, not
1791 just once). Also more thought needs to go into the entire algorithm;
1792 this is where the old parallel job code waits, so... */
1795 else if (has_jobserver_semaphore())
1797 else if (job_fds
[0] >= 0)
1807 DB (DB_JOBS
, ("Need a job token; we %shave children\n",
1808 children
? "" : "don't "));
1810 /* If we don't already have a job started, use our "free" token. */
1811 if (!jobserver_tokens
)
1815 /* Read a token. As long as there's no token available we'll block.
1816 We enable interruptible system calls before the read(2) so that if
1817 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1818 we can process the death(s) and return tokens to the free pool.
1820 Once we return from the read, we immediately reinstate restartable
1821 system calls. This allows us to not worry about checking for
1822 EINTR on all the other system calls in the program.
1824 There is one other twist: there is a span between the time
1825 reap_children() does its last check for dead children and the time
1826 the read(2) call is entered, below, where if a child dies we won't
1827 notice. This is extremely serious as it could cause us to
1828 deadlock, given the right set of events.
1830 To avoid this, we do the following: before we reap_children(), we
1831 dup(2) the read FD on the jobserver pipe. The read(2) call below
1832 uses that new FD. In the signal handler, we close that FD. That
1833 way, if a child dies during the section mentioned above, the
1834 read(2) will be invoked with an invalid FD and will return
1835 immediately with EBADF. */
1837 /* Make sure we have a dup'd FD. */
1840 DB (DB_JOBS
, ("Duplicate the job FD\n"));
1841 job_rfd
= dup (job_fds
[0]);
1845 /* Reap anything that's currently waiting. */
1846 reap_children (0, 0);
1848 /* Kick off any jobs we have waiting for an opportunity that
1849 can run now (ie waiting for load). */
1850 start_waiting_jobs ();
1852 /* If our "free" slot has become available, use it; we don't need an
1854 if (!jobserver_tokens
)
1857 /* There must be at least one child already, or we have no business
1858 waiting for a token. */
1860 fatal (NILF
, "INTERNAL: no children as we go to sleep on read\n");
1863 /* On Windows we simply wait for the jobserver semaphore to become
1864 * signalled or one of our child processes to terminate.
1866 got_token
= wait_for_semaphore_or_child_process();
1869 DWORD err
= GetLastError();
1870 fatal (NILF
, _("semaphore or child process wait: (Error %ld: %s)"),
1871 err
, map_windows32_error_to_string(err
));
1874 /* Set interruptible system calls, and read() for a job token. */
1875 set_child_handler_action_flags (1, waiting_jobs
!= NULL
);
1876 got_token
= read (job_rfd
, &token
, 1);
1877 saved_errno
= errno
;
1878 set_child_handler_action_flags (0, waiting_jobs
!= NULL
);
1881 /* If we got one, we're done here. */
1884 DB (DB_JOBS
, (_("Obtained token for child %p (%s).\n"),
1890 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1891 go back and reap_children(), and try again. */
1892 errno
= saved_errno
;
1893 if (errno
!= EINTR
&& errno
!= EBADF
)
1894 pfatal_with_name (_("read jobs pipe"));
1896 DB (DB_JOBS
, ("Read returned EBADF.\n"));
1904 Use message here so that changes to working directories are logged. */
1907 char *newer
= allocated_variable_expand_for_file ("$?", c
->file
);
1910 if (! cmds
->fileinfo
.filenm
)
1911 nm
= _("<builtin>");
1914 nm
= alloca (strlen (cmds
->fileinfo
.filenm
) + 1 + 11 + 1);
1915 sprintf (nm
, "%s:%lu", cmds
->fileinfo
.filenm
, cmds
->fileinfo
.lineno
);
1918 if (newer
[0] == '\0')
1919 message (0, _("%s: target '%s' does not exist"), nm
, c
->file
->name
);
1921 message (0, _("%s: update target '%s' due to: %s"), nm
,
1922 c
->file
->name
, newer
);
1928 /* The job is now primed. Start it running.
1929 (This will notice if there is in fact no recipe.) */
1930 start_waiting_job (c
);
1932 if (job_slots
== 1 || not_parallel
)
1933 /* Since there is only one job slot, make things run linearly.
1934 Wait for the child to die, setting the state to 'cs_finished'. */
1935 while (file
->command_state
== cs_running
)
1936 reap_children (1, 0);
1941 /* Move CHILD's pointers to the next command for it to execute.
1942 Returns nonzero if there is another command. */
1945 job_next_command (struct child
*child
)
1947 while (child
->command_ptr
== 0 || *child
->command_ptr
== '\0')
1949 /* There are no more lines in the expansion of this line. */
1950 if (child
->command_line
== child
->file
->cmds
->ncommand_lines
)
1952 /* There are no more lines to be expanded. */
1953 child
->command_ptr
= 0;
1957 /* Get the next line to run. */
1958 child
->command_ptr
= child
->command_lines
[child
->command_line
++];
1963 /* Determine if the load average on the system is too high to start a new job.
1964 The real system load average is only recomputed once a second. However, a
1965 very parallel make can easily start tens or even hundreds of jobs in a
1966 second, which brings the system to its knees for a while until that first
1967 batch of jobs clears out.
1969 To avoid this we use a weighted algorithm to try to account for jobs which
1970 have been started since the last second, and guess what the load average
1971 would be now if it were computed.
1973 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1976 ! calculate something load-oid and add to the observed sys.load,
1977 ! so that latter can catch up:
1978 ! - every job started increases jobctr;
1979 ! - every dying job decreases a positive jobctr;
1980 ! - the jobctr value gets zeroed every change of seconds,
1981 ! after its value*weight_b is stored into the 'backlog' value last_sec
1982 ! - weight_a times the sum of jobctr and last_sec gets
1983 ! added to the observed sys.load.
1985 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1986 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1987 ! sub-shelled commands (rm, echo, sed...) for tests.
1988 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1989 ! resulted in significant excession of the load limit, raising it
1990 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1991 ! reach the limit in most test cases.
1993 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1994 ! exceeding the limit for longer-running stuff (compile jobs in
1995 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1996 ! small jobs' effects.
2000 #define LOAD_WEIGHT_A 0.25
2001 #define LOAD_WEIGHT_B 0.25
2004 load_too_high (void)
2006 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
2009 static double last_sec
;
2010 static time_t last_now
;
2015 /* sub_proc.c cannot wait for more than MAXIMUM_WAIT_OBJECTS children */
2016 if (process_used_slots () >= MAXIMUM_WAIT_OBJECTS
)
2020 if (max_load_average
< 0)
2023 /* Find the real system load average. */
2025 if (getloadavg (&load
, 1) != 1)
2027 static int lossage
= -1;
2028 /* Complain only once for the same error. */
2029 if (lossage
== -1 || errno
!= lossage
)
2032 /* An errno value of zero means getloadavg is just unsupported. */
2034 _("cannot enforce load limits on this operating system"));
2036 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
2043 /* If we're in a new second zero the counter and correct the backlog
2044 value. Only keep the backlog for one extra second; after that it's 0. */
2048 if (last_now
== now
- 1)
2049 last_sec
= LOAD_WEIGHT_B
* job_counter
;
2057 /* Try to guess what the load would be right now. */
2058 guess
= load
+ (LOAD_WEIGHT_A
* (job_counter
+ last_sec
));
2060 DB (DB_JOBS
, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
2061 guess
, load
, max_load_average
));
2063 return guess
>= max_load_average
;
2067 /* Start jobs that are waiting for the load to be lower. */
2070 start_waiting_jobs (void)
2074 if (waiting_jobs
== 0)
2079 /* Check for recently deceased descendants. */
2080 reap_children (0, 0);
2082 /* Take a job off the waiting list. */
2084 waiting_jobs
= job
->next
;
2086 /* Try to start that job. We break out of the loop as soon
2087 as start_waiting_job puts one back on the waiting list. */
2089 while (start_waiting_job (job
) && waiting_jobs
!= 0);
2096 /* EMX: Start a child process. This function returns the new pid. */
2097 # if defined __EMX__
2099 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2102 /* stdin_fd == 0 means: nothing to do for stdin;
2103 stdout_fd == 1 means: nothing to do for stdout */
2104 int save_stdin
= (stdin_fd
!= 0) ? dup (0) : 0;
2105 int save_stdout
= (stdout_fd
!= 1) ? dup (1): 1;
2107 /* < 0 only if dup() failed */
2109 fatal (NILF
, _("no more file handles: could not duplicate stdin\n"));
2110 if (save_stdout
< 0)
2111 fatal (NILF
, _("no more file handles: could not duplicate stdout\n"));
2113 /* Close unnecessary file handles for the child. */
2114 if (save_stdin
!= 0)
2115 CLOSE_ON_EXEC (save_stdin
);
2116 if (save_stdout
!= 1)
2117 CLOSE_ON_EXEC (save_stdout
);
2119 /* Connect the pipes to the child process. */
2121 (void) dup2 (stdin_fd
, 0);
2123 (void) dup2 (stdout_fd
, 1);
2125 /* stdin_fd and stdout_fd must be closed on exit because we are
2126 still in the parent process */
2128 CLOSE_ON_EXEC (stdin_fd
);
2130 CLOSE_ON_EXEC (stdout_fd
);
2132 /* Run the command. */
2133 pid
= exec_command (argv
, envp
);
2135 /* Restore stdout/stdin of the parent and close temporary FDs. */
2138 if (dup2 (save_stdin
, 0) != 0)
2139 fatal (NILF
, _("Could not restore stdin\n"));
2146 if (dup2 (save_stdout
, 1) != 1)
2147 fatal (NILF
, _("Could not restore stdout\n"));
2149 close (save_stdout
);
2155 #elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
2158 Replace the current process with one executing the command in ARGV.
2159 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2160 the environment of the new program. This function does not return. */
2162 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2165 (void) dup2 (stdin_fd
, 0);
2167 (void) dup2 (stdout_fd
, 1);
2169 (void) close (stdin_fd
);
2171 (void) close (stdout_fd
);
2173 /* Run the command. */
2174 exec_command (argv
, envp
);
2176 #endif /* !AMIGA && !__MSDOS__ && !VMS */
2177 #endif /* !WINDOWS32 */
2180 /* Replace the current process with one running the command in ARGV,
2181 with environment ENVP. This function does not return. */
2183 /* EMX: This function returns the pid of the child process. */
2189 exec_command (char **argv
, char **envp
)
2192 /* to work around a problem with signals and execve: ignore them */
2194 signal (SIGCHLD
,SIG_IGN
);
2196 /* Run the program. */
2197 execve (argv
[0], argv
, envp
);
2198 perror_with_name ("execve: ", argv
[0]);
2199 _exit (EXIT_FAILURE
);
2205 int exit_code
= EXIT_FAILURE
;
2207 /* make sure CreateProcess() has Path it needs */
2208 sync_Path_environment();
2210 /* launch command */
2211 hPID
= process_easy(argv
, envp
);
2213 /* make sure launch ok */
2214 if (hPID
== INVALID_HANDLE_VALUE
)
2218 _("process_easy() failed to launch process (e=%ld)\n"),
2219 process_last_err(hPID
));
2220 for (i
= 0; argv
[i
]; i
++)
2221 fprintf(stderr
, "%s ", argv
[i
]);
2222 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
2226 /* wait and reap last child */
2227 hWaitPID
= process_wait_for_any(1, 0);
2230 /* was an error found on this process? */
2231 err
= process_last_err(hWaitPID
);
2234 exit_code
= process_exit_code(hWaitPID
);
2237 fprintf(stderr
, "make (e=%d, rc=%d): %s",
2238 err
, exit_code
, map_windows32_error_to_string(err
));
2240 /* cleanup process */
2241 process_cleanup(hWaitPID
);
2243 /* expect to find only last pid, warn about other pids reaped */
2244 if (hWaitPID
== hPID
)
2248 char *pidstr
= xstrdup (pid2str ((pid_t
)hWaitPID
));
2251 _("make reaped child pid %s, still waiting for pid %s\n"),
2252 pidstr
, pid2str ((pid_t
)hPID
));
2257 /* return child's exit code as our exit code */
2260 #else /* !WINDOWS32 */
2266 /* Be the user, permanently. */
2271 /* Run the program. */
2272 pid
= spawnvpe (P_NOWAIT
, argv
[0], argv
, envp
);
2277 /* the file might have a strange shell extension */
2278 if (errno
== ENOENT
)
2283 /* Run the program. */
2285 execvp (argv
[0], argv
);
2287 # endif /* !__EMX__ */
2292 error (NILF
, _("%s: Command not found"), argv
[0]);
2296 /* The file is not executable. Try it as a shell script. */
2297 extern char *getenv ();
2304 /* Do not use $SHELL from the environment */
2305 struct variable
*p
= lookup_variable ("SHELL", 5);
2311 shell
= getenv ("SHELL");
2314 shell
= default_shell
;
2317 while (argv
[argc
] != 0)
2325 new_argv
= alloca ((1 + argc
+ 1) * sizeof (char *));
2326 new_argv
[0] = shell
;
2337 new_argv
[i
] = argv
[0];
2340 new_argv
[i
+ argc
] = argv
[argc
];
2345 pid
= spawnvpe (P_NOWAIT
, shell
, new_argv
, envp
);
2349 execvp (shell
, new_argv
);
2351 if (errno
== ENOENT
)
2352 error (NILF
, _("%s: Shell program not found"), shell
);
2354 perror_with_name ("execvp: ", shell
);
2360 /* this nasty error was driving me nuts :-( */
2361 error (NILF
, _("spawnvpe: environment space might be exhausted"));
2366 perror_with_name ("execvp: ", argv
[0]);
2375 #endif /* !WINDOWS32 */
2378 #else /* On Amiga */
2379 void exec_command (char **argv
)
2384 void clean_tmp (void)
2386 DeleteFile (amiga_bname
);
2389 #endif /* On Amiga */
2392 /* Figure out the argument list necessary to run LINE as a command. Try to
2393 avoid using a shell. This routine handles only ' quoting, and " quoting
2394 when no backslash, $ or ' characters are seen in the quotes. Starting
2395 quotes may be escaped with a backslash. If any of the characters in
2396 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2397 is the first word of a line, the shell is used.
2399 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2400 If *RESTP is NULL, newlines will be ignored.
2402 SHELL is the shell to use, or nil to use the default shell.
2403 IFS is the value of $IFS, or nil (meaning the default).
2405 FLAGS is the value of lines_flags for this command line. It is
2406 used in the WINDOWS32 port to check whether + or $(MAKE) were found
2407 in this command line, in which case the effect of just_print_flag
2411 construct_command_argv_internal (char *line
, char **restp
, char *shell
,
2412 char *shellflags
, char *ifs
, int flags
,
2413 char **batch_filename UNUSED
)
2416 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2417 We call 'system' for anything that requires ''slow'' processing,
2418 because DOS shells are too dumb. When $SHELL points to a real
2419 (unix-style) shell, 'system' just calls it to do everything. When
2420 $SHELL points to a DOS shell, 'system' does most of the work
2421 internally, calling the shell only for its internal commands.
2422 However, it looks on the $PATH first, so you can e.g. have an
2423 external command named 'mkdir'.
2425 Since we call 'system', certain characters and commands below are
2426 actually not specific to COMMAND.COM, but to the DJGPP implementation
2427 of 'system'. In particular:
2429 The shell wildcard characters are in DOS_CHARS because they will
2430 not be expanded if we call the child via 'spawnXX'.
2432 The ';' is in DOS_CHARS, because our 'system' knows how to run
2433 multiple commands on a single line.
2435 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2436 won't have to tell one from another and have one more set of
2437 commands and special characters. */
2438 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2439 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2440 "copy", "ctty", "date", "del", "dir", "echo",
2441 "erase", "exit", "for", "goto", "if", "md",
2442 "mkdir", "path", "pause", "prompt", "rd",
2443 "rmdir", "rem", "ren", "rename", "set",
2444 "shift", "time", "type", "ver", "verify",
2447 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2448 static char *sh_cmds_sh
[] = { "cd", "echo", "eval", "exec", "exit", "login",
2449 "logout", "set", "umask", "wait", "while",
2450 "for", "case", "if", ":", ".", "break",
2451 "continue", "export", "read", "readonly",
2452 "shift", "times", "trap", "switch", "unset",
2457 #elif defined (__EMX__)
2458 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2459 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2460 "copy", "ctty", "date", "del", "dir", "echo",
2461 "erase", "exit", "for", "goto", "if", "md",
2462 "mkdir", "path", "pause", "prompt", "rd",
2463 "rmdir", "rem", "ren", "rename", "set",
2464 "shift", "time", "type", "ver", "verify",
2467 static char sh_chars_os2
[] = "*?[];|<>%^()\"'&";
2468 static char *sh_cmds_os2
[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2469 "date", "del", "detach", "dir", "echo",
2470 "endlocal", "erase", "exit", "for", "goto", "if",
2471 "keys", "md", "mkdir", "move", "path", "pause",
2472 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2473 "set", "setlocal", "shift", "start", "time",
2474 "type", "ver", "verify", "vol", ":", 0 };
2476 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^~'";
2477 static char *sh_cmds_sh
[] = { "echo", "cd", "eval", "exec", "exit", "login",
2478 "logout", "set", "umask", "wait", "while",
2479 "for", "case", "if", ":", ".", "break",
2480 "continue", "export", "read", "readonly",
2481 "shift", "times", "trap", "switch", "unset",
2486 #elif defined (_AMIGA)
2487 static char sh_chars
[] = "#;\"|<>()?*$`";
2488 static char *sh_cmds
[] = { "cd", "eval", "if", "delete", "echo", "copy",
2489 "rename", "set", "setenv", "date", "makedir",
2490 "skip", "else", "endif", "path", "prompt",
2491 "unset", "unsetenv", "version",
2493 #elif defined (WINDOWS32)
2494 static char sh_chars_dos
[] = "\"|&<>";
2495 static char *sh_cmds_dos
[] = { "assoc", "break", "call", "cd", "chcp",
2496 "chdir", "cls", "color", "copy", "ctty",
2497 "date", "del", "dir", "echo", "echo.",
2498 "endlocal", "erase", "exit", "for", "ftype",
2499 "goto", "if", "if", "md", "mkdir", "path",
2500 "pause", "prompt", "rd", "rem", "ren",
2501 "rename", "rmdir", "set", "setlocal",
2502 "shift", "time", "title", "type", "ver",
2503 "verify", "vol", ":", 0 };
2504 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2505 static char *sh_cmds_sh
[] = { "cd", "eval", "exec", "exit", "login",
2506 "logout", "set", "umask", "wait", "while", "for",
2507 "case", "if", ":", ".", "break", "continue",
2508 "export", "read", "readonly", "shift", "times",
2509 "trap", "switch", "test",
2510 #ifdef BATCH_MODE_ONLY_SHELL
2516 #elif defined(__riscos__)
2517 static char sh_chars
[] = "";
2518 static char *sh_cmds
[] = { 0 };
2519 #else /* must be UNIX-ish */
2520 static char sh_chars
[] = "#;\"*?[]&|<>(){}$`^~!";
2521 static char *sh_cmds
[] = { ".", ":", "break", "case", "cd", "continue",
2522 "eval", "exec", "exit", "export", "for", "if",
2523 "login", "logout", "read", "readonly", "set",
2524 "shift", "switch", "test", "times", "trap",
2525 "ulimit", "umask", "unset", "wait", "while", 0 };
2526 # ifdef HAVE_DOS_PATHS
2527 /* This is required if the MSYS/Cygwin ports (which do not define
2528 WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
2529 sh_chars_sh[] directly (see below). */
2530 static char *sh_chars_sh
= sh_chars
;
2531 # endif /* HAVE_DOS_PATHS */
2537 int instring
, word_has_equals
, seen_nonequals
, last_argument_was_empty
;
2538 char **new_argv
= 0;
2544 sh_cmds
= sh_cmds_dos
;
2545 sh_chars
= sh_chars_dos
;
2547 sh_cmds
= sh_cmds_sh
;
2548 sh_chars
= sh_chars_sh
;
2550 #endif /* WINDOWS32 */
2555 /* Make sure not to bother processing an empty line. */
2556 while (isblank ((unsigned char)*line
))
2561 if (shellflags
== 0)
2562 shellflags
= posix_pedantic
? "-ec" : "-c";
2564 /* See if it is safe to parse commands internally. */
2566 shell
= default_shell
;
2568 else if (strcmp (shell
, default_shell
))
2570 char *s1
= _fullpath (NULL
, shell
, 0);
2571 char *s2
= _fullpath (NULL
, default_shell
, 0);
2573 slow_flag
= strcmp ((s1
? s1
: ""), (s2
? s2
: ""));
2582 #else /* not WINDOWS32 */
2583 #if defined (__MSDOS__) || defined (__EMX__)
2584 else if (strcasecmp (shell
, default_shell
))
2586 extern int _is_unixy_shell (const char *_path
);
2588 DB (DB_BASIC
, (_("$SHELL changed (was '%s', now '%s')\n"),
2589 default_shell
, shell
));
2590 unixy_shell
= _is_unixy_shell (shell
);
2591 /* we must allocate a copy of shell: construct_command_argv() will free
2592 * shell after this function returns. */
2593 default_shell
= xstrdup (shell
);
2597 sh_chars
= sh_chars_sh
;
2598 sh_cmds
= sh_cmds_sh
;
2602 sh_chars
= sh_chars_dos
;
2603 sh_cmds
= sh_cmds_dos
;
2605 if (_osmode
== OS2_MODE
)
2607 sh_chars
= sh_chars_os2
;
2608 sh_cmds
= sh_cmds_os2
;
2612 #else /* !__MSDOS__ */
2613 else if (strcmp (shell
, default_shell
))
2615 #endif /* !__MSDOS__ && !__EMX__ */
2616 #endif /* not WINDOWS32 */
2619 for (ap
= ifs
; *ap
!= '\0'; ++ap
)
2620 if (*ap
!= ' ' && *ap
!= '\t' && *ap
!= '\n')
2623 if (shellflags
!= 0)
2624 if (shellflags
[0] != '-'
2625 || ((shellflags
[1] != 'c' || shellflags
[2] != '\0')
2626 && (shellflags
[1] != 'e' || shellflags
[2] != 'c' || shellflags
[3] != '\0')))
2629 i
= strlen (line
) + 1;
2631 /* More than 1 arg per character is impossible. */
2632 new_argv
= xmalloc (i
* sizeof (char *));
2634 /* All the args can fit in a buffer as big as LINE is. */
2635 ap
= new_argv
[0] = argstr
= xmalloc (i
);
2638 /* I is how many complete arguments have been found. */
2640 instring
= word_has_equals
= seen_nonequals
= last_argument_was_empty
= 0;
2641 for (p
= line
; *p
!= '\0'; ++p
)
2647 /* Inside a string, just copy any char except a closing quote
2648 or a backslash-newline combination. */
2652 if (ap
== new_argv
[0] || *(ap
-1) == '\0')
2653 last_argument_was_empty
= 1;
2655 else if (*p
== '\\' && p
[1] == '\n')
2657 /* Backslash-newline is handled differently depending on what
2658 kind of string we're in: inside single-quoted strings you
2659 keep them; in double-quoted strings they disappear. For
2660 DOS/Windows/OS2, if we don't have a POSIX shell, we keep the
2661 pre-POSIX behavior of removing the backslash-newline. */
2663 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2674 else if (*p
== '\n' && restp
!= NULL
)
2676 /* End of the command line. */
2680 /* Backslash, $, and ` are special inside double quotes.
2681 If we see any of those, punt.
2682 But on MSDOS, if we use COMMAND.COM, double and single
2683 quotes have the same effect. */
2684 else if (instring
== '"' && strchr ("\\$`", *p
) != 0 && unixy_shell
)
2689 else if (strchr (sh_chars
, *p
) != 0)
2690 /* Not inside a string, but it's a special char. */
2692 else if (one_shell
&& *p
== '\n')
2693 /* In .ONESHELL mode \n is a separator like ; or && */
2696 else if (*p
== '.' && p
[1] == '.' && p
[2] == '.' && p
[3] != '.')
2697 /* '...' is a wildcard in DJGPP. */
2701 /* Not a special char. */
2705 /* Equals is a special character in leading words before the
2706 first word with no equals sign in it. This is not the case
2707 with sh -k, but we never get here when using nonstandard
2709 if (! seen_nonequals
&& unixy_shell
)
2711 word_has_equals
= 1;
2716 /* Backslash-newline has special case handling, ref POSIX.
2717 We're in the fastpath, so emulate what the shell would do. */
2720 /* Throw out the backslash and newline. */
2723 /* If there's nothing in this argument yet, skip any
2724 whitespace before the start of the next word. */
2725 if (ap
== new_argv
[i
])
2726 p
= next_token (p
+ 1) - 1;
2728 else if (p
[1] != '\0')
2730 #ifdef HAVE_DOS_PATHS
2731 /* Only remove backslashes before characters special to Unixy
2732 shells. All other backslashes are copied verbatim, since
2733 they are probably DOS-style directory separators. This
2734 still leaves a small window for problems, but at least it
2735 should work for the vast majority of naive users. */
2738 /* A dot is only special as part of the "..."
2740 if (strneq (p
+ 1, ".\\.\\.", 5))
2748 if (p
[1] != '\\' && p
[1] != '\''
2749 && !isspace ((unsigned char)p
[1])
2750 && strchr (sh_chars_sh
, p
[1]) == 0)
2751 /* back up one notch, to copy the backslash */
2753 #endif /* HAVE_DOS_PATHS */
2755 /* Copy and skip the following char. */
2768 /* End of the command line. */
2773 /* Newlines are not special. */
2779 /* We have the end of an argument.
2780 Terminate the text of the argument. */
2783 last_argument_was_empty
= 0;
2785 /* Update SEEN_NONEQUALS, which tells us if every word
2786 heretofore has contained an '='. */
2787 seen_nonequals
|= ! word_has_equals
;
2788 if (word_has_equals
&& ! seen_nonequals
)
2789 /* An '=' in a word before the first
2790 word without one is magical. */
2792 word_has_equals
= 0; /* Prepare for the next word. */
2794 /* If this argument is the command name,
2795 see if it is a built-in shell command.
2796 If so, have the shell handle it. */
2800 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2802 if (streq (sh_cmds
[j
], new_argv
[0]))
2805 /* Non-Unix shells are case insensitive. */
2807 && strcasecmp (sh_cmds
[j
], new_argv
[0]) == 0)
2813 /* Ignore multiple whitespace chars. */
2814 p
= next_token (p
) - 1;
2825 /* Let the shell deal with an unterminated quote. */
2828 /* Terminate the last argument and the argument list. */
2831 if (new_argv
[i
][0] != '\0' || last_argument_was_empty
)
2838 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2839 if (streq (sh_cmds
[j
], new_argv
[0]))
2843 if (new_argv
[0] == 0)
2845 /* Line was empty. */
2854 /* We must use the shell. */
2858 /* Free the old argument list we were working on. */
2864 execute_by_shell
= 1; /* actually, call 'system' if shell isn't unixy */
2873 buffer
= xmalloc (strlen (line
)+1);
2876 for (dptr
=buffer
; *ptr
; )
2878 if (*ptr
== '\\' && ptr
[1] == '\n')
2880 else if (*ptr
== '@') /* Kludge: multiline commands */
2890 new_argv
= xmalloc (2 * sizeof (char *));
2891 new_argv
[0] = buffer
;
2894 #else /* Not Amiga */
2897 * Not eating this whitespace caused things like
2901 * which gave the shell fits. I think we have to eat
2902 * whitespace here, but this code should be considered
2903 * suspicious if things start failing....
2906 /* Make sure not to bother processing an empty line. */
2907 while (isspace ((unsigned char)*line
))
2911 #endif /* WINDOWS32 */
2914 /* SHELL may be a multi-word command. Construct a command line
2915 "$(SHELL) $(.SHELLFLAGS) LINE", with all special chars in LINE escaped.
2916 Then recurse, expanding this command line to get the final
2919 unsigned int shell_len
= strlen (shell
);
2920 unsigned int line_len
= strlen (line
);
2921 unsigned int sflags_len
= shellflags
? strlen (shellflags
) : 0;
2922 char *command_ptr
= NULL
; /* used for batch_mode_shell mode */
2925 # ifdef __EMX__ /* is this necessary? */
2926 if (!unixy_shell
&& shellflags
)
2927 shellflags
[0] = '/'; /* "/c" */
2930 /* In .ONESHELL mode we are allowed to throw the entire current
2931 recipe string at a single shell and trust that the user
2932 has configured the shell and shell flags, and formatted
2933 the string, appropriately. */
2936 /* If the shell is Bourne compatible, we must remove and ignore
2937 interior special chars [@+-] because they're meaningless to
2938 the shell itself. If, however, we're in .ONESHELL mode and
2939 have changed SHELL to something non-standard, we should
2940 leave those alone because they could be part of the
2941 script. In this case we must also leave in place
2942 any leading [@+-] for the same reason. */
2944 /* Remove and ignore interior prefix chars [@+-] because they're
2945 meaningless given a single shell. */
2946 #if defined __MSDOS__ || defined (__EMX__)
2947 if (unixy_shell
) /* the test is complicated and we already did it */
2949 if (is_bourne_compatible_shell(shell
))
2952 const char *f
= line
;
2955 /* Copy the recipe, removing and ignoring interior prefix chars
2956 [@+-]: they're meaningless in .ONESHELL mode. */
2957 while (f
[0] != '\0')
2961 /* This is the start of a new recipe line.
2962 Skip whitespace and prefix characters. */
2963 while (isblank (*f
) || *f
== '-' || *f
== '@' || *f
== '+')
2966 /* Copy until we get to the next logical recipe line. */
2974 /* On unescaped newline, we're done with this line. */
2975 if (f
[-1] == '\n' && ! esc
)
2978 /* Something else: reset the escape sequence. */
2986 /* Create an argv list for the shell command line. */
2990 new_argv
= xmalloc ((4 + sflags_len
/2) * sizeof (char *));
2991 new_argv
[n
++] = xstrdup (shell
);
2993 /* Chop up the shellflags (if any) and assign them. */
2995 new_argv
[n
++] = xstrdup ("");
2998 const char *s
= shellflags
;
3001 while ((t
= find_next_token (&s
, &len
)) != 0)
3002 new_argv
[n
++] = xstrndup (t
, len
);
3005 /* Set the command to invoke. */
3006 new_argv
[n
++] = line
;
3007 new_argv
[n
++] = NULL
;
3012 new_line
= xmalloc ((shell_len
*2) + 1 + sflags_len
+ 1
3013 + (line_len
*2) + 1);
3015 /* Copy SHELL, escaping any characters special to the shell. If
3016 we don't escape them, construct_command_argv_internal will
3017 recursively call itself ad nauseam, or until stack overflow,
3018 whichever happens first. */
3019 for (p
= shell
; *p
!= '\0'; ++p
)
3021 if (strchr (sh_chars
, *p
) != 0)
3027 memcpy (ap
, shellflags
, sflags_len
);
3031 for (p
= line
; *p
!= '\0'; ++p
)
3033 if (restp
!= NULL
&& *p
== '\n')
3038 else if (*p
== '\\' && p
[1] == '\n')
3040 /* POSIX says we keep the backslash-newline. If we don't have a
3041 POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
3042 and remove the backslash/newline. */
3043 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
3044 # define PRESERVE_BSNL unixy_shell
3046 # define PRESERVE_BSNL 1
3051 /* Only non-batch execution needs another backslash,
3052 because it will be passed through a recursive
3053 invocation of this function. */
3054 if (!batch_mode_shell
)
3062 /* DOS shells don't know about backslash-escaping. */
3063 if (unixy_shell
&& !batch_mode_shell
&&
3064 (*p
== '\\' || *p
== '\'' || *p
== '"'
3065 || isspace ((unsigned char)*p
)
3066 || strchr (sh_chars
, *p
) != 0))
3069 else if (unixy_shell
&& strneq (p
, "...", 3))
3071 /* The case of '...' wildcard again. */
3072 strcpy (ap
, "\\.\\.\\");
3079 if (ap
== new_line
+ shell_len
+ sflags_len
+ 2)
3081 /* Line was empty. */
3088 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3089 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3090 cases, run commands via a script file. */
3091 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
)) {
3092 /* Need to allocate new_argv, although it's unused, because
3093 start_job_command will want to free it and its 0'th element. */
3094 new_argv
= xmalloc(2 * sizeof (char *));
3095 new_argv
[0] = xstrdup ("");
3097 } else if ((no_default_sh_exe
|| batch_mode_shell
) && batch_filename
) {
3100 int id
= GetCurrentProcessId();
3103 /* create a file name */
3104 sprintf(fbuf
, "make%d", id
);
3105 *batch_filename
= create_batch_file (fbuf
, unixy_shell
, &temp_fd
);
3107 DB (DB_JOBS
, (_("Creating temporary batch file %s\n"),
3110 /* Create a FILE object for the batch file, and write to it the
3111 commands to be executed. Put the batch file in TEXT mode. */
3112 _setmode (temp_fd
, _O_TEXT
);
3113 batch
= _fdopen (temp_fd
, "wt");
3115 fputs ("@echo off\n", batch
);
3116 fputs (command_ptr
, batch
);
3117 fputc ('\n', batch
);
3119 DB (DB_JOBS
, (_("Batch file contents:%s\n\t%s\n"),
3120 !unixy_shell
? "\n\t@echo off" : "", command_ptr
));
3123 new_argv
= xmalloc(3 * sizeof (char *));
3125 new_argv
[0] = xstrdup (shell
);
3126 new_argv
[1] = *batch_filename
; /* only argv[0] gets freed later */
3128 new_argv
[0] = xstrdup (*batch_filename
);
3133 #endif /* WINDOWS32 */
3136 new_argv
= construct_command_argv_internal (new_line
, 0, 0, 0, 0,
3140 else if (!unixy_shell
)
3142 /* new_line is local, must not be freed therefore
3143 We use line here instead of new_line because we run the shell
3145 size_t line_len
= strlen (line
);
3148 memcpy (new_line
, line
, line_len
+ 1);
3149 /* Replace all backslash-newline combination and also following tabs.
3150 Important: stop at the first '\n' because that's what the loop above
3151 did. The next line starting at restp[0] will be executed during the
3152 next call of this function. */
3153 while (*q
!= '\0' && *q
!= '\n')
3155 if (q
[0] == '\\' && q
[1] == '\n')
3156 q
+= 2; /* remove '\\' and '\n' */
3162 # ifndef NO_CMD_DEFAULT
3163 if (strnicmp (new_line
, "echo", 4) == 0
3164 && (new_line
[4] == ' ' || new_line
[4] == '\t'))
3166 /* the builtin echo command: handle it separately */
3167 size_t echo_len
= line_len
- 5;
3168 char *echo_line
= new_line
+ 5;
3170 /* special case: echo 'x="y"'
3171 cmd works this way: a string is printed as is, i.e., no quotes
3172 are removed. But autoconf uses a command like echo 'x="y"' to
3173 determine whether make works. autoconf expects the output x="y"
3174 so we will do exactly that.
3175 Note: if we do not allow cmd to be the default shell
3176 we do not need this kind of voodoo */
3177 if (echo_line
[0] == '\''
3178 && echo_line
[echo_len
- 1] == '\''
3179 && strncmp (echo_line
+ 1, "ac_maketemp=",
3180 strlen ("ac_maketemp=")) == 0)
3182 /* remove the enclosing quotes */
3183 memmove (echo_line
, echo_line
+ 1, echo_len
- 2);
3184 echo_line
[echo_len
- 2] = '\0';
3190 /* Let the shell decide what to do. Put the command line into the
3191 2nd command line argument and hope for the best ;-) */
3192 size_t sh_len
= strlen (shell
);
3194 /* exactly 3 arguments + NULL */
3195 new_argv
= xmalloc (4 * sizeof (char *));
3196 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3197 the trailing '\0' */
3198 new_argv
[0] = xmalloc (sh_len
+ line_len
+ 5);
3199 memcpy (new_argv
[0], shell
, sh_len
+ 1);
3200 new_argv
[1] = new_argv
[0] + sh_len
+ 1;
3201 memcpy (new_argv
[1], "/c", 3);
3202 new_argv
[2] = new_argv
[1] + 3;
3203 memcpy (new_argv
[2], new_line
, line_len
+ 1);
3207 #elif defined(__MSDOS__)
3210 /* With MSDOS shells, we must construct the command line here
3211 instead of recursively calling ourselves, because we
3212 cannot backslash-escape the special characters (see above). */
3213 new_argv
= xmalloc (sizeof (char *));
3214 line_len
= strlen (new_line
) - shell_len
- sflags_len
- 2;
3215 new_argv
[0] = xmalloc (line_len
+ 1);
3216 strncpy (new_argv
[0],
3217 new_line
+ shell_len
+ sflags_len
+ 2, line_len
);
3218 new_argv
[0][line_len
] = '\0';
3222 fatal (NILF
, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3223 __FILE__
, __LINE__
);
3228 #endif /* ! AMIGA */
3234 /* Figure out the argument list necessary to run LINE as a command. Try to
3235 avoid using a shell. This routine handles only ' quoting, and " quoting
3236 when no backslash, $ or ' characters are seen in the quotes. Starting
3237 quotes may be escaped with a backslash. If any of the characters in
3238 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3239 is the first word of a line, the shell is used.
3241 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3242 If *RESTP is NULL, newlines will be ignored.
3244 FILE is the target whose commands these are. It is used for
3245 variable expansion for $(SHELL) and $(IFS). */
3248 construct_command_argv (char *line
, char **restp
, struct file
*file
,
3249 int cmd_flags
, char **batch_filename
)
3251 char *shell
, *ifs
, *shellflags
;
3263 && (isspace ((unsigned char)*cptr
)))
3268 && (!isspace((unsigned char)*cptr
)))
3273 argv
= xmalloc (argc
* sizeof (char *));
3282 && (isspace ((unsigned char)*cptr
)))
3286 DB (DB_JOBS
, ("argv[%d] = [%s]\n", argc
, cptr
));
3287 argv
[argc
++] = cptr
;
3289 && (!isspace((unsigned char)*cptr
)))
3296 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3297 int save
= warn_undefined_variables_flag
;
3298 warn_undefined_variables_flag
= 0;
3300 shell
= allocated_variable_expand_for_file ("$(SHELL)", file
);
3303 * Convert to forward slashes so that construct_command_argv_internal()
3307 char *p
= w32ify (shell
, 0);
3313 static const char *unixroot
= NULL
;
3314 static const char *last_shell
= "";
3315 static int init
= 0;
3318 unixroot
= getenv ("UNIXROOT");
3319 /* unixroot must be NULL or not empty */
3320 if (unixroot
&& unixroot
[0] == '\0') unixroot
= NULL
;
3324 /* if we have an unixroot drive and if shell is not default_shell
3325 (which means it's either cmd.exe or the test has already been
3326 performed) and if shell is an absolute path without drive letter,
3327 try whether it exists e.g.: if "/bin/sh" does not exist use
3328 "$UNIXROOT/bin/sh" instead. */
3329 if (unixroot
&& shell
&& strcmp (shell
, last_shell
) != 0
3330 && (shell
[0] == '/' || shell
[0] == '\\'))
3332 /* trying a new shell, check whether it exists */
3333 size_t size
= strlen (shell
);
3334 char *buf
= xmalloc (size
+ 7);
3335 memcpy (buf
, shell
, size
);
3336 memcpy (buf
+ size
, ".exe", 5); /* including the trailing '\0' */
3337 if (access (shell
, F_OK
) != 0 && access (buf
, F_OK
) != 0)
3339 /* try the same for the unixroot drive */
3340 memmove (buf
+ 2, buf
, size
+ 5);
3341 buf
[0] = unixroot
[0];
3342 buf
[1] = unixroot
[1];
3343 if (access (buf
, F_OK
) == 0)
3344 /* we have found a shell! */
3354 #endif /* __EMX__ */
3356 shellflags
= allocated_variable_expand_for_file ("$(.SHELLFLAGS)", file
);
3357 ifs
= allocated_variable_expand_for_file ("$(IFS)", file
);
3359 warn_undefined_variables_flag
= save
;
3362 argv
= construct_command_argv_internal (line
, restp
, shell
, shellflags
, ifs
,
3363 cmd_flags
, batch_filename
);
3372 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3374 dup2 (int old
, int new)
3389 #endif /* !HAVE_DUP2 && !_AMIGA */
3391 /* On VMS systems, include special VMS functions. */
3394 #include "vmsjobs.c"