(set_command_state): Actually set FILE->command_state.
[make.git] / job.c
blob51d3576f5d1929134078165bf54d64ecb90416c8
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 #ifdef __MSDOS__
32 #include <process.h>
33 static int dos_pid = 123;
34 static int dos_status;
35 static char *dos_bname;
36 static char *dos_bename;
37 static int dos_batch_file;
38 #endif /* MSDOS. */
41 /* If NGROUPS_MAX == 0 then try other methods for finding a real value. */
42 #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0
43 #undef NGROUPS_MAX
44 #endif /* NGROUPS_MAX == 0 */
46 #ifndef NGROUPS_MAX
47 #ifdef POSIX
48 #define GET_NGROUPS_MAX sysconf (_SC_NGROUPS_MAX)
49 #else /* Not POSIX. */
50 #define NGROUPS_MAX NGROUPS
51 #endif /* POSIX. */
52 #endif
54 #ifdef HAVE_SYS_WAIT_H
55 #include <sys/wait.h>
56 #endif
58 #ifdef HAVE_WAITPID
59 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
60 #else /* Don't have waitpid. */
61 #ifdef HAVE_WAIT3
62 #ifndef wait3
63 extern int wait3 ();
64 #endif
65 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
66 #endif /* Have wait3. */
67 #endif /* Have waitpid. */
69 #if !defined (wait) && !defined (POSIX)
70 extern int wait ();
71 #endif
73 #ifndef HAVE_UNION_WAIT
75 #define WAIT_T int
77 #ifndef WTERMSIG
78 #define WTERMSIG(x) ((x) & 0x7f)
79 #endif
80 #ifndef WCOREDUMP
81 #define WCOREDUMP(x) ((x) & 0x80)
82 #endif
83 #ifndef WEXITSTATUS
84 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
85 #endif
86 #ifndef WIFSIGNALED
87 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
88 #endif
89 #ifndef WIFEXITED
90 #define WIFEXITED(x) (WTERMSIG (x) == 0)
91 #endif
93 #else /* Have `union wait'. */
95 #define WAIT_T union wait
96 #ifndef WTERMSIG
97 #define WTERMSIG(x) ((x).w_termsig)
98 #endif
99 #ifndef WCOREDUMP
100 #define WCOREDUMP(x) ((x).w_coredump)
101 #endif
102 #ifndef WEXITSTATUS
103 #define WEXITSTATUS(x) ((x).w_retcode)
104 #endif
105 #ifndef WIFSIGNALED
106 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
107 #endif
108 #ifndef WIFEXITED
109 #define WIFEXITED(x) (WTERMSIG(x) == 0)
110 #endif
112 #endif /* Don't have `union wait'. */
115 #ifndef HAVE_UNISTD_H
116 extern int dup2 ();
117 extern int execve ();
118 extern void _exit ();
119 extern int geteuid (), getegid ();
120 extern int setgid (), getgid ();
121 #endif
123 #ifndef getdtablesize
124 #ifdef HAVE_GETDTABLESIZE
125 extern int getdtablesize ();
126 #else
127 #include <sys/param.h>
128 #define getdtablesize() NOFILE
129 #if !defined (NOFILE) && defined (NOFILES_MAX)
130 /* SCO 3.2 "devsys 4.2" defines NOFILES_{MIN,MAX} in lieu of NOFILE. */
131 #define NOFILE NOFILES_MAX
132 #endif
133 #endif
134 #endif
136 extern int getloadavg ();
137 extern int start_remote_job_p ();
138 extern int start_remote_job (), remote_status ();
140 RETSIGTYPE child_handler ();
141 static void free_child (), start_job_command ();
142 static int load_too_high (), job_next_command ();
144 /* Chain of all live (or recently deceased) children. */
146 struct child *children = 0;
148 /* Number of children currently running. */
150 unsigned int job_slots_used = 0;
152 /* Nonzero if the `good' standard input is in use. */
154 static int good_stdin_used = 0;
156 /* Chain of children waiting to run until the load average goes down. */
158 static struct child *waiting_jobs = 0;
160 /* Write an error message describing the exit status given in
161 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
162 Append "(ignored)" if IGNORED is nonzero. */
164 static void
165 child_error (target_name, exit_code, exit_sig, coredump, ignored)
166 char *target_name;
167 int exit_code, exit_sig, coredump;
168 int ignored;
170 if (exit_sig == 0)
171 error (ignored ? "[%s] Error %d (ignored)" :
172 "*** [%s] Error %d",
173 target_name, exit_code);
174 else
176 char *coredump_string = coredump ? " (core dumped)" : "";
177 if (exit_sig > 0 && exit_sig < NSIG)
178 error ("*** [%s] %s%s",
179 target_name, sys_siglist[exit_sig], coredump_string);
180 else
181 error ("*** [%s] Signal %d%s", target_name, exit_sig, coredump_string);
185 static unsigned int dead_children = 0;
187 /* Notice that a child died.
188 reap_children should be called when convenient. */
189 RETSIGTYPE
190 child_handler (sig)
191 int sig;
193 ++dead_children;
195 if (debug_flag)
196 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
199 extern int shell_function_pid, shell_function_completed;
201 /* Reap dead children, storing the returned status and the new command
202 state (`cs_finished') in the `file' member of the `struct child' for the
203 dead child, and removing the child from the chain. If BLOCK nonzero,
204 reap at least one child, waiting for it to die if necessary. If ERR is
205 nonzero, print an error message first. */
207 void
208 reap_children (block, err)
209 int block, err;
211 WAIT_T status;
213 while ((children != 0 || shell_function_pid != 0) &&
214 (block || dead_children > 0))
216 int remote = 0;
217 register int pid;
218 int exit_code, exit_sig, coredump;
219 register struct child *lastc, *c;
220 int child_failed;
221 int any_remote, any_local;
223 if (err && dead_children == 0)
225 /* We might block for a while, so let the user know why. */
226 fflush (stdout);
227 error ("*** Waiting for unfinished jobs....");
230 /* We have one less dead child to reap.
231 The test and decrement are not atomic; if it is compiled into:
232 register = dead_children - 1;
233 dead_children = register;
234 a SIGCHLD could come between the two instructions.
235 child_handler increments dead_children.
236 The second instruction here would lose that increment. But the
237 only effect of dead_children being wrong is that we might wait
238 longer than necessary to reap a child, and lose some parallelism;
239 and we might print the "Waiting for unfinished jobs" message above
240 when not necessary. */
242 if (dead_children != 0)
243 --dead_children;
245 any_remote = 0;
246 any_local = shell_function_pid != -1;
247 for (c = children; c != 0; c = c->next)
249 any_remote |= c->remote;
250 any_local |= ! c->remote;
251 if (debug_flag)
252 printf ("Live child 0x%08lx PID %d%s\n",
253 (unsigned long int) c,
254 c->pid, c->remote ? " (remote)" : "");
257 /* First, check for remote children. */
258 if (any_remote)
259 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
260 else
261 pid = 0;
262 if (pid < 0)
264 remote_status_lose:
265 #ifdef EINTR
266 if (errno == EINTR)
267 continue;
268 #endif
269 pfatal_with_name ("remote_status");
271 else if (pid == 0)
273 #ifndef __MSDOS__
274 /* No remote children. Check for local children. */
276 if (any_local)
278 #ifdef WAIT_NOHANG
279 if (!block)
280 pid = WAIT_NOHANG (&status);
281 else
282 #endif
283 pid = wait (&status);
285 else
286 pid = 0;
288 if (pid < 0)
290 #ifdef EINTR
291 if (errno == EINTR)
292 continue;
293 #endif
294 pfatal_with_name ("wait");
296 else if (pid == 0)
298 /* No local children. */
299 if (block && any_remote)
301 /* Now try a blocking wait for a remote child. */
302 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
303 if (pid < 0)
304 goto remote_status_lose;
305 else if (pid == 0)
306 /* No remote children either. Finally give up. */
307 break;
308 else
309 /* We got a remote child. */
310 remote = 1;
312 else
313 break;
315 else
317 /* Chop the status word up. */
318 exit_code = WEXITSTATUS (status);
319 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
320 coredump = WCOREDUMP (status);
322 #else /* MSDOS. */
323 /* Life is very different on MSDOS. */
324 pid = dos_pid - 1;
325 status = dos_status;
326 exit_code = dos_status;
327 exit_sig = 0;
328 coredump = 0;
329 #endif /* Not MSDOS. */
331 else
332 /* We got a remote child. */
333 remote = 1;
335 /* Check if this is the child of the `shell' function. */
336 if (!remote && pid == shell_function_pid)
338 /* It is. Leave an indicator for the `shell' function. */
339 if (exit_sig == 0 && exit_code == 127)
340 shell_function_completed = -1;
341 else
342 shell_function_completed = 1;
343 break;
346 child_failed = exit_sig != 0 || exit_code != 0;
348 /* Search for a child matching the deceased one. */
349 lastc = 0;
350 for (c = children; c != 0; lastc = c, c = c->next)
351 if (c->remote == remote && c->pid == pid)
352 break;
354 if (c == 0)
356 /* An unknown child died. */
357 char buf[100];
358 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
359 if (child_failed)
360 child_error (buf, exit_code, exit_sig, coredump,
361 ignore_errors_flag);
362 else
363 error ("%s finished.", buf);
365 else
367 if (debug_flag)
368 printf ("Reaping %s child 0x%08lx PID %d%s\n",
369 child_failed ? "losing" : "winning",
370 (unsigned long int) c,
371 c->pid, c->remote ? " (remote)" : "");
373 /* If this child had the good stdin, say it is now free. */
374 if (c->good_stdin)
375 good_stdin_used = 0;
377 if (child_failed && !c->noerror && !ignore_errors_flag)
379 /* The commands failed. Write an error message,
380 delete non-precious targets, and abort. */
381 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
382 c->file->update_status = 1;
383 if (exit_sig != 0)
384 delete_child_targets (c);
386 else
388 if (child_failed)
390 /* The commands failed, but we don't care. */
391 child_error (c->file->name,
392 exit_code, exit_sig, coredump, 1);
393 child_failed = 0;
396 /* If there are more commands to run, try to start them. */
397 if (job_next_command (c))
399 if (handling_fatal_signal)
401 /* Never start new commands while we are dying.
402 Since there are more commands that wanted to be run,
403 the target was not completely remade. So we treat
404 this as if a command had failed. */
405 c->file->command_state = cs_finished;
406 c->file->update_status = 1;
408 else
410 /* Check again whether to start remotely.
411 Whether or not we want to changes over time.
412 Also, start_remote_job may need state set up
413 by start_remote_job_p. */
414 c->remote = start_remote_job_p ();
415 start_job_command (c);
419 switch (c->file->command_state)
421 case cs_running:
422 /* Successfully started. Loop to reap more children. */
423 continue;
425 case cs_finished:
426 if (c->file->update_status != 0)
427 /* We failed to start the commands. */
428 delete_child_targets (c);
429 break;
431 default:
432 error ("internal error: `%s' has bogus command_state \
433 %d in reap_children",
434 c->file->name, (int) c->file->command_state);
435 abort ();
436 break;
440 if (! handling_fatal_signal)
441 /* Notice if the target of the commands has been changed. */
442 notice_finished_file (c->file);
444 if (debug_flag)
445 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
446 (unsigned long int) c,
447 c->pid, c->remote ? " (remote)" : "");
449 /* Remove the child from the chain and free it. */
450 if (lastc == 0)
451 children = c->next;
452 else
453 lastc->next = c->next;
454 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
455 free_child (c);
457 /* There is now another slot open. */
458 --job_slots_used;
460 /* If the job failed, and the -k flag was not given, die,
461 unless we are already in the process of dying. */
462 if (!err && child_failed && !keep_going_flag)
463 die (2);
466 /* Only block for one child. */
467 block = 0;
471 /* Free the storage allocated for CHILD. */
473 static void
474 free_child (child)
475 register struct child *child;
477 if (child->command_lines != 0)
479 register unsigned int i;
480 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
481 free (child->command_lines[i]);
482 free ((char *) child->command_lines);
485 if (child->environment != 0)
487 register char **ep = child->environment;
488 while (*ep != 0)
489 free (*ep++);
490 free ((char *) child->environment);
493 free ((char *) child);
496 #ifdef POSIX
497 #ifdef __MSDOS__
498 void
499 unblock_sigs ()
501 return;
503 #else
504 extern sigset_t fatal_signal_set;
506 void
507 unblock_sigs ()
509 sigset_t empty;
510 sigemptyset (&empty);
511 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
513 #endif
514 #endif
516 /* Start a job to run the commands specified in CHILD.
517 CHILD is updated to reflect the commands and ID of the child process. */
519 static void
520 start_job_command (child)
521 register struct child *child;
523 static int bad_stdin = -1;
524 register char *p;
525 int flags = child->file->cmds->lines_flags[child->command_line - 1];
526 char **argv;
528 p = child->command_ptr;
529 child->noerror = flags & COMMANDS_NOERROR;
530 while (*p != '\0')
532 if (*p == '@')
533 flags |= COMMANDS_SILENT;
534 else if (*p == '+')
535 flags |= COMMANDS_RECURSE;
536 else if (*p == '-')
537 child->noerror = 1;
538 else if (!isblank (*p) && *p != '+')
539 break;
540 ++p;
543 /* If -q was given, just say that updating `failed'. The exit status of
544 1 tells the user that -q is saying `something to do'; the exit status
545 for a random error is 2. */
546 if (question_flag && !(flags & COMMANDS_RECURSE))
548 child->file->update_status = 1;
549 set_command_state (child->file, cs_finished);
550 return;
553 /* There may be some preceding whitespace left if there
554 was nothing but a backslash on the first line. */
555 p = next_token (p);
557 /* Figure out an argument list from this command line. */
560 char *end;
561 argv = construct_command_argv (p, &end, child->file);
562 if (end == NULL)
563 child->command_ptr = NULL;
564 else
566 *end++ = '\0';
567 child->command_ptr = end;
571 if (touch_flag && !(flags & COMMANDS_RECURSE))
573 /* Go on to the next command. It might be the recursive one.
574 We construct ARGV only to find the end of the command line. */
575 free (argv[0]);
576 free ((char *) argv);
577 argv = 0;
580 if (argv == 0)
582 /* This line has no commands. Go to the next. */
583 if (job_next_command (child))
584 start_job_command (child);
585 return;
588 /* Print out the command. */
590 if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
591 puts (p);
593 /* Tell update_goal_chain that a command has been started on behalf of
594 this target. It is important that this happens here and not in
595 reap_children (where we used to do it), because reap_children might be
596 reaping children from a different target. We want this increment to
597 guaranteedly indicate that a command was started for the dependency
598 chain (i.e., update_file recursion chain) we are processing. */
600 ++commands_started;
602 /* If -n was given, recurse to get the next line in the sequence. */
604 if (just_print_flag && !(flags & COMMANDS_RECURSE))
606 free (argv[0]);
607 free ((char *) argv);
608 if (job_next_command (child))
609 start_job_command (child);
610 return;
613 /* Flush the output streams so they won't have things written twice. */
615 fflush (stdout);
616 fflush (stderr);
618 /* Set up a bad standard input that reads from a broken pipe. */
620 if (bad_stdin == -1)
622 /* Make a file descriptor that is the read end of a broken pipe.
623 This will be used for some children's standard inputs. */
624 int pd[2];
625 if (pipe (pd) == 0)
627 /* Close the write side. */
628 (void) close (pd[1]);
629 /* Save the read side. */
630 bad_stdin = pd[0];
634 /* Decide whether to give this child the `good' standard input
635 (one that points to the terminal or whatever), or the `bad' one
636 that points to the read side of a broken pipe. */
638 child->good_stdin = !good_stdin_used;
639 if (child->good_stdin)
640 good_stdin_used = 1;
642 child->deleted = 0;
644 /* Set up the environment for the child. */
645 if (child->environment == 0)
646 child->environment = target_environment (child->file);
648 #ifndef __MSDOS__
650 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
651 if (child->remote)
653 int is_remote, id, used_stdin;
654 if (start_remote_job (argv, child->environment,
655 child->good_stdin ? 0 : bad_stdin,
656 &is_remote, &id, &used_stdin))
657 goto error;
658 else
660 if (child->good_stdin && !used_stdin)
662 child->good_stdin = 0;
663 good_stdin_used = 0;
665 child->remote = is_remote;
666 child->pid = id;
669 else
671 /* Fork the child process. */
673 #ifdef POSIX
674 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
675 #else
676 #ifdef HAVE_SIGSETMASK
677 (void) sigblock (fatal_signal_mask);
678 #endif
679 #endif
681 child->remote = 0;
682 child->pid = vfork ();
683 if (child->pid == 0)
685 /* We are the child side. */
686 unblock_sigs ();
687 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
688 argv, child->environment);
690 else if (child->pid < 0)
692 /* Fork failed! */
693 unblock_sigs ();
694 perror_with_name ("vfork", "");
695 goto error;
699 #else /* MSDOS. */
700 dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
701 ++dead_children;
702 child->pid = dos_pid++;
703 if (dos_batch_file)
705 dos_batch_file = 0;
706 remove (dos_bname); /* Ignore errors. */
707 if (access (dos_bename, 0))
708 dos_status = 1;
709 else
710 dos_status = 0;
711 remove (dos_bename);
713 #endif /* Not MSDOS. */
715 /* We are the parent side. Set the state to
716 say the commands are running and return. */
718 set_command_state (child->file, cs_running);
720 /* Free the storage used by the child's argument list. */
722 free (argv[0]);
723 free ((char *) argv);
725 return;
727 error:
728 child->file->update_status = 2;
729 set_command_state (child->file, cs_finished);
732 /* Try to start a child running.
733 Returns nonzero if the child was started (and maybe finished), or zero if
734 the load was too high and the child was put on the `waiting_jobs' chain. */
736 static int
737 start_waiting_job (c)
738 struct child *c;
740 /* If we can start a job remotely, we always want to, and don't care about
741 the local load average. We record that the job should be started
742 remotely in C->remote for start_job_command to test. */
744 c->remote = start_remote_job_p ();
746 /* If this job is to be started locally, and we are already running
747 some jobs, make this one wait if the load average is too high. */
748 if (!c->remote && job_slots_used > 0 && load_too_high ())
750 /* Put this child on the chain of children waiting
751 for the load average to go down. */
752 c->file->command_state = cs_running;
753 c->next = waiting_jobs;
754 waiting_jobs = c;
755 return 0;
758 /* Start the first command; reap_children will run later command lines. */
759 start_job_command (c);
761 switch (c->file->command_state)
763 case cs_running:
764 c->next = children;
765 if (debug_flag)
766 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
767 (unsigned long int) c,
768 c->pid, c->remote ? " (remote)" : "");
769 children = c;
770 /* One more job slot is in use. */
771 ++job_slots_used;
772 unblock_sigs ();
773 break;
775 case cs_finished:
776 notice_finished_file (c->file);
777 free_child (c);
778 break;
780 default:
781 error ("internal error: `%s' command_state == %d in new_job",
782 c->file->name, (int) c->file->command_state);
783 abort ();
784 break;
787 return 1;
790 /* Create a `struct child' for FILE and start its commands running. */
792 void
793 new_job (file)
794 register struct file *file;
796 register struct commands *cmds = file->cmds;
797 register struct child *c;
798 char **lines;
799 register unsigned int i;
801 /* Let any previously decided-upon jobs that are waiting
802 for the load to go down start before this new one. */
803 start_waiting_jobs ();
805 /* Reap any children that might have finished recently. */
806 reap_children (0, 0);
808 /* Chop the commands up into lines if they aren't already. */
809 chop_commands (cmds);
811 if (job_slots != 0)
812 /* Wait for a job slot to be freed up. */
813 while (job_slots_used == job_slots)
814 reap_children (1, 0);
816 /* Expand the command lines and store the results in LINES. */
817 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
818 for (i = 0; i < cmds->ncommand_lines; ++i)
820 /* Collapse backslash-newline combinations that are inside variable
821 or function references. These are left alone by the parser so
822 that they will appear in the echoing of commands (where they look
823 nice); and collapsed by construct_command_argv when it tokenizes.
824 But letting them survive inside function invocations loses because
825 we don't want the functions to see them as part of the text. */
827 char *in, *out, *ref;
829 /* IN points to where in the line we are scanning.
830 OUT points to where in the line we are writing.
831 When we collapse a backslash-newline combination,
832 IN gets ahead out OUT. */
834 in = out = cmds->command_lines[i];
835 while ((ref = index (in, '$')) != 0)
837 ++ref; /* Move past the $. */
839 if (out != in)
840 /* Copy the text between the end of the last chunk
841 we processed (where IN points) and the new chunk
842 we are about to process (where REF points). */
843 bcopy (in, out, ref - in);
845 /* Move both pointers past the boring stuff. */
846 out += ref - in;
847 in = ref;
849 if (*ref == '(' || *ref == '{')
851 char openparen = *ref;
852 char closeparen = openparen == '(' ? ')' : '}';
853 int count;
854 char *p;
856 *out++ = *in++; /* Copy OPENPAREN. */
857 /* IN now points past the opening paren or brace.
858 Count parens or braces until it is matched. */
859 count = 0;
860 while (*in != '\0')
862 if (*in == closeparen && --count < 0)
863 break;
864 else if (*in == '\\' && in[1] == '\n')
866 /* We have found a backslash-newline inside a
867 variable or function reference. Eat it and
868 any following whitespace. */
870 int quoted = 0;
871 for (p = in - 1; p > ref && *p == '\\'; --p)
872 quoted = !quoted;
874 if (quoted)
875 /* There were two or more backslashes, so this is
876 not really a continuation line. We don't collapse
877 the quoting backslashes here as is done in
878 collapse_continuations, because the line will
879 be collapsed again after expansion. */
880 *out++ = *in++;
881 else
883 /* Skip the backslash, newline and
884 any following whitespace. */
885 in = next_token (in + 2);
887 /* Discard any preceding whitespace that has
888 already been written to the output. */
889 while (out > ref && isblank (out[-1]))
890 --out;
892 /* Replace it all with a single space. */
893 *out++ = ' ';
896 else
898 if (*in == openparen)
899 ++count;
901 *out++ = *in++;
907 /* There are no more references in this line to worry about.
908 Copy the remaining uninteresting text to the output. */
909 if (out != in)
910 strcpy (out, in);
912 /* Finally, expand the line. */
913 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
914 file);
917 /* Start the command sequence, record it in a new
918 `struct child', and add that to the chain. */
920 c = (struct child *) xmalloc (sizeof (struct child));
921 c->file = file;
922 c->command_lines = lines;
923 c->command_line = 0;
924 c->command_ptr = 0;
925 c->environment = 0;
927 /* Fetch the first command line to be run. */
928 if (! job_next_command (c))
929 /* There were no commands! */
930 free_child (c);
931 else
933 /* The job is now primed. Start it running. */
934 start_waiting_job (c);
936 if (job_slots == 1)
937 /* Since there is only one job slot, make things run linearly.
938 Wait for the child to die, setting the state to `cs_finished'. */
939 while (file->command_state == cs_running)
940 reap_children (1, 0);
944 /* Move CHILD's pointers to the next command for it to execute.
945 Returns nonzero if there is another command. */
947 static int
948 job_next_command (child)
949 struct child *child;
951 if (child->command_ptr == 0 || *child->command_ptr == '\0')
953 /* There are no more lines in the expansion of this line. */
954 if (child->command_line == child->file->cmds->ncommand_lines)
956 /* There are no more lines to be expanded. */
957 child->command_ptr = 0;
958 set_command_state (child->file, cs_finished);
959 child->file->update_status = 0;
960 return 0;
962 else
963 /* Get the next line to run. */
964 child->command_ptr = child->command_lines[child->command_line++];
966 return 1;
969 static int
970 load_too_high ()
972 #ifdef __MSDOS__
973 return 1;
974 #else
975 extern int getloadavg ();
976 double load;
978 if (max_load_average < 0)
979 return 0;
981 make_access ();
982 if (getloadavg (&load, 1) != 1)
984 static int lossage = -1;
985 /* Complain only once for the same error. */
986 if (lossage == -1 || errno != lossage)
988 if (errno == 0)
989 /* An errno value of zero means getloadavg is just unsupported. */
990 error ("cannot enforce load limits on this operating system");
991 else
992 perror_with_name ("cannot enforce load limit: ", "getloadavg");
994 lossage = errno;
995 load = 0;
997 user_access ();
999 return load >= max_load_average;
1000 #endif
1003 /* Start jobs that are waiting for the load to be lower. */
1005 void
1006 start_waiting_jobs ()
1008 struct child *job;
1010 if (waiting_jobs == 0)
1011 return;
1015 /* Check for recently deceased descendants. */
1016 reap_children (0, 0);
1018 /* Take a job off the waiting list. */
1019 job = waiting_jobs;
1020 waiting_jobs = job->next;
1022 /* Try to start that job. We break out of the loop as soon
1023 as start_waiting_job puts one back on the waiting list. */
1024 } while (start_waiting_job (job) && waiting_jobs != 0);
1027 /* Replace the current process with one executing the command in ARGV.
1028 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1029 the environment of the new program. This function does not return. */
1031 void
1032 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1033 int stdin_fd, stdout_fd;
1034 char **argv, **envp;
1036 if (stdin_fd != 0)
1037 (void) dup2 (stdin_fd, 0);
1038 if (stdout_fd != 1)
1039 (void) dup2 (stdout_fd, 1);
1041 /* Free up file descriptors. */
1043 register int d;
1044 int max = getdtablesize ();
1045 for (d = 3; d < max; ++d)
1046 (void) close (d);
1049 /* Run the command. */
1050 exec_command (argv, envp);
1053 /* Search PATH for FILE.
1054 If successful, store the full pathname in PROGRAM and return 1.
1055 If not sucessful, return zero. */
1057 static int
1058 search_path (file, path, program)
1059 char *file, *path, *program;
1061 if (path == 0 || path[0] == '\0')
1062 path = default_path;
1064 if (
1065 #ifdef __MSDOS__
1066 strpbrk (file, "/\\:")
1067 #else
1068 index (file, '/')
1069 #endif
1070 != 0)
1072 strcpy (program, file);
1073 return 1;
1075 else
1077 unsigned int len;
1079 #ifdef HAVE_GETGROUPS
1080 #ifndef HAVE_UNISTD_H
1081 extern int getgroups ();
1082 #endif
1083 static int ngroups = -1;
1084 #ifdef NGROUPS_MAX
1085 static GETGROUPS_T groups[NGROUPS_MAX];
1086 #define ngroups_max NGROUPS_MAX
1087 #else
1088 static GETGROUPS_T *groups = 0;
1089 static int ngroups_max;
1090 if (groups == 0)
1092 ngroups_max = GET_NGROUPS_MAX;
1093 groups = (GETGROUPS_T *) malloc (ngroups_max * sizeof (GETGROUPS_T));
1095 #endif
1096 if (groups != 0 && ngroups == -1)
1097 ngroups = getgroups (ngroups_max, groups);
1098 #endif /* Have getgroups. */
1100 len = strlen (file) + 1;
1103 struct stat st;
1104 int perm;
1105 char *p;
1107 p = index (path, PATH_SEPARATOR_CHAR);
1108 if (p == 0)
1109 p = path + strlen (path);
1111 if (p == path)
1112 bcopy (file, program, len);
1113 else
1115 bcopy (path, program, p - path);
1116 program[p - path] = '/';
1117 bcopy (file, program + (p - path) + 1, len);
1120 if (safe_stat (program, &st) == 0
1121 && S_ISREG (st.st_mode))
1123 if (st.st_uid == geteuid ())
1124 perm = (st.st_mode & 0100);
1125 else if (st.st_gid == getegid ())
1126 perm = (st.st_mode & 0010);
1127 else
1129 #ifdef HAVE_GETGROUPS
1130 register int i;
1131 for (i = 0; i < ngroups; ++i)
1132 if (groups[i] == st.st_gid)
1133 break;
1134 if (i < ngroups)
1135 perm = (st.st_mode & 0010);
1136 else
1137 #endif /* Have getgroups. */
1138 perm = (st.st_mode & 0001);
1141 if (perm != 0)
1142 return 1;
1145 path = p + 1;
1146 } while (*path != '\0');
1149 return 0;
1152 /* Replace the current process with one running the command in ARGV,
1153 with environment ENVP. This function does not return. */
1155 void
1156 exec_command (argv, envp)
1157 char **argv, **envp;
1159 char *shell, *path;
1160 PATH_VAR (program);
1161 register char **ep;
1163 shell = path = 0;
1164 for (ep = envp; *ep != 0; ++ep)
1166 if (shell == 0 && !strncmp(*ep, "SHELL=", 6))
1167 shell = &(*ep)[6];
1168 else if (path == 0 && !strncmp(*ep, "PATH=", 5))
1169 path = &(*ep)[5];
1170 else if (path != 0 && shell != 0)
1171 break;
1174 /* Be the user, permanently. */
1175 child_access ();
1177 if (!search_path (argv[0], path, program))
1178 error ("%s: Command not found", argv[0]);
1179 else
1181 /* Run the program. */
1182 execve (program, argv, envp);
1184 if (errno == ENOEXEC)
1186 PATH_VAR (shell_program);
1187 char *shell_path;
1188 if (shell == 0)
1189 shell_path = default_shell;
1190 else
1192 if (search_path (shell, path, shell_program))
1193 shell_path = shell_program;
1194 else
1196 shell_path = 0;
1197 error ("%s: Shell program not found", shell);
1201 if (shell_path != 0)
1203 char **new_argv;
1204 int argc;
1206 argc = 1;
1207 while (argv[argc] != 0)
1208 ++argc;
1210 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1211 new_argv[0] = shell_path;
1212 new_argv[1] = program;
1213 while (argc > 0)
1215 new_argv[1 + argc] = argv[argc];
1216 --argc;
1219 execve (shell_path, new_argv, envp);
1220 perror_with_name ("execve: ", shell_path);
1223 else
1224 perror_with_name ("execve: ", program);
1227 _exit (127);
1230 /* Figure out the argument list necessary to run LINE as a command.
1231 Try to avoid using a shell. This routine handles only ' quoting.
1232 Starting quotes may be escaped with a backslash. If any of the
1233 characters in sh_chars[] is seen, or any of the builtin commands
1234 listed in sh_cmds[] is the first word of a line, the shell is used.
1236 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1237 If *RESTP is NULL, newlines will be ignored.
1239 SHELL is the shell to use, or nil to use the default shell.
1240 IFS is the value of $IFS, or nil (meaning the default). */
1242 static char **
1243 construct_command_argv_internal (line, restp, shell, ifs)
1244 char *line, **restp;
1245 char *shell, *ifs;
1247 #ifdef __MSDOS__
1248 static char sh_chars[] = "\"|<>";
1249 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1250 "copy", "ctty", "date", "del", "dir", "echo",
1251 "erase", "exit", "for", "goto", "if", "if", "md",
1252 "mkdir", "path", "pause", "prompt", "rem", "ren",
1253 "rename", "set", "shift", "time", "type",
1254 "ver", "verify", "vol", ":", 0 };
1255 #else
1256 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1257 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1258 "logout", "set", "umask", "wait", "while", "for",
1259 "case", "if", ":", ".", "break", "continue",
1260 "export", "read", "readonly", "shift", "times",
1261 "trap", "switch", 0 };
1262 #endif
1263 register int i;
1264 register char *p;
1265 register char *ap;
1266 char *end;
1267 int instring, word_has_equals, seen_nonequals;
1268 char **new_argv = 0;
1270 if (restp != NULL)
1271 *restp = NULL;
1273 /* Make sure not to bother processing an empty line. */
1274 while (isblank (*line))
1275 ++line;
1276 if (*line == '\0')
1277 return 0;
1279 /* See if it is safe to parse commands internally. */
1280 if (shell == 0)
1281 shell = default_shell;
1282 else if (strcmp (shell, default_shell))
1283 goto slow;
1285 if (ifs != 0)
1286 for (ap = ifs; *ap != '\0'; ++ap)
1287 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1288 goto slow;
1290 i = strlen (line) + 1;
1292 /* More than 1 arg per character is impossible. */
1293 new_argv = (char **) xmalloc (i * sizeof (char *));
1295 /* All the args can fit in a buffer as big as LINE is. */
1296 ap = new_argv[0] = (char *) xmalloc (i);
1297 end = ap + i;
1299 /* I is how many complete arguments have been found. */
1300 i = 0;
1301 instring = word_has_equals = seen_nonequals = 0;
1302 for (p = line; *p != '\0'; ++p)
1304 if (ap > end)
1305 abort ();
1307 if (instring)
1309 string_char:
1310 /* Inside a string, just copy any char except a closing quote
1311 or a backslash-newline combination. */
1312 if (*p == '\'')
1313 instring = 0;
1314 else if (*p == '\\' && p[1] == '\n')
1315 goto swallow_escaped_newline;
1316 else if (*p == '\n' && restp != NULL)
1318 /* End of the command line. */
1319 *restp = p;
1320 goto end_of_line;
1322 else
1323 *ap++ = *p;
1325 else if (index (sh_chars, *p) != 0)
1326 /* Not inside a string, but it's a special char. */
1327 goto slow;
1328 else
1329 /* Not a special char. */
1330 switch (*p)
1332 case '=':
1333 /* Equals is a special character in leading words before the
1334 first word with no equals sign in it. This is not the case
1335 with sh -k, but we never get here when using nonstandard
1336 shell flags. */
1337 if (! seen_nonequals)
1338 goto slow;
1339 word_has_equals = 1;
1340 *ap++ = '=';
1341 break;
1343 case '\\':
1344 /* Backslash-newline combinations are eaten. */
1345 if (p[1] == '\n')
1347 swallow_escaped_newline:
1349 /* Eat the backslash, the newline, and following whitespace,
1350 replacing it all with a single space. */
1351 p += 2;
1353 /* If there is a tab after a backslash-newline,
1354 remove it from the source line which will be echoed,
1355 since it was most likely used to line
1356 up the continued line with the previous one. */
1357 if (*p == '\t')
1358 strcpy (p, p + 1);
1360 if (instring)
1361 goto string_char;
1362 else
1364 if (ap != new_argv[i])
1365 /* Treat this as a space, ending the arg.
1366 But if it's at the beginning of the arg, it should
1367 just get eaten, rather than becoming an empty arg. */
1368 goto end_of_arg;
1369 else
1370 p = next_token (p) - 1;
1373 else if (p[1] != '\0')
1374 /* Copy and skip the following char. */
1375 *ap++ = *++p;
1376 break;
1378 case '\'':
1379 instring = 1;
1380 break;
1382 case '\n':
1383 if (restp != NULL)
1385 /* End of the command line. */
1386 *restp = p;
1387 goto end_of_line;
1389 else
1390 /* Newlines are not special. */
1391 *ap++ = '\n';
1392 break;
1394 case ' ':
1395 case '\t':
1396 end_of_arg:
1397 /* We have the end of an argument.
1398 Terminate the text of the argument. */
1399 *ap++ = '\0';
1400 new_argv[++i] = ap;
1402 /* Update SEEN_NONEQUALS, which tells us if every word
1403 heretofore has contained an `='. */
1404 seen_nonequals |= ! word_has_equals;
1405 if (word_has_equals && ! seen_nonequals)
1406 /* An `=' in a word before the first
1407 word without one is magical. */
1408 goto slow;
1409 word_has_equals = 0; /* Prepare for the next word. */
1411 /* If this argument is the command name,
1412 see if it is a built-in shell command.
1413 If so, have the shell handle it. */
1414 if (i == 1)
1416 register int j;
1417 for (j = 0; sh_cmds[j] != 0; ++j)
1418 if (streq (sh_cmds[j], new_argv[0]))
1419 goto slow;
1422 /* Ignore multiple whitespace chars. */
1423 p = next_token (p);
1424 /* Next iteration should examine the first nonwhite char. */
1425 --p;
1426 break;
1428 default:
1429 *ap++ = *p;
1430 break;
1433 end_of_line:
1435 if (instring)
1436 /* Let the shell deal with an unterminated quote. */
1437 goto slow;
1439 /* Terminate the last argument and the argument list. */
1441 *ap = '\0';
1442 if (new_argv[i][0] != '\0')
1443 ++i;
1444 new_argv[i] = 0;
1446 if (i == 1)
1448 register int j;
1449 for (j = 0; sh_cmds[j] != 0; ++j)
1450 if (streq (sh_cmds[j], new_argv[0]))
1451 goto slow;
1454 if (new_argv[0] == 0)
1455 /* Line was empty. */
1456 return 0;
1457 else
1458 return new_argv;
1460 slow:;
1461 /* We must use the shell. */
1463 if (new_argv != 0)
1465 /* Free the old argument list we were working on. */
1466 free (new_argv[0]);
1467 free (new_argv);
1470 #ifdef __MSDOS__
1472 FILE *batch;
1473 dos_batch_file = 1;
1474 if (dos_bname == 0)
1476 dos_bname = tempnam (".", "mk");
1477 for (i = 0; dos_bname[i] != '\0'; ++i)
1478 if (dos_bname[i] == '/')
1479 dos_bname[i] = '\\';
1480 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1481 strcpy (dos_bename, dos_bname);
1482 strcat (dos_bname, ".bat");
1483 strcat (dos_bename, ".err");
1485 batch = fopen(bename, "w"); /* Create a file. */
1486 if (batch != NULL)
1487 fclose (batch);
1488 batch = fopen (dos_bname, "w");
1489 fputs ("@echo off\n", batch);
1490 fputs (line, batch);
1491 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1492 fclose (batch);
1493 new_argv = (char **) xmalloc(2 * sizeof(char *));
1494 new_argv[0] = strdup (bname);
1495 new_argv[1] = 0;
1497 #else /* Not MSDOS. */
1499 /* SHELL may be a multi-word command. Construct a command line
1500 "SHELL -c LINE", with all special chars in LINE escaped.
1501 Then recurse, expanding this command line to get the final
1502 argument list. */
1504 unsigned int shell_len = strlen (shell);
1505 static char minus_c[] = " -c ";
1506 unsigned int line_len = strlen (line);
1508 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1509 + (line_len * 2) + 1);
1511 ap = new_line;
1512 bcopy (shell, ap, shell_len);
1513 ap += shell_len;
1514 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1515 ap += sizeof (minus_c) - 1;
1516 for (p = line; *p != '\0'; ++p)
1518 if (restp != NULL && *p == '\n')
1520 *restp = p;
1521 break;
1523 else if (*p == '\\' && p[1] == '\n')
1525 /* Eat the backslash, the newline, and following whitespace,
1526 replacing it all with a single space (which is escaped
1527 from the shell). */
1528 p += 2;
1530 /* If there is a tab after a backslash-newline,
1531 remove it from the source line which will be echoed,
1532 since it was most likely used to line
1533 up the continued line with the previous one. */
1534 if (*p == '\t')
1535 strcpy (p, p + 1);
1537 p = next_token (p);
1538 --p;
1539 *ap++ = '\\';
1540 *ap++ = ' ';
1541 continue;
1544 if (*p == '\\' || *p == '\''
1545 || isspace (*p)
1546 || index (sh_chars, *p) != 0)
1547 *ap++ = '\\';
1548 *ap++ = *p;
1550 *ap = '\0';
1552 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1553 (char *) 0, (char *) 0);
1555 #endif /* MSDOS. */
1557 return new_argv;
1560 /* Figure out the argument list necessary to run LINE as a command.
1561 Try to avoid using a shell. This routine handles only ' quoting.
1562 Starting quotes may be escaped with a backslash. If any of the
1563 characters in sh_chars[] is seen, or any of the builtin commands
1564 listed in sh_cmds[] is the first word of a line, the shell is used.
1566 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1567 If *RESTP is NULL, newlines will be ignored.
1569 FILE is the target whose commands these are. It is used for
1570 variable expansion for $(SHELL) and $(IFS). */
1572 char **
1573 construct_command_argv (line, restp, file)
1574 char *line, **restp;
1575 struct file *file;
1577 char *shell, *ifs;
1578 char **argv;
1581 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1582 int save = warn_undefined_variables_flag;
1583 warn_undefined_variables_flag = 0;
1585 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1586 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1588 warn_undefined_variables_flag = save;
1591 argv = construct_command_argv_internal (line, restp, shell, ifs);
1593 free (shell);
1594 free (ifs);
1596 return argv;
1599 #ifndef HAVE_DUP2
1601 dup2 (old, new)
1602 int old, new;
1604 int fd;
1606 (void) close (new);
1607 fd = dup (old);
1608 if (fd != new)
1610 (void) close (fd);
1611 errno = EMFILE;
1612 return -1;
1615 return fd;
1617 #endif