.
[make.git] / job.c
blob5173dfbd43efb807e91b092dfa51154a36bfa9a9
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988, 89, 90, 91, 92, 93, 94, 1995 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, 675 Mass Ave, Cambridge, MA 02139, USA. */
19 #include "make.h"
20 #include "commands.h"
21 #include "job.h"
22 #include "file.h"
23 #include "variable.h"
24 #include <assert.h>
26 /* Default shell to use. */
27 char default_shell[] = "/bin/sh";
29 #ifdef __MSDOS__
30 #include <process.h>
31 static int dos_pid = 123;
32 static int dos_status;
33 static char *dos_bname;
34 static char *dos_bename;
35 static int dos_batch_file;
36 #endif /* MSDOS. */
38 #ifdef HAVE_FCNTL_H
39 #include <fcntl.h>
40 #else
41 #include <sys/file.h>
42 #endif
45 /* If NGROUPS_MAX == 0 then try other methods for finding a real value. */
46 #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0
47 #undef NGROUPS_MAX
48 #endif /* NGROUPS_MAX == 0 */
50 #ifndef NGROUPS_MAX
51 #ifdef POSIX
52 #define GET_NGROUPS_MAX sysconf (_SC_NGROUPS_MAX)
53 #else /* Not POSIX. */
54 #define NGROUPS_MAX NGROUPS
55 #endif /* POSIX. */
56 #endif
58 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
59 #include <sys/wait.h>
60 #endif
62 #ifdef HAVE_WAITPID
63 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
64 #else /* Don't have waitpid. */
65 #ifdef HAVE_WAIT3
66 #ifndef wait3
67 extern int wait3 ();
68 #endif
69 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
70 #endif /* Have wait3. */
71 #endif /* Have waitpid. */
73 #if !defined (wait) && !defined (POSIX)
74 extern int wait ();
75 #endif
77 #ifndef HAVE_UNION_WAIT
79 #define WAIT_T int
81 #ifndef WTERMSIG
82 #define WTERMSIG(x) ((x) & 0x7f)
83 #endif
84 #ifndef WCOREDUMP
85 #define WCOREDUMP(x) ((x) & 0x80)
86 #endif
87 #ifndef WEXITSTATUS
88 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
89 #endif
90 #ifndef WIFSIGNALED
91 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
92 #endif
93 #ifndef WIFEXITED
94 #define WIFEXITED(x) (WTERMSIG (x) == 0)
95 #endif
97 #else /* Have `union wait'. */
99 #define WAIT_T union wait
100 #ifndef WTERMSIG
101 #define WTERMSIG(x) ((x).w_termsig)
102 #endif
103 #ifndef WCOREDUMP
104 #define WCOREDUMP(x) ((x).w_coredump)
105 #endif
106 #ifndef WEXITSTATUS
107 #define WEXITSTATUS(x) ((x).w_retcode)
108 #endif
109 #ifndef WIFSIGNALED
110 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
111 #endif
112 #ifndef WIFEXITED
113 #define WIFEXITED(x) (WTERMSIG(x) == 0)
114 #endif
116 #endif /* Don't have `union wait'. */
119 #ifndef HAVE_UNISTD_H
120 extern int dup2 ();
121 extern int execve ();
122 extern void _exit ();
123 extern int geteuid (), getegid ();
124 extern int setgid (), getgid ();
125 #endif
127 extern int getloadavg ();
128 extern int start_remote_job_p ();
129 extern int start_remote_job (), remote_status ();
131 RETSIGTYPE child_handler ();
132 static void free_child (), start_job_command ();
133 static int load_too_high (), job_next_command ();
135 /* Chain of all live (or recently deceased) children. */
137 struct child *children = 0;
139 /* Number of children currently running. */
141 unsigned int job_slots_used = 0;
143 /* Nonzero if the `good' standard input is in use. */
145 static int good_stdin_used = 0;
147 /* Chain of children waiting to run until the load average goes down. */
149 static struct child *waiting_jobs = 0;
151 /* Write an error message describing the exit status given in
152 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
153 Append "(ignored)" if IGNORED is nonzero. */
155 static void
156 child_error (target_name, exit_code, exit_sig, coredump, ignored)
157 char *target_name;
158 int exit_code, exit_sig, coredump;
159 int ignored;
161 if (ignored && silent_flag)
162 return;
164 if (exit_sig == 0)
165 error (ignored ? "[%s] Error %d (ignored)" :
166 "*** [%s] Error %d",
167 target_name, exit_code);
168 else
169 error ("*** [%s] %s%s",
170 target_name, strsignal (exit_sig),
171 coredump ? " (core dumped)" : "");
174 static unsigned int dead_children = 0;
176 /* Notice that a child died.
177 reap_children should be called when convenient. */
178 RETSIGTYPE
179 child_handler (sig)
180 int sig;
182 ++dead_children;
184 if (debug_flag)
185 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
188 extern int shell_function_pid, shell_function_completed;
190 /* Reap dead children, storing the returned status and the new command
191 state (`cs_finished') in the `file' member of the `struct child' for the
192 dead child, and removing the child from the chain. If BLOCK nonzero,
193 reap at least one child, waiting for it to die if necessary. If ERR is
194 nonzero, print an error message first. */
196 void
197 reap_children (block, err)
198 int block, err;
200 WAIT_T status;
202 while ((children != 0 || shell_function_pid != 0) &&
203 (block || dead_children > 0))
205 int remote = 0;
206 register int pid;
207 int exit_code, exit_sig, coredump;
208 register struct child *lastc, *c;
209 int child_failed;
210 int any_remote, any_local;
212 if (err && dead_children == 0)
214 /* We might block for a while, so let the user know why. */
215 fflush (stdout);
216 error ("*** Waiting for unfinished jobs....");
219 /* We have one less dead child to reap.
220 The test and decrement are not atomic; if it is compiled into:
221 register = dead_children - 1;
222 dead_children = register;
223 a SIGCHLD could come between the two instructions.
224 child_handler increments dead_children.
225 The second instruction here would lose that increment. But the
226 only effect of dead_children being wrong is that we might wait
227 longer than necessary to reap a child, and lose some parallelism;
228 and we might print the "Waiting for unfinished jobs" message above
229 when not necessary. */
231 if (dead_children != 0)
232 --dead_children;
234 any_remote = 0;
235 any_local = shell_function_pid != -1;
236 for (c = children; c != 0; c = c->next)
238 any_remote |= c->remote;
239 any_local |= ! c->remote;
240 if (debug_flag)
241 printf ("Live child 0x%08lx PID %d%s\n",
242 (unsigned long int) c,
243 c->pid, c->remote ? " (remote)" : "");
246 /* First, check for remote children. */
247 if (any_remote)
248 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
249 else
250 pid = 0;
251 if (pid < 0)
253 remote_status_lose:
254 #ifdef EINTR
255 if (errno == EINTR)
256 continue;
257 #endif
258 pfatal_with_name ("remote_status");
260 else if (pid == 0)
262 #ifndef __MSDOS__
263 /* No remote children. Check for local children. */
265 if (any_local)
267 #ifdef WAIT_NOHANG
268 if (!block)
269 pid = WAIT_NOHANG (&status);
270 else
271 #endif
272 pid = wait (&status);
274 else
275 pid = 0;
277 if (pid < 0)
279 #ifdef EINTR
280 if (errno == EINTR)
281 continue;
282 #endif
283 pfatal_with_name ("wait");
285 else if (pid == 0)
287 /* No local children. */
288 if (block && any_remote)
290 /* Now try a blocking wait for a remote child. */
291 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
292 if (pid < 0)
293 goto remote_status_lose;
294 else if (pid == 0)
295 /* No remote children either. Finally give up. */
296 break;
297 else
298 /* We got a remote child. */
299 remote = 1;
301 else
302 break;
304 else
306 /* Chop the status word up. */
307 exit_code = WEXITSTATUS (status);
308 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
309 coredump = WCOREDUMP (status);
311 #else /* MSDOS. */
312 /* Life is very different on MSDOS. */
313 pid = dos_pid - 1;
314 status = dos_status;
315 exit_code = dos_status;
316 exit_sig = 0;
317 coredump = 0;
318 #endif /* Not MSDOS. */
320 else
321 /* We got a remote child. */
322 remote = 1;
324 /* Check if this is the child of the `shell' function. */
325 if (!remote && pid == shell_function_pid)
327 /* It is. Leave an indicator for the `shell' function. */
328 if (exit_sig == 0 && exit_code == 127)
329 shell_function_completed = -1;
330 else
331 shell_function_completed = 1;
332 break;
335 child_failed = exit_sig != 0 || exit_code != 0;
337 /* Search for a child matching the deceased one. */
338 lastc = 0;
339 for (c = children; c != 0; lastc = c, c = c->next)
340 if (c->remote == remote && c->pid == pid)
341 break;
343 if (c == 0)
345 /* An unknown child died. */
346 char buf[100];
347 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
348 if (child_failed)
349 child_error (buf, exit_code, exit_sig, coredump,
350 ignore_errors_flag);
351 else
352 error ("%s finished.", buf);
354 else
356 if (debug_flag)
357 printf ("Reaping %s child 0x%08lx PID %d%s\n",
358 child_failed ? "losing" : "winning",
359 (unsigned long int) c,
360 c->pid, c->remote ? " (remote)" : "");
362 /* If this child had the good stdin, say it is now free. */
363 if (c->good_stdin)
364 good_stdin_used = 0;
366 if (child_failed && !c->noerror && !ignore_errors_flag)
368 /* The commands failed. Write an error message,
369 delete non-precious targets, and abort. */
370 static int delete_on_error = -1;
371 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
372 c->file->update_status = 2;
373 if (delete_on_error == -1)
375 struct file *f = lookup_file (".DELETE_ON_ERROR");
376 delete_on_error = f != 0 && f->is_target;
378 if (exit_sig != 0 || delete_on_error)
379 delete_child_targets (c);
381 else
383 if (child_failed)
385 /* The commands failed, but we don't care. */
386 child_error (c->file->name,
387 exit_code, exit_sig, coredump, 1);
388 child_failed = 0;
391 /* If there are more commands to run, try to start them. */
392 if (job_next_command (c))
394 if (handling_fatal_signal)
396 /* Never start new commands while we are dying.
397 Since there are more commands that wanted to be run,
398 the target was not completely remade. So we treat
399 this as if a command had failed. */
400 c->file->update_status = 2;
402 else
404 /* Check again whether to start remotely.
405 Whether or not we want to changes over time.
406 Also, start_remote_job may need state set up
407 by start_remote_job_p. */
408 c->remote = start_remote_job_p ();
409 start_job_command (c);
410 if (c->file->command_state == cs_running)
411 /* We successfully started the new command.
412 Loop to reap more children. */
413 continue;
416 if (c->file->update_status != 0)
417 /* We failed to start the commands. */
418 delete_child_targets (c);
420 else
421 /* There are no more commands. We got through them all
422 without an unignored error. Now the target has been
423 successfully updated. */
424 c->file->update_status = 0;
427 /* When we get here, all the commands for C->file are finished
428 (or aborted) and C->file->update_status contains 0 or 2. But
429 C->file->command_state is still cs_running if all the commands
430 ran; notice_finish_file looks for cs_running to tell it that
431 it's interesting to check the file's modtime again now. */
433 if (! handling_fatal_signal)
434 /* Notice if the target of the commands has been changed.
435 This also propagates its values for command_state and
436 update_status to its also_make files. */
437 notice_finished_file (c->file);
439 if (debug_flag)
440 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
441 (unsigned long int) c,
442 c->pid, c->remote ? " (remote)" : "");
444 /* Remove the child from the chain and free it. */
445 if (lastc == 0)
446 children = c->next;
447 else
448 lastc->next = c->next;
449 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
450 free_child (c);
452 /* There is now another slot open. */
453 --job_slots_used;
455 /* If the job failed, and the -k flag was not given, die,
456 unless we are already in the process of dying. */
457 if (!err && child_failed && !keep_going_flag)
458 die (2);
461 /* Only block for one child. */
462 block = 0;
466 /* Free the storage allocated for CHILD. */
468 static void
469 free_child (child)
470 register struct child *child;
472 if (child->command_lines != 0)
474 register unsigned int i;
475 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
476 free (child->command_lines[i]);
477 free ((char *) child->command_lines);
480 if (child->environment != 0)
482 register char **ep = child->environment;
483 while (*ep != 0)
484 free (*ep++);
485 free ((char *) child->environment);
488 free ((char *) child);
491 #ifdef POSIX
492 #ifdef __MSDOS__
493 void
494 unblock_sigs ()
496 return;
498 #else
499 extern sigset_t fatal_signal_set;
501 void
502 unblock_sigs ()
504 sigset_t empty;
505 sigemptyset (&empty);
506 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
508 #endif
509 #endif
511 /* Start a job to run the commands specified in CHILD.
512 CHILD is updated to reflect the commands and ID of the child process. */
514 static void
515 start_job_command (child)
516 register struct child *child;
518 static int bad_stdin = -1;
519 register char *p;
520 int flags;
521 char **argv;
523 /* Combine the flags parsed for the line itself with
524 the flags specified globally for this target. */
525 flags = (child->file->command_flags
526 | child->file->cmds->lines_flags[child->command_line - 1]);
528 p = child->command_ptr;
529 child->noerror = flags & COMMANDS_NOERROR;
530 while (*p != '\0')
532 if (*p == '@')
533 flags |= COMMANDS_SILENT;
534 else if (*p == '+')
535 flags |= COMMANDS_RECURSE;
536 else if (*p == '-')
537 child->noerror = 1;
538 else if (!isblank (*p) && *p != '+')
539 break;
540 ++p;
543 /* If -q was given, just say that updating `failed'. The exit status of
544 1 tells the user that -q is saying `something to do'; the exit status
545 for a random error is 2. */
546 if (question_flag && !(flags & COMMANDS_RECURSE))
548 child->file->update_status = 1;
549 notice_finished_file (child->file);
550 return;
553 /* There may be some preceding whitespace left if there
554 was nothing but a backslash on the first line. */
555 p = next_token (p);
557 /* Figure out an argument list from this command line. */
560 char *end;
561 argv = construct_command_argv (p, &end, child->file);
562 if (end == NULL)
563 child->command_ptr = NULL;
564 else
566 *end++ = '\0';
567 child->command_ptr = end;
571 if (touch_flag && !(flags & COMMANDS_RECURSE))
573 /* Go on to the next command. It might be the recursive one.
574 We construct ARGV only to find the end of the command line. */
575 free (argv[0]);
576 free ((char *) argv);
577 argv = 0;
580 if (argv == 0)
582 next_command:
583 /* This line has no commands. Go to the next. */
584 if (job_next_command (child))
585 start_job_command (child);
586 else
588 /* No more commands. All done. */
589 child->file->update_status = 0;
590 notice_finished_file (child->file);
592 return;
595 /* Print out the command. If silent, we call `message' with null so it
596 can log the working directory before the command's own error messages
597 appear. */
599 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
600 ? "%s" : (char *) 0, p);
602 /* Tell update_goal_chain that a command has been started on behalf of
603 this target. It is important that this happens here and not in
604 reap_children (where we used to do it), because reap_children might be
605 reaping children from a different target. We want this increment to
606 guaranteedly indicate that a command was started for the dependency
607 chain (i.e., update_file recursion chain) we are processing. */
609 ++commands_started;
611 /* If -n was given, recurse to get the next line in the sequence. */
613 if (just_print_flag && !(flags & COMMANDS_RECURSE))
615 free (argv[0]);
616 free ((char *) argv);
617 goto next_command;
620 /* Flush the output streams so they won't have things written twice. */
622 fflush (stdout);
623 fflush (stderr);
625 /* Set up a bad standard input that reads from a broken pipe. */
627 if (bad_stdin == -1)
629 /* Make a file descriptor that is the read end of a broken pipe.
630 This will be used for some children's standard inputs. */
631 int pd[2];
632 if (pipe (pd) == 0)
634 /* Close the write side. */
635 (void) close (pd[1]);
636 /* Save the read side. */
637 bad_stdin = pd[0];
639 /* Set the descriptor to close on exec, so it does not litter any
640 child's descriptor table. When it is dup2'd onto descriptor 0,
641 that descriptor will not close on exec. */
642 #ifdef FD_SETFD
643 #ifndef FD_CLOEXEC
644 #define FD_CLOEXEC 1
645 #endif
646 (void) fcntl (bad_stdin, F_SETFD, FD_CLOEXEC);
647 #endif
651 /* Decide whether to give this child the `good' standard input
652 (one that points to the terminal or whatever), or the `bad' one
653 that points to the read side of a broken pipe. */
655 child->good_stdin = !good_stdin_used;
656 if (child->good_stdin)
657 good_stdin_used = 1;
659 child->deleted = 0;
661 /* Set up the environment for the child. */
662 if (child->environment == 0)
663 child->environment = target_environment (child->file);
665 #ifndef __MSDOS__
667 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
668 if (child->remote)
670 int is_remote, id, used_stdin;
671 if (start_remote_job (argv, child->environment,
672 child->good_stdin ? 0 : bad_stdin,
673 &is_remote, &id, &used_stdin))
674 goto error;
675 else
677 if (child->good_stdin && !used_stdin)
679 child->good_stdin = 0;
680 good_stdin_used = 0;
682 child->remote = is_remote;
683 child->pid = id;
686 else
688 /* Fork the child process. */
690 char **parent_environ;
692 #ifdef POSIX
693 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
694 #else
695 #ifdef HAVE_SIGSETMASK
696 (void) sigblock (fatal_signal_mask);
697 #endif
698 #endif
700 child->remote = 0;
701 parent_environ = environ;
702 child->pid = vfork ();
703 environ = parent_environ; /* Restore value child may have clobbered. */
704 if (child->pid == 0)
706 /* We are the child side. */
707 unblock_sigs ();
708 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
709 argv, child->environment);
711 else if (child->pid < 0)
713 /* Fork failed! */
714 unblock_sigs ();
715 perror_with_name ("vfork", "");
716 goto error;
720 #else /* MSDOS. */
721 dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
722 ++dead_children;
723 child->pid = dos_pid++;
724 if (dos_batch_file)
726 dos_batch_file = 0;
727 remove (dos_bname); /* Ignore errors. */
728 if (access (dos_bename, 0))
729 dos_status = 1;
730 else
731 dos_status = 0;
732 remove (dos_bename);
734 #endif /* Not MSDOS. */
736 /* We are the parent side. Set the state to
737 say the commands are running and return. */
739 set_command_state (child->file, cs_running);
741 /* Free the storage used by the child's argument list. */
743 free (argv[0]);
744 free ((char *) argv);
746 return;
748 error:
749 child->file->update_status = 2;
750 notice_finished_file (child->file);
753 /* Try to start a child running.
754 Returns nonzero if the child was started (and maybe finished), or zero if
755 the load was too high and the child was put on the `waiting_jobs' chain. */
757 static int
758 start_waiting_job (c)
759 struct child *c;
761 /* If we can start a job remotely, we always want to, and don't care about
762 the local load average. We record that the job should be started
763 remotely in C->remote for start_job_command to test. */
765 c->remote = start_remote_job_p ();
767 /* If this job is to be started locally, and we are already running
768 some jobs, make this one wait if the load average is too high. */
769 if (!c->remote && job_slots_used > 0 && load_too_high ())
771 /* Put this child on the chain of children waiting
772 for the load average to go down. */
773 set_command_state (c->file, cs_running);
774 c->next = waiting_jobs;
775 waiting_jobs = c;
776 return 0;
779 /* Start the first command; reap_children will run later command lines. */
780 start_job_command (c);
782 switch (c->file->command_state)
784 case cs_running:
785 c->next = children;
786 if (debug_flag)
787 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
788 (unsigned long int) c,
789 c->pid, c->remote ? " (remote)" : "");
790 children = c;
791 /* One more job slot is in use. */
792 ++job_slots_used;
793 unblock_sigs ();
794 break;
796 case cs_not_started:
797 /* All the command lines turned out to be empty. */
798 c->file->update_status = 0;
799 /* FALLTHROUGH */
801 case cs_finished:
802 notice_finished_file (c->file);
803 free_child (c);
804 break;
806 default:
807 assert (c->file->command_state == cs_finished);
808 break;
811 return 1;
814 /* Create a `struct child' for FILE and start its commands running. */
816 void
817 new_job (file)
818 register struct file *file;
820 register struct commands *cmds = file->cmds;
821 register struct child *c;
822 char **lines;
823 register unsigned int i;
825 /* Let any previously decided-upon jobs that are waiting
826 for the load to go down start before this new one. */
827 start_waiting_jobs ();
829 /* Reap any children that might have finished recently. */
830 reap_children (0, 0);
832 /* Chop the commands up into lines if they aren't already. */
833 chop_commands (cmds);
835 if (job_slots != 0)
836 /* Wait for a job slot to be freed up. */
837 while (job_slots_used == job_slots)
838 reap_children (1, 0);
840 /* Expand the command lines and store the results in LINES. */
841 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
842 for (i = 0; i < cmds->ncommand_lines; ++i)
844 /* Collapse backslash-newline combinations that are inside variable
845 or function references. These are left alone by the parser so
846 that they will appear in the echoing of commands (where they look
847 nice); and collapsed by construct_command_argv when it tokenizes.
848 But letting them survive inside function invocations loses because
849 we don't want the functions to see them as part of the text. */
851 char *in, *out, *ref;
853 /* IN points to where in the line we are scanning.
854 OUT points to where in the line we are writing.
855 When we collapse a backslash-newline combination,
856 IN gets ahead out OUT. */
858 in = out = cmds->command_lines[i];
859 while ((ref = index (in, '$')) != 0)
861 ++ref; /* Move past the $. */
863 if (out != in)
864 /* Copy the text between the end of the last chunk
865 we processed (where IN points) and the new chunk
866 we are about to process (where REF points). */
867 bcopy (in, out, ref - in);
869 /* Move both pointers past the boring stuff. */
870 out += ref - in;
871 in = ref;
873 if (*ref == '(' || *ref == '{')
875 char openparen = *ref;
876 char closeparen = openparen == '(' ? ')' : '}';
877 int count;
878 char *p;
880 *out++ = *in++; /* Copy OPENPAREN. */
881 /* IN now points past the opening paren or brace.
882 Count parens or braces until it is matched. */
883 count = 0;
884 while (*in != '\0')
886 if (*in == closeparen && --count < 0)
887 break;
888 else if (*in == '\\' && in[1] == '\n')
890 /* We have found a backslash-newline inside a
891 variable or function reference. Eat it and
892 any following whitespace. */
894 int quoted = 0;
895 for (p = in - 1; p > ref && *p == '\\'; --p)
896 quoted = !quoted;
898 if (quoted)
899 /* There were two or more backslashes, so this is
900 not really a continuation line. We don't collapse
901 the quoting backslashes here as is done in
902 collapse_continuations, because the line will
903 be collapsed again after expansion. */
904 *out++ = *in++;
905 else
907 /* Skip the backslash, newline and
908 any following whitespace. */
909 in = next_token (in + 2);
911 /* Discard any preceding whitespace that has
912 already been written to the output. */
913 while (out > ref && isblank (out[-1]))
914 --out;
916 /* Replace it all with a single space. */
917 *out++ = ' ';
920 else
922 if (*in == openparen)
923 ++count;
925 *out++ = *in++;
931 /* There are no more references in this line to worry about.
932 Copy the remaining uninteresting text to the output. */
933 if (out != in)
934 strcpy (out, in);
936 /* Finally, expand the line. */
937 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
938 file);
941 /* Start the command sequence, record it in a new
942 `struct child', and add that to the chain. */
944 c = (struct child *) xmalloc (sizeof (struct child));
945 c->file = file;
946 c->command_lines = lines;
947 c->command_line = 0;
948 c->command_ptr = 0;
949 c->environment = 0;
951 /* Fetch the first command line to be run. */
952 job_next_command (c);
954 /* The job is now primed. Start it running.
955 (This will notice if there are in fact no commands.) */
956 start_waiting_job (c);
958 if (job_slots == 1)
959 /* Since there is only one job slot, make things run linearly.
960 Wait for the child to die, setting the state to `cs_finished'. */
961 while (file->command_state == cs_running)
962 reap_children (1, 0);
965 /* Move CHILD's pointers to the next command for it to execute.
966 Returns nonzero if there is another command. */
968 static int
969 job_next_command (child)
970 struct child *child;
972 while (child->command_ptr == 0 || *child->command_ptr == '\0')
974 /* There are no more lines in the expansion of this line. */
975 if (child->command_line == child->file->cmds->ncommand_lines)
977 /* There are no more lines to be expanded. */
978 child->command_ptr = 0;
979 return 0;
981 else
982 /* Get the next line to run. */
983 child->command_ptr = child->command_lines[child->command_line++];
985 return 1;
988 static int
989 load_too_high ()
991 #ifdef __MSDOS__
992 return 1;
993 #else
994 extern int getloadavg ();
995 double load;
997 if (max_load_average < 0)
998 return 0;
1000 make_access ();
1001 if (getloadavg (&load, 1) != 1)
1003 static int lossage = -1;
1004 /* Complain only once for the same error. */
1005 if (lossage == -1 || errno != lossage)
1007 if (errno == 0)
1008 /* An errno value of zero means getloadavg is just unsupported. */
1009 error ("cannot enforce load limits on this operating system");
1010 else
1011 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1013 lossage = errno;
1014 load = 0;
1016 user_access ();
1018 return load >= max_load_average;
1019 #endif
1022 /* Start jobs that are waiting for the load to be lower. */
1024 void
1025 start_waiting_jobs ()
1027 struct child *job;
1029 if (waiting_jobs == 0)
1030 return;
1034 /* Check for recently deceased descendants. */
1035 reap_children (0, 0);
1037 /* Take a job off the waiting list. */
1038 job = waiting_jobs;
1039 waiting_jobs = job->next;
1041 /* Try to start that job. We break out of the loop as soon
1042 as start_waiting_job puts one back on the waiting list. */
1043 } while (start_waiting_job (job) && waiting_jobs != 0);
1046 /* Replace the current process with one executing the command in ARGV.
1047 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1048 the environment of the new program. This function does not return. */
1050 void
1051 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1052 int stdin_fd, stdout_fd;
1053 char **argv, **envp;
1055 if (stdin_fd != 0)
1056 (void) dup2 (stdin_fd, 0);
1057 if (stdout_fd != 1)
1058 (void) dup2 (stdout_fd, 1);
1059 if (stdin_fd != 0)
1060 (void) close (stdin_fd);
1061 if (stdout_fd != 1)
1062 (void) close (stdout_fd);
1064 /* Run the command. */
1065 exec_command (argv, envp);
1068 /* Replace the current process with one running the command in ARGV,
1069 with environment ENVP. This function does not return. */
1071 void
1072 exec_command (argv, envp)
1073 char **argv, **envp;
1075 /* Be the user, permanently. */
1076 child_access ();
1078 /* Run the program. */
1079 environ = envp;
1080 execvp (argv[0], argv);
1082 switch (errno)
1084 case ENOENT:
1085 error ("%s: Command not found", argv[0]);
1086 break;
1087 case ENOEXEC:
1089 /* The file is not executable. Try it as a shell script. */
1090 extern char *getenv ();
1091 char *shell;
1092 char **new_argv;
1093 int argc;
1095 shell = getenv ("SHELL");
1096 if (shell == 0)
1097 shell = default_shell;
1099 argc = 1;
1100 while (argv[argc] != 0)
1101 ++argc;
1103 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1104 new_argv[0] = shell;
1105 new_argv[1] = argv[0];
1106 while (argc > 0)
1108 new_argv[1 + argc] = argv[argc];
1109 --argc;
1112 execvp (shell, new_argv);
1113 if (errno == ENOENT)
1114 error ("%s: Shell program not found", shell);
1115 else
1116 perror_with_name ("execvp: ", shell);
1117 break;
1120 default:
1121 perror_with_name ("execvp: ", argv[0]);
1122 break;
1125 _exit (127);
1128 /* Figure out the argument list necessary to run LINE as a command. Try to
1129 avoid using a shell. This routine handles only ' quoting, and " quoting
1130 when no backslash, $ or ` characters are seen in the quotes. Starting
1131 quotes may be escaped with a backslash. If any of the characters in
1132 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1133 is the first word of a line, the shell is used.
1135 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1136 If *RESTP is NULL, newlines will be ignored.
1138 SHELL is the shell to use, or nil to use the default shell.
1139 IFS is the value of $IFS, or nil (meaning the default). */
1141 static char **
1142 construct_command_argv_internal (line, restp, shell, ifs)
1143 char *line, **restp;
1144 char *shell, *ifs;
1146 #ifdef __MSDOS__
1147 static char sh_chars[] = "\"|<>";
1148 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1149 "copy", "ctty", "date", "del", "dir", "echo",
1150 "erase", "exit", "for", "goto", "if", "if", "md",
1151 "mkdir", "path", "pause", "prompt", "rem", "ren",
1152 "rename", "set", "shift", "time", "type",
1153 "ver", "verify", "vol", ":", 0 };
1154 #else
1155 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1156 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1157 "logout", "set", "umask", "wait", "while", "for",
1158 "case", "if", ":", ".", "break", "continue",
1159 "export", "read", "readonly", "shift", "times",
1160 "trap", "switch", 0 };
1161 #endif
1162 register int i;
1163 register char *p;
1164 register char *ap;
1165 char *end;
1166 int instring, word_has_equals, seen_nonequals;
1167 char **new_argv = 0;
1169 if (restp != NULL)
1170 *restp = NULL;
1172 /* Make sure not to bother processing an empty line. */
1173 while (isblank (*line))
1174 ++line;
1175 if (*line == '\0')
1176 return 0;
1178 /* See if it is safe to parse commands internally. */
1179 if (shell == 0)
1180 shell = default_shell;
1181 else if (strcmp (shell, default_shell))
1182 goto slow;
1184 if (ifs != 0)
1185 for (ap = ifs; *ap != '\0'; ++ap)
1186 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1187 goto slow;
1189 i = strlen (line) + 1;
1191 /* More than 1 arg per character is impossible. */
1192 new_argv = (char **) xmalloc (i * sizeof (char *));
1194 /* All the args can fit in a buffer as big as LINE is. */
1195 ap = new_argv[0] = (char *) xmalloc (i);
1196 end = ap + i;
1198 /* I is how many complete arguments have been found. */
1199 i = 0;
1200 instring = word_has_equals = seen_nonequals = 0;
1201 for (p = line; *p != '\0'; ++p)
1203 if (ap > end)
1204 abort ();
1206 if (instring)
1208 string_char:
1209 /* Inside a string, just copy any char except a closing quote
1210 or a backslash-newline combination. */
1211 if (*p == instring)
1212 instring = 0;
1213 else if (*p == '\\' && p[1] == '\n')
1214 goto swallow_escaped_newline;
1215 else if (*p == '\n' && restp != NULL)
1217 /* End of the command line. */
1218 *restp = p;
1219 goto end_of_line;
1221 /* Backslash, $, and ` are special inside double quotes.
1222 If we see any of those, punt. */
1223 else if (instring == '"' && index ("\\$`", *p) != 0)
1224 goto slow;
1225 else
1226 *ap++ = *p;
1228 else if (index (sh_chars, *p) != 0)
1229 /* Not inside a string, but it's a special char. */
1230 goto slow;
1231 else
1232 /* Not a special char. */
1233 switch (*p)
1235 case '=':
1236 /* Equals is a special character in leading words before the
1237 first word with no equals sign in it. This is not the case
1238 with sh -k, but we never get here when using nonstandard
1239 shell flags. */
1240 if (! seen_nonequals)
1241 goto slow;
1242 word_has_equals = 1;
1243 *ap++ = '=';
1244 break;
1246 case '\\':
1247 /* Backslash-newline combinations are eaten. */
1248 if (p[1] == '\n')
1250 swallow_escaped_newline:
1252 /* Eat the backslash, the newline, and following whitespace,
1253 replacing it all with a single space. */
1254 p += 2;
1256 /* If there is a tab after a backslash-newline,
1257 remove it from the source line which will be echoed,
1258 since it was most likely used to line
1259 up the continued line with the previous one. */
1260 if (*p == '\t')
1261 strcpy (p, p + 1);
1263 if (instring)
1264 goto string_char;
1265 else
1267 if (ap != new_argv[i])
1268 /* Treat this as a space, ending the arg.
1269 But if it's at the beginning of the arg, it should
1270 just get eaten, rather than becoming an empty arg. */
1271 goto end_of_arg;
1272 else
1273 p = next_token (p) - 1;
1276 else if (p[1] != '\0')
1277 /* Copy and skip the following char. */
1278 *ap++ = *++p;
1279 break;
1281 case '\'':
1282 case '"':
1283 instring = *p;
1284 break;
1286 case '\n':
1287 if (restp != NULL)
1289 /* End of the command line. */
1290 *restp = p;
1291 goto end_of_line;
1293 else
1294 /* Newlines are not special. */
1295 *ap++ = '\n';
1296 break;
1298 case ' ':
1299 case '\t':
1300 end_of_arg:
1301 /* We have the end of an argument.
1302 Terminate the text of the argument. */
1303 *ap++ = '\0';
1304 new_argv[++i] = ap;
1306 /* Update SEEN_NONEQUALS, which tells us if every word
1307 heretofore has contained an `='. */
1308 seen_nonequals |= ! word_has_equals;
1309 if (word_has_equals && ! seen_nonequals)
1310 /* An `=' in a word before the first
1311 word without one is magical. */
1312 goto slow;
1313 word_has_equals = 0; /* Prepare for the next word. */
1315 /* If this argument is the command name,
1316 see if it is a built-in shell command.
1317 If so, have the shell handle it. */
1318 if (i == 1)
1320 register int j;
1321 for (j = 0; sh_cmds[j] != 0; ++j)
1322 if (streq (sh_cmds[j], new_argv[0]))
1323 goto slow;
1326 /* Ignore multiple whitespace chars. */
1327 p = next_token (p);
1328 /* Next iteration should examine the first nonwhite char. */
1329 --p;
1330 break;
1332 default:
1333 *ap++ = *p;
1334 break;
1337 end_of_line:
1339 if (instring)
1340 /* Let the shell deal with an unterminated quote. */
1341 goto slow;
1343 /* Terminate the last argument and the argument list. */
1345 *ap = '\0';
1346 if (new_argv[i][0] != '\0')
1347 ++i;
1348 new_argv[i] = 0;
1350 if (i == 1)
1352 register int j;
1353 for (j = 0; sh_cmds[j] != 0; ++j)
1354 if (streq (sh_cmds[j], new_argv[0]))
1355 goto slow;
1358 if (new_argv[0] == 0)
1359 /* Line was empty. */
1360 return 0;
1361 else
1362 return new_argv;
1364 slow:;
1365 /* We must use the shell. */
1367 if (new_argv != 0)
1369 /* Free the old argument list we were working on. */
1370 free (new_argv[0]);
1371 free (new_argv);
1374 #ifdef __MSDOS__
1376 FILE *batch;
1377 dos_batch_file = 1;
1378 if (dos_bname == 0)
1380 dos_bname = tempnam (".", "mk");
1381 for (i = 0; dos_bname[i] != '\0'; ++i)
1382 if (dos_bname[i] == '/')
1383 dos_bname[i] = '\\';
1384 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1385 strcpy (dos_bename, dos_bname);
1386 strcat (dos_bname, ".bat");
1387 strcat (dos_bename, ".err");
1389 batch = fopen (dos_bename, "w"); /* Create a file. */
1390 if (batch != NULL)
1391 fclose (batch);
1392 batch = fopen (dos_bname, "w");
1393 fputs ("@echo off\n", batch);
1394 fputs (line, batch);
1395 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1396 fclose (batch);
1397 new_argv = (char **) xmalloc(2 * sizeof(char *));
1398 new_argv[0] = strdup (dos_bname);
1399 new_argv[1] = 0;
1401 #else /* Not MSDOS. */
1403 /* SHELL may be a multi-word command. Construct a command line
1404 "SHELL -c LINE", with all special chars in LINE escaped.
1405 Then recurse, expanding this command line to get the final
1406 argument list. */
1408 unsigned int shell_len = strlen (shell);
1409 static char minus_c[] = " -c ";
1410 unsigned int line_len = strlen (line);
1412 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1413 + (line_len * 2) + 1);
1415 ap = new_line;
1416 bcopy (shell, ap, shell_len);
1417 ap += shell_len;
1418 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1419 ap += sizeof (minus_c) - 1;
1420 for (p = line; *p != '\0'; ++p)
1422 if (restp != NULL && *p == '\n')
1424 *restp = p;
1425 break;
1427 else if (*p == '\\' && p[1] == '\n')
1429 /* Eat the backslash, the newline, and following whitespace,
1430 replacing it all with a single space (which is escaped
1431 from the shell). */
1432 p += 2;
1434 /* If there is a tab after a backslash-newline,
1435 remove it from the source line which will be echoed,
1436 since it was most likely used to line
1437 up the continued line with the previous one. */
1438 if (*p == '\t')
1439 strcpy (p, p + 1);
1441 p = next_token (p);
1442 --p;
1443 *ap++ = '\\';
1444 *ap++ = ' ';
1445 continue;
1448 if (*p == '\\' || *p == '\'' || *p == '"'
1449 || isspace (*p)
1450 || index (sh_chars, *p) != 0)
1451 *ap++ = '\\';
1452 *ap++ = *p;
1454 *ap = '\0';
1456 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1457 (char *) 0, (char *) 0);
1459 #endif /* MSDOS. */
1461 return new_argv;
1464 /* Figure out the argument list necessary to run LINE as a command. Try to
1465 avoid using a shell. This routine handles only ' quoting, and " quoting
1466 when no backslash, $ or ` characters are seen in the quotes. Starting
1467 quotes may be escaped with a backslash. If any of the characters in
1468 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1469 is the first word of a line, the shell is used.
1471 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1472 If *RESTP is NULL, newlines will be ignored.
1474 FILE is the target whose commands these are. It is used for
1475 variable expansion for $(SHELL) and $(IFS). */
1477 char **
1478 construct_command_argv (line, restp, file)
1479 char *line, **restp;
1480 struct file *file;
1482 char *shell, *ifs;
1483 char **argv;
1486 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1487 int save = warn_undefined_variables_flag;
1488 warn_undefined_variables_flag = 0;
1490 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1491 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1493 warn_undefined_variables_flag = save;
1496 argv = construct_command_argv_internal (line, restp, shell, ifs);
1498 free (shell);
1499 free (ifs);
1501 return argv;
1504 #ifndef HAVE_DUP2
1506 dup2 (old, new)
1507 int old, new;
1509 int fd;
1511 (void) close (new);
1512 fd = dup (old);
1513 if (fd != new)
1515 (void) close (fd);
1516 errno = EMFILE;
1517 return -1;
1520 return fd;
1522 #endif