Fix typo in last change.
[make.git] / job.c
blob335c6a10b5a99274a086b6e328f489daae0a1b5e
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988, 89, 90, 91, 92, 93, 94 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"
25 /* Default path to search for executables. */
26 static char default_path[] = ":/bin:/usr/bin";
28 /* Default shell to use. */
29 char default_shell[] = "/bin/sh";
31 /* If NGROUPS_MAX == 0 then try other methods for finding a real value. */
32 #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0
33 #undef NGROUPS_MAX
34 #endif /* NGROUPS_MAX == 0 */
36 #ifndef NGROUPS_MAX
37 #ifdef POSIX
38 #define GET_NGROUPS_MAX sysconf (_SC_NGROUPS_MAX)
39 #else /* Not POSIX. */
40 #define NGROUPS_MAX NGROUPS
41 #endif /* POSIX. */
42 #endif
44 #ifdef HAVE_SYS_WAIT_H
45 #include <sys/wait.h>
46 #endif
48 #ifdef HAVE_WAITPID
49 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
50 #else /* Don't have waitpid. */
51 #ifdef HAVE_WAIT3
52 #ifndef wait3
53 extern int wait3 ();
54 #endif
55 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
56 #endif /* Have wait3. */
57 #endif /* Have waitpid. */
59 #if !defined (wait) && !defined (POSIX)
60 extern int wait ();
61 #endif
63 #ifndef HAVE_UNION_WAIT
65 #define WAIT_T int
67 #ifndef WTERMSIG
68 #define WTERMSIG(x) ((x) & 0x7f)
69 #endif
70 #ifndef WCOREDUMP
71 #define WCOREDUMP(x) ((x) & 0x80)
72 #endif
73 #ifndef WEXITSTATUS
74 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
75 #endif
76 #ifndef WIFSIGNALED
77 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
78 #endif
79 #ifndef WIFEXITED
80 #define WIFEXITED(x) (WTERMSIG (x) == 0)
81 #endif
83 #else /* Have `union wait'. */
85 #define WAIT_T union wait
86 #ifndef WTERMSIG
87 #define WTERMSIG(x) ((x).w_termsig)
88 #endif
89 #ifndef WCOREDUMP
90 #define WCOREDUMP(x) ((x).w_coredump)
91 #endif
92 #ifndef WEXITSTATUS
93 #define WEXITSTATUS(x) ((x).w_retcode)
94 #endif
95 #ifndef WIFSIGNALED
96 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
97 #endif
98 #ifndef WIFEXITED
99 #define WIFEXITED(x) (WTERMSIG(x) == 0)
100 #endif
102 #endif /* Don't have `union wait'. */
105 #ifndef HAVE_UNISTD_H
106 extern int dup2 ();
107 extern int execve ();
108 extern void _exit ();
109 extern int geteuid (), getegid ();
110 extern int setgid (), getgid ();
111 #endif
113 #ifndef getdtablesize
114 #ifdef HAVE_GETDTABLESIZE
115 extern int getdtablesize ();
116 #else
117 #include <sys/param.h>
118 #define getdtablesize() NOFILE
119 #if !defined (NOFILE) && defined (NOFILES_MAX)
120 /* SCO 3.2 "devsys 4.2" defines NOFILES_{MIN,MAX} in lieu of NOFILE. */
121 #define NOFILE NOFILES_MAX
122 #endif
123 #endif
124 #endif
126 extern int getloadavg ();
127 extern int start_remote_job_p ();
128 extern int start_remote_job (), remote_status ();
130 RETSIGTYPE child_handler ();
131 static void free_child (), start_job_command ();
132 static int load_too_high (), job_next_command ();
134 /* Chain of all live (or recently deceased) children. */
136 struct child *children = 0;
138 /* Number of children currently running. */
140 unsigned int job_slots_used = 0;
142 /* Nonzero if the `good' standard input is in use. */
144 static int good_stdin_used = 0;
146 /* Chain of children waiting to run until the load average goes down. */
148 static struct child *waiting_jobs = 0;
150 /* Write an error message describing the exit status given in
151 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
152 Append "(ignored)" if IGNORED is nonzero. */
154 static void
155 child_error (target_name, exit_code, exit_sig, coredump, ignored)
156 char *target_name;
157 int exit_code, exit_sig, coredump;
158 int ignored;
160 if (exit_sig == 0)
161 error (ignored ? "[%s] Error %d (ignored)" :
162 "*** [%s] Error %d",
163 target_name, exit_code);
164 else
166 char *coredump_string = coredump ? " (core dumped)" : "";
167 if (exit_sig > 0 && exit_sig < NSIG)
168 error ("*** [%s] %s%s",
169 target_name, sys_siglist[exit_sig], coredump_string);
170 else
171 error ("*** [%s] Signal %d%s", target_name, exit_sig, coredump_string);
175 static unsigned int dead_children = 0;
177 /* Notice that a child died.
178 reap_children should be called when convenient. */
179 RETSIGTYPE
180 child_handler (sig)
181 int sig;
183 ++dead_children;
185 if (debug_flag)
186 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
189 extern int shell_function_pid, shell_function_completed;
191 /* Reap dead children, storing the returned status and the new command
192 state (`cs_finished') in the `file' member of the `struct child' for the
193 dead child, and removing the child from the chain. If BLOCK nonzero,
194 reap at least one child, waiting for it to die if necessary. If ERR is
195 nonzero, print an error message first. */
197 void
198 reap_children (block, err)
199 int block, err;
201 WAIT_T status;
203 while ((children != 0 || shell_function_pid != 0) &&
204 (block || dead_children > 0))
206 int remote = 0;
207 register int pid;
208 int exit_code, exit_sig, coredump;
209 register struct child *lastc, *c;
210 int child_failed;
211 int any_remote, any_local;
213 if (err && dead_children == 0)
215 /* We might block for a while, so let the user know why. */
216 fflush (stdout);
217 error ("*** Waiting for unfinished jobs....");
220 /* We have one less dead child to reap.
221 The test and decrement are not atomic; if it is compiled into:
222 register = dead_children - 1;
223 dead_children = register;
224 a SIGCHLD could come between the two instructions.
225 child_handler increments dead_children.
226 The second instruction here would lose that increment. But the
227 only effect of dead_children being wrong is that we might wait
228 longer than necessary to reap a child, and lose some parallelism;
229 and we might print the "Waiting for unfinished jobs" message above
230 when not necessary. */
232 if (dead_children != 0)
233 --dead_children;
235 any_remote = 0;
236 any_local = shell_function_pid != -1;
237 for (c = children; c != 0; c = c->next)
239 any_remote |= c->remote;
240 any_local |= ! c->remote;
241 if (debug_flag)
242 printf ("Live child 0x%08lx PID %d%s\n",
243 (unsigned long int) c,
244 c->pid, c->remote ? " (remote)" : "");
247 /* First, check for remote children. */
248 if (any_remote)
249 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
250 else
251 pid = 0;
252 if (pid < 0)
254 remote_status_lose:
255 #ifdef EINTR
256 if (errno == EINTR)
257 continue;
258 #endif
259 pfatal_with_name ("remote_status");
261 else if (pid == 0)
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);
312 else
313 /* We got a remote child. */
314 remote = 1;
316 /* Check if this is the child of the `shell' function. */
317 if (!remote && pid == shell_function_pid)
319 /* It is. Leave an indicator for the `shell' function. */
320 if (exit_sig == 0 && exit_code == 127)
321 shell_function_completed = -1;
322 else
323 shell_function_completed = 1;
324 break;
327 child_failed = exit_sig != 0 || exit_code != 0;
329 /* Search for a child matching the deceased one. */
330 lastc = 0;
331 for (c = children; c != 0; lastc = c, c = c->next)
332 if (c->remote == remote && c->pid == pid)
333 break;
335 if (c == 0)
337 /* An unknown child died. */
338 char buf[100];
339 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
340 if (child_failed)
341 child_error (buf, exit_code, exit_sig, coredump,
342 ignore_errors_flag);
343 else
344 error ("%s finished.", buf);
346 else
348 if (debug_flag)
349 printf ("Reaping %s child 0x%08lx PID %d%s\n",
350 child_failed ? "losing" : "winning",
351 (unsigned long int) c,
352 c->pid, c->remote ? " (remote)" : "");
354 /* If this child had the good stdin, say it is now free. */
355 if (c->good_stdin)
356 good_stdin_used = 0;
358 if (child_failed && !c->noerror && !ignore_errors_flag)
360 /* The commands failed. Write an error message,
361 delete non-precious targets, and abort. */
362 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
363 c->file->update_status = 1;
364 if (exit_sig != 0)
365 delete_child_targets (c);
367 else
369 if (child_failed)
371 /* The commands failed, but we don't care. */
372 child_error (c->file->name,
373 exit_code, exit_sig, coredump, 1);
374 child_failed = 0;
377 /* If there are more commands to run, try to start them. */
378 if (job_next_command (c))
380 if (handling_fatal_signal)
382 /* Never start new commands while we are dying.
383 Since there are more commands that wanted to be run,
384 the target was not completely remade. So we treat
385 this as if a command had failed. */
386 c->file->command_state = cs_finished;
387 c->file->update_status = 1;
389 else
391 /* Check again whether to start remotely.
392 Whether or not we want to changes over time.
393 Also, start_remote_job may need state set up
394 by start_remote_job_p. */
395 c->remote = start_remote_job_p ();
396 start_job_command (c);
400 switch (c->file->command_state)
402 case cs_running:
403 /* Successfully started. Loop to reap more children. */
404 continue;
406 case cs_finished:
407 if (c->file->update_status != 0)
408 /* We failed to start the commands. */
409 delete_child_targets (c);
410 break;
412 default:
413 error ("internal error: `%s' has bogus command_state \
414 %d in reap_children",
415 c->file->name, (int) c->file->command_state);
416 abort ();
417 break;
421 if (! handling_fatal_signal)
422 /* Notice if the target of the commands has been changed. */
423 notice_finished_file (c->file);
425 if (debug_flag)
426 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
427 (unsigned long int) c,
428 c->pid, c->remote ? " (remote)" : "");
430 /* Remove the child from the chain and free it. */
431 if (lastc == 0)
432 children = c->next;
433 else
434 lastc->next = c->next;
435 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
436 free_child (c);
438 /* There is now another slot open. */
439 --job_slots_used;
441 /* If the job failed, and the -k flag was not given, die,
442 unless we are already in the process of dying. */
443 if (!err && child_failed && !keep_going_flag)
444 die (2);
447 /* Only block for one child. */
448 block = 0;
452 /* Free the storage allocated for CHILD. */
454 static void
455 free_child (child)
456 register struct child *child;
458 if (child->command_lines != 0)
460 register unsigned int i;
461 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
462 free (child->command_lines[i]);
463 free ((char *) child->command_lines);
466 if (child->environment != 0)
468 register char **ep = child->environment;
469 while (*ep != 0)
470 free (*ep++);
471 free ((char *) child->environment);
474 free ((char *) child);
477 #ifdef POSIX
478 extern sigset_t fatal_signal_set;
480 void
481 unblock_sigs ()
483 sigset_t empty;
484 sigemptyset (&empty);
485 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
487 #endif
489 /* Start a job to run the commands specified in CHILD.
490 CHILD is updated to reflect the commands and ID of the child process. */
492 static void
493 start_job_command (child)
494 register struct child *child;
496 static int bad_stdin = -1;
497 register char *p;
498 int flags = child->file->cmds->lines_flags[child->command_line - 1];
499 char **argv;
501 p = child->command_ptr;
502 child->noerror = flags & COMMANDS_NOERROR;
503 while (*p != '\0')
505 if (*p == '@')
506 flags |= COMMANDS_SILENT;
507 else if (*p == '+')
508 flags |= COMMANDS_RECURSE;
509 else if (*p == '-')
510 child->noerror = 1;
511 else if (!isblank (*p) && *p != '+')
512 break;
513 ++p;
516 /* If -q was given, just say that updating `failed'. The exit status of
517 1 tells the user that -q is saying `something to do'; the exit status
518 for a random error is 2. */
519 if (question_flag && !(flags & COMMANDS_RECURSE))
521 child->file->update_status = 1;
522 child->file->command_state = cs_finished;
523 return;
526 /* There may be some preceding whitespace left if there
527 was nothing but a backslash on the first line. */
528 p = next_token (p);
530 /* Figure out an argument list from this command line. */
533 char *end;
534 argv = construct_command_argv (p, &end, child->file);
535 if (end == NULL)
536 child->command_ptr = NULL;
537 else
539 *end++ = '\0';
540 child->command_ptr = end;
544 if (touch_flag && !(flags & COMMANDS_RECURSE))
546 /* Go on to the next command. It might be the recursive one.
547 We construct ARGV only to find the end of the command line. */
548 free (argv[0]);
549 free ((char *) argv);
550 argv = 0;
553 if (argv == 0)
555 /* This line has no commands. Go to the next. */
556 if (job_next_command (child))
557 start_job_command (child);
558 return;
561 /* Print out the command. */
563 if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
564 puts (p);
566 /* Tell update_goal_chain that a command has been started on behalf of
567 this target. It is important that this happens here and not in
568 reap_children (where we used to do it), because reap_children might be
569 reaping children from a different target. We want this increment to
570 guaranteedly indicate that a command was started for the dependency
571 chain (i.e., update_file recursion chain) we are processing. */
573 ++commands_started;
575 /* If -n was given, recurse to get the next line in the sequence. */
577 if (just_print_flag && !(flags & COMMANDS_RECURSE))
579 free (argv[0]);
580 free ((char *) argv);
581 if (job_next_command (child))
582 start_job_command (child);
583 return;
586 /* Flush the output streams so they won't have things written twice. */
588 fflush (stdout);
589 fflush (stderr);
591 /* Set up a bad standard input that reads from a broken pipe. */
593 if (bad_stdin == -1)
595 /* Make a file descriptor that is the read end of a broken pipe.
596 This will be used for some children's standard inputs. */
597 int pd[2];
598 if (pipe (pd) == 0)
600 /* Close the write side. */
601 (void) close (pd[1]);
602 /* Save the read side. */
603 bad_stdin = pd[0];
607 /* Decide whether to give this child the `good' standard input
608 (one that points to the terminal or whatever), or the `bad' one
609 that points to the read side of a broken pipe. */
611 child->good_stdin = !good_stdin_used;
612 if (child->good_stdin)
613 good_stdin_used = 1;
615 child->deleted = 0;
617 /* Set up the environment for the child. */
618 if (child->environment == 0)
619 child->environment = target_environment (child->file);
621 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
622 if (child->remote)
624 int is_remote, id, used_stdin;
625 if (start_remote_job (argv, child->environment,
626 child->good_stdin ? 0 : bad_stdin,
627 &is_remote, &id, &used_stdin))
628 goto error;
629 else
631 if (child->good_stdin && !used_stdin)
633 child->good_stdin = 0;
634 good_stdin_used = 0;
636 child->remote = is_remote;
637 child->pid = id;
640 else
642 /* Fork the child process. */
644 #ifdef POSIX
645 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
646 #else
647 #ifdef HAVE_SIGSETMASK
648 (void) sigblock (fatal_signal_mask);
649 #endif
650 #endif
652 child->remote = 0;
653 child->pid = vfork ();
654 if (child->pid == 0)
656 /* We are the child side. */
657 unblock_sigs ();
658 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
659 argv, child->environment);
661 else if (child->pid < 0)
663 /* Fork failed! */
664 unblock_sigs ();
665 perror_with_name ("vfork", "");
666 goto error;
670 /* We are the parent side. Set the state to
671 say the commands are running and return. */
673 child->file->command_state = cs_running;
675 /* Free the storage used by the child's argument list. */
677 free (argv[0]);
678 free ((char *) argv);
680 return;
682 error:
683 child->file->update_status = 2;
684 child->file->command_state = cs_finished;
687 /* Try to start a child running.
688 Returns nonzero if the child was started (and maybe finished), or zero if
689 the load was too high and the child was put on the `waiting_jobs' chain. */
691 static int
692 start_waiting_job (c)
693 struct child *c;
695 /* If we can start a job remotely, we always want to, and don't care about
696 the local load average. We record that the job should be started
697 remotely in C->remote for start_job_command to test. */
699 c->remote = start_remote_job_p ();
701 /* If this job is to be started locally, and we are already running
702 some jobs, make this one wait if the load average is too high. */
703 if (!c->remote && job_slots_used > 0 && load_too_high ())
705 /* Put this child on the chain of children waiting
706 for the load average to go down. */
707 c->file->command_state = cs_running;
708 c->next = waiting_jobs;
709 waiting_jobs = c;
710 return 0;
713 /* Start the first command; reap_children will run later command lines. */
714 start_job_command (c);
716 switch (c->file->command_state)
718 case cs_running:
719 c->next = children;
720 if (debug_flag)
721 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
722 (unsigned long int) c,
723 c->pid, c->remote ? " (remote)" : "");
724 children = c;
725 /* One more job slot is in use. */
726 ++job_slots_used;
727 unblock_sigs ();
728 break;
730 case cs_finished:
731 notice_finished_file (c->file);
732 free_child (c);
733 break;
735 default:
736 error ("internal error: `%s' command_state == %d in new_job",
737 c->file->name, (int) c->file->command_state);
738 abort ();
739 break;
742 return 1;
745 /* Create a `struct child' for FILE and start its commands running. */
747 void
748 new_job (file)
749 register struct file *file;
751 register struct commands *cmds = file->cmds;
752 register struct child *c;
753 char **lines;
754 register unsigned int i;
756 /* Let any previously decided-upon jobs that are waiting
757 for the load to go down start before this new one. */
758 start_waiting_jobs ();
760 /* Reap any children that might have finished recently. */
761 reap_children (0, 0);
763 /* Chop the commands up into lines if they aren't already. */
764 chop_commands (cmds);
766 if (job_slots != 0)
767 /* Wait for a job slot to be freed up. */
768 while (job_slots_used == job_slots)
769 reap_children (1, 0);
771 /* Expand the command lines and store the results in LINES. */
772 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
773 for (i = 0; i < cmds->ncommand_lines; ++i)
775 /* Collapse backslash-newline combinations that are inside variable
776 or function references. These are left alone by the parser so
777 that they will appear in the echoing of commands (where they look
778 nice); and collapsed by construct_command_argv when it tokenizes.
779 But letting them survive inside function invocations loses because
780 we don't want the functions to see them as part of the text. */
782 char *in, *out, *ref;
784 /* IN points to where in the line we are scanning.
785 OUT points to where in the line we are writing.
786 When we collapse a backslash-newline combination,
787 IN gets ahead out OUT. */
789 in = out = cmds->command_lines[i];
790 while ((ref = index (in, '$')) != 0)
792 ++ref; /* Move past the $. */
794 if (out != in)
795 /* Copy the text between the end of the last chunk
796 we processed (where IN points) and the new chunk
797 we are about to process (where REF points). */
798 bcopy (in, out, ref - in);
800 /* Move both pointers past the boring stuff. */
801 out += ref - in;
802 in = ref;
804 if (*ref == '(' || *ref == '{')
806 char openparen = *ref;
807 char closeparen = openparen == '(' ? ')' : '}';
808 int count;
809 char *p;
811 *out++ = *in++; /* Copy OPENPAREN. */
812 /* IN now points past the opening paren or brace.
813 Count parens or braces until it is matched. */
814 count = 0;
815 while (*in != '\0')
817 if (*in == closeparen && --count < 0)
818 break;
819 else if (*in == '\\' && in[1] == '\n')
821 /* We have found a backslash-newline inside a
822 variable or function reference. Eat it and
823 any following whitespace. */
825 int quoted = 0;
826 for (p = in - 1; p > ref && *p == '\\'; --p)
827 quoted = !quoted;
829 if (quoted)
830 /* There were two or more backslashes, so this is
831 not really a continuation line. We don't collapse
832 the quoting backslashes here as is done in
833 collapse_continuations, because the line will
834 be collapsed again after expansion. */
835 *out++ = *in++;
836 else
838 /* Skip the backslash, newline and
839 any following whitespace. */
840 in = next_token (in + 2);
842 /* Discard any preceding whitespace that has
843 already been written to the output. */
844 while (out > ref && isblank (out[-1]))
845 --out;
847 /* Replace it all with a single space. */
848 *out++ = ' ';
851 else
853 if (*in == openparen)
854 ++count;
856 *out++ = *in++;
862 /* There are no more references in this line to worry about.
863 Copy the remaining uninteresting text to the output. */
864 if (out != in)
865 strcpy (out, in);
867 /* Finally, expand the line. */
868 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
869 file);
872 /* Start the command sequence, record it in a new
873 `struct child', and add that to the chain. */
875 c = (struct child *) xmalloc (sizeof (struct child));
876 c->file = file;
877 c->command_lines = lines;
878 c->command_line = 0;
879 c->command_ptr = 0;
880 c->environment = 0;
882 /* Fetch the first command line to be run. */
883 if (! job_next_command (c))
884 /* There were no commands! */
885 free_child (c);
886 else
888 /* The job is now primed. Start it running. */
889 start_waiting_job (c);
891 if (job_slots == 1)
892 /* Since there is only one job slot, make things run linearly.
893 Wait for the child to die, setting the state to `cs_finished'. */
894 while (file->command_state == cs_running)
895 reap_children (1, 0);
899 /* Move CHILD's pointers to the next command for it to execute.
900 Returns nonzero if there is another command. */
902 static int
903 job_next_command (child)
904 struct child *child;
906 if (child->command_ptr == 0 || *child->command_ptr == '\0')
908 /* There are no more lines in the expansion of this line. */
909 if (child->command_line == child->file->cmds->ncommand_lines)
911 /* There are no more lines to be expanded. */
912 child->command_ptr = 0;
913 child->file->command_state = cs_finished;
914 child->file->update_status = 0;
915 return 0;
917 else
918 /* Get the next line to run. */
919 child->command_ptr = child->command_lines[child->command_line++];
921 return 1;
924 static int
925 load_too_high ()
927 extern int getloadavg ();
928 double load;
930 if (max_load_average < 0)
931 return 0;
933 make_access ();
934 if (getloadavg (&load, 1) != 1)
936 static int lossage = -1;
937 /* Complain only once for the same error. */
938 if (lossage == -1 || errno != lossage)
940 if (errno == 0)
941 /* An errno value of zero means getloadavg is just unsupported. */
942 error ("cannot enforce load limits on this operating system");
943 else
944 perror_with_name ("cannot enforce load limit: ", "getloadavg");
946 lossage = errno;
947 load = 0;
949 user_access ();
951 return load >= max_load_average;
954 /* Start jobs that are waiting for the load to be lower. */
956 void
957 start_waiting_jobs ()
959 struct child *job;
961 if (waiting_jobs == 0)
962 return;
966 /* Check for recently deceased descendants. */
967 reap_children (0, 0);
969 /* Take a job off the waiting list. */
970 job = waiting_jobs;
971 waiting_jobs = job->next;
973 /* Try to start that job. We break out of the loop as soon
974 as start_waiting_job puts one back on the waiting list. */
975 } while (start_waiting_job (job) && waiting_jobs != 0);
978 /* Replace the current process with one executing the command in ARGV.
979 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
980 the environment of the new program. This function does not return. */
982 void
983 child_execute_job (stdin_fd, stdout_fd, argv, envp)
984 int stdin_fd, stdout_fd;
985 char **argv, **envp;
987 if (stdin_fd != 0)
988 (void) dup2 (stdin_fd, 0);
989 if (stdout_fd != 1)
990 (void) dup2 (stdout_fd, 1);
992 /* Free up file descriptors. */
994 register int d;
995 int max = getdtablesize ();
996 for (d = 3; d < max; ++d)
997 (void) close (d);
1000 /* Run the command. */
1001 exec_command (argv, envp);
1004 /* Search PATH for FILE.
1005 If successful, store the full pathname in PROGRAM and return 1.
1006 If not sucessful, return zero. */
1008 static int
1009 search_path (file, path, program)
1010 char *file, *path, *program;
1012 if (path == 0 || path[0] == '\0')
1013 path = default_path;
1015 if (index (file, '/') != 0)
1017 strcpy (program, file);
1018 return 1;
1020 else
1022 unsigned int len;
1024 #ifdef HAVE_GETGROUPS
1025 #ifndef HAVE_UNISTD_H
1026 extern int getgroups ();
1027 #endif
1028 static int ngroups = -1;
1029 #ifdef NGROUPS_MAX
1030 static GETGROUPS_T groups[NGROUPS_MAX];
1031 #define ngroups_max NGROUPS_MAX
1032 #else
1033 static GETGROUPS_T *groups = 0;
1034 static int ngroups_max;
1035 if (groups == 0)
1037 ngroups_max = GET_NGROUPS_MAX;
1038 groups = (GETGROUPS_T *) malloc (ngroups_max * sizeof (GETGROUPS_T));
1040 #endif
1041 if (groups != 0 && ngroups == -1)
1042 ngroups = getgroups (ngroups_max, groups);
1043 #endif /* Have getgroups. */
1045 len = strlen (file) + 1;
1048 struct stat st;
1049 int perm;
1050 char *p;
1052 p = index (path, ':');
1053 if (p == 0)
1054 p = path + strlen (path);
1056 if (p == path)
1057 bcopy (file, program, len);
1058 else
1060 bcopy (path, program, p - path);
1061 program[p - path] = '/';
1062 bcopy (file, program + (p - path) + 1, len);
1065 if (stat (program, &st) == 0
1066 && S_ISREG (st.st_mode))
1068 if (st.st_uid == geteuid ())
1069 perm = (st.st_mode & 0100);
1070 else if (st.st_gid == getegid ())
1071 perm = (st.st_mode & 0010);
1072 else
1074 #ifdef HAVE_GETGROUPS
1075 register int i;
1076 for (i = 0; i < ngroups; ++i)
1077 if (groups[i] == st.st_gid)
1078 break;
1079 if (i < ngroups)
1080 perm = (st.st_mode & 0010);
1081 else
1082 #endif /* Have getgroups. */
1083 perm = (st.st_mode & 0001);
1086 if (perm != 0)
1087 return 1;
1090 path = p + 1;
1091 } while (*path != '\0');
1094 return 0;
1097 /* Replace the current process with one running the command in ARGV,
1098 with environment ENVP. This function does not return. */
1100 void
1101 exec_command (argv, envp)
1102 char **argv, **envp;
1104 char *shell, *path;
1105 PATH_VAR (program);
1106 register char **ep;
1108 shell = path = 0;
1109 for (ep = envp; *ep != 0; ++ep)
1111 if (shell == 0 && !strncmp(*ep, "SHELL=", 6))
1112 shell = &(*ep)[6];
1113 else if (path == 0 && !strncmp(*ep, "PATH=", 5))
1114 path = &(*ep)[5];
1115 else if (path != 0 && shell != 0)
1116 break;
1119 /* Be the user, permanently. */
1120 child_access ();
1122 if (!search_path (argv[0], path, program))
1123 error ("%s: Command not found", argv[0]);
1124 else
1126 /* Run the program. */
1127 execve (program, argv, envp);
1129 if (errno == ENOEXEC)
1131 PATH_VAR (shell_program);
1132 char *shell_path;
1133 if (shell == 0)
1134 shell_path = default_shell;
1135 else
1137 if (search_path (shell, path, shell_program))
1138 shell_path = shell_program;
1139 else
1141 shell_path = 0;
1142 error ("%s: Shell program not found", shell);
1146 if (shell_path != 0)
1148 char **new_argv;
1149 int argc;
1151 argc = 1;
1152 while (argv[argc] != 0)
1153 ++argc;
1155 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1156 new_argv[0] = shell_path;
1157 new_argv[1] = program;
1158 while (argc > 0)
1160 new_argv[1 + argc] = argv[argc];
1161 --argc;
1164 execve (shell_path, new_argv, envp);
1165 perror_with_name ("execve: ", shell_path);
1168 else
1169 perror_with_name ("execve: ", program);
1172 _exit (127);
1175 /* Figure out the argument list necessary to run LINE as a command.
1176 Try to avoid using a shell. This routine handles only ' quoting.
1177 Starting quotes may be escaped with a backslash. If any of the
1178 characters in sh_chars[] is seen, or any of the builtin commands
1179 listed in sh_cmds[] is the first word of a line, the shell is used.
1181 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1182 If *RESTP is NULL, newlines will be ignored.
1184 SHELL is the shell to use, or nil to use the default shell.
1185 IFS is the value of $IFS, or nil (meaning the default). */
1187 static char **
1188 construct_command_argv_internal (line, restp, shell, ifs)
1189 char *line, **restp;
1190 char *shell, *ifs;
1192 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1193 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1194 "logout", "set", "umask", "wait", "while", "for",
1195 "case", "if", ":", ".", "break", "continue",
1196 "export", "read", "readonly", "shift", "times",
1197 "trap", "switch", 0 };
1198 register int i;
1199 register char *p;
1200 register char *ap;
1201 char *end;
1202 int instring, word_has_equals, seen_nonequals;
1203 char **new_argv = 0;
1205 if (restp != NULL)
1206 *restp = NULL;
1208 /* Make sure not to bother processing an empty line. */
1209 while (isblank (*line))
1210 ++line;
1211 if (*line == '\0')
1212 return 0;
1214 /* See if it is safe to parse commands internally. */
1215 if (shell == 0)
1216 shell = default_shell;
1217 else if (strcmp (shell, default_shell))
1218 goto slow;
1220 if (ifs != 0)
1221 for (ap = ifs; *ap != '\0'; ++ap)
1222 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1223 goto slow;
1225 i = strlen (line) + 1;
1227 /* More than 1 arg per character is impossible. */
1228 new_argv = (char **) xmalloc (i * sizeof (char *));
1230 /* All the args can fit in a buffer as big as LINE is. */
1231 ap = new_argv[0] = (char *) xmalloc (i);
1232 end = ap + i;
1234 /* I is how many complete arguments have been found. */
1235 i = 0;
1236 instring = word_has_equals = seen_nonequals = 0;
1237 for (p = line; *p != '\0'; ++p)
1239 if (ap > end)
1240 abort ();
1242 if (instring)
1244 string_char:
1245 /* Inside a string, just copy any char except a closing quote
1246 or a backslash-newline combination. */
1247 if (*p == '\'')
1248 instring = 0;
1249 else if (*p == '\\' && p[1] == '\n')
1250 goto swallow_escaped_newline;
1251 else if (*p == '\n' && restp != NULL)
1253 /* End of the command line. */
1254 *restp = p;
1255 goto end_of_line;
1257 else
1258 *ap++ = *p;
1260 else if (index (sh_chars, *p) != 0)
1261 /* Not inside a string, but it's a special char. */
1262 goto slow;
1263 else
1264 /* Not a special char. */
1265 switch (*p)
1267 case '=':
1268 /* Equals is a special character in leading words before the
1269 first word with no equals sign in it. This is not the case
1270 with sh -k, but we never get here when using nonstandard
1271 shell flags. */
1272 if (! seen_nonequals)
1273 goto slow;
1274 word_has_equals = 1;
1275 *ap++ = '=';
1276 break;
1278 case '\\':
1279 /* Backslash-newline combinations are eaten. */
1280 if (p[1] == '\n')
1282 swallow_escaped_newline:
1284 /* Eat the backslash, the newline, and following whitespace,
1285 replacing it all with a single space. */
1286 p += 2;
1288 /* If there is a tab after a backslash-newline,
1289 remove it from the source line which will be echoed,
1290 since it was most likely used to line
1291 up the continued line with the previous one. */
1292 if (*p == '\t')
1293 strcpy (p, p + 1);
1295 if (instring)
1296 goto string_char;
1297 else
1299 if (ap != new_argv[i])
1300 /* Treat this as a space, ending the arg.
1301 But if it's at the beginning of the arg, it should
1302 just get eaten, rather than becoming an empty arg. */
1303 goto end_of_arg;
1304 else
1305 p = next_token (p) - 1;
1308 else if (p[1] != '\0')
1309 /* Copy and skip the following char. */
1310 *ap++ = *++p;
1311 break;
1313 case '\'':
1314 instring = 1;
1315 break;
1317 case '\n':
1318 if (restp != NULL)
1320 /* End of the command line. */
1321 *restp = p;
1322 goto end_of_line;
1324 else
1325 /* Newlines are not special. */
1326 *ap++ = '\n';
1327 break;
1329 case ' ':
1330 case '\t':
1331 end_of_arg:
1332 /* We have the end of an argument.
1333 Terminate the text of the argument. */
1334 *ap++ = '\0';
1335 new_argv[++i] = ap;
1337 /* Update SEEN_NONEQUALS, which tells us if every word
1338 heretofore has contained an `='. */
1339 seen_nonequals |= ! word_has_equals;
1340 if (word_has_equals && ! seen_nonequals)
1341 /* An `=' in a word before the first
1342 word without one is magical. */
1343 goto slow;
1344 word_has_equals = 0; /* Prepare for the next word. */
1346 /* If this argument is the command name,
1347 see if it is a built-in shell command.
1348 If so, have the shell handle it. */
1349 if (i == 1)
1351 register int j;
1352 for (j = 0; sh_cmds[j] != 0; ++j)
1353 if (streq (sh_cmds[j], new_argv[0]))
1354 goto slow;
1357 /* Ignore multiple whitespace chars. */
1358 p = next_token (p);
1359 /* Next iteration should examine the first nonwhite char. */
1360 --p;
1361 break;
1363 default:
1364 *ap++ = *p;
1365 break;
1368 end_of_line:
1370 if (instring)
1371 /* Let the shell deal with an unterminated quote. */
1372 goto slow;
1374 /* Terminate the last argument and the argument list. */
1376 *ap = '\0';
1377 if (new_argv[i][0] != '\0')
1378 ++i;
1379 new_argv[i] = 0;
1381 if (i == 1)
1383 register int j;
1384 for (j = 0; sh_cmds[j] != 0; ++j)
1385 if (streq (sh_cmds[j], new_argv[0]))
1386 goto slow;
1389 if (new_argv[0] == 0)
1390 /* Line was empty. */
1391 return 0;
1392 else
1393 return new_argv;
1395 slow:;
1396 /* We must use the shell. */
1398 if (new_argv != 0)
1400 /* Free the old argument list we were working on. */
1401 free (new_argv[0]);
1402 free (new_argv);
1406 /* SHELL may be a multi-word command. Construct a command line
1407 "SHELL -c LINE", with all special chars in LINE escaped.
1408 Then recurse, expanding this command line to get the final
1409 argument list. */
1411 unsigned int shell_len = strlen (shell);
1412 static char minus_c[] = " -c ";
1413 unsigned int line_len = strlen (line);
1415 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1416 + (line_len * 2) + 1);
1418 ap = new_line;
1419 bcopy (shell, ap, shell_len);
1420 ap += shell_len;
1421 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1422 ap += sizeof (minus_c) - 1;
1423 for (p = line; *p != '\0'; ++p)
1425 if (restp != NULL && *p == '\n')
1427 *restp = p;
1428 break;
1430 else if (*p == '\\' && p[1] == '\n')
1432 /* Eat the backslash, the newline, and following whitespace,
1433 replacing it all with a single space (which is escaped
1434 from the shell). */
1435 p += 2;
1437 /* If there is a tab after a backslash-newline,
1438 remove it from the source line which will be echoed,
1439 since it was most likely used to line
1440 up the continued line with the previous one. */
1441 if (*p == '\t')
1442 strcpy (p, p + 1);
1444 p = next_token (p);
1445 --p;
1446 *ap++ = '\\';
1447 *ap++ = ' ';
1448 continue;
1451 if (*p == '\\' || *p == '\''
1452 || isspace (*p)
1453 || index (sh_chars, *p) != 0)
1454 *ap++ = '\\';
1455 *ap++ = *p;
1457 *ap = '\0';
1459 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1460 (char *) 0, (char *) 0);
1463 return new_argv;
1466 /* Figure out the argument list necessary to run LINE as a command.
1467 Try to avoid using a shell. This routine handles only ' quoting.
1468 Starting quotes may be escaped with a backslash. If any of the
1469 characters in sh_chars[] is seen, or any of the builtin commands
1470 listed in sh_cmds[] is the first word of a line, the shell is used.
1472 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1473 If *RESTP is NULL, newlines will be ignored.
1475 FILE is the target whose commands these are. It is used for
1476 variable expansion for $(SHELL) and $(IFS). */
1478 char **
1479 construct_command_argv (line, restp, file)
1480 char *line, **restp;
1481 struct file *file;
1483 char *shell, *ifs;
1484 char **argv;
1487 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1488 int save = warn_undefined_variables_flag;
1489 warn_undefined_variables_flag = 0;
1491 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1492 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1494 warn_undefined_variables_flag = save;
1497 argv = construct_command_argv_internal (line, restp, shell, ifs);
1499 free (shell);
1500 free (ifs);
1502 return argv;
1505 #ifndef HAVE_DUP2
1507 dup2 (old, new)
1508 int old, new;
1510 int fd;
1512 (void) close (new);
1513 fd = dup (old);
1514 if (fd != new)
1516 (void) close (fd);
1517 errno = EMFILE;
1518 return -1;
1521 return fd;
1523 #endif