Add in HAVE_STDARG_H to the various port config files.
[make.git] / job.c
blob681fdcf99055064b5234af6d3fc3629344c83ab3
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988,89,90,91,92,93,94,95,96,97,99 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
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 GNU Make is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNU Make; see the file COPYING. If not, write to
17 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 #include "make.h"
22 #include <assert.h>
24 #include "job.h"
25 #include "debug.h"
26 #include "filedef.h"
27 #include "commands.h"
28 #include "variable.h"
29 #include "debug.h"
31 #include <string.h>
33 /* Default shell to use. */
34 #ifdef WINDOWS32
36 char *default_shell = "sh.exe";
37 int no_default_sh_exe = 1;
38 int batch_mode_shell = 1;
40 #elif defined (_AMIGA)
42 char default_shell[] = "";
43 extern int MyExecute (char **);
44 int batch_mode_shell = 0;
46 #elif defined (__MSDOS__)
48 /* The default shell is a pointer so we can change it if Makefile
49 says so. It is without an explicit path so we get a chance
50 to search the $PATH for it (since MSDOS doesn't have standard
51 directories we could trust). */
52 char *default_shell = "command.com";
53 int batch_mode_shell = 0;
55 #elif defined (__EMX__)
57 char *default_shell = "/bin/sh";
58 int batch_mode_shell = 0;
60 #elif defined (VMS)
62 # include <descrip.h>
63 char default_shell[] = "";
64 int batch_mode_shell = 0;
66 #else
68 char default_shell[] = "/bin/sh";
69 int batch_mode_shell = 0;
71 #endif
73 #ifdef __MSDOS__
74 # include <process.h>
75 static int execute_by_shell;
76 static int dos_pid = 123;
77 int dos_status;
78 int dos_command_running;
79 #endif /* __MSDOS__ */
81 #ifdef _AMIGA
82 # include <proto/dos.h>
83 static int amiga_pid = 123;
84 static int amiga_status;
85 static char amiga_bname[32];
86 static int amiga_batch_file;
87 #endif /* Amiga. */
89 #ifdef VMS
90 # ifndef __GNUC__
91 # include <processes.h>
92 # endif
93 # include <starlet.h>
94 # include <lib$routines.h>
95 #endif
97 #ifdef WINDOWS32
98 # include <windows.h>
99 # include <io.h>
100 # include <process.h>
101 # include "sub_proc.h"
102 # include "w32err.h"
103 # include "pathstuff.h"
104 #endif /* WINDOWS32 */
106 #ifdef __EMX__
107 # include <process.h>
108 #endif
110 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
111 # include <sys/wait.h>
112 #endif
114 #ifdef HAVE_WAITPID
115 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
116 #else /* Don't have waitpid. */
117 # ifdef HAVE_WAIT3
118 # ifndef wait3
119 extern int wait3 ();
120 # endif
121 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
122 # endif /* Have wait3. */
123 #endif /* Have waitpid. */
125 #if !defined (wait) && !defined (POSIX)
126 extern int wait ();
127 #endif
129 #ifndef HAVE_UNION_WAIT
131 # define WAIT_T int
133 # ifndef WTERMSIG
134 # define WTERMSIG(x) ((x) & 0x7f)
135 # endif
136 # ifndef WCOREDUMP
137 # define WCOREDUMP(x) ((x) & 0x80)
138 # endif
139 # ifndef WEXITSTATUS
140 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
141 # endif
142 # ifndef WIFSIGNALED
143 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
144 # endif
145 # ifndef WIFEXITED
146 # define WIFEXITED(x) (WTERMSIG (x) == 0)
147 # endif
149 #else /* Have `union wait'. */
151 # define WAIT_T union wait
152 # ifndef WTERMSIG
153 # define WTERMSIG(x) ((x).w_termsig)
154 # endif
155 # ifndef WCOREDUMP
156 # define WCOREDUMP(x) ((x).w_coredump)
157 # endif
158 # ifndef WEXITSTATUS
159 # define WEXITSTATUS(x) ((x).w_retcode)
160 # endif
161 # ifndef WIFSIGNALED
162 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
163 # endif
164 # ifndef WIFEXITED
165 # define WIFEXITED(x) (WTERMSIG(x) == 0)
166 # endif
168 #endif /* Don't have `union wait'. */
170 #ifdef VMS
171 static int vms_jobsefnmask = 0;
172 #endif /* !VMS */
174 #ifndef HAVE_UNISTD_H
175 extern int dup2 ();
176 extern int execve ();
177 extern void _exit ();
178 # ifndef VMS
179 extern int geteuid ();
180 extern int getegid ();
181 extern int setgid ();
182 extern int getgid ();
183 # endif
184 #endif
186 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
188 extern int getloadavg PARAMS ((double loadavg[], int nelem));
189 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
190 int *is_remote, int *id_ptr, int *used_stdin));
191 extern int start_remote_job_p PARAMS ((int));
192 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
193 int *coredump_ptr, int block));
195 RETSIGTYPE child_handler PARAMS ((int));
196 static void free_child PARAMS ((struct child *));
197 static void start_job_command PARAMS ((struct child *child));
198 static int load_too_high PARAMS ((void));
199 static int job_next_command PARAMS ((struct child *));
200 static int start_waiting_job PARAMS ((struct child *));
201 #ifdef VMS
202 static void vmsWaitForChildren PARAMS ((int *));
203 #endif
205 /* Chain of all live (or recently deceased) children. */
207 struct child *children = 0;
209 /* Number of children currently running. */
211 unsigned int job_slots_used = 0;
213 /* Nonzero if the `good' standard input is in use. */
215 static int good_stdin_used = 0;
217 /* Chain of children waiting to run until the load average goes down. */
219 static struct child *waiting_jobs = 0;
221 /* Non-zero if we use a *real* shell (always so on Unix). */
223 int unixy_shell = 1;
225 /* Number of jobs started in the current second. */
227 unsigned long job_counter = 0;
230 #ifdef WINDOWS32
232 * The macro which references this function is defined in make.h.
235 w32_kill(int pid, int sig)
237 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
239 #endif /* WINDOWS32 */
241 #ifdef __EMX__
242 /* returns whether path is assumed to be a unix like shell. */
244 _is_unixy_shell (const char *path)
246 /* list of non unix shells */
247 const char *known_os2shells[] = {
248 "cmd.exe",
249 "cmd",
250 "4os2.exe",
251 "4os2",
252 "4dos.exe",
253 "4dos",
254 "command.com",
255 "command",
256 NULL
259 /* find the rightmost '/' or '\\' */
260 const char *name = strrchr (path, '/');
261 const char *p = strrchr (path, '\\');
262 unsigned i;
264 if (name && p) /* take the max */
265 name = (name > p) ? name : p;
266 else if (p) /* name must be 0 */
267 name = p;
268 else if (!name) /* name and p must be 0 */
269 name = path;
271 if (*name == '/' || *name == '\\') name++;
273 i = 0;
274 while (known_os2shells[i] != NULL) {
275 if (stricmp (name, known_os2shells[i]) == 0) /* strcasecmp() */
276 return 0; /* not a unix shell */
277 i++;
280 /* in doubt assume a unix like shell */
281 return 1;
283 #endif /* __EMX__ */
286 /* Write an error message describing the exit status given in
287 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
288 Append "(ignored)" if IGNORED is nonzero. */
290 static void
291 child_error (char *target_name, int exit_code, int exit_sig, int coredump,
292 int ignored)
294 if (ignored && silent_flag)
295 return;
297 #ifdef VMS
298 if (!(exit_code & 1))
299 error (NILF,
300 (ignored ? _("*** [%s] Error 0x%x (ignored)")
301 : _("*** [%s] Error 0x%x")),
302 target_name, exit_code);
303 #else
304 if (exit_sig == 0)
305 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
306 _("*** [%s] Error %d"),
307 target_name, exit_code);
308 else
309 error (NILF, "*** [%s] %s%s",
310 target_name, strsignal (exit_sig),
311 coredump ? _(" (core dumped)") : "");
312 #endif /* VMS */
315 #ifdef VMS
316 /* Wait for nchildren children to terminate */
317 static void
318 vmsWaitForChildren(int *status)
320 while (1)
322 if (!vms_jobsefnmask)
324 *status = 0;
325 return;
328 *status = sys$wflor (32, vms_jobsefnmask);
330 return;
333 /* Set up IO redirection. */
335 char *
336 vms_redirect (struct dsc$descriptor_s *desc, char *fname, char *ibuf)
338 char *fptr;
339 extern char *vmsify ();
341 ibuf++;
342 while (isspace ((unsigned char)*ibuf))
343 ibuf++;
344 fptr = ibuf;
345 while (*ibuf && !isspace ((unsigned char)*ibuf))
346 ibuf++;
347 *ibuf = 0;
348 if (strcmp (fptr, "/dev/null") != 0)
350 strcpy (fname, vmsify (fptr, 0));
351 if (strchr (fname, '.') == 0)
352 strcat (fname, ".");
354 desc->dsc$w_length = strlen(fname);
355 desc->dsc$a_pointer = fname;
356 desc->dsc$b_dtype = DSC$K_DTYPE_T;
357 desc->dsc$b_class = DSC$K_CLASS_S;
359 if (*fname == 0)
360 printf (_("Warning: Empty redirection\n"));
361 return ibuf;
365 /* found apostrophe at (p-1)
366 inc p until after closing apostrophe.
369 static char *
370 vms_handle_apos (char *p)
372 int alast;
374 #define SEPCHARS ",/()= "
376 alast = 0;
378 while (*p != 0)
380 if (*p == '"')
382 if (alast)
384 alast = 0;
385 p++;
387 else
389 p++;
390 if (strchr (SEPCHARS, *p))
391 break;
392 alast = 1;
395 else
396 p++;
399 return p;
402 #endif
405 /* Handle a dead child. This handler may or may not ever be installed.
407 If we're using the jobserver feature, we need it. First, installing it
408 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
409 read FD to ensure we don't enter another blocking read without reaping all
410 the dead children. In this case we don't need the dead_children count.
412 If we don't have either waitpid or wait3, then make is unreliable, but we
413 use the dead_children count to reap children as best we can. */
415 static unsigned int dead_children = 0;
417 RETSIGTYPE
418 child_handler (int sig UNUSED)
420 ++dead_children;
422 if (job_rfd >= 0)
424 close (job_rfd);
425 job_rfd = -1;
428 #ifdef __EMX__
429 /* The signal handler must called only once! */
430 signal (SIGCHLD, SIG_DFL);
431 #endif
433 /* This causes problems if the SIGCHLD interrupts a printf().
434 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
438 extern int shell_function_pid, shell_function_completed;
440 /* Reap all dead children, storing the returned status and the new command
441 state (`cs_finished') in the `file' member of the `struct child' for the
442 dead child, and removing the child from the chain. In addition, if BLOCK
443 nonzero, we block in this function until we've reaped at least one
444 complete child, waiting for it to die if necessary. If ERR is nonzero,
445 print an error message first. */
447 void
448 reap_children (int block, int err)
450 WAIT_T status;
451 /* Initially, assume we have some. */
452 int reap_more = 1;
454 #ifdef WAIT_NOHANG
455 # define REAP_MORE reap_more
456 #else
457 # define REAP_MORE dead_children
458 #endif
460 /* As long as:
462 We have at least one child outstanding OR a shell function in progress,
464 We're blocking for a complete child OR there are more children to reap
466 we'll keep reaping children. */
468 while ((children != 0 || shell_function_pid != 0)
469 && (block || REAP_MORE))
471 int remote = 0;
472 register int pid;
473 int exit_code, exit_sig, coredump;
474 register struct child *lastc, *c;
475 int child_failed;
476 int any_remote, any_local;
478 if (err && block)
480 /* We might block for a while, so let the user know why. */
481 fflush (stdout);
482 error (NILF, _("*** Waiting for unfinished jobs...."));
485 /* We have one less dead child to reap. As noted in
486 child_handler() above, this count is completely unimportant for
487 all modern, POSIX-y systems that support wait3() or waitpid().
488 The rest of this comment below applies only to early, broken
489 pre-POSIX systems. We keep the count only because... it's there...
491 The test and decrement are not atomic; if it is compiled into:
492 register = dead_children - 1;
493 dead_children = register;
494 a SIGCHLD could come between the two instructions.
495 child_handler increments dead_children.
496 The second instruction here would lose that increment. But the
497 only effect of dead_children being wrong is that we might wait
498 longer than necessary to reap a child, and lose some parallelism;
499 and we might print the "Waiting for unfinished jobs" message above
500 when not necessary. */
502 if (dead_children > 0)
503 --dead_children;
505 any_remote = 0;
506 any_local = shell_function_pid != 0;
507 for (c = children; c != 0; c = c->next)
509 any_remote |= c->remote;
510 any_local |= ! c->remote;
511 DB (DB_JOBS, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
512 (unsigned long int) c, c->file->name,
513 (long) c->pid, c->remote ? _(" (remote)") : ""));
514 #ifdef VMS
515 break;
516 #endif
519 /* First, check for remote children. */
520 if (any_remote)
521 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
522 else
523 pid = 0;
525 if (pid > 0)
526 /* We got a remote child. */
527 remote = 1;
528 else if (pid < 0)
530 /* A remote status command failed miserably. Punt. */
531 remote_status_lose:
532 pfatal_with_name ("remote_status");
534 else
536 /* No remote children. Check for local children. */
537 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
538 if (any_local)
540 #ifdef VMS
541 vmsWaitForChildren (&status);
542 pid = c->pid;
543 #else
544 #ifdef WAIT_NOHANG
545 if (!block)
546 pid = WAIT_NOHANG (&status);
547 else
548 #endif
549 pid = wait (&status);
550 #endif /* !VMS */
552 else
553 pid = 0;
555 if (pid < 0)
557 /* The wait*() failed miserably. Punt. */
558 pfatal_with_name ("wait");
560 else if (pid > 0)
562 /* We got a child exit; chop the status word up. */
563 exit_code = WEXITSTATUS (status);
564 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
565 coredump = WCOREDUMP (status);
567 /* If we have started jobs in this second, remove one. */
568 if (job_counter)
569 --job_counter;
571 else
573 /* No local children are dead. */
574 reap_more = 0;
576 if (!block || !any_remote)
577 break;
579 /* Now try a blocking wait for a remote child. */
580 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
581 if (pid < 0)
582 goto remote_status_lose;
583 else if (pid == 0)
584 /* No remote children either. Finally give up. */
585 break;
587 /* We got a remote child. */
588 remote = 1;
590 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
592 #ifdef __MSDOS__
593 /* Life is very different on MSDOS. */
594 pid = dos_pid - 1;
595 status = dos_status;
596 exit_code = WEXITSTATUS (status);
597 if (exit_code == 0xff)
598 exit_code = -1;
599 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
600 coredump = 0;
601 #endif /* __MSDOS__ */
602 #ifdef _AMIGA
603 /* Same on Amiga */
604 pid = amiga_pid - 1;
605 status = amiga_status;
606 exit_code = amiga_status;
607 exit_sig = 0;
608 coredump = 0;
609 #endif /* _AMIGA */
610 #ifdef WINDOWS32
612 HANDLE hPID;
613 int err;
615 /* wait for anything to finish */
616 if (hPID = process_wait_for_any()) {
618 /* was an error found on this process? */
619 err = process_last_err(hPID);
621 /* get exit data */
622 exit_code = process_exit_code(hPID);
624 if (err)
625 fprintf(stderr, "make (e=%d): %s",
626 exit_code, map_windows32_error_to_string(exit_code));
628 /* signal */
629 exit_sig = process_signal(hPID);
631 /* cleanup process */
632 process_cleanup(hPID);
634 coredump = 0;
636 pid = (int) hPID;
638 #endif /* WINDOWS32 */
641 /* Check if this is the child of the `shell' function. */
642 if (!remote && pid == shell_function_pid)
644 /* It is. Leave an indicator for the `shell' function. */
645 if (exit_sig == 0 && exit_code == 127)
646 shell_function_completed = -1;
647 else
648 shell_function_completed = 1;
649 break;
652 child_failed = exit_sig != 0 || exit_code != 0;
654 /* Search for a child matching the deceased one. */
655 lastc = 0;
656 for (c = children; c != 0; lastc = c, c = c->next)
657 if (c->remote == remote && c->pid == pid)
658 break;
660 if (c == 0)
661 /* An unknown child died.
662 Ignore it; it was inherited from our invoker. */
663 continue;
665 DB (DB_JOBS, (child_failed
666 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
667 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
668 (unsigned long int) c, (long) c->pid,
669 c->remote ? _(" (remote)") : ""));
671 if (c->sh_batch_file) {
672 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
673 c->sh_batch_file));
675 /* just try and remove, don't care if this fails */
676 remove (c->sh_batch_file);
678 /* all done with memory */
679 free (c->sh_batch_file);
680 c->sh_batch_file = NULL;
683 /* If this child had the good stdin, say it is now free. */
684 if (c->good_stdin)
685 good_stdin_used = 0;
687 if (child_failed && !c->noerror && !ignore_errors_flag)
689 /* The commands failed. Write an error message,
690 delete non-precious targets, and abort. */
691 static int delete_on_error = -1;
692 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
693 c->file->update_status = 2;
694 if (delete_on_error == -1)
696 struct file *f = lookup_file (".DELETE_ON_ERROR");
697 delete_on_error = f != 0 && f->is_target;
699 if (exit_sig != 0 || delete_on_error)
700 delete_child_targets (c);
702 else
704 if (child_failed)
706 /* The commands failed, but we don't care. */
707 child_error (c->file->name,
708 exit_code, exit_sig, coredump, 1);
709 child_failed = 0;
712 /* If there are more commands to run, try to start them. */
713 if (job_next_command (c))
715 if (handling_fatal_signal)
717 /* Never start new commands while we are dying.
718 Since there are more commands that wanted to be run,
719 the target was not completely remade. So we treat
720 this as if a command had failed. */
721 c->file->update_status = 2;
723 else
725 /* Check again whether to start remotely.
726 Whether or not we want to changes over time.
727 Also, start_remote_job may need state set up
728 by start_remote_job_p. */
729 c->remote = start_remote_job_p (0);
730 start_job_command (c);
731 /* Fatal signals are left blocked in case we were
732 about to put that child on the chain. But it is
733 already there, so it is safe for a fatal signal to
734 arrive now; it will clean up this child's targets. */
735 unblock_sigs ();
736 if (c->file->command_state == cs_running)
737 /* We successfully started the new command.
738 Loop to reap more children. */
739 continue;
742 if (c->file->update_status != 0)
743 /* We failed to start the commands. */
744 delete_child_targets (c);
746 else
747 /* There are no more commands. We got through them all
748 without an unignored error. Now the target has been
749 successfully updated. */
750 c->file->update_status = 0;
753 /* When we get here, all the commands for C->file are finished
754 (or aborted) and C->file->update_status contains 0 or 2. But
755 C->file->command_state is still cs_running if all the commands
756 ran; notice_finish_file looks for cs_running to tell it that
757 it's interesting to check the file's modtime again now. */
759 if (! handling_fatal_signal)
760 /* Notice if the target of the commands has been changed.
761 This also propagates its values for command_state and
762 update_status to its also_make files. */
763 notice_finished_file (c->file);
765 DB (DB_JOBS, (_("Removing child 0x%08lx PID %ld%s from chain.\n"),
766 (unsigned long int) c, (long) c->pid,
767 c->remote ? _(" (remote)") : ""));
769 /* Block fatal signals while frobnicating the list, so that
770 children and job_slots_used are always consistent. Otherwise
771 a fatal signal arriving after the child is off the chain and
772 before job_slots_used is decremented would believe a child was
773 live and call reap_children again. */
774 block_sigs ();
776 /* There is now another slot open. */
777 if (job_slots_used > 0)
778 --job_slots_used;
780 /* Remove the child from the chain and free it. */
781 if (lastc == 0)
782 children = c->next;
783 else
784 lastc->next = c->next;
786 free_child (c);
788 unblock_sigs ();
790 /* If the job failed, and the -k flag was not given, die,
791 unless we are already in the process of dying. */
792 if (!err && child_failed && !keep_going_flag &&
793 /* fatal_error_signal will die with the right signal. */
794 !handling_fatal_signal)
795 die (2);
797 /* Only block for one child. */
798 block = 0;
801 return;
804 /* Free the storage allocated for CHILD. */
806 static void
807 free_child (struct child *child)
809 /* If this child is the only one it was our "free" job, so don't put a
810 token back for it. This child has already been removed from the list,
811 so if there any left this wasn't the last one. */
813 if (job_fds[1] >= 0 && children)
815 char token = '+';
816 int r;
818 /* Write a job token back to the pipe. */
820 EINTRLOOP (r, write (job_fds[1], &token, 1));
821 if (r != 1)
822 pfatal_with_name (_("write jobserver"));
824 DB (DB_JOBS, (_("Released token for child 0x%08lx (%s).\n"),
825 (unsigned long int) child, child->file->name));
828 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
829 return;
831 if (child->command_lines != 0)
833 register unsigned int i;
834 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
835 free (child->command_lines[i]);
836 free ((char *) child->command_lines);
839 if (child->environment != 0)
841 register char **ep = child->environment;
842 while (*ep != 0)
843 free (*ep++);
844 free ((char *) child->environment);
847 free ((char *) child);
850 #ifdef POSIX
851 extern sigset_t fatal_signal_set;
852 #endif
854 void
855 block_sigs (void)
857 #ifdef POSIX
858 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
859 #else
860 # ifdef HAVE_SIGSETMASK
861 (void) sigblock (fatal_signal_mask);
862 # endif
863 #endif
866 #ifdef POSIX
867 void
868 unblock_sigs (void)
870 sigset_t empty;
871 sigemptyset (&empty);
872 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
874 #endif
876 #ifdef MAKE_JOBSERVER
877 /* Set the child handler action flags to FLAGS. */
878 static void
879 set_child_handler_action_flags (int flags)
881 struct sigaction sa;
882 bzero ((char *) &sa, sizeof sa);
883 sa.sa_handler = child_handler;
884 sa.sa_flags = flags;
885 #if defined SIGCHLD
886 sigaction (SIGCHLD, &sa, NULL);
887 #endif
888 #if defined SIGCLD && SIGCLD != SIGCHLD
889 sigaction (SIGCLD, &sa, NULL);
890 #endif
892 #endif
895 /* Start a job to run the commands specified in CHILD.
896 CHILD is updated to reflect the commands and ID of the child process.
898 NOTE: On return fatal signals are blocked! The caller is responsible
899 for calling `unblock_sigs', once the new child is safely on the chain so
900 it can be cleaned up in the event of a fatal signal. */
902 static void
903 start_job_command (struct child *child)
905 #ifndef _AMIGA
906 static int bad_stdin = -1;
907 #endif
908 register char *p;
909 int flags;
910 #ifdef VMS
911 char *argv;
912 #else
913 char **argv;
914 #endif
916 /* If we have a completely empty commandset, stop now. */
917 if (!child->command_ptr)
918 goto next_command;
920 /* Combine the flags parsed for the line itself with
921 the flags specified globally for this target. */
922 flags = (child->file->command_flags
923 | child->file->cmds->lines_flags[child->command_line - 1]);
925 p = child->command_ptr;
926 child->noerror = flags & COMMANDS_NOERROR;
928 while (*p != '\0')
930 if (*p == '@')
931 flags |= COMMANDS_SILENT;
932 else if (*p == '+')
933 flags |= COMMANDS_RECURSE;
934 else if (*p == '-')
935 child->noerror = 1;
936 else if (!isblank ((unsigned char)*p))
937 break;
938 ++p;
941 /* Update the file's command flags with any new ones we found. We only
942 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
943 now marking more commands recursive than should be in the case of
944 multiline define/endef scripts where only one line is marked "+". In
945 order to really fix this, we'll have to keep a lines_flags for every
946 actual line, after expansion. */
947 child->file->cmds->lines_flags[child->command_line - 1]
948 |= flags & COMMANDS_RECURSE;
950 /* Figure out an argument list from this command line. */
953 char *end = 0;
954 #ifdef VMS
955 argv = p;
956 #else
957 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
958 #endif
959 if (end == NULL)
960 child->command_ptr = NULL;
961 else
963 *end++ = '\0';
964 child->command_ptr = end;
968 /* If -q was given, say that updating `failed' if there was any text on the
969 command line, or `succeeded' otherwise. The exit status of 1 tells the
970 user that -q is saying `something to do'; the exit status for a random
971 error is 2. */
972 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
974 #ifndef VMS
975 free (argv[0]);
976 free ((char *) argv);
977 #endif
978 child->file->update_status = 1;
979 notice_finished_file (child->file);
980 return;
983 if (touch_flag && !(flags & COMMANDS_RECURSE))
985 /* Go on to the next command. It might be the recursive one.
986 We construct ARGV only to find the end of the command line. */
987 #ifndef VMS
988 if (argv)
990 free (argv[0]);
991 free ((char *) argv);
993 #endif
994 argv = 0;
997 if (argv == 0)
999 next_command:
1000 #ifdef __MSDOS__
1001 execute_by_shell = 0; /* in case construct_command_argv sets it */
1002 #endif
1003 /* This line has no commands. Go to the next. */
1004 if (job_next_command (child))
1005 start_job_command (child);
1006 else
1008 /* No more commands. Make sure we're "running"; we might not be if
1009 (e.g.) all commands were skipped due to -n. */
1010 set_command_state (child->file, cs_running);
1011 child->file->update_status = 0;
1012 notice_finished_file (child->file);
1014 return;
1017 /* Print out the command. If silent, we call `message' with null so it
1018 can log the working directory before the command's own error messages
1019 appear. */
1021 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
1022 ? "%s" : (char *) 0, p);
1024 /* Tell update_goal_chain that a command has been started on behalf of
1025 this target. It is important that this happens here and not in
1026 reap_children (where we used to do it), because reap_children might be
1027 reaping children from a different target. We want this increment to
1028 guaranteedly indicate that a command was started for the dependency
1029 chain (i.e., update_file recursion chain) we are processing. */
1031 ++commands_started;
1033 /* Optimize an empty command. People use this for timestamp rules,
1034 so avoid forking a useless shell. Do this after we increment
1035 commands_started so make still treats this special case as if it
1036 performed some action (makes a difference as to what messages are
1037 printed, etc. */
1039 #if !defined(VMS) && !defined(_AMIGA)
1040 if (
1041 #if defined __MSDOS__ || defined (__EMX__)
1042 unixy_shell /* the test is complicated and we already did it */
1043 #else
1044 (argv[0] && !strcmp (argv[0], "/bin/sh"))
1045 #endif
1046 && (argv[1]
1047 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
1048 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1049 && argv[3] == NULL)
1051 free (argv[0]);
1052 free ((char *) argv);
1053 goto next_command;
1055 #endif /* !VMS && !_AMIGA */
1057 /* If -n was given, recurse to get the next line in the sequence. */
1059 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1061 #ifndef VMS
1062 free (argv[0]);
1063 free ((char *) argv);
1064 #endif
1065 goto next_command;
1068 /* Flush the output streams so they won't have things written twice. */
1070 fflush (stdout);
1071 fflush (stderr);
1073 #ifndef VMS
1074 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1076 /* Set up a bad standard input that reads from a broken pipe. */
1078 if (bad_stdin == -1)
1080 /* Make a file descriptor that is the read end of a broken pipe.
1081 This will be used for some children's standard inputs. */
1082 int pd[2];
1083 if (pipe (pd) == 0)
1085 /* Close the write side. */
1086 (void) close (pd[1]);
1087 /* Save the read side. */
1088 bad_stdin = pd[0];
1090 /* Set the descriptor to close on exec, so it does not litter any
1091 child's descriptor table. When it is dup2'd onto descriptor 0,
1092 that descriptor will not close on exec. */
1093 CLOSE_ON_EXEC (bad_stdin);
1097 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1099 /* Decide whether to give this child the `good' standard input
1100 (one that points to the terminal or whatever), or the `bad' one
1101 that points to the read side of a broken pipe. */
1103 child->good_stdin = !good_stdin_used;
1104 if (child->good_stdin)
1105 good_stdin_used = 1;
1107 #endif /* !VMS */
1109 child->deleted = 0;
1111 #ifndef _AMIGA
1112 /* Set up the environment for the child. */
1113 if (child->environment == 0)
1114 child->environment = target_environment (child->file);
1115 #endif
1117 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1119 #ifndef VMS
1120 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1121 if (child->remote)
1123 int is_remote, id, used_stdin;
1124 if (start_remote_job (argv, child->environment,
1125 child->good_stdin ? 0 : bad_stdin,
1126 &is_remote, &id, &used_stdin))
1127 /* Don't give up; remote execution may fail for various reasons. If
1128 so, simply run the job locally. */
1129 goto run_local;
1130 else
1132 if (child->good_stdin && !used_stdin)
1134 child->good_stdin = 0;
1135 good_stdin_used = 0;
1137 child->remote = is_remote;
1138 child->pid = id;
1141 else
1142 #endif /* !VMS */
1144 /* Fork the child process. */
1146 char **parent_environ;
1148 run_local:
1149 block_sigs ();
1151 child->remote = 0;
1153 #ifdef VMS
1155 if (!child_execute_job (argv, child)) {
1156 /* Fork failed! */
1157 perror_with_name ("vfork", "");
1158 goto error;
1161 #else
1163 parent_environ = environ;
1165 # ifdef __EMX__
1166 /* If we aren't running a recursive command and we have a jobserver
1167 pipe, close it before exec'ing. */
1168 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1170 CLOSE_ON_EXEC (job_fds[0]);
1171 CLOSE_ON_EXEC (job_fds[1]);
1173 if (job_rfd >= 0)
1174 CLOSE_ON_EXEC (job_rfd);
1176 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1177 child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1178 argv, child->environment);
1179 if (child->pid < 0)
1181 /* spawn failed! */
1182 unblock_sigs ();
1183 perror_with_name ("spawn", "");
1184 goto error;
1187 /* undo CLOSE_ON_EXEC() after the child process has been started */
1188 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1190 fcntl (job_fds[0], F_SETFD, 0);
1191 fcntl (job_fds[1], F_SETFD, 0);
1193 if (job_rfd >= 0)
1194 fcntl (job_rfd, F_SETFD, 0);
1196 #else /* !__EMX__ */
1198 child->pid = vfork ();
1199 environ = parent_environ; /* Restore value child may have clobbered. */
1200 if (child->pid == 0)
1202 /* We are the child side. */
1203 unblock_sigs ();
1205 /* If we aren't running a recursive command and we have a jobserver
1206 pipe, close it before exec'ing. */
1207 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1209 close (job_fds[0]);
1210 close (job_fds[1]);
1212 if (job_rfd >= 0)
1213 close (job_rfd);
1215 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1216 argv, child->environment);
1218 else if (child->pid < 0)
1220 /* Fork failed! */
1221 unblock_sigs ();
1222 perror_with_name ("vfork", "");
1223 goto error;
1225 # endif /* !__EMX__ */
1226 #endif /* !VMS */
1229 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1230 #ifdef __MSDOS__
1232 int proc_return;
1234 block_sigs ();
1235 dos_status = 0;
1237 /* We call `system' to do the job of the SHELL, since stock DOS
1238 shell is too dumb. Our `system' knows how to handle long
1239 command lines even if pipes/redirection is needed; it will only
1240 call COMMAND.COM when its internal commands are used. */
1241 if (execute_by_shell)
1243 char *cmdline = argv[0];
1244 /* We don't have a way to pass environment to `system',
1245 so we need to save and restore ours, sigh... */
1246 char **parent_environ = environ;
1248 environ = child->environment;
1250 /* If we have a *real* shell, tell `system' to call
1251 it to do everything for us. */
1252 if (unixy_shell)
1254 /* A *real* shell on MSDOS may not support long
1255 command lines the DJGPP way, so we must use `system'. */
1256 cmdline = argv[2]; /* get past "shell -c" */
1259 dos_command_running = 1;
1260 proc_return = system (cmdline);
1261 environ = parent_environ;
1262 execute_by_shell = 0; /* for the next time */
1264 else
1266 dos_command_running = 1;
1267 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1270 /* Need to unblock signals before turning off
1271 dos_command_running, so that child's signals
1272 will be treated as such (see fatal_error_signal). */
1273 unblock_sigs ();
1274 dos_command_running = 0;
1276 /* If the child got a signal, dos_status has its
1277 high 8 bits set, so be careful not to alter them. */
1278 if (proc_return == -1)
1279 dos_status |= 0xff;
1280 else
1281 dos_status |= (proc_return & 0xff);
1282 ++dead_children;
1283 child->pid = dos_pid++;
1285 #endif /* __MSDOS__ */
1286 #ifdef _AMIGA
1287 amiga_status = MyExecute (argv);
1289 ++dead_children;
1290 child->pid = amiga_pid++;
1291 if (amiga_batch_file)
1293 amiga_batch_file = 0;
1294 DeleteFile (amiga_bname); /* Ignore errors. */
1296 #endif /* Amiga */
1297 #ifdef WINDOWS32
1299 HANDLE hPID;
1300 char* arg0;
1302 /* make UNC paths safe for CreateProcess -- backslash format */
1303 arg0 = argv[0];
1304 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1305 for ( ; arg0 && *arg0; arg0++)
1306 if (*arg0 == '/')
1307 *arg0 = '\\';
1309 /* make sure CreateProcess() has Path it needs */
1310 sync_Path_environment();
1312 hPID = process_easy(argv, child->environment);
1314 if (hPID != INVALID_HANDLE_VALUE)
1315 child->pid = (int) hPID;
1316 else {
1317 int i;
1318 unblock_sigs();
1319 fprintf(stderr,
1320 _("process_easy() failed failed to launch process (e=%d)\n"),
1321 process_last_err(hPID));
1322 for (i = 0; argv[i]; i++)
1323 fprintf(stderr, "%s ", argv[i]);
1324 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1327 #endif /* WINDOWS32 */
1328 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1330 /* Bump the number of jobs started in this second. */
1331 ++job_counter;
1333 /* We are the parent side. Set the state to
1334 say the commands are running and return. */
1336 set_command_state (child->file, cs_running);
1338 /* Free the storage used by the child's argument list. */
1339 #ifndef VMS
1340 free (argv[0]);
1341 free ((char *) argv);
1342 #endif
1344 return;
1346 error:
1347 child->file->update_status = 2;
1348 notice_finished_file (child->file);
1349 return;
1352 /* Try to start a child running.
1353 Returns nonzero if the child was started (and maybe finished), or zero if
1354 the load was too high and the child was put on the `waiting_jobs' chain. */
1356 static int
1357 start_waiting_job (struct child *c)
1359 struct file *f = c->file;
1361 /* If we can start a job remotely, we always want to, and don't care about
1362 the local load average. We record that the job should be started
1363 remotely in C->remote for start_job_command to test. */
1365 c->remote = start_remote_job_p (1);
1367 /* If we are running at least one job already and the load average
1368 is too high, make this one wait. */
1369 if (!c->remote && job_slots_used > 0 && load_too_high ())
1371 /* Put this child on the chain of children waiting for the load average
1372 to go down. */
1373 set_command_state (f, cs_running);
1374 c->next = waiting_jobs;
1375 waiting_jobs = c;
1376 return 0;
1379 /* Start the first command; reap_children will run later command lines. */
1380 start_job_command (c);
1382 switch (f->command_state)
1384 case cs_running:
1385 c->next = children;
1386 DB (DB_JOBS, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1387 (unsigned long int) c, c->file->name,
1388 (long) c->pid, c->remote ? _(" (remote)") : ""));
1389 children = c;
1390 /* One more job slot is in use. */
1391 ++job_slots_used;
1392 unblock_sigs ();
1393 break;
1395 case cs_not_started:
1396 /* All the command lines turned out to be empty. */
1397 f->update_status = 0;
1398 /* FALLTHROUGH */
1400 case cs_finished:
1401 notice_finished_file (f);
1402 free_child (c);
1403 break;
1405 default:
1406 assert (f->command_state == cs_finished);
1407 break;
1410 return 1;
1413 /* Create a `struct child' for FILE and start its commands running. */
1415 void
1416 new_job (struct file *file)
1418 register struct commands *cmds = file->cmds;
1419 register struct child *c;
1420 char **lines;
1421 register unsigned int i;
1423 /* Let any previously decided-upon jobs that are waiting
1424 for the load to go down start before this new one. */
1425 start_waiting_jobs ();
1427 /* Reap any children that might have finished recently. */
1428 reap_children (0, 0);
1430 /* Chop the commands up into lines if they aren't already. */
1431 chop_commands (cmds);
1433 /* Expand the command lines and store the results in LINES. */
1434 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1435 for (i = 0; i < cmds->ncommand_lines; ++i)
1437 /* Collapse backslash-newline combinations that are inside variable
1438 or function references. These are left alone by the parser so
1439 that they will appear in the echoing of commands (where they look
1440 nice); and collapsed by construct_command_argv when it tokenizes.
1441 But letting them survive inside function invocations loses because
1442 we don't want the functions to see them as part of the text. */
1444 char *in, *out, *ref;
1446 /* IN points to where in the line we are scanning.
1447 OUT points to where in the line we are writing.
1448 When we collapse a backslash-newline combination,
1449 IN gets ahead of OUT. */
1451 in = out = cmds->command_lines[i];
1452 while ((ref = strchr (in, '$')) != 0)
1454 ++ref; /* Move past the $. */
1456 if (out != in)
1457 /* Copy the text between the end of the last chunk
1458 we processed (where IN points) and the new chunk
1459 we are about to process (where REF points). */
1460 bcopy (in, out, ref - in);
1462 /* Move both pointers past the boring stuff. */
1463 out += ref - in;
1464 in = ref;
1466 if (*ref == '(' || *ref == '{')
1468 char openparen = *ref;
1469 char closeparen = openparen == '(' ? ')' : '}';
1470 int count;
1471 char *p;
1473 *out++ = *in++; /* Copy OPENPAREN. */
1474 /* IN now points past the opening paren or brace.
1475 Count parens or braces until it is matched. */
1476 count = 0;
1477 while (*in != '\0')
1479 if (*in == closeparen && --count < 0)
1480 break;
1481 else if (*in == '\\' && in[1] == '\n')
1483 /* We have found a backslash-newline inside a
1484 variable or function reference. Eat it and
1485 any following whitespace. */
1487 int quoted = 0;
1488 for (p = in - 1; p > ref && *p == '\\'; --p)
1489 quoted = !quoted;
1491 if (quoted)
1492 /* There were two or more backslashes, so this is
1493 not really a continuation line. We don't collapse
1494 the quoting backslashes here as is done in
1495 collapse_continuations, because the line will
1496 be collapsed again after expansion. */
1497 *out++ = *in++;
1498 else
1500 /* Skip the backslash, newline and
1501 any following whitespace. */
1502 in = next_token (in + 2);
1504 /* Discard any preceding whitespace that has
1505 already been written to the output. */
1506 while (out > ref
1507 && isblank ((unsigned char)out[-1]))
1508 --out;
1510 /* Replace it all with a single space. */
1511 *out++ = ' ';
1514 else
1516 if (*in == openparen)
1517 ++count;
1519 *out++ = *in++;
1525 /* There are no more references in this line to worry about.
1526 Copy the remaining uninteresting text to the output. */
1527 if (out != in)
1528 strcpy (out, in);
1530 /* Finally, expand the line. */
1531 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1532 file);
1535 /* Start the command sequence, record it in a new
1536 `struct child', and add that to the chain. */
1538 c = (struct child *) xmalloc (sizeof (struct child));
1539 bzero ((char *)c, sizeof (struct child));
1540 c->file = file;
1541 c->command_lines = lines;
1542 c->sh_batch_file = NULL;
1544 /* Fetch the first command line to be run. */
1545 job_next_command (c);
1547 /* Wait for a job slot to be freed up. If we allow an infinite number
1548 don't bother; also job_slots will == 0 if we're using the jobserver. */
1550 if (job_slots != 0)
1551 while (job_slots_used == job_slots)
1552 reap_children (1, 0);
1554 #ifdef MAKE_JOBSERVER
1555 /* If we are controlling multiple jobs make sure we have a token before
1556 starting the child. */
1558 /* This can be inefficient. There's a decent chance that this job won't
1559 actually have to run any subprocesses: the command script may be empty
1560 or otherwise optimized away. It would be nice if we could defer
1561 obtaining a token until just before we need it, in start_job_command.
1562 To do that we'd need to keep track of whether we'd already obtained a
1563 token (since start_job_command is called for each line of the job, not
1564 just once). Also more thought needs to go into the entire algorithm;
1565 this is where the old parallel job code waits, so... */
1567 else if (job_fds[0] >= 0)
1568 while (1)
1570 char token;
1571 int got_token;
1572 int saved_errno;
1574 DB (DB_JOBS, ("Need a job token; we %shave children\n",
1575 children ? "" : "don't "));
1577 /* If we don't already have a job started, use our "free" token. */
1578 if (!children)
1579 break;
1581 /* Read a token. As long as there's no token available we'll block.
1582 We enable interruptible system calls before the read(2) so that if
1583 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1584 we can process the death(s) and return tokens to the free pool.
1586 Once we return from the read, we immediately reinstate restartable
1587 system calls. This allows us to not worry about checking for
1588 EINTR on all the other system calls in the program.
1590 There is one other twist: there is a span between the time
1591 reap_children() does its last check for dead children and the time
1592 the read(2) call is entered, below, where if a child dies we won't
1593 notice. This is extremely serious as it could cause us to
1594 deadlock, given the right set of events.
1596 To avoid this, we do the following: before we reap_children(), we
1597 dup(2) the read FD on the jobserver pipe. The read(2) call below
1598 uses that new FD. In the signal handler, we close that FD. That
1599 way, if a child dies during the section mentioned above, the
1600 read(2) will be invoked with an invalid FD and will return
1601 immediately with EBADF. */
1603 /* Make sure we have a dup'd FD. */
1604 if (job_rfd < 0)
1606 DB (DB_JOBS, ("Duplicate the job FD\n"));
1607 job_rfd = dup (job_fds[0]);
1610 /* Reap anything that's currently waiting. */
1611 reap_children (0, 0);
1613 /* If our "free" token has become available, use it. */
1614 if (!children)
1615 break;
1617 /* Set interruptible system calls, and read() for a job token. */
1618 set_child_handler_action_flags (0);
1619 got_token = read (job_rfd, &token, 1);
1620 saved_errno = errno;
1621 #ifdef __EMX__
1622 /* The child handler must be turned off here. */
1623 signal (SIGCHLD, SIG_DFL);
1624 #endif
1625 set_child_handler_action_flags (SA_RESTART);
1627 /* If we got one, we're done here. */
1628 if (got_token == 1)
1630 DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1631 (unsigned long int) c, c->file->name));
1632 break;
1635 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1636 go back and reap_children(), and try again. */
1637 errno = saved_errno;
1638 if (errno != EINTR && errno != EBADF)
1639 pfatal_with_name (_("read jobs pipe"));
1640 if (errno == EBADF)
1641 DB (DB_JOBS, ("Read returned EBADF.\n"));
1643 #endif
1645 /* The job is now primed. Start it running.
1646 (This will notice if there are in fact no commands.) */
1647 (void) start_waiting_job (c);
1649 if (job_slots == 1 || not_parallel)
1650 /* Since there is only one job slot, make things run linearly.
1651 Wait for the child to die, setting the state to `cs_finished'. */
1652 while (file->command_state == cs_running)
1653 reap_children (1, 0);
1655 return;
1658 /* Move CHILD's pointers to the next command for it to execute.
1659 Returns nonzero if there is another command. */
1661 static int
1662 job_next_command (struct child *child)
1664 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1666 /* There are no more lines in the expansion of this line. */
1667 if (child->command_line == child->file->cmds->ncommand_lines)
1669 /* There are no more lines to be expanded. */
1670 child->command_ptr = 0;
1671 return 0;
1673 else
1674 /* Get the next line to run. */
1675 child->command_ptr = child->command_lines[child->command_line++];
1677 return 1;
1680 /* Determine if the load average on the system is too high to start a new job.
1681 The real system load average is only recomputed once a second. However, a
1682 very parallel make can easily start tens or even hundreds of jobs in a
1683 second, which brings the system to its knees for a while until that first
1684 batch of jobs clears out.
1686 To avoid this we use a weighted algorithm to try to account for jobs which
1687 have been started since the last second, and guess what the load average
1688 would be now if it were computed.
1690 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1691 who writes:
1693 ! calculate something load-oid and add to the observed sys.load,
1694 ! so that latter can catch up:
1695 ! - every job started increases jobctr;
1696 ! - every dying job decreases a positive jobctr;
1697 ! - the jobctr value gets zeroed every change of seconds,
1698 ! after its value*weight_b is stored into the 'backlog' value last_sec
1699 ! - weight_a times the sum of jobctr and last_sec gets
1700 ! added to the observed sys.load.
1702 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1703 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1704 ! sub-shelled commands (rm, echo, sed...) for tests.
1705 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1706 ! resulted in significant excession of the load limit, raising it
1707 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1708 ! reach the limit in most test cases.
1710 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1711 ! exceeding the limit for longer-running stuff (compile jobs in
1712 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1713 ! small jobs' effects.
1717 #define LOAD_WEIGHT_A 0.25
1718 #define LOAD_WEIGHT_B 0.25
1720 static int
1721 load_too_high (void)
1723 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1724 return 1;
1725 #else
1726 static double last_sec;
1727 static time_t last_now;
1728 double load, guess;
1729 time_t now;
1731 if (max_load_average < 0)
1732 return 0;
1734 /* Find the real system load average. */
1735 make_access ();
1736 if (getloadavg (&load, 1) != 1)
1738 static int lossage = -1;
1739 /* Complain only once for the same error. */
1740 if (lossage == -1 || errno != lossage)
1742 if (errno == 0)
1743 /* An errno value of zero means getloadavg is just unsupported. */
1744 error (NILF,
1745 _("cannot enforce load limits on this operating system"));
1746 else
1747 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1749 lossage = errno;
1750 load = 0;
1752 user_access ();
1754 /* If we're in a new second zero the counter and correct the backlog
1755 value. Only keep the backlog for one extra second; after that it's 0. */
1756 now = time (NULL);
1757 if (last_now < now)
1759 if (last_now == now - 1)
1760 last_sec = LOAD_WEIGHT_B * job_counter;
1761 else
1762 last_sec = 0.0;
1764 job_counter = 0;
1765 last_now = now;
1768 /* Try to guess what the load would be right now. */
1769 guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
1771 DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1772 guess, load, max_load_average));
1774 return guess >= max_load_average;
1775 #endif
1778 /* Start jobs that are waiting for the load to be lower. */
1780 void
1781 start_waiting_jobs (void)
1783 struct child *job;
1785 if (waiting_jobs == 0)
1786 return;
1790 /* Check for recently deceased descendants. */
1791 reap_children (0, 0);
1793 /* Take a job off the waiting list. */
1794 job = waiting_jobs;
1795 waiting_jobs = job->next;
1797 /* Try to start that job. We break out of the loop as soon
1798 as start_waiting_job puts one back on the waiting list. */
1800 while (start_waiting_job (job) && waiting_jobs != 0);
1802 return;
1805 #ifndef WINDOWS32
1806 #ifdef VMS
1807 #include <descrip.h>
1808 #include <clidef.h>
1810 /* This is called as an AST when a child process dies (it won't get
1811 interrupted by anything except a higher level AST).
1813 int vmsHandleChildTerm(struct child *child)
1815 int status;
1816 register struct child *lastc, *c;
1817 int child_failed;
1819 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1821 lib$free_ef(&child->efn);
1823 (void) sigblock (fatal_signal_mask);
1825 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1827 /* Search for a child matching the deceased one. */
1828 lastc = 0;
1829 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1830 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1831 #else
1832 c = child;
1833 #endif
1835 if (child_failed && !c->noerror && !ignore_errors_flag)
1837 /* The commands failed. Write an error message,
1838 delete non-precious targets, and abort. */
1839 child_error (c->file->name, c->cstatus, 0, 0, 0);
1840 c->file->update_status = 1;
1841 delete_child_targets (c);
1843 else
1845 if (child_failed)
1847 /* The commands failed, but we don't care. */
1848 child_error (c->file->name, c->cstatus, 0, 0, 1);
1849 child_failed = 0;
1852 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1853 /* If there are more commands to run, try to start them. */
1854 start_job (c);
1856 switch (c->file->command_state)
1858 case cs_running:
1859 /* Successfully started. */
1860 break;
1862 case cs_finished:
1863 if (c->file->update_status != 0) {
1864 /* We failed to start the commands. */
1865 delete_child_targets (c);
1867 break;
1869 default:
1870 error (NILF, _("internal error: `%s' command_state"),
1871 c->file->name);
1872 abort ();
1873 break;
1875 #endif /* RECURSIVEJOBS */
1878 /* Set the state flag to say the commands have finished. */
1879 c->file->command_state = cs_finished;
1880 notice_finished_file (c->file);
1882 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1883 /* Remove the child from the chain and free it. */
1884 if (lastc == 0)
1885 children = c->next;
1886 else
1887 lastc->next = c->next;
1888 free_child (c);
1889 #endif /* RECURSIVEJOBS */
1891 /* There is now another slot open. */
1892 if (job_slots_used > 0)
1893 --job_slots_used;
1895 /* If the job failed, and the -k flag was not given, die. */
1896 if (child_failed && !keep_going_flag)
1897 die (EXIT_FAILURE);
1899 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1901 return 1;
1904 /* VMS:
1905 Spawn a process executing the command in ARGV and return its pid. */
1907 #define MAXCMDLEN 200
1909 /* local helpers to make ctrl+c and ctrl+y working, see below */
1910 #include <iodef.h>
1911 #include <libclidef.h>
1912 #include <ssdef.h>
1914 static int ctrlMask= LIB$M_CLI_CTRLY;
1915 static int oldCtrlMask;
1916 static int setupYAstTried= 0;
1917 static int pidToAbort= 0;
1918 static int chan= 0;
1920 static void reEnableAst(void) {
1921 lib$enable_ctrl (&oldCtrlMask,0);
1924 static astHandler (void) {
1925 if (pidToAbort) {
1926 sys$forcex (&pidToAbort, 0, SS$_ABORT);
1927 pidToAbort= 0;
1929 kill (getpid(),SIGQUIT);
1932 static void tryToSetupYAst(void) {
1933 $DESCRIPTOR(inputDsc,"SYS$COMMAND");
1934 int status;
1935 struct {
1936 short int status, count;
1937 int dvi;
1938 } iosb;
1940 setupYAstTried++;
1942 if (!chan) {
1943 status= sys$assign(&inputDsc,&chan,0,0);
1944 if (!(status&SS$_NORMAL)) {
1945 lib$signal(status);
1946 return;
1949 status= sys$qiow (0, chan, IO$_SETMODE|IO$M_CTRLYAST,&iosb,0,0,
1950 astHandler,0,0,0,0,0);
1951 if (status==SS$_ILLIOFUNC) {
1952 sys$dassgn(chan);
1953 #ifdef CTRLY_ENABLED_ANYWAY
1954 fprintf (stderr,
1955 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
1956 #else
1957 return;
1958 #endif
1960 if (status==SS$_NORMAL)
1961 status= iosb.status;
1962 if (!(status&SS$_NORMAL)) {
1963 lib$signal(status);
1964 return;
1967 /* called from AST handler ? */
1968 if (setupYAstTried>1)
1969 return;
1970 if (atexit(reEnableAst))
1971 fprintf (stderr,
1972 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
1973 status= lib$disable_ctrl (&ctrlMask, &oldCtrlMask);
1974 if (!(status&SS$_NORMAL)) {
1975 lib$signal(status);
1976 return;
1980 child_execute_job (char *argv, struct child *child)
1982 int i;
1983 static struct dsc$descriptor_s cmddsc;
1984 static struct dsc$descriptor_s pnamedsc;
1985 static struct dsc$descriptor_s ifiledsc;
1986 static struct dsc$descriptor_s ofiledsc;
1987 static struct dsc$descriptor_s efiledsc;
1988 int have_redirection = 0;
1989 int have_newline = 0;
1991 int spflags = CLI$M_NOWAIT;
1992 int status;
1993 char *cmd = alloca (strlen (argv) + 512), *p, *q;
1994 char ifile[256], ofile[256], efile[256];
1995 char *comname = 0;
1996 char procname[100];
1998 /* Parse IO redirection. */
2000 ifile[0] = 0;
2001 ofile[0] = 0;
2002 efile[0] = 0;
2004 DB (DB_JOBS, ("child_execute_job (%s)\n", argv));
2006 while (isspace ((unsigned char)*argv))
2007 argv++;
2009 if (*argv == 0)
2010 return 0;
2012 sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
2013 pnamedsc.dsc$w_length = strlen(procname);
2014 pnamedsc.dsc$a_pointer = procname;
2015 pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
2016 pnamedsc.dsc$b_class = DSC$K_CLASS_S;
2018 /* Handle comments and redirection. */
2019 for (p = argv, q = cmd; *p; p++, q++)
2021 switch (*p)
2023 case '#':
2024 *p-- = 0;
2025 *q-- = 0;
2026 break;
2027 case '\\':
2028 p++;
2029 if (*p == '\n')
2030 p++;
2031 if (isspace ((unsigned char)*p))
2033 do { p++; } while (isspace ((unsigned char)*p));
2034 p--;
2036 *q = *p;
2037 break;
2038 case '<':
2039 p = vms_redirect (&ifiledsc, ifile, p);
2040 *q = ' ';
2041 have_redirection = 1;
2042 break;
2043 case '>':
2044 have_redirection = 1;
2045 if (*(p-1) == '2')
2047 q--;
2048 if (strncmp (p, ">&1", 3) == 0)
2050 p += 3;
2051 strcpy (efile, "sys$output");
2052 efiledsc.dsc$w_length = strlen(efile);
2053 efiledsc.dsc$a_pointer = efile;
2054 efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
2055 efiledsc.dsc$b_class = DSC$K_CLASS_S;
2057 else
2059 p = vms_redirect (&efiledsc, efile, p);
2062 else
2064 p = vms_redirect (&ofiledsc, ofile, p);
2066 *q = ' ';
2067 break;
2068 case '\n':
2069 have_newline = 1;
2070 default:
2071 *q = *p;
2072 break;
2075 *q = *p;
2077 if (strncmp (cmd, "builtin_", 8) == 0)
2079 child->pid = 270163;
2080 child->efn = 0;
2081 child->cstatus = 1;
2083 DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));
2085 p = cmd + 8;
2087 if ((*(p) == 'c')
2088 && (*(p+1) == 'd')
2089 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
2091 p += 3;
2092 while ((*p == ' ') || (*p == '\t'))
2093 p++;
2094 DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
2095 if (chdir (p))
2096 return 0;
2097 else
2098 return 1;
2100 else if ((*(p) == 'r')
2101 && (*(p+1) == 'm')
2102 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
2104 int in_arg;
2106 /* rm */
2107 p += 3;
2108 while ((*p == ' ') || (*p == '\t'))
2109 p++;
2110 in_arg = 1;
2112 DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
2113 while (*p)
2115 switch (*p)
2117 case ' ':
2118 case '\t':
2119 if (in_arg)
2121 *p++ = ';';
2122 in_arg = 0;
2124 break;
2125 default:
2126 break;
2128 p++;
2131 else
2133 printf(_("Unknown builtin command '%s'\n"), cmd);
2134 fflush(stdout);
2135 return 0;
2139 /* Create a *.com file if either the command is too long for
2140 lib$spawn, or the command contains a newline, or if redirection
2141 is desired. Forcing commands with newlines into DCLs allows to
2142 store search lists on user mode logicals. */
2144 if (strlen (cmd) > MAXCMDLEN
2145 || (have_redirection != 0)
2146 || (have_newline != 0))
2148 FILE *outfile;
2149 char c;
2150 char *sep;
2151 int alevel = 0; /* apostrophe level */
2153 if (strlen (cmd) == 0)
2155 printf (_("Error, empty command\n"));
2156 fflush (stdout);
2157 return 0;
2160 outfile = open_tmpfile (&comname, "sys$scratch:CMDXXXXXX.COM");
2161 if (outfile == 0)
2162 pfatal_with_name (_("fopen (temporary file)"));
2164 if (ifile[0])
2166 fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
2167 DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
2168 ifiledsc.dsc$w_length = 0;
2171 if (efile[0])
2173 fprintf (outfile, "$ define sys$error %s\n", efile);
2174 DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
2175 efiledsc.dsc$w_length = 0;
2178 if (ofile[0])
2180 fprintf (outfile, "$ define sys$output %s\n", ofile);
2181 DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
2182 ofiledsc.dsc$w_length = 0;
2185 p = sep = q = cmd;
2186 for (c = '\n'; c; c = *q++)
2188 switch (c)
2190 case '\n':
2191 /* At a newline, skip any whitespace around a leading $
2192 from the command and issue exactly one $ into the DCL. */
2193 while (isspace ((unsigned char)*p))
2194 p++;
2195 if (*p == '$')
2196 p++;
2197 while (isspace ((unsigned char)*p))
2198 p++;
2199 fwrite (p, 1, q - p, outfile);
2200 fputc ('$', outfile);
2201 fputc (' ', outfile);
2202 /* Reset variables. */
2203 p = sep = q;
2204 break;
2206 /* Nice places for line breaks are after strings, after
2207 comma or space and before slash. */
2208 case '"':
2209 q = vms_handle_apos (q);
2210 sep = q;
2211 break;
2212 case ',':
2213 case ' ':
2214 sep = q;
2215 break;
2216 case '/':
2217 case '\0':
2218 sep = q - 1;
2219 break;
2220 default:
2221 break;
2223 if (sep - p > 78)
2225 /* Enough stuff for a line. */
2226 fwrite (p, 1, sep - p, outfile);
2227 p = sep;
2228 if (*sep)
2230 /* The command continues. */
2231 fputc ('-', outfile);
2233 fputc ('\n', outfile);
2237 fwrite (p, 1, q - p, outfile);
2238 fputc ('\n', outfile);
2240 fclose (outfile);
2242 sprintf (cmd, "$ @%s", comname);
2244 DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
2247 cmddsc.dsc$w_length = strlen(cmd);
2248 cmddsc.dsc$a_pointer = cmd;
2249 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
2250 cmddsc.dsc$b_class = DSC$K_CLASS_S;
2252 child->efn = 0;
2253 while (child->efn < 32 || child->efn > 63)
2255 status = lib$get_ef ((unsigned long *)&child->efn);
2256 if (!(status & 1))
2257 return 0;
2260 sys$clref (child->efn);
2262 vms_jobsefnmask |= (1 << (child->efn - 32));
2265 LIB$SPAWN [command-string]
2266 [,input-file]
2267 [,output-file]
2268 [,flags]
2269 [,process-name]
2270 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2271 [,AST-address] [,varying-AST-argument]
2272 [,prompt-string] [,cli] [,table]
2275 #ifndef DONTWAITFORCHILD
2277 * Code to make ctrl+c and ctrl+y working.
2278 * The problem starts with the synchronous case where after lib$spawn is
2279 * called any input will go to the child. But with input re-directed,
2280 * both control characters won't make it to any of the programs, neither
2281 * the spawning nor to the spawned one. Hence the caller needs to spawn
2282 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2283 * has to follow to simulate the wanted synchronous behaviour.
2284 * The next problem is ctrl+y which isn't caught by the crtl and
2285 * therefore isn't converted to SIGQUIT (for a signal handler which is
2286 * already established). The only way to catch ctrl+y, is an AST
2287 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2288 * disabled, otherwise it will handle it. Not to mention the previous
2289 * ctrl+y handling of DCL needs to be re-established before make exits.
2290 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2291 * make it to the signal handler after the child "normally" terminates.
2292 * This isn't enough. It seems reasonable for simple command lines like
2293 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2294 * spawning make. Therefore we need to abort the process in the AST.
2296 * Prior to the spawn it is checked if an AST is already set up for
2297 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2298 * this will work except if make is run in a batch environment, but there
2299 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2300 * is disabled and an exit handler is established to re-enable it.
2301 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2302 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2303 * the already established handler and will bring us back to common code.
2304 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2305 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2306 * which the crtl converts to SIGINT and which is caught by the common
2307 * signal handler. Because signals were blocked before entering this code
2308 * sys$waitfr will always complete and the SIGQUIT will be processed after
2309 * it (after termination of the current block, somewhere in common code).
2310 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2311 * current command completes. Anyway it's better than nothing :-)
2314 if (!setupYAstTried)
2315 tryToSetupYAst();
2316 status = lib$spawn (&cmddsc, /* cmd-string */
2317 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file */
2318 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
2319 &spflags, /* flags */
2320 &pnamedsc, /* proc name */
2321 &child->pid, &child->cstatus, &child->efn,
2322 0, 0,
2323 0, 0, 0);
2324 if (status & 1)
2326 pidToAbort= child->pid;
2327 status= sys$waitfr (child->efn);
2328 pidToAbort= 0;
2329 vmsHandleChildTerm(child);
2331 #else
2332 status = lib$spawn (&cmddsc,
2333 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
2334 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
2335 &spflags,
2336 &pnamedsc,
2337 &child->pid, &child->cstatus, &child->efn,
2338 vmsHandleChildTerm, child,
2339 0, 0, 0);
2340 #endif
2342 if (!(status & 1))
2344 printf (_("Error spawning, %d\n") ,status);
2345 fflush (stdout);
2346 switch (status)
2348 case 0x1c:
2349 errno = EPROCLIM;
2350 break;
2351 default:
2352 errno = EFAIL;
2356 if (comname && !ISDB (DB_JOBS))
2357 unlink (comname);
2359 return (status & 1);
2362 #else /* !VMS */
2364 /* EMX: Start a child process. This function returns the new pid. */
2365 # if defined __MSDOS__ || defined __EMX__
2367 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2369 int pid;
2370 /* stdin_fd == 0 means: nothing to do for stdin;
2371 stdout_fd == 1 means: nothing to do for stdout */
2372 int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
2373 int save_stdout = (stdout_fd != 1) ? dup (1): 1;
2375 /* < 0 only if dup() failed */
2376 if (save_stdin < 0)
2377 fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
2378 if (save_stdout < 0)
2379 fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
2381 /* Close unnecessary file handles for the child. */
2382 if (save_stdin != 0)
2383 CLOSE_ON_EXEC (save_stdin);
2384 if (save_stdout != 1)
2385 CLOSE_ON_EXEC (save_stdout);
2387 /* Connect the pipes to the child process. */
2388 if (stdin_fd != 0)
2389 (void) dup2 (stdin_fd, 0);
2390 if (stdout_fd != 1)
2391 (void) dup2 (stdout_fd, 1);
2393 /* stdin_fd and stdout_fd must be closed on exit because we are
2394 still in the parent process */
2395 if (stdin_fd != 0)
2396 CLOSE_ON_EXEC (stdin_fd);
2397 if (stdout_fd != 1)
2398 CLOSE_ON_EXEC (stdout_fd);
2400 /* Run the command. */
2401 pid = exec_command (argv, envp);
2403 /* Restore stdout/stdin of the parent process. */
2404 if (stdin_fd != 0 && dup2 (save_stdin, 0) != 0)
2405 fatal (NILF, _("restoring of stdin failed\n"));
2406 if (stdout_fd != 1 && dup2 (save_stdout, 1) != 1)
2407 fatal (NILF, _("restoring of stdout failed\n"));
2409 return pid;
2412 #elif !defined (_AMIGA) && !defined (__MSDOS__)
2414 /* UNIX:
2415 Replace the current process with one executing the command in ARGV.
2416 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2417 the environment of the new program. This function does not return. */
2418 void
2419 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2421 if (stdin_fd != 0)
2422 (void) dup2 (stdin_fd, 0);
2423 if (stdout_fd != 1)
2424 (void) dup2 (stdout_fd, 1);
2425 if (stdin_fd != 0)
2426 (void) close (stdin_fd);
2427 if (stdout_fd != 1)
2428 (void) close (stdout_fd);
2430 /* Run the command. */
2431 exec_command (argv, envp);
2433 #endif /* !AMIGA && !__MSDOS__ */
2434 #endif /* !VMS */
2435 #endif /* !WINDOWS32 */
2437 #ifndef _AMIGA
2438 /* Replace the current process with one running the command in ARGV,
2439 with environment ENVP. This function does not return. */
2441 /* EMX: This function returns the pid of the child process. */
2442 # ifdef __EMX__
2444 # else
2445 void
2446 # endif
2447 exec_command (char **argv, char **envp)
2449 #ifdef VMS
2450 /* to work around a problem with signals and execve: ignore them */
2451 #ifdef SIGCHLD
2452 signal (SIGCHLD,SIG_IGN);
2453 #endif
2454 /* Run the program. */
2455 execve (argv[0], argv, envp);
2456 perror_with_name ("execve: ", argv[0]);
2457 _exit (EXIT_FAILURE);
2458 #else
2459 #ifdef WINDOWS32
2460 HANDLE hPID;
2461 HANDLE hWaitPID;
2462 int err = 0;
2463 int exit_code = EXIT_FAILURE;
2465 /* make sure CreateProcess() has Path it needs */
2466 sync_Path_environment();
2468 /* launch command */
2469 hPID = process_easy(argv, envp);
2471 /* make sure launch ok */
2472 if (hPID == INVALID_HANDLE_VALUE)
2474 int i;
2475 fprintf(stderr,
2476 _("process_easy() failed failed to launch process (e=%d)\n"),
2477 process_last_err(hPID));
2478 for (i = 0; argv[i]; i++)
2479 fprintf(stderr, "%s ", argv[i]);
2480 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2481 exit(EXIT_FAILURE);
2484 /* wait and reap last child */
2485 while (hWaitPID = process_wait_for_any())
2487 /* was an error found on this process? */
2488 err = process_last_err(hWaitPID);
2490 /* get exit data */
2491 exit_code = process_exit_code(hWaitPID);
2493 if (err)
2494 fprintf(stderr, "make (e=%d, rc=%d): %s",
2495 err, exit_code, map_windows32_error_to_string(err));
2497 /* cleanup process */
2498 process_cleanup(hWaitPID);
2500 /* expect to find only last pid, warn about other pids reaped */
2501 if (hWaitPID == hPID)
2502 break;
2503 else
2504 fprintf(stderr,
2505 _("make reaped child pid %d, still waiting for pid %d\n"),
2506 hWaitPID, hPID);
2509 /* return child's exit code as our exit code */
2510 exit(exit_code);
2512 #else /* !WINDOWS32 */
2514 # ifdef __EMX__
2515 int pid;
2516 # endif
2518 /* Be the user, permanently. */
2519 child_access ();
2521 # ifdef __EMX__
2523 /* Run the program. */
2524 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2526 if (pid >= 0)
2527 return pid;
2529 /* the file might have a strange shell extension */
2530 if (errno == ENOENT)
2531 errno = ENOEXEC;
2533 # else
2535 /* Run the program. */
2536 environ = envp;
2537 execvp (argv[0], argv);
2539 # endif /* !__EMX__ */
2541 switch (errno)
2543 case ENOENT:
2544 error (NILF, _("%s: Command not found"), argv[0]);
2545 break;
2546 case ENOEXEC:
2548 /* The file is not executable. Try it as a shell script. */
2549 extern char *getenv ();
2550 char *shell;
2551 char **new_argv;
2552 int argc;
2554 # ifdef __EMX__
2555 /* Do not use $SHELL from the environment */
2556 struct variable *p = lookup_variable ("SHELL", 5);
2557 if (p)
2558 shell = p->value;
2559 else
2560 shell = 0;
2561 # else
2562 shell = getenv ("SHELL");
2563 # endif
2564 if (shell == 0)
2565 shell = default_shell;
2567 argc = 1;
2568 while (argv[argc] != 0)
2569 ++argc;
2571 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
2572 new_argv[0] = shell;
2573 new_argv[1] = argv[0];
2574 while (argc > 0)
2576 new_argv[1 + argc] = argv[argc];
2577 --argc;
2580 # ifdef __EMX__
2581 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2582 if (pid >= 0)
2583 break;
2584 # else
2585 execvp (shell, new_argv);
2586 # endif
2587 if (errno == ENOENT)
2588 error (NILF, _("%s: Shell program not found"), shell);
2589 else
2590 perror_with_name ("execvp: ", shell);
2591 break;
2594 # ifdef __EMX__
2595 case EINVAL:
2596 /* this nasty error was driving me nuts :-( */
2597 error (NILF, _("spawnvpe: environment space might be exhausted"));
2598 /* FALLTHROUGH */
2599 # endif
2601 default:
2602 perror_with_name ("execvp: ", argv[0]);
2603 break;
2606 # ifdef __EMX__
2607 return pid;
2608 # else
2609 _exit (127);
2610 # endif
2611 #endif /* !WINDOWS32 */
2612 #endif /* !VMS */
2614 #else /* On Amiga */
2615 void exec_command (char **argv)
2617 MyExecute (argv);
2620 void clean_tmp (void)
2622 DeleteFile (amiga_bname);
2625 #endif /* On Amiga */
2627 #ifndef VMS
2628 /* Figure out the argument list necessary to run LINE as a command. Try to
2629 avoid using a shell. This routine handles only ' quoting, and " quoting
2630 when no backslash, $ or ` characters are seen in the quotes. Starting
2631 quotes may be escaped with a backslash. If any of the characters in
2632 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2633 is the first word of a line, the shell is used.
2635 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2636 If *RESTP is NULL, newlines will be ignored.
2638 SHELL is the shell to use, or nil to use the default shell.
2639 IFS is the value of $IFS, or nil (meaning the default). */
2641 static char **
2642 construct_command_argv_internal (char *line, char **restp, char *shell,
2643 char *ifs, char **batch_filename_ptr)
2645 #ifdef __MSDOS__
2646 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2647 We call `system' for anything that requires ``slow'' processing,
2648 because DOS shells are too dumb. When $SHELL points to a real
2649 (unix-style) shell, `system' just calls it to do everything. When
2650 $SHELL points to a DOS shell, `system' does most of the work
2651 internally, calling the shell only for its internal commands.
2652 However, it looks on the $PATH first, so you can e.g. have an
2653 external command named `mkdir'.
2655 Since we call `system', certain characters and commands below are
2656 actually not specific to COMMAND.COM, but to the DJGPP implementation
2657 of `system'. In particular:
2659 The shell wildcard characters are in DOS_CHARS because they will
2660 not be expanded if we call the child via `spawnXX'.
2662 The `;' is in DOS_CHARS, because our `system' knows how to run
2663 multiple commands on a single line.
2665 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2666 won't have to tell one from another and have one more set of
2667 commands and special characters. */
2668 static char sh_chars_dos[] = "*?[];|<>%^&()";
2669 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2670 "copy", "ctty", "date", "del", "dir", "echo",
2671 "erase", "exit", "for", "goto", "if", "md",
2672 "mkdir", "path", "pause", "prompt", "rd",
2673 "rmdir", "rem", "ren", "rename", "set",
2674 "shift", "time", "type", "ver", "verify",
2675 "vol", ":", 0 };
2677 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2678 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2679 "logout", "set", "umask", "wait", "while",
2680 "for", "case", "if", ":", ".", "break",
2681 "continue", "export", "read", "readonly",
2682 "shift", "times", "trap", "switch", "unset",
2683 0 };
2685 char *sh_chars;
2686 char **sh_cmds;
2687 #elif defined (__EMX__)
2688 static char sh_chars_dos[] = "*?[];|<>%^&()";
2689 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2690 "copy", "ctty", "date", "del", "dir", "echo",
2691 "erase", "exit", "for", "goto", "if", "md",
2692 "mkdir", "path", "pause", "prompt", "rd",
2693 "rmdir", "rem", "ren", "rename", "set",
2694 "shift", "time", "type", "ver", "verify",
2695 "vol", ":", 0 };
2697 static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
2698 static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2699 "date", "del", "detach", "dir", "echo",
2700 "endlocal", "erase", "exit", "for", "goto", "if",
2701 "keys", "md", "mkdir", "move", "path", "pause",
2702 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2703 "set", "setlocal", "shift", "start", "time",
2704 "type", "ver", "verify", "vol", ":", 0 };
2706 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~'";
2707 static char *sh_cmds_sh[] = { "echo", "cd", "eval", "exec", "exit", "login",
2708 "logout", "set", "umask", "wait", "while",
2709 "for", "case", "if", ":", ".", "break",
2710 "continue", "export", "read", "readonly",
2711 "shift", "times", "trap", "switch", "unset",
2712 0 };
2713 char *sh_chars;
2714 char **sh_cmds;
2716 #elif defined (_AMIGA)
2717 static char sh_chars[] = "#;\"|<>()?*$`";
2718 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2719 "rename", "set", "setenv", "date", "makedir",
2720 "skip", "else", "endif", "path", "prompt",
2721 "unset", "unsetenv", "version",
2722 0 };
2723 #elif defined (WINDOWS32)
2724 static char sh_chars_dos[] = "\"|&<>";
2725 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2726 "copy", "ctty", "date", "del", "dir", "echo",
2727 "erase", "exit", "for", "goto", "if", "if", "md",
2728 "mkdir", "path", "pause", "prompt", "rd", "rem",
2729 "ren", "rename", "rmdir", "set", "shift", "time",
2730 "type", "ver", "verify", "vol", ":", 0 };
2731 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2732 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2733 "logout", "set", "umask", "wait", "while", "for",
2734 "case", "if", ":", ".", "break", "continue",
2735 "export", "read", "readonly", "shift", "times",
2736 "trap", "switch", "test",
2737 #ifdef BATCH_MODE_ONLY_SHELL
2738 "echo",
2739 #endif
2740 0 };
2741 char* sh_chars;
2742 char** sh_cmds;
2743 #else /* must be UNIX-ish */
2744 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~!";
2745 static char *sh_cmds[] = { ".", ":", "break", "case", "cd", "continue",
2746 "eval", "exec", "exit", "export", "for", "if",
2747 "login", "logout", "read", "readonly", "set",
2748 "shift", "switch", "test", "times", "trap",
2749 "umask", "wait", "while", 0 };
2750 #endif
2751 register int i;
2752 register char *p;
2753 register char *ap;
2754 char *end;
2755 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2756 char **new_argv = 0;
2757 #ifdef WINDOWS32
2758 int slow_flag = 0;
2760 if (no_default_sh_exe) {
2761 sh_cmds = sh_cmds_dos;
2762 sh_chars = sh_chars_dos;
2763 } else {
2764 sh_cmds = sh_cmds_sh;
2765 sh_chars = sh_chars_sh;
2767 #endif /* WINDOWS32 */
2769 if (restp != NULL)
2770 *restp = NULL;
2772 /* Make sure not to bother processing an empty line. */
2773 while (isblank ((unsigned char)*line))
2774 ++line;
2775 if (*line == '\0')
2776 return 0;
2778 /* See if it is safe to parse commands internally. */
2779 if (shell == 0)
2780 shell = default_shell;
2781 #ifdef WINDOWS32
2782 else if (strcmp (shell, default_shell))
2784 char *s1 = _fullpath(NULL, shell, 0);
2785 char *s2 = _fullpath(NULL, default_shell, 0);
2787 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2789 if (s1)
2790 free (s1);
2791 if (s2)
2792 free (s2);
2794 if (slow_flag)
2795 goto slow;
2796 #else /* not WINDOWS32 */
2797 #if defined (__MSDOS__) || defined (__EMX__)
2798 else if (stricmp (shell, default_shell))
2800 extern int _is_unixy_shell (const char *_path);
2802 DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
2803 default_shell, shell));
2804 unixy_shell = _is_unixy_shell (shell);
2805 /* we must allocate a copy of shell: construct_command_argv() will free
2806 * shell after this function returns. */
2807 default_shell = xstrdup (shell);
2809 if (unixy_shell)
2811 sh_chars = sh_chars_sh;
2812 sh_cmds = sh_cmds_sh;
2814 else
2816 sh_chars = sh_chars_dos;
2817 sh_cmds = sh_cmds_dos;
2818 # ifdef __EMX__
2819 if (_osmode == OS2_MODE)
2821 sh_chars = sh_chars_os2;
2822 sh_cmds = sh_cmds_os2;
2824 # endif
2826 #else /* !__MSDOS__ */
2827 else if (strcmp (shell, default_shell))
2828 goto slow;
2829 #endif /* !__MSDOS__ && !__EMX__ */
2830 #endif /* not WINDOWS32 */
2832 if (ifs != 0)
2833 for (ap = ifs; *ap != '\0'; ++ap)
2834 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2835 goto slow;
2837 i = strlen (line) + 1;
2839 /* More than 1 arg per character is impossible. */
2840 new_argv = (char **) xmalloc (i * sizeof (char *));
2842 /* All the args can fit in a buffer as big as LINE is. */
2843 ap = new_argv[0] = (char *) xmalloc (i);
2844 end = ap + i;
2846 /* I is how many complete arguments have been found. */
2847 i = 0;
2848 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2849 for (p = line; *p != '\0'; ++p)
2851 if (ap > end)
2852 abort ();
2854 if (instring)
2856 string_char:
2857 /* Inside a string, just copy any char except a closing quote
2858 or a backslash-newline combination. */
2859 if (*p == instring)
2861 instring = 0;
2862 if (ap == new_argv[0] || *(ap-1) == '\0')
2863 last_argument_was_empty = 1;
2865 else if (*p == '\\' && p[1] == '\n')
2866 goto swallow_escaped_newline;
2867 else if (*p == '\n' && restp != NULL)
2869 /* End of the command line. */
2870 *restp = p;
2871 goto end_of_line;
2873 /* Backslash, $, and ` are special inside double quotes.
2874 If we see any of those, punt.
2875 But on MSDOS, if we use COMMAND.COM, double and single
2876 quotes have the same effect. */
2877 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2878 goto slow;
2879 else
2880 *ap++ = *p;
2882 else if (strchr (sh_chars, *p) != 0)
2883 /* Not inside a string, but it's a special char. */
2884 goto slow;
2885 #ifdef __MSDOS__
2886 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2887 /* `...' is a wildcard in DJGPP. */
2888 goto slow;
2889 #endif
2890 else
2891 /* Not a special char. */
2892 switch (*p)
2894 case '=':
2895 /* Equals is a special character in leading words before the
2896 first word with no equals sign in it. This is not the case
2897 with sh -k, but we never get here when using nonstandard
2898 shell flags. */
2899 if (! seen_nonequals && unixy_shell)
2900 goto slow;
2901 word_has_equals = 1;
2902 *ap++ = '=';
2903 break;
2905 case '\\':
2906 /* Backslash-newline combinations are eaten. */
2907 if (p[1] == '\n')
2909 swallow_escaped_newline:
2911 /* Eat the backslash, the newline, and following whitespace,
2912 replacing it all with a single space. */
2913 p += 2;
2915 /* If there is a tab after a backslash-newline,
2916 remove it from the source line which will be echoed,
2917 since it was most likely used to line
2918 up the continued line with the previous one. */
2919 if (*p == '\t')
2920 /* Note these overlap and strcpy() is undefined for
2921 overlapping objects in ANSI C. The strlen() _IS_ right,
2922 since we need to copy the nul byte too. */
2923 bcopy (p + 1, p, strlen (p));
2925 if (instring)
2926 goto string_char;
2927 else
2929 if (ap != new_argv[i])
2930 /* Treat this as a space, ending the arg.
2931 But if it's at the beginning of the arg, it should
2932 just get eaten, rather than becoming an empty arg. */
2933 goto end_of_arg;
2934 else
2935 p = next_token (p) - 1;
2938 else if (p[1] != '\0')
2940 #ifdef HAVE_DOS_PATHS
2941 /* Only remove backslashes before characters special
2942 to Unixy shells. All other backslashes are copied
2943 verbatim, since they are probably DOS-style
2944 directory separators. This still leaves a small
2945 window for problems, but at least it should work
2946 for the vast majority of naive users. */
2948 #ifdef __MSDOS__
2949 /* A dot is only special as part of the "..."
2950 wildcard. */
2951 if (strneq (p + 1, ".\\.\\.", 5))
2953 *ap++ = '.';
2954 *ap++ = '.';
2955 p += 4;
2957 else
2958 #endif
2959 if (p[1] != '\\' && p[1] != '\''
2960 && !isspace ((unsigned char)p[1])
2961 && (strchr (sh_chars_sh, p[1]) == 0))
2962 /* back up one notch, to copy the backslash */
2963 --p;
2964 #endif /* HAVE_DOS_PATHS */
2966 /* Copy and skip the following char. */
2967 *ap++ = *++p;
2969 break;
2971 case '\'':
2972 case '"':
2973 instring = *p;
2974 break;
2976 case '\n':
2977 if (restp != NULL)
2979 /* End of the command line. */
2980 *restp = p;
2981 goto end_of_line;
2983 else
2984 /* Newlines are not special. */
2985 *ap++ = '\n';
2986 break;
2988 case ' ':
2989 case '\t':
2990 end_of_arg:
2991 /* We have the end of an argument.
2992 Terminate the text of the argument. */
2993 *ap++ = '\0';
2994 new_argv[++i] = ap;
2995 last_argument_was_empty = 0;
2997 /* Update SEEN_NONEQUALS, which tells us if every word
2998 heretofore has contained an `='. */
2999 seen_nonequals |= ! word_has_equals;
3000 if (word_has_equals && ! seen_nonequals)
3001 /* An `=' in a word before the first
3002 word without one is magical. */
3003 goto slow;
3004 word_has_equals = 0; /* Prepare for the next word. */
3006 /* If this argument is the command name,
3007 see if it is a built-in shell command.
3008 If so, have the shell handle it. */
3009 if (i == 1)
3011 register int j;
3012 for (j = 0; sh_cmds[j] != 0; ++j)
3013 if (streq (sh_cmds[j], new_argv[0]))
3014 goto slow;
3017 /* Ignore multiple whitespace chars. */
3018 p = next_token (p);
3019 /* Next iteration should examine the first nonwhite char. */
3020 --p;
3021 break;
3023 default:
3024 *ap++ = *p;
3025 break;
3028 end_of_line:
3030 if (instring)
3031 /* Let the shell deal with an unterminated quote. */
3032 goto slow;
3034 /* Terminate the last argument and the argument list. */
3036 *ap = '\0';
3037 if (new_argv[i][0] != '\0' || last_argument_was_empty)
3038 ++i;
3039 new_argv[i] = 0;
3041 if (i == 1)
3043 register int j;
3044 for (j = 0; sh_cmds[j] != 0; ++j)
3045 if (streq (sh_cmds[j], new_argv[0]))
3046 goto slow;
3049 if (new_argv[0] == 0)
3050 /* Line was empty. */
3051 return 0;
3052 else
3053 return new_argv;
3055 slow:;
3056 /* We must use the shell. */
3058 if (new_argv != 0)
3060 /* Free the old argument list we were working on. */
3061 free (new_argv[0]);
3062 free ((void *)new_argv);
3065 #ifdef __MSDOS__
3066 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
3067 #endif
3069 #ifdef _AMIGA
3071 char *ptr;
3072 char *buffer;
3073 char *dptr;
3075 buffer = (char *)xmalloc (strlen (line)+1);
3077 ptr = line;
3078 for (dptr=buffer; *ptr; )
3080 if (*ptr == '\\' && ptr[1] == '\n')
3081 ptr += 2;
3082 else if (*ptr == '@') /* Kludge: multiline commands */
3084 ptr += 2;
3085 *dptr++ = '\n';
3087 else
3088 *dptr++ = *ptr++;
3090 *dptr = 0;
3092 new_argv = (char **) xmalloc (2 * sizeof (char *));
3093 new_argv[0] = buffer;
3094 new_argv[1] = 0;
3096 #else /* Not Amiga */
3097 #ifdef WINDOWS32
3099 * Not eating this whitespace caused things like
3101 * sh -c "\n"
3103 * which gave the shell fits. I think we have to eat
3104 * whitespace here, but this code should be considered
3105 * suspicious if things start failing....
3108 /* Make sure not to bother processing an empty line. */
3109 while (isspace ((unsigned char)*line))
3110 ++line;
3111 if (*line == '\0')
3112 return 0;
3113 #endif /* WINDOWS32 */
3115 /* SHELL may be a multi-word command. Construct a command line
3116 "SHELL -c LINE", with all special chars in LINE escaped.
3117 Then recurse, expanding this command line to get the final
3118 argument list. */
3120 unsigned int shell_len = strlen (shell);
3121 #ifndef VMS
3122 static char minus_c[] = " -c ";
3123 #else
3124 static char minus_c[] = "";
3125 #endif
3126 unsigned int line_len = strlen (line);
3128 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
3129 + (line_len * 2) + 1);
3130 char *command_ptr = NULL; /* used for batch_mode_shell mode */
3132 # ifdef __EMX__ /* is this necessary? */
3133 if (!unixy_shell)
3134 minus_c[1] = '/'; /* " /c " */
3135 # endif
3137 ap = new_line;
3138 bcopy (shell, ap, shell_len);
3139 ap += shell_len;
3140 bcopy (minus_c, ap, sizeof (minus_c) - 1);
3141 ap += sizeof (minus_c) - 1;
3142 command_ptr = ap;
3143 for (p = line; *p != '\0'; ++p)
3145 if (restp != NULL && *p == '\n')
3147 *restp = p;
3148 break;
3150 else if (*p == '\\' && p[1] == '\n')
3152 /* Eat the backslash, the newline, and following whitespace,
3153 replacing it all with a single space (which is escaped
3154 from the shell). */
3155 p += 2;
3157 /* If there is a tab after a backslash-newline,
3158 remove it from the source line which will be echoed,
3159 since it was most likely used to line
3160 up the continued line with the previous one. */
3161 if (*p == '\t')
3162 bcopy (p + 1, p, strlen (p));
3164 p = next_token (p);
3165 --p;
3166 if (unixy_shell && !batch_mode_shell)
3167 *ap++ = '\\';
3168 *ap++ = ' ';
3169 continue;
3172 /* DOS shells don't know about backslash-escaping. */
3173 if (unixy_shell && !batch_mode_shell &&
3174 (*p == '\\' || *p == '\'' || *p == '"'
3175 || isspace ((unsigned char)*p)
3176 || strchr (sh_chars, *p) != 0))
3177 *ap++ = '\\';
3178 #ifdef __MSDOS__
3179 else if (unixy_shell && strneq (p, "...", 3))
3181 /* The case of `...' wildcard again. */
3182 strcpy (ap, "\\.\\.\\");
3183 ap += 5;
3184 p += 2;
3186 #endif
3187 *ap++ = *p;
3189 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
3190 /* Line was empty. */
3191 return 0;
3192 *ap = '\0';
3194 #ifdef WINDOWS32
3195 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3196 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3197 cases, run commands via a script file. */
3198 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
3199 FILE* batch = NULL;
3200 int id = GetCurrentProcessId();
3201 PATH_VAR(fbuf);
3202 char* fname = NULL;
3204 /* create a file name */
3205 sprintf(fbuf, "make%d", id);
3206 fname = tempnam(".", fbuf);
3208 /* create batch file name */
3209 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
3210 strcpy(*batch_filename_ptr, fname);
3212 /* make sure path name is in DOS backslash format */
3213 if (!unixy_shell) {
3214 fname = *batch_filename_ptr;
3215 for (i = 0; fname[i] != '\0'; ++i)
3216 if (fname[i] == '/')
3217 fname[i] = '\\';
3218 strcat(*batch_filename_ptr, ".bat");
3219 } else {
3220 strcat(*batch_filename_ptr, ".sh");
3223 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3224 *batch_filename_ptr));
3226 /* create batch file to execute command */
3227 batch = fopen (*batch_filename_ptr, "w");
3228 if (!unixy_shell)
3229 fputs ("@echo off\n", batch);
3230 fputs (command_ptr, batch);
3231 fputc ('\n', batch);
3232 fclose (batch);
3234 /* create argv */
3235 new_argv = (char **) xmalloc(3 * sizeof (char *));
3236 if (unixy_shell) {
3237 new_argv[0] = xstrdup (shell);
3238 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
3239 } else {
3240 new_argv[0] = xstrdup (*batch_filename_ptr);
3241 new_argv[1] = NULL;
3243 new_argv[2] = NULL;
3244 } else
3245 #endif /* WINDOWS32 */
3246 if (unixy_shell)
3247 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
3248 (char *) 0, (char *) 0,
3249 (char **) 0);
3250 # ifdef __EMX__
3251 else if (!unixy_shell)
3253 /* new_line is local, must not be freed therefore */
3254 char *p, *q;
3255 int quote;
3256 size_t index;
3257 size_t len;
3259 /* handle quotes
3260 We have to remove all double quotes and to split the line
3261 into distinct arguments because of the strange handling
3262 of builtin commands by cmd: 'echo "bla"' prints "bla"
3263 (with quotes) while 'c:\bin\echo.exe "bla"' prints bla
3264 (without quotes). Some programs like autoconf rely
3265 on the second behaviour. */
3267 len = strlen (new_line) + 1;
3269 /* More than 1 arg per character is impossible. */
3270 new_argv = (char **) xmalloc (len * sizeof (char *));
3272 /* All the args can fit in a buffer as big as new_line is. */
3273 new_argv[0] = (char *) xmalloc (len);
3275 index = 0;
3276 quote = 0;
3277 q = new_line;
3278 p = new_argv[index];
3279 while(*q != '\0')
3281 /* searching for closing quote */
3282 if (quote)
3284 if (*q == quote)
3286 /* remove the quote */
3287 q++;
3288 quote = 0;
3290 else /* normal character: copy it */
3291 *p++ = *q++;
3294 /* searching for opening quote */
3295 else if (*q == '\"'
3296 # ifndef NO_CMD_DEFAULT
3297 || *q == '\''
3298 # endif
3301 /* remove opening quote */
3302 quote = *q;
3303 q++;
3306 /* spaces outside of a quoted string: remove them
3307 and start a new argument */
3308 else if (*q == ' ' || *q == '\t')
3310 *p++ = '\0'; /* trailing '\0' for last argument */
3312 /* remove all successive spaces */
3315 q++;
3317 while(*q == ' ' || *q == '\t');
3319 /* start new argument */
3320 index++;
3321 new_argv[index] = p;
3324 /* normal character (no space) outside a quoted string*/
3325 else
3326 *p++ = *q++;
3327 } /* end while() */
3329 *p = '\0'; /* trailing '\0' for the last argument */
3330 new_argv[index + 1] = NULL;
3332 # ifndef NO_CMD_DEFAULT
3333 /* special case: echo x="y"
3334 (e.g. autoconf uses this to determine whether make works)
3335 this is pure idioty but cmd works this way:
3336 if 'echo' and 'x="y"' are two different arguments cmd
3337 will print '"x="y""' but if they are only one argument
3338 cmd will print 'bla="blurb"' as it should be
3339 note: if we do not allow cmd to be the default shell
3340 we do not need this kind of voodoo */
3341 if (index == 3 && strcasecmp(new_argv[2], "echo") == 0)
3343 new_argv[2][4] = ' ';
3344 new_argv[3] = NULL;
3346 # endif
3348 #elif defined(__MSDOS__)
3349 else
3351 /* With MSDOS shells, we must construct the command line here
3352 instead of recursively calling ourselves, because we
3353 cannot backslash-escape the special characters (see above). */
3354 new_argv = (char **) xmalloc (sizeof (char *));
3355 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
3356 new_argv[0] = xmalloc (line_len + 1);
3357 strncpy (new_argv[0],
3358 new_line + shell_len + sizeof (minus_c) - 1, line_len);
3359 new_argv[0][line_len] = '\0';
3361 #else
3362 else
3363 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3364 __FILE__, __LINE__);
3365 #endif
3367 #endif /* ! AMIGA */
3369 return new_argv;
3371 #endif /* !VMS */
3373 /* Figure out the argument list necessary to run LINE as a command. Try to
3374 avoid using a shell. This routine handles only ' quoting, and " quoting
3375 when no backslash, $ or ` characters are seen in the quotes. Starting
3376 quotes may be escaped with a backslash. If any of the characters in
3377 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3378 is the first word of a line, the shell is used.
3380 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3381 If *RESTP is NULL, newlines will be ignored.
3383 FILE is the target whose commands these are. It is used for
3384 variable expansion for $(SHELL) and $(IFS). */
3386 char **
3387 construct_command_argv (char *line, char **restp, struct file *file,
3388 char **batch_filename_ptr)
3390 char *shell, *ifs;
3391 char **argv;
3393 #ifdef VMS
3394 char *cptr;
3395 int argc;
3397 argc = 0;
3398 cptr = line;
3399 for (;;)
3401 while ((*cptr != 0)
3402 && (isspace ((unsigned char)*cptr)))
3403 cptr++;
3404 if (*cptr == 0)
3405 break;
3406 while ((*cptr != 0)
3407 && (!isspace((unsigned char)*cptr)))
3408 cptr++;
3409 argc++;
3412 argv = (char **)malloc (argc * sizeof (char *));
3413 if (argv == 0)
3414 abort ();
3416 cptr = line;
3417 argc = 0;
3418 for (;;)
3420 while ((*cptr != 0)
3421 && (isspace ((unsigned char)*cptr)))
3422 cptr++;
3423 if (*cptr == 0)
3424 break;
3425 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3426 argv[argc++] = cptr;
3427 while ((*cptr != 0)
3428 && (!isspace((unsigned char)*cptr)))
3429 cptr++;
3430 if (*cptr != 0)
3431 *cptr++ = 0;
3433 #else
3435 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3436 int save = warn_undefined_variables_flag;
3437 warn_undefined_variables_flag = 0;
3439 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3440 #ifdef WINDOWS32
3442 * Convert to forward slashes so that construct_command_argv_internal()
3443 * is not confused.
3445 if (shell) {
3446 char *p = w32ify (shell, 0);
3447 strcpy (shell, p);
3449 #endif
3450 #ifdef __EMX__
3452 static const char *unixroot = NULL;
3453 static const char *last_shell = "";
3454 static int init = 0;
3455 if (init == 0)
3457 unixroot = getenv ("UNIXROOT");
3458 /* unixroot must be NULL or not empty */
3459 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3460 init = 1;
3463 /* if we have an unixroot drive and if shell is not default_shell
3464 (which means it's either cmd.exe or the test has already been
3465 performed) and if shell is an absolute path without drive letter,
3466 try whether it exists e.g.: if "/bin/sh" does not exist use
3467 "$UNIXROOT/bin/sh" instead. */
3468 if (unixroot && shell && strcmp (shell, last_shell) != 0
3469 && (shell[0] == '/' || shell[0] == '\\'))
3471 /* trying a new shell, check whether it exists */
3472 size_t size = strlen (shell);
3473 char *buf = xmalloc (size + 7);
3474 memcpy (buf, shell, size);
3475 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3476 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3478 /* try the same for the unixroot drive */
3479 memmove (buf + 2, buf, size + 5);
3480 buf[0] = unixroot[0];
3481 buf[1] = unixroot[1];
3482 if (access (buf, F_OK) == 0)
3483 /* we have found a shell! */
3484 /* free(shell); */
3485 shell = buf;
3486 else
3487 free (buf);
3489 else
3490 free (buf);
3493 #endif /* __EMX__ */
3495 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3497 warn_undefined_variables_flag = save;
3500 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
3502 free (shell);
3503 free (ifs);
3504 #endif /* !VMS */
3505 return argv;
3508 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3510 dup2 (int old, int new)
3512 int fd;
3514 (void) close (new);
3515 fd = dup (old);
3516 if (fd != new)
3518 (void) close (fd);
3519 errno = EMFILE;
3520 return -1;
3523 return fd;
3525 #endif /* !HAPE_DUP2 && !_AMIGA */