Many bug fixes etc.
[make.git] / job.c
blobd3a8e6b26d6595e94aba86fd7ee05a05d804d81c
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988,89,90,91,92,93,94,95,96,97,99 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 GNU Make is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNU Make; see the file COPYING. If not, write to
17 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 #include "make.h"
22 #include <assert.h>
24 #include "job.h"
25 #include "debug.h"
26 #include "filedef.h"
27 #include "commands.h"
28 #include "variable.h"
29 #include "debug.h"
31 #include <string.h>
33 /* Default shell to use. */
34 #ifdef WINDOWS32
36 char *default_shell = "sh.exe";
37 int no_default_sh_exe = 1;
38 int batch_mode_shell = 1;
40 #elif defined (_AMIGA)
42 char default_shell[] = "";
43 extern int MyExecute (char **);
44 int batch_mode_shell = 0;
46 #elif defined (__MSDOS__)
48 /* The default shell is a pointer so we can change it if Makefile
49 says so. It is without an explicit path so we get a chance
50 to search the $PATH for it (since MSDOS doesn't have standard
51 directories we could trust). */
52 char *default_shell = "command.com";
53 int batch_mode_shell = 0;
55 #elif defined (__EMX__)
57 const char *default_shell = "/bin/sh";
58 int batch_mode_shell = 0;
60 #elif defined (VMS)
62 # include <descrip.h>
63 char default_shell[] = "";
64 int batch_mode_shell = 0;
66 #else
68 char default_shell[] = "/bin/sh";
69 int batch_mode_shell = 0;
71 #endif
73 #ifdef __MSDOS__
74 # include <process.h>
75 static int execute_by_shell;
76 static int dos_pid = 123;
77 int dos_status;
78 int dos_command_running;
79 #endif /* __MSDOS__ */
81 #ifdef _AMIGA
82 # include <proto/dos.h>
83 static int amiga_pid = 123;
84 static int amiga_status;
85 static char amiga_bname[32];
86 static int amiga_batch_file;
87 #endif /* Amiga. */
89 #ifdef VMS
90 # ifndef __GNUC__
91 # include <processes.h>
92 # endif
93 # include <starlet.h>
94 # include <lib$routines.h>
95 #endif
97 #ifdef WINDOWS32
98 # include <windows.h>
99 # include <io.h>
100 # include <process.h>
101 # include "sub_proc.h"
102 # include "w32err.h"
103 # include "pathstuff.h"
104 #endif /* WINDOWS32 */
106 #ifdef __EMX__
107 # include <process.h>
108 #endif
110 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
111 # include <sys/wait.h>
112 #endif
114 #ifdef HAVE_WAITPID
115 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
116 #else /* Don't have waitpid. */
117 # ifdef HAVE_WAIT3
118 # ifndef wait3
119 extern int wait3 ();
120 # endif
121 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
122 # endif /* Have wait3. */
123 #endif /* Have waitpid. */
125 #if !defined (wait) && !defined (POSIX)
126 extern int wait ();
127 #endif
129 #ifndef HAVE_UNION_WAIT
131 # define WAIT_T int
133 # ifndef WTERMSIG
134 # define WTERMSIG(x) ((x) & 0x7f)
135 # endif
136 # ifndef WCOREDUMP
137 # define WCOREDUMP(x) ((x) & 0x80)
138 # endif
139 # ifndef WEXITSTATUS
140 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
141 # endif
142 # ifndef WIFSIGNALED
143 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
144 # endif
145 # ifndef WIFEXITED
146 # define WIFEXITED(x) (WTERMSIG (x) == 0)
147 # endif
149 #else /* Have `union wait'. */
151 # define WAIT_T union wait
152 # ifndef WTERMSIG
153 # define WTERMSIG(x) ((x).w_termsig)
154 # endif
155 # ifndef WCOREDUMP
156 # define WCOREDUMP(x) ((x).w_coredump)
157 # endif
158 # ifndef WEXITSTATUS
159 # define WEXITSTATUS(x) ((x).w_retcode)
160 # endif
161 # ifndef WIFSIGNALED
162 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
163 # endif
164 # ifndef WIFEXITED
165 # define WIFEXITED(x) (WTERMSIG(x) == 0)
166 # endif
168 #endif /* Don't have `union wait'. */
170 #ifdef VMS
171 static int vms_jobsefnmask = 0;
172 #endif /* !VMS */
174 #ifndef HAVE_UNISTD_H
175 extern int dup2 ();
176 extern int execve ();
177 extern void _exit ();
178 # ifndef VMS
179 extern int geteuid ();
180 extern int getegid ();
181 extern int setgid ();
182 extern int getgid ();
183 # endif
184 #endif
186 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
188 extern int getloadavg PARAMS ((double loadavg[], int nelem));
189 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
190 int *is_remote, int *id_ptr, int *used_stdin));
191 extern int start_remote_job_p PARAMS ((int));
192 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
193 int *coredump_ptr, int block));
195 RETSIGTYPE child_handler PARAMS ((int));
196 static void free_child PARAMS ((struct child *));
197 static void start_job_command PARAMS ((struct child *child));
198 static int load_too_high PARAMS ((void));
199 static int job_next_command PARAMS ((struct child *));
200 static int start_waiting_job PARAMS ((struct child *));
201 #ifdef VMS
202 static void vmsWaitForChildren PARAMS ((int *));
203 #endif
205 /* Chain of all live (or recently deceased) children. */
207 struct child *children = 0;
209 /* Number of children currently running. */
211 unsigned int job_slots_used = 0;
213 /* Nonzero if the `good' standard input is in use. */
215 static int good_stdin_used = 0;
217 /* Chain of children waiting to run until the load average goes down. */
219 static struct child *waiting_jobs = 0;
221 /* Non-zero if we use a *real* shell (always so on Unix). */
223 int unixy_shell = 1;
225 /* Number of jobs started in the current second. */
227 unsigned long job_counter = 0;
230 #ifdef WINDOWS32
232 * The macro which references this function is defined in make.h.
235 w32_kill(int pid, int sig)
237 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
239 #endif /* WINDOWS32 */
241 #ifdef __EMX__
242 /* returns whether path is assumed to be a unix like shell. */
244 _is_unixy_shell (const char *path)
246 /* list of non unix shells */
247 const char *known_os2shells[] = {
248 "cmd.exe",
249 "cmd",
250 "4os2.exe",
251 "4os2",
252 "4dos.exe",
253 "4dos",
254 "command.com",
255 "command",
256 NULL
259 /* find the rightmost '/' or '\\' */
260 const char *name = strrchr (path, '/');
261 const char *p = strrchr (path, '\\');
262 unsigned i;
264 if (name && p) /* take the max */
265 name = (name > p) ? name : p;
266 else if (p) /* name must be 0 */
267 name = p;
268 else if (!name) /* name and p must be 0 */
269 name = path;
271 if (*name == '/' || *name == '\\') name++;
273 i = 0;
274 while (known_os2shells[i] != NULL) {
275 if (stricmp (name, known_os2shells[i]) == 0) /* strcasecmp() */
276 return 0; /* not a unix shell */
277 i++;
280 /* in doubt assume a unix like shell */
281 return 1;
283 #endif /* __EMX__ */
286 /* Write an error message describing the exit status given in
287 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
288 Append "(ignored)" if IGNORED is nonzero. */
290 static void
291 child_error (char *target_name, int exit_code, int exit_sig, int coredump,
292 int ignored)
294 if (ignored && silent_flag)
295 return;
297 #ifdef VMS
298 if (!(exit_code & 1))
299 error (NILF,
300 (ignored ? _("*** [%s] Error 0x%x (ignored)")
301 : _("*** [%s] Error 0x%x")),
302 target_name, exit_code);
303 #else
304 if (exit_sig == 0)
305 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
306 _("*** [%s] Error %d"),
307 target_name, exit_code);
308 else
309 error (NILF, "*** [%s] %s%s",
310 target_name, strsignal (exit_sig),
311 coredump ? _(" (core dumped)") : "");
312 #endif /* VMS */
315 #ifdef VMS
316 /* Wait for nchildren children to terminate */
317 static void
318 vmsWaitForChildren(int *status)
320 while (1)
322 if (!vms_jobsefnmask)
324 *status = 0;
325 return;
328 *status = sys$wflor (32, vms_jobsefnmask);
330 return;
333 /* Set up IO redirection. */
335 char *
336 vms_redirect (struct dsc$descriptor_s *desc, char *fname, char *ibuf)
338 char *fptr;
339 extern char *vmsify ();
341 ibuf++;
342 while (isspace ((unsigned char)*ibuf))
343 ibuf++;
344 fptr = ibuf;
345 while (*ibuf && !isspace ((unsigned char)*ibuf))
346 ibuf++;
347 *ibuf = 0;
348 if (strcmp (fptr, "/dev/null") != 0)
350 strcpy (fname, vmsify (fptr, 0));
351 if (strchr (fname, '.') == 0)
352 strcat (fname, ".");
354 desc->dsc$w_length = strlen(fname);
355 desc->dsc$a_pointer = fname;
356 desc->dsc$b_dtype = DSC$K_DTYPE_T;
357 desc->dsc$b_class = DSC$K_CLASS_S;
359 if (*fname == 0)
360 printf (_("Warning: Empty redirection\n"));
361 return ibuf;
365 /* found apostrophe at (p-1)
366 inc p until after closing apostrophe.
369 static char *
370 vms_handle_apos (char *p)
372 int alast;
373 int inside;
375 #define SEPCHARS ",/()= "
377 inside = 0;
379 while (*p != 0)
381 if (*p == '"')
383 if (inside)
385 while ((alast > 0)
386 && (*p == '"'))
388 p++;
389 alast--;
391 if (alast == 0)
392 inside = 0;
393 else
395 fprintf (stderr, _("Syntax error, still inside '\"'\n"));
396 exit (3);
399 else
401 p++;
402 if (strchr (SEPCHARS, *p))
403 break;
404 inside = 1;
405 alast = 1;
406 while (*p == '"')
408 alast++;
409 p++;
413 else
414 p++;
417 return p;
420 #endif
423 /* Handle a dead child. This handler may or may not ever be installed.
425 If we're using the jobserver feature, we need it. First, installing it
426 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
427 read FD to ensure we don't enter another blocking read without reaping all
428 the dead children. In this case we don't need the dead_children count.
430 If we don't have either waitpid or wait3, then make is unreliable, but we
431 use the dead_children count to reap children as best we can. */
433 static unsigned int dead_children = 0;
435 #ifndef __EMX__ /* Don't use SIGCHLD handler on OS/2. */
436 RETSIGTYPE
437 child_handler (int sig)
439 ++dead_children;
441 if (job_rfd >= 0)
443 close (job_rfd);
444 job_rfd = -1;
447 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
449 #endif /* !__EMX__ */
451 extern int shell_function_pid, shell_function_completed;
453 /* Reap all dead children, storing the returned status and the new command
454 state (`cs_finished') in the `file' member of the `struct child' for the
455 dead child, and removing the child from the chain. In addition, if BLOCK
456 nonzero, we block in this function until we've reaped at least one
457 complete child, waiting for it to die if necessary. If ERR is nonzero,
458 print an error message first. */
460 void
461 reap_children (int block, int err)
463 WAIT_T status;
464 /* Initially, assume we have some. */
465 int reap_more = 1;
467 #ifdef WAIT_NOHANG
468 # define REAP_MORE reap_more
469 #else
470 # define REAP_MORE dead_children
471 #endif
473 /* As long as:
475 We have at least one child outstanding OR a shell function in progress,
477 We're blocking for a complete child OR there are more children to reap
479 we'll keep reaping children. */
481 while ((children != 0 || shell_function_pid != 0)
482 && (block || REAP_MORE))
484 int remote = 0;
485 register int pid;
486 int exit_code, exit_sig, coredump;
487 register struct child *lastc, *c;
488 int child_failed;
489 int any_remote, any_local;
491 if (err && block)
493 /* We might block for a while, so let the user know why. */
494 fflush (stdout);
495 error (NILF, _("*** Waiting for unfinished jobs...."));
498 /* We have one less dead child to reap. As noted in
499 child_handler() above, this count is completely unimportant for
500 all modern, POSIX-y systems that support wait3() or waitpid().
501 The rest of this comment below applies only to early, broken
502 pre-POSIX systems. We keep the count only because... it's there...
504 The test and decrement are not atomic; if it is compiled into:
505 register = dead_children - 1;
506 dead_children = register;
507 a SIGCHLD could come between the two instructions.
508 child_handler increments dead_children.
509 The second instruction here would lose that increment. But the
510 only effect of dead_children being wrong is that we might wait
511 longer than necessary to reap a child, and lose some parallelism;
512 and we might print the "Waiting for unfinished jobs" message above
513 when not necessary. */
515 if (dead_children > 0)
516 --dead_children;
518 any_remote = 0;
519 any_local = shell_function_pid != 0;
520 for (c = children; c != 0; c = c->next)
522 any_remote |= c->remote;
523 any_local |= ! c->remote;
524 DB (DB_JOBS, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
525 (unsigned long int) c, c->file->name,
526 (long) c->pid, c->remote ? _(" (remote)") : ""));
527 #ifdef VMS
528 break;
529 #endif
532 /* First, check for remote children. */
533 if (any_remote)
534 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
535 else
536 pid = 0;
538 if (pid > 0)
539 /* We got a remote child. */
540 remote = 1;
541 else if (pid < 0)
543 /* A remote status command failed miserably. Punt. */
544 remote_status_lose:
545 pfatal_with_name ("remote_status");
547 else
549 /* No remote children. Check for local children. */
550 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
551 if (any_local)
553 #ifdef VMS
554 vmsWaitForChildren (&status);
555 pid = c->pid;
556 #else
557 #ifdef WAIT_NOHANG
558 if (!block)
559 pid = WAIT_NOHANG (&status);
560 else
561 #endif
562 pid = wait (&status);
563 #endif /* !VMS */
565 else
566 pid = 0;
568 if (pid < 0)
570 /* The wait*() failed miserably. Punt. */
571 pfatal_with_name ("wait");
573 else if (pid > 0)
575 /* We got a child exit; chop the status word up. */
576 exit_code = WEXITSTATUS (status);
577 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
578 coredump = WCOREDUMP (status);
580 /* If we have started jobs in this second, remove one. */
581 if (job_counter)
582 --job_counter;
584 #ifdef __EMX__
585 /* the SIGCHLD handler must not be used on OS/2 because, unlike
586 on UNIX systems, it had to call wait() itself. Therefore
587 job_rfd has to be closed here. */
588 if (job_rfd >= 0)
590 close (job_rfd);
591 job_rfd = -1;
593 #endif
596 else
598 /* No local children are dead. */
599 reap_more = 0;
601 if (!block || !any_remote)
602 break;
604 /* Now try a blocking wait for a remote child. */
605 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
606 if (pid < 0)
607 goto remote_status_lose;
608 else if (pid == 0)
609 /* No remote children either. Finally give up. */
610 break;
612 /* We got a remote child. */
613 remote = 1;
615 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
617 #ifdef __MSDOS__
618 /* Life is very different on MSDOS. */
619 pid = dos_pid - 1;
620 status = dos_status;
621 exit_code = WEXITSTATUS (status);
622 if (exit_code == 0xff)
623 exit_code = -1;
624 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
625 coredump = 0;
626 #endif /* __MSDOS__ */
627 #ifdef _AMIGA
628 /* Same on Amiga */
629 pid = amiga_pid - 1;
630 status = amiga_status;
631 exit_code = amiga_status;
632 exit_sig = 0;
633 coredump = 0;
634 #endif /* _AMIGA */
635 #ifdef WINDOWS32
637 HANDLE hPID;
638 int err;
640 /* wait for anything to finish */
641 if (hPID = process_wait_for_any()) {
643 /* was an error found on this process? */
644 err = process_last_err(hPID);
646 /* get exit data */
647 exit_code = process_exit_code(hPID);
649 if (err)
650 fprintf(stderr, "make (e=%d): %s",
651 exit_code, map_windows32_error_to_string(exit_code));
653 /* signal */
654 exit_sig = process_signal(hPID);
656 /* cleanup process */
657 process_cleanup(hPID);
659 coredump = 0;
661 pid = (int) hPID;
663 #endif /* WINDOWS32 */
666 /* Check if this is the child of the `shell' function. */
667 if (!remote && pid == shell_function_pid)
669 /* It is. Leave an indicator for the `shell' function. */
670 if (exit_sig == 0 && exit_code == 127)
671 shell_function_completed = -1;
672 else
673 shell_function_completed = 1;
674 break;
677 child_failed = exit_sig != 0 || exit_code != 0;
679 /* Search for a child matching the deceased one. */
680 lastc = 0;
681 for (c = children; c != 0; lastc = c, c = c->next)
682 if (c->remote == remote && c->pid == pid)
683 break;
685 if (c == 0)
686 /* An unknown child died.
687 Ignore it; it was inherited from our invoker. */
688 continue;
690 DB (DB_JOBS, (child_failed
691 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
692 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
693 (unsigned long int) c, (long) c->pid,
694 c->remote ? _(" (remote)") : ""));
696 if (c->sh_batch_file) {
697 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
698 c->sh_batch_file));
700 /* just try and remove, don't care if this fails */
701 remove (c->sh_batch_file);
703 /* all done with memory */
704 free (c->sh_batch_file);
705 c->sh_batch_file = NULL;
708 /* If this child had the good stdin, say it is now free. */
709 if (c->good_stdin)
710 good_stdin_used = 0;
712 if (child_failed && !c->noerror && !ignore_errors_flag)
714 /* The commands failed. Write an error message,
715 delete non-precious targets, and abort. */
716 static int delete_on_error = -1;
717 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
718 c->file->update_status = 2;
719 if (delete_on_error == -1)
721 struct file *f = lookup_file (".DELETE_ON_ERROR");
722 delete_on_error = f != 0 && f->is_target;
724 if (exit_sig != 0 || delete_on_error)
725 delete_child_targets (c);
727 else
729 if (child_failed)
731 /* The commands failed, but we don't care. */
732 child_error (c->file->name,
733 exit_code, exit_sig, coredump, 1);
734 child_failed = 0;
737 /* If there are more commands to run, try to start them. */
738 if (job_next_command (c))
740 if (handling_fatal_signal)
742 /* Never start new commands while we are dying.
743 Since there are more commands that wanted to be run,
744 the target was not completely remade. So we treat
745 this as if a command had failed. */
746 c->file->update_status = 2;
748 else
750 /* Check again whether to start remotely.
751 Whether or not we want to changes over time.
752 Also, start_remote_job may need state set up
753 by start_remote_job_p. */
754 c->remote = start_remote_job_p (0);
755 start_job_command (c);
756 /* Fatal signals are left blocked in case we were
757 about to put that child on the chain. But it is
758 already there, so it is safe for a fatal signal to
759 arrive now; it will clean up this child's targets. */
760 unblock_sigs ();
761 if (c->file->command_state == cs_running)
762 /* We successfully started the new command.
763 Loop to reap more children. */
764 continue;
767 if (c->file->update_status != 0)
768 /* We failed to start the commands. */
769 delete_child_targets (c);
771 else
772 /* There are no more commands. We got through them all
773 without an unignored error. Now the target has been
774 successfully updated. */
775 c->file->update_status = 0;
778 /* When we get here, all the commands for C->file are finished
779 (or aborted) and C->file->update_status contains 0 or 2. But
780 C->file->command_state is still cs_running if all the commands
781 ran; notice_finish_file looks for cs_running to tell it that
782 it's interesting to check the file's modtime again now. */
784 if (! handling_fatal_signal)
785 /* Notice if the target of the commands has been changed.
786 This also propagates its values for command_state and
787 update_status to its also_make files. */
788 notice_finished_file (c->file);
790 DB (DB_JOBS, (_("Removing child 0x%08lx PID %ld%s from chain.\n"),
791 (unsigned long int) c, (long) c->pid,
792 c->remote ? _(" (remote)") : ""));
794 /* Block fatal signals while frobnicating the list, so that
795 children and job_slots_used are always consistent. Otherwise
796 a fatal signal arriving after the child is off the chain and
797 before job_slots_used is decremented would believe a child was
798 live and call reap_children again. */
799 block_sigs ();
801 /* There is now another slot open. */
802 if (job_slots_used > 0)
803 --job_slots_used;
805 /* Remove the child from the chain and free it. */
806 if (lastc == 0)
807 children = c->next;
808 else
809 lastc->next = c->next;
811 free_child (c);
813 unblock_sigs ();
815 /* If the job failed, and the -k flag was not given, die,
816 unless we are already in the process of dying. */
817 if (!err && child_failed && !keep_going_flag &&
818 /* fatal_error_signal will die with the right signal. */
819 !handling_fatal_signal)
820 die (2);
822 /* Only block for one child. */
823 block = 0;
826 return;
829 /* Free the storage allocated for CHILD. */
831 static void
832 free_child (struct child *child)
834 /* If this child is the only one it was our "free" job, so don't put a
835 token back for it. This child has already been removed from the list,
836 so if there any left this wasn't the last one. */
838 if (job_fds[1] >= 0 && children)
840 char token = '+';
841 int r;
843 /* Write a job token back to the pipe. */
845 EINTRLOOP (r, write (job_fds[1], &token, 1));
846 if (r != 1)
847 pfatal_with_name (_("write jobserver"));
849 DB (DB_JOBS, (_("Released token for child 0x%08lx (%s).\n"),
850 (unsigned long int) child, child->file->name));
853 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
854 return;
856 if (child->command_lines != 0)
858 register unsigned int i;
859 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
860 free (child->command_lines[i]);
861 free ((char *) child->command_lines);
864 if (child->environment != 0)
866 register char **ep = child->environment;
867 while (*ep != 0)
868 free (*ep++);
869 free ((char *) child->environment);
872 free ((char *) child);
875 #ifdef POSIX
876 extern sigset_t fatal_signal_set;
877 #endif
879 void
880 block_sigs (void)
882 #ifdef POSIX
883 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
884 #else
885 # ifdef HAVE_SIGSETMASK
886 (void) sigblock (fatal_signal_mask);
887 # endif
888 #endif
891 #ifdef POSIX
892 void
893 unblock_sigs (void)
895 sigset_t empty;
896 sigemptyset (&empty);
897 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
899 #endif
901 #ifdef MAKE_JOBSERVER
902 # ifdef __EMX__
903 /* Never install the SIGCHLD handler for EMX!!! */
904 # define set_child_handler_action_flags(x)
905 # else
906 /* Set the child handler action flags to FLAGS. */
907 static void
908 set_child_handler_action_flags (int flags)
910 struct sigaction sa;
911 bzero ((char *) &sa, sizeof sa);
912 sa.sa_handler = child_handler;
913 sa.sa_flags = flags;
914 #if defined SIGCHLD
915 sigaction (SIGCHLD, &sa, NULL);
916 #endif
917 #if defined SIGCLD && SIGCLD != SIGCHLD
918 sigaction (SIGCLD, &sa, NULL);
919 #endif
921 #endif /* !__EMX__ */
922 #endif
925 /* Start a job to run the commands specified in CHILD.
926 CHILD is updated to reflect the commands and ID of the child process.
928 NOTE: On return fatal signals are blocked! The caller is responsible
929 for calling `unblock_sigs', once the new child is safely on the chain so
930 it can be cleaned up in the event of a fatal signal. */
932 static void
933 start_job_command (struct child *child)
935 #ifndef _AMIGA
936 static int bad_stdin = -1;
937 #endif
938 register char *p;
939 int flags;
940 #ifdef VMS
941 char *argv;
942 #else
943 char **argv;
944 #endif
946 /* If we have a completely empty commandset, stop now. */
947 if (!child->command_ptr)
948 goto next_command;
950 /* Combine the flags parsed for the line itself with
951 the flags specified globally for this target. */
952 flags = (child->file->command_flags
953 | child->file->cmds->lines_flags[child->command_line - 1]);
955 p = child->command_ptr;
956 child->noerror = flags & COMMANDS_NOERROR;
958 while (*p != '\0')
960 if (*p == '@')
961 flags |= COMMANDS_SILENT;
962 else if (*p == '+')
963 flags |= COMMANDS_RECURSE;
964 else if (*p == '-')
965 child->noerror = 1;
966 else if (!isblank ((unsigned char)*p))
967 break;
968 ++p;
971 /* Update the file's command flags with any new ones we found. We only
972 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
973 now marking more commands recursive than should be in the case of
974 multiline define/endef scripts where only one line is marked "+". In
975 order to really fix this, we'll have to keep a lines_flags for every
976 actual line, after expansion. */
977 child->file->cmds->lines_flags[child->command_line - 1]
978 |= flags & COMMANDS_RECURSE;
980 /* Figure out an argument list from this command line. */
983 char *end = 0;
984 #ifdef VMS
985 argv = p;
986 #else
987 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
988 #endif
989 if (end == NULL)
990 child->command_ptr = NULL;
991 else
993 *end++ = '\0';
994 child->command_ptr = end;
998 /* If -q was given, say that updating `failed' if there was any text on the
999 command line, or `succeeded' otherwise. The exit status of 1 tells the
1000 user that -q is saying `something to do'; the exit status for a random
1001 error is 2. */
1002 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
1004 #ifndef VMS
1005 free (argv[0]);
1006 free ((char *) argv);
1007 #endif
1008 child->file->update_status = 1;
1009 notice_finished_file (child->file);
1010 return;
1013 if (touch_flag && !(flags & COMMANDS_RECURSE))
1015 /* Go on to the next command. It might be the recursive one.
1016 We construct ARGV only to find the end of the command line. */
1017 #ifndef VMS
1018 if (argv)
1020 free (argv[0]);
1021 free ((char *) argv);
1023 #endif
1024 argv = 0;
1027 if (argv == 0)
1029 next_command:
1030 #ifdef __MSDOS__
1031 execute_by_shell = 0; /* in case construct_command_argv sets it */
1032 #endif
1033 /* This line has no commands. Go to the next. */
1034 if (job_next_command (child))
1035 start_job_command (child);
1036 else
1038 /* No more commands. Make sure we're "running"; we might not be if
1039 (e.g.) all commands were skipped due to -n. */
1040 set_command_state (child->file, cs_running);
1041 child->file->update_status = 0;
1042 notice_finished_file (child->file);
1044 return;
1047 /* Print out the command. If silent, we call `message' with null so it
1048 can log the working directory before the command's own error messages
1049 appear. */
1051 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
1052 ? "%s" : (char *) 0, p);
1054 /* Tell update_goal_chain that a command has been started on behalf of
1055 this target. It is important that this happens here and not in
1056 reap_children (where we used to do it), because reap_children might be
1057 reaping children from a different target. We want this increment to
1058 guaranteedly indicate that a command was started for the dependency
1059 chain (i.e., update_file recursion chain) we are processing. */
1061 ++commands_started;
1063 /* Optimize an empty command. People use this for timestamp rules,
1064 so avoid forking a useless shell. Do this after we increment
1065 commands_started so make still treats this special case as if it
1066 performed some action (makes a difference as to what messages are
1067 printed, etc. */
1069 #if !defined(VMS) && !defined(_AMIGA)
1070 if (
1071 #if defined __MSDOS__ || defined (__EMX__)
1072 unixy_shell /* the test is complicated and we already did it */
1073 #else
1074 (argv[0] && !strcmp (argv[0], "/bin/sh"))
1075 #endif
1076 && (argv[1]
1077 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
1078 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1079 && argv[3] == NULL)
1081 free (argv[0]);
1082 free ((char *) argv);
1083 goto next_command;
1085 #endif /* !VMS && !_AMIGA */
1087 /* If -n was given, recurse to get the next line in the sequence. */
1089 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1091 #ifndef VMS
1092 free (argv[0]);
1093 free ((char *) argv);
1094 #endif
1095 goto next_command;
1098 /* Flush the output streams so they won't have things written twice. */
1100 fflush (stdout);
1101 fflush (stderr);
1103 #ifndef VMS
1104 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1106 /* Set up a bad standard input that reads from a broken pipe. */
1108 if (bad_stdin == -1)
1110 /* Make a file descriptor that is the read end of a broken pipe.
1111 This will be used for some children's standard inputs. */
1112 int pd[2];
1113 if (pipe (pd) == 0)
1115 /* Close the write side. */
1116 (void) close (pd[1]);
1117 /* Save the read side. */
1118 bad_stdin = pd[0];
1120 /* Set the descriptor to close on exec, so it does not litter any
1121 child's descriptor table. When it is dup2'd onto descriptor 0,
1122 that descriptor will not close on exec. */
1123 CLOSE_ON_EXEC (bad_stdin);
1127 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1129 /* Decide whether to give this child the `good' standard input
1130 (one that points to the terminal or whatever), or the `bad' one
1131 that points to the read side of a broken pipe. */
1133 child->good_stdin = !good_stdin_used;
1134 if (child->good_stdin)
1135 good_stdin_used = 1;
1137 #endif /* !VMS */
1139 child->deleted = 0;
1141 #ifndef _AMIGA
1142 /* Set up the environment for the child. */
1143 if (child->environment == 0)
1144 child->environment = target_environment (child->file);
1145 #endif
1147 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1149 #ifndef VMS
1150 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1151 if (child->remote)
1153 int is_remote, id, used_stdin;
1154 if (start_remote_job (argv, child->environment,
1155 child->good_stdin ? 0 : bad_stdin,
1156 &is_remote, &id, &used_stdin))
1157 /* Don't give up; remote execution may fail for various reasons. If
1158 so, simply run the job locally. */
1159 goto run_local;
1160 else
1162 if (child->good_stdin && !used_stdin)
1164 child->good_stdin = 0;
1165 good_stdin_used = 0;
1167 child->remote = is_remote;
1168 child->pid = id;
1171 else
1172 #endif /* !VMS */
1174 /* Fork the child process. */
1176 char **parent_environ;
1178 run_local:
1179 block_sigs ();
1181 child->remote = 0;
1183 #ifdef VMS
1185 if (!child_execute_job (argv, child)) {
1186 /* Fork failed! */
1187 perror_with_name ("vfork", "");
1188 goto error;
1191 #else
1193 parent_environ = environ;
1195 # ifdef __EMX__
1196 /* If we aren't running a recursive command and we have a jobserver
1197 pipe, close it before exec'ing. */
1198 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1200 CLOSE_ON_EXEC (job_fds[0]);
1201 CLOSE_ON_EXEC (job_fds[1]);
1203 if (job_rfd >= 0)
1204 CLOSE_ON_EXEC (job_rfd);
1206 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1207 child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1208 argv, child->environment);
1209 if (child->pid < 0)
1211 /* spawn failed! */
1212 unblock_sigs ();
1213 perror_with_name ("spawn", "");
1214 goto error;
1217 /* undo CLOSE_ON_EXEC() after the child process has been started */
1218 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1220 fcntl (job_fds[0], F_SETFD, 0);
1221 fcntl (job_fds[1], F_SETFD, 0);
1223 if (job_rfd >= 0)
1224 fcntl (job_rfd, F_SETFD, 0);
1226 #else /* !__EMX__ */
1228 child->pid = vfork ();
1229 environ = parent_environ; /* Restore value child may have clobbered. */
1230 if (child->pid == 0)
1232 /* We are the child side. */
1233 unblock_sigs ();
1235 /* If we aren't running a recursive command and we have a jobserver
1236 pipe, close it before exec'ing. */
1237 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1239 close (job_fds[0]);
1240 close (job_fds[1]);
1242 if (job_rfd >= 0)
1243 close (job_rfd);
1245 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1246 argv, child->environment);
1248 else if (child->pid < 0)
1250 /* Fork failed! */
1251 unblock_sigs ();
1252 perror_with_name ("vfork", "");
1253 goto error;
1255 # endif /* !__EMX__ */
1256 #endif /* !VMS */
1259 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1260 #ifdef __MSDOS__
1262 int proc_return;
1264 block_sigs ();
1265 dos_status = 0;
1267 /* We call `system' to do the job of the SHELL, since stock DOS
1268 shell is too dumb. Our `system' knows how to handle long
1269 command lines even if pipes/redirection is needed; it will only
1270 call COMMAND.COM when its internal commands are used. */
1271 if (execute_by_shell)
1273 char *cmdline = argv[0];
1274 /* We don't have a way to pass environment to `system',
1275 so we need to save and restore ours, sigh... */
1276 char **parent_environ = environ;
1278 environ = child->environment;
1280 /* If we have a *real* shell, tell `system' to call
1281 it to do everything for us. */
1282 if (unixy_shell)
1284 /* A *real* shell on MSDOS may not support long
1285 command lines the DJGPP way, so we must use `system'. */
1286 cmdline = argv[2]; /* get past "shell -c" */
1289 dos_command_running = 1;
1290 proc_return = system (cmdline);
1291 environ = parent_environ;
1292 execute_by_shell = 0; /* for the next time */
1294 else
1296 dos_command_running = 1;
1297 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1300 /* Need to unblock signals before turning off
1301 dos_command_running, so that child's signals
1302 will be treated as such (see fatal_error_signal). */
1303 unblock_sigs ();
1304 dos_command_running = 0;
1306 /* If the child got a signal, dos_status has its
1307 high 8 bits set, so be careful not to alter them. */
1308 if (proc_return == -1)
1309 dos_status |= 0xff;
1310 else
1311 dos_status |= (proc_return & 0xff);
1312 ++dead_children;
1313 child->pid = dos_pid++;
1315 #endif /* __MSDOS__ */
1316 #ifdef _AMIGA
1317 amiga_status = MyExecute (argv);
1319 ++dead_children;
1320 child->pid = amiga_pid++;
1321 if (amiga_batch_file)
1323 amiga_batch_file = 0;
1324 DeleteFile (amiga_bname); /* Ignore errors. */
1326 #endif /* Amiga */
1327 #ifdef WINDOWS32
1329 HANDLE hPID;
1330 char* arg0;
1332 /* make UNC paths safe for CreateProcess -- backslash format */
1333 arg0 = argv[0];
1334 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1335 for ( ; arg0 && *arg0; arg0++)
1336 if (*arg0 == '/')
1337 *arg0 = '\\';
1339 /* make sure CreateProcess() has Path it needs */
1340 sync_Path_environment();
1342 hPID = process_easy(argv, child->environment);
1344 if (hPID != INVALID_HANDLE_VALUE)
1345 child->pid = (int) hPID;
1346 else {
1347 int i;
1348 unblock_sigs();
1349 fprintf(stderr,
1350 _("process_easy() failed failed to launch process (e=%d)\n"),
1351 process_last_err(hPID));
1352 for (i = 0; argv[i]; i++)
1353 fprintf(stderr, "%s ", argv[i]);
1354 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1357 #endif /* WINDOWS32 */
1358 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1360 /* Bump the number of jobs started in this second. */
1361 ++job_counter;
1363 /* We are the parent side. Set the state to
1364 say the commands are running and return. */
1366 set_command_state (child->file, cs_running);
1368 /* Free the storage used by the child's argument list. */
1369 #ifndef VMS
1370 free (argv[0]);
1371 free ((char *) argv);
1372 #endif
1374 return;
1376 error:
1377 child->file->update_status = 2;
1378 notice_finished_file (child->file);
1379 return;
1382 /* Try to start a child running.
1383 Returns nonzero if the child was started (and maybe finished), or zero if
1384 the load was too high and the child was put on the `waiting_jobs' chain. */
1386 static int
1387 start_waiting_job (struct child *c)
1389 struct file *f = c->file;
1391 /* If we can start a job remotely, we always want to, and don't care about
1392 the local load average. We record that the job should be started
1393 remotely in C->remote for start_job_command to test. */
1395 c->remote = start_remote_job_p (1);
1397 /* If we are running at least one job already and the load average
1398 is too high, make this one wait. */
1399 if (!c->remote && job_slots_used > 0 && load_too_high ())
1401 /* Put this child on the chain of children waiting for the load average
1402 to go down. */
1403 set_command_state (f, cs_running);
1404 c->next = waiting_jobs;
1405 waiting_jobs = c;
1406 return 0;
1409 /* Start the first command; reap_children will run later command lines. */
1410 start_job_command (c);
1412 switch (f->command_state)
1414 case cs_running:
1415 c->next = children;
1416 DB (DB_JOBS, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1417 (unsigned long int) c, c->file->name,
1418 (long) c->pid, c->remote ? _(" (remote)") : ""));
1419 children = c;
1420 /* One more job slot is in use. */
1421 ++job_slots_used;
1422 unblock_sigs ();
1423 break;
1425 case cs_not_started:
1426 /* All the command lines turned out to be empty. */
1427 f->update_status = 0;
1428 /* FALLTHROUGH */
1430 case cs_finished:
1431 notice_finished_file (f);
1432 free_child (c);
1433 break;
1435 default:
1436 assert (f->command_state == cs_finished);
1437 break;
1440 return 1;
1443 /* Create a `struct child' for FILE and start its commands running. */
1445 void
1446 new_job (struct file *file)
1448 register struct commands *cmds = file->cmds;
1449 register struct child *c;
1450 char **lines;
1451 register unsigned int i;
1453 /* Let any previously decided-upon jobs that are waiting
1454 for the load to go down start before this new one. */
1455 start_waiting_jobs ();
1457 /* Reap any children that might have finished recently. */
1458 reap_children (0, 0);
1460 /* Chop the commands up into lines if they aren't already. */
1461 chop_commands (cmds);
1463 /* Expand the command lines and store the results in LINES. */
1464 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1465 for (i = 0; i < cmds->ncommand_lines; ++i)
1467 /* Collapse backslash-newline combinations that are inside variable
1468 or function references. These are left alone by the parser so
1469 that they will appear in the echoing of commands (where they look
1470 nice); and collapsed by construct_command_argv when it tokenizes.
1471 But letting them survive inside function invocations loses because
1472 we don't want the functions to see them as part of the text. */
1474 char *in, *out, *ref;
1476 /* IN points to where in the line we are scanning.
1477 OUT points to where in the line we are writing.
1478 When we collapse a backslash-newline combination,
1479 IN gets ahead of OUT. */
1481 in = out = cmds->command_lines[i];
1482 while ((ref = strchr (in, '$')) != 0)
1484 ++ref; /* Move past the $. */
1486 if (out != in)
1487 /* Copy the text between the end of the last chunk
1488 we processed (where IN points) and the new chunk
1489 we are about to process (where REF points). */
1490 bcopy (in, out, ref - in);
1492 /* Move both pointers past the boring stuff. */
1493 out += ref - in;
1494 in = ref;
1496 if (*ref == '(' || *ref == '{')
1498 char openparen = *ref;
1499 char closeparen = openparen == '(' ? ')' : '}';
1500 int count;
1501 char *p;
1503 *out++ = *in++; /* Copy OPENPAREN. */
1504 /* IN now points past the opening paren or brace.
1505 Count parens or braces until it is matched. */
1506 count = 0;
1507 while (*in != '\0')
1509 if (*in == closeparen && --count < 0)
1510 break;
1511 else if (*in == '\\' && in[1] == '\n')
1513 /* We have found a backslash-newline inside a
1514 variable or function reference. Eat it and
1515 any following whitespace. */
1517 int quoted = 0;
1518 for (p = in - 1; p > ref && *p == '\\'; --p)
1519 quoted = !quoted;
1521 if (quoted)
1522 /* There were two or more backslashes, so this is
1523 not really a continuation line. We don't collapse
1524 the quoting backslashes here as is done in
1525 collapse_continuations, because the line will
1526 be collapsed again after expansion. */
1527 *out++ = *in++;
1528 else
1530 /* Skip the backslash, newline and
1531 any following whitespace. */
1532 in = next_token (in + 2);
1534 /* Discard any preceding whitespace that has
1535 already been written to the output. */
1536 while (out > ref
1537 && isblank ((unsigned char)out[-1]))
1538 --out;
1540 /* Replace it all with a single space. */
1541 *out++ = ' ';
1544 else
1546 if (*in == openparen)
1547 ++count;
1549 *out++ = *in++;
1555 /* There are no more references in this line to worry about.
1556 Copy the remaining uninteresting text to the output. */
1557 if (out != in)
1558 strcpy (out, in);
1560 /* Finally, expand the line. */
1561 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1562 file);
1565 /* Start the command sequence, record it in a new
1566 `struct child', and add that to the chain. */
1568 c = (struct child *) xmalloc (sizeof (struct child));
1569 bzero ((char *)c, sizeof (struct child));
1570 c->file = file;
1571 c->command_lines = lines;
1572 c->sh_batch_file = NULL;
1574 /* Fetch the first command line to be run. */
1575 job_next_command (c);
1577 /* Wait for a job slot to be freed up. If we allow an infinite number
1578 don't bother; also job_slots will == 0 if we're using the jobserver. */
1580 if (job_slots != 0)
1581 while (job_slots_used == job_slots)
1582 reap_children (1, 0);
1584 #ifdef MAKE_JOBSERVER
1585 /* If we are controlling multiple jobs make sure we have a token before
1586 starting the child. */
1588 /* This can be inefficient. There's a decent chance that this job won't
1589 actually have to run any subprocesses: the command script may be empty
1590 or otherwise optimized away. It would be nice if we could defer
1591 obtaining a token until just before we need it, in start_job_command.
1592 To do that we'd need to keep track of whether we'd already obtained a
1593 token (since start_job_command is called for each line of the job, not
1594 just once). Also more thought needs to go into the entire algorithm;
1595 this is where the old parallel job code waits, so... */
1597 else if (job_fds[0] >= 0)
1598 while (1)
1600 char token;
1601 int got_token;
1602 int saved_errno;
1604 DB (DB_JOBS, ("Need a job token; we %shave children\n",
1605 children ? "" : "don't "));
1607 /* If we don't already have a job started, use our "free" token. */
1608 if (!children)
1609 break;
1611 /* Read a token. As long as there's no token available we'll block.
1612 We enable interruptible system calls before the read(2) so that if
1613 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1614 we can process the death(s) and return tokens to the free pool.
1616 Once we return from the read, we immediately reinstate restartable
1617 system calls. This allows us to not worry about checking for
1618 EINTR on all the other system calls in the program.
1620 There is one other twist: there is a span between the time
1621 reap_children() does its last check for dead children and the time
1622 the read(2) call is entered, below, where if a child dies we won't
1623 notice. This is extremely serious as it could cause us to
1624 deadlock, given the right set of events.
1626 To avoid this, we do the following: before we reap_children(), we
1627 dup(2) the read FD on the jobserver pipe. The read(2) call below
1628 uses that new FD. In the signal handler, we close that FD. That
1629 way, if a child dies during the section mentioned above, the
1630 read(2) will be invoked with an invalid FD and will return
1631 immediately with EBADF. */
1633 /* Make sure we have a dup'd FD. */
1634 if (job_rfd < 0)
1636 DB (DB_JOBS, ("Duplicate the job FD\n"));
1637 job_rfd = dup (job_fds[0]);
1640 /* Reap anything that's currently waiting. */
1641 reap_children (0, 0);
1643 /* If our "free" token has become available, use it. */
1644 if (!children)
1645 break;
1647 /* Set interruptible system calls, and read() for a job token. */
1648 set_child_handler_action_flags (0);
1649 got_token = read (job_rfd, &token, 1);
1650 saved_errno = errno;
1651 set_child_handler_action_flags (SA_RESTART);
1653 /* If we got one, we're done here. */
1654 if (got_token == 1)
1656 DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1657 (unsigned long int) c, c->file->name));
1658 break;
1661 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1662 go back and reap_children(), and try again. */
1663 errno = saved_errno;
1664 if (errno != EINTR && errno != EBADF)
1665 pfatal_with_name (_("read jobs pipe"));
1666 if (errno == EBADF)
1667 DB (DB_JOBS, ("Read returned EBADF.\n"));
1669 #endif
1671 /* The job is now primed. Start it running.
1672 (This will notice if there are in fact no commands.) */
1673 (void) start_waiting_job (c);
1675 if (job_slots == 1 || not_parallel)
1676 /* Since there is only one job slot, make things run linearly.
1677 Wait for the child to die, setting the state to `cs_finished'. */
1678 while (file->command_state == cs_running)
1679 reap_children (1, 0);
1681 return;
1684 /* Move CHILD's pointers to the next command for it to execute.
1685 Returns nonzero if there is another command. */
1687 static int
1688 job_next_command (struct child *child)
1690 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1692 /* There are no more lines in the expansion of this line. */
1693 if (child->command_line == child->file->cmds->ncommand_lines)
1695 /* There are no more lines to be expanded. */
1696 child->command_ptr = 0;
1697 return 0;
1699 else
1700 /* Get the next line to run. */
1701 child->command_ptr = child->command_lines[child->command_line++];
1703 return 1;
1706 /* Determine if the load average on the system is too high to start a new job.
1707 The real system load average is only recomputed once a second. However, a
1708 very parallel make can easily start tens or even hundreds of jobs in a
1709 second, which brings the system to its knees for a while until that first
1710 batch of jobs clears out.
1712 To avoid this we use a weighted algorithm to try to account for jobs which
1713 have been started since the last second, and guess what the load average
1714 would be now if it were computed.
1716 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1717 who writes:
1719 ! calculate something load-oid and add to the observed sys.load,
1720 ! so that latter can catch up:
1721 ! - every job started increases jobctr;
1722 ! - every dying job decreases a positive jobctr;
1723 ! - the jobctr value gets zeroed every change of seconds,
1724 ! after its value*weight_b is stored into the 'backlog' value last_sec
1725 ! - weight_a times the sum of jobctr and last_sec gets
1726 ! added to the observed sys.load.
1728 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1729 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1730 ! sub-shelled commands (rm, echo, sed...) for tests.
1731 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1732 ! resulted in significant excession of the load limit, raising it
1733 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1734 ! reach the limit in most test cases.
1736 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1737 ! exceeding the limit for longer-running stuff (compile jobs in
1738 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1739 ! small jobs' effects.
1743 #define LOAD_WEIGHT_A 0.25
1744 #define LOAD_WEIGHT_B 0.25
1746 static int
1747 load_too_high (void)
1749 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1750 return 1;
1751 #else
1752 static double last_sec;
1753 static time_t last_now;
1754 double load, guess;
1755 time_t now;
1757 if (max_load_average < 0)
1758 return 0;
1760 /* Find the real system load average. */
1761 make_access ();
1762 if (getloadavg (&load, 1) != 1)
1764 static int lossage = -1;
1765 /* Complain only once for the same error. */
1766 if (lossage == -1 || errno != lossage)
1768 if (errno == 0)
1769 /* An errno value of zero means getloadavg is just unsupported. */
1770 error (NILF,
1771 _("cannot enforce load limits on this operating system"));
1772 else
1773 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1775 lossage = errno;
1776 load = 0;
1778 user_access ();
1780 /* If we're in a new second zero the counter and correct the backlog
1781 value. Only keep the backlog for one extra second; after that it's 0. */
1782 now = time (NULL);
1783 if (last_now < now)
1785 if (last_now == now - 1)
1786 last_sec = LOAD_WEIGHT_B * job_counter;
1787 else
1788 last_sec = 0.0;
1790 job_counter = 0;
1791 last_now = now;
1794 /* Try to guess what the load would be right now. */
1795 guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
1797 DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1798 guess, load, max_load_average));
1800 return guess >= max_load_average;
1801 #endif
1804 /* Start jobs that are waiting for the load to be lower. */
1806 void
1807 start_waiting_jobs (void)
1809 struct child *job;
1811 if (waiting_jobs == 0)
1812 return;
1816 /* Check for recently deceased descendants. */
1817 reap_children (0, 0);
1819 /* Take a job off the waiting list. */
1820 job = waiting_jobs;
1821 waiting_jobs = job->next;
1823 /* Try to start that job. We break out of the loop as soon
1824 as start_waiting_job puts one back on the waiting list. */
1826 while (start_waiting_job (job) && waiting_jobs != 0);
1828 return;
1831 #ifndef WINDOWS32
1832 #ifdef VMS
1833 #include <descrip.h>
1834 #include <clidef.h>
1836 /* This is called as an AST when a child process dies (it won't get
1837 interrupted by anything except a higher level AST).
1839 int vmsHandleChildTerm(struct child *child)
1841 int status;
1842 register struct child *lastc, *c;
1843 int child_failed;
1845 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1847 lib$free_ef(&child->efn);
1849 (void) sigblock (fatal_signal_mask);
1851 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1853 /* Search for a child matching the deceased one. */
1854 lastc = 0;
1855 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1856 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1857 #else
1858 c = child;
1859 #endif
1861 if (child_failed && !c->noerror && !ignore_errors_flag)
1863 /* The commands failed. Write an error message,
1864 delete non-precious targets, and abort. */
1865 child_error (c->file->name, c->cstatus, 0, 0, 0);
1866 c->file->update_status = 1;
1867 delete_child_targets (c);
1869 else
1871 if (child_failed)
1873 /* The commands failed, but we don't care. */
1874 child_error (c->file->name, c->cstatus, 0, 0, 1);
1875 child_failed = 0;
1878 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1879 /* If there are more commands to run, try to start them. */
1880 start_job (c);
1882 switch (c->file->command_state)
1884 case cs_running:
1885 /* Successfully started. */
1886 break;
1888 case cs_finished:
1889 if (c->file->update_status != 0) {
1890 /* We failed to start the commands. */
1891 delete_child_targets (c);
1893 break;
1895 default:
1896 error (NILF, _("internal error: `%s' command_state"),
1897 c->file->name);
1898 abort ();
1899 break;
1901 #endif /* RECURSIVEJOBS */
1904 /* Set the state flag to say the commands have finished. */
1905 c->file->command_state = cs_finished;
1906 notice_finished_file (c->file);
1908 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1909 /* Remove the child from the chain and free it. */
1910 if (lastc == 0)
1911 children = c->next;
1912 else
1913 lastc->next = c->next;
1914 free_child (c);
1915 #endif /* RECURSIVEJOBS */
1917 /* There is now another slot open. */
1918 if (job_slots_used > 0)
1919 --job_slots_used;
1921 /* If the job failed, and the -k flag was not given, die. */
1922 if (child_failed && !keep_going_flag)
1923 die (EXIT_FAILURE);
1925 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1927 return 1;
1930 /* VMS:
1931 Spawn a process executing the command in ARGV and return its pid. */
1933 #define MAXCMDLEN 200
1935 /* local helpers to make ctrl+c and ctrl+y working, see below */
1936 #include <iodef.h>
1937 #include <libclidef.h>
1938 #include <ssdef.h>
1940 static int ctrlMask= LIB$M_CLI_CTRLY;
1941 static int oldCtrlMask;
1942 static int setupYAstTried= 0;
1943 static int pidToAbort= 0;
1944 static int chan= 0;
1946 static void reEnableAst(void) {
1947 lib$enable_ctrl (&oldCtrlMask,0);
1950 static astHandler (void) {
1951 if (pidToAbort) {
1952 sys$forcex (&pidToAbort, 0, SS$_ABORT);
1953 pidToAbort= 0;
1955 kill (getpid(),SIGQUIT);
1958 static void tryToSetupYAst(void) {
1959 $DESCRIPTOR(inputDsc,"SYS$COMMAND");
1960 int status;
1961 struct {
1962 short int status, count;
1963 int dvi;
1964 } iosb;
1966 setupYAstTried++;
1968 if (!chan) {
1969 status= sys$assign(&inputDsc,&chan,0,0);
1970 if (!(status&SS$_NORMAL)) {
1971 lib$signal(status);
1972 return;
1975 status= sys$qiow (0, chan, IO$_SETMODE|IO$M_CTRLYAST,&iosb,0,0,
1976 astHandler,0,0,0,0,0);
1977 if (status==SS$_ILLIOFUNC) {
1978 sys$dassgn(chan);
1979 #ifdef CTRLY_ENABLED_ANYWAY
1980 fprintf (stderr,
1981 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
1982 #else
1983 return;
1984 #endif
1986 if (status==SS$_NORMAL)
1987 status= iosb.status;
1988 if (!(status&SS$_NORMAL)) {
1989 lib$signal(status);
1990 return;
1993 /* called from AST handler ? */
1994 if (setupYAstTried>1)
1995 return;
1996 if (atexit(reEnableAst))
1997 fprintf (stderr,
1998 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
1999 status= lib$disable_ctrl (&ctrlMask, &oldCtrlMask);
2000 if (!(status&SS$_NORMAL)) {
2001 lib$signal(status);
2002 return;
2006 child_execute_job (char *argv, struct child *child)
2008 int i;
2009 static struct dsc$descriptor_s cmddsc;
2010 static struct dsc$descriptor_s pnamedsc;
2011 static struct dsc$descriptor_s ifiledsc;
2012 static struct dsc$descriptor_s ofiledsc;
2013 static struct dsc$descriptor_s efiledsc;
2014 int have_redirection = 0;
2015 int have_newline = 0;
2017 int spflags = CLI$M_NOWAIT;
2018 int status;
2019 char *cmd = alloca (strlen (argv) + 512), *p, *q;
2020 char ifile[256], ofile[256], efile[256];
2021 char *comname = 0;
2022 char procname[100];
2024 /* Parse IO redirection. */
2026 ifile[0] = 0;
2027 ofile[0] = 0;
2028 efile[0] = 0;
2030 DB (DB_JOBS, ("child_execute_job (%s)\n", argv));
2032 while (isspace ((unsigned char)*argv))
2033 argv++;
2035 if (*argv == 0)
2036 return 0;
2038 sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
2039 pnamedsc.dsc$w_length = strlen(procname);
2040 pnamedsc.dsc$a_pointer = procname;
2041 pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
2042 pnamedsc.dsc$b_class = DSC$K_CLASS_S;
2044 /* Handle comments and redirection. */
2045 for (p = argv, q = cmd; *p; p++, q++)
2047 switch (*p)
2049 case '#':
2050 *p-- = 0;
2051 *q-- = 0;
2052 break;
2053 case '\\':
2054 p++;
2055 if (*p == '\n')
2056 p++;
2057 if (isspace ((unsigned char)*p))
2059 do { p++; } while (isspace ((unsigned char)*p));
2060 p--;
2062 *q = *p;
2063 break;
2064 case '<':
2065 p = vms_redirect (&ifiledsc, ifile, p);
2066 *q = ' ';
2067 have_redirection = 1;
2068 break;
2069 case '>':
2070 have_redirection = 1;
2071 if (*(p-1) == '2')
2073 q--;
2074 if (strncmp (p, ">&1", 3) == 0)
2076 p += 3;
2077 strcpy (efile, "sys$output");
2078 efiledsc.dsc$w_length = strlen(efile);
2079 efiledsc.dsc$a_pointer = efile;
2080 efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
2081 efiledsc.dsc$b_class = DSC$K_CLASS_S;
2083 else
2085 p = vms_redirect (&efiledsc, efile, p);
2088 else
2090 p = vms_redirect (&ofiledsc, ofile, p);
2092 *q = ' ';
2093 break;
2094 case '\n':
2095 have_newline = 1;
2096 default:
2097 *q = *p;
2098 break;
2101 *q = *p;
2103 if (strncmp (cmd, "builtin_", 8) == 0)
2105 child->pid = 270163;
2106 child->efn = 0;
2107 child->cstatus = 1;
2109 DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));
2111 p = cmd + 8;
2113 if ((*(p) == 'c')
2114 && (*(p+1) == 'd')
2115 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
2117 p += 3;
2118 while ((*p == ' ') || (*p == '\t'))
2119 p++;
2120 DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
2121 if (chdir (p))
2122 return 0;
2123 else
2124 return 1;
2126 else if ((*(p) == 'r')
2127 && (*(p+1) == 'm')
2128 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
2130 int in_arg;
2132 /* rm */
2133 p += 3;
2134 while ((*p == ' ') || (*p == '\t'))
2135 p++;
2136 in_arg = 1;
2138 DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
2139 while (*p)
2141 switch (*p)
2143 case ' ':
2144 case '\t':
2145 if (in_arg)
2147 *p++ = ';';
2148 in_arg = 0;
2150 break;
2151 default:
2152 break;
2154 p++;
2157 else
2159 printf(_("Unknown builtin command '%s'\n"), cmd);
2160 fflush(stdout);
2161 return 0;
2165 /* Create a *.com file if either the command is too long for
2166 lib$spawn, or the command contains a newline, or if redirection
2167 is desired. Forcing commands with newlines into DCLs allows to
2168 store search lists on user mode logicals. */
2170 if (strlen (cmd) > MAXCMDLEN
2171 || (have_redirection != 0)
2172 || (have_newline != 0))
2174 FILE *outfile;
2175 char c;
2176 char *sep;
2177 int alevel = 0; /* apostrophe level */
2179 if (strlen (cmd) == 0)
2181 printf (_("Error, empty command\n"));
2182 fflush (stdout);
2183 return 0;
2186 outfile = open_tmpfile (&comname, "sys$scratch:CMDXXXXXX.COM");
2187 if (outfile == 0)
2188 pfatal_with_name (_("fopen (temporary file)"));
2190 if (ifile[0])
2192 fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
2193 DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
2194 ifiledsc.dsc$w_length = 0;
2197 if (efile[0])
2199 fprintf (outfile, "$ define sys$error %s\n", efile);
2200 DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
2201 efiledsc.dsc$w_length = 0;
2204 if (ofile[0])
2206 fprintf (outfile, "$ define sys$output %s\n", ofile);
2207 DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
2208 ofiledsc.dsc$w_length = 0;
2211 p = sep = q = cmd;
2212 for (c = '\n'; c; c = *q++)
2214 switch (c)
2216 case '\n':
2217 /* At a newline, skip any whitespace around a leading $
2218 from the command and issue exactly one $ into the DCL. */
2219 while (isspace ((unsigned char)*p))
2220 p++;
2221 if (*p == '$')
2222 p++;
2223 while (isspace ((unsigned char)*p))
2224 p++;
2225 fwrite (p, 1, q - p, outfile);
2226 fputc ('$', outfile);
2227 fputc (' ', outfile);
2228 /* Reset variables. */
2229 p = sep = q;
2230 break;
2232 /* Nice places for line breaks are after strings, after
2233 comma or space and before slash. */
2234 case '"':
2235 q = vms_handle_apos (q + 1);
2236 sep = q;
2237 break;
2238 case ',':
2239 case ' ':
2240 sep = q;
2241 break;
2242 case '/':
2243 case '\0':
2244 sep = q - 1;
2245 break;
2246 default:
2247 break;
2249 if (sep - p > 78)
2251 /* Enough stuff for a line. */
2252 fwrite (p, 1, sep - p, outfile);
2253 p = sep;
2254 if (*sep)
2256 /* The command continues. */
2257 fputc ('-', outfile);
2259 fputc ('\n', outfile);
2263 fwrite (p, 1, q - p, outfile);
2264 fputc ('\n', outfile);
2266 fclose (outfile);
2268 sprintf (cmd, "$ @%s", comname);
2270 DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
2273 cmddsc.dsc$w_length = strlen(cmd);
2274 cmddsc.dsc$a_pointer = cmd;
2275 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
2276 cmddsc.dsc$b_class = DSC$K_CLASS_S;
2278 child->efn = 0;
2279 while (child->efn < 32 || child->efn > 63)
2281 status = lib$get_ef ((unsigned long *)&child->efn);
2282 if (!(status & 1))
2283 return 0;
2286 sys$clref (child->efn);
2288 vms_jobsefnmask |= (1 << (child->efn - 32));
2291 LIB$SPAWN [command-string]
2292 [,input-file]
2293 [,output-file]
2294 [,flags]
2295 [,process-name]
2296 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2297 [,AST-address] [,varying-AST-argument]
2298 [,prompt-string] [,cli] [,table]
2301 #ifndef DONTWAITFORCHILD
2303 * Code to make ctrl+c and ctrl+y working.
2304 * The problem starts with the synchronous case where after lib$spawn is
2305 * called any input will go to the child. But with input re-directed,
2306 * both control characters won't make it to any of the programs, neither
2307 * the spawning nor to the spawned one. Hence the caller needs to spawn
2308 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2309 * has to follow to simulate the wanted synchronous behaviour.
2310 * The next problem is ctrl+y which isn't caught by the crtl and
2311 * therefore isn't converted to SIGQUIT (for a signal handler which is
2312 * already established). The only way to catch ctrl+y, is an AST
2313 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2314 * disabled, otherwise it will handle it. Not to mention the previous
2315 * ctrl+y handling of DCL needs to be re-established before make exits.
2316 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2317 * make it to the signal handler after the child "normally" terminates.
2318 * This isn't enough. It seems reasonable for simple command lines like
2319 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2320 * spawning make. Therefore we need to abort the process in the AST.
2322 * Prior to the spawn it is checked if an AST is already set up for
2323 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2324 * this will work except if make is run in a batch environment, but there
2325 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2326 * is disabled and an exit handler is established to re-enable it.
2327 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2328 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2329 * the already established handler and will bring us back to common code.
2330 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2331 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2332 * which the crtl converts to SIGINT and which is caught by the common
2333 * signal handler. Because signals were blocked before entering this code
2334 * sys$waitfr will always complete and the SIGQUIT will be processed after
2335 * it (after termination of the current block, somewhere in common code).
2336 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2337 * current command completes. Anyway it's better than nothing :-)
2340 if (!setupYAstTried)
2341 tryToSetupYAst();
2342 status = lib$spawn (&cmddsc, /* cmd-string */
2343 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file */
2344 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
2345 &spflags, /* flags */
2346 &pnamedsc, /* proc name */
2347 &child->pid, &child->cstatus, &child->efn,
2348 0, 0,
2349 0, 0, 0);
2350 if (status & 1)
2352 pidToAbort= child->pid;
2353 status= sys$waitfr (child->efn);
2354 pidToAbort= 0;
2355 vmsHandleChildTerm(child);
2357 #else
2358 status = lib$spawn (&cmddsc,
2359 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
2360 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
2361 &spflags,
2362 &pnamedsc,
2363 &child->pid, &child->cstatus, &child->efn,
2364 vmsHandleChildTerm, child,
2365 0, 0, 0);
2366 #endif
2368 if (!(status & 1))
2370 printf (_("Error spawning, %d\n") ,status);
2371 fflush (stdout);
2372 switch (status)
2374 case 0x1c:
2375 errno = EPROCLIM;
2376 break;
2377 default:
2378 errno = EFAIL;
2382 if (comname && !ISDB (DB_JOBS))
2383 unlink (comname);
2385 return (status & 1);
2388 #else /* !VMS */
2390 /* EMX: Start a child process. This function returns the new pid. */
2391 # if defined __MSDOS__ || defined __EMX__
2393 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2395 int pid;
2396 /* stdin_fd == 0 means: nothing to do for stdin;
2397 stdout_fd == 1 means: nothing to do for stdout */
2398 int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
2399 int save_stdout = (stdout_fd != 1) ? dup (1): 1;
2401 /* < 0 only if dup() failed */
2402 if (save_stdin < 0)
2403 fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
2404 if (save_stdout < 0)
2405 fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
2407 /* Close unnecessary file handles for the child. */
2408 if (save_stdin != 0)
2409 CLOSE_ON_EXEC (save_stdin);
2410 if (save_stdout != 1)
2411 CLOSE_ON_EXEC (save_stdout);
2413 /* Connect the pipes to the child process. */
2414 if (stdin_fd != 0)
2415 (void) dup2 (stdin_fd, 0);
2416 if (stdout_fd != 1)
2417 (void) dup2 (stdout_fd, 1);
2419 /* stdin_fd and stdout_fd must be closed on exit because we are
2420 still in the parent process */
2421 if (stdin_fd != 0)
2422 CLOSE_ON_EXEC (stdin_fd);
2423 if (stdout_fd != 1)
2424 CLOSE_ON_EXEC (stdout_fd);
2426 /* Run the command. */
2427 pid = exec_command (argv, envp);
2429 /* Restore stdout/stdin of the parent process. */
2430 if (stdin_fd != 0 && dup2 (save_stdin, 0) != 0)
2431 fatal (NILF, _("restoring of stdin failed\n"));
2432 if (stdout_fd != 1 && dup2 (save_stdout, 1) != 1)
2433 fatal (NILF, _("restoring of stdout failed\n"));
2435 return pid;
2438 #elif !defined (_AMIGA) && !defined (__MSDOS__)
2440 /* UNIX:
2441 Replace the current process with one executing the command in ARGV.
2442 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2443 the environment of the new program. This function does not return. */
2444 void
2445 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2447 if (stdin_fd != 0)
2448 (void) dup2 (stdin_fd, 0);
2449 if (stdout_fd != 1)
2450 (void) dup2 (stdout_fd, 1);
2451 if (stdin_fd != 0)
2452 (void) close (stdin_fd);
2453 if (stdout_fd != 1)
2454 (void) close (stdout_fd);
2456 /* Run the command. */
2457 exec_command (argv, envp);
2459 #endif /* !AMIGA && !__MSDOS__ */
2460 #endif /* !VMS */
2461 #endif /* !WINDOWS32 */
2463 #ifndef _AMIGA
2464 /* Replace the current process with one running the command in ARGV,
2465 with environment ENVP. This function does not return. */
2467 /* EMX: This function returns the pid of the child process. */
2468 # ifdef __EMX__
2470 # else
2471 void
2472 # endif
2473 exec_command (char **argv, char **envp)
2475 #ifdef VMS
2476 /* to work around a problem with signals and execve: ignore them */
2477 #ifdef SIGCHLD
2478 signal (SIGCHLD,SIG_IGN);
2479 #endif
2480 /* Run the program. */
2481 execve (argv[0], argv, envp);
2482 perror_with_name ("execve: ", argv[0]);
2483 _exit (EXIT_FAILURE);
2484 #else
2485 #ifdef WINDOWS32
2486 HANDLE hPID;
2487 HANDLE hWaitPID;
2488 int err = 0;
2489 int exit_code = EXIT_FAILURE;
2491 /* make sure CreateProcess() has Path it needs */
2492 sync_Path_environment();
2494 /* launch command */
2495 hPID = process_easy(argv, envp);
2497 /* make sure launch ok */
2498 if (hPID == INVALID_HANDLE_VALUE)
2500 int i;
2501 fprintf(stderr,
2502 _("process_easy() failed failed to launch process (e=%d)\n"),
2503 process_last_err(hPID));
2504 for (i = 0; argv[i]; i++)
2505 fprintf(stderr, "%s ", argv[i]);
2506 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2507 exit(EXIT_FAILURE);
2510 /* wait and reap last child */
2511 while (hWaitPID = process_wait_for_any())
2513 /* was an error found on this process? */
2514 err = process_last_err(hWaitPID);
2516 /* get exit data */
2517 exit_code = process_exit_code(hWaitPID);
2519 if (err)
2520 fprintf(stderr, "make (e=%d, rc=%d): %s",
2521 err, exit_code, map_windows32_error_to_string(err));
2523 /* cleanup process */
2524 process_cleanup(hWaitPID);
2526 /* expect to find only last pid, warn about other pids reaped */
2527 if (hWaitPID == hPID)
2528 break;
2529 else
2530 fprintf(stderr,
2531 _("make reaped child pid %d, still waiting for pid %d\n"),
2532 hWaitPID, hPID);
2535 /* return child's exit code as our exit code */
2536 exit(exit_code);
2538 #else /* !WINDOWS32 */
2540 # ifdef __EMX__
2541 int pid;
2542 # endif
2544 /* Be the user, permanently. */
2545 child_access ();
2547 # ifdef __EMX__
2549 /* Run the program. */
2550 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2552 if (pid >= 0)
2553 return pid;
2555 /* the file might have a strange shell extension */
2556 if (errno == ENOENT)
2557 errno = ENOEXEC;
2559 # else
2561 /* Run the program. */
2562 environ = envp;
2563 execvp (argv[0], argv);
2565 # endif /* !__EMX__ */
2567 switch (errno)
2569 case ENOENT:
2570 error (NILF, _("%s: Command not found"), argv[0]);
2571 break;
2572 case ENOEXEC:
2574 /* The file is not executable. Try it as a shell script. */
2575 extern char *getenv ();
2576 char *shell;
2577 char **new_argv;
2578 int argc;
2580 # ifdef __EMX__
2581 /* Do not use $SHELL from the environment */
2582 struct variable *p = lookup_variable ("SHELL", 5);
2583 if (p)
2584 shell = p->value;
2585 else
2586 shell = 0;
2587 # else
2588 shell = getenv ("SHELL");
2589 # endif
2590 if (shell == 0)
2591 shell = default_shell;
2593 argc = 1;
2594 while (argv[argc] != 0)
2595 ++argc;
2597 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
2598 new_argv[0] = shell;
2599 new_argv[1] = argv[0];
2600 while (argc > 0)
2602 new_argv[1 + argc] = argv[argc];
2603 --argc;
2606 # ifdef __EMX__
2607 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2608 if (pid >= 0)
2609 break;
2610 # else
2611 execvp (shell, new_argv);
2612 # endif
2613 if (errno == ENOENT)
2614 error (NILF, _("%s: Shell program not found"), shell);
2615 else
2616 perror_with_name ("execvp: ", shell);
2617 break;
2620 # ifdef __EMX__
2621 case EINVAL:
2622 /* this nasty error was driving me nuts :-( */
2623 error (NILF, _("spawnvpe: environment space might be exhausted"));
2624 /* FALLTHROUGH */
2625 # endif
2627 default:
2628 perror_with_name ("execvp: ", argv[0]);
2629 break;
2632 # ifdef __EMX__
2633 return pid;
2634 # else
2635 _exit (127);
2636 # endif
2637 #endif /* !WINDOWS32 */
2638 #endif /* !VMS */
2640 #else /* On Amiga */
2641 void exec_command (char **argv)
2643 MyExecute (argv);
2646 void clean_tmp (void)
2648 DeleteFile (amiga_bname);
2651 #endif /* On Amiga */
2653 #ifndef VMS
2654 /* Figure out the argument list necessary to run LINE as a command. Try to
2655 avoid using a shell. This routine handles only ' quoting, and " quoting
2656 when no backslash, $ or ` characters are seen in the quotes. Starting
2657 quotes may be escaped with a backslash. If any of the characters in
2658 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2659 is the first word of a line, the shell is used.
2661 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2662 If *RESTP is NULL, newlines will be ignored.
2664 SHELL is the shell to use, or nil to use the default shell.
2665 IFS is the value of $IFS, or nil (meaning the default). */
2667 static char **
2668 construct_command_argv_internal (char *line, char **restp, char *shell,
2669 char *ifs, char **batch_filename_ptr)
2671 #ifdef __MSDOS__
2672 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2673 We call `system' for anything that requires ``slow'' processing,
2674 because DOS shells are too dumb. When $SHELL points to a real
2675 (unix-style) shell, `system' just calls it to do everything. When
2676 $SHELL points to a DOS shell, `system' does most of the work
2677 internally, calling the shell only for its internal commands.
2678 However, it looks on the $PATH first, so you can e.g. have an
2679 external command named `mkdir'.
2681 Since we call `system', certain characters and commands below are
2682 actually not specific to COMMAND.COM, but to the DJGPP implementation
2683 of `system'. In particular:
2685 The shell wildcard characters are in DOS_CHARS because they will
2686 not be expanded if we call the child via `spawnXX'.
2688 The `;' is in DOS_CHARS, because our `system' knows how to run
2689 multiple commands on a single line.
2691 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2692 won't have to tell one from another and have one more set of
2693 commands and special characters. */
2694 static char sh_chars_dos[] = "*?[];|<>%^&()";
2695 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2696 "copy", "ctty", "date", "del", "dir", "echo",
2697 "erase", "exit", "for", "goto", "if", "md",
2698 "mkdir", "path", "pause", "prompt", "rd",
2699 "rmdir", "rem", "ren", "rename", "set",
2700 "shift", "time", "type", "ver", "verify",
2701 "vol", ":", 0 };
2703 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2704 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2705 "logout", "set", "umask", "wait", "while",
2706 "for", "case", "if", ":", ".", "break",
2707 "continue", "export", "read", "readonly",
2708 "shift", "times", "trap", "switch", "unset",
2709 0 };
2711 char *sh_chars;
2712 char **sh_cmds;
2713 #elif defined (__EMX__)
2714 static char sh_chars_dos[] = "*?[];|<>%^&()";
2715 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2716 "copy", "ctty", "date", "del", "dir", "echo",
2717 "erase", "exit", "for", "goto", "if", "md",
2718 "mkdir", "path", "pause", "prompt", "rd",
2719 "rmdir", "rem", "ren", "rename", "set",
2720 "shift", "time", "type", "ver", "verify",
2721 "vol", ":", 0 };
2723 static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
2724 static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2725 "date", "del", "detach", "dir", "echo",
2726 "endlocal", "erase", "exit", "for", "goto", "if",
2727 "keys", "md", "mkdir", "move", "path", "pause",
2728 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2729 "set", "setlocal", "shift", "start", "time",
2730 "type", "ver", "verify", "vol", ":", 0 };
2732 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~'";
2733 static char *sh_cmds_sh[] = { "echo", "cd", "eval", "exec", "exit", "login",
2734 "logout", "set", "umask", "wait", "while",
2735 "for", "case", "if", ":", ".", "break",
2736 "continue", "export", "read", "readonly",
2737 "shift", "times", "trap", "switch", "unset",
2738 0 };
2739 char *sh_chars;
2740 char **sh_cmds;
2742 #elif defined (_AMIGA)
2743 static char sh_chars[] = "#;\"|<>()?*$`";
2744 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2745 "rename", "set", "setenv", "date", "makedir",
2746 "skip", "else", "endif", "path", "prompt",
2747 "unset", "unsetenv", "version",
2748 0 };
2749 #elif defined (WINDOWS32)
2750 static char sh_chars_dos[] = "\"|&<>";
2751 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2752 "copy", "ctty", "date", "del", "dir", "echo",
2753 "erase", "exit", "for", "goto", "if", "if", "md",
2754 "mkdir", "path", "pause", "prompt", "rd", "rem",
2755 "ren", "rename", "rmdir", "set", "shift", "time",
2756 "type", "ver", "verify", "vol", ":", 0 };
2757 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2758 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2759 "logout", "set", "umask", "wait", "while", "for",
2760 "case", "if", ":", ".", "break", "continue",
2761 "export", "read", "readonly", "shift", "times",
2762 "trap", "switch", "test",
2763 #ifdef BATCH_MODE_ONLY_SHELL
2764 "echo",
2765 #endif
2766 0 };
2767 char* sh_chars;
2768 char** sh_cmds;
2769 #else /* must be UNIX-ish */
2770 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~!";
2771 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
2772 "logout", "set", "umask", "wait", "while", "for",
2773 "case", "if", ":", ".", "break", "continue",
2774 "export", "read", "readonly", "shift", "times",
2775 "trap", "switch", 0 };
2776 #endif /* __MSDOS__ */
2777 register int i;
2778 register char *p;
2779 register char *ap;
2780 char *end;
2781 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2782 char **new_argv = 0;
2783 #ifdef WINDOWS32
2784 int slow_flag = 0;
2786 if (no_default_sh_exe) {
2787 sh_cmds = sh_cmds_dos;
2788 sh_chars = sh_chars_dos;
2789 } else {
2790 sh_cmds = sh_cmds_sh;
2791 sh_chars = sh_chars_sh;
2793 #endif /* WINDOWS32 */
2795 if (restp != NULL)
2796 *restp = NULL;
2798 /* Make sure not to bother processing an empty line. */
2799 while (isblank ((unsigned char)*line))
2800 ++line;
2801 if (*line == '\0')
2802 return 0;
2804 /* See if it is safe to parse commands internally. */
2805 if (shell == 0)
2806 shell = default_shell;
2807 #ifdef WINDOWS32
2808 else if (strcmp (shell, default_shell))
2810 char *s1 = _fullpath(NULL, shell, 0);
2811 char *s2 = _fullpath(NULL, default_shell, 0);
2813 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2815 if (s1)
2816 free (s1);
2817 if (s2)
2818 free (s2);
2820 if (slow_flag)
2821 goto slow;
2822 #else /* not WINDOWS32 */
2823 #if defined (__MSDOS__) || defined (__EMX__)
2824 else if (stricmp (shell, default_shell))
2826 extern int _is_unixy_shell (const char *_path);
2828 DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
2829 default_shell, shell));
2830 unixy_shell = _is_unixy_shell (shell);
2831 /* we must allocate a copy of shell: construct_command_argv() will free
2832 * shell after this function returns. */
2833 default_shell = xstrdup (shell);
2835 if (unixy_shell)
2837 sh_chars = sh_chars_sh;
2838 sh_cmds = sh_cmds_sh;
2840 else
2842 sh_chars = sh_chars_dos;
2843 sh_cmds = sh_cmds_dos;
2844 # ifdef __EMX__
2845 if (_osmode == OS2_MODE)
2847 sh_chars = sh_chars_os2;
2848 sh_cmds = sh_cmds_os2;
2850 # endif
2852 #else /* !__MSDOS__ */
2853 else if (strcmp (shell, default_shell))
2854 goto slow;
2855 #endif /* !__MSDOS__ && !__EMX__ */
2856 #endif /* not WINDOWS32 */
2858 if (ifs != 0)
2859 for (ap = ifs; *ap != '\0'; ++ap)
2860 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2861 goto slow;
2863 i = strlen (line) + 1;
2865 /* More than 1 arg per character is impossible. */
2866 new_argv = (char **) xmalloc (i * sizeof (char *));
2868 /* All the args can fit in a buffer as big as LINE is. */
2869 ap = new_argv[0] = (char *) xmalloc (i);
2870 end = ap + i;
2872 /* I is how many complete arguments have been found. */
2873 i = 0;
2874 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2875 for (p = line; *p != '\0'; ++p)
2877 if (ap > end)
2878 abort ();
2880 if (instring)
2882 string_char:
2883 /* Inside a string, just copy any char except a closing quote
2884 or a backslash-newline combination. */
2885 if (*p == instring)
2887 instring = 0;
2888 if (ap == new_argv[0] || *(ap-1) == '\0')
2889 last_argument_was_empty = 1;
2891 else if (*p == '\\' && p[1] == '\n')
2892 goto swallow_escaped_newline;
2893 else if (*p == '\n' && restp != NULL)
2895 /* End of the command line. */
2896 *restp = p;
2897 goto end_of_line;
2899 /* Backslash, $, and ` are special inside double quotes.
2900 If we see any of those, punt.
2901 But on MSDOS, if we use COMMAND.COM, double and single
2902 quotes have the same effect. */
2903 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2904 goto slow;
2905 else
2906 *ap++ = *p;
2908 else if (strchr (sh_chars, *p) != 0)
2909 /* Not inside a string, but it's a special char. */
2910 goto slow;
2911 #ifdef __MSDOS__
2912 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2913 /* `...' is a wildcard in DJGPP. */
2914 goto slow;
2915 #endif
2916 else
2917 /* Not a special char. */
2918 switch (*p)
2920 case '=':
2921 /* Equals is a special character in leading words before the
2922 first word with no equals sign in it. This is not the case
2923 with sh -k, but we never get here when using nonstandard
2924 shell flags. */
2925 if (! seen_nonequals && unixy_shell)
2926 goto slow;
2927 word_has_equals = 1;
2928 *ap++ = '=';
2929 break;
2931 case '\\':
2932 /* Backslash-newline combinations are eaten. */
2933 if (p[1] == '\n')
2935 swallow_escaped_newline:
2937 /* Eat the backslash, the newline, and following whitespace,
2938 replacing it all with a single space. */
2939 p += 2;
2941 /* If there is a tab after a backslash-newline,
2942 remove it from the source line which will be echoed,
2943 since it was most likely used to line
2944 up the continued line with the previous one. */
2945 if (*p == '\t')
2946 /* Note these overlap and strcpy() is undefined for
2947 overlapping objects in ANSI C. The strlen() _IS_ right,
2948 since we need to copy the nul byte too. */
2949 bcopy (p + 1, p, strlen (p));
2951 if (instring)
2952 goto string_char;
2953 else
2955 if (ap != new_argv[i])
2956 /* Treat this as a space, ending the arg.
2957 But if it's at the beginning of the arg, it should
2958 just get eaten, rather than becoming an empty arg. */
2959 goto end_of_arg;
2960 else
2961 p = next_token (p) - 1;
2964 else if (p[1] != '\0')
2966 #ifdef HAVE_DOS_PATHS
2967 /* Only remove backslashes before characters special
2968 to Unixy shells. All other backslashes are copied
2969 verbatim, since they are probably DOS-style
2970 directory separators. This still leaves a small
2971 window for problems, but at least it should work
2972 for the vast majority of naive users. */
2974 #ifdef __MSDOS__
2975 /* A dot is only special as part of the "..."
2976 wildcard. */
2977 if (strneq (p + 1, ".\\.\\.", 5))
2979 *ap++ = '.';
2980 *ap++ = '.';
2981 p += 4;
2983 else
2984 #endif
2985 if (p[1] != '\\' && p[1] != '\''
2986 && !isspace ((unsigned char)p[1])
2987 && (strchr (sh_chars_sh, p[1]) == 0))
2988 /* back up one notch, to copy the backslash */
2989 --p;
2990 #endif /* HAVE_DOS_PATHS */
2992 /* Copy and skip the following char. */
2993 *ap++ = *++p;
2995 break;
2997 case '\'':
2998 case '"':
2999 instring = *p;
3000 break;
3002 case '\n':
3003 if (restp != NULL)
3005 /* End of the command line. */
3006 *restp = p;
3007 goto end_of_line;
3009 else
3010 /* Newlines are not special. */
3011 *ap++ = '\n';
3012 break;
3014 case ' ':
3015 case '\t':
3016 end_of_arg:
3017 /* We have the end of an argument.
3018 Terminate the text of the argument. */
3019 *ap++ = '\0';
3020 new_argv[++i] = ap;
3021 last_argument_was_empty = 0;
3023 /* Update SEEN_NONEQUALS, which tells us if every word
3024 heretofore has contained an `='. */
3025 seen_nonequals |= ! word_has_equals;
3026 if (word_has_equals && ! seen_nonequals)
3027 /* An `=' in a word before the first
3028 word without one is magical. */
3029 goto slow;
3030 word_has_equals = 0; /* Prepare for the next word. */
3032 /* If this argument is the command name,
3033 see if it is a built-in shell command.
3034 If so, have the shell handle it. */
3035 if (i == 1)
3037 register int j;
3038 for (j = 0; sh_cmds[j] != 0; ++j)
3039 if (streq (sh_cmds[j], new_argv[0]))
3040 goto slow;
3043 /* Ignore multiple whitespace chars. */
3044 p = next_token (p);
3045 /* Next iteration should examine the first nonwhite char. */
3046 --p;
3047 break;
3049 default:
3050 *ap++ = *p;
3051 break;
3054 end_of_line:
3056 if (instring)
3057 /* Let the shell deal with an unterminated quote. */
3058 goto slow;
3060 /* Terminate the last argument and the argument list. */
3062 *ap = '\0';
3063 if (new_argv[i][0] != '\0' || last_argument_was_empty)
3064 ++i;
3065 new_argv[i] = 0;
3067 if (i == 1)
3069 register int j;
3070 for (j = 0; sh_cmds[j] != 0; ++j)
3071 if (streq (sh_cmds[j], new_argv[0]))
3072 goto slow;
3075 if (new_argv[0] == 0)
3076 /* Line was empty. */
3077 return 0;
3078 else
3079 return new_argv;
3081 slow:;
3082 /* We must use the shell. */
3084 if (new_argv != 0)
3086 /* Free the old argument list we were working on. */
3087 free (new_argv[0]);
3088 free ((void *)new_argv);
3091 #ifdef __MSDOS__
3092 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
3093 #endif
3095 #ifdef _AMIGA
3097 char *ptr;
3098 char *buffer;
3099 char *dptr;
3101 buffer = (char *)xmalloc (strlen (line)+1);
3103 ptr = line;
3104 for (dptr=buffer; *ptr; )
3106 if (*ptr == '\\' && ptr[1] == '\n')
3107 ptr += 2;
3108 else if (*ptr == '@') /* Kludge: multiline commands */
3110 ptr += 2;
3111 *dptr++ = '\n';
3113 else
3114 *dptr++ = *ptr++;
3116 *dptr = 0;
3118 new_argv = (char **) xmalloc (2 * sizeof (char *));
3119 new_argv[0] = buffer;
3120 new_argv[1] = 0;
3122 #else /* Not Amiga */
3123 #ifdef WINDOWS32
3125 * Not eating this whitespace caused things like
3127 * sh -c "\n"
3129 * which gave the shell fits. I think we have to eat
3130 * whitespace here, but this code should be considered
3131 * suspicious if things start failing....
3134 /* Make sure not to bother processing an empty line. */
3135 while (isspace ((unsigned char)*line))
3136 ++line;
3137 if (*line == '\0')
3138 return 0;
3139 #endif /* WINDOWS32 */
3141 /* SHELL may be a multi-word command. Construct a command line
3142 "SHELL -c LINE", with all special chars in LINE escaped.
3143 Then recurse, expanding this command line to get the final
3144 argument list. */
3146 unsigned int shell_len = strlen (shell);
3147 #ifndef VMS
3148 static char minus_c[] = " -c ";
3149 #else
3150 static char minus_c[] = "";
3151 #endif
3152 unsigned int line_len = strlen (line);
3154 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
3155 + (line_len * 2) + 1);
3156 char *command_ptr = NULL; /* used for batch_mode_shell mode */
3158 # ifdef __EMX__ /* is this necessary? */
3159 if (!unixy_shell)
3160 minus_c[1] = '/'; /* " /c " */
3161 # endif
3163 ap = new_line;
3164 bcopy (shell, ap, shell_len);
3165 ap += shell_len;
3166 bcopy (minus_c, ap, sizeof (minus_c) - 1);
3167 ap += sizeof (minus_c) - 1;
3168 command_ptr = ap;
3169 for (p = line; *p != '\0'; ++p)
3171 if (restp != NULL && *p == '\n')
3173 *restp = p;
3174 break;
3176 else if (*p == '\\' && p[1] == '\n')
3178 /* Eat the backslash, the newline, and following whitespace,
3179 replacing it all with a single space (which is escaped
3180 from the shell). */
3181 p += 2;
3183 /* If there is a tab after a backslash-newline,
3184 remove it from the source line which will be echoed,
3185 since it was most likely used to line
3186 up the continued line with the previous one. */
3187 if (*p == '\t')
3188 bcopy (p + 1, p, strlen (p));
3190 p = next_token (p);
3191 --p;
3192 if (unixy_shell && !batch_mode_shell)
3193 *ap++ = '\\';
3194 *ap++ = ' ';
3195 continue;
3198 /* DOS shells don't know about backslash-escaping. */
3199 if (unixy_shell && !batch_mode_shell &&
3200 (*p == '\\' || *p == '\'' || *p == '"'
3201 || isspace ((unsigned char)*p)
3202 || strchr (sh_chars, *p) != 0))
3203 *ap++ = '\\';
3204 #ifdef __MSDOS__
3205 else if (unixy_shell && strneq (p, "...", 3))
3207 /* The case of `...' wildcard again. */
3208 strcpy (ap, "\\.\\.\\");
3209 ap += 5;
3210 p += 2;
3212 #endif
3213 *ap++ = *p;
3215 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
3216 /* Line was empty. */
3217 return 0;
3218 *ap = '\0';
3220 #ifdef WINDOWS32
3221 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3222 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3223 cases, run commands via a script file. */
3224 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
3225 FILE* batch = NULL;
3226 int id = GetCurrentProcessId();
3227 PATH_VAR(fbuf);
3228 char* fname = NULL;
3230 /* create a file name */
3231 sprintf(fbuf, "make%d", id);
3232 fname = tempnam(".", fbuf);
3234 /* create batch file name */
3235 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
3236 strcpy(*batch_filename_ptr, fname);
3238 /* make sure path name is in DOS backslash format */
3239 if (!unixy_shell) {
3240 fname = *batch_filename_ptr;
3241 for (i = 0; fname[i] != '\0'; ++i)
3242 if (fname[i] == '/')
3243 fname[i] = '\\';
3244 strcat(*batch_filename_ptr, ".bat");
3245 } else {
3246 strcat(*batch_filename_ptr, ".sh");
3249 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3250 *batch_filename_ptr));
3252 /* create batch file to execute command */
3253 batch = fopen (*batch_filename_ptr, "w");
3254 if (!unixy_shell)
3255 fputs ("@echo off\n", batch);
3256 fputs (command_ptr, batch);
3257 fputc ('\n', batch);
3258 fclose (batch);
3260 /* create argv */
3261 new_argv = (char **) xmalloc(3 * sizeof (char *));
3262 if (unixy_shell) {
3263 new_argv[0] = xstrdup (shell);
3264 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
3265 } else {
3266 new_argv[0] = xstrdup (*batch_filename_ptr);
3267 new_argv[1] = NULL;
3269 new_argv[2] = NULL;
3270 } else
3271 #endif /* WINDOWS32 */
3272 if (unixy_shell)
3273 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
3274 (char *) 0, (char *) 0,
3275 (char **) 0);
3276 # ifdef __EMX__
3277 else if (!unixy_shell)
3279 /* new_line is local, must not be freed therefore */
3280 char *p, *q;
3281 int quote;
3282 size_t index;
3283 size_t len;
3285 /* handle quotes
3286 We have to remove all double quotes and to split the line
3287 into distinct arguments because of the strange handling
3288 of builtin commands by cmd: 'echo "bla"' prints "bla"
3289 (with quotes) while 'c:\bin\echo.exe "bla"' prints bla
3290 (without quotes). Some programs like autoconf rely
3291 on the second behaviour. */
3293 len = strlen (new_line) + 1;
3295 /* More than 1 arg per character is impossible. */
3296 new_argv = (char **) xmalloc (len * sizeof (char *));
3298 /* All the args can fit in a buffer as big as new_line is. */
3299 new_argv[0] = (char *) xmalloc (len);
3301 index = 0;
3302 quote = 0;
3303 q = new_line;
3304 p = new_argv[index];
3305 while(*q != '\0')
3307 /* searching for closing quote */
3308 if (quote)
3310 if (*q == quote)
3312 /* remove the quote */
3313 q++;
3314 quote = 0;
3316 else /* normal character: copy it */
3317 *p++ = *q++;
3320 /* searching for opening quote */
3321 else if (*q == '\"'
3322 # ifndef NO_CMD_DEFAULT
3323 || *q == '\''
3324 # endif
3327 /* remove opening quote */
3328 quote = *q;
3329 q++;
3332 /* spaces outside of a quoted string: remove them
3333 and start a new argument */
3334 else if (*q == ' ' || *q == '\t')
3336 *p++ = '\0'; /* trailing '\0' for last argument */
3338 /* remove all successive spaces */
3341 q++;
3343 while(*q == ' ' || *q == '\t');
3345 /* start new argument */
3346 index++;
3347 new_argv[index] = p;
3350 /* normal character (no space) outside a quoted string*/
3351 else
3352 *p++ = *q++;
3353 } /* end while() */
3355 *p = '\0'; /* trailing '\0' for the last argument */
3356 new_argv[index + 1] = NULL;
3358 # ifndef NO_CMD_DEFAULT
3359 /* special case: echo x="y"
3360 (e.g. autoconf uses this to determine whether make works)
3361 this is pure idioty but cmd works this way:
3362 if 'echo' and 'x="y"' are two different arguments cmd
3363 will print '"x="y""' but if they are only one argument
3364 cmd will print 'bla="blurb"' as it should be
3365 note: if we do not allow cmd to be the default shell
3366 we do not need this kind of voodoo */
3367 if (index == 3 && strcasecmp(new_argv[2], "echo") == 0)
3369 new_argv[2][4] = ' ';
3370 new_argv[3] = NULL;
3372 # endif
3374 #elif defined(__MSDOS__)
3375 else
3377 /* With MSDOS shells, we must construct the command line here
3378 instead of recursively calling ourselves, because we
3379 cannot backslash-escape the special characters (see above). */
3380 new_argv = (char **) xmalloc (sizeof (char *));
3381 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
3382 new_argv[0] = xmalloc (line_len + 1);
3383 strncpy (new_argv[0],
3384 new_line + shell_len + sizeof (minus_c) - 1, line_len);
3385 new_argv[0][line_len] = '\0';
3387 #else
3388 else
3389 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3390 __FILE__, __LINE__);
3391 #endif
3393 #endif /* ! AMIGA */
3395 return new_argv;
3397 #endif /* !VMS */
3399 /* Figure out the argument list necessary to run LINE as a command. Try to
3400 avoid using a shell. This routine handles only ' quoting, and " quoting
3401 when no backslash, $ or ` characters are seen in the quotes. Starting
3402 quotes may be escaped with a backslash. If any of the characters in
3403 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3404 is the first word of a line, the shell is used.
3406 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3407 If *RESTP is NULL, newlines will be ignored.
3409 FILE is the target whose commands these are. It is used for
3410 variable expansion for $(SHELL) and $(IFS). */
3412 char **
3413 construct_command_argv (char *line, char **restp, struct file *file,
3414 char **batch_filename_ptr)
3416 char *shell, *ifs;
3417 char **argv;
3419 #ifdef VMS
3420 char *cptr;
3421 int argc;
3423 argc = 0;
3424 cptr = line;
3425 for (;;)
3427 while ((*cptr != 0)
3428 && (isspace ((unsigned char)*cptr)))
3429 cptr++;
3430 if (*cptr == 0)
3431 break;
3432 while ((*cptr != 0)
3433 && (!isspace((unsigned char)*cptr)))
3434 cptr++;
3435 argc++;
3438 argv = (char **)malloc (argc * sizeof (char *));
3439 if (argv == 0)
3440 abort ();
3442 cptr = line;
3443 argc = 0;
3444 for (;;)
3446 while ((*cptr != 0)
3447 && (isspace ((unsigned char)*cptr)))
3448 cptr++;
3449 if (*cptr == 0)
3450 break;
3451 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3452 argv[argc++] = cptr;
3453 while ((*cptr != 0)
3454 && (!isspace((unsigned char)*cptr)))
3455 cptr++;
3456 if (*cptr != 0)
3457 *cptr++ = 0;
3459 #else
3461 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3462 int save = warn_undefined_variables_flag;
3463 warn_undefined_variables_flag = 0;
3465 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3466 #ifdef WINDOWS32
3468 * Convert to forward slashes so that construct_command_argv_internal()
3469 * is not confused.
3471 if (shell) {
3472 char *p = w32ify (shell, 0);
3473 strcpy (shell, p);
3475 #endif
3476 #ifdef __EMX__
3478 static const char *unixroot = NULL;
3479 static const char *last_shell = "";
3480 static int init = 0;
3481 if (init == 0)
3483 unixroot = getenv ("UNIXROOT");
3484 /* unixroot must be NULL or not empty */
3485 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3486 init = 1;
3489 /* if we have an unixroot drive and if shell is not default_shell
3490 (which means it's either cmd.exe or the test has already been
3491 performed) and if shell is an absolute path without drive letter,
3492 try whether it exists e.g.: if "/bin/sh" does not exist use
3493 "$UNIXROOT/bin/sh" instead. */
3494 if (unixroot && shell && strcmp (shell, last_shell) != 0
3495 && (shell[0] == '/' || shell[0] == '\\'))
3497 /* trying a new shell, check whether it exists */
3498 size_t size = strlen (shell);
3499 char *buf = xmalloc (size + 7);
3500 memcpy (buf, shell, size);
3501 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3502 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3504 /* try the same for the unixroot drive */
3505 memmove (buf + 2, buf, size + 5);
3506 buf[0] = unixroot[0];
3507 buf[1] = unixroot[1];
3508 if (access (buf, F_OK) == 0)
3509 /* we have found a shell! */
3510 /* free(shell); */
3511 shell = buf;
3512 else
3513 free (buf);
3515 else
3516 free (buf);
3519 #endif /* __EMX__ */
3521 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3523 warn_undefined_variables_flag = save;
3526 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
3528 free (shell);
3529 free (ifs);
3530 #endif /* !VMS */
3531 return argv;
3534 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3536 dup2 (int old, int new)
3538 int fd;
3540 (void) close (new);
3541 fd = dup (old);
3542 if (fd != new)
3544 (void) close (fd);
3545 errno = EMFILE;
3546 return -1;
3549 return fd;
3551 #endif /* !HAPE_DUP2 && !_AMIGA */