tell openssl to look for the ca-bundle.crt in our common location
[AROS-Contrib.git] / gnu / make / job.c
blob761e08e618f90b2cf4aca75dc0c8fc89733ec514
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>
32 #ifdef _AMIGA
33 #include "amiga.h"
34 #endif
36 /* Default shell to use. */
37 #ifdef WINDOWS32
39 char *default_shell = "sh.exe";
40 int no_default_sh_exe = 1;
41 int batch_mode_shell = 1;
43 #elif defined (_AMIGA)
44 char default_shell[] = "";
45 int batch_mode_shell = 0;
47 #elif defined (__MSDOS__)
49 /* The default shell is a pointer so we can change it if Makefile
50 says so. It is without an explicit path so we get a chance
51 to search the $PATH for it (since MSDOS doesn't have standard
52 directories we could trust). */
53 char *default_shell = "command.com";
54 int batch_mode_shell = 0;
56 #elif defined (__EMX__)
58 char *default_shell = "/bin/sh";
59 int batch_mode_shell = 0;
61 #elif defined (VMS)
63 # include <descrip.h>
64 char default_shell[] = "";
65 int batch_mode_shell = 0;
67 #elif defined (__riscos__)
69 char default_shell[] = "";
70 int batch_mode_shell = 0;
72 #else
74 char default_shell[] = "/bin/sh";
75 int batch_mode_shell = 0;
77 #endif
79 #ifdef __MSDOS__
80 # include <process.h>
81 static int execute_by_shell;
82 static int dos_pid = 123;
83 int dos_status;
84 int dos_command_running;
85 #endif /* __MSDOS__ */
87 #ifdef _AMIGA
88 # include <proto/dos.h>
89 static int amiga_pid = 123;
90 static int amiga_status;
91 static char amiga_bname[32];
92 static int amiga_batch_file;
93 #endif /* Amiga. */
95 #ifdef VMS
96 # ifndef __GNUC__
97 # include <processes.h>
98 # endif
99 # include <starlet.h>
100 # include <lib$routines.h>
101 #endif
103 #ifdef WINDOWS32
104 # include <windows.h>
105 # include <io.h>
106 # include <process.h>
107 # include "sub_proc.h"
108 # include "w32err.h"
109 # include "pathstuff.h"
110 #endif /* WINDOWS32 */
112 #ifdef __EMX__
113 # include <process.h>
114 #endif
116 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
117 # include <sys/wait.h>
118 #endif
120 #ifdef HAVE_WAITPID
121 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
122 #else /* Don't have waitpid. */
123 # ifdef HAVE_WAIT3
124 # ifndef wait3
125 extern int wait3 ();
126 # endif
127 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
128 # endif /* Have wait3. */
129 #endif /* Have waitpid. */
131 #if !defined (wait) && !defined (POSIX)
132 extern int wait ();
133 #endif
135 #ifndef HAVE_UNION_WAIT
137 # define WAIT_T int
139 # ifndef WTERMSIG
140 # define WTERMSIG(x) ((x) & 0x7f)
141 # endif
142 # ifndef WCOREDUMP
143 # define WCOREDUMP(x) ((x) & 0x80)
144 # endif
145 # ifndef WEXITSTATUS
146 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
147 # endif
148 # ifndef WIFSIGNALED
149 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
150 # endif
151 # ifndef WIFEXITED
152 # define WIFEXITED(x) (WTERMSIG (x) == 0)
153 # endif
155 #else /* Have `union wait'. */
157 # define WAIT_T union wait
158 # ifndef WTERMSIG
159 # define WTERMSIG(x) ((x).w_termsig)
160 # endif
161 # ifndef WCOREDUMP
162 # define WCOREDUMP(x) ((x).w_coredump)
163 # endif
164 # ifndef WEXITSTATUS
165 # define WEXITSTATUS(x) ((x).w_retcode)
166 # endif
167 # ifndef WIFSIGNALED
168 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
169 # endif
170 # ifndef WIFEXITED
171 # define WIFEXITED(x) (WTERMSIG(x) == 0)
172 # endif
174 #endif /* Don't have `union wait'. */
176 #ifdef VMS
177 static int vms_jobsefnmask = 0;
178 #endif /* !VMS */
180 #ifndef HAVE_UNISTD_H
181 extern int dup2 ();
182 extern int execve ();
183 extern void _exit ();
184 # ifndef VMS
185 extern int geteuid ();
186 extern int getegid ();
187 extern int setgid ();
188 extern int getgid ();
189 # endif
190 #endif
192 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
194 extern int getloadavg PARAMS ((double loadavg[], int nelem));
195 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
196 int *is_remote, int *id_ptr, int *used_stdin));
197 extern int start_remote_job_p PARAMS ((int));
198 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
199 int *coredump_ptr, int block));
201 RETSIGTYPE child_handler PARAMS ((int));
202 static void free_child PARAMS ((struct child *));
203 static void start_job_command PARAMS ((struct child *child));
204 static int load_too_high PARAMS ((void));
205 static int job_next_command PARAMS ((struct child *));
206 static int start_waiting_job PARAMS ((struct child *));
207 #ifdef VMS
208 static void vmsWaitForChildren PARAMS ((int *));
209 #endif
211 /* Chain of all live (or recently deceased) children. */
213 struct child *children = 0;
215 /* Number of children currently running. */
217 unsigned int job_slots_used = 0;
219 /* Nonzero if the `good' standard input is in use. */
221 static int good_stdin_used = 0;
223 /* Chain of children waiting to run until the load average goes down. */
225 static struct child *waiting_jobs = 0;
227 /* Non-zero if we use a *real* shell (always so on Unix). */
229 int unixy_shell = 1;
231 /* Number of jobs started in the current second. */
233 unsigned long job_counter = 0;
236 #ifdef WINDOWS32
238 * The macro which references this function is defined in make.h.
241 w32_kill(int pid, int sig)
243 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
245 #endif /* WINDOWS32 */
247 #ifdef __EMX__
248 /* returns whether path is assumed to be a unix like shell. */
250 _is_unixy_shell (const char *path)
252 /* list of non unix shells */
253 const char *known_os2shells[] = {
254 "cmd.exe",
255 "cmd",
256 "4os2.exe",
257 "4os2",
258 "4dos.exe",
259 "4dos",
260 "command.com",
261 "command",
262 NULL
265 /* find the rightmost '/' or '\\' */
266 const char *name = strrchr (path, '/');
267 const char *p = strrchr (path, '\\');
268 unsigned i;
270 if (name && p) /* take the max */
271 name = (name > p) ? name : p;
272 else if (p) /* name must be 0 */
273 name = p;
274 else if (!name) /* name and p must be 0 */
275 name = path;
277 if (*name == '/' || *name == '\\') name++;
279 i = 0;
280 while (known_os2shells[i] != NULL) {
281 if (stricmp (name, known_os2shells[i]) == 0) /* strcasecmp() */
282 return 0; /* not a unix shell */
283 i++;
286 /* in doubt assume a unix like shell */
287 return 1;
289 #endif /* __EMX__ */
292 /* Write an error message describing the exit status given in
293 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
294 Append "(ignored)" if IGNORED is nonzero. */
296 static void
297 child_error (char *target_name, int exit_code, int exit_sig, int coredump,
298 int ignored)
300 if (ignored && silent_flag)
301 return;
303 #ifdef VMS
304 if (!(exit_code & 1))
305 error (NILF,
306 (ignored ? _("*** [%s] Error 0x%x (ignored)")
307 : _("*** [%s] Error 0x%x")),
308 target_name, exit_code);
309 #else
310 if (exit_sig == 0)
311 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
312 _("*** [%s] Error %d"),
313 target_name, exit_code);
314 else
315 error (NILF, "*** [%s] %s%s",
316 target_name, strsignal (exit_sig),
317 coredump ? _(" (core dumped)") : "");
318 #endif /* VMS */
321 #ifdef VMS
322 /* Wait for nchildren children to terminate */
323 static void
324 vmsWaitForChildren(int *status)
326 while (1)
328 if (!vms_jobsefnmask)
330 *status = 0;
331 return;
334 *status = sys$wflor (32, vms_jobsefnmask);
336 return;
339 /* Set up IO redirection. */
341 char *
342 vms_redirect (struct dsc$descriptor_s *desc, char *fname, char *ibuf)
344 char *fptr;
345 extern char *vmsify ();
347 ibuf++;
348 while (isspace ((unsigned char)*ibuf))
349 ibuf++;
350 fptr = ibuf;
351 while (*ibuf && !isspace ((unsigned char)*ibuf))
352 ibuf++;
353 *ibuf = 0;
354 if (strcmp (fptr, "/dev/null") != 0)
356 strcpy (fname, vmsify (fptr, 0));
357 if (strchr (fname, '.') == 0)
358 strcat (fname, ".");
360 desc->dsc$w_length = strlen(fname);
361 desc->dsc$a_pointer = fname;
362 desc->dsc$b_dtype = DSC$K_DTYPE_T;
363 desc->dsc$b_class = DSC$K_CLASS_S;
365 if (*fname == 0)
366 printf (_("Warning: Empty redirection\n"));
367 return ibuf;
371 /* found apostrophe at (p-1)
372 inc p until after closing apostrophe.
375 static char *
376 vms_handle_apos (char *p)
378 int alast;
380 #define SEPCHARS ",/()= "
382 alast = 0;
384 while (*p != 0)
386 if (*p == '"')
388 if (alast)
390 alast = 0;
391 p++;
393 else
395 p++;
396 if (strchr (SEPCHARS, *p))
397 break;
398 alast = 1;
401 else
402 p++;
405 return p;
408 #endif
411 /* Handle a dead child. This handler may or may not ever be installed.
413 If we're using the jobserver feature, we need it. First, installing it
414 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
415 read FD to ensure we don't enter another blocking read without reaping all
416 the dead children. In this case we don't need the dead_children count.
418 If we don't have either waitpid or wait3, then make is unreliable, but we
419 use the dead_children count to reap children as best we can. */
421 static unsigned int dead_children = 0;
423 RETSIGTYPE
424 child_handler (int sig UNUSED)
426 ++dead_children;
428 if (job_rfd >= 0)
430 close (job_rfd);
431 job_rfd = -1;
434 #ifdef __EMX__
435 /* The signal handler must called only once! */
436 signal (SIGCHLD, SIG_DFL);
437 #endif
439 /* This causes problems if the SIGCHLD interrupts a printf().
440 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
444 extern int shell_function_pid, shell_function_completed;
446 /* Reap all dead children, storing the returned status and the new command
447 state (`cs_finished') in the `file' member of the `struct child' for the
448 dead child, and removing the child from the chain. In addition, if BLOCK
449 nonzero, we block in this function until we've reaped at least one
450 complete child, waiting for it to die if necessary. If ERR is nonzero,
451 print an error message first. */
453 void
454 reap_children (int block, int err)
456 WAIT_T status;
457 /* Initially, assume we have some. */
458 int reap_more = 1;
460 #ifdef WAIT_NOHANG
461 # define REAP_MORE reap_more
462 #else
463 # define REAP_MORE dead_children
464 #endif
466 /* As long as:
468 We have at least one child outstanding OR a shell function in progress,
470 We're blocking for a complete child OR there are more children to reap
472 we'll keep reaping children. */
474 while ((children != 0 || shell_function_pid != 0)
475 && (block || REAP_MORE))
477 int remote = 0;
478 pid_t pid;
479 int exit_code, exit_sig, coredump;
480 register struct child *lastc, *c;
481 int child_failed;
482 int any_remote, any_local;
484 if (err && block)
486 /* We might block for a while, so let the user know why. */
487 fflush (stdout);
488 error (NILF, _("*** Waiting for unfinished jobs...."));
491 /* We have one less dead child to reap. As noted in
492 child_handler() above, this count is completely unimportant for
493 all modern, POSIX-y systems that support wait3() or waitpid().
494 The rest of this comment below applies only to early, broken
495 pre-POSIX systems. We keep the count only because... it's there...
497 The test and decrement are not atomic; if it is compiled into:
498 register = dead_children - 1;
499 dead_children = register;
500 a SIGCHLD could come between the two instructions.
501 child_handler increments dead_children.
502 The second instruction here would lose that increment. But the
503 only effect of dead_children being wrong is that we might wait
504 longer than necessary to reap a child, and lose some parallelism;
505 and we might print the "Waiting for unfinished jobs" message above
506 when not necessary. */
508 if (dead_children > 0)
509 --dead_children;
511 any_remote = 0;
512 any_local = shell_function_pid != 0;
513 for (c = children; c != 0; c = c->next)
515 any_remote |= c->remote;
516 any_local |= ! c->remote;
517 DB (DB_JOBS, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
518 (unsigned long int) c, c->file->name,
519 (long) c->pid, c->remote ? _(" (remote)") : ""));
520 #ifdef VMS
521 break;
522 #endif
525 /* First, check for remote children. */
526 if (any_remote)
527 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
528 else
529 pid = 0;
531 if (pid > 0)
532 /* We got a remote child. */
533 remote = 1;
534 else if (pid < 0)
536 /* A remote status command failed miserably. Punt. */
537 remote_status_lose:
538 pfatal_with_name ("remote_status");
540 else
542 /* No remote children. Check for local children. */
543 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
544 if (any_local)
546 #ifdef VMS
547 vmsWaitForChildren (&status);
548 pid = c->pid;
549 #else
550 #ifdef WAIT_NOHANG
551 if (!block)
552 pid = WAIT_NOHANG (&status);
553 else
554 #endif
555 pid = wait (&status);
556 #endif /* !VMS */
558 else
559 pid = 0;
561 if (pid < 0)
563 /* The wait*() failed miserably. Punt. */
564 pfatal_with_name ("wait");
566 else if (pid > 0)
568 /* We got a child exit; chop the status word up. */
569 exit_code = WEXITSTATUS (status);
570 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
571 coredump = WCOREDUMP (status);
573 /* If we have started jobs in this second, remove one. */
574 if (job_counter)
575 --job_counter;
577 else
579 /* No local children are dead. */
580 reap_more = 0;
582 if (!block || !any_remote)
583 break;
585 /* Now try a blocking wait for a remote child. */
586 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
587 if (pid < 0)
588 goto remote_status_lose;
589 else if (pid == 0)
590 /* No remote children either. Finally give up. */
591 break;
593 /* We got a remote child. */
594 remote = 1;
596 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
598 #ifdef __MSDOS__
599 /* Life is very different on MSDOS. */
600 pid = dos_pid - 1;
601 status = dos_status;
602 exit_code = WEXITSTATUS (status);
603 if (exit_code == 0xff)
604 exit_code = -1;
605 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
606 coredump = 0;
607 #endif /* __MSDOS__ */
608 #ifdef _AMIGA
609 /* Same on Amiga */
610 pid = amiga_pid - 1;
611 status = amiga_status;
612 exit_code = amiga_status;
613 exit_sig = 0;
614 coredump = 0;
615 #endif /* _AMIGA */
616 #ifdef WINDOWS32
618 HANDLE hPID;
619 int err;
620 exit_code = 0;
621 exit_sig = 0;
622 coredump = 0;
624 /* wait for anything to finish */
625 hPID = process_wait_for_any();
626 if (hPID)
629 /* was an error found on this process? */
630 err = process_last_err(hPID);
632 /* get exit data */
633 exit_code = process_exit_code(hPID);
635 if (err)
636 fprintf(stderr, "make (e=%d): %s",
637 exit_code, map_windows32_error_to_string(exit_code));
639 /* signal */
640 exit_sig = process_signal(hPID);
642 /* cleanup process */
643 process_cleanup(hPID);
645 coredump = 0;
647 pid = (pid_t) hPID;
649 #endif /* WINDOWS32 */
652 /* Check if this is the child of the `shell' function. */
653 if (!remote && pid == shell_function_pid)
655 /* It is. Leave an indicator for the `shell' function. */
656 if (exit_sig == 0 && exit_code == 127)
657 shell_function_completed = -1;
658 else
659 shell_function_completed = 1;
660 break;
663 child_failed = exit_sig != 0 || exit_code != 0;
665 /* Search for a child matching the deceased one. */
666 lastc = 0;
667 for (c = children; c != 0; lastc = c, c = c->next)
668 if (c->remote == remote && c->pid == pid)
669 break;
671 if (c == 0)
672 /* An unknown child died.
673 Ignore it; it was inherited from our invoker. */
674 continue;
676 DB (DB_JOBS, (child_failed
677 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
678 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
679 (unsigned long int) c, (long) c->pid,
680 c->remote ? _(" (remote)") : ""));
682 if (c->sh_batch_file) {
683 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
684 c->sh_batch_file));
686 /* just try and remove, don't care if this fails */
687 remove (c->sh_batch_file);
689 /* all done with memory */
690 free (c->sh_batch_file);
691 c->sh_batch_file = NULL;
694 /* If this child had the good stdin, say it is now free. */
695 if (c->good_stdin)
696 good_stdin_used = 0;
698 if (child_failed && !c->noerror && !ignore_errors_flag)
700 /* The commands failed. Write an error message,
701 delete non-precious targets, and abort. */
702 static int delete_on_error = -1;
703 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
704 c->file->update_status = 2;
705 if (delete_on_error == -1)
707 struct file *f = lookup_file (".DELETE_ON_ERROR");
708 delete_on_error = f != 0 && f->is_target;
710 if (exit_sig != 0 || delete_on_error)
711 delete_child_targets (c);
713 else
715 if (child_failed)
717 /* The commands failed, but we don't care. */
718 child_error (c->file->name,
719 exit_code, exit_sig, coredump, 1);
720 child_failed = 0;
723 /* If there are more commands to run, try to start them. */
724 if (job_next_command (c))
726 if (handling_fatal_signal)
728 /* Never start new commands while we are dying.
729 Since there are more commands that wanted to be run,
730 the target was not completely remade. So we treat
731 this as if a command had failed. */
732 c->file->update_status = 2;
734 else
736 /* Check again whether to start remotely.
737 Whether or not we want to changes over time.
738 Also, start_remote_job may need state set up
739 by start_remote_job_p. */
740 c->remote = start_remote_job_p (0);
741 start_job_command (c);
742 /* Fatal signals are left blocked in case we were
743 about to put that child on the chain. But it is
744 already there, so it is safe for a fatal signal to
745 arrive now; it will clean up this child's targets. */
746 unblock_sigs ();
747 if (c->file->command_state == cs_running)
748 /* We successfully started the new command.
749 Loop to reap more children. */
750 continue;
753 if (c->file->update_status != 0)
754 /* We failed to start the commands. */
755 delete_child_targets (c);
757 else
758 /* There are no more commands. We got through them all
759 without an unignored error. Now the target has been
760 successfully updated. */
761 c->file->update_status = 0;
764 /* When we get here, all the commands for C->file are finished
765 (or aborted) and C->file->update_status contains 0 or 2. But
766 C->file->command_state is still cs_running if all the commands
767 ran; notice_finish_file looks for cs_running to tell it that
768 it's interesting to check the file's modtime again now. */
770 if (! handling_fatal_signal)
771 /* Notice if the target of the commands has been changed.
772 This also propagates its values for command_state and
773 update_status to its also_make files. */
774 notice_finished_file (c->file);
776 DB (DB_JOBS, (_("Removing child 0x%08lx PID %ld%s from chain.\n"),
777 (unsigned long int) c, (long) c->pid,
778 c->remote ? _(" (remote)") : ""));
780 /* Block fatal signals while frobnicating the list, so that
781 children and job_slots_used are always consistent. Otherwise
782 a fatal signal arriving after the child is off the chain and
783 before job_slots_used is decremented would believe a child was
784 live and call reap_children again. */
785 block_sigs ();
787 /* There is now another slot open. */
788 if (job_slots_used > 0)
789 --job_slots_used;
791 /* Remove the child from the chain and free it. */
792 if (lastc == 0)
793 children = c->next;
794 else
795 lastc->next = c->next;
797 free_child (c);
799 unblock_sigs ();
801 /* If the job failed, and the -k flag was not given, die,
802 unless we are already in the process of dying. */
803 if (!err && child_failed && !keep_going_flag &&
804 /* fatal_error_signal will die with the right signal. */
805 !handling_fatal_signal)
806 die (2);
808 /* Only block for one child. */
809 block = 0;
812 return;
815 /* Free the storage allocated for CHILD. */
817 static void
818 free_child (struct child *child)
820 /* If this child is the only one it was our "free" job, so don't put a
821 token back for it. This child has already been removed from the list,
822 so if there any left this wasn't the last one. */
824 if (job_fds[1] >= 0 && children)
826 char token = '+';
827 int r;
829 /* Write a job token back to the pipe. */
831 EINTRLOOP (r, write (job_fds[1], &token, 1));
832 if (r != 1)
833 pfatal_with_name (_("write jobserver"));
835 DB (DB_JOBS, (_("Released token for child 0x%08lx (%s).\n"),
836 (unsigned long int) child, child->file->name));
839 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
840 return;
842 if (child->command_lines != 0)
844 register unsigned int i;
845 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
846 free (child->command_lines[i]);
847 free ((char *) child->command_lines);
850 if (child->environment != 0)
852 register char **ep = child->environment;
853 while (*ep != 0)
854 free (*ep++);
855 free ((char *) child->environment);
858 free ((char *) child);
861 #ifdef POSIX
862 extern sigset_t fatal_signal_set;
863 #endif
866 void
867 block_sigs (void)
869 #ifndef _AMIGA
871 #ifdef POSIX
872 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
873 #else
874 #ifdef HAVE_SIGSETMASK
875 (void) sigblock (fatal_signal_mask);
876 #endif
877 #endif
878 #endif
881 #ifdef POSIX
882 void
883 unblock_sigs (void)
885 #ifndef _AMIGA
886 sigset_t empty;
887 sigemptyset (&empty);
888 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
889 #endif
891 #endif
894 #ifdef MAKE_JOBSERVER
895 /* Set the child handler action flags to FLAGS. */
896 static void
897 set_child_handler_action_flags (int flags)
899 struct sigaction sa;
900 bzero ((char *) &sa, sizeof sa);
901 sa.sa_handler = child_handler;
902 sa.sa_flags = flags;
903 #if defined SIGCHLD
904 sigaction (SIGCHLD, &sa, NULL);
905 #endif
906 #if defined SIGCLD && SIGCLD != SIGCHLD
907 sigaction (SIGCLD, &sa, NULL);
908 #endif
910 #endif
913 /* Start a job to run the commands specified in CHILD.
914 CHILD is updated to reflect the commands and ID of the child process.
916 NOTE: On return fatal signals are blocked! The caller is responsible
917 for calling `unblock_sigs', once the new child is safely on the chain so
918 it can be cleaned up in the event of a fatal signal. */
920 static void
921 start_job_command (struct child *child)
923 #ifndef _AMIGA
924 static int bad_stdin = -1;
925 #endif
926 register char *p;
927 int flags;
928 #ifdef VMS
929 char *argv;
930 #else
931 char **argv;
932 #endif
934 /* If we have a completely empty commandset, stop now. */
935 if (!child->command_ptr)
936 goto next_command;
938 /* Combine the flags parsed for the line itself with
939 the flags specified globally for this target. */
940 flags = (child->file->command_flags
941 | child->file->cmds->lines_flags[child->command_line - 1]);
943 p = child->command_ptr;
944 child->noerror = flags & COMMANDS_NOERROR;
946 while (*p != '\0')
948 if (*p == '@')
949 flags |= COMMANDS_SILENT;
950 else if (*p == '+')
951 flags |= COMMANDS_RECURSE;
952 else if (*p == '-')
953 child->noerror = 1;
954 else if (!isblank ((unsigned char)*p))
955 break;
956 ++p;
959 /* Update the file's command flags with any new ones we found. We only
960 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
961 now marking more commands recursive than should be in the case of
962 multiline define/endef scripts where only one line is marked "+". In
963 order to really fix this, we'll have to keep a lines_flags for every
964 actual line, after expansion. */
965 child->file->cmds->lines_flags[child->command_line - 1]
966 |= flags & COMMANDS_RECURSE;
968 /* Figure out an argument list from this command line. */
971 char *end = 0;
972 #ifdef VMS
973 argv = p;
974 #else
975 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
976 #endif
977 if (end == NULL)
978 child->command_ptr = NULL;
979 else
981 *end++ = '\0';
982 child->command_ptr = end;
986 /* If -q was given, say that updating `failed' if there was any text on the
987 command line, or `succeeded' otherwise. The exit status of 1 tells the
988 user that -q is saying `something to do'; the exit status for a random
989 error is 2. */
990 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
992 #ifndef VMS
993 free (argv[0]);
994 free ((char *) argv);
995 #endif
996 child->file->update_status = 1;
997 notice_finished_file (child->file);
998 return;
1001 if (touch_flag && !(flags & COMMANDS_RECURSE))
1003 /* Go on to the next command. It might be the recursive one.
1004 We construct ARGV only to find the end of the command line. */
1005 #ifndef VMS
1006 if (argv)
1008 free (argv[0]);
1009 free ((char *) argv);
1011 #endif
1012 argv = 0;
1015 if (argv == 0)
1017 next_command:
1018 #ifdef __MSDOS__
1019 execute_by_shell = 0; /* in case construct_command_argv sets it */
1020 #endif
1021 /* This line has no commands. Go to the next. */
1022 if (job_next_command (child))
1023 start_job_command (child);
1024 else
1026 /* No more commands. Make sure we're "running"; we might not be if
1027 (e.g.) all commands were skipped due to -n. */
1028 set_command_state (child->file, cs_running);
1029 child->file->update_status = 0;
1030 notice_finished_file (child->file);
1032 return;
1035 /* Print out the command. If silent, we call `message' with null so it
1036 can log the working directory before the command's own error messages
1037 appear. */
1039 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
1040 ? "%s" : (char *) 0, p);
1042 /* Tell update_goal_chain that a command has been started on behalf of
1043 this target. It is important that this happens here and not in
1044 reap_children (where we used to do it), because reap_children might be
1045 reaping children from a different target. We want this increment to
1046 guaranteedly indicate that a command was started for the dependency
1047 chain (i.e., update_file recursion chain) we are processing. */
1049 ++commands_started;
1051 /* Optimize an empty command. People use this for timestamp rules,
1052 so avoid forking a useless shell. Do this after we increment
1053 commands_started so make still treats this special case as if it
1054 performed some action (makes a difference as to what messages are
1055 printed, etc. */
1057 #if !defined(VMS) && !defined(_AMIGA)
1058 if (
1059 #if defined __MSDOS__ || defined (__EMX__)
1060 unixy_shell /* the test is complicated and we already did it */
1061 #else
1062 (argv[0] && !strcmp (argv[0], "/bin/sh"))
1063 #endif
1064 && (argv[1]
1065 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
1066 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1067 && argv[3] == NULL)
1069 free (argv[0]);
1070 free ((char *) argv);
1071 goto next_command;
1073 #endif /* !VMS && !_AMIGA */
1075 /* If -n was given, recurse to get the next line in the sequence. */
1077 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1079 #ifndef VMS
1080 free (argv[0]);
1081 free ((char *) argv);
1082 #endif
1083 goto next_command;
1086 /* Flush the output streams so they won't have things written twice. */
1088 fflush (stdout);
1089 fflush (stderr);
1091 #ifndef VMS
1092 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1094 /* Set up a bad standard input that reads from a broken pipe. */
1096 if (bad_stdin == -1)
1098 /* Make a file descriptor that is the read end of a broken pipe.
1099 This will be used for some children's standard inputs. */
1100 int pd[2];
1101 if (pipe (pd) == 0)
1103 /* Close the write side. */
1104 (void) close (pd[1]);
1105 /* Save the read side. */
1106 bad_stdin = pd[0];
1108 /* Set the descriptor to close on exec, so it does not litter any
1109 child's descriptor table. When it is dup2'd onto descriptor 0,
1110 that descriptor will not close on exec. */
1111 CLOSE_ON_EXEC (bad_stdin);
1115 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1117 /* Decide whether to give this child the `good' standard input
1118 (one that points to the terminal or whatever), or the `bad' one
1119 that points to the read side of a broken pipe. */
1121 child->good_stdin = !good_stdin_used;
1122 if (child->good_stdin)
1123 good_stdin_used = 1;
1125 #endif /* !VMS */
1127 child->deleted = 0;
1129 #ifndef _AMIGA
1130 /* Set up the environment for the child. */
1131 if (child->environment == 0)
1132 child->environment = target_environment (child->file);
1133 #endif
1135 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1137 #ifndef VMS
1138 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1139 if (child->remote)
1141 int is_remote, id, used_stdin;
1142 if (start_remote_job (argv, child->environment,
1143 child->good_stdin ? 0 : bad_stdin,
1144 &is_remote, &id, &used_stdin))
1145 /* Don't give up; remote execution may fail for various reasons. If
1146 so, simply run the job locally. */
1147 goto run_local;
1148 else
1150 if (child->good_stdin && !used_stdin)
1152 child->good_stdin = 0;
1153 good_stdin_used = 0;
1155 child->remote = is_remote;
1156 child->pid = id;
1159 else
1160 #endif /* !VMS */
1162 /* Fork the child process. */
1164 char **parent_environ;
1166 run_local:
1167 block_sigs ();
1169 child->remote = 0;
1171 #ifdef VMS
1173 if (!child_execute_job (argv, child)) {
1174 /* Fork failed! */
1175 perror_with_name ("vfork", "");
1176 goto error;
1179 #else
1181 parent_environ = environ;
1183 # ifdef __EMX__
1184 /* If we aren't running a recursive command and we have a jobserver
1185 pipe, close it before exec'ing. */
1186 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1188 CLOSE_ON_EXEC (job_fds[0]);
1189 CLOSE_ON_EXEC (job_fds[1]);
1191 if (job_rfd >= 0)
1192 CLOSE_ON_EXEC (job_rfd);
1194 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1195 child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1196 argv, child->environment);
1197 if (child->pid < 0)
1199 /* spawn failed! */
1200 unblock_sigs ();
1201 perror_with_name ("spawn", "");
1202 goto error;
1205 /* undo CLOSE_ON_EXEC() after the child process has been started */
1206 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1208 fcntl (job_fds[0], F_SETFD, 0);
1209 fcntl (job_fds[1], F_SETFD, 0);
1211 if (job_rfd >= 0)
1212 fcntl (job_rfd, F_SETFD, 0);
1214 #else /* !__EMX__ */
1216 child->pid = vfork ();
1217 environ = parent_environ; /* Restore value child may have clobbered. */
1218 if (child->pid == 0)
1220 /* We are the child side. */
1221 unblock_sigs ();
1223 /* If we aren't running a recursive command and we have a jobserver
1224 pipe, close it before exec'ing. */
1225 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1227 close (job_fds[0]);
1228 close (job_fds[1]);
1230 if (job_rfd >= 0)
1231 close (job_rfd);
1233 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1234 argv, child->environment);
1236 else if (child->pid < 0)
1238 /* Fork failed! */
1239 unblock_sigs ();
1240 perror_with_name ("vfork", "");
1241 goto error;
1243 # endif /* !__EMX__ */
1244 #endif /* !VMS */
1247 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1248 #ifdef __MSDOS__
1250 int proc_return;
1252 block_sigs ();
1253 dos_status = 0;
1255 /* We call `system' to do the job of the SHELL, since stock DOS
1256 shell is too dumb. Our `system' knows how to handle long
1257 command lines even if pipes/redirection is needed; it will only
1258 call COMMAND.COM when its internal commands are used. */
1259 if (execute_by_shell)
1261 char *cmdline = argv[0];
1262 /* We don't have a way to pass environment to `system',
1263 so we need to save and restore ours, sigh... */
1264 char **parent_environ = environ;
1266 environ = child->environment;
1268 /* If we have a *real* shell, tell `system' to call
1269 it to do everything for us. */
1270 if (unixy_shell)
1272 /* A *real* shell on MSDOS may not support long
1273 command lines the DJGPP way, so we must use `system'. */
1274 cmdline = argv[2]; /* get past "shell -c" */
1277 dos_command_running = 1;
1278 proc_return = system (cmdline);
1279 environ = parent_environ;
1280 execute_by_shell = 0; /* for the next time */
1282 else
1284 dos_command_running = 1;
1285 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1288 /* Need to unblock signals before turning off
1289 dos_command_running, so that child's signals
1290 will be treated as such (see fatal_error_signal). */
1291 unblock_sigs ();
1292 dos_command_running = 0;
1294 /* If the child got a signal, dos_status has its
1295 high 8 bits set, so be careful not to alter them. */
1296 if (proc_return == -1)
1297 dos_status |= 0xff;
1298 else
1299 dos_status |= (proc_return & 0xff);
1300 ++dead_children;
1301 child->pid = dos_pid++;
1303 #endif /* __MSDOS__ */
1304 #ifdef _AMIGA
1305 amiga_status = MyExecute (argv, child->environment, NULL);
1307 ++dead_children;
1308 child->pid = amiga_pid++;
1309 if (amiga_batch_file)
1311 amiga_batch_file = 0;
1312 DeleteFile (amiga_bname); /* Ignore errors. */
1314 #endif /* Amiga */
1315 #ifdef WINDOWS32
1317 HANDLE hPID;
1318 char* arg0;
1320 /* make UNC paths safe for CreateProcess -- backslash format */
1321 arg0 = argv[0];
1322 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1323 for ( ; arg0 && *arg0; arg0++)
1324 if (*arg0 == '/')
1325 *arg0 = '\\';
1327 /* make sure CreateProcess() has Path it needs */
1328 sync_Path_environment();
1330 hPID = process_easy(argv, child->environment);
1332 if (hPID != INVALID_HANDLE_VALUE)
1333 child->pid = (int) hPID;
1334 else {
1335 int i;
1336 unblock_sigs();
1337 fprintf(stderr,
1338 _("process_easy() failed failed to launch process (e=%d)\n"),
1339 process_last_err(hPID));
1340 for (i = 0; argv[i]; i++)
1341 fprintf(stderr, "%s ", argv[i]);
1342 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1345 #endif /* WINDOWS32 */
1346 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1348 /* Bump the number of jobs started in this second. */
1349 ++job_counter;
1351 /* We are the parent side. Set the state to
1352 say the commands are running and return. */
1354 set_command_state (child->file, cs_running);
1356 /* Free the storage used by the child's argument list. */
1357 #ifndef VMS
1358 free (argv[0]);
1359 free ((char *) argv);
1360 #endif
1362 return;
1364 error:
1365 child->file->update_status = 2;
1366 notice_finished_file (child->file);
1367 return;
1370 /* Try to start a child running.
1371 Returns nonzero if the child was started (and maybe finished), or zero if
1372 the load was too high and the child was put on the `waiting_jobs' chain. */
1374 static int
1375 start_waiting_job (struct child *c)
1377 struct file *f = c->file;
1379 /* If we can start a job remotely, we always want to, and don't care about
1380 the local load average. We record that the job should be started
1381 remotely in C->remote for start_job_command to test. */
1383 c->remote = start_remote_job_p (1);
1385 /* If we are running at least one job already and the load average
1386 is too high, make this one wait. */
1387 if (!c->remote && job_slots_used > 0 && load_too_high ())
1389 /* Put this child on the chain of children waiting for the load average
1390 to go down. */
1391 set_command_state (f, cs_running);
1392 c->next = waiting_jobs;
1393 waiting_jobs = c;
1394 return 0;
1397 /* Start the first command; reap_children will run later command lines. */
1398 start_job_command (c);
1400 switch (f->command_state)
1402 case cs_running:
1403 c->next = children;
1404 DB (DB_JOBS, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1405 (unsigned long int) c, c->file->name,
1406 (long) c->pid, c->remote ? _(" (remote)") : ""));
1407 children = c;
1408 /* One more job slot is in use. */
1409 ++job_slots_used;
1410 unblock_sigs ();
1411 break;
1413 case cs_not_started:
1414 /* All the command lines turned out to be empty. */
1415 f->update_status = 0;
1416 /* FALLTHROUGH */
1418 case cs_finished:
1419 notice_finished_file (f);
1420 free_child (c);
1421 break;
1423 default:
1424 assert (f->command_state == cs_finished);
1425 break;
1428 return 1;
1431 /* Create a `struct child' for FILE and start its commands running. */
1433 void
1434 new_job (struct file *file)
1436 register struct commands *cmds = file->cmds;
1437 register struct child *c;
1438 char **lines;
1439 register unsigned int i;
1441 /* Let any previously decided-upon jobs that are waiting
1442 for the load to go down start before this new one. */
1443 start_waiting_jobs ();
1445 /* Reap any children that might have finished recently. */
1446 reap_children (0, 0);
1448 /* Chop the commands up into lines if they aren't already. */
1449 chop_commands (cmds);
1451 /* Expand the command lines and store the results in LINES. */
1452 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1453 for (i = 0; i < cmds->ncommand_lines; ++i)
1455 /* Collapse backslash-newline combinations that are inside variable
1456 or function references. These are left alone by the parser so
1457 that they will appear in the echoing of commands (where they look
1458 nice); and collapsed by construct_command_argv when it tokenizes.
1459 But letting them survive inside function invocations loses because
1460 we don't want the functions to see them as part of the text. */
1462 char *in, *out, *ref;
1464 /* IN points to where in the line we are scanning.
1465 OUT points to where in the line we are writing.
1466 When we collapse a backslash-newline combination,
1467 IN gets ahead of OUT. */
1469 in = out = cmds->command_lines[i];
1470 while ((ref = strchr (in, '$')) != 0)
1472 ++ref; /* Move past the $. */
1474 if (out != in)
1475 /* Copy the text between the end of the last chunk
1476 we processed (where IN points) and the new chunk
1477 we are about to process (where REF points). */
1478 bcopy (in, out, ref - in);
1480 /* Move both pointers past the boring stuff. */
1481 out += ref - in;
1482 in = ref;
1484 if (*ref == '(' || *ref == '{')
1486 char openparen = *ref;
1487 char closeparen = openparen == '(' ? ')' : '}';
1488 int count;
1489 char *p;
1491 *out++ = *in++; /* Copy OPENPAREN. */
1492 /* IN now points past the opening paren or brace.
1493 Count parens or braces until it is matched. */
1494 count = 0;
1495 while (*in != '\0')
1497 if (*in == closeparen && --count < 0)
1498 break;
1499 else if (*in == '\\' && in[1] == '\n')
1501 /* We have found a backslash-newline inside a
1502 variable or function reference. Eat it and
1503 any following whitespace. */
1505 int quoted = 0;
1506 for (p = in - 1; p > ref && *p == '\\'; --p)
1507 quoted = !quoted;
1509 if (quoted)
1510 /* There were two or more backslashes, so this is
1511 not really a continuation line. We don't collapse
1512 the quoting backslashes here as is done in
1513 collapse_continuations, because the line will
1514 be collapsed again after expansion. */
1515 *out++ = *in++;
1516 else
1518 /* Skip the backslash, newline and
1519 any following whitespace. */
1520 in = next_token (in + 2);
1522 /* Discard any preceding whitespace that has
1523 already been written to the output. */
1524 while (out > ref
1525 && isblank ((unsigned char)out[-1]))
1526 --out;
1528 /* Replace it all with a single space. */
1529 *out++ = ' ';
1532 else
1534 if (*in == openparen)
1535 ++count;
1537 *out++ = *in++;
1543 /* There are no more references in this line to worry about.
1544 Copy the remaining uninteresting text to the output. */
1545 if (out != in)
1546 strcpy (out, in);
1548 /* Finally, expand the line. */
1549 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1550 file);
1553 /* Start the command sequence, record it in a new
1554 `struct child', and add that to the chain. */
1556 c = (struct child *) xmalloc (sizeof (struct child));
1557 bzero ((char *)c, sizeof (struct child));
1558 c->file = file;
1559 c->command_lines = lines;
1560 c->sh_batch_file = NULL;
1562 /* Fetch the first command line to be run. */
1563 job_next_command (c);
1565 /* Wait for a job slot to be freed up. If we allow an infinite number
1566 don't bother; also job_slots will == 0 if we're using the jobserver. */
1568 if (job_slots != 0)
1569 while (job_slots_used == job_slots)
1570 reap_children (1, 0);
1572 #ifdef MAKE_JOBSERVER
1573 /* If we are controlling multiple jobs make sure we have a token before
1574 starting the child. */
1576 /* This can be inefficient. There's a decent chance that this job won't
1577 actually have to run any subprocesses: the command script may be empty
1578 or otherwise optimized away. It would be nice if we could defer
1579 obtaining a token until just before we need it, in start_job_command.
1580 To do that we'd need to keep track of whether we'd already obtained a
1581 token (since start_job_command is called for each line of the job, not
1582 just once). Also more thought needs to go into the entire algorithm;
1583 this is where the old parallel job code waits, so... */
1585 else if (job_fds[0] >= 0)
1586 while (1)
1588 char token;
1589 int got_token;
1590 int saved_errno;
1592 DB (DB_JOBS, ("Need a job token; we %shave children\n",
1593 children ? "" : "don't "));
1595 /* If we don't already have a job started, use our "free" token. */
1596 if (!children)
1597 break;
1599 /* Read a token. As long as there's no token available we'll block.
1600 We enable interruptible system calls before the read(2) so that if
1601 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1602 we can process the death(s) and return tokens to the free pool.
1604 Once we return from the read, we immediately reinstate restartable
1605 system calls. This allows us to not worry about checking for
1606 EINTR on all the other system calls in the program.
1608 There is one other twist: there is a span between the time
1609 reap_children() does its last check for dead children and the time
1610 the read(2) call is entered, below, where if a child dies we won't
1611 notice. This is extremely serious as it could cause us to
1612 deadlock, given the right set of events.
1614 To avoid this, we do the following: before we reap_children(), we
1615 dup(2) the read FD on the jobserver pipe. The read(2) call below
1616 uses that new FD. In the signal handler, we close that FD. That
1617 way, if a child dies during the section mentioned above, the
1618 read(2) will be invoked with an invalid FD and will return
1619 immediately with EBADF. */
1621 /* Make sure we have a dup'd FD. */
1622 if (job_rfd < 0)
1624 DB (DB_JOBS, ("Duplicate the job FD\n"));
1625 job_rfd = dup (job_fds[0]);
1628 /* Reap anything that's currently waiting. */
1629 reap_children (0, 0);
1631 /* If our "free" token has become available, use it. */
1632 if (!children)
1633 break;
1635 /* Set interruptible system calls, and read() for a job token. */
1636 set_child_handler_action_flags (0);
1637 got_token = read (job_rfd, &token, 1);
1638 saved_errno = errno;
1639 #ifdef __EMX__
1640 /* The child handler must be turned off here. */
1641 signal (SIGCHLD, SIG_DFL);
1642 #endif
1643 set_child_handler_action_flags (SA_RESTART);
1645 /* If we got one, we're done here. */
1646 if (got_token == 1)
1648 DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1649 (unsigned long int) c, c->file->name));
1650 break;
1653 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1654 go back and reap_children(), and try again. */
1655 errno = saved_errno;
1656 if (errno != EINTR && errno != EBADF)
1657 pfatal_with_name (_("read jobs pipe"));
1658 if (errno == EBADF)
1659 DB (DB_JOBS, ("Read returned EBADF.\n"));
1661 #endif
1663 /* The job is now primed. Start it running.
1664 (This will notice if there are in fact no commands.) */
1665 (void) start_waiting_job (c);
1667 if (job_slots == 1 || not_parallel)
1668 /* Since there is only one job slot, make things run linearly.
1669 Wait for the child to die, setting the state to `cs_finished'. */
1670 while (file->command_state == cs_running)
1671 reap_children (1, 0);
1673 return;
1676 /* Move CHILD's pointers to the next command for it to execute.
1677 Returns nonzero if there is another command. */
1679 static int
1680 job_next_command (struct child *child)
1682 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1684 /* There are no more lines in the expansion of this line. */
1685 if (child->command_line == child->file->cmds->ncommand_lines)
1687 /* There are no more lines to be expanded. */
1688 child->command_ptr = 0;
1689 return 0;
1691 else
1692 /* Get the next line to run. */
1693 child->command_ptr = child->command_lines[child->command_line++];
1695 return 1;
1698 /* Determine if the load average on the system is too high to start a new job.
1699 The real system load average is only recomputed once a second. However, a
1700 very parallel make can easily start tens or even hundreds of jobs in a
1701 second, which brings the system to its knees for a while until that first
1702 batch of jobs clears out.
1704 To avoid this we use a weighted algorithm to try to account for jobs which
1705 have been started since the last second, and guess what the load average
1706 would be now if it were computed.
1708 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1709 who writes:
1711 ! calculate something load-oid and add to the observed sys.load,
1712 ! so that latter can catch up:
1713 ! - every job started increases jobctr;
1714 ! - every dying job decreases a positive jobctr;
1715 ! - the jobctr value gets zeroed every change of seconds,
1716 ! after its value*weight_b is stored into the 'backlog' value last_sec
1717 ! - weight_a times the sum of jobctr and last_sec gets
1718 ! added to the observed sys.load.
1720 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1721 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1722 ! sub-shelled commands (rm, echo, sed...) for tests.
1723 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1724 ! resulted in significant excession of the load limit, raising it
1725 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1726 ! reach the limit in most test cases.
1728 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1729 ! exceeding the limit for longer-running stuff (compile jobs in
1730 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1731 ! small jobs' effects.
1735 #define LOAD_WEIGHT_A 0.25
1736 #define LOAD_WEIGHT_B 0.25
1738 static int
1739 load_too_high (void)
1741 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
1742 return 1;
1743 #else
1744 static double last_sec;
1745 static time_t last_now;
1746 double load, guess;
1747 time_t now;
1749 if (max_load_average < 0)
1750 return 0;
1752 /* Find the real system load average. */
1753 make_access ();
1754 if (getloadavg (&load, 1) != 1)
1756 static int lossage = -1;
1757 /* Complain only once for the same error. */
1758 if (lossage == -1 || errno != lossage)
1760 if (errno == 0)
1761 /* An errno value of zero means getloadavg is just unsupported. */
1762 error (NILF,
1763 _("cannot enforce load limits on this operating system"));
1764 else
1765 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1767 lossage = errno;
1768 load = 0;
1770 user_access ();
1772 /* If we're in a new second zero the counter and correct the backlog
1773 value. Only keep the backlog for one extra second; after that it's 0. */
1774 now = time (NULL);
1775 if (last_now < now)
1777 if (last_now == now - 1)
1778 last_sec = LOAD_WEIGHT_B * job_counter;
1779 else
1780 last_sec = 0.0;
1782 job_counter = 0;
1783 last_now = now;
1786 /* Try to guess what the load would be right now. */
1787 guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
1789 DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1790 guess, load, max_load_average));
1792 return guess >= max_load_average;
1793 #endif
1796 /* Start jobs that are waiting for the load to be lower. */
1798 void
1799 start_waiting_jobs (void)
1801 struct child *job;
1803 if (waiting_jobs == 0)
1804 return;
1808 /* Check for recently deceased descendants. */
1809 reap_children (0, 0);
1811 /* Take a job off the waiting list. */
1812 job = waiting_jobs;
1813 waiting_jobs = job->next;
1815 /* Try to start that job. We break out of the loop as soon
1816 as start_waiting_job puts one back on the waiting list. */
1818 while (start_waiting_job (job) && waiting_jobs != 0);
1820 return;
1823 #ifndef WINDOWS32
1824 #ifdef VMS
1825 #include <descrip.h>
1826 #include <clidef.h>
1828 /* This is called as an AST when a child process dies (it won't get
1829 interrupted by anything except a higher level AST).
1831 int vmsHandleChildTerm(struct child *child)
1833 int status;
1834 register struct child *lastc, *c;
1835 int child_failed;
1837 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1839 lib$free_ef(&child->efn);
1841 (void) sigblock (fatal_signal_mask);
1843 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1845 /* Search for a child matching the deceased one. */
1846 lastc = 0;
1847 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1848 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1849 #else
1850 c = child;
1851 #endif
1853 if (child_failed && !c->noerror && !ignore_errors_flag)
1855 /* The commands failed. Write an error message,
1856 delete non-precious targets, and abort. */
1857 child_error (c->file->name, c->cstatus, 0, 0, 0);
1858 c->file->update_status = 1;
1859 delete_child_targets (c);
1861 else
1863 if (child_failed)
1865 /* The commands failed, but we don't care. */
1866 child_error (c->file->name, c->cstatus, 0, 0, 1);
1867 child_failed = 0;
1870 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1871 /* If there are more commands to run, try to start them. */
1872 start_job (c);
1874 switch (c->file->command_state)
1876 case cs_running:
1877 /* Successfully started. */
1878 break;
1880 case cs_finished:
1881 if (c->file->update_status != 0) {
1882 /* We failed to start the commands. */
1883 delete_child_targets (c);
1885 break;
1887 default:
1888 error (NILF, _("internal error: `%s' command_state"),
1889 c->file->name);
1890 abort ();
1891 break;
1893 #endif /* RECURSIVEJOBS */
1896 /* Set the state flag to say the commands have finished. */
1897 c->file->command_state = cs_finished;
1898 notice_finished_file (c->file);
1900 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1901 /* Remove the child from the chain and free it. */
1902 if (lastc == 0)
1903 children = c->next;
1904 else
1905 lastc->next = c->next;
1906 free_child (c);
1907 #endif /* RECURSIVEJOBS */
1909 /* There is now another slot open. */
1910 if (job_slots_used > 0)
1911 --job_slots_used;
1913 /* If the job failed, and the -k flag was not given, die. */
1914 if (child_failed && !keep_going_flag)
1915 die (EXIT_FAILURE);
1917 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1919 return 1;
1922 /* VMS:
1923 Spawn a process executing the command in ARGV and return its pid. */
1925 #define MAXCMDLEN 200
1927 /* local helpers to make ctrl+c and ctrl+y working, see below */
1928 #include <iodef.h>
1929 #include <libclidef.h>
1930 #include <ssdef.h>
1932 static int ctrlMask= LIB$M_CLI_CTRLY;
1933 static int oldCtrlMask;
1934 static int setupYAstTried= 0;
1935 static int pidToAbort= 0;
1936 static int chan= 0;
1938 static void reEnableAst(void) {
1939 lib$enable_ctrl (&oldCtrlMask,0);
1942 static astHandler (void) {
1943 if (pidToAbort) {
1944 sys$forcex (&pidToAbort, 0, SS$_ABORT);
1945 pidToAbort= 0;
1947 kill (getpid(),SIGQUIT);
1950 static void tryToSetupYAst(void) {
1951 $DESCRIPTOR(inputDsc,"SYS$COMMAND");
1952 int status;
1953 struct {
1954 short int status, count;
1955 int dvi;
1956 } iosb;
1958 setupYAstTried++;
1960 if (!chan) {
1961 status= sys$assign(&inputDsc,&chan,0,0);
1962 if (!(status&SS$_NORMAL)) {
1963 lib$signal(status);
1964 return;
1967 status= sys$qiow (0, chan, IO$_SETMODE|IO$M_CTRLYAST,&iosb,0,0,
1968 astHandler,0,0,0,0,0);
1969 if (status==SS$_NORMAL)
1970 status= iosb.status;
1971 if (status==SS$_ILLIOFUNC || status==SS$_NOPRIV) {
1972 sys$dassgn(chan);
1973 #ifdef CTRLY_ENABLED_ANYWAY
1974 fprintf (stderr,
1975 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
1976 #else
1977 return;
1978 #endif
1980 else if (!(status&SS$_NORMAL)) {
1981 sys$dassgn(chan);
1982 lib$signal(status);
1983 return;
1986 /* called from AST handler ? */
1987 if (setupYAstTried>1)
1988 return;
1989 if (atexit(reEnableAst))
1990 fprintf (stderr,
1991 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
1992 status= lib$disable_ctrl (&ctrlMask, &oldCtrlMask);
1993 if (!(status&SS$_NORMAL)) {
1994 lib$signal(status);
1995 return;
1999 child_execute_job (char *argv, struct child *child)
2001 int i;
2002 static struct dsc$descriptor_s cmddsc;
2003 static struct dsc$descriptor_s pnamedsc;
2004 static struct dsc$descriptor_s ifiledsc;
2005 static struct dsc$descriptor_s ofiledsc;
2006 static struct dsc$descriptor_s efiledsc;
2007 int have_redirection = 0;
2008 int have_newline = 0;
2010 int spflags = CLI$M_NOWAIT;
2011 int status;
2012 char *cmd = alloca (strlen (argv) + 512), *p, *q;
2013 char ifile[256], ofile[256], efile[256];
2014 char *comname = 0;
2015 char procname[100];
2017 /* Parse IO redirection. */
2019 ifile[0] = 0;
2020 ofile[0] = 0;
2021 efile[0] = 0;
2023 DB (DB_JOBS, ("child_execute_job (%s)\n", argv));
2025 while (isspace ((unsigned char)*argv))
2026 argv++;
2028 if (*argv == 0)
2029 return 0;
2031 sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
2032 pnamedsc.dsc$w_length = strlen(procname);
2033 pnamedsc.dsc$a_pointer = procname;
2034 pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
2035 pnamedsc.dsc$b_class = DSC$K_CLASS_S;
2037 /* Handle comments and redirection. */
2038 for (p = argv, q = cmd; *p; p++, q++)
2040 switch (*p)
2042 case '#':
2043 *p-- = 0;
2044 *q-- = 0;
2045 break;
2046 case '\\':
2047 p++;
2048 if (*p == '\n')
2049 p++;
2050 if (isspace ((unsigned char)*p))
2052 do { p++; } while (isspace ((unsigned char)*p));
2053 p--;
2055 *q = *p;
2056 break;
2057 case '<':
2058 p = vms_redirect (&ifiledsc, ifile, p);
2059 *q = ' ';
2060 have_redirection = 1;
2061 break;
2062 case '>':
2063 have_redirection = 1;
2064 if (*(p-1) == '2')
2066 q--;
2067 if (strncmp (p, ">&1", 3) == 0)
2069 p += 3;
2070 strcpy (efile, "sys$output");
2071 efiledsc.dsc$w_length = strlen(efile);
2072 efiledsc.dsc$a_pointer = efile;
2073 efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
2074 efiledsc.dsc$b_class = DSC$K_CLASS_S;
2076 else
2078 p = vms_redirect (&efiledsc, efile, p);
2081 else
2083 p = vms_redirect (&ofiledsc, ofile, p);
2085 *q = ' ';
2086 break;
2087 case '\n':
2088 have_newline = 1;
2089 default:
2090 *q = *p;
2091 break;
2094 *q = *p;
2096 if (strncmp (cmd, "builtin_", 8) == 0)
2098 child->pid = 270163;
2099 child->efn = 0;
2100 child->cstatus = 1;
2102 DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));
2104 p = cmd + 8;
2106 if ((*(p) == 'c')
2107 && (*(p+1) == 'd')
2108 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
2110 p += 3;
2111 while ((*p == ' ') || (*p == '\t'))
2112 p++;
2113 DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
2114 if (chdir (p))
2115 return 0;
2116 else
2117 return 1;
2119 else if ((*(p) == 'r')
2120 && (*(p+1) == 'm')
2121 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
2123 int in_arg;
2125 /* rm */
2126 p += 3;
2127 while ((*p == ' ') || (*p == '\t'))
2128 p++;
2129 in_arg = 1;
2131 DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
2132 while (*p)
2134 switch (*p)
2136 case ' ':
2137 case '\t':
2138 if (in_arg)
2140 *p++ = ';';
2141 in_arg = 0;
2143 break;
2144 default:
2145 break;
2147 p++;
2150 else
2152 printf(_("Unknown builtin command '%s'\n"), cmd);
2153 fflush(stdout);
2154 return 0;
2158 /* Create a *.com file if either the command is too long for
2159 lib$spawn, or the command contains a newline, or if redirection
2160 is desired. Forcing commands with newlines into DCLs allows to
2161 store search lists on user mode logicals. */
2163 if (strlen (cmd) > MAXCMDLEN
2164 || (have_redirection != 0)
2165 || (have_newline != 0))
2167 FILE *outfile;
2168 char c;
2169 char *sep;
2170 int alevel = 0; /* apostrophe level */
2172 if (strlen (cmd) == 0)
2174 printf (_("Error, empty command\n"));
2175 fflush (stdout);
2176 return 0;
2179 outfile = open_tmpfile (&comname, "sys$scratch:CMDXXXXXX.COM");
2180 if (outfile == 0)
2181 pfatal_with_name (_("fopen (temporary file)"));
2183 if (ifile[0])
2185 fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
2186 DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
2187 ifiledsc.dsc$w_length = 0;
2190 if (efile[0])
2192 fprintf (outfile, "$ define sys$error %s\n", efile);
2193 DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
2194 efiledsc.dsc$w_length = 0;
2197 if (ofile[0])
2199 fprintf (outfile, "$ define sys$output %s\n", ofile);
2200 DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
2201 ofiledsc.dsc$w_length = 0;
2204 p = sep = q = cmd;
2205 for (c = '\n'; c; c = *q++)
2207 switch (c)
2209 case '\n':
2210 /* At a newline, skip any whitespace around a leading $
2211 from the command and issue exactly one $ into the DCL. */
2212 while (isspace ((unsigned char)*p))
2213 p++;
2214 if (*p == '$')
2215 p++;
2216 while (isspace ((unsigned char)*p))
2217 p++;
2218 fwrite (p, 1, q - p, outfile);
2219 fputc ('$', outfile);
2220 fputc (' ', outfile);
2221 /* Reset variables. */
2222 p = sep = q;
2223 break;
2225 /* Nice places for line breaks are after strings, after
2226 comma or space and before slash. */
2227 case '"':
2228 q = vms_handle_apos (q);
2229 sep = q;
2230 break;
2231 case ',':
2232 case ' ':
2233 sep = q;
2234 break;
2235 case '/':
2236 case '\0':
2237 sep = q - 1;
2238 break;
2239 default:
2240 break;
2242 if (sep - p > 78)
2244 /* Enough stuff for a line. */
2245 fwrite (p, 1, sep - p, outfile);
2246 p = sep;
2247 if (*sep)
2249 /* The command continues. */
2250 fputc ('-', outfile);
2252 fputc ('\n', outfile);
2256 fwrite (p, 1, q - p, outfile);
2257 fputc ('\n', outfile);
2259 fclose (outfile);
2261 sprintf (cmd, "$ @%s", comname);
2263 DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
2266 cmddsc.dsc$w_length = strlen(cmd);
2267 cmddsc.dsc$a_pointer = cmd;
2268 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
2269 cmddsc.dsc$b_class = DSC$K_CLASS_S;
2271 child->efn = 0;
2272 while (child->efn < 32 || child->efn > 63)
2274 status = lib$get_ef ((unsigned long *)&child->efn);
2275 if (!(status & 1))
2276 return 0;
2279 sys$clref (child->efn);
2281 vms_jobsefnmask |= (1 << (child->efn - 32));
2284 LIB$SPAWN [command-string]
2285 [,input-file]
2286 [,output-file]
2287 [,flags]
2288 [,process-name]
2289 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2290 [,AST-address] [,varying-AST-argument]
2291 [,prompt-string] [,cli] [,table]
2294 #ifndef DONTWAITFORCHILD
2296 * Code to make ctrl+c and ctrl+y working.
2297 * The problem starts with the synchronous case where after lib$spawn is
2298 * called any input will go to the child. But with input re-directed,
2299 * both control characters won't make it to any of the programs, neither
2300 * the spawning nor to the spawned one. Hence the caller needs to spawn
2301 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2302 * has to follow to simulate the wanted synchronous behaviour.
2303 * The next problem is ctrl+y which isn't caught by the crtl and
2304 * therefore isn't converted to SIGQUIT (for a signal handler which is
2305 * already established). The only way to catch ctrl+y, is an AST
2306 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2307 * disabled, otherwise it will handle it. Not to mention the previous
2308 * ctrl+y handling of DCL needs to be re-established before make exits.
2309 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2310 * make it to the signal handler after the child "normally" terminates.
2311 * This isn't enough. It seems reasonable for simple command lines like
2312 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2313 * spawning make. Therefore we need to abort the process in the AST.
2315 * Prior to the spawn it is checked if an AST is already set up for
2316 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2317 * this will work except if make is run in a batch environment, but there
2318 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2319 * is disabled and an exit handler is established to re-enable it.
2320 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2321 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2322 * the already established handler and will bring us back to common code.
2323 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2324 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2325 * which the crtl converts to SIGINT and which is caught by the common
2326 * signal handler. Because signals were blocked before entering this code
2327 * sys$waitfr will always complete and the SIGQUIT will be processed after
2328 * it (after termination of the current block, somewhere in common code).
2329 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2330 * current command completes. Anyway it's better than nothing :-)
2333 if (!setupYAstTried)
2334 tryToSetupYAst();
2335 status = lib$spawn (&cmddsc, /* cmd-string */
2336 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file */
2337 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
2338 &spflags, /* flags */
2339 &pnamedsc, /* proc name */
2340 &child->pid, &child->cstatus, &child->efn,
2341 0, 0,
2342 0, 0, 0);
2343 if (status & 1)
2345 pidToAbort= child->pid;
2346 status= sys$waitfr (child->efn);
2347 pidToAbort= 0;
2348 vmsHandleChildTerm(child);
2350 #else
2351 status = lib$spawn (&cmddsc,
2352 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
2353 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
2354 &spflags,
2355 &pnamedsc,
2356 &child->pid, &child->cstatus, &child->efn,
2357 vmsHandleChildTerm, child,
2358 0, 0, 0);
2359 #endif
2361 if (!(status & 1))
2363 printf (_("Error spawning, %d\n") ,status);
2364 fflush (stdout);
2365 switch (status)
2367 case 0x1c:
2368 errno = EPROCLIM;
2369 break;
2370 default:
2371 errno = EFAIL;
2375 if (comname && !ISDB (DB_JOBS))
2376 unlink (comname);
2378 return (status & 1);
2381 #else /* !VMS */
2383 /* EMX: Start a child process. This function returns the new pid. */
2384 # if defined __MSDOS__ || defined __EMX__
2386 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2388 int pid;
2389 /* stdin_fd == 0 means: nothing to do for stdin;
2390 stdout_fd == 1 means: nothing to do for stdout */
2391 int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
2392 int save_stdout = (stdout_fd != 1) ? dup (1): 1;
2394 /* < 0 only if dup() failed */
2395 if (save_stdin < 0)
2396 fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
2397 if (save_stdout < 0)
2398 fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
2400 /* Close unnecessary file handles for the child. */
2401 if (save_stdin != 0)
2402 CLOSE_ON_EXEC (save_stdin);
2403 if (save_stdout != 1)
2404 CLOSE_ON_EXEC (save_stdout);
2406 /* Connect the pipes to the child process. */
2407 if (stdin_fd != 0)
2408 (void) dup2 (stdin_fd, 0);
2409 if (stdout_fd != 1)
2410 (void) dup2 (stdout_fd, 1);
2412 /* stdin_fd and stdout_fd must be closed on exit because we are
2413 still in the parent process */
2414 if (stdin_fd != 0)
2415 CLOSE_ON_EXEC (stdin_fd);
2416 if (stdout_fd != 1)
2417 CLOSE_ON_EXEC (stdout_fd);
2419 /* Run the command. */
2420 pid = exec_command (argv, envp);
2422 /* Restore stdout/stdin of the parent and close temporary FDs. */
2423 if (stdin_fd != 0)
2425 if (dup2 (save_stdin, 0) != 0)
2426 fatal (NILF, _("Could not restore stdin\n"));
2427 else
2428 close (save_stdin);
2431 if (stdout_fd != 1)
2433 if (dup2 (save_stdout, 1) != 1)
2434 fatal (NILF, _("Could not restore stdout\n"));
2435 else
2436 close (save_stdout);
2439 return pid;
2442 #elif !defined (_AMIGA) && !defined (__MSDOS__)
2444 /* UNIX:
2445 Replace the current process with one executing the command in ARGV.
2446 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2447 the environment of the new program. This function does not return. */
2448 void
2449 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2451 if (stdin_fd != 0)
2452 (void) dup2 (stdin_fd, 0);
2453 if (stdout_fd != 1)
2454 (void) dup2 (stdout_fd, 1);
2455 if (stdin_fd != 0)
2456 (void) close (stdin_fd);
2457 if (stdout_fd != 1)
2458 (void) close (stdout_fd);
2460 /* Run the command. */
2461 exec_command (argv, envp);
2463 #endif /* !AMIGA && !__MSDOS__ */
2464 #endif /* !VMS */
2465 #endif /* !WINDOWS32 */
2467 #ifndef _AMIGA
2468 /* Replace the current process with one running the command in ARGV,
2469 with environment ENVP. This function does not return. */
2471 /* EMX: This function returns the pid of the child process. */
2472 # ifdef __EMX__
2474 # else
2475 void
2476 # endif
2477 exec_command (char **argv, char **envp)
2479 #ifdef VMS
2480 /* to work around a problem with signals and execve: ignore them */
2481 #ifdef SIGCHLD
2482 signal (SIGCHLD,SIG_IGN);
2483 #endif
2484 /* Run the program. */
2485 execve (argv[0], argv, envp);
2486 perror_with_name ("execve: ", argv[0]);
2487 _exit (EXIT_FAILURE);
2488 #else
2489 #ifdef WINDOWS32
2490 HANDLE hPID;
2491 HANDLE hWaitPID;
2492 int err = 0;
2493 int exit_code = EXIT_FAILURE;
2495 /* make sure CreateProcess() has Path it needs */
2496 sync_Path_environment();
2498 /* launch command */
2499 hPID = process_easy(argv, envp);
2501 /* make sure launch ok */
2502 if (hPID == INVALID_HANDLE_VALUE)
2504 int i;
2505 fprintf(stderr,
2506 _("process_easy() failed failed to launch process (e=%d)\n"),
2507 process_last_err(hPID));
2508 for (i = 0; argv[i]; i++)
2509 fprintf(stderr, "%s ", argv[i]);
2510 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2511 exit(EXIT_FAILURE);
2514 /* wait and reap last child */
2515 hWaitPID = process_wait_for_any();
2516 while (hWaitPID)
2518 /* was an error found on this process? */
2519 err = process_last_err(hWaitPID);
2521 /* get exit data */
2522 exit_code = process_exit_code(hWaitPID);
2524 if (err)
2525 fprintf(stderr, "make (e=%d, rc=%d): %s",
2526 err, exit_code, map_windows32_error_to_string(err));
2528 /* cleanup process */
2529 process_cleanup(hWaitPID);
2531 /* expect to find only last pid, warn about other pids reaped */
2532 if (hWaitPID == hPID)
2533 break;
2534 else
2535 fprintf(stderr,
2536 _("make reaped child pid %d, still waiting for pid %d\n"),
2537 hWaitPID, hPID);
2540 /* return child's exit code as our exit code */
2541 exit(exit_code);
2543 #else /* !WINDOWS32 */
2545 # ifdef __EMX__
2546 int pid;
2547 # endif
2549 /* Be the user, permanently. */
2550 child_access ();
2552 # ifdef __EMX__
2554 /* Run the program. */
2555 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2557 if (pid >= 0)
2558 return pid;
2560 /* the file might have a strange shell extension */
2561 if (errno == ENOENT)
2562 errno = ENOEXEC;
2564 # else
2566 /* Run the program. */
2567 environ = envp;
2568 execvp (argv[0], argv);
2570 # endif /* !__EMX__ */
2572 switch (errno)
2574 case ENOENT:
2575 error (NILF, _("%s: Command not found"), argv[0]);
2576 break;
2577 case ENOEXEC:
2579 /* The file is not executable. Try it as a shell script. */
2580 extern char *getenv ();
2581 char *shell;
2582 char **new_argv;
2583 int argc;
2584 int i=1;
2586 # ifdef __EMX__
2587 /* Do not use $SHELL from the environment */
2588 struct variable *p = lookup_variable ("SHELL", 5);
2589 if (p)
2590 shell = p->value;
2591 else
2592 shell = 0;
2593 # else
2594 shell = getenv ("SHELL");
2595 # endif
2596 if (shell == 0)
2597 shell = default_shell;
2599 argc = 1;
2600 while (argv[argc] != 0)
2601 ++argc;
2603 # ifdef __EMX__
2604 if (!unixy_shell)
2605 ++argc;
2606 # endif
2608 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
2609 new_argv[0] = shell;
2611 # ifdef __EMX__
2612 if (!unixy_shell)
2614 new_argv[1] = "/c";
2615 ++i;
2616 --argc;
2618 # endif
2620 new_argv[i] = argv[0];
2621 while (argc > 0)
2623 new_argv[i + argc] = argv[argc];
2624 --argc;
2627 # ifdef __EMX__
2628 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2629 if (pid >= 0)
2630 break;
2631 # else
2632 execvp (shell, new_argv);
2633 # endif
2634 if (errno == ENOENT)
2635 error (NILF, _("%s: Shell program not found"), shell);
2636 else
2637 perror_with_name ("execvp: ", shell);
2638 break;
2641 # ifdef __EMX__
2642 case EINVAL:
2643 /* this nasty error was driving me nuts :-( */
2644 error (NILF, _("spawnvpe: environment space might be exhausted"));
2645 /* FALLTHROUGH */
2646 # endif
2648 default:
2649 perror_with_name ("execvp: ", argv[0]);
2650 break;
2653 # ifdef __EMX__
2654 return pid;
2655 # else
2656 _exit (127);
2657 # endif
2658 #endif /* !WINDOWS32 */
2659 #endif /* !VMS */
2661 #else /* On Amiga */
2662 void exec_command (char **argv,char **envp)
2664 MyExecute (argv,envp,NULL);
2667 void clean_tmp (void)
2669 DeleteFile (amiga_bname);
2672 #endif /* On Amiga */
2674 #ifndef VMS
2675 /* Figure out the argument list necessary to run LINE as a command. Try to
2676 avoid using a shell. This routine handles only ' quoting, and " quoting
2677 when no backslash, $ or ` characters are seen in the quotes. Starting
2678 quotes may be escaped with a backslash. If any of the characters in
2679 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2680 is the first word of a line, the shell is used.
2682 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2683 If *RESTP is NULL, newlines will be ignored.
2685 SHELL is the shell to use, or nil to use the default shell.
2686 IFS is the value of $IFS, or nil (meaning the default). */
2688 static char **
2689 construct_command_argv_internal (char *line, char **restp, char *shell,
2690 char *ifs, char **batch_filename_ptr)
2692 #ifdef __MSDOS__
2693 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2694 We call `system' for anything that requires ``slow'' processing,
2695 because DOS shells are too dumb. When $SHELL points to a real
2696 (unix-style) shell, `system' just calls it to do everything. When
2697 $SHELL points to a DOS shell, `system' does most of the work
2698 internally, calling the shell only for its internal commands.
2699 However, it looks on the $PATH first, so you can e.g. have an
2700 external command named `mkdir'.
2702 Since we call `system', certain characters and commands below are
2703 actually not specific to COMMAND.COM, but to the DJGPP implementation
2704 of `system'. In particular:
2706 The shell wildcard characters are in DOS_CHARS because they will
2707 not be expanded if we call the child via `spawnXX'.
2709 The `;' is in DOS_CHARS, because our `system' knows how to run
2710 multiple commands on a single line.
2712 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2713 won't have to tell one from another and have one more set of
2714 commands and special characters. */
2715 static char sh_chars_dos[] = "*?[];|<>%^&()";
2716 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2717 "copy", "ctty", "date", "del", "dir", "echo",
2718 "erase", "exit", "for", "goto", "if", "md",
2719 "mkdir", "path", "pause", "prompt", "rd",
2720 "rmdir", "rem", "ren", "rename", "set",
2721 "shift", "time", "type", "ver", "verify",
2722 "vol", ":", 0 };
2724 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2725 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2726 "logout", "set", "umask", "wait", "while",
2727 "for", "case", "if", ":", ".", "break",
2728 "continue", "export", "read", "readonly",
2729 "shift", "times", "trap", "switch", "unset",
2730 0 };
2732 char *sh_chars;
2733 char **sh_cmds;
2734 #elif defined (__EMX__)
2735 static char sh_chars_dos[] = "*?[];|<>%^&()";
2736 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2737 "copy", "ctty", "date", "del", "dir", "echo",
2738 "erase", "exit", "for", "goto", "if", "md",
2739 "mkdir", "path", "pause", "prompt", "rd",
2740 "rmdir", "rem", "ren", "rename", "set",
2741 "shift", "time", "type", "ver", "verify",
2742 "vol", ":", 0 };
2744 static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
2745 static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2746 "date", "del", "detach", "dir", "echo",
2747 "endlocal", "erase", "exit", "for", "goto", "if",
2748 "keys", "md", "mkdir", "move", "path", "pause",
2749 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2750 "set", "setlocal", "shift", "start", "time",
2751 "type", "ver", "verify", "vol", ":", 0 };
2753 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~'";
2754 static char *sh_cmds_sh[] = { "echo", "cd", "eval", "exec", "exit", "login",
2755 "logout", "set", "umask", "wait", "while",
2756 "for", "case", "if", ":", ".", "break",
2757 "continue", "export", "read", "readonly",
2758 "shift", "times", "trap", "switch", "unset",
2759 0 };
2760 char *sh_chars;
2761 char **sh_cmds;
2763 #elif defined (_AMIGA)
2764 static char sh_chars[] = "#;\"|<>()?*$`";
2765 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2766 "rename", "set", "setenv", "date", "makedir",
2767 "skip", "else", "endif", "path", "prompt",
2768 "unset", "unsetenv", "version",
2769 0 };
2770 #elif defined (WINDOWS32)
2771 static char sh_chars_dos[] = "\"|&<>";
2772 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2773 "copy", "ctty", "date", "del", "dir", "echo",
2774 "erase", "exit", "for", "goto", "if", "if", "md",
2775 "mkdir", "path", "pause", "prompt", "rd", "rem",
2776 "ren", "rename", "rmdir", "set", "shift", "time",
2777 "type", "ver", "verify", "vol", ":", 0 };
2778 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2779 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2780 "logout", "set", "umask", "wait", "while", "for",
2781 "case", "if", ":", ".", "break", "continue",
2782 "export", "read", "readonly", "shift", "times",
2783 "trap", "switch", "test",
2784 #ifdef BATCH_MODE_ONLY_SHELL
2785 "echo",
2786 #endif
2787 0 };
2788 char* sh_chars;
2789 char** sh_cmds;
2790 #elif defined(__riscos__)
2791 static char sh_chars[] = "";
2792 static char *sh_cmds[] = { 0 };
2793 #else /* must be UNIX-ish */
2794 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~!";
2795 static char *sh_cmds[] = { ".", ":", "break", "case", "cd", "continue",
2796 "eval", "exec", "exit", "export", "for", "if",
2797 "login", "logout", "read", "readonly", "set",
2798 "shift", "switch", "test", "times", "trap",
2799 "umask", "wait", "while", 0 };
2800 #endif
2801 register int i;
2802 register char *p;
2803 register char *ap;
2804 char *end;
2805 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2806 char **new_argv = 0;
2807 #ifdef WINDOWS32
2808 int slow_flag = 0;
2810 if (no_default_sh_exe) {
2811 sh_cmds = sh_cmds_dos;
2812 sh_chars = sh_chars_dos;
2813 } else {
2814 sh_cmds = sh_cmds_sh;
2815 sh_chars = sh_chars_sh;
2817 #endif /* WINDOWS32 */
2819 if (restp != NULL)
2820 *restp = NULL;
2822 /* Make sure not to bother processing an empty line. */
2823 while (isblank ((unsigned char)*line))
2824 ++line;
2825 if (*line == '\0')
2826 return 0;
2828 /* See if it is safe to parse commands internally. */
2829 if (shell == 0)
2830 shell = default_shell;
2831 #ifdef WINDOWS32
2832 else if (strcmp (shell, default_shell))
2834 char *s1 = _fullpath(NULL, shell, 0);
2835 char *s2 = _fullpath(NULL, default_shell, 0);
2837 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2839 if (s1)
2840 free (s1);
2841 if (s2)
2842 free (s2);
2844 if (slow_flag)
2845 goto slow;
2846 #else /* not WINDOWS32 */
2847 #if defined (__MSDOS__) || defined (__EMX__)
2848 else if (stricmp (shell, default_shell))
2850 extern int _is_unixy_shell (const char *_path);
2852 DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
2853 default_shell, shell));
2854 unixy_shell = _is_unixy_shell (shell);
2855 /* we must allocate a copy of shell: construct_command_argv() will free
2856 * shell after this function returns. */
2857 default_shell = xstrdup (shell);
2859 if (unixy_shell)
2861 sh_chars = sh_chars_sh;
2862 sh_cmds = sh_cmds_sh;
2864 else
2866 sh_chars = sh_chars_dos;
2867 sh_cmds = sh_cmds_dos;
2868 # ifdef __EMX__
2869 if (_osmode == OS2_MODE)
2871 sh_chars = sh_chars_os2;
2872 sh_cmds = sh_cmds_os2;
2874 # endif
2876 #else /* !__MSDOS__ */
2877 else if (strcmp (shell, default_shell))
2878 goto slow;
2879 #endif /* !__MSDOS__ && !__EMX__ */
2880 #endif /* not WINDOWS32 */
2882 if (ifs != 0)
2883 for (ap = ifs; *ap != '\0'; ++ap)
2884 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2885 goto slow;
2887 i = strlen (line) + 1;
2889 /* More than 1 arg per character is impossible. */
2890 new_argv = (char **) xmalloc (i * sizeof (char *));
2892 /* All the args can fit in a buffer as big as LINE is. */
2893 ap = new_argv[0] = (char *) xmalloc (i);
2894 end = ap + i;
2896 /* I is how many complete arguments have been found. */
2897 i = 0;
2898 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2899 for (p = line; *p != '\0'; ++p)
2901 if (ap > end)
2902 abort ();
2904 if (instring)
2906 string_char:
2907 /* Inside a string, just copy any char except a closing quote
2908 or a backslash-newline combination. */
2909 if (*p == instring)
2911 instring = 0;
2912 if (ap == new_argv[0] || *(ap-1) == '\0')
2913 last_argument_was_empty = 1;
2915 else if (*p == '\\' && p[1] == '\n')
2916 goto swallow_escaped_newline;
2917 else if (*p == '\n' && restp != NULL)
2919 /* End of the command line. */
2920 *restp = p;
2921 goto end_of_line;
2923 /* Backslash, $, and ` are special inside double quotes.
2924 If we see any of those, punt.
2925 But on MSDOS, if we use COMMAND.COM, double and single
2926 quotes have the same effect. */
2927 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2928 goto slow;
2929 else
2930 *ap++ = *p;
2932 else if (strchr (sh_chars, *p) != 0)
2933 /* Not inside a string, but it's a special char. */
2934 goto slow;
2935 #ifdef __MSDOS__
2936 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2937 /* `...' is a wildcard in DJGPP. */
2938 goto slow;
2939 #endif
2940 else
2941 /* Not a special char. */
2942 switch (*p)
2944 case '=':
2945 /* Equals is a special character in leading words before the
2946 first word with no equals sign in it. This is not the case
2947 with sh -k, but we never get here when using nonstandard
2948 shell flags. */
2949 if (! seen_nonequals && unixy_shell)
2950 goto slow;
2951 word_has_equals = 1;
2952 *ap++ = '=';
2953 break;
2955 case '\\':
2956 /* Backslash-newline combinations are eaten. */
2957 if (p[1] == '\n')
2959 swallow_escaped_newline:
2961 /* Eat the backslash, the newline, and following whitespace,
2962 replacing it all with a single space. */
2963 p += 2;
2965 /* If there is a tab after a backslash-newline,
2966 remove it from the source line which will be echoed,
2967 since it was most likely used to line
2968 up the continued line with the previous one. */
2969 if (*p == '\t')
2970 /* Note these overlap and strcpy() is undefined for
2971 overlapping objects in ANSI C. The strlen() _IS_ right,
2972 since we need to copy the nul byte too. */
2973 bcopy (p + 1, p, strlen (p));
2975 if (instring)
2976 goto string_char;
2977 else
2979 if (ap != new_argv[i])
2980 /* Treat this as a space, ending the arg.
2981 But if it's at the beginning of the arg, it should
2982 just get eaten, rather than becoming an empty arg. */
2983 goto end_of_arg;
2984 else
2985 p = next_token (p) - 1;
2988 else if (p[1] != '\0')
2990 #ifdef HAVE_DOS_PATHS
2991 /* Only remove backslashes before characters special
2992 to Unixy shells. All other backslashes are copied
2993 verbatim, since they are probably DOS-style
2994 directory separators. This still leaves a small
2995 window for problems, but at least it should work
2996 for the vast majority of naive users. */
2998 #ifdef __MSDOS__
2999 /* A dot is only special as part of the "..."
3000 wildcard. */
3001 if (strneq (p + 1, ".\\.\\.", 5))
3003 *ap++ = '.';
3004 *ap++ = '.';
3005 p += 4;
3007 else
3008 #endif
3009 if (p[1] != '\\' && p[1] != '\''
3010 && !isspace ((unsigned char)p[1])
3011 && (strchr (sh_chars_sh, p[1]) == 0))
3012 /* back up one notch, to copy the backslash */
3013 --p;
3014 #endif /* HAVE_DOS_PATHS */
3016 /* Copy and skip the following char. */
3017 *ap++ = *++p;
3019 break;
3021 case '\'':
3022 case '"':
3023 instring = *p;
3024 break;
3026 case '\n':
3027 if (restp != NULL)
3029 /* End of the command line. */
3030 *restp = p;
3031 goto end_of_line;
3033 else
3034 /* Newlines are not special. */
3035 *ap++ = '\n';
3036 break;
3038 case ' ':
3039 case '\t':
3040 end_of_arg:
3041 /* We have the end of an argument.
3042 Terminate the text of the argument. */
3043 *ap++ = '\0';
3044 new_argv[++i] = ap;
3045 last_argument_was_empty = 0;
3047 /* Update SEEN_NONEQUALS, which tells us if every word
3048 heretofore has contained an `='. */
3049 seen_nonequals |= ! word_has_equals;
3050 if (word_has_equals && ! seen_nonequals)
3051 /* An `=' in a word before the first
3052 word without one is magical. */
3053 goto slow;
3054 word_has_equals = 0; /* Prepare for the next word. */
3056 /* If this argument is the command name,
3057 see if it is a built-in shell command.
3058 If so, have the shell handle it. */
3059 if (i == 1)
3061 register int j;
3062 for (j = 0; sh_cmds[j] != 0; ++j)
3064 if (streq (sh_cmds[j], new_argv[0]))
3065 goto slow;
3066 # ifdef __EMX__
3067 /* Non-Unix shells are case insensitive. */
3068 if (!unixy_shell
3069 && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
3070 goto slow;
3071 # endif
3075 /* Ignore multiple whitespace chars. */
3076 p = next_token (p);
3077 /* Next iteration should examine the first nonwhite char. */
3078 --p;
3079 break;
3081 default:
3082 *ap++ = *p;
3083 break;
3086 end_of_line:
3088 if (instring)
3089 /* Let the shell deal with an unterminated quote. */
3090 goto slow;
3092 /* Terminate the last argument and the argument list. */
3094 *ap = '\0';
3095 if (new_argv[i][0] != '\0' || last_argument_was_empty)
3096 ++i;
3097 new_argv[i] = 0;
3099 if (i == 1)
3101 register int j;
3102 for (j = 0; sh_cmds[j] != 0; ++j)
3103 if (streq (sh_cmds[j], new_argv[0]))
3104 goto slow;
3107 if (new_argv[0] == 0)
3108 /* Line was empty. */
3109 return 0;
3110 else
3111 return new_argv;
3113 slow:;
3114 /* We must use the shell. */
3116 if (new_argv != 0)
3118 /* Free the old argument list we were working on. */
3119 free (new_argv[0]);
3120 free ((void *)new_argv);
3123 #ifdef __MSDOS__
3124 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
3125 #endif
3127 #ifdef _AMIGA
3129 char *ptr;
3130 char *buffer;
3131 char *dptr;
3133 buffer = (char *)xmalloc (strlen (line)+1);
3135 ptr = line;
3136 for (dptr=buffer; *ptr; )
3138 if (*ptr == '\\' && ptr[1] == '\n')
3139 ptr += 2;
3140 else if (*ptr == '@') /* Kludge: multiline commands */
3142 ptr += 2;
3143 *dptr++ = '\n';
3145 else
3146 *dptr++ = *ptr++;
3148 *dptr = 0;
3150 new_argv = (char **) xmalloc (2 * sizeof (char *));
3151 new_argv[0] = buffer;
3152 new_argv[1] = 0;
3154 #else /* Not Amiga */
3155 #ifdef WINDOWS32
3157 * Not eating this whitespace caused things like
3159 * sh -c "\n"
3161 * which gave the shell fits. I think we have to eat
3162 * whitespace here, but this code should be considered
3163 * suspicious if things start failing....
3166 /* Make sure not to bother processing an empty line. */
3167 while (isspace ((unsigned char)*line))
3168 ++line;
3169 if (*line == '\0')
3170 return 0;
3171 #endif /* WINDOWS32 */
3173 /* SHELL may be a multi-word command. Construct a command line
3174 "SHELL -c LINE", with all special chars in LINE escaped.
3175 Then recurse, expanding this command line to get the final
3176 argument list. */
3178 unsigned int shell_len = strlen (shell);
3179 #ifndef VMS
3180 static char minus_c[] = " -c ";
3181 #else
3182 static char minus_c[] = "";
3183 #endif
3184 unsigned int line_len = strlen (line);
3186 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
3187 + (line_len * 2) + 1);
3188 char *command_ptr = NULL; /* used for batch_mode_shell mode */
3190 # ifdef __EMX__ /* is this necessary? */
3191 if (!unixy_shell)
3192 minus_c[1] = '/'; /* " /c " */
3193 # endif
3195 ap = new_line;
3196 bcopy (shell, ap, shell_len);
3197 ap += shell_len;
3198 bcopy (minus_c, ap, sizeof (minus_c) - 1);
3199 ap += sizeof (minus_c) - 1;
3200 command_ptr = ap;
3201 for (p = line; *p != '\0'; ++p)
3203 if (restp != NULL && *p == '\n')
3205 *restp = p;
3206 break;
3208 else if (*p == '\\' && p[1] == '\n')
3210 /* Eat the backslash, the newline, and following whitespace,
3211 replacing it all with a single space (which is escaped
3212 from the shell). */
3213 p += 2;
3215 /* If there is a tab after a backslash-newline,
3216 remove it from the source line which will be echoed,
3217 since it was most likely used to line
3218 up the continued line with the previous one. */
3219 if (*p == '\t')
3220 bcopy (p + 1, p, strlen (p));
3222 p = next_token (p);
3223 --p;
3224 if (unixy_shell && !batch_mode_shell)
3225 *ap++ = '\\';
3226 *ap++ = ' ';
3227 continue;
3230 /* DOS shells don't know about backslash-escaping. */
3231 if (unixy_shell && !batch_mode_shell &&
3232 (*p == '\\' || *p == '\'' || *p == '"'
3233 || isspace ((unsigned char)*p)
3234 || strchr (sh_chars, *p) != 0))
3235 *ap++ = '\\';
3236 #ifdef __MSDOS__
3237 else if (unixy_shell && strneq (p, "...", 3))
3239 /* The case of `...' wildcard again. */
3240 strcpy (ap, "\\.\\.\\");
3241 ap += 5;
3242 p += 2;
3244 #endif
3245 *ap++ = *p;
3247 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
3248 /* Line was empty. */
3249 return 0;
3250 *ap = '\0';
3252 #ifdef WINDOWS32
3253 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3254 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3255 cases, run commands via a script file. */
3256 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
3257 FILE* batch = NULL;
3258 int id = GetCurrentProcessId();
3259 PATH_VAR(fbuf);
3260 char* fname = NULL;
3262 /* create a file name */
3263 sprintf(fbuf, "make%d", id);
3264 fname = tempnam(".", fbuf);
3266 /* create batch file name */
3267 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
3268 strcpy(*batch_filename_ptr, fname);
3270 /* make sure path name is in DOS backslash format */
3271 if (!unixy_shell) {
3272 fname = *batch_filename_ptr;
3273 for (i = 0; fname[i] != '\0'; ++i)
3274 if (fname[i] == '/')
3275 fname[i] = '\\';
3276 strcat(*batch_filename_ptr, ".bat");
3277 } else {
3278 strcat(*batch_filename_ptr, ".sh");
3281 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3282 *batch_filename_ptr));
3284 /* create batch file to execute command */
3285 batch = fopen (*batch_filename_ptr, "w");
3286 if (!unixy_shell)
3287 fputs ("@echo off\n", batch);
3288 fputs (command_ptr, batch);
3289 fputc ('\n', batch);
3290 fclose (batch);
3292 /* create argv */
3293 new_argv = (char **) xmalloc(3 * sizeof (char *));
3294 if (unixy_shell) {
3295 new_argv[0] = xstrdup (shell);
3296 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
3297 } else {
3298 new_argv[0] = xstrdup (*batch_filename_ptr);
3299 new_argv[1] = NULL;
3301 new_argv[2] = NULL;
3302 } else
3303 #endif /* WINDOWS32 */
3304 if (unixy_shell)
3305 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
3306 (char *) 0, (char *) 0,
3307 (char **) 0);
3308 #ifdef __EMX__
3309 else if (!unixy_shell)
3311 /* new_line is local, must not be freed therefore
3312 We use line here instead of new_line because we run the shell
3313 manually. */
3314 size_t line_len = strlen (line);
3315 char *p = new_line;
3316 char *q = new_line;
3317 memcpy (new_line, line, line_len + 1);
3318 /* replace all backslash-newline combination and also following tabs */
3319 while (*q != '\0')
3321 if (q[0] == '\\' && q[1] == '\n')
3323 q += 2; /* remove '\\' and '\n' */
3324 if (q[0] == '\t')
3325 q++; /* remove 1st tab in the next line */
3327 else
3328 *p++ = *q++;
3330 *p = '\0';
3332 # ifndef NO_CMD_DEFAULT
3333 if (strnicmp (new_line, "echo", 4) == 0
3334 && (new_line[4] == ' ' || new_line[4] == '\t'))
3336 /* the builtin echo command: handle it separately */
3337 size_t echo_len = line_len - 5;
3338 char *echo_line = new_line + 5;
3340 /* special case: echo 'x="y"'
3341 cmd works this way: a string is printed as is, i.e., no quotes
3342 are removed. But autoconf uses a command like echo 'x="y"' to
3343 determine whether make works. autoconf expects the output x="y"
3344 so we will do exactly that.
3345 Note: if we do not allow cmd to be the default shell
3346 we do not need this kind of voodoo */
3347 if (echo_line[0] == '\''
3348 && echo_line[echo_len - 1] == '\''
3349 && strncmp (echo_line + 1, "ac_maketemp=",
3350 strlen ("ac_maketemp=")) == 0)
3352 /* remove the enclosing quotes */
3353 memmove (echo_line, echo_line + 1, echo_len - 2);
3354 echo_line[echo_len - 2] = '\0';
3357 # endif
3360 /* Let the shell decide what to do. Put the command line into the
3361 2nd command line argument and hope for the best ;-) */
3362 size_t sh_len = strlen (shell);
3364 /* exactly 3 arguments + NULL */
3365 new_argv = (char **) xmalloc (4 * sizeof (char *));
3366 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3367 the trailing '\0' */
3368 new_argv[0] = (char *) malloc (sh_len + line_len + 5);
3369 memcpy (new_argv[0], shell, sh_len + 1);
3370 new_argv[1] = new_argv[0] + sh_len + 1;
3371 memcpy (new_argv[1], "/c", 3);
3372 new_argv[2] = new_argv[1] + 3;
3373 memcpy (new_argv[2], new_line, line_len + 1);
3374 new_argv[3] = NULL;
3377 #elif defined(__MSDOS__)
3378 else
3380 /* With MSDOS shells, we must construct the command line here
3381 instead of recursively calling ourselves, because we
3382 cannot backslash-escape the special characters (see above). */
3383 new_argv = (char **) xmalloc (sizeof (char *));
3384 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
3385 new_argv[0] = xmalloc (line_len + 1);
3386 strncpy (new_argv[0],
3387 new_line + shell_len + sizeof (minus_c) - 1, line_len);
3388 new_argv[0][line_len] = '\0';
3390 #else
3391 else
3392 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3393 __FILE__, __LINE__);
3394 #endif
3396 #endif /* ! AMIGA */
3398 return new_argv;
3400 #endif /* !VMS */
3402 /* Figure out the argument list necessary to run LINE as a command. Try to
3403 avoid using a shell. This routine handles only ' quoting, and " quoting
3404 when no backslash, $ or ` characters are seen in the quotes. Starting
3405 quotes may be escaped with a backslash. If any of the characters in
3406 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3407 is the first word of a line, the shell is used.
3409 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3410 If *RESTP is NULL, newlines will be ignored.
3412 FILE is the target whose commands these are. It is used for
3413 variable expansion for $(SHELL) and $(IFS). */
3415 char **
3416 construct_command_argv (char *line, char **restp, struct file *file,
3417 char **batch_filename_ptr)
3419 char *shell, *ifs;
3420 char **argv;
3422 #ifdef VMS
3423 char *cptr;
3424 int argc;
3426 argc = 0;
3427 cptr = line;
3428 for (;;)
3430 while ((*cptr != 0)
3431 && (isspace ((unsigned char)*cptr)))
3432 cptr++;
3433 if (*cptr == 0)
3434 break;
3435 while ((*cptr != 0)
3436 && (!isspace((unsigned char)*cptr)))
3437 cptr++;
3438 argc++;
3441 argv = (char **)malloc (argc * sizeof (char *));
3442 if (argv == 0)
3443 abort ();
3445 cptr = line;
3446 argc = 0;
3447 for (;;)
3449 while ((*cptr != 0)
3450 && (isspace ((unsigned char)*cptr)))
3451 cptr++;
3452 if (*cptr == 0)
3453 break;
3454 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3455 argv[argc++] = cptr;
3456 while ((*cptr != 0)
3457 && (!isspace((unsigned char)*cptr)))
3458 cptr++;
3459 if (*cptr != 0)
3460 *cptr++ = 0;
3462 #else
3464 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3465 int save = warn_undefined_variables_flag;
3466 warn_undefined_variables_flag = 0;
3468 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3469 #ifdef WINDOWS32
3471 * Convert to forward slashes so that construct_command_argv_internal()
3472 * is not confused.
3474 if (shell) {
3475 char *p = w32ify (shell, 0);
3476 strcpy (shell, p);
3478 #endif
3479 #ifdef __EMX__
3481 static const char *unixroot = NULL;
3482 static const char *last_shell = "";
3483 static int init = 0;
3484 if (init == 0)
3486 unixroot = getenv ("UNIXROOT");
3487 /* unixroot must be NULL or not empty */
3488 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3489 init = 1;
3492 /* if we have an unixroot drive and if shell is not default_shell
3493 (which means it's either cmd.exe or the test has already been
3494 performed) and if shell is an absolute path without drive letter,
3495 try whether it exists e.g.: if "/bin/sh" does not exist use
3496 "$UNIXROOT/bin/sh" instead. */
3497 if (unixroot && shell && strcmp (shell, last_shell) != 0
3498 && (shell[0] == '/' || shell[0] == '\\'))
3500 /* trying a new shell, check whether it exists */
3501 size_t size = strlen (shell);
3502 char *buf = xmalloc (size + 7);
3503 memcpy (buf, shell, size);
3504 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3505 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3507 /* try the same for the unixroot drive */
3508 memmove (buf + 2, buf, size + 5);
3509 buf[0] = unixroot[0];
3510 buf[1] = unixroot[1];
3511 if (access (buf, F_OK) == 0)
3512 /* we have found a shell! */
3513 /* free(shell); */
3514 shell = buf;
3515 else
3516 free (buf);
3518 else
3519 free (buf);
3522 #endif /* __EMX__ */
3524 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3526 warn_undefined_variables_flag = save;
3529 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
3531 free (shell);
3532 free (ifs);
3533 #endif /* !VMS */
3534 return argv;
3537 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3539 dup2 (int old, int new)
3541 int fd;
3543 (void) close (new);
3544 fd = dup (old);
3545 if (fd != new)
3547 (void) close (fd);
3548 errno = EMFILE;
3549 return -1;
3552 return fd;
3554 #endif /* !HAPE_DUP2 && !_AMIGA */