Formerly job.c.~106~
[make.git] / job.c
blobfb0f22e28e76dee44c2f34fac32ae638e53e3a2b
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993 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 #endif
120 #endif
122 extern int getloadavg ();
123 extern int start_remote_job_p ();
124 extern int start_remote_job (), remote_status ();
126 RETSIGTYPE child_handler ();
127 static void free_child (), start_job_command ();
128 static int load_too_high (), job_next_command ();
130 /* Chain of all live (or recently deceased) children. */
132 struct child *children = 0;
134 /* Number of children currently running. */
136 unsigned int job_slots_used = 0;
138 /* Nonzero if the `good' standard input is in use. */
140 static int good_stdin_used = 0;
142 /* Chain of children waiting to run until the load average goes down. */
144 static struct child *waiting_jobs = 0;
146 /* Write an error message describing the exit status given in
147 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
148 Append "(ignored)" if IGNORED is nonzero. */
150 static void
151 child_error (target_name, exit_code, exit_sig, coredump, ignored)
152 char *target_name;
153 int exit_code, exit_sig, coredump;
154 int ignored;
156 if (exit_sig == 0)
157 error (ignored ? "[%s] Error %d (ignored)" :
158 "*** [%s] Error %d",
159 target_name, exit_code);
160 else
162 char *coredump_string = coredump ? " (core dumped)" : "";
163 if (exit_sig > 0 && exit_sig < NSIG)
164 error ("*** [%s] %s%s",
165 target_name, sys_siglist[exit_sig], coredump_string);
166 else
167 error ("*** [%s] Signal %d%s", target_name, exit_sig, coredump_string);
171 static unsigned int dead_children = 0;
173 /* Notice that a child died.
174 reap_children should be called when convenient. */
175 RETSIGTYPE
176 child_handler (sig)
177 int sig;
179 ++dead_children;
181 if (debug_flag)
182 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
185 extern int shell_function_pid, shell_function_completed;
187 /* Reap dead children, storing the returned status and the new command
188 state (`cs_finished') in the `file' member of the `struct child' for the
189 dead child, and removing the child from the chain. If BLOCK nonzero,
190 reap at least one child, waiting for it to die if necessary. If ERR is
191 nonzero, print an error message first. */
193 void
194 reap_children (block, err)
195 int block, err;
197 WAIT_T status;
199 while ((children != 0 || shell_function_pid != 0) &&
200 (block || dead_children > 0))
202 int remote = 0;
203 register int pid;
204 int exit_code, exit_sig, coredump;
205 register struct child *lastc, *c;
206 int child_failed;
207 int any_remote, any_local;
209 if (err && dead_children == 0)
211 /* We might block for a while, so let the user know why. */
212 fflush (stdout);
213 error ("*** Waiting for unfinished jobs....");
216 /* We have one less dead child to reap.
217 The test and decrement are not atomic; if it is compiled into:
218 register = dead_children - 1;
219 dead_children = register;
220 a SIGCHLD could come between the two instructions.
221 child_handler increments dead_children.
222 The second instruction here would lose that increment. But the
223 only effect of dead_children being wrong is that we might wait
224 longer than necessary to reap a child, and lose some parallelism;
225 and we might print the "Waiting for unfinished jobs" message above
226 when not necessary. */
228 if (dead_children != 0)
229 --dead_children;
231 any_remote = 0;
232 any_local = shell_function_pid != -1;
233 for (c = children; c != 0; c = c->next)
235 any_remote |= c->remote;
236 any_locate != ! c->remote;
237 if (debug_flag)
238 printf ("Live child 0x%08lx PID %d%s\n",
239 (unsigned long int) c,
240 c->pid, c->remote ? " (remote)" : "");
243 /* First, check for remote children. */
244 if (any_remote)
245 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
246 else
247 pid = 0;
248 if (pid < 0)
250 remote_status_lose:
251 #ifdef EINTR
252 if (errno == EINTR)
253 continue;
254 #endif
255 pfatal_with_name ("remote_status");
257 else if (pid == 0)
259 /* No remote children. Check for local children. */
261 if (any_local)
263 #ifdef WAIT_NOHANG
264 if (!block)
265 pid = WAIT_NOHANG (&status);
266 else
267 #endif
268 pid = wait (&status);
270 else
271 pid = 0;
273 if (pid < 0)
275 #ifdef EINTR
276 if (errno == EINTR)
277 continue;
278 #endif
279 pfatal_with_name ("wait");
281 else if (pid == 0)
283 /* No local children. */
284 if (block && any_remote)
286 /* Now try a blocking wait for a remote child. */
287 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
288 if (pid < 0)
289 goto remote_status_lose;
290 else if (pid == 0)
291 /* No remote children either. Finally give up. */
292 break;
293 else
294 /* We got a remote child. */
295 remote = 1;
297 else
298 break;
300 else
302 /* Chop the status word up. */
303 exit_code = WEXITSTATUS (status);
304 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
305 coredump = WCOREDUMP (status);
308 else
309 /* We got a remote child. */
310 remote = 1;
312 /* Check if this is the child of the `shell' function. */
313 if (!remote && pid == shell_function_pid)
315 /* It is. Leave an indicator for the `shell' function. */
316 if (exit_sig == 0 && exit_code == 127)
317 shell_function_completed = -1;
318 else
319 shell_function_completed = 1;
320 break;
323 child_failed = exit_sig != 0 || exit_code != 0;
325 /* Search for a child matching the deceased one. */
326 lastc = 0;
327 for (c = children; c != 0; lastc = c, c = c->next)
328 if (c->remote == remote && c->pid == pid)
329 break;
331 if (c == 0)
333 /* An unknown child died. */
334 char buf[100];
335 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
336 if (child_failed)
337 child_error (buf, exit_code, exit_sig, coredump,
338 ignore_errors_flag);
339 else
340 error ("%s finished.", buf);
342 else
344 if (debug_flag)
345 printf ("Reaping %s child 0x%08lx PID %d%s\n",
346 child_failed ? "losing" : "winning",
347 (unsigned long int) c,
348 c->pid, c->remote ? " (remote)" : "");
350 /* If this child had the good stdin, say it is now free. */
351 if (c->good_stdin)
352 good_stdin_used = 0;
354 if (child_failed && !c->noerror && !ignore_errors_flag)
356 /* The commands failed. Write an error message,
357 delete non-precious targets, and abort. */
358 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
359 c->file->update_status = 1;
360 if (exit_sig != 0)
361 delete_child_targets (c);
363 else
365 if (child_failed)
367 /* The commands failed, but we don't care. */
368 child_error (c->file->name,
369 exit_code, exit_sig, coredump, 1);
370 child_failed = 0;
373 /* If there are more commands to run, try to start them. */
374 if (job_next_command (c))
376 if (handling_fatal_signal)
378 /* Never start new commands while we are dying.
379 Since there are more commands that wanted to be run,
380 the target was not completely remade. So we treat
381 this as if a command had failed. */
382 c->file->command_state = cs_finished;
383 c->file->update_status = 1;
385 else
387 /* Check again whether to start remotely.
388 Whether or not we want to changes over time.
389 Also, start_remote_job may need state set up
390 by start_remote_job_p. */
391 c->remote = start_remote_job_p ();
392 start_job_command (c);
396 switch (c->file->command_state)
398 case cs_running:
399 /* Successfully started. Loop to reap more children. */
400 continue;
402 case cs_finished:
403 if (c->file->update_status != 0)
404 /* We failed to start the commands. */
405 delete_child_targets (c);
406 break;
408 default:
409 error ("internal error: `%s' has bogus command_state \
410 %d in reap_children",
411 c->file->name, (int) c->file->command_state);
412 abort ();
413 break;
417 if (! handling_fatal_signal)
418 /* Notice if the target of the commands has been changed. */
419 notice_finished_file (c->file);
421 if (debug_flag)
422 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
423 (unsigned long int) c,
424 c->pid, c->remote ? " (remote)" : "");
426 /* Remove the child from the chain and free it. */
427 if (lastc == 0)
428 children = c->next;
429 else
430 lastc->next = c->next;
431 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
432 free_child (c);
434 /* There is now another slot open. */
435 --job_slots_used;
437 /* If the job failed, and the -k flag was not given, die,
438 unless we are already in the process of dying. */
439 if (!err && child_failed && !keep_going_flag)
440 die (1);
443 /* Only block for one child. */
444 block = 0;
448 /* Free the storage allocated for CHILD. */
450 static void
451 free_child (child)
452 register struct child *child;
454 if (child->command_lines != 0)
456 register unsigned int i;
457 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
458 free (child->command_lines[i]);
459 free ((char *) child->command_lines);
462 if (child->environment != 0)
464 register char **ep = child->environment;
465 while (*ep != 0)
466 free (*ep++);
467 free ((char *) child->environment);
470 free ((char *) child);
473 #ifdef POSIX
474 extern sigset_t fatal_signal_set;
476 void
477 unblock_sigs ()
479 sigset_t empty;
480 sigemptyset (&empty);
481 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
483 #endif
485 /* Start a job to run the commands specified in CHILD.
486 CHILD is updated to reflect the commands and ID of the child process. */
488 static void
489 start_job_command (child)
490 register struct child *child;
492 static int bad_stdin = -1;
493 register char *p;
494 int flags = child->file->cmds->lines_flags[child->command_line - 1];
495 char **argv;
497 p = child->command_ptr;
498 child->noerror = flags & COMMANDS_NOERROR;
499 while (*p != '\0')
501 if (*p == '@')
502 flags |= COMMANDS_SILENT;
503 else if (*p == '-')
504 child->noerror = 1;
505 else if (!isblank (*p) && *p != '+')
506 break;
507 ++p;
510 /* If -q was given, just say that updating `failed'. */
511 if (question_flag && !(flags & COMMANDS_RECURSE))
512 goto error;
514 /* There may be some preceding whitespace left if there
515 was nothing but a backslash on the first line. */
516 p = next_token (p);
518 /* Figure out an argument list from this command line. */
521 char *end;
522 argv = construct_command_argv (p, &end, child->file);
523 if (end == NULL)
524 child->command_ptr = NULL;
525 else
527 *end++ = '\0';
528 child->command_ptr = end;
532 if (touch_flag && !(flags & COMMANDS_RECURSE))
534 /* Go on to the next command. It might be the recursive one.
535 We construct ARGV only to find the end of the command line. */
536 free (argv[0]);
537 free ((char *) argv);
538 argv = 0;
541 if (argv == 0)
543 /* This line has no commands. Go to the next. */
544 if (job_next_command (child))
545 start_job_command (child);
546 return;
549 /* Print out the command. */
551 if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
552 puts (p);
554 /* Tell update_goal_chain that a command has been started on behalf of
555 this target. It is important that this happens here and not in
556 reap_children (where we used to do it), because reap_children might be
557 reaping children from a different target. We want this increment to
558 guaranteedly indicate that a command was started for the dependency
559 chain (i.e., update_file recursion chain) we are processing. */
561 ++commands_started;
563 /* If -n was given, recurse to get the next line in the sequence. */
565 if (just_print_flag && !(flags & COMMANDS_RECURSE))
567 free (argv[0]);
568 free ((char *) argv);
569 if (job_next_command (child))
570 start_job_command (child);
571 return;
574 /* Flush the output streams so they won't have things written twice. */
576 fflush (stdout);
577 fflush (stderr);
579 /* Set up a bad standard input that reads from a broken pipe. */
581 if (bad_stdin == -1)
583 /* Make a file descriptor that is the read end of a broken pipe.
584 This will be used for some children's standard inputs. */
585 int pd[2];
586 if (pipe (pd) == 0)
588 /* Close the write side. */
589 (void) close (pd[1]);
590 /* Save the read side. */
591 bad_stdin = pd[0];
595 /* Decide whether to give this child the `good' standard input
596 (one that points to the terminal or whatever), or the `bad' one
597 that points to the read side of a broken pipe. */
599 child->good_stdin = !good_stdin_used;
600 if (child->good_stdin)
601 good_stdin_used = 1;
603 child->deleted = 0;
605 /* Set up the environment for the child. */
606 if (child->environment == 0)
607 child->environment = target_environment (child->file);
609 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
610 if (child->remote)
612 int is_remote, id, used_stdin;
613 if (start_remote_job (argv, child->environment,
614 child->good_stdin ? 0 : bad_stdin,
615 &is_remote, &id, &used_stdin))
616 goto error;
617 else
619 if (child->good_stdin && !used_stdin)
621 child->good_stdin = 0;
622 good_stdin_used = 0;
624 child->remote = is_remote;
625 child->pid = id;
628 else
630 /* Fork the child process. */
632 #ifdef POSIX
633 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
634 #else
635 #ifdef HAVE_SIGSETMASK
636 (void) sigblock (fatal_signal_mask);
637 #endif
638 #endif
640 child->remote = 0;
641 child->pid = vfork ();
642 if (child->pid == 0)
644 /* We are the child side. */
645 unblock_sigs ();
646 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
647 argv, child->environment);
649 else if (child->pid < 0)
651 /* Fork failed! */
652 unblock_sigs ();
653 perror_with_name ("vfork", "");
654 goto error;
658 /* We are the parent side. Set the state to
659 say the commands are running and return. */
661 child->file->command_state = cs_running;
663 /* Free the storage used by the child's argument list. */
665 free (argv[0]);
666 free ((char *) argv);
668 return;
670 error:;
671 child->file->update_status = 1;
672 child->file->command_state = cs_finished;
675 /* Try to start a child running.
676 Returns nonzero if the child was started (and maybe finished), or zero if
677 the load was too high and the child was put on the `waiting_jobs' chain. */
679 static int
680 start_waiting_job (c)
681 struct child *c;
683 /* If we can start a job remotely, we always want to, and don't care about
684 the local load average. We record that the job should be started
685 remotely in C->remote for start_job_command to test. */
687 c->remote = start_remote_job_p ();
689 /* If this job is to be started locally, and we are already running
690 some jobs, make this one wait if the load average is too high. */
691 if (!c->remote && job_slots_used > 0 && load_too_high ())
693 /* Put this child on the chain of children waiting
694 for the load average to go down. */
695 c->file->command_state = cs_running;
696 c->next = waiting_jobs;
697 waiting_jobs = c;
698 return 0;
701 /* Start the first command; reap_children will run later command lines. */
702 start_job_command (c);
704 switch (c->file->command_state)
706 case cs_running:
707 c->next = children;
708 if (debug_flag)
709 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
710 (unsigned long int) c,
711 c->pid, c->remote ? " (remote)" : "");
712 children = c;
713 /* One more job slot is in use. */
714 ++job_slots_used;
715 unblock_sigs ();
716 break;
718 case cs_finished:
719 notice_finished_file (c->file);
720 free_child (c);
721 break;
723 default:
724 error ("internal error: `%s' command_state == %d in new_job",
725 c->file->name, (int) c->file->command_state);
726 abort ();
727 break;
730 return 1;
733 /* Create a `struct child' for FILE and start its commands running. */
735 void
736 new_job (file)
737 register struct file *file;
739 register struct commands *cmds = file->cmds;
740 register struct child *c;
741 char **lines;
742 register unsigned int i;
744 /* Let any previously decided-upon jobs that are waiting
745 for the load to go down start before this new one. */
746 start_waiting_jobs ();
748 /* Reap any children that might have finished recently. */
749 reap_children (0, 0);
751 /* Chop the commands up into lines if they aren't already. */
752 chop_commands (cmds);
754 if (job_slots != 0)
755 /* Wait for a job slot to be freed up. */
756 while (job_slots_used == job_slots)
757 reap_children (1, 0);
759 /* Expand the command lines and store the results in LINES. */
760 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
761 for (i = 0; i < cmds->ncommand_lines; ++i)
763 /* Collapse backslash-newline combinations that are inside variable
764 or function references. These are left alone by the parser so
765 that they will appear in the echoing of commands (where they look
766 nice); and collapsed by construct_command_argv when it tokenizes.
767 But letting them survive inside function invocations loses because
768 we don't want the functions to see them as part of the text. */
770 char *in, *out, *ref;
772 /* IN points to where in the line we are scanning.
773 OUT points to where in the line we are writing.
774 When we collapse a backslash-newline combination,
775 IN gets ahead out OUT. */
777 in = out = cmds->command_lines[i];
778 while ((ref = index (in, '$')) != 0)
780 ++ref; /* Move past the $. */
782 if (out != in)
783 /* Copy the text between the end of the last chunk
784 we processed (where IN points) and the new chunk
785 we are about to process (where REF points). */
786 bcopy (in, out, ref - in);
788 /* Move both pointers past the boring stuff. */
789 out += ref - in;
790 in = ref;
792 if (*ref == '(' || *ref == '{')
794 char openparen = *ref;
795 char closeparen = openparen == '(' ? ')' : '}';
796 int count;
797 char *p;
799 *out++ = *in++; /* Copy OPENPAREN. */
800 /* IN now points past the opening paren or brace.
801 Count parens or braces until it is matched. */
802 count = 0;
803 while (*in != '\0')
805 if (*in == closeparen && --count < 0)
806 break;
807 else if (*in == '\\' && in[1] == '\n')
809 /* We have found a backslash-newline inside a
810 variable or function reference. Eat it and
811 any following whitespace. */
813 int quoted = 0;
814 for (p = in - 1; p > ref && *p == '\\'; --p)
815 quoted = !quoted;
817 if (quoted)
818 /* There were two or more backslashes, so this is
819 not really a continuation line. We don't collapse
820 the quoting backslashes here as is done in
821 collapse_continuations, because the line will
822 be collapsed again after expansion. */
823 *out++ = *in++;
824 else
826 /* Skip the backslash, newline and
827 any following whitespace. */
828 in = next_token (in + 2);
830 /* Discard any preceding whitespace that has
831 already been written to the output. */
832 while (out > ref && isblank (out[-1]))
833 --out;
835 /* Replace it all with a single space. */
836 *out++ = ' ';
839 else
841 if (*in == openparen)
842 ++count;
844 *out++ = *in++;
850 /* There are no more references in this line to worry about.
851 Copy the remaining uninteresting text to the output. */
852 if (out != in)
853 strcpy (out, in);
855 /* Finally, expand the line. */
856 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
857 file);
860 /* Start the command sequence, record it in a new
861 `struct child', and add that to the chain. */
863 c = (struct child *) xmalloc (sizeof (struct child));
864 c->file = file;
865 c->command_lines = lines;
866 c->command_line = 0;
867 c->command_ptr = 0;
868 c->environment = 0;
870 /* Fetch the first command line to be run. */
871 if (! job_next_command (c))
872 /* There were no commands! */
873 free_child (c);
874 else
876 /* The job is now primed. Start it running. */
877 start_waiting_job (c);
879 if (job_slots == 1)
880 /* Since there is only one job slot, make things run linearly.
881 Wait for the child to die, setting the state to `cs_finished'. */
882 while (file->command_state == cs_running)
883 reap_children (1, 0);
887 /* Move CHILD's pointers to the next command for it to execute.
888 Returns nonzero if there is another command. */
890 static int
891 job_next_command (child)
892 struct child *child;
894 if (child->command_ptr == 0 || *child->command_ptr == '\0')
896 /* There are no more lines in the expansion of this line. */
897 if (child->command_line == child->file->cmds->ncommand_lines)
899 /* There are no more lines to be expanded. */
900 child->command_ptr = 0;
901 child->file->command_state = cs_finished;
902 child->file->update_status = 0;
903 return 0;
905 else
906 /* Get the next line to run. */
907 child->command_ptr = child->command_lines[child->command_line++];
909 return 1;
912 static int
913 load_too_high ()
915 extern int getloadavg ();
916 double load;
918 if (max_load_average < 0)
919 return 0;
921 make_access ();
922 if (getloadavg (&load, 1) != 1)
924 static int lossage = -1;
925 /* Complain only once for the same error. */
926 if (lossage == -1 || errno != lossage)
928 if (errno == 0)
929 /* An errno value of zero means getloadavg is just unsupported. */
930 error ("cannot enforce load limits on this operating system");
931 else
932 perror_with_name ("cannot enforce load limit: ", "getloadavg");
934 lossage = errno;
935 load = 0;
937 user_access ();
939 return load >= max_load_average;
942 /* Start jobs that are waiting for the load to be lower. */
944 void
945 start_waiting_jobs ()
947 struct child *job;
949 if (waiting_jobs == 0)
950 return;
954 /* Check for recently deceased descendants. */
955 reap_children (0, 0);
957 /* Take a job off the waiting list. */
958 job = waiting_jobs;
959 waiting_jobs = job->next;
961 /* Try to start that job. We break out of the loop as soon
962 as start_waiting_job puts one back on the waiting list. */
963 } while (start_waiting_job (job) && waiting_jobs != 0);
966 /* Replace the current process with one executing the command in ARGV.
967 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
968 the environment of the new program. This function does not return. */
970 void
971 child_execute_job (stdin_fd, stdout_fd, argv, envp)
972 int stdin_fd, stdout_fd;
973 char **argv, **envp;
975 if (stdin_fd != 0)
976 (void) dup2 (stdin_fd, 0);
977 if (stdout_fd != 1)
978 (void) dup2 (stdout_fd, 1);
980 /* Free up file descriptors. */
982 register int d;
983 int max = getdtablesize ();
984 for (d = 3; d < max; ++d)
985 (void) close (d);
988 /* Run the command. */
989 exec_command (argv, envp);
992 /* Search PATH for FILE.
993 If successful, store the full pathname in PROGRAM and return 1.
994 If not sucessful, return zero. */
996 static int
997 search_path (file, path, program)
998 char *file, *path, *program;
1000 if (path == 0 || path[0] == '\0')
1001 path = default_path;
1003 if (index (file, '/') != 0)
1005 strcpy (program, file);
1006 return 1;
1008 else
1010 unsigned int len;
1012 #ifdef HAVE_GETGROUPS
1013 #ifndef HAVE_UNISTD_H
1014 extern int getgroups ();
1015 #endif
1016 static int ngroups = -1;
1017 #ifdef NGROUPS_MAX
1018 static GETGROUPS_T groups[NGROUPS_MAX];
1019 #define ngroups_max NGROUPS_MAX
1020 #else
1021 static GETGROUPS_T *groups = 0;
1022 static int ngroups_max;
1023 if (groups == 0)
1025 ngroups_max = GET_NGROUPS_MAX;
1026 groups = (GETGROUPS_T *) malloc (ngroups_max * sizeof (GETGROUPS_T));
1028 #endif
1029 if (groups != 0 && ngroups == -1)
1030 ngroups = getgroups (ngroups_max, groups);
1031 #endif /* Have getgroups. */
1033 len = strlen (file) + 1;
1036 struct stat st;
1037 int perm;
1038 char *p;
1040 p = index (path, ':');
1041 if (p == 0)
1042 p = path + strlen (path);
1044 if (p == path)
1045 bcopy (file, program, len);
1046 else
1048 bcopy (path, program, p - path);
1049 program[p - path] = '/';
1050 bcopy (file, program + (p - path) + 1, len);
1053 if (stat (program, &st) == 0
1054 && S_ISREG (st.st_mode))
1056 if (st.st_uid == geteuid ())
1057 perm = (st.st_mode & 0100);
1058 else if (st.st_gid == getegid ())
1059 perm = (st.st_mode & 0010);
1060 else
1062 #ifdef HAVE_GETGROUPS
1063 register int i;
1064 for (i = 0; i < ngroups; ++i)
1065 if (groups[i] == st.st_gid)
1066 break;
1067 if (i < ngroups)
1068 perm = (st.st_mode & 0010);
1069 else
1070 #endif /* Have getgroups. */
1071 perm = (st.st_mode & 0001);
1074 if (perm != 0)
1075 return 1;
1078 path = p + 1;
1079 } while (*path != '\0');
1082 return 0;
1085 /* Replace the current process with one running the command in ARGV,
1086 with environment ENVP. This function does not return. */
1088 void
1089 exec_command (argv, envp)
1090 char **argv, **envp;
1092 char *shell, *path;
1093 PATH_VAR (program);
1094 register char **ep;
1096 shell = path = 0;
1097 for (ep = envp; *ep != 0; ++ep)
1099 if (shell == 0 && !strncmp(*ep, "SHELL=", 6))
1100 shell = &(*ep)[6];
1101 else if (path == 0 && !strncmp(*ep, "PATH=", 5))
1102 path = &(*ep)[5];
1103 else if (path != 0 && shell != 0)
1104 break;
1107 /* Be the user, permanently. */
1108 child_access ();
1110 if (!search_path (argv[0], path, program))
1111 error ("%s: Command not found", argv[0]);
1112 else
1114 /* Run the program. */
1115 execve (program, argv, envp);
1117 if (errno == ENOEXEC)
1119 PATH_VAR (shell_program);
1120 char *shell_path;
1121 if (shell == 0)
1122 shell_path = default_shell;
1123 else
1125 if (search_path (shell, path, shell_program))
1126 shell_path = shell_program;
1127 else
1129 shell_path = 0;
1130 error ("%s: Shell program not found", shell);
1134 if (shell_path != 0)
1136 char **new_argv;
1137 int argc;
1139 argc = 1;
1140 while (argv[argc] != 0)
1141 ++argc;
1143 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1144 new_argv[0] = shell_path;
1145 new_argv[1] = program;
1146 while (argc > 0)
1148 new_argv[1 + argc] = argv[argc];
1149 --argc;
1152 execve (shell_path, new_argv, envp);
1153 perror_with_name ("execve: ", shell_path);
1156 else
1157 perror_with_name ("execve: ", program);
1160 _exit (127);
1163 /* Figure out the argument list necessary to run LINE as a command.
1164 Try to avoid using a shell. This routine handles only ' quoting.
1165 Starting quotes may be escaped with a backslash. If any of the
1166 characters in sh_chars[] is seen, or any of the builtin commands
1167 listed in sh_cmds[] is the first word of a line, the shell is used.
1169 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1170 If *RESTP is NULL, newlines will be ignored.
1172 SHELL is the shell to use, or nil to use the default shell.
1173 IFS is the value of $IFS, or nil (meaning the default). */
1175 static char **
1176 construct_command_argv_internal (line, restp, shell, ifs)
1177 char *line, **restp;
1178 char *shell, *ifs;
1180 static char sh_chars[] = "#;\"*?[]&|<>(){}=$`";
1181 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1182 "logout", "set", "umask", "wait", "while", "for",
1183 "case", "if", ":", ".", "break", "continue",
1184 "export", "read", "readonly", "shift", "times",
1185 "trap", "switch", 0 };
1186 register int i;
1187 register char *p;
1188 register char *ap;
1189 char *end;
1190 int instring;
1191 char **new_argv = 0;
1193 if (restp != NULL)
1194 *restp = NULL;
1196 /* Make sure not to bother processing an empty line. */
1197 while (isblank (*line))
1198 ++line;
1199 if (*line == '\0')
1200 return 0;
1202 /* See if it is safe to parse commands internally. */
1203 if (shell == 0)
1204 shell = default_shell;
1205 else if (strcmp (shell, default_shell))
1206 goto slow;
1208 if (ifs != 0)
1209 for (ap = ifs; *ap != '\0'; ++ap)
1210 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1211 goto slow;
1213 i = strlen (line) + 1;
1215 /* More than 1 arg per character is impossible. */
1216 new_argv = (char **) xmalloc (i * sizeof (char *));
1218 /* All the args can fit in a buffer as big as LINE is. */
1219 ap = new_argv[0] = (char *) xmalloc (i);
1220 end = ap + i;
1222 /* I is how many complete arguments have been found. */
1223 i = 0;
1224 instring = 0;
1225 for (p = line; *p != '\0'; ++p)
1227 if (ap > end)
1228 abort ();
1230 if (instring)
1232 /* Inside a string, just copy any char except a closing quote. */
1233 if (*p == '\'')
1234 instring = 0;
1235 else
1236 *ap++ = *p;
1238 else if (index (sh_chars, *p) != 0)
1239 /* Not inside a string, but it's a special char. */
1240 goto slow;
1241 else
1242 /* Not a special char. */
1243 switch (*p)
1245 case '\\':
1246 /* Backslash-newline combinations are eaten. */
1247 if (p[1] == '\n')
1249 /* Eat the backslash, the newline, and following whitespace,
1250 replacing it all with a single space. */
1251 p += 2;
1253 /* If there is a tab after a backslash-newline,
1254 remove it from the source line which will be echoed,
1255 since it was most likely used to line
1256 up the continued line with the previous one. */
1257 if (*p == '\t')
1258 strcpy (p, p + 1);
1260 if (ap != new_argv[i])
1261 /* Treat this as a space, ending the arg.
1262 But if it's at the beginning of the arg, it should
1263 just get eaten, rather than becoming an empty arg. */
1264 goto end_of_arg;
1265 else
1266 p = next_token (p) - 1;
1268 else if (p[1] != '\0')
1269 /* Copy and skip the following char. */
1270 *ap++ = *++p;
1271 break;
1273 case '\'':
1274 instring = 1;
1275 break;
1277 case '\n':
1278 if (restp != NULL)
1280 /* End of the command line. */
1281 *restp = p;
1282 goto end_of_line;
1284 else
1285 /* Newlines are not special. */
1286 *ap++ = '\n';
1287 break;
1289 case ' ':
1290 case '\t':
1291 end_of_arg:
1292 /* We have the end of an argument.
1293 Terminate the text of the argument. */
1294 *ap++ = '\0';
1295 new_argv[++i] = ap;
1296 /* If this argument is the command name,
1297 see if it is a built-in shell command.
1298 If so, have the shell handle it. */
1299 if (i == 1)
1301 register int j;
1302 for (j = 0; sh_cmds[j] != 0; ++j)
1303 if (streq (sh_cmds[j], new_argv[0]))
1304 goto slow;
1307 /* Ignore multiple whitespace chars. */
1308 p = next_token (p);
1309 /* Next iteration should examine the first nonwhite char. */
1310 --p;
1311 break;
1313 default:
1314 *ap++ = *p;
1315 break;
1318 end_of_line:
1320 if (instring)
1321 /* Let the shell deal with an unterminated quote. */
1322 goto slow;
1324 /* Terminate the last argument and the argument list. */
1326 *ap = '\0';
1327 if (new_argv[i][0] != '\0')
1328 ++i;
1329 new_argv[i] = 0;
1331 if (i == 1)
1333 register int j;
1334 for (j = 0; sh_cmds[j] != 0; ++j)
1335 if (streq (sh_cmds[j], new_argv[0]))
1336 goto slow;
1339 if (new_argv[0] == 0)
1340 /* Line was empty. */
1341 return 0;
1342 else
1343 return new_argv;
1345 slow:;
1346 /* We must use the shell. */
1348 if (new_argv != 0)
1350 /* Free the old argument list we were working on. */
1351 free (new_argv[0]);
1352 free (new_argv);
1356 /* SHELL may be a multi-word command. Construct a command line
1357 "SHELL -c LINE", with all special chars in LINE escaped.
1358 Then recurse, expanding this command line to get the final
1359 argument list. */
1361 unsigned int shell_len = strlen (shell);
1362 static char minus_c[] = " -c ";
1363 unsigned int line_len = strlen (line);
1365 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1366 + (line_len * 2) + 1);
1368 ap = new_line;
1369 bcopy (shell, ap, shell_len);
1370 ap += shell_len;
1371 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1372 ap += sizeof (minus_c) - 1;
1373 for (p = line; *p != '\0'; ++p)
1375 if (restp != NULL && *p == '\n')
1377 *restp = p;
1378 break;
1380 else if (*p == '\\' && p[1] == '\n')
1382 /* Eat the backslash, the newline, and following whitespace,
1383 replacing it all with a single space (which is escaped
1384 from the shell). */
1385 p += 2;
1387 /* If there is a tab after a backslash-newline,
1388 remove it from the source line which will be echoed,
1389 since it was most likely used to line
1390 up the continued line with the previous one. */
1391 if (*p == '\t')
1392 strcpy (p, p + 1);
1394 p = next_token (p);
1395 --p;
1396 *ap++ = '\\';
1397 *ap++ = ' ';
1398 continue;
1401 if (*p == '\\' || *p == '\''
1402 || isspace (*p)
1403 || index (sh_chars, *p) != 0)
1404 *ap++ = '\\';
1405 *ap++ = *p;
1407 *ap = '\0';
1409 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1410 (char *) 0, (char *) 0);
1413 return new_argv;
1416 /* Figure out the argument list necessary to run LINE as a command.
1417 Try to avoid using a shell. This routine handles only ' quoting.
1418 Starting quotes may be escaped with a backslash. If any of the
1419 characters in sh_chars[] is seen, or any of the builtin commands
1420 listed in sh_cmds[] is the first word of a line, the shell is used.
1422 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1423 If *RESTP is NULL, newlines will be ignored.
1425 FILE is the target whose commands these are. It is used for
1426 variable expansion for $(SHELL) and $(IFS). */
1428 char **
1429 construct_command_argv (line, restp, file)
1430 char *line, **restp;
1431 struct file *file;
1433 char *shell, *ifs;
1434 char **argv;
1437 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1438 int save = warn_undefined_variables_flag;
1439 warn_undefined_variables_flag = 0;
1441 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1442 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1444 warn_undefined_variables_flag = save;
1447 argv = construct_command_argv_internal (line, restp, shell, ifs);
1449 free (shell);
1450 free (ifs);
1452 return argv;
1455 #ifndef HAVE_DUP2
1457 dup2 (old, new)
1458 int old, new;
1460 int fd;
1462 (void) close (new);
1463 fd = dup (old);
1464 if (fd != new)
1466 (void) close (fd);
1467 errno = EMFILE;
1468 return -1;
1471 return fd;
1473 #endif