Fix bug #2238: the read.c:eval() function was not entirely reentrant.
[make/kirr.git] / job.c
blobefdf4dd07282de0f21a136e16ffd1d64afc9b57a
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 (char *target_name, int exit_code, int exit_sig, int coredump,
243 int ignored)
245 if (ignored && silent_flag)
246 return;
248 #ifdef VMS
249 if (!(exit_code & 1))
250 error (NILF,
251 (ignored ? _("*** [%s] Error 0x%x (ignored)")
252 : _("*** [%s] Error 0x%x")),
253 target_name, exit_code);
254 #else
255 if (exit_sig == 0)
256 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
257 _("*** [%s] Error %d"),
258 target_name, exit_code);
259 else
260 error (NILF, "*** [%s] %s%s",
261 target_name, strsignal (exit_sig),
262 coredump ? _(" (core dumped)") : "");
263 #endif /* VMS */
266 #ifdef VMS
267 /* Wait for nchildren children to terminate */
268 static void
269 vmsWaitForChildren(int *status)
271 while (1)
273 if (!vms_jobsefnmask)
275 *status = 0;
276 return;
279 *status = sys$wflor (32, vms_jobsefnmask);
281 return;
284 /* Set up IO redirection. */
286 char *
287 vms_redirect (struct dsc$descriptor_s *desc, char *fname, char *ibuf)
289 char *fptr;
290 extern char *vmsify ();
292 ibuf++;
293 while (isspace ((unsigned char)*ibuf))
294 ibuf++;
295 fptr = ibuf;
296 while (*ibuf && !isspace ((unsigned char)*ibuf))
297 ibuf++;
298 *ibuf = 0;
299 if (strcmp (fptr, "/dev/null") != 0)
301 strcpy (fname, vmsify (fptr, 0));
302 if (strchr (fname, '.') == 0)
303 strcat (fname, ".");
305 desc->dsc$w_length = strlen(fname);
306 desc->dsc$a_pointer = fname;
307 desc->dsc$b_dtype = DSC$K_DTYPE_T;
308 desc->dsc$b_class = DSC$K_CLASS_S;
310 if (*fname == 0)
311 printf (_("Warning: Empty redirection\n"));
312 return ibuf;
317 found apostrophe at (p-1)
319 inc p until after closing apostrophe. */
321 static char *
322 handle_apos (char *p)
324 int alast;
325 int inside;
327 #define SEPCHARS ",/()= "
329 inside = 0;
331 while (*p != 0)
333 if (*p == '"')
335 if (inside)
337 while ((alast > 0)
338 && (*p == '"'))
340 p++;
341 alast--;
343 if (alast == 0)
344 inside = 0;
345 else
347 fprintf (stderr, _("Syntax error, still inside '\"'\n"));
348 exit (3);
351 else
353 p++;
354 if (strchr (SEPCHARS, *p))
355 break;
356 inside = 1;
357 alast = 1;
358 while (*p == '"')
360 alast++;
361 p++;
365 else
366 p++;
369 return p;
372 #endif
375 /* Handle a dead child. This handler may or may not ever be installed.
377 If we're using the jobserver feature, we need it. First, installing it
378 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
379 read FD to ensure we don't enter another blocking read without reaping all
380 the dead children. In this case we don't need the dead_children count.
382 If we don't have either waitpid or wait3, then make is unreliable, but we
383 use the dead_children count to reap children as best we can. */
385 static unsigned int dead_children = 0;
387 RETSIGTYPE
388 child_handler (int sig)
390 ++dead_children;
392 if (job_rfd >= 0)
394 close (job_rfd);
395 job_rfd = -1;
398 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
402 extern int shell_function_pid, shell_function_completed;
404 /* Reap all dead children, storing the returned status and the new command
405 state (`cs_finished') in the `file' member of the `struct child' for the
406 dead child, and removing the child from the chain. In addition, if BLOCK
407 nonzero, we block in this function until we've reaped at least one
408 complete child, waiting for it to die if necessary. If ERR is nonzero,
409 print an error message first. */
411 void
412 reap_children (int block, int err)
414 WAIT_T status;
415 /* Initially, assume we have some. */
416 int reap_more = 1;
418 #ifdef WAIT_NOHANG
419 # define REAP_MORE reap_more
420 #else
421 # define REAP_MORE dead_children
422 #endif
424 /* As long as:
426 We have at least one child outstanding OR a shell function in progress,
428 We're blocking for a complete child OR there are more children to reap
430 we'll keep reaping children. */
432 while ((children != 0 || shell_function_pid != 0)
433 && (block || REAP_MORE))
435 int remote = 0;
436 register int pid;
437 int exit_code, exit_sig, coredump;
438 register struct child *lastc, *c;
439 int child_failed;
440 int any_remote, any_local;
442 if (err && block)
444 /* We might block for a while, so let the user know why. */
445 fflush (stdout);
446 error (NILF, _("*** Waiting for unfinished jobs...."));
449 /* We have one less dead child to reap. As noted in
450 child_handler() above, this count is completely unimportant for
451 all modern, POSIX-y systems that support wait3() or waitpid().
452 The rest of this comment below applies only to early, broken
453 pre-POSIX systems. We keep the count only because... it's there...
455 The test and decrement are not atomic; if it is compiled into:
456 register = dead_children - 1;
457 dead_children = register;
458 a SIGCHLD could come between the two instructions.
459 child_handler increments dead_children.
460 The second instruction here would lose that increment. But the
461 only effect of dead_children being wrong is that we might wait
462 longer than necessary to reap a child, and lose some parallelism;
463 and we might print the "Waiting for unfinished jobs" message above
464 when not necessary. */
466 if (dead_children > 0)
467 --dead_children;
469 any_remote = 0;
470 any_local = shell_function_pid != 0;
471 for (c = children; c != 0; c = c->next)
473 any_remote |= c->remote;
474 any_local |= ! c->remote;
475 DB (DB_JOBS, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
476 (unsigned long int) c, c->file->name,
477 (long) c->pid, c->remote ? _(" (remote)") : ""));
478 #ifdef VMS
479 break;
480 #endif
483 /* First, check for remote children. */
484 if (any_remote)
485 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
486 else
487 pid = 0;
489 if (pid > 0)
490 /* We got a remote child. */
491 remote = 1;
492 else if (pid < 0)
494 /* A remote status command failed miserably. Punt. */
495 remote_status_lose:
496 pfatal_with_name ("remote_status");
498 else
500 /* No remote children. Check for local children. */
501 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
502 if (any_local)
504 #ifdef VMS
505 vmsWaitForChildren (&status);
506 pid = c->pid;
507 #else
508 #ifdef WAIT_NOHANG
509 if (!block)
510 pid = WAIT_NOHANG (&status);
511 else
512 #endif
513 pid = wait (&status);
514 #endif /* !VMS */
516 else
517 pid = 0;
519 if (pid < 0)
521 /* The wait*() failed miserably. Punt. */
522 pfatal_with_name ("wait");
524 else if (pid > 0)
526 /* We got a child exit; chop the status word up. */
527 exit_code = WEXITSTATUS (status);
528 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
529 coredump = WCOREDUMP (status);
531 else
533 /* No local children are dead. */
534 reap_more = 0;
536 if (!block || !any_remote)
537 break;
539 /* Now try a blocking wait for a remote child. */
540 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
541 if (pid < 0)
542 goto remote_status_lose;
543 else if (pid == 0)
544 /* No remote children either. Finally give up. */
545 break;
547 /* We got a remote child. */
548 remote = 1;
550 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
552 #ifdef __MSDOS__
553 /* Life is very different on MSDOS. */
554 pid = dos_pid - 1;
555 status = dos_status;
556 exit_code = WEXITSTATUS (status);
557 if (exit_code == 0xff)
558 exit_code = -1;
559 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
560 coredump = 0;
561 #endif /* __MSDOS__ */
562 #ifdef _AMIGA
563 /* Same on Amiga */
564 pid = amiga_pid - 1;
565 status = amiga_status;
566 exit_code = amiga_status;
567 exit_sig = 0;
568 coredump = 0;
569 #endif /* _AMIGA */
570 #ifdef WINDOWS32
572 HANDLE hPID;
573 int err;
575 /* wait for anything to finish */
576 if (hPID = process_wait_for_any()) {
578 /* was an error found on this process? */
579 err = process_last_err(hPID);
581 /* get exit data */
582 exit_code = process_exit_code(hPID);
584 if (err)
585 fprintf(stderr, "make (e=%d): %s",
586 exit_code, map_windows32_error_to_string(exit_code));
588 /* signal */
589 exit_sig = process_signal(hPID);
591 /* cleanup process */
592 process_cleanup(hPID);
594 coredump = 0;
596 pid = (int) hPID;
598 #endif /* WINDOWS32 */
601 /* Check if this is the child of the `shell' function. */
602 if (!remote && pid == shell_function_pid)
604 /* It is. Leave an indicator for the `shell' function. */
605 if (exit_sig == 0 && exit_code == 127)
606 shell_function_completed = -1;
607 else
608 shell_function_completed = 1;
609 break;
612 child_failed = exit_sig != 0 || exit_code != 0;
614 /* Search for a child matching the deceased one. */
615 lastc = 0;
616 for (c = children; c != 0; lastc = c, c = c->next)
617 if (c->remote == remote && c->pid == pid)
618 break;
620 if (c == 0)
621 /* An unknown child died.
622 Ignore it; it was inherited from our invoker. */
623 continue;
625 DB (DB_JOBS, (child_failed
626 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
627 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
628 (unsigned long int) c, (long) c->pid,
629 c->remote ? _(" (remote)") : ""));
631 if (c->sh_batch_file) {
632 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
633 c->sh_batch_file));
635 /* just try and remove, don't care if this fails */
636 remove (c->sh_batch_file);
638 /* all done with memory */
639 free (c->sh_batch_file);
640 c->sh_batch_file = NULL;
643 /* If this child had the good stdin, say it is now free. */
644 if (c->good_stdin)
645 good_stdin_used = 0;
647 if (child_failed && !c->noerror && !ignore_errors_flag)
649 /* The commands failed. Write an error message,
650 delete non-precious targets, and abort. */
651 static int delete_on_error = -1;
652 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
653 c->file->update_status = 2;
654 if (delete_on_error == -1)
656 struct file *f = lookup_file (".DELETE_ON_ERROR");
657 delete_on_error = f != 0 && f->is_target;
659 if (exit_sig != 0 || delete_on_error)
660 delete_child_targets (c);
662 else
664 if (child_failed)
666 /* The commands failed, but we don't care. */
667 child_error (c->file->name,
668 exit_code, exit_sig, coredump, 1);
669 child_failed = 0;
672 /* If there are more commands to run, try to start them. */
673 if (job_next_command (c))
675 if (handling_fatal_signal)
677 /* Never start new commands while we are dying.
678 Since there are more commands that wanted to be run,
679 the target was not completely remade. So we treat
680 this as if a command had failed. */
681 c->file->update_status = 2;
683 else
685 /* Check again whether to start remotely.
686 Whether or not we want to changes over time.
687 Also, start_remote_job may need state set up
688 by start_remote_job_p. */
689 c->remote = start_remote_job_p (0);
690 start_job_command (c);
691 /* Fatal signals are left blocked in case we were
692 about to put that child on the chain. But it is
693 already there, so it is safe for a fatal signal to
694 arrive now; it will clean up this child's targets. */
695 unblock_sigs ();
696 if (c->file->command_state == cs_running)
697 /* We successfully started the new command.
698 Loop to reap more children. */
699 continue;
702 if (c->file->update_status != 0)
703 /* We failed to start the commands. */
704 delete_child_targets (c);
706 else
707 /* There are no more commands. We got through them all
708 without an unignored error. Now the target has been
709 successfully updated. */
710 c->file->update_status = 0;
713 /* When we get here, all the commands for C->file are finished
714 (or aborted) and C->file->update_status contains 0 or 2. But
715 C->file->command_state is still cs_running if all the commands
716 ran; notice_finish_file looks for cs_running to tell it that
717 it's interesting to check the file's modtime again now. */
719 if (! handling_fatal_signal)
720 /* Notice if the target of the commands has been changed.
721 This also propagates its values for command_state and
722 update_status to its also_make files. */
723 notice_finished_file (c->file);
725 DB (DB_JOBS, (_("Removing child 0x%08lx PID %ld%s from chain.\n"),
726 (unsigned long int) c, (long) c->pid,
727 c->remote ? _(" (remote)") : ""));
729 /* Block fatal signals while frobnicating the list, so that
730 children and job_slots_used are always consistent. Otherwise
731 a fatal signal arriving after the child is off the chain and
732 before job_slots_used is decremented would believe a child was
733 live and call reap_children again. */
734 block_sigs ();
736 /* There is now another slot open. */
737 if (job_slots_used > 0)
738 --job_slots_used;
740 /* Remove the child from the chain and free it. */
741 if (lastc == 0)
742 children = c->next;
743 else
744 lastc->next = c->next;
746 free_child (c);
748 unblock_sigs ();
750 /* If the job failed, and the -k flag was not given, die,
751 unless we are already in the process of dying. */
752 if (!err && child_failed && !keep_going_flag &&
753 /* fatal_error_signal will die with the right signal. */
754 !handling_fatal_signal)
755 die (2);
757 /* Only block for one child. */
758 block = 0;
761 return;
764 /* Free the storage allocated for CHILD. */
766 static void
767 free_child (struct child *child)
769 /* If this child is the only one it was our "free" job, so don't put a
770 token back for it. This child has already been removed from the list,
771 so if there any left this wasn't the last one. */
773 if (job_fds[1] >= 0 && children)
775 char token = '+';
777 /* Write a job token back to the pipe. */
779 if (write (job_fds[1], &token, 1) != 1)
780 pfatal_with_name (_("write jobserver"));
782 DB (DB_JOBS, (_("Released token for child 0x%08lx (%s).\n"),
783 (unsigned long int) child, child->file->name));
786 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
787 return;
789 if (child->command_lines != 0)
791 register unsigned int i;
792 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
793 free (child->command_lines[i]);
794 free ((char *) child->command_lines);
797 if (child->environment != 0)
799 register char **ep = child->environment;
800 while (*ep != 0)
801 free (*ep++);
802 free ((char *) child->environment);
805 free ((char *) child);
808 #ifdef POSIX
809 extern sigset_t fatal_signal_set;
810 #endif
812 void
813 block_sigs (void)
815 #ifdef POSIX
816 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
817 #else
818 # ifdef HAVE_SIGSETMASK
819 (void) sigblock (fatal_signal_mask);
820 # endif
821 #endif
824 #ifdef POSIX
825 void
826 unblock_sigs (void)
828 sigset_t empty;
829 sigemptyset (&empty);
830 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
832 #endif
834 #ifdef MAKE_JOBSERVER
835 /* Set the child handler action flags to FLAGS. */
836 static void
837 set_child_handler_action_flags (int flags)
839 struct sigaction sa;
840 bzero ((char *) &sa, sizeof sa);
841 sa.sa_handler = child_handler;
842 sa.sa_flags = flags;
843 #if defined SIGCHLD
844 sigaction (SIGCHLD, &sa, NULL);
845 #endif
846 #if defined SIGCLD && SIGCLD != SIGCHLD
847 sigaction (SIGCLD, &sa, NULL);
848 #endif
850 #endif
853 /* Start a job to run the commands specified in CHILD.
854 CHILD is updated to reflect the commands and ID of the child process.
856 NOTE: On return fatal signals are blocked! The caller is responsible
857 for calling `unblock_sigs', once the new child is safely on the chain so
858 it can be cleaned up in the event of a fatal signal. */
860 static void
861 start_job_command (struct child *child)
863 #ifndef _AMIGA
864 static int bad_stdin = -1;
865 #endif
866 register char *p;
867 int flags;
868 #ifdef VMS
869 char *argv;
870 #else
871 char **argv;
872 #endif
874 /* If we have a completely empty commandset, stop now. */
875 if (!child->command_ptr)
876 goto next_command;
878 /* Combine the flags parsed for the line itself with
879 the flags specified globally for this target. */
880 flags = (child->file->command_flags
881 | child->file->cmds->lines_flags[child->command_line - 1]);
883 p = child->command_ptr;
884 child->noerror = flags & COMMANDS_NOERROR;
886 while (*p != '\0')
888 if (*p == '@')
889 flags |= COMMANDS_SILENT;
890 else if (*p == '+')
891 flags |= COMMANDS_RECURSE;
892 else if (*p == '-')
893 child->noerror = 1;
894 else if (!isblank ((unsigned char)*p))
895 break;
896 ++p;
899 /* Update the file's command flags with any new ones we found. We only
900 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
901 now marking more commands recursive than should be in the case of
902 multiline define/endef scripts where only one line is marked "+". In
903 order to really fix this, we'll have to keep a lines_flags for every
904 actual line, after expansion. */
905 child->file->cmds->lines_flags[child->command_line - 1]
906 |= flags & COMMANDS_RECURSE;
908 /* Figure out an argument list from this command line. */
911 char *end = 0;
912 #ifdef VMS
913 argv = p;
914 #else
915 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
916 #endif
917 if (end == NULL)
918 child->command_ptr = NULL;
919 else
921 *end++ = '\0';
922 child->command_ptr = end;
926 /* If -q was given, say that updating `failed' if there was any text on the
927 command line, or `succeeded' otherwise. The exit status of 1 tells the
928 user that -q is saying `something to do'; the exit status for a random
929 error is 2. */
930 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
932 #ifndef VMS
933 free (argv[0]);
934 free ((char *) argv);
935 #endif
936 child->file->update_status = 1;
937 notice_finished_file (child->file);
938 return;
941 if (touch_flag && !(flags & COMMANDS_RECURSE))
943 /* Go on to the next command. It might be the recursive one.
944 We construct ARGV only to find the end of the command line. */
945 #ifndef VMS
946 if (argv)
948 free (argv[0]);
949 free ((char *) argv);
951 #endif
952 argv = 0;
955 if (argv == 0)
957 next_command:
958 #ifdef __MSDOS__
959 execute_by_shell = 0; /* in case construct_command_argv sets it */
960 #endif
961 /* This line has no commands. Go to the next. */
962 if (job_next_command (child))
963 start_job_command (child);
964 else
966 /* No more commands. Make sure we're "running"; we might not be if
967 (e.g.) all commands were skipped due to -n. */
968 set_command_state (child->file, cs_running);
969 child->file->update_status = 0;
970 notice_finished_file (child->file);
972 return;
975 /* Print out the command. If silent, we call `message' with null so it
976 can log the working directory before the command's own error messages
977 appear. */
979 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
980 ? "%s" : (char *) 0, p);
982 /* Tell update_goal_chain that a command has been started on behalf of
983 this target. It is important that this happens here and not in
984 reap_children (where we used to do it), because reap_children might be
985 reaping children from a different target. We want this increment to
986 guaranteedly indicate that a command was started for the dependency
987 chain (i.e., update_file recursion chain) we are processing. */
989 ++commands_started;
991 /* Optimize an empty command. People use this for timestamp rules,
992 so avoid forking a useless shell. Do this after we increment
993 commands_started so make still treats this special case as if it
994 performed some action (makes a difference as to what messages are
995 printed, etc. */
997 #if !defined(VMS) && !defined(_AMIGA)
998 if (
999 #ifdef __MSDOS__
1000 unixy_shell /* the test is complicated and we already did it */
1001 #else
1002 (argv[0] && !strcmp (argv[0], "/bin/sh"))
1003 #endif
1004 && (argv[1]
1005 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
1006 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1007 && argv[3] == NULL)
1009 free (argv[0]);
1010 free ((char *) argv);
1011 goto next_command;
1013 #endif /* !VMS && !_AMIGA */
1015 /* If -n was given, recurse to get the next line in the sequence. */
1017 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1019 #ifndef VMS
1020 free (argv[0]);
1021 free ((char *) argv);
1022 #endif
1023 goto next_command;
1026 /* Flush the output streams so they won't have things written twice. */
1028 fflush (stdout);
1029 fflush (stderr);
1031 #ifndef VMS
1032 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1034 /* Set up a bad standard input that reads from a broken pipe. */
1036 if (bad_stdin == -1)
1038 /* Make a file descriptor that is the read end of a broken pipe.
1039 This will be used for some children's standard inputs. */
1040 int pd[2];
1041 if (pipe (pd) == 0)
1043 /* Close the write side. */
1044 (void) close (pd[1]);
1045 /* Save the read side. */
1046 bad_stdin = pd[0];
1048 /* Set the descriptor to close on exec, so it does not litter any
1049 child's descriptor table. When it is dup2'd onto descriptor 0,
1050 that descriptor will not close on exec. */
1051 CLOSE_ON_EXEC (bad_stdin);
1055 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1057 /* Decide whether to give this child the `good' standard input
1058 (one that points to the terminal or whatever), or the `bad' one
1059 that points to the read side of a broken pipe. */
1061 child->good_stdin = !good_stdin_used;
1062 if (child->good_stdin)
1063 good_stdin_used = 1;
1065 #endif /* !VMS */
1067 child->deleted = 0;
1069 #ifndef _AMIGA
1070 /* Set up the environment for the child. */
1071 if (child->environment == 0)
1072 child->environment = target_environment (child->file);
1073 #endif
1075 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1077 #ifndef VMS
1078 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1079 if (child->remote)
1081 int is_remote, id, used_stdin;
1082 if (start_remote_job (argv, child->environment,
1083 child->good_stdin ? 0 : bad_stdin,
1084 &is_remote, &id, &used_stdin))
1085 /* Don't give up; remote execution may fail for various reasons. If
1086 so, simply run the job locally. */
1087 goto run_local;
1088 else
1090 if (child->good_stdin && !used_stdin)
1092 child->good_stdin = 0;
1093 good_stdin_used = 0;
1095 child->remote = is_remote;
1096 child->pid = id;
1099 else
1100 #endif /* !VMS */
1102 /* Fork the child process. */
1104 char **parent_environ;
1106 run_local:
1107 block_sigs ();
1109 child->remote = 0;
1111 #ifdef VMS
1113 if (!child_execute_job (argv, child)) {
1114 /* Fork failed! */
1115 perror_with_name ("vfork", "");
1116 goto error;
1119 #else
1121 parent_environ = environ;
1122 child->pid = vfork ();
1123 environ = parent_environ; /* Restore value child may have clobbered. */
1124 if (child->pid == 0)
1126 /* We are the child side. */
1127 unblock_sigs ();
1129 /* If we aren't running a recursive command and we have a jobserver
1130 pipe, close it before exec'ing. */
1131 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1133 close (job_fds[0]);
1134 close (job_fds[1]);
1136 if (job_rfd >= 0)
1137 close (job_rfd);
1139 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1140 argv, child->environment);
1142 else if (child->pid < 0)
1144 /* Fork failed! */
1145 unblock_sigs ();
1146 perror_with_name ("vfork", "");
1147 goto error;
1149 #endif /* !VMS */
1152 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1153 #ifdef __MSDOS__
1155 int proc_return;
1157 block_sigs ();
1158 dos_status = 0;
1160 /* We call `system' to do the job of the SHELL, since stock DOS
1161 shell is too dumb. Our `system' knows how to handle long
1162 command lines even if pipes/redirection is needed; it will only
1163 call COMMAND.COM when its internal commands are used. */
1164 if (execute_by_shell)
1166 char *cmdline = argv[0];
1167 /* We don't have a way to pass environment to `system',
1168 so we need to save and restore ours, sigh... */
1169 char **parent_environ = environ;
1171 environ = child->environment;
1173 /* If we have a *real* shell, tell `system' to call
1174 it to do everything for us. */
1175 if (unixy_shell)
1177 /* A *real* shell on MSDOS may not support long
1178 command lines the DJGPP way, so we must use `system'. */
1179 cmdline = argv[2]; /* get past "shell -c" */
1182 dos_command_running = 1;
1183 proc_return = system (cmdline);
1184 environ = parent_environ;
1185 execute_by_shell = 0; /* for the next time */
1187 else
1189 dos_command_running = 1;
1190 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1193 /* Need to unblock signals before turning off
1194 dos_command_running, so that child's signals
1195 will be treated as such (see fatal_error_signal). */
1196 unblock_sigs ();
1197 dos_command_running = 0;
1199 /* If the child got a signal, dos_status has its
1200 high 8 bits set, so be careful not to alter them. */
1201 if (proc_return == -1)
1202 dos_status |= 0xff;
1203 else
1204 dos_status |= (proc_return & 0xff);
1205 ++dead_children;
1206 child->pid = dos_pid++;
1208 #endif /* __MSDOS__ */
1209 #ifdef _AMIGA
1210 amiga_status = MyExecute (argv);
1212 ++dead_children;
1213 child->pid = amiga_pid++;
1214 if (amiga_batch_file)
1216 amiga_batch_file = 0;
1217 DeleteFile (amiga_bname); /* Ignore errors. */
1219 #endif /* Amiga */
1220 #ifdef WINDOWS32
1222 HANDLE hPID;
1223 char* arg0;
1225 /* make UNC paths safe for CreateProcess -- backslash format */
1226 arg0 = argv[0];
1227 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1228 for ( ; arg0 && *arg0; arg0++)
1229 if (*arg0 == '/')
1230 *arg0 = '\\';
1232 /* make sure CreateProcess() has Path it needs */
1233 sync_Path_environment();
1235 hPID = process_easy(argv, child->environment);
1237 if (hPID != INVALID_HANDLE_VALUE)
1238 child->pid = (int) hPID;
1239 else {
1240 int i;
1241 unblock_sigs();
1242 fprintf(stderr,
1243 _("process_easy() failed failed to launch process (e=%d)\n"),
1244 process_last_err(hPID));
1245 for (i = 0; argv[i]; i++)
1246 fprintf(stderr, "%s ", argv[i]);
1247 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1250 #endif /* WINDOWS32 */
1251 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1253 /* We are the parent side. Set the state to
1254 say the commands are running and return. */
1256 set_command_state (child->file, cs_running);
1258 /* Free the storage used by the child's argument list. */
1259 #ifndef VMS
1260 free (argv[0]);
1261 free ((char *) argv);
1262 #endif
1264 return;
1266 error:
1267 child->file->update_status = 2;
1268 notice_finished_file (child->file);
1269 return;
1272 /* Try to start a child running.
1273 Returns nonzero if the child was started (and maybe finished), or zero if
1274 the load was too high and the child was put on the `waiting_jobs' chain. */
1276 static int
1277 start_waiting_job (struct child *c)
1279 struct file *f = c->file;
1281 /* If we can start a job remotely, we always want to, and don't care about
1282 the local load average. We record that the job should be started
1283 remotely in C->remote for start_job_command to test. */
1285 c->remote = start_remote_job_p (1);
1287 /* If we are running at least one job already and the load average
1288 is too high, make this one wait. */
1289 if (!c->remote && job_slots_used > 0 && load_too_high ())
1291 /* Put this child on the chain of children waiting for the load average
1292 to go down. */
1293 set_command_state (f, cs_running);
1294 c->next = waiting_jobs;
1295 waiting_jobs = c;
1296 return 0;
1299 /* Start the first command; reap_children will run later command lines. */
1300 start_job_command (c);
1302 switch (f->command_state)
1304 case cs_running:
1305 c->next = children;
1306 DB (DB_JOBS, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1307 (unsigned long int) c, c->file->name,
1308 (long) c->pid, c->remote ? _(" (remote)") : ""));
1309 children = c;
1310 /* One more job slot is in use. */
1311 ++job_slots_used;
1312 unblock_sigs ();
1313 break;
1315 case cs_not_started:
1316 /* All the command lines turned out to be empty. */
1317 f->update_status = 0;
1318 /* FALLTHROUGH */
1320 case cs_finished:
1321 notice_finished_file (f);
1322 free_child (c);
1323 break;
1325 default:
1326 assert (f->command_state == cs_finished);
1327 break;
1330 return 1;
1333 /* Create a `struct child' for FILE and start its commands running. */
1335 void
1336 new_job (struct file *file)
1338 register struct commands *cmds = file->cmds;
1339 register struct child *c;
1340 char **lines;
1341 register unsigned int i;
1343 /* Let any previously decided-upon jobs that are waiting
1344 for the load to go down start before this new one. */
1345 start_waiting_jobs ();
1347 /* Reap any children that might have finished recently. */
1348 reap_children (0, 0);
1350 /* Chop the commands up into lines if they aren't already. */
1351 chop_commands (cmds);
1353 /* Expand the command lines and store the results in LINES. */
1354 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1355 for (i = 0; i < cmds->ncommand_lines; ++i)
1357 /* Collapse backslash-newline combinations that are inside variable
1358 or function references. These are left alone by the parser so
1359 that they will appear in the echoing of commands (where they look
1360 nice); and collapsed by construct_command_argv when it tokenizes.
1361 But letting them survive inside function invocations loses because
1362 we don't want the functions to see them as part of the text. */
1364 char *in, *out, *ref;
1366 /* IN points to where in the line we are scanning.
1367 OUT points to where in the line we are writing.
1368 When we collapse a backslash-newline combination,
1369 IN gets ahead of OUT. */
1371 in = out = cmds->command_lines[i];
1372 while ((ref = strchr (in, '$')) != 0)
1374 ++ref; /* Move past the $. */
1376 if (out != in)
1377 /* Copy the text between the end of the last chunk
1378 we processed (where IN points) and the new chunk
1379 we are about to process (where REF points). */
1380 bcopy (in, out, ref - in);
1382 /* Move both pointers past the boring stuff. */
1383 out += ref - in;
1384 in = ref;
1386 if (*ref == '(' || *ref == '{')
1388 char openparen = *ref;
1389 char closeparen = openparen == '(' ? ')' : '}';
1390 int count;
1391 char *p;
1393 *out++ = *in++; /* Copy OPENPAREN. */
1394 /* IN now points past the opening paren or brace.
1395 Count parens or braces until it is matched. */
1396 count = 0;
1397 while (*in != '\0')
1399 if (*in == closeparen && --count < 0)
1400 break;
1401 else if (*in == '\\' && in[1] == '\n')
1403 /* We have found a backslash-newline inside a
1404 variable or function reference. Eat it and
1405 any following whitespace. */
1407 int quoted = 0;
1408 for (p = in - 1; p > ref && *p == '\\'; --p)
1409 quoted = !quoted;
1411 if (quoted)
1412 /* There were two or more backslashes, so this is
1413 not really a continuation line. We don't collapse
1414 the quoting backslashes here as is done in
1415 collapse_continuations, because the line will
1416 be collapsed again after expansion. */
1417 *out++ = *in++;
1418 else
1420 /* Skip the backslash, newline and
1421 any following whitespace. */
1422 in = next_token (in + 2);
1424 /* Discard any preceding whitespace that has
1425 already been written to the output. */
1426 while (out > ref
1427 && isblank ((unsigned char)out[-1]))
1428 --out;
1430 /* Replace it all with a single space. */
1431 *out++ = ' ';
1434 else
1436 if (*in == openparen)
1437 ++count;
1439 *out++ = *in++;
1445 /* There are no more references in this line to worry about.
1446 Copy the remaining uninteresting text to the output. */
1447 if (out != in)
1448 strcpy (out, in);
1450 /* Finally, expand the line. */
1451 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1452 file);
1455 /* Start the command sequence, record it in a new
1456 `struct child', and add that to the chain. */
1458 c = (struct child *) xmalloc (sizeof (struct child));
1459 bzero ((char *)c, sizeof (struct child));
1460 c->file = file;
1461 c->command_lines = lines;
1462 c->sh_batch_file = NULL;
1464 /* Fetch the first command line to be run. */
1465 job_next_command (c);
1467 /* Wait for a job slot to be freed up. If we allow an infinite number
1468 don't bother; also job_slots will == 0 if we're using the jobserver. */
1470 if (job_slots != 0)
1471 while (job_slots_used == job_slots)
1472 reap_children (1, 0);
1474 #ifdef MAKE_JOBSERVER
1475 /* If we are controlling multiple jobs make sure we have a token before
1476 starting the child. */
1478 /* This can be inefficient. There's a decent chance that this job won't
1479 actually have to run any subprocesses: the command script may be empty
1480 or otherwise optimized away. It would be nice if we could defer
1481 obtaining a token until just before we need it, in start_job_command.
1482 To do that we'd need to keep track of whether we'd already obtained a
1483 token (since start_job_command is called for each line of the job, not
1484 just once). Also more thought needs to go into the entire algorithm;
1485 this is where the old parallel job code waits, so... */
1487 else if (job_fds[0] >= 0)
1488 while (1)
1490 char token;
1491 int got_token;
1492 int saved_errno;
1494 DB (DB_JOBS, ("Need a job token; we %shave children\n",
1495 children ? "" : "don't "));
1497 /* If we don't already have a job started, use our "free" token. */
1498 if (!children)
1499 break;
1501 /* Read a token. As long as there's no token available we'll block.
1502 We enable interruptible system calls before the read(2) so that if
1503 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1504 we can process the death(s) and return tokens to the free pool.
1506 Once we return from the read, we immediately reinstate restartable
1507 system calls. This allows us to not worry about checking for
1508 EINTR on all the other system calls in the program.
1510 There is one other twist: there is a span between the time
1511 reap_children() does its last check for dead children and the time
1512 the read(2) call is entered, below, where if a child dies we won't
1513 notice. This is extremely serious as it could cause us to
1514 deadlock, given the right set of events.
1516 To avoid this, we do the following: before we reap_children(), we
1517 dup(2) the read FD on the jobserver pipe. The read(2) call below
1518 uses that new FD. In the signal handler, we close that FD. That
1519 way, if a child dies during the section mentioned above, the
1520 read(2) will be invoked with an invalid FD and will return
1521 immediately with EBADF. */
1523 /* Make sure we have a dup'd FD. */
1524 if (job_rfd < 0)
1526 DB (DB_JOBS, ("Duplicate the job FD\n"));
1527 job_rfd = dup (job_fds[0]);
1530 /* Reap anything that's currently waiting. */
1531 reap_children (0, 0);
1533 /* If our "free" token has become available, use it. */
1534 if (!children)
1535 break;
1537 /* Set interruptible system calls, and read() for a job token. */
1538 set_child_handler_action_flags (0);
1539 got_token = read (job_rfd, &token, 1);
1540 saved_errno = errno;
1541 set_child_handler_action_flags (SA_RESTART);
1543 /* If we got one, we're done here. */
1544 if (got_token == 1)
1546 DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1547 (unsigned long int) c, c->file->name));
1548 break;
1551 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1552 go back and reap_children(), and try again. */
1553 errno = saved_errno;
1554 if (errno != EINTR && errno != EBADF)
1555 pfatal_with_name (_("read jobs pipe"));
1556 if (errno == EBADF)
1557 DB (DB_JOBS, ("Read returned EBADF.\n"));
1559 #endif
1561 /* The job is now primed. Start it running.
1562 (This will notice if there are in fact no commands.) */
1563 (void) start_waiting_job (c);
1565 if (job_slots == 1 || not_parallel)
1566 /* Since there is only one job slot, make things run linearly.
1567 Wait for the child to die, setting the state to `cs_finished'. */
1568 while (file->command_state == cs_running)
1569 reap_children (1, 0);
1571 return;
1574 /* Move CHILD's pointers to the next command for it to execute.
1575 Returns nonzero if there is another command. */
1577 static int
1578 job_next_command (struct child *child)
1580 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1582 /* There are no more lines in the expansion of this line. */
1583 if (child->command_line == child->file->cmds->ncommand_lines)
1585 /* There are no more lines to be expanded. */
1586 child->command_ptr = 0;
1587 return 0;
1589 else
1590 /* Get the next line to run. */
1591 child->command_ptr = child->command_lines[child->command_line++];
1593 return 1;
1596 static int
1597 load_too_high (void)
1599 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1600 return 1;
1601 #else
1602 double load;
1604 if (max_load_average < 0)
1605 return 0;
1607 make_access ();
1608 if (getloadavg (&load, 1) != 1)
1610 static int lossage = -1;
1611 /* Complain only once for the same error. */
1612 if (lossage == -1 || errno != lossage)
1614 if (errno == 0)
1615 /* An errno value of zero means getloadavg is just unsupported. */
1616 error (NILF,
1617 _("cannot enforce load limits on this operating system"));
1618 else
1619 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1621 lossage = errno;
1622 load = 0;
1624 user_access ();
1626 DB (DB_JOBS, ("Current system load = %f (max requested = %f)\n",
1627 load, max_load_average));
1628 return load >= max_load_average;
1629 #endif
1632 /* Start jobs that are waiting for the load to be lower. */
1634 void
1635 start_waiting_jobs (void)
1637 struct child *job;
1639 if (waiting_jobs == 0)
1640 return;
1644 /* Check for recently deceased descendants. */
1645 reap_children (0, 0);
1647 /* Take a job off the waiting list. */
1648 job = waiting_jobs;
1649 waiting_jobs = job->next;
1651 /* Try to start that job. We break out of the loop as soon
1652 as start_waiting_job puts one back on the waiting list. */
1654 while (start_waiting_job (job) && waiting_jobs != 0);
1656 return;
1659 #ifndef WINDOWS32
1660 #ifdef VMS
1661 #include <descrip.h>
1662 #include <clidef.h>
1664 /* This is called as an AST when a child process dies (it won't get
1665 interrupted by anything except a higher level AST).
1667 int vmsHandleChildTerm(struct child *child)
1669 int status;
1670 register struct child *lastc, *c;
1671 int child_failed;
1673 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1675 lib$free_ef(&child->efn);
1677 (void) sigblock (fatal_signal_mask);
1679 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1681 /* Search for a child matching the deceased one. */
1682 lastc = 0;
1683 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1684 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1685 #else
1686 c = child;
1687 #endif
1689 if (child_failed && !c->noerror && !ignore_errors_flag)
1691 /* The commands failed. Write an error message,
1692 delete non-precious targets, and abort. */
1693 child_error (c->file->name, c->cstatus, 0, 0, 0);
1694 c->file->update_status = 1;
1695 delete_child_targets (c);
1697 else
1699 if (child_failed)
1701 /* The commands failed, but we don't care. */
1702 child_error (c->file->name, c->cstatus, 0, 0, 1);
1703 child_failed = 0;
1706 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1707 /* If there are more commands to run, try to start them. */
1708 start_job (c);
1710 switch (c->file->command_state)
1712 case cs_running:
1713 /* Successfully started. */
1714 break;
1716 case cs_finished:
1717 if (c->file->update_status != 0) {
1718 /* We failed to start the commands. */
1719 delete_child_targets (c);
1721 break;
1723 default:
1724 error (NILF, _("internal error: `%s' command_state"),
1725 c->file->name);
1726 abort ();
1727 break;
1729 #endif /* RECURSIVEJOBS */
1732 /* Set the state flag to say the commands have finished. */
1733 c->file->command_state = cs_finished;
1734 notice_finished_file (c->file);
1736 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1737 /* Remove the child from the chain and free it. */
1738 if (lastc == 0)
1739 children = c->next;
1740 else
1741 lastc->next = c->next;
1742 free_child (c);
1743 #endif /* RECURSIVEJOBS */
1745 /* There is now another slot open. */
1746 if (job_slots_used > 0)
1747 --job_slots_used;
1749 /* If the job failed, and the -k flag was not given, die. */
1750 if (child_failed && !keep_going_flag)
1751 die (EXIT_FAILURE);
1753 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1755 return 1;
1758 /* VMS:
1759 Spawn a process executing the command in ARGV and return its pid. */
1761 #define MAXCMDLEN 200
1763 /* local helpers to make ctrl+c and ctrl+y working, see below */
1764 #include <iodef.h>
1765 #include <libclidef.h>
1766 #include <ssdef.h>
1768 static int ctrlMask= LIB$M_CLI_CTRLY;
1769 static int oldCtrlMask;
1770 static int setupYAstTried= 0;
1771 static int pidToAbort= 0;
1772 static int chan= 0;
1774 static void reEnableAst(void) {
1775 lib$enable_ctrl (&oldCtrlMask,0);
1778 static astHandler (void) {
1779 if (pidToAbort) {
1780 sys$forcex (&pidToAbort, 0, SS$_ABORT);
1781 pidToAbort= 0;
1783 kill (getpid(),SIGQUIT);
1786 static void tryToSetupYAst(void) {
1787 $DESCRIPTOR(inputDsc,"SYS$COMMAND");
1788 int status;
1789 struct {
1790 short int status, count;
1791 int dvi;
1792 } iosb;
1794 setupYAstTried++;
1796 if (!chan) {
1797 status= sys$assign(&inputDsc,&chan,0,0);
1798 if (!(status&SS$_NORMAL)) {
1799 lib$signal(status);
1800 return;
1803 status= sys$qiow (0, chan, IO$_SETMODE|IO$M_CTRLYAST,&iosb,0,0,
1804 astHandler,0,0,0,0,0);
1805 if (status==SS$_ILLIOFUNC) {
1806 sys$dassgn(chan);
1807 #ifdef CTRLY_ENABLED_ANYWAY
1808 fprintf (stderr,
1809 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
1810 #else
1811 return;
1812 #endif
1814 if (status==SS$_NORMAL)
1815 status= iosb.status;
1816 if (!(status&SS$_NORMAL)) {
1817 lib$signal(status);
1818 return;
1821 /* called from AST handler ? */
1822 if (setupYAstTried>1)
1823 return;
1824 if (atexit(reEnableAst))
1825 fprintf (stderr,
1826 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
1827 status= lib$disable_ctrl (&ctrlMask, &oldCtrlMask);
1828 if (!(status&SS$_NORMAL)) {
1829 lib$signal(status);
1830 return;
1834 child_execute_job (char *argv, struct child *child)
1836 int i;
1837 static struct dsc$descriptor_s cmddsc;
1838 static struct dsc$descriptor_s pnamedsc;
1839 static struct dsc$descriptor_s ifiledsc;
1840 static struct dsc$descriptor_s ofiledsc;
1841 static struct dsc$descriptor_s efiledsc;
1842 int have_redirection = 0;
1843 int have_newline = 0;
1845 int spflags = CLI$M_NOWAIT;
1846 int status;
1847 char *cmd = alloca (strlen (argv) + 512), *p, *q;
1848 char ifile[256], ofile[256], efile[256];
1849 char *comname = 0;
1850 char procname[100];
1852 /* Parse IO redirection. */
1854 ifile[0] = 0;
1855 ofile[0] = 0;
1856 efile[0] = 0;
1858 DB (DB_JOBS, ("child_execute_job (%s)\n", argv));
1860 while (isspace ((unsigned char)*argv))
1861 argv++;
1863 if (*argv == 0)
1864 return 0;
1866 sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
1867 pnamedsc.dsc$w_length = strlen(procname);
1868 pnamedsc.dsc$a_pointer = procname;
1869 pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
1870 pnamedsc.dsc$b_class = DSC$K_CLASS_S;
1872 /* Handle comments and redirection. */
1873 for (p = argv, q = cmd; *p; p++, q++)
1875 switch (*p)
1877 case '#':
1878 *p-- = 0;
1879 *q-- = 0;
1880 break;
1881 case '\\':
1882 p++;
1883 if (*p == '\n')
1884 p++;
1885 if (isspace ((unsigned char)*p))
1887 do { p++; } while (isspace ((unsigned char)*p));
1888 p--;
1890 *q = *p;
1891 break;
1892 case '<':
1893 p = vms_redirect (&ifiledsc, ifile, p);
1894 *q = ' ';
1895 have_redirection = 1;
1896 break;
1897 case '>':
1898 have_redirection = 1;
1899 if (*(p-1) == '2')
1901 q--;
1902 if (strncmp (p, ">&1", 3) == 0)
1904 p += 3;
1905 strcpy (efile, "sys$output");
1906 efiledsc.dsc$w_length = strlen(efile);
1907 efiledsc.dsc$a_pointer = efile;
1908 efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
1909 efiledsc.dsc$b_class = DSC$K_CLASS_S;
1911 else
1913 p = vms_redirect (&efiledsc, efile, p);
1916 else
1918 p = vms_redirect (&ofiledsc, ofile, p);
1920 *q = ' ';
1921 break;
1922 case '\n':
1923 have_newline = 1;
1924 default:
1925 *q = *p;
1926 break;
1929 *q = *p;
1931 if (strncmp (cmd, "builtin_", 8) == 0)
1933 child->pid = 270163;
1934 child->efn = 0;
1935 child->cstatus = 1;
1937 DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));
1939 p = cmd + 8;
1941 if ((*(p) == 'c')
1942 && (*(p+1) == 'd')
1943 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
1945 p += 3;
1946 while ((*p == ' ') || (*p == '\t'))
1947 p++;
1948 DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
1949 if (chdir (p))
1950 return 0;
1951 else
1952 return 1;
1954 else if ((*(p) == 'r')
1955 && (*(p+1) == 'm')
1956 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
1958 int in_arg;
1960 /* rm */
1961 p += 3;
1962 while ((*p == ' ') || (*p == '\t'))
1963 p++;
1964 in_arg = 1;
1966 DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
1967 while (*p)
1969 switch (*p)
1971 case ' ':
1972 case '\t':
1973 if (in_arg)
1975 *p++ = ';';
1976 in_arg = 0;
1978 break;
1979 default:
1980 break;
1982 p++;
1985 else
1987 printf(_("Unknown builtin command '%s'\n"), cmd);
1988 fflush(stdout);
1989 return 0;
1993 /* Create a *.com file if either the command is too long for
1994 lib$spawn, or the command contains a newline, or if redirection
1995 is desired. Forcing commands with newlines into DCLs allows to
1996 store search lists on user mode logicals. */
1998 if (strlen (cmd) > MAXCMDLEN
1999 || (have_redirection != 0)
2000 || (have_newline != 0))
2002 FILE *outfile;
2003 char c;
2004 char *sep;
2005 int alevel = 0; /* apostrophe level */
2007 if (strlen (cmd) == 0)
2009 printf (_("Error, empty command\n"));
2010 fflush (stdout);
2011 return 0;
2014 outfile = open_tmpfile (&comname, "sys$scratch:CMDXXXXXX.COM");
2015 if (outfile == 0)
2016 pfatal_with_name (_("fopen (temporary file)"));
2018 if (ifile[0])
2020 fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
2021 DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
2022 ifiledsc.dsc$w_length = 0;
2025 if (efile[0])
2027 fprintf (outfile, "$ define sys$error %s\n", efile);
2028 DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
2029 efiledsc.dsc$w_length = 0;
2032 if (ofile[0])
2034 fprintf (outfile, "$ define sys$output %s\n", ofile);
2035 DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
2036 ofiledsc.dsc$w_length = 0;
2039 p = sep = q = cmd;
2040 for (c = '\n'; c; c = *q++)
2042 switch (c)
2044 case '\n':
2045 /* At a newline, skip any whitespace around a leading $
2046 from the command and issue exactly one $ into the DCL. */
2047 while (isspace ((unsigned char)*p))
2048 p++;
2049 if (*p == '$')
2050 p++;
2051 while (isspace ((unsigned char)*p))
2052 p++;
2053 fwrite (p, 1, q - p, outfile);
2054 fputc ('$', outfile);
2055 fputc (' ', outfile);
2056 /* Reset variables. */
2057 p = sep = q;
2058 break;
2060 /* Nice places for line breaks are after strings, after
2061 comma or space and before slash. */
2062 case '"':
2063 q = handle_apos (q + 1);
2064 sep = q;
2065 break;
2066 case ',':
2067 case ' ':
2068 sep = q;
2069 break;
2070 case '/':
2071 case '\0':
2072 sep = q - 1;
2073 break;
2074 default:
2075 break;
2077 if (sep - p > 78)
2079 /* Enough stuff for a line. */
2080 fwrite (p, 1, sep - p, outfile);
2081 p = sep;
2082 if (*sep)
2084 /* The command continues. */
2085 fputc ('-', outfile);
2087 fputc ('\n', outfile);
2091 fwrite (p, 1, q - p, outfile);
2092 fputc ('\n', outfile);
2094 fclose (outfile);
2096 sprintf (cmd, "$ @%s", comname);
2098 DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
2101 cmddsc.dsc$w_length = strlen(cmd);
2102 cmddsc.dsc$a_pointer = cmd;
2103 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
2104 cmddsc.dsc$b_class = DSC$K_CLASS_S;
2106 child->efn = 0;
2107 while (child->efn < 32 || child->efn > 63)
2109 status = lib$get_ef ((unsigned long *)&child->efn);
2110 if (!(status & 1))
2111 return 0;
2114 sys$clref (child->efn);
2116 vms_jobsefnmask |= (1 << (child->efn - 32));
2119 LIB$SPAWN [command-string]
2120 [,input-file]
2121 [,output-file]
2122 [,flags]
2123 [,process-name]
2124 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2125 [,AST-address] [,varying-AST-argument]
2126 [,prompt-string] [,cli] [,table]
2129 #ifndef DONTWAITFORCHILD
2131 * Code to make ctrl+c and ctrl+y working.
2132 * The problem starts with the synchronous case where after lib$spawn is
2133 * called any input will go to the child. But with input re-directed,
2134 * both control characters won't make it to any of the programs, neither
2135 * the spawning nor to the spawned one. Hence the caller needs to spawn
2136 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2137 * has to follow to simulate the wanted synchronous behaviour.
2138 * The next problem is ctrl+y which isn't caught by the crtl and
2139 * therefore isn't converted to SIGQUIT (for a signal handler which is
2140 * already established). The only way to catch ctrl+y, is an AST
2141 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2142 * disabled, otherwise it will handle it. Not to mention the previous
2143 * ctrl+y handling of DCL needs to be re-established before make exits.
2144 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2145 * make it to the signal handler after the child "normally" terminates.
2146 * This isn't enough. It seems reasonable for simple command lines like
2147 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2148 * spawning make. Therefore we need to abort the process in the AST.
2150 * Prior to the spawn it is checked if an AST is already set up for
2151 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2152 * this will work except if make is run in a batch environment, but there
2153 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2154 * is disabled and an exit handler is established to re-enable it.
2155 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2156 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2157 * the already established handler and will bring us back to common code.
2158 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2159 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2160 * which the crtl converts to SIGINT and which is caught by the common
2161 * signal handler. Because signals were blocked before entering this code
2162 * sys$waitfr will always complete and the SIGQUIT will be processed after
2163 * it (after termination of the current block, somewhere in common code).
2164 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2165 * current command completes. Anyway it's better than nothing :-)
2168 if (!setupYAstTried)
2169 tryToSetupYAst();
2170 status = lib$spawn (&cmddsc, /* cmd-string */
2171 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file */
2172 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
2173 &spflags, /* flags */
2174 &pnamedsc, /* proc name */
2175 &child->pid, &child->cstatus, &child->efn,
2176 0, 0,
2177 0, 0, 0);
2178 pidToAbort= child->pid;
2179 status= sys$waitfr (child->efn);
2180 pidToAbort= 0;
2181 vmsHandleChildTerm(child);
2182 #else
2183 status = lib$spawn (&cmddsc,
2184 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
2185 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
2186 &spflags,
2187 &pnamedsc,
2188 &child->pid, &child->cstatus, &child->efn,
2189 vmsHandleChildTerm, child,
2190 0, 0, 0);
2191 #endif
2193 if (!(status & 1))
2195 printf (_("Error spawning, %d\n") ,status);
2196 fflush (stdout);
2199 if (comname && !ISDB (DB_JOBS))
2200 unlink (comname);
2202 return (status & 1);
2205 #else /* !VMS */
2207 #if !defined (_AMIGA) && !defined (__MSDOS__)
2208 /* UNIX:
2209 Replace the current process with one executing the command in ARGV.
2210 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2211 the environment of the new program. This function does not return. */
2213 void
2214 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2216 if (stdin_fd != 0)
2217 (void) dup2 (stdin_fd, 0);
2218 if (stdout_fd != 1)
2219 (void) dup2 (stdout_fd, 1);
2220 if (stdin_fd != 0)
2221 (void) close (stdin_fd);
2222 if (stdout_fd != 1)
2223 (void) close (stdout_fd);
2225 /* Run the command. */
2226 exec_command (argv, envp);
2228 #endif /* !AMIGA && !__MSDOS__ */
2229 #endif /* !VMS */
2230 #endif /* !WINDOWS32 */
2232 #ifndef _AMIGA
2233 /* Replace the current process with one running the command in ARGV,
2234 with environment ENVP. This function does not return. */
2236 void
2237 exec_command (char **argv, char **envp)
2239 #ifdef VMS
2240 /* to work around a problem with signals and execve: ignore them */
2241 #ifdef SIGCHLD
2242 signal (SIGCHLD,SIG_IGN);
2243 #endif
2244 /* Run the program. */
2245 execve (argv[0], argv, envp);
2246 perror_with_name ("execve: ", argv[0]);
2247 _exit (EXIT_FAILURE);
2248 #else
2249 #ifdef WINDOWS32
2250 HANDLE hPID;
2251 HANDLE hWaitPID;
2252 int err = 0;
2253 int exit_code = EXIT_FAILURE;
2255 /* make sure CreateProcess() has Path it needs */
2256 sync_Path_environment();
2258 /* launch command */
2259 hPID = process_easy(argv, envp);
2261 /* make sure launch ok */
2262 if (hPID == INVALID_HANDLE_VALUE)
2264 int i;
2265 fprintf(stderr,
2266 _("process_easy() failed failed to launch process (e=%d)\n"),
2267 process_last_err(hPID));
2268 for (i = 0; argv[i]; i++)
2269 fprintf(stderr, "%s ", argv[i]);
2270 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2271 exit(EXIT_FAILURE);
2274 /* wait and reap last child */
2275 while (hWaitPID = process_wait_for_any())
2277 /* was an error found on this process? */
2278 err = process_last_err(hWaitPID);
2280 /* get exit data */
2281 exit_code = process_exit_code(hWaitPID);
2283 if (err)
2284 fprintf(stderr, "make (e=%d, rc=%d): %s",
2285 err, exit_code, map_windows32_error_to_string(err));
2287 /* cleanup process */
2288 process_cleanup(hWaitPID);
2290 /* expect to find only last pid, warn about other pids reaped */
2291 if (hWaitPID == hPID)
2292 break;
2293 else
2294 fprintf(stderr,
2295 _("make reaped child pid %d, still waiting for pid %d\n"),
2296 hWaitPID, hPID);
2299 /* return child's exit code as our exit code */
2300 exit(exit_code);
2302 #else /* !WINDOWS32 */
2304 /* Be the user, permanently. */
2305 child_access ();
2307 /* Run the program. */
2308 environ = envp;
2309 execvp (argv[0], argv);
2311 switch (errno)
2313 case ENOENT:
2314 error (NILF, _("%s: Command not found"), argv[0]);
2315 break;
2316 case ENOEXEC:
2318 /* The file is not executable. Try it as a shell script. */
2319 extern char *getenv ();
2320 char *shell;
2321 char **new_argv;
2322 int argc;
2324 shell = getenv ("SHELL");
2325 if (shell == 0)
2326 shell = default_shell;
2328 argc = 1;
2329 while (argv[argc] != 0)
2330 ++argc;
2332 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
2333 new_argv[0] = shell;
2334 new_argv[1] = argv[0];
2335 while (argc > 0)
2337 new_argv[1 + argc] = argv[argc];
2338 --argc;
2341 execvp (shell, new_argv);
2342 if (errno == ENOENT)
2343 error (NILF, _("%s: Shell program not found"), shell);
2344 else
2345 perror_with_name ("execvp: ", shell);
2346 break;
2349 default:
2350 perror_with_name ("execvp: ", argv[0]);
2351 break;
2354 _exit (127);
2355 #endif /* !WINDOWS32 */
2356 #endif /* !VMS */
2358 #else /* On Amiga */
2359 void exec_command (char **argv)
2361 MyExecute (argv);
2364 void clean_tmp (void)
2366 DeleteFile (amiga_bname);
2369 #endif /* On Amiga */
2371 #ifndef VMS
2372 /* Figure out the argument list necessary to run LINE as a command. Try to
2373 avoid using a shell. This routine handles only ' quoting, and " quoting
2374 when no backslash, $ or ` characters are seen in the quotes. Starting
2375 quotes may be escaped with a backslash. If any of the characters in
2376 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2377 is the first word of a line, the shell is used.
2379 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2380 If *RESTP is NULL, newlines will be ignored.
2382 SHELL is the shell to use, or nil to use the default shell.
2383 IFS is the value of $IFS, or nil (meaning the default). */
2385 static char **
2386 construct_command_argv_internal (char *line, char **restp, char *shell,
2387 char *ifs, char **batch_filename_ptr)
2389 #ifdef __MSDOS__
2390 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2391 We call `system' for anything that requires ``slow'' processing,
2392 because DOS shells are too dumb. When $SHELL points to a real
2393 (unix-style) shell, `system' just calls it to do everything. When
2394 $SHELL points to a DOS shell, `system' does most of the work
2395 internally, calling the shell only for its internal commands.
2396 However, it looks on the $PATH first, so you can e.g. have an
2397 external command named `mkdir'.
2399 Since we call `system', certain characters and commands below are
2400 actually not specific to COMMAND.COM, but to the DJGPP implementation
2401 of `system'. In particular:
2403 The shell wildcard characters are in DOS_CHARS because they will
2404 not be expanded if we call the child via `spawnXX'.
2406 The `;' is in DOS_CHARS, because our `system' knows how to run
2407 multiple commands on a single line.
2409 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2410 won't have to tell one from another and have one more set of
2411 commands and special characters. */
2412 static char sh_chars_dos[] = "*?[];|<>%^&()";
2413 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2414 "copy", "ctty", "date", "del", "dir", "echo",
2415 "erase", "exit", "for", "goto", "if", "md",
2416 "mkdir", "path", "pause", "prompt", "rd",
2417 "rmdir", "rem", "ren", "rename", "set",
2418 "shift", "time", "type", "ver", "verify",
2419 "vol", ":", 0 };
2421 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2422 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2423 "logout", "set", "umask", "wait", "while",
2424 "for", "case", "if", ":", ".", "break",
2425 "continue", "export", "read", "readonly",
2426 "shift", "times", "trap", "switch", "unset",
2427 0 };
2429 char *sh_chars;
2430 char **sh_cmds;
2431 #else
2432 #ifdef _AMIGA
2433 static char sh_chars[] = "#;\"|<>()?*$`";
2434 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2435 "rename", "set", "setenv", "date", "makedir",
2436 "skip", "else", "endif", "path", "prompt",
2437 "unset", "unsetenv", "version",
2438 0 };
2439 #else
2440 #ifdef WINDOWS32
2441 static char sh_chars_dos[] = "\"|&<>";
2442 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2443 "copy", "ctty", "date", "del", "dir", "echo",
2444 "erase", "exit", "for", "goto", "if", "if", "md",
2445 "mkdir", "path", "pause", "prompt", "rd", "rem",
2446 "ren", "rename", "rmdir", "set", "shift", "time",
2447 "type", "ver", "verify", "vol", ":", 0 };
2448 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2449 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2450 "logout", "set", "umask", "wait", "while", "for",
2451 "case", "if", ":", ".", "break", "continue",
2452 "export", "read", "readonly", "shift", "times",
2453 "trap", "switch", "test",
2454 #ifdef BATCH_MODE_ONLY_SHELL
2455 "echo",
2456 #endif
2457 0 };
2458 char* sh_chars;
2459 char** sh_cmds;
2460 #else /* must be UNIX-ish */
2461 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~";
2462 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
2463 "logout", "set", "umask", "wait", "while", "for",
2464 "case", "if", ":", ".", "break", "continue",
2465 "export", "read", "readonly", "shift", "times",
2466 "trap", "switch", 0 };
2467 #endif /* WINDOWS32 */
2468 #endif /* Amiga */
2469 #endif /* __MSDOS__ */
2470 register int i;
2471 register char *p;
2472 register char *ap;
2473 char *end;
2474 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2475 char **new_argv = 0;
2476 #ifdef WINDOWS32
2477 int slow_flag = 0;
2479 if (no_default_sh_exe) {
2480 sh_cmds = sh_cmds_dos;
2481 sh_chars = sh_chars_dos;
2482 } else {
2483 sh_cmds = sh_cmds_sh;
2484 sh_chars = sh_chars_sh;
2486 #endif /* WINDOWS32 */
2488 if (restp != NULL)
2489 *restp = NULL;
2491 /* Make sure not to bother processing an empty line. */
2492 while (isblank ((unsigned char)*line))
2493 ++line;
2494 if (*line == '\0')
2495 return 0;
2497 /* See if it is safe to parse commands internally. */
2498 if (shell == 0)
2499 shell = default_shell;
2500 #ifdef WINDOWS32
2501 else if (strcmp (shell, default_shell))
2503 char *s1 = _fullpath(NULL, shell, 0);
2504 char *s2 = _fullpath(NULL, default_shell, 0);
2506 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2508 if (s1)
2509 free (s1);
2510 if (s2)
2511 free (s2);
2513 if (slow_flag)
2514 goto slow;
2515 #else /* not WINDOWS32 */
2516 #ifdef __MSDOS__
2517 else if (stricmp (shell, default_shell))
2519 extern int _is_unixy_shell (const char *_path);
2521 message (1, _("$SHELL changed (was `%s', now `%s')"), default_shell, shell);
2522 unixy_shell = _is_unixy_shell (shell);
2523 default_shell = shell;
2525 if (unixy_shell)
2527 sh_chars = sh_chars_sh;
2528 sh_cmds = sh_cmds_sh;
2530 else
2532 sh_chars = sh_chars_dos;
2533 sh_cmds = sh_cmds_dos;
2535 #else /* not __MSDOS__ */
2536 else if (strcmp (shell, default_shell))
2537 goto slow;
2538 #endif /* not __MSDOS__ */
2539 #endif /* not WINDOWS32 */
2541 if (ifs != 0)
2542 for (ap = ifs; *ap != '\0'; ++ap)
2543 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2544 goto slow;
2546 i = strlen (line) + 1;
2548 /* More than 1 arg per character is impossible. */
2549 new_argv = (char **) xmalloc (i * sizeof (char *));
2551 /* All the args can fit in a buffer as big as LINE is. */
2552 ap = new_argv[0] = (char *) xmalloc (i);
2553 end = ap + i;
2555 /* I is how many complete arguments have been found. */
2556 i = 0;
2557 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2558 for (p = line; *p != '\0'; ++p)
2560 if (ap > end)
2561 abort ();
2563 if (instring)
2565 string_char:
2566 /* Inside a string, just copy any char except a closing quote
2567 or a backslash-newline combination. */
2568 if (*p == instring)
2570 instring = 0;
2571 if (ap == new_argv[0] || *(ap-1) == '\0')
2572 last_argument_was_empty = 1;
2574 else if (*p == '\\' && p[1] == '\n')
2575 goto swallow_escaped_newline;
2576 else if (*p == '\n' && restp != NULL)
2578 /* End of the command line. */
2579 *restp = p;
2580 goto end_of_line;
2582 /* Backslash, $, and ` are special inside double quotes.
2583 If we see any of those, punt.
2584 But on MSDOS, if we use COMMAND.COM, double and single
2585 quotes have the same effect. */
2586 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2587 goto slow;
2588 else
2589 *ap++ = *p;
2591 else if (strchr (sh_chars, *p) != 0)
2592 /* Not inside a string, but it's a special char. */
2593 goto slow;
2594 #ifdef __MSDOS__
2595 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2596 /* `...' is a wildcard in DJGPP. */
2597 goto slow;
2598 #endif
2599 else
2600 /* Not a special char. */
2601 switch (*p)
2603 case '=':
2604 /* Equals is a special character in leading words before the
2605 first word with no equals sign in it. This is not the case
2606 with sh -k, but we never get here when using nonstandard
2607 shell flags. */
2608 if (! seen_nonequals && unixy_shell)
2609 goto slow;
2610 word_has_equals = 1;
2611 *ap++ = '=';
2612 break;
2614 case '\\':
2615 /* Backslash-newline combinations are eaten. */
2616 if (p[1] == '\n')
2618 swallow_escaped_newline:
2620 /* Eat the backslash, the newline, and following whitespace,
2621 replacing it all with a single space. */
2622 p += 2;
2624 /* If there is a tab after a backslash-newline,
2625 remove it from the source line which will be echoed,
2626 since it was most likely used to line
2627 up the continued line with the previous one. */
2628 if (*p == '\t')
2629 /* Note these overlap and strcpy() is undefined for
2630 overlapping objects in ANSI C. The strlen() _IS_ right,
2631 since we need to copy the nul byte too. */
2632 bcopy (p + 1, p, strlen (p));
2634 if (instring)
2635 goto string_char;
2636 else
2638 if (ap != new_argv[i])
2639 /* Treat this as a space, ending the arg.
2640 But if it's at the beginning of the arg, it should
2641 just get eaten, rather than becoming an empty arg. */
2642 goto end_of_arg;
2643 else
2644 p = next_token (p) - 1;
2647 else if (p[1] != '\0')
2649 #ifdef HAVE_DOS_PATHS
2650 /* Only remove backslashes before characters special
2651 to Unixy shells. All other backslashes are copied
2652 verbatim, since they are probably DOS-style
2653 directory separators. This still leaves a small
2654 window for problems, but at least it should work
2655 for the vast majority of naive users. */
2657 #ifdef __MSDOS__
2658 /* A dot is only special as part of the "..."
2659 wildcard. */
2660 if (strneq (p + 1, ".\\.\\.", 5))
2662 *ap++ = '.';
2663 *ap++ = '.';
2664 p += 4;
2666 else
2667 #endif
2668 if (p[1] != '\\' && p[1] != '\''
2669 && !isspace ((unsigned char)p[1])
2670 && (strchr (sh_chars_sh, p[1]) == 0))
2671 /* back up one notch, to copy the backslash */
2672 --p;
2673 #endif /* HAVE_DOS_PATHS */
2675 /* Copy and skip the following char. */
2676 *ap++ = *++p;
2678 break;
2680 case '\'':
2681 case '"':
2682 instring = *p;
2683 break;
2685 case '\n':
2686 if (restp != NULL)
2688 /* End of the command line. */
2689 *restp = p;
2690 goto end_of_line;
2692 else
2693 /* Newlines are not special. */
2694 *ap++ = '\n';
2695 break;
2697 case ' ':
2698 case '\t':
2699 end_of_arg:
2700 /* We have the end of an argument.
2701 Terminate the text of the argument. */
2702 *ap++ = '\0';
2703 new_argv[++i] = ap;
2704 last_argument_was_empty = 0;
2706 /* Update SEEN_NONEQUALS, which tells us if every word
2707 heretofore has contained an `='. */
2708 seen_nonequals |= ! word_has_equals;
2709 if (word_has_equals && ! seen_nonequals)
2710 /* An `=' in a word before the first
2711 word without one is magical. */
2712 goto slow;
2713 word_has_equals = 0; /* Prepare for the next word. */
2715 /* If this argument is the command name,
2716 see if it is a built-in shell command.
2717 If so, have the shell handle it. */
2718 if (i == 1)
2720 register int j;
2721 for (j = 0; sh_cmds[j] != 0; ++j)
2722 if (streq (sh_cmds[j], new_argv[0]))
2723 goto slow;
2726 /* Ignore multiple whitespace chars. */
2727 p = next_token (p);
2728 /* Next iteration should examine the first nonwhite char. */
2729 --p;
2730 break;
2732 default:
2733 *ap++ = *p;
2734 break;
2737 end_of_line:
2739 if (instring)
2740 /* Let the shell deal with an unterminated quote. */
2741 goto slow;
2743 /* Terminate the last argument and the argument list. */
2745 *ap = '\0';
2746 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2747 ++i;
2748 new_argv[i] = 0;
2750 if (i == 1)
2752 register int j;
2753 for (j = 0; sh_cmds[j] != 0; ++j)
2754 if (streq (sh_cmds[j], new_argv[0]))
2755 goto slow;
2758 if (new_argv[0] == 0)
2759 /* Line was empty. */
2760 return 0;
2761 else
2762 return new_argv;
2764 slow:;
2765 /* We must use the shell. */
2767 if (new_argv != 0)
2769 /* Free the old argument list we were working on. */
2770 free (new_argv[0]);
2771 free ((void *)new_argv);
2774 #ifdef __MSDOS__
2775 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2776 #endif
2778 #ifdef _AMIGA
2780 char *ptr;
2781 char *buffer;
2782 char *dptr;
2784 buffer = (char *)xmalloc (strlen (line)+1);
2786 ptr = line;
2787 for (dptr=buffer; *ptr; )
2789 if (*ptr == '\\' && ptr[1] == '\n')
2790 ptr += 2;
2791 else if (*ptr == '@') /* Kludge: multiline commands */
2793 ptr += 2;
2794 *dptr++ = '\n';
2796 else
2797 *dptr++ = *ptr++;
2799 *dptr = 0;
2801 new_argv = (char **) xmalloc (2 * sizeof (char *));
2802 new_argv[0] = buffer;
2803 new_argv[1] = 0;
2805 #else /* Not Amiga */
2806 #ifdef WINDOWS32
2808 * Not eating this whitespace caused things like
2810 * sh -c "\n"
2812 * which gave the shell fits. I think we have to eat
2813 * whitespace here, but this code should be considered
2814 * suspicious if things start failing....
2817 /* Make sure not to bother processing an empty line. */
2818 while (isspace ((unsigned char)*line))
2819 ++line;
2820 if (*line == '\0')
2821 return 0;
2822 #endif /* WINDOWS32 */
2824 /* SHELL may be a multi-word command. Construct a command line
2825 "SHELL -c LINE", with all special chars in LINE escaped.
2826 Then recurse, expanding this command line to get the final
2827 argument list. */
2829 unsigned int shell_len = strlen (shell);
2830 #ifndef VMS
2831 static char minus_c[] = " -c ";
2832 #else
2833 static char minus_c[] = "";
2834 #endif
2835 unsigned int line_len = strlen (line);
2837 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2838 + (line_len * 2) + 1);
2839 char *command_ptr = NULL; /* used for batch_mode_shell mode */
2841 ap = new_line;
2842 bcopy (shell, ap, shell_len);
2843 ap += shell_len;
2844 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2845 ap += sizeof (minus_c) - 1;
2846 command_ptr = ap;
2847 for (p = line; *p != '\0'; ++p)
2849 if (restp != NULL && *p == '\n')
2851 *restp = p;
2852 break;
2854 else if (*p == '\\' && p[1] == '\n')
2856 /* Eat the backslash, the newline, and following whitespace,
2857 replacing it all with a single space (which is escaped
2858 from the shell). */
2859 p += 2;
2861 /* If there is a tab after a backslash-newline,
2862 remove it from the source line which will be echoed,
2863 since it was most likely used to line
2864 up the continued line with the previous one. */
2865 if (*p == '\t')
2866 bcopy (p + 1, p, strlen (p));
2868 p = next_token (p);
2869 --p;
2870 if (unixy_shell && !batch_mode_shell)
2871 *ap++ = '\\';
2872 *ap++ = ' ';
2873 continue;
2876 /* DOS shells don't know about backslash-escaping. */
2877 if (unixy_shell && !batch_mode_shell &&
2878 (*p == '\\' || *p == '\'' || *p == '"'
2879 || isspace ((unsigned char)*p)
2880 || strchr (sh_chars, *p) != 0))
2881 *ap++ = '\\';
2882 #ifdef __MSDOS__
2883 else if (unixy_shell && strneq (p, "...", 3))
2885 /* The case of `...' wildcard again. */
2886 strcpy (ap, "\\.\\.\\");
2887 ap += 5;
2888 p += 2;
2890 #endif
2891 *ap++ = *p;
2893 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2894 /* Line was empty. */
2895 return 0;
2896 *ap = '\0';
2898 #ifdef WINDOWS32
2899 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2900 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2901 cases, run commands via a script file. */
2902 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2903 FILE* batch = NULL;
2904 int id = GetCurrentProcessId();
2905 PATH_VAR(fbuf);
2906 char* fname = NULL;
2908 /* create a file name */
2909 sprintf(fbuf, "make%d", id);
2910 fname = tempnam(".", fbuf);
2912 /* create batch file name */
2913 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
2914 strcpy(*batch_filename_ptr, fname);
2916 /* make sure path name is in DOS backslash format */
2917 if (!unixy_shell) {
2918 fname = *batch_filename_ptr;
2919 for (i = 0; fname[i] != '\0'; ++i)
2920 if (fname[i] == '/')
2921 fname[i] = '\\';
2922 strcat(*batch_filename_ptr, ".bat");
2923 } else {
2924 strcat(*batch_filename_ptr, ".sh");
2927 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
2928 *batch_filename_ptr));
2930 /* create batch file to execute command */
2931 batch = fopen (*batch_filename_ptr, "w");
2932 if (!unixy_shell)
2933 fputs ("@echo off\n", batch);
2934 fputs (command_ptr, batch);
2935 fputc ('\n', batch);
2936 fclose (batch);
2938 /* create argv */
2939 new_argv = (char **) xmalloc(3 * sizeof (char *));
2940 if (unixy_shell) {
2941 new_argv[0] = xstrdup (shell);
2942 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2943 } else {
2944 new_argv[0] = xstrdup (*batch_filename_ptr);
2945 new_argv[1] = NULL;
2947 new_argv[2] = NULL;
2948 } else
2949 #endif /* WINDOWS32 */
2950 if (unixy_shell)
2951 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2952 (char *) 0, (char *) 0,
2953 (char **) 0);
2954 #ifdef __MSDOS__
2955 else
2957 /* With MSDOS shells, we must construct the command line here
2958 instead of recursively calling ourselves, because we
2959 cannot backslash-escape the special characters (see above). */
2960 new_argv = (char **) xmalloc (sizeof (char *));
2961 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2962 new_argv[0] = xmalloc (line_len + 1);
2963 strncpy (new_argv[0],
2964 new_line + shell_len + sizeof (minus_c) - 1, line_len);
2965 new_argv[0][line_len] = '\0';
2967 #else
2968 else
2969 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2970 __FILE__, __LINE__);
2971 #endif
2973 #endif /* ! AMIGA */
2975 return new_argv;
2977 #endif /* !VMS */
2979 /* Figure out the argument list necessary to run LINE as a command. Try to
2980 avoid using a shell. This routine handles only ' quoting, and " quoting
2981 when no backslash, $ or ` characters are seen in the quotes. Starting
2982 quotes may be escaped with a backslash. If any of the characters in
2983 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2984 is the first word of a line, the shell is used.
2986 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2987 If *RESTP is NULL, newlines will be ignored.
2989 FILE is the target whose commands these are. It is used for
2990 variable expansion for $(SHELL) and $(IFS). */
2992 char **
2993 construct_command_argv (char *line, char **restp, struct file *file,
2994 char **batch_filename_ptr)
2996 char *shell, *ifs;
2997 char **argv;
2999 #ifdef VMS
3000 char *cptr;
3001 int argc;
3003 argc = 0;
3004 cptr = line;
3005 for (;;)
3007 while ((*cptr != 0)
3008 && (isspace ((unsigned char)*cptr)))
3009 cptr++;
3010 if (*cptr == 0)
3011 break;
3012 while ((*cptr != 0)
3013 && (!isspace((unsigned char)*cptr)))
3014 cptr++;
3015 argc++;
3018 argv = (char **)malloc (argc * sizeof (char *));
3019 if (argv == 0)
3020 abort ();
3022 cptr = line;
3023 argc = 0;
3024 for (;;)
3026 while ((*cptr != 0)
3027 && (isspace ((unsigned char)*cptr)))
3028 cptr++;
3029 if (*cptr == 0)
3030 break;
3031 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3032 argv[argc++] = cptr;
3033 while ((*cptr != 0)
3034 && (!isspace((unsigned char)*cptr)))
3035 cptr++;
3036 if (*cptr != 0)
3037 *cptr++ = 0;
3039 #else
3041 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3042 int save = warn_undefined_variables_flag;
3043 warn_undefined_variables_flag = 0;
3045 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3046 #ifdef WINDOWS32
3048 * Convert to forward slashes so that construct_command_argv_internal()
3049 * is not confused.
3051 if (shell) {
3052 char *p = w32ify(shell, 0);
3053 strcpy(shell, p);
3055 #endif
3056 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3058 warn_undefined_variables_flag = save;
3061 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
3063 free (shell);
3064 free (ifs);
3065 #endif /* !VMS */
3066 return argv;
3069 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3071 dup2 (int old, int new)
3073 int fd;
3075 (void) close (new);
3076 fd = dup (old);
3077 if (fd != new)
3079 (void) close (fd);
3080 errno = EMFILE;
3081 return -1;
3084 return fd;
3086 #endif /* !HAPE_DUP2 && !_AMIGA */