Formerly compatMakefile.~80~
[make.git] / job.c
blobee10f062a0f80481bc0bde05efcd42d86eafabfa
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;
208 if (err && dead_children == 0)
210 /* We might block for a while, so let the user know why. */
211 fflush (stdout);
212 error ("*** Waiting for unfinished jobs....");
215 /* We have one less dead child to reap.
216 The test and decrement are not atomic; if it is compiled into:
217 register = dead_children - 1;
218 dead_children = register;
219 a SIGCHLD could come between the two instructions.
220 child_handler increments dead_children.
221 The second instruction here would lose that increment. But the
222 only effect of dead_children being wrong is that we might wait
223 longer than necessary to reap a child, and lose some parallelism;
224 and we might print the "Waiting for unfinished jobs" message above
225 when not necessary. */
227 if (dead_children != 0)
228 --dead_children;
230 if (debug_flag)
231 for (c = children; c != 0; c = c->next)
232 printf ("Live child 0x%08lx PID %d%s\n",
233 (unsigned long int) c,
234 c->pid, c->remote ? " (remote)" : "");
236 /* First, check for remote children. */
237 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
238 if (pid <= 0)
240 /* No remote children. Check for local children. */
242 #ifdef WAIT_NOHANG
243 if (!block)
244 pid = WAIT_NOHANG (&status);
245 else
246 #endif
247 pid = wait (&status);
249 if (pid < 0)
251 #ifdef EINTR
252 if (errno == EINTR)
253 continue;
254 #endif
255 pfatal_with_name ("wait");
257 else if (pid == 0)
258 /* No local children. */
259 break;
260 else
262 /* Chop the status word up. */
263 exit_code = WEXITSTATUS (status);
264 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
265 coredump = WCOREDUMP (status);
268 else
269 /* We got a remote child. */
270 remote = 1;
272 /* Check if this is the child of the `shell' function. */
273 if (!remote && pid == shell_function_pid)
275 /* It is. Leave an indicator for the `shell' function. */
276 if (exit_sig == 0 && exit_code == 127)
277 shell_function_completed = -1;
278 else
279 shell_function_completed = 1;
280 break;
283 child_failed = exit_sig != 0 || exit_code != 0;
285 /* Search for a child matching the deceased one. */
286 lastc = 0;
287 for (c = children; c != 0; lastc = c, c = c->next)
288 if (c->remote == remote && c->pid == pid)
289 break;
291 if (c == 0)
293 /* An unknown child died. */
294 char buf[100];
295 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
296 if (child_failed)
297 child_error (buf, exit_code, exit_sig, coredump,
298 ignore_errors_flag);
299 else
300 error ("%s finished.", buf);
302 else
304 if (debug_flag)
305 printf ("Reaping %s child 0x%08lx PID %d%s\n",
306 child_failed ? "losing" : "winning",
307 (unsigned long int) c,
308 c->pid, c->remote ? " (remote)" : "");
310 /* If this child had the good stdin, say it is now free. */
311 if (c->good_stdin)
312 good_stdin_used = 0;
314 if (child_failed && !c->noerror && !ignore_errors_flag)
316 /* The commands failed. Write an error message,
317 delete non-precious targets, and abort. */
318 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
319 c->file->update_status = 1;
320 if (exit_sig != 0)
321 delete_child_targets (c);
323 else
325 if (child_failed)
327 /* The commands failed, but we don't care. */
328 child_error (c->file->name,
329 exit_code, exit_sig, coredump, 1);
330 child_failed = 0;
333 /* If there are more commands to run, try to start them. */
334 if (job_next_command (c))
336 if (handling_fatal_signal)
338 /* Never start new commands while we are dying.
339 Since there are more commands that wanted to be run,
340 the target was not completely remade. So we treat
341 this as if a command had failed. */
342 c->file->command_state = cs_finished;
343 c->file->update_status = 1;
345 else
347 /* Check again whether to start remotely.
348 Whether or not we want to changes over time.
349 Also, start_remote_job may need state set up
350 by start_remote_job_p. */
351 c->remote = start_remote_job_p ();
352 start_job_command (c);
356 switch (c->file->command_state)
358 case cs_running:
359 /* Successfully started. Loop to reap more children. */
360 continue;
362 case cs_finished:
363 if (c->file->update_status != 0)
364 /* We failed to start the commands. */
365 delete_child_targets (c);
366 break;
368 default:
369 error ("internal error: `%s' has bogus command_state \
370 %d in reap_children",
371 c->file->name, (int) c->file->command_state);
372 abort ();
373 break;
377 if (! handling_fatal_signal)
378 /* Notice if the target of the commands has been changed. */
379 notice_finished_file (c->file);
381 if (debug_flag)
382 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
383 (unsigned long int) c,
384 c->pid, c->remote ? " (remote)" : "");
386 /* Remove the child from the chain and free it. */
387 if (lastc == 0)
388 children = c->next;
389 else
390 lastc->next = c->next;
391 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
392 free_child (c);
394 /* There is now another slot open. */
395 --job_slots_used;
397 /* If the job failed, and the -k flag was not given, die,
398 unless we are already in the process of dying. */
399 if (!err && child_failed && !keep_going_flag)
400 die (1);
403 /* Only block for one child. */
404 block = 0;
408 /* Free the storage allocated for CHILD. */
410 static void
411 free_child (child)
412 register struct child *child;
414 if (child->command_lines != 0)
416 register unsigned int i;
417 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
418 free (child->command_lines[i]);
419 free ((char *) child->command_lines);
422 if (child->environment != 0)
424 register char **ep = child->environment;
425 while (*ep != 0)
426 free (*ep++);
427 free ((char *) child->environment);
430 free ((char *) child);
433 #ifdef POSIX
434 extern sigset_t fatal_signal_set;
436 void
437 unblock_sigs ()
439 sigset_t empty;
440 sigemptyset (&empty);
441 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
443 #endif
445 /* Start a job to run the commands specified in CHILD.
446 CHILD is updated to reflect the commands and ID of the child process. */
448 static void
449 start_job_command (child)
450 register struct child *child;
452 static int bad_stdin = -1;
453 register char *p;
454 int flags = child->file->cmds->lines_flags[child->command_line - 1];
455 char **argv;
457 p = child->command_ptr;
458 child->noerror = flags & COMMANDS_NOERROR;
459 while (*p != '\0')
461 if (*p == '@')
462 flags |= COMMANDS_SILENT;
463 else if (*p == '-')
464 child->noerror = 1;
465 else if (!isblank (*p) && *p != '+')
466 break;
467 ++p;
470 /* If -q was given, just say that updating `failed'. */
471 if (question_flag && !(flags & COMMANDS_RECURSE))
472 goto error;
474 /* There may be some preceding whitespace left if there
475 was nothing but a backslash on the first line. */
476 p = next_token (p);
478 /* Figure out an argument list from this command line. */
481 char *end;
482 argv = construct_command_argv (p, &end, child->file);
483 if (end == NULL)
484 child->command_ptr = NULL;
485 else
487 *end++ = '\0';
488 child->command_ptr = end;
492 if (touch_flag && !(flags & COMMANDS_RECURSE))
494 /* Go on to the next command. It might be the recursive one.
495 We construct ARGV only to find the end of the command line. */
496 free (argv[0]);
497 free ((char *) argv);
498 argv = 0;
501 if (argv == 0)
503 /* This line has no commands. Go to the next. */
504 if (job_next_command (child))
505 start_job_command (child);
506 return;
509 /* Print out the command. */
511 if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
512 puts (p);
514 /* Tell update_goal_chain that a command has been started on behalf of
515 this target. It is important that this happens here and not in
516 reap_children (where we used to do it), because reap_children might be
517 reaping children from a different target. We want this increment to
518 guaranteedly indicate that a command was started for the dependency
519 chain (i.e., update_file recursion chain) we are processing. */
521 ++commands_started;
523 /* If -n was given, recurse to get the next line in the sequence. */
525 if (just_print_flag && !(flags & COMMANDS_RECURSE))
527 free (argv[0]);
528 free ((char *) argv);
529 if (job_next_command (child))
530 start_job_command (child);
531 return;
534 /* Flush the output streams so they won't have things written twice. */
536 fflush (stdout);
537 fflush (stderr);
539 /* Set up a bad standard input that reads from a broken pipe. */
541 if (bad_stdin == -1)
543 /* Make a file descriptor that is the read end of a broken pipe.
544 This will be used for some children's standard inputs. */
545 int pd[2];
546 if (pipe (pd) == 0)
548 /* Close the write side. */
549 (void) close (pd[1]);
550 /* Save the read side. */
551 bad_stdin = pd[0];
555 /* Decide whether to give this child the `good' standard input
556 (one that points to the terminal or whatever), or the `bad' one
557 that points to the read side of a broken pipe. */
559 child->good_stdin = !good_stdin_used;
560 if (child->good_stdin)
561 good_stdin_used = 1;
563 child->deleted = 0;
565 /* Set up the environment for the child. */
566 if (child->environment == 0)
567 child->environment = target_environment (child->file);
569 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
570 if (child->remote)
572 int is_remote, id, used_stdin;
573 if (start_remote_job (argv, child->environment,
574 child->good_stdin ? 0 : bad_stdin,
575 &is_remote, &id, &used_stdin))
576 goto error;
577 else
579 if (child->good_stdin && !used_stdin)
581 child->good_stdin = 0;
582 good_stdin_used = 0;
584 child->remote = is_remote;
585 child->pid = id;
588 else
590 /* Fork the child process. */
592 #ifdef POSIX
593 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
594 #else
595 #ifdef HAVE_SIGSETMASK
596 (void) sigblock (fatal_signal_mask);
597 #endif
598 #endif
600 child->remote = 0;
601 child->pid = vfork ();
602 if (child->pid == 0)
604 /* We are the child side. */
605 unblock_sigs ();
606 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
607 argv, child->environment);
609 else if (child->pid < 0)
611 /* Fork failed! */
612 unblock_sigs ();
613 perror_with_name ("vfork", "");
614 goto error;
618 /* We are the parent side. Set the state to
619 say the commands are running and return. */
621 child->file->command_state = cs_running;
623 /* Free the storage used by the child's argument list. */
625 free (argv[0]);
626 free ((char *) argv);
628 return;
630 error:;
631 child->file->update_status = 1;
632 child->file->command_state = cs_finished;
635 /* Try to start a child running.
636 Returns nonzero if the child was started (and maybe finished), or zero if
637 the load was too high and the child was put on the `waiting_jobs' chain. */
639 static int
640 start_waiting_job (c)
641 struct child *c;
643 /* If we can start a job remotely, we always want to, and don't care about
644 the local load average. We record that the job should be started
645 remotely in C->remote for start_job_command to test. */
647 c->remote = start_remote_job_p ();
649 /* If this job is to be started locally, and we are already running
650 some jobs, make this one wait if the load average is too high. */
651 if (!c->remote && job_slots_used > 0 && load_too_high ())
653 /* Put this child on the chain of children waiting
654 for the load average to go down. */
655 c->file->command_state = cs_running;
656 c->next = waiting_jobs;
657 waiting_jobs = c;
658 return 0;
661 /* Start the first command; reap_children will run later command lines. */
662 start_job_command (c);
664 switch (c->file->command_state)
666 case cs_running:
667 c->next = children;
668 if (debug_flag)
669 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
670 (unsigned long int) c,
671 c->pid, c->remote ? " (remote)" : "");
672 children = c;
673 /* One more job slot is in use. */
674 ++job_slots_used;
675 unblock_sigs ();
676 break;
678 case cs_finished:
679 notice_finished_file (c->file);
680 free_child (c);
681 break;
683 default:
684 error ("internal error: `%s' command_state == %d in new_job",
685 c->file->name, (int) c->file->command_state);
686 abort ();
687 break;
690 return 1;
693 /* Create a `struct child' for FILE and start its commands running. */
695 void
696 new_job (file)
697 register struct file *file;
699 register struct commands *cmds = file->cmds;
700 register struct child *c;
701 char **lines;
702 register unsigned int i;
704 /* Let any previously decided-upon jobs that are waiting
705 for the load to go down start before this new one. */
706 start_waiting_jobs ();
708 /* Reap any children that might have finished recently. */
709 reap_children (0, 0);
711 /* Chop the commands up into lines if they aren't already. */
712 chop_commands (cmds);
714 if (job_slots != 0)
715 /* Wait for a job slot to be freed up. */
716 while (job_slots_used == job_slots)
717 reap_children (1, 0);
719 /* Expand the command lines and store the results in LINES. */
720 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
721 for (i = 0; i < cmds->ncommand_lines; ++i)
723 /* Collapse backslash-newline combinations that are inside variable
724 or function references. These are left alone by the parser so
725 that they will appear in the echoing of commands (where they look
726 nice); and collapsed by construct_command_argv when it tokenizes.
727 But letting them survive inside function invocations loses because
728 we don't want the functions to see them as part of the text. */
730 char *in, *out, *ref;
732 /* IN points to where in the line we are scanning.
733 OUT points to where in the line we are writing.
734 When we collapse a backslash-newline combination,
735 IN gets ahead out OUT. */
737 in = out = cmds->command_lines[i];
738 while ((ref = index (in, '$')) != 0)
740 ++ref; /* Move past the $. */
742 if (out != in)
743 /* Copy the text between the end of the last chunk
744 we processed (where IN points) and the new chunk
745 we are about to process (where REF points). */
746 bcopy (in, out, ref - in);
748 /* Move both pointers past the boring stuff. */
749 out += ref - in;
750 in = ref;
752 if (*ref == '(' || *ref == '{')
754 char openparen = *ref;
755 char closeparen = openparen == '(' ? ')' : '}';
756 int count;
757 char *p;
759 *out++ = *in++; /* Copy OPENPAREN. */
760 /* IN now points past the opening paren or brace.
761 Count parens or braces until it is matched. */
762 count = 0;
763 while (*in != '\0')
765 if (*in == closeparen && --count < 0)
766 break;
767 else if (*in == '\\' && in[1] == '\n')
769 /* We have found a backslash-newline inside a
770 variable or function reference. Eat it and
771 any following whitespace. */
773 int quoted = 0;
774 for (p = in - 1; p > ref && *p == '\\'; --p)
775 quoted = !quoted;
777 if (quoted)
778 /* There were two or more backslashes, so this is
779 not really a continuation line. We don't collapse
780 the quoting backslashes here as is done in
781 collapse_continuations, because the line will
782 be collapsed again after expansion. */
783 *out++ = *in++;
784 else
786 /* Skip the backslash, newline and
787 any following whitespace. */
788 in = next_token (in + 2);
790 /* Discard any preceding whitespace that has
791 already been written to the output. */
792 while (out > ref && isblank (out[-1]))
793 --out;
795 /* Replace it all with a single space. */
796 *out++ = ' ';
799 else
801 if (*in == openparen)
802 ++count;
804 *out++ = *in++;
810 /* There are no more references in this line to worry about.
811 Copy the remaining uninteresting text to the output. */
812 if (out != in)
813 strcpy (out, in);
815 /* Finally, expand the line. */
816 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
817 file);
820 /* Start the command sequence, record it in a new
821 `struct child', and add that to the chain. */
823 c = (struct child *) xmalloc (sizeof (struct child));
824 c->file = file;
825 c->command_lines = lines;
826 c->command_line = 0;
827 c->command_ptr = 0;
828 c->environment = 0;
830 /* Fetch the first command line to be run. */
831 if (! job_next_command (c))
832 /* There were no commands! */
833 free_child (c);
834 else
836 /* The job is now primed. Start it running. */
837 start_waiting_job (c);
839 if (job_slots == 1)
840 /* Since there is only one job slot, make things run linearly.
841 Wait for the child to die, setting the state to `cs_finished'. */
842 while (file->command_state == cs_running)
843 reap_children (1, 0);
847 /* Move CHILD's pointers to the next command for it to execute.
848 Returns nonzero if there is another command. */
850 static int
851 job_next_command (child)
852 struct child *child;
854 if (child->command_ptr == 0 || *child->command_ptr == '\0')
856 /* There are no more lines in the expansion of this line. */
857 if (child->command_line == child->file->cmds->ncommand_lines)
859 /* There are no more lines to be expanded. */
860 child->command_ptr = 0;
861 child->file->command_state = cs_finished;
862 child->file->update_status = 0;
863 return 0;
865 else
866 /* Get the next line to run. */
867 child->command_ptr = child->command_lines[child->command_line++];
869 return 1;
872 static int
873 load_too_high ()
875 extern int getloadavg ();
876 double load;
878 if (max_load_average < 0)
879 return 0;
881 make_access ();
882 if (getloadavg (&load, 1) != 1)
884 static int lossage = -1;
885 /* Complain only once for the same error. */
886 if (lossage == -1 || errno != lossage)
888 if (errno == 0)
889 /* An errno value of zero means getloadavg is just unsupported. */
890 error ("cannot enforce load limits on this operating system");
891 else
892 perror_with_name ("cannot enforce load limit: ", "getloadavg");
894 lossage = errno;
895 load = 0;
897 user_access ();
899 return load >= max_load_average;
902 /* Start jobs that are waiting for the load to be lower. */
904 void
905 start_waiting_jobs ()
907 struct child *job;
909 if (waiting_jobs == 0)
910 return;
914 /* Check for recently deceased descendants. */
915 reap_children (0, 0);
917 /* Take a job off the waiting list. */
918 job = waiting_jobs;
919 waiting_jobs = job->next;
921 /* Try to start that job. We break out of the loop as soon
922 as start_waiting_job puts one back on the waiting list. */
923 } while (start_waiting_job (job) && waiting_jobs != 0);
926 /* Replace the current process with one executing the command in ARGV.
927 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
928 the environment of the new program. This function does not return. */
930 void
931 child_execute_job (stdin_fd, stdout_fd, argv, envp)
932 int stdin_fd, stdout_fd;
933 char **argv, **envp;
935 if (stdin_fd != 0)
936 (void) dup2 (stdin_fd, 0);
937 if (stdout_fd != 1)
938 (void) dup2 (stdout_fd, 1);
940 /* Free up file descriptors. */
942 register int d;
943 int max = getdtablesize ();
944 for (d = 3; d < max; ++d)
945 (void) close (d);
948 /* Run the command. */
949 exec_command (argv, envp);
952 /* Search PATH for FILE.
953 If successful, store the full pathname in PROGRAM and return 1.
954 If not sucessful, return zero. */
956 static int
957 search_path (file, path, program)
958 char *file, *path, *program;
960 if (path == 0 || path[0] == '\0')
961 path = default_path;
963 if (index (file, '/') != 0)
965 strcpy (program, file);
966 return 1;
968 else
970 unsigned int len;
972 #ifdef HAVE_GETGROUPS
973 #ifndef HAVE_UNISTD_H
974 extern int getgroups ();
975 #endif
976 static int ngroups = -1;
977 #ifdef NGROUPS_MAX
978 static GETGROUPS_T groups[NGROUPS_MAX];
979 #define ngroups_max NGROUPS_MAX
980 #else
981 static GETGROUPS_T *groups = 0;
982 static int ngroups_max;
983 if (groups == 0)
985 ngroups_max = GET_NGROUPS_MAX;
986 groups = (GETGROUPS_T *) malloc (ngroups_max * sizeof (GETGROUPS_T));
988 #endif
989 if (groups != 0 && ngroups == -1)
990 ngroups = getgroups (ngroups_max, groups);
991 #endif /* Have getgroups. */
993 len = strlen (file) + 1;
996 struct stat st;
997 int perm;
998 char *p;
1000 p = index (path, ':');
1001 if (p == 0)
1002 p = path + strlen (path);
1004 if (p == path)
1005 bcopy (file, program, len);
1006 else
1008 bcopy (path, program, p - path);
1009 program[p - path] = '/';
1010 bcopy (file, program + (p - path) + 1, len);
1013 if (stat (program, &st) == 0
1014 && S_ISREG (st.st_mode))
1016 if (st.st_uid == geteuid ())
1017 perm = (st.st_mode & 0100);
1018 else if (st.st_gid == getegid ())
1019 perm = (st.st_mode & 0010);
1020 else
1022 #ifdef HAVE_GETGROUPS
1023 register int i;
1024 for (i = 0; i < ngroups; ++i)
1025 if (groups[i] == st.st_gid)
1026 break;
1027 if (i < ngroups)
1028 perm = (st.st_mode & 0010);
1029 else
1030 #endif /* Have getgroups. */
1031 perm = (st.st_mode & 0001);
1034 if (perm != 0)
1035 return 1;
1038 path = p + 1;
1039 } while (*path != '\0');
1042 return 0;
1045 /* Replace the current process with one running the command in ARGV,
1046 with environment ENVP. This function does not return. */
1048 void
1049 exec_command (argv, envp)
1050 char **argv, **envp;
1052 char *shell, *path;
1053 PATH_VAR (program);
1054 register char **ep;
1056 shell = path = 0;
1057 for (ep = envp; *ep != 0; ++ep)
1059 if (shell == 0 && !strncmp(*ep, "SHELL=", 6))
1060 shell = &(*ep)[6];
1061 else if (path == 0 && !strncmp(*ep, "PATH=", 5))
1062 path = &(*ep)[5];
1063 else if (path != 0 && shell != 0)
1064 break;
1067 /* Be the user, permanently. */
1068 child_access ();
1070 if (!search_path (argv[0], path, program))
1071 error ("%s: Command not found", argv[0]);
1072 else
1074 /* Run the program. */
1075 execve (program, argv, envp);
1077 if (errno == ENOEXEC)
1079 PATH_VAR (shell_program);
1080 char *shell_path;
1081 if (shell == 0)
1082 shell_path = default_shell;
1083 else
1085 if (search_path (shell, path, shell_program))
1086 shell_path = shell_program;
1087 else
1089 shell_path = 0;
1090 error ("%s: Shell program not found", shell);
1094 if (shell_path != 0)
1096 char **new_argv;
1097 int argc;
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_path;
1105 new_argv[1] = program;
1106 while (argc > 0)
1108 new_argv[1 + argc] = argv[argc];
1109 --argc;
1112 execve (shell_path, new_argv, envp);
1113 perror_with_name ("execve: ", shell_path);
1116 else
1117 perror_with_name ("execve: ", program);
1120 _exit (127);
1123 /* Figure out the argument list necessary to run LINE as a command.
1124 Try to avoid using a shell. This routine handles only ' quoting.
1125 Starting quotes may be escaped with a backslash. If any of the
1126 characters in sh_chars[] is seen, or any of the builtin commands
1127 listed in sh_cmds[] is the first word of a line, the shell is used.
1129 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1130 If *RESTP is NULL, newlines will be ignored.
1132 SHELL is the shell to use, or nil to use the default shell.
1133 IFS is the value of $IFS, or nil (meaning the default). */
1135 static char **
1136 construct_command_argv_internal (line, restp, shell, ifs)
1137 char *line, **restp;
1138 char *shell, *ifs;
1140 static char sh_chars[] = "#;\"*?[]&|<>(){}=$`";
1141 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1142 "logout", "set", "umask", "wait", "while", "for",
1143 "case", "if", ":", ".", "break", "continue",
1144 "export", "read", "readonly", "shift", "times",
1145 "trap", "switch", 0 };
1146 register int i;
1147 register char *p;
1148 register char *ap;
1149 char *end;
1150 int instring;
1151 char **new_argv = 0;
1153 if (restp != NULL)
1154 *restp = NULL;
1156 /* Make sure not to bother processing an empty line. */
1157 while (isblank (*line))
1158 ++line;
1159 if (*line == '\0')
1160 return 0;
1162 /* See if it is safe to parse commands internally. */
1163 if (shell == 0)
1164 shell = default_shell;
1165 else if (strcmp (shell, default_shell))
1166 goto slow;
1168 if (ifs != 0)
1169 for (ap = ifs; *ap != '\0'; ++ap)
1170 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1171 goto slow;
1173 i = strlen (line) + 1;
1175 /* More than 1 arg per character is impossible. */
1176 new_argv = (char **) xmalloc (i * sizeof (char *));
1178 /* All the args can fit in a buffer as big as LINE is. */
1179 ap = new_argv[0] = (char *) xmalloc (i);
1180 end = ap + i;
1182 /* I is how many complete arguments have been found. */
1183 i = 0;
1184 instring = 0;
1185 for (p = line; *p != '\0'; ++p)
1187 if (ap > end)
1188 abort ();
1190 if (instring)
1192 /* Inside a string, just copy any char except a closing quote. */
1193 if (*p == '\'')
1194 instring = 0;
1195 else
1196 *ap++ = *p;
1198 else if (index (sh_chars, *p) != 0)
1199 /* Not inside a string, but it's a special char. */
1200 goto slow;
1201 else
1202 /* Not a special char. */
1203 switch (*p)
1205 case '\\':
1206 /* Backslash-newline combinations are eaten. */
1207 if (p[1] == '\n')
1209 /* Eat the backslash, the newline, and following whitespace,
1210 replacing it all with a single space. */
1211 p += 2;
1213 /* If there is a tab after a backslash-newline,
1214 remove it from the source line which will be echoed,
1215 since it was most likely used to line
1216 up the continued line with the previous one. */
1217 if (*p == '\t')
1218 strcpy (p, p + 1);
1220 if (ap != new_argv[i])
1221 /* Treat this as a space, ending the arg.
1222 But if it's at the beginning of the arg, it should
1223 just get eaten, rather than becoming an empty arg. */
1224 goto end_of_arg;
1225 else
1226 p = next_token (p) - 1;
1228 else if (p[1] != '\0')
1229 /* Copy and skip the following char. */
1230 *ap++ = *++p;
1231 break;
1233 case '\'':
1234 instring = 1;
1235 break;
1237 case '\n':
1238 if (restp != NULL)
1240 /* End of the command line. */
1241 *restp = p;
1242 goto end_of_line;
1244 else
1245 /* Newlines are not special. */
1246 *ap++ = '\n';
1247 break;
1249 case ' ':
1250 case '\t':
1251 end_of_arg:
1252 /* We have the end of an argument.
1253 Terminate the text of the argument. */
1254 *ap++ = '\0';
1255 new_argv[++i] = ap;
1256 /* If this argument is the command name,
1257 see if it is a built-in shell command.
1258 If so, have the shell handle it. */
1259 if (i == 1)
1261 register int j;
1262 for (j = 0; sh_cmds[j] != 0; ++j)
1263 if (streq (sh_cmds[j], new_argv[0]))
1264 goto slow;
1267 /* Ignore multiple whitespace chars. */
1268 p = next_token (p);
1269 /* Next iteration should examine the first nonwhite char. */
1270 --p;
1271 break;
1273 default:
1274 *ap++ = *p;
1275 break;
1278 end_of_line:
1280 if (instring)
1281 /* Let the shell deal with an unterminated quote. */
1282 goto slow;
1284 /* Terminate the last argument and the argument list. */
1286 *ap = '\0';
1287 if (new_argv[i][0] != '\0')
1288 ++i;
1289 new_argv[i] = 0;
1291 if (i == 1)
1293 register int j;
1294 for (j = 0; sh_cmds[j] != 0; ++j)
1295 if (streq (sh_cmds[j], new_argv[0]))
1296 goto slow;
1299 if (new_argv[0] == 0)
1300 /* Line was empty. */
1301 return 0;
1302 else
1303 return new_argv;
1305 slow:;
1306 /* We must use the shell. */
1308 if (new_argv != 0)
1310 /* Free the old argument list we were working on. */
1311 free (new_argv[0]);
1312 free (new_argv);
1316 /* SHELL may be a multi-word command. Construct a command line
1317 "SHELL -c LINE", with all special chars in LINE escaped.
1318 Then recurse, expanding this command line to get the final
1319 argument list. */
1321 unsigned int shell_len = strlen (shell);
1322 static char minus_c[] = " -c ";
1323 unsigned int line_len = strlen (line);
1325 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1326 + (line_len * 2) + 1);
1328 ap = new_line;
1329 bcopy (shell, ap, shell_len);
1330 ap += shell_len;
1331 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1332 ap += sizeof (minus_c) - 1;
1333 for (p = line; *p != '\0'; ++p)
1335 if (restp != NULL && *p == '\n')
1337 *restp = p;
1338 break;
1340 else if (*p == '\\' && p[1] == '\n')
1342 /* Eat the backslash, the newline, and following whitespace,
1343 replacing it all with a single space (which is escaped
1344 from the shell). */
1345 p += 2;
1347 /* If there is a tab after a backslash-newline,
1348 remove it from the source line which will be echoed,
1349 since it was most likely used to line
1350 up the continued line with the previous one. */
1351 if (*p == '\t')
1352 strcpy (p, p + 1);
1354 p = next_token (p);
1355 --p;
1356 *ap++ = '\\';
1357 *ap++ = ' ';
1358 continue;
1361 if (*p == '\\' || *p == '\''
1362 || isspace (*p)
1363 || index (sh_chars, *p) != 0)
1364 *ap++ = '\\';
1365 *ap++ = *p;
1367 *ap = '\0';
1369 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1370 (char *) 0, (char *) 0);
1373 return new_argv;
1376 /* Figure out the argument list necessary to run LINE as a command.
1377 Try to avoid using a shell. This routine handles only ' quoting.
1378 Starting quotes may be escaped with a backslash. If any of the
1379 characters in sh_chars[] is seen, or any of the builtin commands
1380 listed in sh_cmds[] is the first word of a line, the shell is used.
1382 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1383 If *RESTP is NULL, newlines will be ignored.
1385 FILE is the target whose commands these are. It is used for
1386 variable expansion for $(SHELL) and $(IFS). */
1388 char **
1389 construct_command_argv (line, restp, file)
1390 char *line, **restp;
1391 struct file *file;
1393 char *shell, *ifs;
1394 char **argv;
1397 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1398 int save = warn_undefined_variables_flag;
1399 warn_undefined_variables_flag = 0;
1401 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1402 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1404 warn_undefined_variables_flag = save;
1407 argv = construct_command_argv_internal (line, restp, shell, ifs);
1409 free (shell);
1410 free (ifs);
1412 return argv;
1415 #ifndef HAVE_DUP2
1417 dup2 (old, new)
1418 int old, new;
1420 int fd;
1422 (void) close (new);
1423 fd = dup (old);
1424 if (fd != new)
1426 (void) close (fd);
1427 errno = EMFILE;
1428 return -1;
1431 return fd;
1433 #endif