[alliant && i860] (FSCALE): Move defn before #ifndef FSCALE.
[make.git] / job.c
blob666c0d795cd12f28f0f0cd99da98daab2fa383de
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"
24 #include <assert.h>
26 /* Default path to search for executables. */
27 static char default_path[] = ":/bin:/usr/bin";
29 /* Default shell to use. */
30 char default_shell[] = "/bin/sh";
32 #ifdef __MSDOS__
33 #include <process.h>
34 static int dos_pid = 123;
35 static int dos_status;
36 static char *dos_bname;
37 static char *dos_bename;
38 static int dos_batch_file;
39 #endif /* MSDOS. */
42 /* If NGROUPS_MAX == 0 then try other methods for finding a real value. */
43 #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0
44 #undef NGROUPS_MAX
45 #endif /* NGROUPS_MAX == 0 */
47 #ifndef NGROUPS_MAX
48 #ifdef POSIX
49 #define GET_NGROUPS_MAX sysconf (_SC_NGROUPS_MAX)
50 #else /* Not POSIX. */
51 #define NGROUPS_MAX NGROUPS
52 #endif /* POSIX. */
53 #endif
55 #ifdef HAVE_SYS_WAIT_H
56 #include <sys/wait.h>
57 #endif
59 #ifdef HAVE_WAITPID
60 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
61 #else /* Don't have waitpid. */
62 #ifdef HAVE_WAIT3
63 #ifndef wait3
64 extern int wait3 ();
65 #endif
66 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
67 #endif /* Have wait3. */
68 #endif /* Have waitpid. */
70 #if !defined (wait) && !defined (POSIX)
71 extern int wait ();
72 #endif
74 #ifndef HAVE_UNION_WAIT
76 #define WAIT_T int
78 #ifndef WTERMSIG
79 #define WTERMSIG(x) ((x) & 0x7f)
80 #endif
81 #ifndef WCOREDUMP
82 #define WCOREDUMP(x) ((x) & 0x80)
83 #endif
84 #ifndef WEXITSTATUS
85 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
86 #endif
87 #ifndef WIFSIGNALED
88 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
89 #endif
90 #ifndef WIFEXITED
91 #define WIFEXITED(x) (WTERMSIG (x) == 0)
92 #endif
94 #else /* Have `union wait'. */
96 #define WAIT_T union wait
97 #ifndef WTERMSIG
98 #define WTERMSIG(x) ((x).w_termsig)
99 #endif
100 #ifndef WCOREDUMP
101 #define WCOREDUMP(x) ((x).w_coredump)
102 #endif
103 #ifndef WEXITSTATUS
104 #define WEXITSTATUS(x) ((x).w_retcode)
105 #endif
106 #ifndef WIFSIGNALED
107 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
108 #endif
109 #ifndef WIFEXITED
110 #define WIFEXITED(x) (WTERMSIG(x) == 0)
111 #endif
113 #endif /* Don't have `union wait'. */
116 #ifndef HAVE_UNISTD_H
117 extern int dup2 ();
118 extern int execve ();
119 extern void _exit ();
120 extern int geteuid (), getegid ();
121 extern int setgid (), getgid ();
122 #endif
124 #ifndef getdtablesize
125 #ifdef HAVE_GETDTABLESIZE
126 extern int getdtablesize ();
127 #else
128 #include <sys/param.h>
129 #define getdtablesize() NOFILE
130 #if !defined (NOFILE) && defined (NOFILES_MAX)
131 /* SCO 3.2 "devsys 4.2" defines NOFILES_{MIN,MAX} in lieu of NOFILE. */
132 #define NOFILE NOFILES_MAX
133 #endif
134 #endif
135 #endif
137 extern int getloadavg ();
138 extern int start_remote_job_p ();
139 extern int start_remote_job (), remote_status ();
141 RETSIGTYPE child_handler ();
142 static void free_child (), start_job_command ();
143 static int load_too_high (), job_next_command ();
145 /* Chain of all live (or recently deceased) children. */
147 struct child *children = 0;
149 /* Number of children currently running. */
151 unsigned int job_slots_used = 0;
153 /* Nonzero if the `good' standard input is in use. */
155 static int good_stdin_used = 0;
157 /* Chain of children waiting to run until the load average goes down. */
159 static struct child *waiting_jobs = 0;
161 /* Write an error message describing the exit status given in
162 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
163 Append "(ignored)" if IGNORED is nonzero. */
165 static void
166 child_error (target_name, exit_code, exit_sig, coredump, ignored)
167 char *target_name;
168 int exit_code, exit_sig, coredump;
169 int ignored;
171 if (exit_sig == 0)
172 error (ignored ? "[%s] Error %d (ignored)" :
173 "*** [%s] Error %d",
174 target_name, exit_code);
175 else
177 char *coredump_string = coredump ? " (core dumped)" : "";
178 if (exit_sig > 0 && exit_sig < NSIG)
179 error ("*** [%s] %s%s",
180 target_name, sys_siglist[exit_sig], coredump_string);
181 else
182 error ("*** [%s] Signal %d%s", target_name, exit_sig, coredump_string);
186 static unsigned int dead_children = 0;
188 /* Notice that a child died.
189 reap_children should be called when convenient. */
190 RETSIGTYPE
191 child_handler (sig)
192 int sig;
194 ++dead_children;
196 if (debug_flag)
197 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
200 extern int shell_function_pid, shell_function_completed;
202 /* Reap dead children, storing the returned status and the new command
203 state (`cs_finished') in the `file' member of the `struct child' for the
204 dead child, and removing the child from the chain. If BLOCK nonzero,
205 reap at least one child, waiting for it to die if necessary. If ERR is
206 nonzero, print an error message first. */
208 void
209 reap_children (block, err)
210 int block, err;
212 WAIT_T status;
214 while ((children != 0 || shell_function_pid != 0) &&
215 (block || dead_children > 0))
217 int remote = 0;
218 register int pid;
219 int exit_code, exit_sig, coredump;
220 register struct child *lastc, *c;
221 int child_failed;
222 int any_remote, any_local;
224 if (err && dead_children == 0)
226 /* We might block for a while, so let the user know why. */
227 fflush (stdout);
228 error ("*** Waiting for unfinished jobs....");
231 /* We have one less dead child to reap.
232 The test and decrement are not atomic; if it is compiled into:
233 register = dead_children - 1;
234 dead_children = register;
235 a SIGCHLD could come between the two instructions.
236 child_handler increments dead_children.
237 The second instruction here would lose that increment. But the
238 only effect of dead_children being wrong is that we might wait
239 longer than necessary to reap a child, and lose some parallelism;
240 and we might print the "Waiting for unfinished jobs" message above
241 when not necessary. */
243 if (dead_children != 0)
244 --dead_children;
246 any_remote = 0;
247 any_local = shell_function_pid != -1;
248 for (c = children; c != 0; c = c->next)
250 any_remote |= c->remote;
251 any_local |= ! c->remote;
252 if (debug_flag)
253 printf ("Live child 0x%08lx PID %d%s\n",
254 (unsigned long int) c,
255 c->pid, c->remote ? " (remote)" : "");
258 /* First, check for remote children. */
259 if (any_remote)
260 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
261 else
262 pid = 0;
263 if (pid < 0)
265 remote_status_lose:
266 #ifdef EINTR
267 if (errno == EINTR)
268 continue;
269 #endif
270 pfatal_with_name ("remote_status");
272 else if (pid == 0)
274 #ifndef __MSDOS__
275 /* No remote children. Check for local children. */
277 if (any_local)
279 #ifdef WAIT_NOHANG
280 if (!block)
281 pid = WAIT_NOHANG (&status);
282 else
283 #endif
284 pid = wait (&status);
286 else
287 pid = 0;
289 if (pid < 0)
291 #ifdef EINTR
292 if (errno == EINTR)
293 continue;
294 #endif
295 pfatal_with_name ("wait");
297 else if (pid == 0)
299 /* No local children. */
300 if (block && any_remote)
302 /* Now try a blocking wait for a remote child. */
303 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
304 if (pid < 0)
305 goto remote_status_lose;
306 else if (pid == 0)
307 /* No remote children either. Finally give up. */
308 break;
309 else
310 /* We got a remote child. */
311 remote = 1;
313 else
314 break;
316 else
318 /* Chop the status word up. */
319 exit_code = WEXITSTATUS (status);
320 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
321 coredump = WCOREDUMP (status);
323 #else /* MSDOS. */
324 /* Life is very different on MSDOS. */
325 pid = dos_pid - 1;
326 status = dos_status;
327 exit_code = dos_status;
328 exit_sig = 0;
329 coredump = 0;
330 #endif /* Not MSDOS. */
332 else
333 /* We got a remote child. */
334 remote = 1;
336 /* Check if this is the child of the `shell' function. */
337 if (!remote && pid == shell_function_pid)
339 /* It is. Leave an indicator for the `shell' function. */
340 if (exit_sig == 0 && exit_code == 127)
341 shell_function_completed = -1;
342 else
343 shell_function_completed = 1;
344 break;
347 child_failed = exit_sig != 0 || exit_code != 0;
349 /* Search for a child matching the deceased one. */
350 lastc = 0;
351 for (c = children; c != 0; lastc = c, c = c->next)
352 if (c->remote == remote && c->pid == pid)
353 break;
355 if (c == 0)
357 /* An unknown child died. */
358 char buf[100];
359 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
360 if (child_failed)
361 child_error (buf, exit_code, exit_sig, coredump,
362 ignore_errors_flag);
363 else
364 error ("%s finished.", buf);
366 else
368 if (debug_flag)
369 printf ("Reaping %s child 0x%08lx PID %d%s\n",
370 child_failed ? "losing" : "winning",
371 (unsigned long int) c,
372 c->pid, c->remote ? " (remote)" : "");
374 /* If this child had the good stdin, say it is now free. */
375 if (c->good_stdin)
376 good_stdin_used = 0;
378 if (child_failed && !c->noerror && !ignore_errors_flag)
380 /* The commands failed. Write an error message,
381 delete non-precious targets, and abort. */
382 static int delete_on_error = -1;
383 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
384 c->file->update_status = 1;
385 if (delete_on_error == -1)
387 struct file *f = lookup_file (".DELETE_ON_ERROR");
388 delete_on_error = f != 0 && f->is_target;
390 if (exit_sig != 0 || delete_on_error)
391 delete_child_targets (c);
393 else
395 if (child_failed)
397 /* The commands failed, but we don't care. */
398 child_error (c->file->name,
399 exit_code, exit_sig, coredump, 1);
400 child_failed = 0;
403 /* If there are more commands to run, try to start them. */
404 if (job_next_command (c))
406 if (handling_fatal_signal)
408 /* Never start new commands while we are dying.
409 Since there are more commands that wanted to be run,
410 the target was not completely remade. So we treat
411 this as if a command had failed. */
412 c->file->update_status = 1;
414 else
416 /* Check again whether to start remotely.
417 Whether or not we want to changes over time.
418 Also, start_remote_job may need state set up
419 by start_remote_job_p. */
420 c->remote = start_remote_job_p ();
421 start_job_command (c);
422 if (c->file->command_state == cs_running)
423 /* We successfully started the new command.
424 Loop to reap more children. */
425 continue;
428 if (c->file->update_status != 0)
429 /* We failed to start the commands. */
430 delete_child_targets (c);
432 else
433 /* There are no more commands. We got through them all
434 without an unignored error. Now the target has been
435 successfully updated. */
436 c->file->update_status = 0;
439 /* When we get here, all the commands for C->file are finished
440 (or aborted) and C->file->update_status contains 0 or 1. But
441 C->file->command_state is still cs_running if all the commands
442 ran; notice_finish_file looks for cs_running to tell it that
443 it's interesting to check the file's modtime again now. */
445 if (! handling_fatal_signal)
446 /* Notice if the target of the commands has been changed.
447 This also propagates its values for command_state and
448 update_status to its also_make files. */
449 notice_finished_file (c->file);
451 if (debug_flag)
452 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
453 (unsigned long int) c,
454 c->pid, c->remote ? " (remote)" : "");
456 /* Remove the child from the chain and free it. */
457 if (lastc == 0)
458 children = c->next;
459 else
460 lastc->next = c->next;
461 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
462 free_child (c);
464 /* There is now another slot open. */
465 --job_slots_used;
467 /* If the job failed, and the -k flag was not given, die,
468 unless we are already in the process of dying. */
469 if (!err && child_failed && !keep_going_flag)
470 die (2);
473 /* Only block for one child. */
474 block = 0;
478 /* Free the storage allocated for CHILD. */
480 static void
481 free_child (child)
482 register struct child *child;
484 if (child->command_lines != 0)
486 register unsigned int i;
487 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
488 free (child->command_lines[i]);
489 free ((char *) child->command_lines);
492 if (child->environment != 0)
494 register char **ep = child->environment;
495 while (*ep != 0)
496 free (*ep++);
497 free ((char *) child->environment);
500 free ((char *) child);
503 #ifdef POSIX
504 #ifdef __MSDOS__
505 void
506 unblock_sigs ()
508 return;
510 #else
511 extern sigset_t fatal_signal_set;
513 void
514 unblock_sigs ()
516 sigset_t empty;
517 sigemptyset (&empty);
518 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
520 #endif
521 #endif
523 /* Start a job to run the commands specified in CHILD.
524 CHILD is updated to reflect the commands and ID of the child process. */
526 static void
527 start_job_command (child)
528 register struct child *child;
530 static int bad_stdin = -1;
531 register char *p;
532 int flags;
533 char **argv;
535 /* Combine the flags parsed for the line itself with
536 the flags specified globally for this target. */
537 flags = (child->file->command_flags
538 | child->file->cmds->lines_flags[child->command_line - 1]);
540 p = child->command_ptr;
541 child->noerror = flags & COMMANDS_NOERROR;
542 while (*p != '\0')
544 if (*p == '@')
545 flags |= COMMANDS_SILENT;
546 else if (*p == '+')
547 flags |= COMMANDS_RECURSE;
548 else if (*p == '-')
549 child->noerror = 1;
550 else if (!isblank (*p) && *p != '+')
551 break;
552 ++p;
555 /* If -q was given, just say that updating `failed'. The exit status of
556 1 tells the user that -q is saying `something to do'; the exit status
557 for a random error is 2. */
558 if (question_flag && !(flags & COMMANDS_RECURSE))
560 child->file->update_status = 1;
561 notice_finished_file (child->file);
562 return;
565 /* There may be some preceding whitespace left if there
566 was nothing but a backslash on the first line. */
567 p = next_token (p);
569 /* Figure out an argument list from this command line. */
572 char *end;
573 argv = construct_command_argv (p, &end, child->file);
574 if (end == NULL)
575 child->command_ptr = NULL;
576 else
578 *end++ = '\0';
579 child->command_ptr = end;
583 if (touch_flag && !(flags & COMMANDS_RECURSE))
585 /* Go on to the next command. It might be the recursive one.
586 We construct ARGV only to find the end of the command line. */
587 free (argv[0]);
588 free ((char *) argv);
589 argv = 0;
592 if (argv == 0)
594 /* This line has no commands. Go to the next. */
595 if (job_next_command (child))
596 start_job_command (child);
597 child->file->update_status = 0;
598 return;
601 /* Print out the command. */
603 if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
604 puts (p);
606 /* Tell update_goal_chain that a command has been started on behalf of
607 this target. It is important that this happens here and not in
608 reap_children (where we used to do it), because reap_children might be
609 reaping children from a different target. We want this increment to
610 guaranteedly indicate that a command was started for the dependency
611 chain (i.e., update_file recursion chain) we are processing. */
613 ++commands_started;
615 /* If -n was given, recurse to get the next line in the sequence. */
617 if (just_print_flag && !(flags & COMMANDS_RECURSE))
619 free (argv[0]);
620 free ((char *) argv);
621 if (job_next_command (child))
622 start_job_command (child);
623 child->file->update_status = 0;
624 return;
627 /* Flush the output streams so they won't have things written twice. */
629 fflush (stdout);
630 fflush (stderr);
632 /* Set up a bad standard input that reads from a broken pipe. */
634 if (bad_stdin == -1)
636 /* Make a file descriptor that is the read end of a broken pipe.
637 This will be used for some children's standard inputs. */
638 int pd[2];
639 if (pipe (pd) == 0)
641 /* Close the write side. */
642 (void) close (pd[1]);
643 /* Save the read side. */
644 bad_stdin = pd[0];
648 /* Decide whether to give this child the `good' standard input
649 (one that points to the terminal or whatever), or the `bad' one
650 that points to the read side of a broken pipe. */
652 child->good_stdin = !good_stdin_used;
653 if (child->good_stdin)
654 good_stdin_used = 1;
656 child->deleted = 0;
658 /* Set up the environment for the child. */
659 if (child->environment == 0)
660 child->environment = target_environment (child->file);
662 #ifndef __MSDOS__
664 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
665 if (child->remote)
667 int is_remote, id, used_stdin;
668 if (start_remote_job (argv, child->environment,
669 child->good_stdin ? 0 : bad_stdin,
670 &is_remote, &id, &used_stdin))
671 goto error;
672 else
674 if (child->good_stdin && !used_stdin)
676 child->good_stdin = 0;
677 good_stdin_used = 0;
679 child->remote = is_remote;
680 child->pid = id;
683 else
685 /* Fork the child process. */
687 #ifdef POSIX
688 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
689 #else
690 #ifdef HAVE_SIGSETMASK
691 (void) sigblock (fatal_signal_mask);
692 #endif
693 #endif
695 child->remote = 0;
696 child->pid = vfork ();
697 if (child->pid == 0)
699 /* We are the child side. */
700 unblock_sigs ();
701 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
702 argv, child->environment);
704 else if (child->pid < 0)
706 /* Fork failed! */
707 unblock_sigs ();
708 perror_with_name ("vfork", "");
709 goto error;
713 #else /* MSDOS. */
714 dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
715 ++dead_children;
716 child->pid = dos_pid++;
717 if (dos_batch_file)
719 dos_batch_file = 0;
720 remove (dos_bname); /* Ignore errors. */
721 if (access (dos_bename, 0))
722 dos_status = 1;
723 else
724 dos_status = 0;
725 remove (dos_bename);
727 #endif /* Not MSDOS. */
729 /* We are the parent side. Set the state to
730 say the commands are running and return. */
732 set_command_state (child->file, cs_running);
734 /* Free the storage used by the child's argument list. */
736 free (argv[0]);
737 free ((char *) argv);
739 return;
741 error:
742 child->file->update_status = 2;
743 notice_finished_file (child->file);
746 /* Try to start a child running.
747 Returns nonzero if the child was started (and maybe finished), or zero if
748 the load was too high and the child was put on the `waiting_jobs' chain. */
750 static int
751 start_waiting_job (c)
752 struct child *c;
754 /* If we can start a job remotely, we always want to, and don't care about
755 the local load average. We record that the job should be started
756 remotely in C->remote for start_job_command to test. */
758 c->remote = start_remote_job_p ();
760 /* If this job is to be started locally, and we are already running
761 some jobs, make this one wait if the load average is too high. */
762 if (!c->remote && job_slots_used > 0 && load_too_high ())
764 /* Put this child on the chain of children waiting
765 for the load average to go down. */
766 c->file->command_state = cs_running;
767 c->next = waiting_jobs;
768 waiting_jobs = c;
769 return 0;
772 /* Start the first command; reap_children will run later command lines. */
773 start_job_command (c);
775 switch (c->file->command_state)
777 case cs_running:
778 c->next = children;
779 if (debug_flag)
780 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
781 (unsigned long int) c,
782 c->pid, c->remote ? " (remote)" : "");
783 children = c;
784 /* One more job slot is in use. */
785 ++job_slots_used;
786 unblock_sigs ();
787 break;
789 case cs_not_started:
790 /* All the command lines turned out to be empty. */
791 c->file->update_status = 0;
792 /* FALLTHROUGH */
794 case cs_finished:
795 notice_finished_file (c->file);
796 free_child (c);
797 break;
799 default:
800 assert (c->file->command_state == cs_finished);
801 break;
804 return 1;
807 /* Create a `struct child' for FILE and start its commands running. */
809 void
810 new_job (file)
811 register struct file *file;
813 register struct commands *cmds = file->cmds;
814 register struct child *c;
815 char **lines;
816 register unsigned int i;
818 /* Let any previously decided-upon jobs that are waiting
819 for the load to go down start before this new one. */
820 start_waiting_jobs ();
822 /* Reap any children that might have finished recently. */
823 reap_children (0, 0);
825 /* Chop the commands up into lines if they aren't already. */
826 chop_commands (cmds);
828 if (job_slots != 0)
829 /* Wait for a job slot to be freed up. */
830 while (job_slots_used == job_slots)
831 reap_children (1, 0);
833 /* Expand the command lines and store the results in LINES. */
834 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
835 for (i = 0; i < cmds->ncommand_lines; ++i)
837 /* Collapse backslash-newline combinations that are inside variable
838 or function references. These are left alone by the parser so
839 that they will appear in the echoing of commands (where they look
840 nice); and collapsed by construct_command_argv when it tokenizes.
841 But letting them survive inside function invocations loses because
842 we don't want the functions to see them as part of the text. */
844 char *in, *out, *ref;
846 /* IN points to where in the line we are scanning.
847 OUT points to where in the line we are writing.
848 When we collapse a backslash-newline combination,
849 IN gets ahead out OUT. */
851 in = out = cmds->command_lines[i];
852 while ((ref = index (in, '$')) != 0)
854 ++ref; /* Move past the $. */
856 if (out != in)
857 /* Copy the text between the end of the last chunk
858 we processed (where IN points) and the new chunk
859 we are about to process (where REF points). */
860 bcopy (in, out, ref - in);
862 /* Move both pointers past the boring stuff. */
863 out += ref - in;
864 in = ref;
866 if (*ref == '(' || *ref == '{')
868 char openparen = *ref;
869 char closeparen = openparen == '(' ? ')' : '}';
870 int count;
871 char *p;
873 *out++ = *in++; /* Copy OPENPAREN. */
874 /* IN now points past the opening paren or brace.
875 Count parens or braces until it is matched. */
876 count = 0;
877 while (*in != '\0')
879 if (*in == closeparen && --count < 0)
880 break;
881 else if (*in == '\\' && in[1] == '\n')
883 /* We have found a backslash-newline inside a
884 variable or function reference. Eat it and
885 any following whitespace. */
887 int quoted = 0;
888 for (p = in - 1; p > ref && *p == '\\'; --p)
889 quoted = !quoted;
891 if (quoted)
892 /* There were two or more backslashes, so this is
893 not really a continuation line. We don't collapse
894 the quoting backslashes here as is done in
895 collapse_continuations, because the line will
896 be collapsed again after expansion. */
897 *out++ = *in++;
898 else
900 /* Skip the backslash, newline and
901 any following whitespace. */
902 in = next_token (in + 2);
904 /* Discard any preceding whitespace that has
905 already been written to the output. */
906 while (out > ref && isblank (out[-1]))
907 --out;
909 /* Replace it all with a single space. */
910 *out++ = ' ';
913 else
915 if (*in == openparen)
916 ++count;
918 *out++ = *in++;
924 /* There are no more references in this line to worry about.
925 Copy the remaining uninteresting text to the output. */
926 if (out != in)
927 strcpy (out, in);
929 /* Finally, expand the line. */
930 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
931 file);
934 /* Start the command sequence, record it in a new
935 `struct child', and add that to the chain. */
937 c = (struct child *) xmalloc (sizeof (struct child));
938 c->file = file;
939 c->command_lines = lines;
940 c->command_line = 0;
941 c->command_ptr = 0;
942 c->environment = 0;
944 /* Fetch the first command line to be run. */
945 if (! job_next_command (c))
947 /* There were no commands! */
948 free_child (c);
949 c->file->update_status = 0;
951 else
953 /* The job is now primed. Start it running. */
954 start_waiting_job (c);
956 if (job_slots == 1)
957 /* Since there is only one job slot, make things run linearly.
958 Wait for the child to die, setting the state to `cs_finished'. */
959 while (file->command_state == cs_running)
960 reap_children (1, 0);
964 /* Move CHILD's pointers to the next command for it to execute.
965 Returns nonzero if there is another command. */
967 static int
968 job_next_command (child)
969 struct child *child;
971 if (child->command_ptr == 0 || *child->command_ptr == '\0')
973 /* There are no more lines in the expansion of this line. */
974 if (child->command_line == child->file->cmds->ncommand_lines)
976 /* There are no more lines to be expanded. */
977 child->command_ptr = 0;
978 return 0;
980 else
981 /* Get the next line to run. */
982 child->command_ptr = child->command_lines[child->command_line++];
984 return 1;
987 static int
988 load_too_high ()
990 #ifdef __MSDOS__
991 return 1;
992 #else
993 extern int getloadavg ();
994 double load;
996 if (max_load_average < 0)
997 return 0;
999 make_access ();
1000 if (getloadavg (&load, 1) != 1)
1002 static int lossage = -1;
1003 /* Complain only once for the same error. */
1004 if (lossage == -1 || errno != lossage)
1006 if (errno == 0)
1007 /* An errno value of zero means getloadavg is just unsupported. */
1008 error ("cannot enforce load limits on this operating system");
1009 else
1010 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1012 lossage = errno;
1013 load = 0;
1015 user_access ();
1017 return load >= max_load_average;
1018 #endif
1021 /* Start jobs that are waiting for the load to be lower. */
1023 void
1024 start_waiting_jobs ()
1026 struct child *job;
1028 if (waiting_jobs == 0)
1029 return;
1033 /* Check for recently deceased descendants. */
1034 reap_children (0, 0);
1036 /* Take a job off the waiting list. */
1037 job = waiting_jobs;
1038 waiting_jobs = job->next;
1040 /* Try to start that job. We break out of the loop as soon
1041 as start_waiting_job puts one back on the waiting list. */
1042 } while (start_waiting_job (job) && waiting_jobs != 0);
1045 /* Replace the current process with one executing the command in ARGV.
1046 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1047 the environment of the new program. This function does not return. */
1049 void
1050 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1051 int stdin_fd, stdout_fd;
1052 char **argv, **envp;
1054 if (stdin_fd != 0)
1055 (void) dup2 (stdin_fd, 0);
1056 if (stdout_fd != 1)
1057 (void) dup2 (stdout_fd, 1);
1059 /* Free up file descriptors. */
1061 register int d;
1062 int max = getdtablesize ();
1063 for (d = 3; d < max; ++d)
1064 (void) close (d);
1067 /* Run the command. */
1068 exec_command (argv, envp);
1071 /* Search PATH for FILE.
1072 If successful, store the full pathname in PROGRAM and return 1.
1073 If not sucessful, return zero. */
1075 static int
1076 search_path (file, path, program)
1077 char *file, *path, *program;
1079 if (path == 0 || path[0] == '\0')
1080 path = default_path;
1082 if (
1083 #ifdef __MSDOS__
1084 strpbrk (file, "/\\:")
1085 #else
1086 index (file, '/')
1087 #endif
1088 != 0)
1090 strcpy (program, file);
1091 return 1;
1093 else
1095 unsigned int len;
1097 #ifdef HAVE_GETGROUPS
1098 #ifndef HAVE_UNISTD_H
1099 extern int getgroups ();
1100 #endif
1101 static int ngroups = -1;
1102 #ifdef NGROUPS_MAX
1103 static GETGROUPS_T groups[NGROUPS_MAX];
1104 #define ngroups_max NGROUPS_MAX
1105 #else
1106 static GETGROUPS_T *groups = 0;
1107 static int ngroups_max;
1108 if (groups == 0)
1110 ngroups_max = GET_NGROUPS_MAX;
1111 groups = (GETGROUPS_T *) malloc (ngroups_max * sizeof (GETGROUPS_T));
1113 #endif
1114 if (groups != 0 && ngroups == -1)
1115 ngroups = getgroups (ngroups_max, groups);
1116 #endif /* Have getgroups. */
1118 len = strlen (file) + 1;
1121 struct stat st;
1122 int perm;
1123 char *p;
1125 p = index (path, PATH_SEPARATOR_CHAR);
1126 if (p == 0)
1127 p = path + strlen (path);
1129 if (p == path)
1130 bcopy (file, program, len);
1131 else
1133 bcopy (path, program, p - path);
1134 program[p - path] = '/';
1135 bcopy (file, program + (p - path) + 1, len);
1138 if (safe_stat (program, &st) == 0
1139 && S_ISREG (st.st_mode))
1141 if (st.st_uid == geteuid ())
1142 perm = (st.st_mode & 0100);
1143 else if (st.st_gid == getegid ())
1144 perm = (st.st_mode & 0010);
1145 else
1147 #ifdef HAVE_GETGROUPS
1148 register int i;
1149 for (i = 0; i < ngroups; ++i)
1150 if (groups[i] == st.st_gid)
1151 break;
1152 if (i < ngroups)
1153 perm = (st.st_mode & 0010);
1154 else
1155 #endif /* Have getgroups. */
1156 perm = (st.st_mode & 0001);
1159 if (perm != 0)
1160 return 1;
1163 path = p + 1;
1164 } while (*path != '\0');
1167 return 0;
1170 /* Replace the current process with one running the command in ARGV,
1171 with environment ENVP. This function does not return. */
1173 void
1174 exec_command (argv, envp)
1175 char **argv, **envp;
1177 char *shell, *path;
1178 PATH_VAR (program);
1179 register char **ep;
1181 shell = path = 0;
1182 for (ep = envp; *ep != 0; ++ep)
1184 if (shell == 0 && !strncmp(*ep, "SHELL=", 6))
1185 shell = &(*ep)[6];
1186 else if (path == 0 && !strncmp(*ep, "PATH=", 5))
1187 path = &(*ep)[5];
1188 else if (path != 0 && shell != 0)
1189 break;
1192 /* Be the user, permanently. */
1193 child_access ();
1195 if (!search_path (argv[0], path, program))
1196 error ("%s: Command not found", argv[0]);
1197 else
1199 /* Run the program. */
1200 execve (program, argv, envp);
1202 if (errno == ENOEXEC)
1204 PATH_VAR (shell_program);
1205 char *shell_path;
1206 if (shell == 0)
1207 shell_path = default_shell;
1208 else
1210 if (search_path (shell, path, shell_program))
1211 shell_path = shell_program;
1212 else
1214 shell_path = 0;
1215 error ("%s: Shell program not found", shell);
1219 if (shell_path != 0)
1221 char **new_argv;
1222 int argc;
1224 argc = 1;
1225 while (argv[argc] != 0)
1226 ++argc;
1228 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1229 new_argv[0] = shell_path;
1230 new_argv[1] = program;
1231 while (argc > 0)
1233 new_argv[1 + argc] = argv[argc];
1234 --argc;
1237 execve (shell_path, new_argv, envp);
1238 perror_with_name ("execve: ", shell_path);
1241 else
1242 perror_with_name ("execve: ", program);
1245 _exit (127);
1248 /* Figure out the argument list necessary to run LINE as a command.
1249 Try to avoid using a shell. This routine handles only ' quoting.
1250 Starting quotes may be escaped with a backslash. If any of the
1251 characters in sh_chars[] is seen, or any of the builtin commands
1252 listed in sh_cmds[] is the first word of a line, the shell is used.
1254 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1255 If *RESTP is NULL, newlines will be ignored.
1257 SHELL is the shell to use, or nil to use the default shell.
1258 IFS is the value of $IFS, or nil (meaning the default). */
1260 static char **
1261 construct_command_argv_internal (line, restp, shell, ifs)
1262 char *line, **restp;
1263 char *shell, *ifs;
1265 #ifdef __MSDOS__
1266 static char sh_chars[] = "\"|<>";
1267 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1268 "copy", "ctty", "date", "del", "dir", "echo",
1269 "erase", "exit", "for", "goto", "if", "if", "md",
1270 "mkdir", "path", "pause", "prompt", "rem", "ren",
1271 "rename", "set", "shift", "time", "type",
1272 "ver", "verify", "vol", ":", 0 };
1273 #else
1274 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1275 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1276 "logout", "set", "umask", "wait", "while", "for",
1277 "case", "if", ":", ".", "break", "continue",
1278 "export", "read", "readonly", "shift", "times",
1279 "trap", "switch", 0 };
1280 #endif
1281 register int i;
1282 register char *p;
1283 register char *ap;
1284 char *end;
1285 int instring, word_has_equals, seen_nonequals;
1286 char **new_argv = 0;
1288 if (restp != NULL)
1289 *restp = NULL;
1291 /* Make sure not to bother processing an empty line. */
1292 while (isblank (*line))
1293 ++line;
1294 if (*line == '\0')
1295 return 0;
1297 /* See if it is safe to parse commands internally. */
1298 if (shell == 0)
1299 shell = default_shell;
1300 else if (strcmp (shell, default_shell))
1301 goto slow;
1303 if (ifs != 0)
1304 for (ap = ifs; *ap != '\0'; ++ap)
1305 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1306 goto slow;
1308 i = strlen (line) + 1;
1310 /* More than 1 arg per character is impossible. */
1311 new_argv = (char **) xmalloc (i * sizeof (char *));
1313 /* All the args can fit in a buffer as big as LINE is. */
1314 ap = new_argv[0] = (char *) xmalloc (i);
1315 end = ap + i;
1317 /* I is how many complete arguments have been found. */
1318 i = 0;
1319 instring = word_has_equals = seen_nonequals = 0;
1320 for (p = line; *p != '\0'; ++p)
1322 if (ap > end)
1323 abort ();
1325 if (instring)
1327 string_char:
1328 /* Inside a string, just copy any char except a closing quote
1329 or a backslash-newline combination. */
1330 if (*p == '\'')
1331 instring = 0;
1332 else if (*p == '\\' && p[1] == '\n')
1333 goto swallow_escaped_newline;
1334 else if (*p == '\n' && restp != NULL)
1336 /* End of the command line. */
1337 *restp = p;
1338 goto end_of_line;
1340 else
1341 *ap++ = *p;
1343 else if (index (sh_chars, *p) != 0)
1344 /* Not inside a string, but it's a special char. */
1345 goto slow;
1346 else
1347 /* Not a special char. */
1348 switch (*p)
1350 case '=':
1351 /* Equals is a special character in leading words before the
1352 first word with no equals sign in it. This is not the case
1353 with sh -k, but we never get here when using nonstandard
1354 shell flags. */
1355 if (! seen_nonequals)
1356 goto slow;
1357 word_has_equals = 1;
1358 *ap++ = '=';
1359 break;
1361 case '\\':
1362 /* Backslash-newline combinations are eaten. */
1363 if (p[1] == '\n')
1365 swallow_escaped_newline:
1367 /* Eat the backslash, the newline, and following whitespace,
1368 replacing it all with a single space. */
1369 p += 2;
1371 /* If there is a tab after a backslash-newline,
1372 remove it from the source line which will be echoed,
1373 since it was most likely used to line
1374 up the continued line with the previous one. */
1375 if (*p == '\t')
1376 strcpy (p, p + 1);
1378 if (instring)
1379 goto string_char;
1380 else
1382 if (ap != new_argv[i])
1383 /* Treat this as a space, ending the arg.
1384 But if it's at the beginning of the arg, it should
1385 just get eaten, rather than becoming an empty arg. */
1386 goto end_of_arg;
1387 else
1388 p = next_token (p) - 1;
1391 else if (p[1] != '\0')
1392 /* Copy and skip the following char. */
1393 *ap++ = *++p;
1394 break;
1396 case '\'':
1397 instring = 1;
1398 break;
1400 case '\n':
1401 if (restp != NULL)
1403 /* End of the command line. */
1404 *restp = p;
1405 goto end_of_line;
1407 else
1408 /* Newlines are not special. */
1409 *ap++ = '\n';
1410 break;
1412 case ' ':
1413 case '\t':
1414 end_of_arg:
1415 /* We have the end of an argument.
1416 Terminate the text of the argument. */
1417 *ap++ = '\0';
1418 new_argv[++i] = ap;
1420 /* Update SEEN_NONEQUALS, which tells us if every word
1421 heretofore has contained an `='. */
1422 seen_nonequals |= ! word_has_equals;
1423 if (word_has_equals && ! seen_nonequals)
1424 /* An `=' in a word before the first
1425 word without one is magical. */
1426 goto slow;
1427 word_has_equals = 0; /* Prepare for the next word. */
1429 /* If this argument is the command name,
1430 see if it is a built-in shell command.
1431 If so, have the shell handle it. */
1432 if (i == 1)
1434 register int j;
1435 for (j = 0; sh_cmds[j] != 0; ++j)
1436 if (streq (sh_cmds[j], new_argv[0]))
1437 goto slow;
1440 /* Ignore multiple whitespace chars. */
1441 p = next_token (p);
1442 /* Next iteration should examine the first nonwhite char. */
1443 --p;
1444 break;
1446 default:
1447 *ap++ = *p;
1448 break;
1451 end_of_line:
1453 if (instring)
1454 /* Let the shell deal with an unterminated quote. */
1455 goto slow;
1457 /* Terminate the last argument and the argument list. */
1459 *ap = '\0';
1460 if (new_argv[i][0] != '\0')
1461 ++i;
1462 new_argv[i] = 0;
1464 if (i == 1)
1466 register int j;
1467 for (j = 0; sh_cmds[j] != 0; ++j)
1468 if (streq (sh_cmds[j], new_argv[0]))
1469 goto slow;
1472 if (new_argv[0] == 0)
1473 /* Line was empty. */
1474 return 0;
1475 else
1476 return new_argv;
1478 slow:;
1479 /* We must use the shell. */
1481 if (new_argv != 0)
1483 /* Free the old argument list we were working on. */
1484 free (new_argv[0]);
1485 free (new_argv);
1488 #ifdef __MSDOS__
1490 FILE *batch;
1491 dos_batch_file = 1;
1492 if (dos_bname == 0)
1494 dos_bname = tempnam (".", "mk");
1495 for (i = 0; dos_bname[i] != '\0'; ++i)
1496 if (dos_bname[i] == '/')
1497 dos_bname[i] = '\\';
1498 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1499 strcpy (dos_bename, dos_bname);
1500 strcat (dos_bname, ".bat");
1501 strcat (dos_bename, ".err");
1503 batch = fopen(bename, "w"); /* Create a file. */
1504 if (batch != NULL)
1505 fclose (batch);
1506 batch = fopen (dos_bname, "w");
1507 fputs ("@echo off\n", batch);
1508 fputs (line, batch);
1509 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1510 fclose (batch);
1511 new_argv = (char **) xmalloc(2 * sizeof(char *));
1512 new_argv[0] = strdup (bname);
1513 new_argv[1] = 0;
1515 #else /* Not MSDOS. */
1517 /* SHELL may be a multi-word command. Construct a command line
1518 "SHELL -c LINE", with all special chars in LINE escaped.
1519 Then recurse, expanding this command line to get the final
1520 argument list. */
1522 unsigned int shell_len = strlen (shell);
1523 static char minus_c[] = " -c ";
1524 unsigned int line_len = strlen (line);
1526 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1527 + (line_len * 2) + 1);
1529 ap = new_line;
1530 bcopy (shell, ap, shell_len);
1531 ap += shell_len;
1532 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1533 ap += sizeof (minus_c) - 1;
1534 for (p = line; *p != '\0'; ++p)
1536 if (restp != NULL && *p == '\n')
1538 *restp = p;
1539 break;
1541 else if (*p == '\\' && p[1] == '\n')
1543 /* Eat the backslash, the newline, and following whitespace,
1544 replacing it all with a single space (which is escaped
1545 from the shell). */
1546 p += 2;
1548 /* If there is a tab after a backslash-newline,
1549 remove it from the source line which will be echoed,
1550 since it was most likely used to line
1551 up the continued line with the previous one. */
1552 if (*p == '\t')
1553 strcpy (p, p + 1);
1555 p = next_token (p);
1556 --p;
1557 *ap++ = '\\';
1558 *ap++ = ' ';
1559 continue;
1562 if (*p == '\\' || *p == '\''
1563 || isspace (*p)
1564 || index (sh_chars, *p) != 0)
1565 *ap++ = '\\';
1566 *ap++ = *p;
1568 *ap = '\0';
1570 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1571 (char *) 0, (char *) 0);
1573 #endif /* MSDOS. */
1575 return new_argv;
1578 /* Figure out the argument list necessary to run LINE as a command.
1579 Try to avoid using a shell. This routine handles only ' quoting.
1580 Starting quotes may be escaped with a backslash. If any of the
1581 characters in sh_chars[] is seen, or any of the builtin commands
1582 listed in sh_cmds[] is the first word of a line, the shell is used.
1584 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1585 If *RESTP is NULL, newlines will be ignored.
1587 FILE is the target whose commands these are. It is used for
1588 variable expansion for $(SHELL) and $(IFS). */
1590 char **
1591 construct_command_argv (line, restp, file)
1592 char *line, **restp;
1593 struct file *file;
1595 char *shell, *ifs;
1596 char **argv;
1599 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1600 int save = warn_undefined_variables_flag;
1601 warn_undefined_variables_flag = 0;
1603 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1604 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1606 warn_undefined_variables_flag = save;
1609 argv = construct_command_argv_internal (line, restp, shell, ifs);
1611 free (shell);
1612 free (ifs);
1614 return argv;
1617 #ifndef HAVE_DUP2
1619 dup2 (old, new)
1620 int old, new;
1622 int fd;
1624 (void) close (new);
1625 fd = dup (old);
1626 if (fd != new)
1628 (void) close (fd);
1629 errno = EMFILE;
1630 return -1;
1633 return fd;
1635 #endif