Update the README template.
[make/kirr.git] / job.c
blob5b8628a3f61c4e40829772a292e0f05179c791b4
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
35 char *default_shell = "sh.exe";
36 int no_default_sh_exe = 1;
37 int batch_mode_shell = 1;
38 #else /* WINDOWS32 */
39 # ifdef _AMIGA
40 char default_shell[] = "";
41 extern int MyExecute (char **);
42 # else /* _AMIGA */
43 # ifdef __MSDOS__
44 /* The default shell is a pointer so we can change it if Makefile
45 says so. It is without an explicit path so we get a chance
46 to search the $PATH for it (since MSDOS doesn't have standard
47 directories we could trust). */
48 char *default_shell = "command.com";
49 # else /* __MSDOS__ */
50 # ifdef VMS
51 # include <descrip.h>
52 char default_shell[] = "";
53 # else
54 char default_shell[] = "/bin/sh";
55 # endif /* VMS */
56 # endif /* __MSDOS__ */
57 int batch_mode_shell = 0;
58 # endif /* _AMIGA */
59 #endif /* WINDOWS32 */
61 #ifdef __MSDOS__
62 # include <process.h>
63 static int execute_by_shell;
64 static int dos_pid = 123;
65 int dos_status;
66 int dos_command_running;
67 #endif /* __MSDOS__ */
69 #ifdef _AMIGA
70 # include <proto/dos.h>
71 static int amiga_pid = 123;
72 static int amiga_status;
73 static char amiga_bname[32];
74 static int amiga_batch_file;
75 #endif /* Amiga. */
77 #ifdef VMS
78 # ifndef __GNUC__
79 # include <processes.h>
80 # endif
81 # include <starlet.h>
82 # include <lib$routines.h>
83 #endif
85 #ifdef WINDOWS32
86 # include <windows.h>
87 # include <io.h>
88 # include <process.h>
89 # include "sub_proc.h"
90 # include "w32err.h"
91 # include "pathstuff.h"
92 #endif /* WINDOWS32 */
94 #ifdef HAVE_FCNTL_H
95 # include <fcntl.h>
96 #else
97 # include <sys/file.h>
98 #endif
100 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
101 # include <sys/wait.h>
102 #endif
104 #ifdef HAVE_WAITPID
105 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
106 #else /* Don't have waitpid. */
107 # ifdef HAVE_WAIT3
108 # ifndef wait3
109 extern int wait3 ();
110 # endif
111 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
112 # endif /* Have wait3. */
113 #endif /* Have waitpid. */
115 #if !defined (wait) && !defined (POSIX)
116 extern int wait ();
117 #endif
119 #ifndef HAVE_UNION_WAIT
121 # define WAIT_T int
123 # ifndef WTERMSIG
124 # define WTERMSIG(x) ((x) & 0x7f)
125 # endif
126 # ifndef WCOREDUMP
127 # define WCOREDUMP(x) ((x) & 0x80)
128 # endif
129 # ifndef WEXITSTATUS
130 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
131 # endif
132 # ifndef WIFSIGNALED
133 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
134 # endif
135 # ifndef WIFEXITED
136 # define WIFEXITED(x) (WTERMSIG (x) == 0)
137 # endif
139 #else /* Have `union wait'. */
141 # define WAIT_T union wait
142 # ifndef WTERMSIG
143 # define WTERMSIG(x) ((x).w_termsig)
144 # endif
145 # ifndef WCOREDUMP
146 # define WCOREDUMP(x) ((x).w_coredump)
147 # endif
148 # ifndef WEXITSTATUS
149 # define WEXITSTATUS(x) ((x).w_retcode)
150 # endif
151 # ifndef WIFSIGNALED
152 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
153 # endif
154 # ifndef WIFEXITED
155 # define WIFEXITED(x) (WTERMSIG(x) == 0)
156 # endif
158 #endif /* Don't have `union wait'. */
160 /* How to set close-on-exec for a file descriptor. */
162 #if !defined F_SETFD
163 # define CLOSE_ON_EXEC(_d)
164 #else
165 # ifndef FD_CLOEXEC
166 # define FD_CLOEXEC 1
167 # endif
168 # define CLOSE_ON_EXEC(_d) (void) fcntl ((_d), F_SETFD, FD_CLOEXEC)
169 #endif
171 #ifdef VMS
172 static int vms_jobsefnmask = 0;
173 #endif /* !VMS */
175 #ifndef HAVE_UNISTD_H
176 extern int dup2 ();
177 extern int execve ();
178 extern void _exit ();
179 # ifndef VMS
180 extern int geteuid ();
181 extern int getegid ();
182 extern int setgid ();
183 extern int getgid ();
184 # endif
185 #endif
187 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
189 extern int getloadavg PARAMS ((double loadavg[], int nelem));
190 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
191 int *is_remote, int *id_ptr, int *used_stdin));
192 extern int start_remote_job_p PARAMS ((int));
193 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
194 int *coredump_ptr, int block));
196 RETSIGTYPE child_handler PARAMS ((int));
197 static void free_child PARAMS ((struct child *));
198 static void start_job_command PARAMS ((struct child *child));
199 static int load_too_high PARAMS ((void));
200 static int job_next_command PARAMS ((struct child *));
201 static int start_waiting_job PARAMS ((struct child *));
202 #ifdef VMS
203 static void vmsWaitForChildren PARAMS ((int *));
204 #endif
206 /* Chain of all live (or recently deceased) children. */
208 struct child *children = 0;
210 /* Number of children currently running. */
212 unsigned int job_slots_used = 0;
214 /* Nonzero if the `good' standard input is in use. */
216 static int good_stdin_used = 0;
218 /* Chain of children waiting to run until the load average goes down. */
220 static struct child *waiting_jobs = 0;
222 /* Non-zero if we use a *real* shell (always so on Unix). */
224 int unixy_shell = 1;
227 #ifdef WINDOWS32
229 * The macro which references this function is defined in make.h.
231 int w32_kill(int pid, int sig)
233 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
235 #endif /* WINDOWS32 */
237 /* Write an error message describing the exit status given in
238 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
239 Append "(ignored)" if IGNORED is nonzero. */
241 static void
242 child_error (target_name, exit_code, exit_sig, coredump, ignored)
243 char *target_name;
244 int exit_code, exit_sig, coredump;
245 int ignored;
247 if (ignored && silent_flag)
248 return;
250 #ifdef VMS
251 if (!(exit_code & 1))
252 error (NILF,
253 (ignored ? _("*** [%s] Error 0x%x (ignored)")
254 : _("*** [%s] Error 0x%x")),
255 target_name, exit_code);
256 #else
257 if (exit_sig == 0)
258 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
259 _("*** [%s] Error %d"),
260 target_name, exit_code);
261 else
262 error (NILF, "*** [%s] %s%s",
263 target_name, strsignal (exit_sig),
264 coredump ? _(" (core dumped)") : "");
265 #endif /* VMS */
268 #ifdef VMS
269 /* Wait for nchildren children to terminate */
270 static void
271 vmsWaitForChildren(int *status)
273 while (1)
275 if (!vms_jobsefnmask)
277 *status = 0;
278 return;
281 *status = sys$wflor (32, vms_jobsefnmask);
283 return;
286 /* Set up IO redirection. */
288 char *
289 vms_redirect (desc, fname, ibuf)
290 struct dsc$descriptor_s *desc;
291 char *fname;
292 char *ibuf;
294 char *fptr;
295 extern char *vmsify ();
297 ibuf++;
298 while (isspace ((unsigned char)*ibuf))
299 ibuf++;
300 fptr = ibuf;
301 while (*ibuf && !isspace ((unsigned char)*ibuf))
302 ibuf++;
303 *ibuf = 0;
304 if (strcmp (fptr, "/dev/null") != 0)
306 strcpy (fname, vmsify (fptr, 0));
307 if (strchr (fname, '.') == 0)
308 strcat (fname, ".");
310 desc->dsc$w_length = strlen(fname);
311 desc->dsc$a_pointer = fname;
312 desc->dsc$b_dtype = DSC$K_DTYPE_T;
313 desc->dsc$b_class = DSC$K_CLASS_S;
315 if (*fname == 0)
316 printf (_("Warning: Empty redirection\n"));
317 return ibuf;
322 found apostrophe at (p-1)
324 inc p until after closing apostrophe. */
326 static char *
327 handle_apos (char *p)
329 int alast;
330 int inside;
332 #define SEPCHARS ",/()= "
334 inside = 0;
336 while (*p != 0)
338 if (*p == '"')
340 if (inside)
342 while ((alast > 0)
343 && (*p == '"'))
345 p++;
346 alast--;
348 if (alast == 0)
349 inside = 0;
350 else
352 fprintf (stderr, _("Syntax error, still inside '\"'\n"));
353 exit (3);
356 else
358 p++;
359 if (strchr (SEPCHARS, *p))
360 break;
361 inside = 1;
362 alast = 1;
363 while (*p == '"')
365 alast++;
366 p++;
370 else
371 p++;
374 return p;
377 #endif
380 /* Handle a dead child. This handler may or may not ever be installed.
382 If we're using the jobserver feature, we need it. First, installing it
383 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
384 read FD to ensure we don't enter another blocking read without reaping all
385 the dead children. In this case we don't need the dead_children count.
387 If we don't have either waitpid or wait3, then make is unreliable, but we
388 use the dead_children count to reap children as best we can. */
390 static unsigned int dead_children = 0;
392 RETSIGTYPE
393 child_handler (sig)
394 int sig;
396 ++dead_children;
398 if (job_rfd >= 0)
400 close (job_rfd);
401 job_rfd = -1;
404 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
408 extern int shell_function_pid, shell_function_completed;
410 /* Reap all dead children, storing the returned status and the new command
411 state (`cs_finished') in the `file' member of the `struct child' for the
412 dead child, and removing the child from the chain. In addition, if BLOCK
413 nonzero, we block in this function until we've reaped at least one
414 complete child, waiting for it to die if necessary. If ERR is nonzero,
415 print an error message first. */
417 void
418 reap_children (block, err)
419 int block, err;
421 WAIT_T status;
422 /* Initially, assume we have some. */
423 int reap_more = 1;
425 #ifdef WAIT_NOHANG
426 # define REAP_MORE reap_more
427 #else
428 # define REAP_MORE dead_children
429 #endif
431 /* As long as:
433 We have at least one child outstanding OR a shell function in progress,
435 We're blocking for a complete child OR there are more children to reap
437 we'll keep reaping children. */
439 while ((children != 0 || shell_function_pid != 0)
440 && (block || REAP_MORE))
442 int remote = 0;
443 register int pid;
444 int exit_code, exit_sig, coredump;
445 register struct child *lastc, *c;
446 int child_failed;
447 int any_remote, any_local;
449 if (err && block)
451 /* We might block for a while, so let the user know why. */
452 fflush (stdout);
453 error (NILF, _("*** Waiting for unfinished jobs...."));
456 /* We have one less dead child to reap. As noted in
457 child_handler() above, this count is completely unimportant for
458 all modern, POSIX-y systems that support wait3() or waitpid().
459 The rest of this comment below applies only to early, broken
460 pre-POSIX systems. We keep the count only because... it's there...
462 The test and decrement are not atomic; if it is compiled into:
463 register = dead_children - 1;
464 dead_children = register;
465 a SIGCHLD could come between the two instructions.
466 child_handler increments dead_children.
467 The second instruction here would lose that increment. But the
468 only effect of dead_children being wrong is that we might wait
469 longer than necessary to reap a child, and lose some parallelism;
470 and we might print the "Waiting for unfinished jobs" message above
471 when not necessary. */
473 if (dead_children > 0)
474 --dead_children;
476 any_remote = 0;
477 any_local = shell_function_pid != 0;
478 for (c = children; c != 0; c = c->next)
480 any_remote |= c->remote;
481 any_local |= ! c->remote;
482 DB (DB_JOBS, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
483 (unsigned long int) c, c->file->name,
484 (long) c->pid, c->remote ? _(" (remote)") : ""));
485 #ifdef VMS
486 break;
487 #endif
490 /* First, check for remote children. */
491 if (any_remote)
492 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
493 else
494 pid = 0;
496 if (pid > 0)
497 /* We got a remote child. */
498 remote = 1;
499 else if (pid < 0)
501 /* A remote status command failed miserably. Punt. */
502 remote_status_lose:
503 pfatal_with_name ("remote_status");
505 else
507 /* No remote children. Check for local children. */
508 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
509 if (any_local)
511 #ifdef VMS
512 vmsWaitForChildren (&status);
513 pid = c->pid;
514 #else
515 #ifdef WAIT_NOHANG
516 if (!block)
517 pid = WAIT_NOHANG (&status);
518 else
519 #endif
520 pid = wait (&status);
521 #endif /* !VMS */
523 else
524 pid = 0;
526 if (pid < 0)
528 /* The wait*() failed miserably. Punt. */
529 pfatal_with_name ("wait");
531 else if (pid > 0)
533 /* We got a child exit; chop the status word up. */
534 exit_code = WEXITSTATUS (status);
535 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
536 coredump = WCOREDUMP (status);
538 else
540 /* No local children are dead. */
541 reap_more = 0;
543 if (!block || !any_remote)
544 break;
546 /* Now try a blocking wait for a remote child. */
547 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
548 if (pid < 0)
549 goto remote_status_lose;
550 else if (pid == 0)
551 /* No remote children either. Finally give up. */
552 break;
554 /* We got a remote child. */
555 remote = 1;
557 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
559 #ifdef __MSDOS__
560 /* Life is very different on MSDOS. */
561 pid = dos_pid - 1;
562 status = dos_status;
563 exit_code = WEXITSTATUS (status);
564 if (exit_code == 0xff)
565 exit_code = -1;
566 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
567 coredump = 0;
568 #endif /* __MSDOS__ */
569 #ifdef _AMIGA
570 /* Same on Amiga */
571 pid = amiga_pid - 1;
572 status = amiga_status;
573 exit_code = amiga_status;
574 exit_sig = 0;
575 coredump = 0;
576 #endif /* _AMIGA */
577 #ifdef WINDOWS32
579 HANDLE hPID;
580 int err;
582 /* wait for anything to finish */
583 if (hPID = process_wait_for_any()) {
585 /* was an error found on this process? */
586 err = process_last_err(hPID);
588 /* get exit data */
589 exit_code = process_exit_code(hPID);
591 if (err)
592 fprintf(stderr, "make (e=%d): %s",
593 exit_code, map_windows32_error_to_string(exit_code));
595 /* signal */
596 exit_sig = process_signal(hPID);
598 /* cleanup process */
599 process_cleanup(hPID);
601 coredump = 0;
603 pid = (int) hPID;
605 #endif /* WINDOWS32 */
608 /* Check if this is the child of the `shell' function. */
609 if (!remote && pid == shell_function_pid)
611 /* It is. Leave an indicator for the `shell' function. */
612 if (exit_sig == 0 && exit_code == 127)
613 shell_function_completed = -1;
614 else
615 shell_function_completed = 1;
616 break;
619 child_failed = exit_sig != 0 || exit_code != 0;
621 /* Search for a child matching the deceased one. */
622 lastc = 0;
623 for (c = children; c != 0; lastc = c, c = c->next)
624 if (c->remote == remote && c->pid == pid)
625 break;
627 if (c == 0)
628 /* An unknown child died.
629 Ignore it; it was inherited from our invoker. */
630 continue;
632 DB (DB_JOBS, (child_failed
633 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
634 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
635 (unsigned long int) c, (long) c->pid,
636 c->remote ? _(" (remote)") : ""));
638 if (c->sh_batch_file) {
639 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
640 c->sh_batch_file));
642 /* just try and remove, don't care if this fails */
643 remove (c->sh_batch_file);
645 /* all done with memory */
646 free (c->sh_batch_file);
647 c->sh_batch_file = NULL;
650 /* If this child had the good stdin, say it is now free. */
651 if (c->good_stdin)
652 good_stdin_used = 0;
654 if (child_failed && !c->noerror && !ignore_errors_flag)
656 /* The commands failed. Write an error message,
657 delete non-precious targets, and abort. */
658 static int delete_on_error = -1;
659 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
660 c->file->update_status = 2;
661 if (delete_on_error == -1)
663 struct file *f = lookup_file (".DELETE_ON_ERROR");
664 delete_on_error = f != 0 && f->is_target;
666 if (exit_sig != 0 || delete_on_error)
667 delete_child_targets (c);
669 else
671 if (child_failed)
673 /* The commands failed, but we don't care. */
674 child_error (c->file->name,
675 exit_code, exit_sig, coredump, 1);
676 child_failed = 0;
679 /* If there are more commands to run, try to start them. */
680 if (job_next_command (c))
682 if (handling_fatal_signal)
684 /* Never start new commands while we are dying.
685 Since there are more commands that wanted to be run,
686 the target was not completely remade. So we treat
687 this as if a command had failed. */
688 c->file->update_status = 2;
690 else
692 /* Check again whether to start remotely.
693 Whether or not we want to changes over time.
694 Also, start_remote_job may need state set up
695 by start_remote_job_p. */
696 c->remote = start_remote_job_p (0);
697 start_job_command (c);
698 /* Fatal signals are left blocked in case we were
699 about to put that child on the chain. But it is
700 already there, so it is safe for a fatal signal to
701 arrive now; it will clean up this child's targets. */
702 unblock_sigs ();
703 if (c->file->command_state == cs_running)
704 /* We successfully started the new command.
705 Loop to reap more children. */
706 continue;
709 if (c->file->update_status != 0)
710 /* We failed to start the commands. */
711 delete_child_targets (c);
713 else
714 /* There are no more commands. We got through them all
715 without an unignored error. Now the target has been
716 successfully updated. */
717 c->file->update_status = 0;
720 /* When we get here, all the commands for C->file are finished
721 (or aborted) and C->file->update_status contains 0 or 2. But
722 C->file->command_state is still cs_running if all the commands
723 ran; notice_finish_file looks for cs_running to tell it that
724 it's interesting to check the file's modtime again now. */
726 if (! handling_fatal_signal)
727 /* Notice if the target of the commands has been changed.
728 This also propagates its values for command_state and
729 update_status to its also_make files. */
730 notice_finished_file (c->file);
732 DB (DB_JOBS, (_("Removing child 0x%08lx PID %ld%s from chain.\n"),
733 (unsigned long int) c, (long) c->pid,
734 c->remote ? _(" (remote)") : ""));
736 /* Block fatal signals while frobnicating the list, so that
737 children and job_slots_used are always consistent. Otherwise
738 a fatal signal arriving after the child is off the chain and
739 before job_slots_used is decremented would believe a child was
740 live and call reap_children again. */
741 block_sigs ();
743 /* There is now another slot open. */
744 if (job_slots_used > 0)
745 --job_slots_used;
747 /* Remove the child from the chain and free it. */
748 if (lastc == 0)
749 children = c->next;
750 else
751 lastc->next = c->next;
753 free_child (c);
755 unblock_sigs ();
757 /* If the job failed, and the -k flag was not given, die,
758 unless we are already in the process of dying. */
759 if (!err && child_failed && !keep_going_flag &&
760 /* fatal_error_signal will die with the right signal. */
761 !handling_fatal_signal)
762 die (2);
764 /* Only block for one child. */
765 block = 0;
768 return;
771 /* Free the storage allocated for CHILD. */
773 static void
774 free_child (child)
775 register struct child *child;
777 /* If this child is the only one it was our "free" job, so don't put a
778 token back for it. This child has already been removed from the list,
779 so if there any left this wasn't the last one. */
781 if (job_fds[1] >= 0 && children)
783 char token = '+';
785 /* Write a job token back to the pipe. */
787 if (write (job_fds[1], &token, 1) != 1)
788 pfatal_with_name (_("write jobserver"));
790 DB (DB_JOBS, (_("Released token for child 0x%08lx (%s).\n"),
791 (unsigned long int) child, child->file->name));
794 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
795 return;
797 if (child->command_lines != 0)
799 register unsigned int i;
800 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
801 free (child->command_lines[i]);
802 free ((char *) child->command_lines);
805 if (child->environment != 0)
807 register char **ep = child->environment;
808 while (*ep != 0)
809 free (*ep++);
810 free ((char *) child->environment);
813 free ((char *) child);
816 #ifdef POSIX
817 extern sigset_t fatal_signal_set;
818 #endif
820 void
821 block_sigs ()
823 #ifdef POSIX
824 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
825 #else
826 # ifdef HAVE_SIGSETMASK
827 (void) sigblock (fatal_signal_mask);
828 # endif
829 #endif
832 #ifdef POSIX
833 void
834 unblock_sigs ()
836 sigset_t empty;
837 sigemptyset (&empty);
838 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
840 #endif
842 #ifdef MAKE_JOBSERVER
843 /* Set the child handler action flags to FLAGS. */
844 static void
845 set_child_handler_action_flags (flags)
846 int flags;
848 struct sigaction sa;
849 bzero ((char *) &sa, sizeof sa);
850 sa.sa_handler = child_handler;
851 sa.sa_flags = flags;
852 #if defined SIGCHLD
853 sigaction (SIGCHLD, &sa, NULL);
854 #endif
855 #if defined SIGCLD && SIGCLD != SIGCHLD
856 sigaction (SIGCLD, &sa, NULL);
857 #endif
859 #endif
862 /* Start a job to run the commands specified in CHILD.
863 CHILD is updated to reflect the commands and ID of the child process.
865 NOTE: On return fatal signals are blocked! The caller is responsible
866 for calling `unblock_sigs', once the new child is safely on the chain so
867 it can be cleaned up in the event of a fatal signal. */
869 static void
870 start_job_command (child)
871 register struct child *child;
873 #ifndef _AMIGA
874 static int bad_stdin = -1;
875 #endif
876 register char *p;
877 int flags;
878 #ifdef VMS
879 char *argv;
880 #else
881 char **argv;
882 #endif
884 /* If we have a completely empty commandset, stop now. */
885 if (!child->command_ptr)
886 goto next_command;
888 /* Combine the flags parsed for the line itself with
889 the flags specified globally for this target. */
890 flags = (child->file->command_flags
891 | child->file->cmds->lines_flags[child->command_line - 1]);
893 p = child->command_ptr;
894 child->noerror = flags & COMMANDS_NOERROR;
896 while (*p != '\0')
898 if (*p == '@')
899 flags |= COMMANDS_SILENT;
900 else if (*p == '+')
901 flags |= COMMANDS_RECURSE;
902 else if (*p == '-')
903 child->noerror = 1;
904 else if (!isblank ((unsigned char)*p))
905 break;
906 ++p;
909 /* Update the file's command flags with any new ones we found. We only
910 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
911 now marking more commands recursive than should be in the case of
912 multiline define/endef scripts where only one line is marked "+". In
913 order to really fix this, we'll have to keep a lines_flags for every
914 actual line, after expansion. */
915 child->file->cmds->lines_flags[child->command_line - 1]
916 |= flags & COMMANDS_RECURSE;
918 /* Figure out an argument list from this command line. */
921 char *end = 0;
922 #ifdef VMS
923 argv = p;
924 #else
925 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
926 #endif
927 if (end == NULL)
928 child->command_ptr = NULL;
929 else
931 *end++ = '\0';
932 child->command_ptr = end;
936 /* If -q was given, say that updating `failed' if there was any text on the
937 command line, or `succeeded' otherwise. The exit status of 1 tells the
938 user that -q is saying `something to do'; the exit status for a random
939 error is 2. */
940 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
942 #ifndef VMS
943 free (argv[0]);
944 free ((char *) argv);
945 #endif
946 child->file->update_status = 1;
947 notice_finished_file (child->file);
948 return;
951 if (touch_flag && !(flags & COMMANDS_RECURSE))
953 /* Go on to the next command. It might be the recursive one.
954 We construct ARGV only to find the end of the command line. */
955 #ifndef VMS
956 if (argv)
958 free (argv[0]);
959 free ((char *) argv);
961 #endif
962 argv = 0;
965 if (argv == 0)
967 next_command:
968 #ifdef __MSDOS__
969 execute_by_shell = 0; /* in case construct_command_argv sets it */
970 #endif
971 /* This line has no commands. Go to the next. */
972 if (job_next_command (child))
973 start_job_command (child);
974 else
976 /* No more commands. Make sure we're "running"; we might not be if
977 (e.g.) all commands were skipped due to -n. */
978 set_command_state (child->file, cs_running);
979 child->file->update_status = 0;
980 notice_finished_file (child->file);
982 return;
985 /* Print out the command. If silent, we call `message' with null so it
986 can log the working directory before the command's own error messages
987 appear. */
989 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
990 ? "%s" : (char *) 0, p);
992 /* Tell update_goal_chain that a command has been started on behalf of
993 this target. It is important that this happens here and not in
994 reap_children (where we used to do it), because reap_children might be
995 reaping children from a different target. We want this increment to
996 guaranteedly indicate that a command was started for the dependency
997 chain (i.e., update_file recursion chain) we are processing. */
999 ++commands_started;
1001 /* Optimize an empty command. People use this for timestamp rules,
1002 so avoid forking a useless shell. Do this after we increment
1003 commands_started so make still treats this special case as if it
1004 performed some action (makes a difference as to what messages are
1005 printed, etc. */
1007 #if !defined(VMS) && !defined(_AMIGA)
1008 if (
1009 #ifdef __MSDOS__
1010 unixy_shell /* the test is complicated and we already did it */
1011 #else
1012 (argv[0] && !strcmp (argv[0], "/bin/sh"))
1013 #endif
1014 && (argv[1]
1015 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
1016 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1017 && argv[3] == NULL)
1019 free (argv[0]);
1020 free ((char *) argv);
1021 goto next_command;
1023 #endif /* !VMS && !_AMIGA */
1025 /* If -n was given, recurse to get the next line in the sequence. */
1027 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1029 #ifndef VMS
1030 free (argv[0]);
1031 free ((char *) argv);
1032 #endif
1033 goto next_command;
1036 /* Flush the output streams so they won't have things written twice. */
1038 fflush (stdout);
1039 fflush (stderr);
1041 #ifndef VMS
1042 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1044 /* Set up a bad standard input that reads from a broken pipe. */
1046 if (bad_stdin == -1)
1048 /* Make a file descriptor that is the read end of a broken pipe.
1049 This will be used for some children's standard inputs. */
1050 int pd[2];
1051 if (pipe (pd) == 0)
1053 /* Close the write side. */
1054 (void) close (pd[1]);
1055 /* Save the read side. */
1056 bad_stdin = pd[0];
1058 /* Set the descriptor to close on exec, so it does not litter any
1059 child's descriptor table. When it is dup2'd onto descriptor 0,
1060 that descriptor will not close on exec. */
1061 CLOSE_ON_EXEC (bad_stdin);
1065 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1067 /* Decide whether to give this child the `good' standard input
1068 (one that points to the terminal or whatever), or the `bad' one
1069 that points to the read side of a broken pipe. */
1071 child->good_stdin = !good_stdin_used;
1072 if (child->good_stdin)
1073 good_stdin_used = 1;
1075 #endif /* !VMS */
1077 child->deleted = 0;
1079 #ifndef _AMIGA
1080 /* Set up the environment for the child. */
1081 if (child->environment == 0)
1082 child->environment = target_environment (child->file);
1083 #endif
1085 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1087 #ifndef VMS
1088 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1089 if (child->remote)
1091 int is_remote, id, used_stdin;
1092 if (start_remote_job (argv, child->environment,
1093 child->good_stdin ? 0 : bad_stdin,
1094 &is_remote, &id, &used_stdin))
1095 /* Don't give up; remote execution may fail for various reasons. If
1096 so, simply run the job locally. */
1097 goto run_local;
1098 else
1100 if (child->good_stdin && !used_stdin)
1102 child->good_stdin = 0;
1103 good_stdin_used = 0;
1105 child->remote = is_remote;
1106 child->pid = id;
1109 else
1110 #endif /* !VMS */
1112 /* Fork the child process. */
1114 char **parent_environ;
1116 run_local:
1117 block_sigs ();
1119 child->remote = 0;
1121 #ifdef VMS
1123 if (!child_execute_job (argv, child)) {
1124 /* Fork failed! */
1125 perror_with_name ("vfork", "");
1126 goto error;
1129 #else
1131 parent_environ = environ;
1132 child->pid = vfork ();
1133 environ = parent_environ; /* Restore value child may have clobbered. */
1134 if (child->pid == 0)
1136 /* We are the child side. */
1137 unblock_sigs ();
1139 /* If we aren't running a recursive command and we have a jobserver
1140 pipe, close it before exec'ing. */
1141 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1143 close (job_fds[0]);
1144 close (job_fds[1]);
1146 if (job_rfd >= 0)
1147 close (job_rfd);
1149 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1150 argv, child->environment);
1152 else if (child->pid < 0)
1154 /* Fork failed! */
1155 unblock_sigs ();
1156 perror_with_name ("vfork", "");
1157 goto error;
1159 #endif /* !VMS */
1162 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1163 #ifdef __MSDOS__
1165 int proc_return;
1167 block_sigs ();
1168 dos_status = 0;
1170 /* We call `system' to do the job of the SHELL, since stock DOS
1171 shell is too dumb. Our `system' knows how to handle long
1172 command lines even if pipes/redirection is needed; it will only
1173 call COMMAND.COM when its internal commands are used. */
1174 if (execute_by_shell)
1176 char *cmdline = argv[0];
1177 /* We don't have a way to pass environment to `system',
1178 so we need to save and restore ours, sigh... */
1179 char **parent_environ = environ;
1181 environ = child->environment;
1183 /* If we have a *real* shell, tell `system' to call
1184 it to do everything for us. */
1185 if (unixy_shell)
1187 /* A *real* shell on MSDOS may not support long
1188 command lines the DJGPP way, so we must use `system'. */
1189 cmdline = argv[2]; /* get past "shell -c" */
1192 dos_command_running = 1;
1193 proc_return = system (cmdline);
1194 environ = parent_environ;
1195 execute_by_shell = 0; /* for the next time */
1197 else
1199 dos_command_running = 1;
1200 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1203 /* Need to unblock signals before turning off
1204 dos_command_running, so that child's signals
1205 will be treated as such (see fatal_error_signal). */
1206 unblock_sigs ();
1207 dos_command_running = 0;
1209 /* If the child got a signal, dos_status has its
1210 high 8 bits set, so be careful not to alter them. */
1211 if (proc_return == -1)
1212 dos_status |= 0xff;
1213 else
1214 dos_status |= (proc_return & 0xff);
1215 ++dead_children;
1216 child->pid = dos_pid++;
1218 #endif /* __MSDOS__ */
1219 #ifdef _AMIGA
1220 amiga_status = MyExecute (argv);
1222 ++dead_children;
1223 child->pid = amiga_pid++;
1224 if (amiga_batch_file)
1226 amiga_batch_file = 0;
1227 DeleteFile (amiga_bname); /* Ignore errors. */
1229 #endif /* Amiga */
1230 #ifdef WINDOWS32
1232 HANDLE hPID;
1233 char* arg0;
1235 /* make UNC paths safe for CreateProcess -- backslash format */
1236 arg0 = argv[0];
1237 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1238 for ( ; arg0 && *arg0; arg0++)
1239 if (*arg0 == '/')
1240 *arg0 = '\\';
1242 /* make sure CreateProcess() has Path it needs */
1243 sync_Path_environment();
1245 hPID = process_easy(argv, child->environment);
1247 if (hPID != INVALID_HANDLE_VALUE)
1248 child->pid = (int) hPID;
1249 else {
1250 int i;
1251 unblock_sigs();
1252 fprintf(stderr,
1253 _("process_easy() failed failed to launch process (e=%d)\n"),
1254 process_last_err(hPID));
1255 for (i = 0; argv[i]; i++)
1256 fprintf(stderr, "%s ", argv[i]);
1257 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1260 #endif /* WINDOWS32 */
1261 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1263 /* We are the parent side. Set the state to
1264 say the commands are running and return. */
1266 set_command_state (child->file, cs_running);
1268 /* Free the storage used by the child's argument list. */
1269 #ifndef VMS
1270 free (argv[0]);
1271 free ((char *) argv);
1272 #endif
1274 return;
1276 error:
1277 child->file->update_status = 2;
1278 notice_finished_file (child->file);
1279 return;
1282 /* Try to start a child running.
1283 Returns nonzero if the child was started (and maybe finished), or zero if
1284 the load was too high and the child was put on the `waiting_jobs' chain. */
1286 static int
1287 start_waiting_job (c)
1288 struct child *c;
1290 struct file *f = c->file;
1292 /* If we can start a job remotely, we always want to, and don't care about
1293 the local load average. We record that the job should be started
1294 remotely in C->remote for start_job_command to test. */
1296 c->remote = start_remote_job_p (1);
1298 /* If we are running at least one job already and the load average
1299 is too high, make this one wait. */
1300 if (!c->remote && job_slots_used > 0 && load_too_high ())
1302 /* Put this child on the chain of children waiting for the load average
1303 to go down. */
1304 set_command_state (f, cs_running);
1305 c->next = waiting_jobs;
1306 waiting_jobs = c;
1307 return 0;
1310 /* Start the first command; reap_children will run later command lines. */
1311 start_job_command (c);
1313 switch (f->command_state)
1315 case cs_running:
1316 c->next = children;
1317 DB (DB_JOBS, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1318 (unsigned long int) c, c->file->name,
1319 (long) c->pid, c->remote ? _(" (remote)") : ""));
1320 children = c;
1321 /* One more job slot is in use. */
1322 ++job_slots_used;
1323 unblock_sigs ();
1324 break;
1326 case cs_not_started:
1327 /* All the command lines turned out to be empty. */
1328 f->update_status = 0;
1329 /* FALLTHROUGH */
1331 case cs_finished:
1332 notice_finished_file (f);
1333 free_child (c);
1334 break;
1336 default:
1337 assert (f->command_state == cs_finished);
1338 break;
1341 return 1;
1344 /* Create a `struct child' for FILE and start its commands running. */
1346 void
1347 new_job (file)
1348 register struct file *file;
1350 register struct commands *cmds = file->cmds;
1351 register struct child *c;
1352 char **lines;
1353 register unsigned int i;
1355 /* Let any previously decided-upon jobs that are waiting
1356 for the load to go down start before this new one. */
1357 start_waiting_jobs ();
1359 /* Reap any children that might have finished recently. */
1360 reap_children (0, 0);
1362 /* Chop the commands up into lines if they aren't already. */
1363 chop_commands (cmds);
1365 /* Expand the command lines and store the results in LINES. */
1366 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1367 for (i = 0; i < cmds->ncommand_lines; ++i)
1369 /* Collapse backslash-newline combinations that are inside variable
1370 or function references. These are left alone by the parser so
1371 that they will appear in the echoing of commands (where they look
1372 nice); and collapsed by construct_command_argv when it tokenizes.
1373 But letting them survive inside function invocations loses because
1374 we don't want the functions to see them as part of the text. */
1376 char *in, *out, *ref;
1378 /* IN points to where in the line we are scanning.
1379 OUT points to where in the line we are writing.
1380 When we collapse a backslash-newline combination,
1381 IN gets ahead of OUT. */
1383 in = out = cmds->command_lines[i];
1384 while ((ref = strchr (in, '$')) != 0)
1386 ++ref; /* Move past the $. */
1388 if (out != in)
1389 /* Copy the text between the end of the last chunk
1390 we processed (where IN points) and the new chunk
1391 we are about to process (where REF points). */
1392 bcopy (in, out, ref - in);
1394 /* Move both pointers past the boring stuff. */
1395 out += ref - in;
1396 in = ref;
1398 if (*ref == '(' || *ref == '{')
1400 char openparen = *ref;
1401 char closeparen = openparen == '(' ? ')' : '}';
1402 int count;
1403 char *p;
1405 *out++ = *in++; /* Copy OPENPAREN. */
1406 /* IN now points past the opening paren or brace.
1407 Count parens or braces until it is matched. */
1408 count = 0;
1409 while (*in != '\0')
1411 if (*in == closeparen && --count < 0)
1412 break;
1413 else if (*in == '\\' && in[1] == '\n')
1415 /* We have found a backslash-newline inside a
1416 variable or function reference. Eat it and
1417 any following whitespace. */
1419 int quoted = 0;
1420 for (p = in - 1; p > ref && *p == '\\'; --p)
1421 quoted = !quoted;
1423 if (quoted)
1424 /* There were two or more backslashes, so this is
1425 not really a continuation line. We don't collapse
1426 the quoting backslashes here as is done in
1427 collapse_continuations, because the line will
1428 be collapsed again after expansion. */
1429 *out++ = *in++;
1430 else
1432 /* Skip the backslash, newline and
1433 any following whitespace. */
1434 in = next_token (in + 2);
1436 /* Discard any preceding whitespace that has
1437 already been written to the output. */
1438 while (out > ref
1439 && isblank ((unsigned char)out[-1]))
1440 --out;
1442 /* Replace it all with a single space. */
1443 *out++ = ' ';
1446 else
1448 if (*in == openparen)
1449 ++count;
1451 *out++ = *in++;
1457 /* There are no more references in this line to worry about.
1458 Copy the remaining uninteresting text to the output. */
1459 if (out != in)
1460 strcpy (out, in);
1462 /* Finally, expand the line. */
1463 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1464 file);
1467 /* Start the command sequence, record it in a new
1468 `struct child', and add that to the chain. */
1470 c = (struct child *) xmalloc (sizeof (struct child));
1471 bzero ((char *)c, sizeof (struct child));
1472 c->file = file;
1473 c->command_lines = lines;
1474 c->sh_batch_file = NULL;
1476 /* Fetch the first command line to be run. */
1477 job_next_command (c);
1479 /* Wait for a job slot to be freed up. If we allow an infinite number
1480 don't bother; also job_slots will == 0 if we're using the jobserver. */
1482 if (job_slots != 0)
1483 while (job_slots_used == job_slots)
1484 reap_children (1, 0);
1486 #ifdef MAKE_JOBSERVER
1487 /* If we are controlling multiple jobs make sure we have a token before
1488 starting the child. */
1490 /* This can be inefficient. There's a decent chance that this job won't
1491 actually have to run any subprocesses: the command script may be empty
1492 or otherwise optimized away. It would be nice if we could defer
1493 obtaining a token until just before we need it, in start_job_command.
1494 To do that we'd need to keep track of whether we'd already obtained a
1495 token (since start_job_command is called for each line of the job, not
1496 just once). Also more thought needs to go into the entire algorithm;
1497 this is where the old parallel job code waits, so... */
1499 else if (job_fds[0] >= 0)
1500 while (1)
1502 char token;
1503 int got_token;
1504 int saved_errno;
1506 DB (DB_JOBS, ("Need a job token; we %shave children\n",
1507 children ? "" : "don't "));
1509 /* If we don't already have a job started, use our "free" token. */
1510 if (!children)
1511 break;
1513 /* Read a token. As long as there's no token available we'll block.
1514 We enable interruptible system calls before the read(2) so that if
1515 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1516 we can process the death(s) and return tokens to the free pool.
1518 Once we return from the read, we immediately reinstate restartable
1519 system calls. This allows us to not worry about checking for
1520 EINTR on all the other system calls in the program.
1522 There is one other twist: there is a span between the time
1523 reap_children() does its last check for dead children and the time
1524 the read(2) call is entered, below, where if a child dies we won't
1525 notice. This is extremely serious as it could cause us to
1526 deadlock, given the right set of events.
1528 To avoid this, we do the following: before we reap_children(), we
1529 dup(2) the read FD on the jobserver pipe. The read(2) call below
1530 uses that new FD. In the signal handler, we close that FD. That
1531 way, if a child dies during the section mentioned above, the
1532 read(2) will be invoked with an invalid FD and will return
1533 immediately with EBADF. */
1535 /* Make sure we have a dup'd FD. */
1536 if (job_rfd < 0)
1538 DB (DB_JOBS, ("Duplicate the job FD\n"));
1539 job_rfd = dup (job_fds[0]);
1542 /* Reap anything that's currently waiting. */
1543 reap_children (0, 0);
1545 /* If our "free" token has become available, use it. */
1546 if (!children)
1547 break;
1549 /* Set interruptible system calls, and read() for a job token. */
1550 set_child_handler_action_flags (0);
1551 got_token = read (job_rfd, &token, 1);
1552 saved_errno = errno;
1553 set_child_handler_action_flags (SA_RESTART);
1555 /* If we got one, we're done here. */
1556 if (got_token == 1)
1558 DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1559 (unsigned long int) c, c->file->name));
1560 break;
1563 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1564 go back and reap_children(), and try again. */
1565 errno = saved_errno;
1566 if (errno != EINTR && errno != EBADF)
1567 pfatal_with_name (_("read jobs pipe"));
1568 if (errno == EBADF)
1569 DB (DB_JOBS, ("Read returned EBADF.\n"));
1571 #endif
1573 /* The job is now primed. Start it running.
1574 (This will notice if there are in fact no commands.) */
1575 (void) start_waiting_job (c);
1577 if (job_slots == 1 || not_parallel)
1578 /* Since there is only one job slot, make things run linearly.
1579 Wait for the child to die, setting the state to `cs_finished'. */
1580 while (file->command_state == cs_running)
1581 reap_children (1, 0);
1583 return;
1586 /* Move CHILD's pointers to the next command for it to execute.
1587 Returns nonzero if there is another command. */
1589 static int
1590 job_next_command (child)
1591 struct child *child;
1593 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1595 /* There are no more lines in the expansion of this line. */
1596 if (child->command_line == child->file->cmds->ncommand_lines)
1598 /* There are no more lines to be expanded. */
1599 child->command_ptr = 0;
1600 return 0;
1602 else
1603 /* Get the next line to run. */
1604 child->command_ptr = child->command_lines[child->command_line++];
1606 return 1;
1609 static int
1610 load_too_high ()
1612 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1613 return 1;
1614 #else
1615 double load;
1617 if (max_load_average < 0)
1618 return 0;
1620 make_access ();
1621 if (getloadavg (&load, 1) != 1)
1623 static int lossage = -1;
1624 /* Complain only once for the same error. */
1625 if (lossage == -1 || errno != lossage)
1627 if (errno == 0)
1628 /* An errno value of zero means getloadavg is just unsupported. */
1629 error (NILF,
1630 _("cannot enforce load limits on this operating system"));
1631 else
1632 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1634 lossage = errno;
1635 load = 0;
1637 user_access ();
1639 DB (DB_JOBS, ("Current system load = %f (max requested = %f)\n",
1640 load, max_load_average));
1641 return load >= max_load_average;
1642 #endif
1645 /* Start jobs that are waiting for the load to be lower. */
1647 void
1648 start_waiting_jobs ()
1650 struct child *job;
1652 if (waiting_jobs == 0)
1653 return;
1657 /* Check for recently deceased descendants. */
1658 reap_children (0, 0);
1660 /* Take a job off the waiting list. */
1661 job = waiting_jobs;
1662 waiting_jobs = job->next;
1664 /* Try to start that job. We break out of the loop as soon
1665 as start_waiting_job puts one back on the waiting list. */
1667 while (start_waiting_job (job) && waiting_jobs != 0);
1669 return;
1672 #ifndef WINDOWS32
1673 #ifdef VMS
1674 #include <descrip.h>
1675 #include <clidef.h>
1677 /* This is called as an AST when a child process dies (it won't get
1678 interrupted by anything except a higher level AST).
1680 int vmsHandleChildTerm(struct child *child)
1682 int status;
1683 register struct child *lastc, *c;
1684 int child_failed;
1686 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1688 lib$free_ef(&child->efn);
1690 (void) sigblock (fatal_signal_mask);
1692 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1694 /* Search for a child matching the deceased one. */
1695 lastc = 0;
1696 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1697 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1698 #else
1699 c = child;
1700 #endif
1702 if (child_failed && !c->noerror && !ignore_errors_flag)
1704 /* The commands failed. Write an error message,
1705 delete non-precious targets, and abort. */
1706 child_error (c->file->name, c->cstatus, 0, 0, 0);
1707 c->file->update_status = 1;
1708 delete_child_targets (c);
1710 else
1712 if (child_failed)
1714 /* The commands failed, but we don't care. */
1715 child_error (c->file->name, c->cstatus, 0, 0, 1);
1716 child_failed = 0;
1719 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1720 /* If there are more commands to run, try to start them. */
1721 start_job (c);
1723 switch (c->file->command_state)
1725 case cs_running:
1726 /* Successfully started. */
1727 break;
1729 case cs_finished:
1730 if (c->file->update_status != 0) {
1731 /* We failed to start the commands. */
1732 delete_child_targets (c);
1734 break;
1736 default:
1737 error (NILF, _("internal error: `%s' command_state"),
1738 c->file->name);
1739 abort ();
1740 break;
1742 #endif /* RECURSIVEJOBS */
1745 /* Set the state flag to say the commands have finished. */
1746 c->file->command_state = cs_finished;
1747 notice_finished_file (c->file);
1749 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1750 /* Remove the child from the chain and free it. */
1751 if (lastc == 0)
1752 children = c->next;
1753 else
1754 lastc->next = c->next;
1755 free_child (c);
1756 #endif /* RECURSIVEJOBS */
1758 /* There is now another slot open. */
1759 if (job_slots_used > 0)
1760 --job_slots_used;
1762 /* If the job failed, and the -k flag was not given, die. */
1763 if (child_failed && !keep_going_flag)
1764 die (EXIT_FAILURE);
1766 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1768 return 1;
1771 /* VMS:
1772 Spawn a process executing the command in ARGV and return its pid. */
1774 #define MAXCMDLEN 200
1776 /* local helpers to make ctrl+c and ctrl+y working, see below */
1777 #include <iodef.h>
1778 #include <libclidef.h>
1779 #include <ssdef.h>
1781 static int ctrlMask= LIB$M_CLI_CTRLY;
1782 static int oldCtrlMask;
1783 static int setupYAstTried= 0;
1784 static int pidToAbort= 0;
1785 static int chan= 0;
1787 static void reEnableAst(void) {
1788 lib$enable_ctrl (&oldCtrlMask,0);
1791 static astHandler (void) {
1792 if (pidToAbort) {
1793 sys$forcex (&pidToAbort, 0, SS$_ABORT);
1794 pidToAbort= 0;
1796 kill (getpid(),SIGQUIT);
1799 static void tryToSetupYAst(void) {
1800 $DESCRIPTOR(inputDsc,"SYS$COMMAND");
1801 int status;
1802 struct {
1803 short int status, count;
1804 int dvi;
1805 } iosb;
1807 setupYAstTried++;
1809 if (!chan) {
1810 status= sys$assign(&inputDsc,&chan,0,0);
1811 if (!(status&SS$_NORMAL)) {
1812 lib$signal(status);
1813 return;
1816 status= sys$qiow (0, chan, IO$_SETMODE|IO$M_CTRLYAST,&iosb,0,0,
1817 astHandler,0,0,0,0,0);
1818 if (status==SS$_ILLIOFUNC) {
1819 sys$dassgn(chan);
1820 #ifdef CTRLY_ENABLED_ANYWAY
1821 fprintf (stderr,
1822 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
1823 #else
1824 return;
1825 #endif
1827 if (status==SS$_NORMAL)
1828 status= iosb.status;
1829 if (!(status&SS$_NORMAL)) {
1830 lib$signal(status);
1831 return;
1834 /* called from AST handler ? */
1835 if (setupYAstTried>1)
1836 return;
1837 if (atexit(reEnableAst))
1838 fprintf (stderr,
1839 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
1840 status= lib$disable_ctrl (&ctrlMask, &oldCtrlMask);
1841 if (!(status&SS$_NORMAL)) {
1842 lib$signal(status);
1843 return;
1847 child_execute_job (argv, child)
1848 char *argv;
1849 struct child *child;
1851 int i;
1852 static struct dsc$descriptor_s cmddsc;
1853 static struct dsc$descriptor_s pnamedsc;
1854 static struct dsc$descriptor_s ifiledsc;
1855 static struct dsc$descriptor_s ofiledsc;
1856 static struct dsc$descriptor_s efiledsc;
1857 int have_redirection = 0;
1858 int have_newline = 0;
1860 int spflags = CLI$M_NOWAIT;
1861 int status;
1862 char *cmd = alloca (strlen (argv) + 512), *p, *q;
1863 char ifile[256], ofile[256], efile[256];
1864 char *comname = 0;
1865 char procname[100];
1867 /* Parse IO redirection. */
1869 ifile[0] = 0;
1870 ofile[0] = 0;
1871 efile[0] = 0;
1873 DB (DB_JOBS, ("child_execute_job (%s)\n", argv));
1875 while (isspace ((unsigned char)*argv))
1876 argv++;
1878 if (*argv == 0)
1879 return 0;
1881 sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
1882 pnamedsc.dsc$w_length = strlen(procname);
1883 pnamedsc.dsc$a_pointer = procname;
1884 pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
1885 pnamedsc.dsc$b_class = DSC$K_CLASS_S;
1887 /* Handle comments and redirection. */
1888 for (p = argv, q = cmd; *p; p++, q++)
1890 switch (*p)
1892 case '#':
1893 *p-- = 0;
1894 *q-- = 0;
1895 break;
1896 case '\\':
1897 p++;
1898 if (*p == '\n')
1899 p++;
1900 if (isspace ((unsigned char)*p))
1902 do { p++; } while (isspace ((unsigned char)*p));
1903 p--;
1905 *q = *p;
1906 break;
1907 case '<':
1908 p = vms_redirect (&ifiledsc, ifile, p);
1909 *q = ' ';
1910 have_redirection = 1;
1911 break;
1912 case '>':
1913 have_redirection = 1;
1914 if (*(p-1) == '2')
1916 q--;
1917 if (strncmp (p, ">&1", 3) == 0)
1919 p += 3;
1920 strcpy (efile, "sys$output");
1921 efiledsc.dsc$w_length = strlen(efile);
1922 efiledsc.dsc$a_pointer = efile;
1923 efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
1924 efiledsc.dsc$b_class = DSC$K_CLASS_S;
1926 else
1928 p = vms_redirect (&efiledsc, efile, p);
1931 else
1933 p = vms_redirect (&ofiledsc, ofile, p);
1935 *q = ' ';
1936 break;
1937 case '\n':
1938 have_newline = 1;
1939 default:
1940 *q = *p;
1941 break;
1944 *q = *p;
1946 if (strncmp (cmd, "builtin_", 8) == 0)
1948 child->pid = 270163;
1949 child->efn = 0;
1950 child->cstatus = 1;
1952 DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));
1954 p = cmd + 8;
1956 if ((*(p) == 'c')
1957 && (*(p+1) == 'd')
1958 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
1960 p += 3;
1961 while ((*p == ' ') || (*p == '\t'))
1962 p++;
1963 DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
1964 if (chdir (p))
1965 return 0;
1966 else
1967 return 1;
1969 else if ((*(p) == 'r')
1970 && (*(p+1) == 'm')
1971 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
1973 int in_arg;
1975 /* rm */
1976 p += 3;
1977 while ((*p == ' ') || (*p == '\t'))
1978 p++;
1979 in_arg = 1;
1981 DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
1982 while (*p)
1984 switch (*p)
1986 case ' ':
1987 case '\t':
1988 if (in_arg)
1990 *p++ = ';';
1991 in_arg = 0;
1993 break;
1994 default:
1995 break;
1997 p++;
2000 else
2002 printf(_("Unknown builtin command '%s'\n"), cmd);
2003 fflush(stdout);
2004 return 0;
2008 /* Create a *.com file if either the command is too long for
2009 lib$spawn, or the command contains a newline, or if redirection
2010 is desired. Forcing commands with newlines into DCLs allows to
2011 store search lists on user mode logicals. */
2013 if (strlen (cmd) > MAXCMDLEN
2014 || (have_redirection != 0)
2015 || (have_newline != 0))
2017 FILE *outfile;
2018 char c;
2019 char *sep;
2020 int alevel = 0; /* apostrophe level */
2022 if (strlen (cmd) == 0)
2024 printf (_("Error, empty command\n"));
2025 fflush (stdout);
2026 return 0;
2029 outfile = open_tmpfile (&comname, "sys$scratch:CMDXXXXXX.COM");
2030 if (outfile == 0)
2031 pfatal_with_name (_("fopen (temporary file)"));
2033 if (ifile[0])
2035 fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
2036 DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
2037 ifiledsc.dsc$w_length = 0;
2040 if (efile[0])
2042 fprintf (outfile, "$ define sys$error %s\n", efile);
2043 DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
2044 efiledsc.dsc$w_length = 0;
2047 if (ofile[0])
2049 fprintf (outfile, "$ define sys$output %s\n", ofile);
2050 DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
2051 ofiledsc.dsc$w_length = 0;
2054 p = sep = q = cmd;
2055 for (c = '\n'; c; c = *q++)
2057 switch (c)
2059 case '\n':
2060 /* At a newline, skip any whitespace around a leading $
2061 from the command and issue exactly one $ into the DCL. */
2062 while (isspace ((unsigned char)*p))
2063 p++;
2064 if (*p == '$')
2065 p++;
2066 while (isspace ((unsigned char)*p))
2067 p++;
2068 fwrite (p, 1, q - p, outfile);
2069 fputc ('$', outfile);
2070 fputc (' ', outfile);
2071 /* Reset variables. */
2072 p = sep = q;
2073 break;
2075 /* Nice places for line breaks are after strings, after
2076 comma or space and before slash. */
2077 case '"':
2078 q = handle_apos (q + 1);
2079 sep = q;
2080 break;
2081 case ',':
2082 case ' ':
2083 sep = q;
2084 break;
2085 case '/':
2086 case '\0':
2087 sep = q - 1;
2088 break;
2089 default:
2090 break;
2092 if (sep - p > 78)
2094 /* Enough stuff for a line. */
2095 fwrite (p, 1, sep - p, outfile);
2096 p = sep;
2097 if (*sep)
2099 /* The command continues. */
2100 fputc ('-', outfile);
2102 fputc ('\n', outfile);
2106 fwrite (p, 1, q - p, outfile);
2107 fputc ('\n', outfile);
2109 fclose (outfile);
2111 sprintf (cmd, "$ @%s", comname);
2113 DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
2116 cmddsc.dsc$w_length = strlen(cmd);
2117 cmddsc.dsc$a_pointer = cmd;
2118 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
2119 cmddsc.dsc$b_class = DSC$K_CLASS_S;
2121 child->efn = 0;
2122 while (child->efn < 32 || child->efn > 63)
2124 status = lib$get_ef ((unsigned long *)&child->efn);
2125 if (!(status & 1))
2126 return 0;
2129 sys$clref (child->efn);
2131 vms_jobsefnmask |= (1 << (child->efn - 32));
2134 LIB$SPAWN [command-string]
2135 [,input-file]
2136 [,output-file]
2137 [,flags]
2138 [,process-name]
2139 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2140 [,AST-address] [,varying-AST-argument]
2141 [,prompt-string] [,cli] [,table]
2144 #ifndef DONTWAITFORCHILD
2146 * Code to make ctrl+c and ctrl+y working.
2147 * The problem starts with the synchronous case where after lib$spawn is
2148 * called any input will go to the child. But with input re-directed,
2149 * both control characters won't make it to any of the programs, neither
2150 * the spawning nor to the spawned one. Hence the caller needs to spawn
2151 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2152 * has to follow to simulate the wanted synchronous behaviour.
2153 * The next problem is ctrl+y which isn't caught by the crtl and
2154 * therefore isn't converted to SIGQUIT (for a signal handler which is
2155 * already established). The only way to catch ctrl+y, is an AST
2156 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2157 * disabled, otherwise it will handle it. Not to mention the previous
2158 * ctrl+y handling of DCL needs to be re-established before make exits.
2159 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2160 * make it to the signal handler after the child "normally" terminates.
2161 * This isn't enough. It seems reasonable for simple command lines like
2162 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2163 * spawning make. Therefore we need to abort the process in the AST.
2165 * Prior to the spawn it is checked if an AST is already set up for
2166 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2167 * this will work except if make is run in a batch environment, but there
2168 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2169 * is disabled and an exit handler is established to re-enable it.
2170 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2171 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2172 * the already established handler and will bring us back to common code.
2173 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2174 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2175 * which the crtl converts to SIGINT and which is caught by the common
2176 * signal handler. Because signals were blocked before entering this code
2177 * sys$waitfr will always complete and the SIGQUIT will be processed after
2178 * it (after termination of the current block, somewhere in common code).
2179 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2180 * current command completes. Anyway it's better than nothing :-)
2183 if (!setupYAstTried)
2184 tryToSetupYAst();
2185 status = lib$spawn (&cmddsc, /* cmd-string */
2186 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file */
2187 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
2188 &spflags, /* flags */
2189 &pnamedsc, /* proc name */
2190 &child->pid, &child->cstatus, &child->efn,
2191 0, 0,
2192 0, 0, 0);
2193 pidToAbort= child->pid;
2194 status= sys$waitfr (child->efn);
2195 pidToAbort= 0;
2196 vmsHandleChildTerm(child);
2197 #else
2198 status = lib$spawn (&cmddsc,
2199 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
2200 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
2201 &spflags,
2202 &pnamedsc,
2203 &child->pid, &child->cstatus, &child->efn,
2204 vmsHandleChildTerm, child,
2205 0, 0, 0);
2206 #endif
2208 if (!(status & 1))
2210 printf (_("Error spawning, %d\n") ,status);
2211 fflush (stdout);
2214 if (comname && !ISDB (DB_JOBS))
2215 unlink (comname);
2217 return (status & 1);
2220 #else /* !VMS */
2222 #if !defined (_AMIGA) && !defined (__MSDOS__)
2223 /* UNIX:
2224 Replace the current process with one executing the command in ARGV.
2225 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2226 the environment of the new program. This function does not return. */
2228 void
2229 child_execute_job (stdin_fd, stdout_fd, argv, envp)
2230 int stdin_fd, stdout_fd;
2231 char **argv, **envp;
2233 if (stdin_fd != 0)
2234 (void) dup2 (stdin_fd, 0);
2235 if (stdout_fd != 1)
2236 (void) dup2 (stdout_fd, 1);
2237 if (stdin_fd != 0)
2238 (void) close (stdin_fd);
2239 if (stdout_fd != 1)
2240 (void) close (stdout_fd);
2242 /* Run the command. */
2243 exec_command (argv, envp);
2245 #endif /* !AMIGA && !__MSDOS__ */
2246 #endif /* !VMS */
2247 #endif /* !WINDOWS32 */
2249 #ifndef _AMIGA
2250 /* Replace the current process with one running the command in ARGV,
2251 with environment ENVP. This function does not return. */
2253 void
2254 exec_command (argv, envp)
2255 char **argv, **envp;
2257 #ifdef VMS
2258 /* to work around a problem with signals and execve: ignore them */
2259 #ifdef SIGCHLD
2260 signal (SIGCHLD,SIG_IGN);
2261 #endif
2262 /* Run the program. */
2263 execve (argv[0], argv, envp);
2264 perror_with_name ("execve: ", argv[0]);
2265 _exit (EXIT_FAILURE);
2266 #else
2267 #ifdef WINDOWS32
2268 HANDLE hPID;
2269 HANDLE hWaitPID;
2270 int err = 0;
2271 int exit_code = EXIT_FAILURE;
2273 /* make sure CreateProcess() has Path it needs */
2274 sync_Path_environment();
2276 /* launch command */
2277 hPID = process_easy(argv, envp);
2279 /* make sure launch ok */
2280 if (hPID == INVALID_HANDLE_VALUE)
2282 int i;
2283 fprintf(stderr,
2284 _("process_easy() failed failed to launch process (e=%d)\n"),
2285 process_last_err(hPID));
2286 for (i = 0; argv[i]; i++)
2287 fprintf(stderr, "%s ", argv[i]);
2288 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2289 exit(EXIT_FAILURE);
2292 /* wait and reap last child */
2293 while (hWaitPID = process_wait_for_any())
2295 /* was an error found on this process? */
2296 err = process_last_err(hWaitPID);
2298 /* get exit data */
2299 exit_code = process_exit_code(hWaitPID);
2301 if (err)
2302 fprintf(stderr, "make (e=%d, rc=%d): %s",
2303 err, exit_code, map_windows32_error_to_string(err));
2305 /* cleanup process */
2306 process_cleanup(hWaitPID);
2308 /* expect to find only last pid, warn about other pids reaped */
2309 if (hWaitPID == hPID)
2310 break;
2311 else
2312 fprintf(stderr,
2313 _("make reaped child pid %d, still waiting for pid %d\n"),
2314 hWaitPID, hPID);
2317 /* return child's exit code as our exit code */
2318 exit(exit_code);
2320 #else /* !WINDOWS32 */
2322 /* Be the user, permanently. */
2323 child_access ();
2325 /* Run the program. */
2326 environ = envp;
2327 execvp (argv[0], argv);
2329 switch (errno)
2331 case ENOENT:
2332 error (NILF, _("%s: Command not found"), argv[0]);
2333 break;
2334 case ENOEXEC:
2336 /* The file is not executable. Try it as a shell script. */
2337 extern char *getenv ();
2338 char *shell;
2339 char **new_argv;
2340 int argc;
2342 shell = getenv ("SHELL");
2343 if (shell == 0)
2344 shell = default_shell;
2346 argc = 1;
2347 while (argv[argc] != 0)
2348 ++argc;
2350 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
2351 new_argv[0] = shell;
2352 new_argv[1] = argv[0];
2353 while (argc > 0)
2355 new_argv[1 + argc] = argv[argc];
2356 --argc;
2359 execvp (shell, new_argv);
2360 if (errno == ENOENT)
2361 error (NILF, _("%s: Shell program not found"), shell);
2362 else
2363 perror_with_name ("execvp: ", shell);
2364 break;
2367 default:
2368 perror_with_name ("execvp: ", argv[0]);
2369 break;
2372 _exit (127);
2373 #endif /* !WINDOWS32 */
2374 #endif /* !VMS */
2376 #else /* On Amiga */
2377 void exec_command (argv)
2378 char **argv;
2380 MyExecute (argv);
2383 void clean_tmp (void)
2385 DeleteFile (amiga_bname);
2388 #endif /* On Amiga */
2390 #ifndef VMS
2391 /* Figure out the argument list necessary to run LINE as a command. Try to
2392 avoid using a shell. This routine handles only ' quoting, and " quoting
2393 when no backslash, $ or ` characters are seen in the quotes. Starting
2394 quotes may be escaped with a backslash. If any of the characters in
2395 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2396 is the first word of a line, the shell is used.
2398 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2399 If *RESTP is NULL, newlines will be ignored.
2401 SHELL is the shell to use, or nil to use the default shell.
2402 IFS is the value of $IFS, or nil (meaning the default). */
2404 static char **
2405 construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr)
2406 char *line, **restp;
2407 char *shell, *ifs;
2408 char **batch_filename_ptr;
2410 #ifdef __MSDOS__
2411 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2412 We call `system' for anything that requires ``slow'' processing,
2413 because DOS shells are too dumb. When $SHELL points to a real
2414 (unix-style) shell, `system' just calls it to do everything. When
2415 $SHELL points to a DOS shell, `system' does most of the work
2416 internally, calling the shell only for its internal commands.
2417 However, it looks on the $PATH first, so you can e.g. have an
2418 external command named `mkdir'.
2420 Since we call `system', certain characters and commands below are
2421 actually not specific to COMMAND.COM, but to the DJGPP implementation
2422 of `system'. In particular:
2424 The shell wildcard characters are in DOS_CHARS because they will
2425 not be expanded if we call the child via `spawnXX'.
2427 The `;' is in DOS_CHARS, because our `system' knows how to run
2428 multiple commands on a single line.
2430 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2431 won't have to tell one from another and have one more set of
2432 commands and special characters. */
2433 static char sh_chars_dos[] = "*?[];|<>%^&()";
2434 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2435 "copy", "ctty", "date", "del", "dir", "echo",
2436 "erase", "exit", "for", "goto", "if", "md",
2437 "mkdir", "path", "pause", "prompt", "rd",
2438 "rmdir", "rem", "ren", "rename", "set",
2439 "shift", "time", "type", "ver", "verify",
2440 "vol", ":", 0 };
2442 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2443 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2444 "logout", "set", "umask", "wait", "while",
2445 "for", "case", "if", ":", ".", "break",
2446 "continue", "export", "read", "readonly",
2447 "shift", "times", "trap", "switch", "unset",
2448 0 };
2450 char *sh_chars;
2451 char **sh_cmds;
2452 #else
2453 #ifdef _AMIGA
2454 static char sh_chars[] = "#;\"|<>()?*$`";
2455 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2456 "rename", "set", "setenv", "date", "makedir",
2457 "skip", "else", "endif", "path", "prompt",
2458 "unset", "unsetenv", "version",
2459 0 };
2460 #else
2461 #ifdef WINDOWS32
2462 static char sh_chars_dos[] = "\"|&<>";
2463 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2464 "copy", "ctty", "date", "del", "dir", "echo",
2465 "erase", "exit", "for", "goto", "if", "if", "md",
2466 "mkdir", "path", "pause", "prompt", "rd", "rem",
2467 "ren", "rename", "rmdir", "set", "shift", "time",
2468 "type", "ver", "verify", "vol", ":", 0 };
2469 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2470 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2471 "logout", "set", "umask", "wait", "while", "for",
2472 "case", "if", ":", ".", "break", "continue",
2473 "export", "read", "readonly", "shift", "times",
2474 "trap", "switch", "test",
2475 #ifdef BATCH_MODE_ONLY_SHELL
2476 "echo",
2477 #endif
2478 0 };
2479 char* sh_chars;
2480 char** sh_cmds;
2481 #else /* must be UNIX-ish */
2482 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~";
2483 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
2484 "logout", "set", "umask", "wait", "while", "for",
2485 "case", "if", ":", ".", "break", "continue",
2486 "export", "read", "readonly", "shift", "times",
2487 "trap", "switch", 0 };
2488 #endif /* WINDOWS32 */
2489 #endif /* Amiga */
2490 #endif /* __MSDOS__ */
2491 register int i;
2492 register char *p;
2493 register char *ap;
2494 char *end;
2495 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2496 char **new_argv = 0;
2497 #ifdef WINDOWS32
2498 int slow_flag = 0;
2500 if (no_default_sh_exe) {
2501 sh_cmds = sh_cmds_dos;
2502 sh_chars = sh_chars_dos;
2503 } else {
2504 sh_cmds = sh_cmds_sh;
2505 sh_chars = sh_chars_sh;
2507 #endif /* WINDOWS32 */
2509 if (restp != NULL)
2510 *restp = NULL;
2512 /* Make sure not to bother processing an empty line. */
2513 while (isblank ((unsigned char)*line))
2514 ++line;
2515 if (*line == '\0')
2516 return 0;
2518 /* See if it is safe to parse commands internally. */
2519 if (shell == 0)
2520 shell = default_shell;
2521 #ifdef WINDOWS32
2522 else if (strcmp (shell, default_shell))
2524 char *s1 = _fullpath(NULL, shell, 0);
2525 char *s2 = _fullpath(NULL, default_shell, 0);
2527 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2529 if (s1)
2530 free (s1);
2531 if (s2)
2532 free (s2);
2534 if (slow_flag)
2535 goto slow;
2536 #else /* not WINDOWS32 */
2537 #ifdef __MSDOS__
2538 else if (stricmp (shell, default_shell))
2540 extern int _is_unixy_shell (const char *_path);
2542 message (1, _("$SHELL changed (was `%s', now `%s')"), default_shell, shell);
2543 unixy_shell = _is_unixy_shell (shell);
2544 default_shell = shell;
2546 if (unixy_shell)
2548 sh_chars = sh_chars_sh;
2549 sh_cmds = sh_cmds_sh;
2551 else
2553 sh_chars = sh_chars_dos;
2554 sh_cmds = sh_cmds_dos;
2556 #else /* not __MSDOS__ */
2557 else if (strcmp (shell, default_shell))
2558 goto slow;
2559 #endif /* not __MSDOS__ */
2560 #endif /* not WINDOWS32 */
2562 if (ifs != 0)
2563 for (ap = ifs; *ap != '\0'; ++ap)
2564 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2565 goto slow;
2567 i = strlen (line) + 1;
2569 /* More than 1 arg per character is impossible. */
2570 new_argv = (char **) xmalloc (i * sizeof (char *));
2572 /* All the args can fit in a buffer as big as LINE is. */
2573 ap = new_argv[0] = (char *) xmalloc (i);
2574 end = ap + i;
2576 /* I is how many complete arguments have been found. */
2577 i = 0;
2578 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2579 for (p = line; *p != '\0'; ++p)
2581 if (ap > end)
2582 abort ();
2584 if (instring)
2586 string_char:
2587 /* Inside a string, just copy any char except a closing quote
2588 or a backslash-newline combination. */
2589 if (*p == instring)
2591 instring = 0;
2592 if (ap == new_argv[0] || *(ap-1) == '\0')
2593 last_argument_was_empty = 1;
2595 else if (*p == '\\' && p[1] == '\n')
2596 goto swallow_escaped_newline;
2597 else if (*p == '\n' && restp != NULL)
2599 /* End of the command line. */
2600 *restp = p;
2601 goto end_of_line;
2603 /* Backslash, $, and ` are special inside double quotes.
2604 If we see any of those, punt.
2605 But on MSDOS, if we use COMMAND.COM, double and single
2606 quotes have the same effect. */
2607 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2608 goto slow;
2609 else
2610 *ap++ = *p;
2612 else if (strchr (sh_chars, *p) != 0)
2613 /* Not inside a string, but it's a special char. */
2614 goto slow;
2615 #ifdef __MSDOS__
2616 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2617 /* `...' is a wildcard in DJGPP. */
2618 goto slow;
2619 #endif
2620 else
2621 /* Not a special char. */
2622 switch (*p)
2624 case '=':
2625 /* Equals is a special character in leading words before the
2626 first word with no equals sign in it. This is not the case
2627 with sh -k, but we never get here when using nonstandard
2628 shell flags. */
2629 if (! seen_nonequals && unixy_shell)
2630 goto slow;
2631 word_has_equals = 1;
2632 *ap++ = '=';
2633 break;
2635 case '\\':
2636 /* Backslash-newline combinations are eaten. */
2637 if (p[1] == '\n')
2639 swallow_escaped_newline:
2641 /* Eat the backslash, the newline, and following whitespace,
2642 replacing it all with a single space. */
2643 p += 2;
2645 /* If there is a tab after a backslash-newline,
2646 remove it from the source line which will be echoed,
2647 since it was most likely used to line
2648 up the continued line with the previous one. */
2649 if (*p == '\t')
2650 /* Note these overlap and strcpy() is undefined for
2651 overlapping objects in ANSI C. The strlen() _IS_ right,
2652 since we need to copy the nul byte too. */
2653 bcopy (p + 1, p, strlen (p));
2655 if (instring)
2656 goto string_char;
2657 else
2659 if (ap != new_argv[i])
2660 /* Treat this as a space, ending the arg.
2661 But if it's at the beginning of the arg, it should
2662 just get eaten, rather than becoming an empty arg. */
2663 goto end_of_arg;
2664 else
2665 p = next_token (p) - 1;
2668 else if (p[1] != '\0')
2670 #if defined(__MSDOS__) || defined(WINDOWS32)
2671 /* Only remove backslashes before characters special
2672 to Unixy shells. All other backslashes are copied
2673 verbatim, since they are probably DOS-style
2674 directory separators. This still leaves a small
2675 window for problems, but at least it should work
2676 for the vast majority of naive users. */
2678 #ifdef __MSDOS__
2679 /* A dot is only special as part of the "..."
2680 wildcard. */
2681 if (strneq (p + 1, ".\\.\\.", 5))
2683 *ap++ = '.';
2684 *ap++ = '.';
2685 p += 4;
2687 else
2688 #endif
2689 if (p[1] != '\\' && p[1] != '\''
2690 && !isspace ((unsigned char)p[1])
2691 && (strchr (sh_chars_sh, p[1]) == 0))
2692 /* back up one notch, to copy the backslash */
2693 --p;
2695 #endif /* __MSDOS__ || WINDOWS32 */
2696 /* Copy and skip the following char. */
2697 *ap++ = *++p;
2699 break;
2701 case '\'':
2702 case '"':
2703 instring = *p;
2704 break;
2706 case '\n':
2707 if (restp != NULL)
2709 /* End of the command line. */
2710 *restp = p;
2711 goto end_of_line;
2713 else
2714 /* Newlines are not special. */
2715 *ap++ = '\n';
2716 break;
2718 case ' ':
2719 case '\t':
2720 end_of_arg:
2721 /* We have the end of an argument.
2722 Terminate the text of the argument. */
2723 *ap++ = '\0';
2724 new_argv[++i] = ap;
2725 last_argument_was_empty = 0;
2727 /* Update SEEN_NONEQUALS, which tells us if every word
2728 heretofore has contained an `='. */
2729 seen_nonequals |= ! word_has_equals;
2730 if (word_has_equals && ! seen_nonequals)
2731 /* An `=' in a word before the first
2732 word without one is magical. */
2733 goto slow;
2734 word_has_equals = 0; /* Prepare for the next word. */
2736 /* If this argument is the command name,
2737 see if it is a built-in shell command.
2738 If so, have the shell handle it. */
2739 if (i == 1)
2741 register int j;
2742 for (j = 0; sh_cmds[j] != 0; ++j)
2743 if (streq (sh_cmds[j], new_argv[0]))
2744 goto slow;
2747 /* Ignore multiple whitespace chars. */
2748 p = next_token (p);
2749 /* Next iteration should examine the first nonwhite char. */
2750 --p;
2751 break;
2753 default:
2754 *ap++ = *p;
2755 break;
2758 end_of_line:
2760 if (instring)
2761 /* Let the shell deal with an unterminated quote. */
2762 goto slow;
2764 /* Terminate the last argument and the argument list. */
2766 *ap = '\0';
2767 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2768 ++i;
2769 new_argv[i] = 0;
2771 if (i == 1)
2773 register int j;
2774 for (j = 0; sh_cmds[j] != 0; ++j)
2775 if (streq (sh_cmds[j], new_argv[0]))
2776 goto slow;
2779 if (new_argv[0] == 0)
2780 /* Line was empty. */
2781 return 0;
2782 else
2783 return new_argv;
2785 slow:;
2786 /* We must use the shell. */
2788 if (new_argv != 0)
2790 /* Free the old argument list we were working on. */
2791 free (new_argv[0]);
2792 free ((void *)new_argv);
2795 #ifdef __MSDOS__
2796 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2797 #endif
2799 #ifdef _AMIGA
2801 char *ptr;
2802 char *buffer;
2803 char *dptr;
2805 buffer = (char *)xmalloc (strlen (line)+1);
2807 ptr = line;
2808 for (dptr=buffer; *ptr; )
2810 if (*ptr == '\\' && ptr[1] == '\n')
2811 ptr += 2;
2812 else if (*ptr == '@') /* Kludge: multiline commands */
2814 ptr += 2;
2815 *dptr++ = '\n';
2817 else
2818 *dptr++ = *ptr++;
2820 *dptr = 0;
2822 new_argv = (char **) xmalloc (2 * sizeof (char *));
2823 new_argv[0] = buffer;
2824 new_argv[1] = 0;
2826 #else /* Not Amiga */
2827 #ifdef WINDOWS32
2829 * Not eating this whitespace caused things like
2831 * sh -c "\n"
2833 * which gave the shell fits. I think we have to eat
2834 * whitespace here, but this code should be considered
2835 * suspicious if things start failing....
2838 /* Make sure not to bother processing an empty line. */
2839 while (isspace ((unsigned char)*line))
2840 ++line;
2841 if (*line == '\0')
2842 return 0;
2843 #endif /* WINDOWS32 */
2845 /* SHELL may be a multi-word command. Construct a command line
2846 "SHELL -c LINE", with all special chars in LINE escaped.
2847 Then recurse, expanding this command line to get the final
2848 argument list. */
2850 unsigned int shell_len = strlen (shell);
2851 #ifndef VMS
2852 static char minus_c[] = " -c ";
2853 #else
2854 static char minus_c[] = "";
2855 #endif
2856 unsigned int line_len = strlen (line);
2858 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2859 + (line_len * 2) + 1);
2860 char *command_ptr = NULL; /* used for batch_mode_shell mode */
2862 ap = new_line;
2863 bcopy (shell, ap, shell_len);
2864 ap += shell_len;
2865 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2866 ap += sizeof (minus_c) - 1;
2867 command_ptr = ap;
2868 for (p = line; *p != '\0'; ++p)
2870 if (restp != NULL && *p == '\n')
2872 *restp = p;
2873 break;
2875 else if (*p == '\\' && p[1] == '\n')
2877 /* Eat the backslash, the newline, and following whitespace,
2878 replacing it all with a single space (which is escaped
2879 from the shell). */
2880 p += 2;
2882 /* If there is a tab after a backslash-newline,
2883 remove it from the source line which will be echoed,
2884 since it was most likely used to line
2885 up the continued line with the previous one. */
2886 if (*p == '\t')
2887 bcopy (p + 1, p, strlen (p));
2889 p = next_token (p);
2890 --p;
2891 if (unixy_shell && !batch_mode_shell)
2892 *ap++ = '\\';
2893 *ap++ = ' ';
2894 continue;
2897 /* DOS shells don't know about backslash-escaping. */
2898 if (unixy_shell && !batch_mode_shell &&
2899 (*p == '\\' || *p == '\'' || *p == '"'
2900 || isspace ((unsigned char)*p)
2901 || strchr (sh_chars, *p) != 0))
2902 *ap++ = '\\';
2903 #ifdef __MSDOS__
2904 else if (unixy_shell && strneq (p, "...", 3))
2906 /* The case of `...' wildcard again. */
2907 strcpy (ap, "\\.\\.\\");
2908 ap += 5;
2909 p += 2;
2911 #endif
2912 *ap++ = *p;
2914 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2915 /* Line was empty. */
2916 return 0;
2917 *ap = '\0';
2919 #ifdef WINDOWS32
2920 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2921 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2922 cases, run commands via a script file. */
2923 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2924 FILE* batch = NULL;
2925 int id = GetCurrentProcessId();
2926 PATH_VAR(fbuf);
2927 char* fname = NULL;
2929 /* create a file name */
2930 sprintf(fbuf, "make%d", id);
2931 fname = tempnam(".", fbuf);
2933 /* create batch file name */
2934 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
2935 strcpy(*batch_filename_ptr, fname);
2937 /* make sure path name is in DOS backslash format */
2938 if (!unixy_shell) {
2939 fname = *batch_filename_ptr;
2940 for (i = 0; fname[i] != '\0'; ++i)
2941 if (fname[i] == '/')
2942 fname[i] = '\\';
2943 strcat(*batch_filename_ptr, ".bat");
2944 } else {
2945 strcat(*batch_filename_ptr, ".sh");
2948 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
2949 *batch_filename_ptr));
2951 /* create batch file to execute command */
2952 batch = fopen (*batch_filename_ptr, "w");
2953 if (!unixy_shell)
2954 fputs ("@echo off\n", batch);
2955 fputs (command_ptr, batch);
2956 fputc ('\n', batch);
2957 fclose (batch);
2959 /* create argv */
2960 new_argv = (char **) xmalloc(3 * sizeof (char *));
2961 if (unixy_shell) {
2962 new_argv[0] = xstrdup (shell);
2963 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2964 } else {
2965 new_argv[0] = xstrdup (*batch_filename_ptr);
2966 new_argv[1] = NULL;
2968 new_argv[2] = NULL;
2969 } else
2970 #endif /* WINDOWS32 */
2971 if (unixy_shell)
2972 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2973 (char *) 0, (char *) 0,
2974 (char **) 0);
2975 #ifdef __MSDOS__
2976 else
2978 /* With MSDOS shells, we must construct the command line here
2979 instead of recursively calling ourselves, because we
2980 cannot backslash-escape the special characters (see above). */
2981 new_argv = (char **) xmalloc (sizeof (char *));
2982 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2983 new_argv[0] = xmalloc (line_len + 1);
2984 strncpy (new_argv[0],
2985 new_line + shell_len + sizeof (minus_c) - 1, line_len);
2986 new_argv[0][line_len] = '\0';
2988 #else
2989 else
2990 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2991 __FILE__, __LINE__);
2992 #endif
2994 #endif /* ! AMIGA */
2996 return new_argv;
2998 #endif /* !VMS */
3000 /* Figure out the argument list necessary to run LINE as a command. Try to
3001 avoid using a shell. This routine handles only ' quoting, and " quoting
3002 when no backslash, $ or ` characters are seen in the quotes. Starting
3003 quotes may be escaped with a backslash. If any of the characters in
3004 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3005 is the first word of a line, the shell is used.
3007 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3008 If *RESTP is NULL, newlines will be ignored.
3010 FILE is the target whose commands these are. It is used for
3011 variable expansion for $(SHELL) and $(IFS). */
3013 char **
3014 construct_command_argv (line, restp, file, batch_filename_ptr)
3015 char *line, **restp;
3016 struct file *file;
3017 char** batch_filename_ptr;
3019 char *shell, *ifs;
3020 char **argv;
3022 #ifdef VMS
3023 char *cptr;
3024 int argc;
3026 argc = 0;
3027 cptr = line;
3028 for (;;)
3030 while ((*cptr != 0)
3031 && (isspace ((unsigned char)*cptr)))
3032 cptr++;
3033 if (*cptr == 0)
3034 break;
3035 while ((*cptr != 0)
3036 && (!isspace((unsigned char)*cptr)))
3037 cptr++;
3038 argc++;
3041 argv = (char **)malloc (argc * sizeof (char *));
3042 if (argv == 0)
3043 abort ();
3045 cptr = line;
3046 argc = 0;
3047 for (;;)
3049 while ((*cptr != 0)
3050 && (isspace ((unsigned char)*cptr)))
3051 cptr++;
3052 if (*cptr == 0)
3053 break;
3054 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3055 argv[argc++] = cptr;
3056 while ((*cptr != 0)
3057 && (!isspace((unsigned char)*cptr)))
3058 cptr++;
3059 if (*cptr != 0)
3060 *cptr++ = 0;
3062 #else
3064 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3065 int save = warn_undefined_variables_flag;
3066 warn_undefined_variables_flag = 0;
3068 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3069 #ifdef WINDOWS32
3071 * Convert to forward slashes so that construct_command_argv_internal()
3072 * is not confused.
3074 if (shell) {
3075 char *p = w32ify(shell, 0);
3076 strcpy(shell, p);
3078 #endif
3079 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3081 warn_undefined_variables_flag = save;
3084 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
3086 free (shell);
3087 free (ifs);
3088 #endif /* !VMS */
3089 return argv;
3092 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3094 dup2 (old, new)
3095 int old, new;
3097 int fd;
3099 (void) close (new);
3100 fd = dup (old);
3101 if (fd != new)
3103 (void) close (fd);
3104 errno = EMFILE;
3105 return -1;
3108 return fd;
3110 #endif /* !HAPE_DUP2 && !_AMIGA */