autoconf
[make.git] / job.c
blob3d4f328b099aef1912f3c7220e56480e070208a7
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988, 89, 90, 91, 92, 93, 94, 1995 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 shell to use. */
27 char default_shell[] = "/bin/sh";
29 #ifdef __MSDOS__
30 #include <process.h>
31 static int dos_pid = 123;
32 static int dos_status;
33 static char *dos_bname;
34 static char *dos_bename;
35 static int dos_batch_file;
36 #endif /* MSDOS. */
38 #ifdef HAVE_FCNTL_H
39 #include <fcntl.h>
40 #else
41 #include <sys/file.h>
42 #endif
45 /* If NGROUPS_MAX == 0 then try other methods for finding a real value. */
46 #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0
47 #undef NGROUPS_MAX
48 #endif /* NGROUPS_MAX == 0 */
50 #ifndef NGROUPS_MAX
51 #ifdef POSIX
52 #define GET_NGROUPS_MAX sysconf (_SC_NGROUPS_MAX)
53 #else /* Not POSIX. */
54 #define NGROUPS_MAX NGROUPS
55 #endif /* POSIX. */
56 #endif
58 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
59 #include <sys/wait.h>
60 #endif
62 #ifdef HAVE_WAITPID
63 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
64 #else /* Don't have waitpid. */
65 #ifdef HAVE_WAIT3
66 #ifndef wait3
67 extern int wait3 ();
68 #endif
69 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
70 #endif /* Have wait3. */
71 #endif /* Have waitpid. */
73 #if !defined (wait) && !defined (POSIX)
74 extern int wait ();
75 #endif
77 #ifndef HAVE_UNION_WAIT
79 #define WAIT_T int
81 #ifndef WTERMSIG
82 #define WTERMSIG(x) ((x) & 0x7f)
83 #endif
84 #ifndef WCOREDUMP
85 #define WCOREDUMP(x) ((x) & 0x80)
86 #endif
87 #ifndef WEXITSTATUS
88 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
89 #endif
90 #ifndef WIFSIGNALED
91 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
92 #endif
93 #ifndef WIFEXITED
94 #define WIFEXITED(x) (WTERMSIG (x) == 0)
95 #endif
97 #else /* Have `union wait'. */
99 #define WAIT_T union wait
100 #ifndef WTERMSIG
101 #define WTERMSIG(x) ((x).w_termsig)
102 #endif
103 #ifndef WCOREDUMP
104 #define WCOREDUMP(x) ((x).w_coredump)
105 #endif
106 #ifndef WEXITSTATUS
107 #define WEXITSTATUS(x) ((x).w_retcode)
108 #endif
109 #ifndef WIFSIGNALED
110 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
111 #endif
112 #ifndef WIFEXITED
113 #define WIFEXITED(x) (WTERMSIG(x) == 0)
114 #endif
116 #endif /* Don't have `union wait'. */
119 #ifndef HAVE_UNISTD_H
120 extern int dup2 ();
121 extern int execve ();
122 extern void _exit ();
123 extern int geteuid (), getegid ();
124 extern int setgid (), getgid ();
125 #endif
127 extern int getloadavg ();
128 extern int start_remote_job_p ();
129 extern int start_remote_job (), remote_status ();
131 RETSIGTYPE child_handler ();
132 void unblock_sigs ();
133 static void free_child (), start_job_command ();
134 static int load_too_high (), job_next_command ();
136 /* Chain of all live (or recently deceased) children. */
138 struct child *children = 0;
140 /* Number of children currently running. */
142 unsigned int job_slots_used = 0;
144 /* Nonzero if the `good' standard input is in use. */
146 static int good_stdin_used = 0;
148 /* Chain of children waiting to run until the load average goes down. */
150 static struct child *waiting_jobs = 0;
152 /* Write an error message describing the exit status given in
153 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
154 Append "(ignored)" if IGNORED is nonzero. */
156 static void
157 child_error (target_name, exit_code, exit_sig, coredump, ignored)
158 char *target_name;
159 int exit_code, exit_sig, coredump;
160 int ignored;
162 if (ignored && silent_flag)
163 return;
165 if (exit_sig == 0)
166 error (ignored ? "[%s] Error %d (ignored)" :
167 "*** [%s] Error %d",
168 target_name, exit_code);
169 else
170 error ("*** [%s] %s%s",
171 target_name, strsignal (exit_sig),
172 coredump ? " (core dumped)" : "");
175 static unsigned int dead_children = 0;
177 /* Notice that a child died.
178 reap_children should be called when convenient. */
179 RETSIGTYPE
180 child_handler (sig)
181 int sig;
183 ++dead_children;
185 if (debug_flag)
186 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
189 extern int shell_function_pid, shell_function_completed;
191 /* Reap dead children, storing the returned status and the new command
192 state (`cs_finished') in the `file' member of the `struct child' for the
193 dead child, and removing the child from the chain. If BLOCK nonzero,
194 reap at least one child, waiting for it to die if necessary. If ERR is
195 nonzero, print an error message first. */
197 void
198 reap_children (block, err)
199 int block, err;
201 WAIT_T status;
203 while ((children != 0 || shell_function_pid != 0) &&
204 (block || dead_children > 0))
206 int remote = 0;
207 register int pid;
208 int exit_code, exit_sig, coredump;
209 register struct child *lastc, *c;
210 int child_failed;
211 int any_remote, any_local;
213 if (err && dead_children == 0)
215 /* We might block for a while, so let the user know why. */
216 fflush (stdout);
217 error ("*** Waiting for unfinished jobs....");
220 /* We have one less dead child to reap.
221 The test and decrement are not atomic; if it is compiled into:
222 register = dead_children - 1;
223 dead_children = register;
224 a SIGCHLD could come between the two instructions.
225 child_handler increments dead_children.
226 The second instruction here would lose that increment. But the
227 only effect of dead_children being wrong is that we might wait
228 longer than necessary to reap a child, and lose some parallelism;
229 and we might print the "Waiting for unfinished jobs" message above
230 when not necessary. */
232 if (dead_children != 0)
233 --dead_children;
235 any_remote = 0;
236 any_local = shell_function_pid != -1;
237 for (c = children; c != 0; c = c->next)
239 any_remote |= c->remote;
240 any_local |= ! c->remote;
241 if (debug_flag)
242 printf ("Live child 0x%08lx PID %d%s\n",
243 (unsigned long int) c,
244 c->pid, c->remote ? " (remote)" : "");
247 /* First, check for remote children. */
248 if (any_remote)
249 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
250 else
251 pid = 0;
252 if (pid < 0)
254 remote_status_lose:
255 #ifdef EINTR
256 if (errno == EINTR)
257 continue;
258 #endif
259 pfatal_with_name ("remote_status");
261 else if (pid == 0)
263 #ifndef __MSDOS__
264 /* No remote children. Check for local children. */
266 if (any_local)
268 #ifdef WAIT_NOHANG
269 if (!block)
270 pid = WAIT_NOHANG (&status);
271 else
272 #endif
273 pid = wait (&status);
275 else
276 pid = 0;
278 if (pid < 0)
280 #ifdef EINTR
281 if (errno == EINTR)
282 continue;
283 #endif
284 pfatal_with_name ("wait");
286 else if (pid == 0)
288 /* No local children. */
289 if (block && any_remote)
291 /* Now try a blocking wait for a remote child. */
292 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
293 if (pid < 0)
294 goto remote_status_lose;
295 else if (pid == 0)
296 /* No remote children either. Finally give up. */
297 break;
298 else
299 /* We got a remote child. */
300 remote = 1;
302 else
303 break;
305 else
307 /* Chop the status word up. */
308 exit_code = WEXITSTATUS (status);
309 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
310 coredump = WCOREDUMP (status);
312 #else /* MSDOS. */
313 /* Life is very different on MSDOS. */
314 pid = dos_pid - 1;
315 status = dos_status;
316 exit_code = dos_status;
317 exit_sig = 0;
318 coredump = 0;
319 #endif /* Not MSDOS. */
321 else
322 /* We got a remote child. */
323 remote = 1;
325 /* Check if this is the child of the `shell' function. */
326 if (!remote && pid == shell_function_pid)
328 /* It is. Leave an indicator for the `shell' function. */
329 if (exit_sig == 0 && exit_code == 127)
330 shell_function_completed = -1;
331 else
332 shell_function_completed = 1;
333 break;
336 child_failed = exit_sig != 0 || exit_code != 0;
338 /* Search for a child matching the deceased one. */
339 lastc = 0;
340 for (c = children; c != 0; lastc = c, c = c->next)
341 if (c->remote == remote && c->pid == pid)
342 break;
344 if (c == 0)
346 /* An unknown child died. */
347 char buf[100];
348 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
349 if (child_failed)
350 child_error (buf, exit_code, exit_sig, coredump,
351 ignore_errors_flag);
352 else
353 error ("%s finished.", buf);
355 else
357 if (debug_flag)
358 printf ("Reaping %s child 0x%08lx PID %d%s\n",
359 child_failed ? "losing" : "winning",
360 (unsigned long int) c,
361 c->pid, c->remote ? " (remote)" : "");
363 /* If this child had the good stdin, say it is now free. */
364 if (c->good_stdin)
365 good_stdin_used = 0;
367 if (child_failed && !c->noerror && !ignore_errors_flag)
369 /* The commands failed. Write an error message,
370 delete non-precious targets, and abort. */
371 static int delete_on_error = -1;
372 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
373 c->file->update_status = 2;
374 if (delete_on_error == -1)
376 struct file *f = lookup_file (".DELETE_ON_ERROR");
377 delete_on_error = f != 0 && f->is_target;
379 if (exit_sig != 0 || delete_on_error)
380 delete_child_targets (c);
382 else
384 if (child_failed)
386 /* The commands failed, but we don't care. */
387 child_error (c->file->name,
388 exit_code, exit_sig, coredump, 1);
389 child_failed = 0;
392 /* If there are more commands to run, try to start them. */
393 if (job_next_command (c))
395 if (handling_fatal_signal)
397 /* Never start new commands while we are dying.
398 Since there are more commands that wanted to be run,
399 the target was not completely remade. So we treat
400 this as if a command had failed. */
401 c->file->update_status = 2;
403 else
405 /* Check again whether to start remotely.
406 Whether or not we want to changes over time.
407 Also, start_remote_job may need state set up
408 by start_remote_job_p. */
409 c->remote = start_remote_job_p ();
410 start_job_command (c);
411 /* Fatal signals are left blocked in case we were
412 about to put that child on the chain. But it is
413 already there, so it is safe for a fatal signal to
414 arrive now; it will clean up this child's targets. */
415 unblock_sigs ();
416 if (c->file->command_state == cs_running)
417 /* We successfully started the new command.
418 Loop to reap more children. */
419 continue;
422 if (c->file->update_status != 0)
423 /* We failed to start the commands. */
424 delete_child_targets (c);
426 else
427 /* There are no more commands. We got through them all
428 without an unignored error. Now the target has been
429 successfully updated. */
430 c->file->update_status = 0;
433 /* When we get here, all the commands for C->file are finished
434 (or aborted) and C->file->update_status contains 0 or 2. But
435 C->file->command_state is still cs_running if all the commands
436 ran; notice_finish_file looks for cs_running to tell it that
437 it's interesting to check the file's modtime again now. */
439 if (! handling_fatal_signal)
440 /* Notice if the target of the commands has been changed.
441 This also propagates its values for command_state and
442 update_status to its also_make files. */
443 notice_finished_file (c->file);
445 if (debug_flag)
446 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
447 (unsigned long int) c,
448 c->pid, c->remote ? " (remote)" : "");
450 /* Remove the child from the chain and free it. */
451 if (lastc == 0)
452 children = c->next;
453 else
454 lastc->next = c->next;
455 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
456 free_child (c);
458 /* There is now another slot open. */
459 --job_slots_used;
461 /* If the job failed, and the -k flag was not given, die,
462 unless we are already in the process of dying. */
463 if (!err && child_failed && !keep_going_flag)
464 die (2);
467 /* Only block for one child. */
468 block = 0;
472 /* Free the storage allocated for CHILD. */
474 static void
475 free_child (child)
476 register struct child *child;
478 if (child->command_lines != 0)
480 register unsigned int i;
481 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
482 free (child->command_lines[i]);
483 free ((char *) child->command_lines);
486 if (child->environment != 0)
488 register char **ep = child->environment;
489 while (*ep != 0)
490 free (*ep++);
491 free ((char *) child->environment);
494 free ((char *) child);
497 #ifdef POSIX
498 #ifdef __MSDOS__
499 void
500 unblock_sigs ()
502 return;
504 #else
505 extern sigset_t fatal_signal_set;
507 void
508 unblock_sigs ()
510 sigset_t empty;
511 sigemptyset (&empty);
512 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
514 #endif
515 #endif
517 /* Start a job to run the commands specified in CHILD.
518 CHILD is updated to reflect the commands and ID of the child process.
520 NOTE: On return fatal signals are blocked! The caller is responsible
521 for calling `unblock_sigs', once the new child is safely on the chain so
522 it can be cleaned up in the event of a fatal signal. */
524 static void
525 start_job_command (child)
526 register struct child *child;
528 static int bad_stdin = -1;
529 register char *p;
530 int flags;
531 char **argv;
533 /* Combine the flags parsed for the line itself with
534 the flags specified globally for this target. */
535 flags = (child->file->command_flags
536 | child->file->cmds->lines_flags[child->command_line - 1]);
538 p = child->command_ptr;
539 child->noerror = flags & COMMANDS_NOERROR;
540 while (*p != '\0')
542 if (*p == '@')
543 flags |= COMMANDS_SILENT;
544 else if (*p == '+')
545 flags |= COMMANDS_RECURSE;
546 else if (*p == '-')
547 child->noerror = 1;
548 else if (!isblank (*p) && *p != '+')
549 break;
550 ++p;
553 /* If -q was given, just say that updating `failed'. The exit status of
554 1 tells the user that -q is saying `something to do'; the exit status
555 for a random error is 2. */
556 if (question_flag && !(flags & COMMANDS_RECURSE))
558 child->file->update_status = 1;
559 notice_finished_file (child->file);
560 return;
563 /* There may be some preceding whitespace left if there
564 was nothing but a backslash on the first line. */
565 p = next_token (p);
567 /* Figure out an argument list from this command line. */
570 char *end;
571 argv = construct_command_argv (p, &end, child->file);
572 if (end == NULL)
573 child->command_ptr = NULL;
574 else
576 *end++ = '\0';
577 child->command_ptr = end;
581 if (touch_flag && !(flags & COMMANDS_RECURSE))
583 /* Go on to the next command. It might be the recursive one.
584 We construct ARGV only to find the end of the command line. */
585 free (argv[0]);
586 free ((char *) argv);
587 argv = 0;
590 if (argv == 0)
592 next_command:
593 /* This line has no commands. Go to the next. */
594 if (job_next_command (child))
595 start_job_command (child);
596 else
598 /* No more commands. All done. */
599 child->file->update_status = 0;
600 notice_finished_file (child->file);
602 return;
605 /* Print out the command. If silent, we call `message' with null so it
606 can log the working directory before the command's own error messages
607 appear. */
609 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
610 ? "%s" : (char *) 0, p);
612 /* Tell update_goal_chain that a command has been started on behalf of
613 this target. It is important that this happens here and not in
614 reap_children (where we used to do it), because reap_children might be
615 reaping children from a different target. We want this increment to
616 guaranteedly indicate that a command was started for the dependency
617 chain (i.e., update_file recursion chain) we are processing. */
619 ++commands_started;
621 /* If -n was given, recurse to get the next line in the sequence. */
623 if (just_print_flag && !(flags & COMMANDS_RECURSE))
625 free (argv[0]);
626 free ((char *) argv);
627 goto next_command;
630 /* Flush the output streams so they won't have things written twice. */
632 fflush (stdout);
633 fflush (stderr);
635 /* Set up a bad standard input that reads from a broken pipe. */
637 if (bad_stdin == -1)
639 /* Make a file descriptor that is the read end of a broken pipe.
640 This will be used for some children's standard inputs. */
641 int pd[2];
642 if (pipe (pd) == 0)
644 /* Close the write side. */
645 (void) close (pd[1]);
646 /* Save the read side. */
647 bad_stdin = pd[0];
649 /* Set the descriptor to close on exec, so it does not litter any
650 child's descriptor table. When it is dup2'd onto descriptor 0,
651 that descriptor will not close on exec. */
652 #ifdef FD_SETFD
653 #ifndef FD_CLOEXEC
654 #define FD_CLOEXEC 1
655 #endif
656 (void) fcntl (bad_stdin, F_SETFD, FD_CLOEXEC);
657 #endif
661 /* Decide whether to give this child the `good' standard input
662 (one that points to the terminal or whatever), or the `bad' one
663 that points to the read side of a broken pipe. */
665 child->good_stdin = !good_stdin_used;
666 if (child->good_stdin)
667 good_stdin_used = 1;
669 child->deleted = 0;
671 /* Set up the environment for the child. */
672 if (child->environment == 0)
673 child->environment = target_environment (child->file);
675 #ifndef __MSDOS__
677 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
678 if (child->remote)
680 int is_remote, id, used_stdin;
681 if (start_remote_job (argv, child->environment,
682 child->good_stdin ? 0 : bad_stdin,
683 &is_remote, &id, &used_stdin))
684 goto error;
685 else
687 if (child->good_stdin && !used_stdin)
689 child->good_stdin = 0;
690 good_stdin_used = 0;
692 child->remote = is_remote;
693 child->pid = id;
696 else
698 /* Fork the child process. */
700 char **parent_environ;
702 #ifdef POSIX
703 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
704 #else
705 #ifdef HAVE_SIGSETMASK
706 (void) sigblock (fatal_signal_mask);
707 #endif
708 #endif
710 child->remote = 0;
711 parent_environ = environ;
712 child->pid = vfork ();
713 environ = parent_environ; /* Restore value child may have clobbered. */
714 if (child->pid == 0)
716 /* We are the child side. */
717 unblock_sigs ();
718 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
719 argv, child->environment);
721 else if (child->pid < 0)
723 /* Fork failed! */
724 unblock_sigs ();
725 perror_with_name ("vfork", "");
726 goto error;
730 #else /* MSDOS. */
731 dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
732 ++dead_children;
733 child->pid = dos_pid++;
734 if (dos_batch_file)
736 dos_batch_file = 0;
737 remove (dos_bname); /* Ignore errors. */
738 if (access (dos_bename, 0))
739 dos_status = 1;
740 else
741 dos_status = 0;
742 remove (dos_bename);
744 #endif /* Not MSDOS. */
746 /* We are the parent side. Set the state to
747 say the commands are running and return. */
749 set_command_state (child->file, cs_running);
751 /* Free the storage used by the child's argument list. */
753 free (argv[0]);
754 free ((char *) argv);
756 return;
758 error:
759 child->file->update_status = 2;
760 notice_finished_file (child->file);
763 /* Try to start a child running.
764 Returns nonzero if the child was started (and maybe finished), or zero if
765 the load was too high and the child was put on the `waiting_jobs' chain. */
767 static int
768 start_waiting_job (c)
769 struct child *c;
771 /* If we can start a job remotely, we always want to, and don't care about
772 the local load average. We record that the job should be started
773 remotely in C->remote for start_job_command to test. */
775 c->remote = start_remote_job_p ();
777 /* If this job is to be started locally, and we are already running
778 some jobs, make this one wait if the load average is too high. */
779 if (!c->remote && job_slots_used > 0 && load_too_high ())
781 /* Put this child on the chain of children waiting
782 for the load average to go down. */
783 set_command_state (c->file, cs_running);
784 c->next = waiting_jobs;
785 waiting_jobs = c;
786 return 0;
789 /* Start the first command; reap_children will run later command lines. */
790 start_job_command (c);
792 switch (c->file->command_state)
794 case cs_running:
795 c->next = children;
796 if (debug_flag)
797 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
798 (unsigned long int) c,
799 c->pid, c->remote ? " (remote)" : "");
800 children = c;
801 /* One more job slot is in use. */
802 ++job_slots_used;
803 unblock_sigs ();
804 break;
806 case cs_not_started:
807 /* All the command lines turned out to be empty. */
808 c->file->update_status = 0;
809 /* FALLTHROUGH */
811 case cs_finished:
812 notice_finished_file (c->file);
813 free_child (c);
814 break;
816 default:
817 assert (c->file->command_state == cs_finished);
818 break;
821 return 1;
824 /* Create a `struct child' for FILE and start its commands running. */
826 void
827 new_job (file)
828 register struct file *file;
830 register struct commands *cmds = file->cmds;
831 register struct child *c;
832 char **lines;
833 register unsigned int i;
835 /* Let any previously decided-upon jobs that are waiting
836 for the load to go down start before this new one. */
837 start_waiting_jobs ();
839 /* Reap any children that might have finished recently. */
840 reap_children (0, 0);
842 /* Chop the commands up into lines if they aren't already. */
843 chop_commands (cmds);
845 if (job_slots != 0)
846 /* Wait for a job slot to be freed up. */
847 while (job_slots_used == job_slots)
848 reap_children (1, 0);
850 /* Expand the command lines and store the results in LINES. */
851 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
852 for (i = 0; i < cmds->ncommand_lines; ++i)
854 /* Collapse backslash-newline combinations that are inside variable
855 or function references. These are left alone by the parser so
856 that they will appear in the echoing of commands (where they look
857 nice); and collapsed by construct_command_argv when it tokenizes.
858 But letting them survive inside function invocations loses because
859 we don't want the functions to see them as part of the text. */
861 char *in, *out, *ref;
863 /* IN points to where in the line we are scanning.
864 OUT points to where in the line we are writing.
865 When we collapse a backslash-newline combination,
866 IN gets ahead out OUT. */
868 in = out = cmds->command_lines[i];
869 while ((ref = index (in, '$')) != 0)
871 ++ref; /* Move past the $. */
873 if (out != in)
874 /* Copy the text between the end of the last chunk
875 we processed (where IN points) and the new chunk
876 we are about to process (where REF points). */
877 bcopy (in, out, ref - in);
879 /* Move both pointers past the boring stuff. */
880 out += ref - in;
881 in = ref;
883 if (*ref == '(' || *ref == '{')
885 char openparen = *ref;
886 char closeparen = openparen == '(' ? ')' : '}';
887 int count;
888 char *p;
890 *out++ = *in++; /* Copy OPENPAREN. */
891 /* IN now points past the opening paren or brace.
892 Count parens or braces until it is matched. */
893 count = 0;
894 while (*in != '\0')
896 if (*in == closeparen && --count < 0)
897 break;
898 else if (*in == '\\' && in[1] == '\n')
900 /* We have found a backslash-newline inside a
901 variable or function reference. Eat it and
902 any following whitespace. */
904 int quoted = 0;
905 for (p = in - 1; p > ref && *p == '\\'; --p)
906 quoted = !quoted;
908 if (quoted)
909 /* There were two or more backslashes, so this is
910 not really a continuation line. We don't collapse
911 the quoting backslashes here as is done in
912 collapse_continuations, because the line will
913 be collapsed again after expansion. */
914 *out++ = *in++;
915 else
917 /* Skip the backslash, newline and
918 any following whitespace. */
919 in = next_token (in + 2);
921 /* Discard any preceding whitespace that has
922 already been written to the output. */
923 while (out > ref && isblank (out[-1]))
924 --out;
926 /* Replace it all with a single space. */
927 *out++ = ' ';
930 else
932 if (*in == openparen)
933 ++count;
935 *out++ = *in++;
941 /* There are no more references in this line to worry about.
942 Copy the remaining uninteresting text to the output. */
943 if (out != in)
944 strcpy (out, in);
946 /* Finally, expand the line. */
947 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
948 file);
951 /* Start the command sequence, record it in a new
952 `struct child', and add that to the chain. */
954 c = (struct child *) xmalloc (sizeof (struct child));
955 c->file = file;
956 c->command_lines = lines;
957 c->command_line = 0;
958 c->command_ptr = 0;
959 c->environment = 0;
961 /* Fetch the first command line to be run. */
962 job_next_command (c);
964 /* The job is now primed. Start it running.
965 (This will notice if there are in fact no commands.) */
966 start_waiting_job (c);
968 if (job_slots == 1)
969 /* Since there is only one job slot, make things run linearly.
970 Wait for the child to die, setting the state to `cs_finished'. */
971 while (file->command_state == cs_running)
972 reap_children (1, 0);
975 /* Move CHILD's pointers to the next command for it to execute.
976 Returns nonzero if there is another command. */
978 static int
979 job_next_command (child)
980 struct child *child;
982 while (child->command_ptr == 0 || *child->command_ptr == '\0')
984 /* There are no more lines in the expansion of this line. */
985 if (child->command_line == child->file->cmds->ncommand_lines)
987 /* There are no more lines to be expanded. */
988 child->command_ptr = 0;
989 return 0;
991 else
992 /* Get the next line to run. */
993 child->command_ptr = child->command_lines[child->command_line++];
995 return 1;
998 static int
999 load_too_high ()
1001 #ifdef __MSDOS__
1002 return 1;
1003 #else
1004 extern int getloadavg ();
1005 double load;
1007 if (max_load_average < 0)
1008 return 0;
1010 make_access ();
1011 if (getloadavg (&load, 1) != 1)
1013 static int lossage = -1;
1014 /* Complain only once for the same error. */
1015 if (lossage == -1 || errno != lossage)
1017 if (errno == 0)
1018 /* An errno value of zero means getloadavg is just unsupported. */
1019 error ("cannot enforce load limits on this operating system");
1020 else
1021 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1023 lossage = errno;
1024 load = 0;
1026 user_access ();
1028 return load >= max_load_average;
1029 #endif
1032 /* Start jobs that are waiting for the load to be lower. */
1034 void
1035 start_waiting_jobs ()
1037 struct child *job;
1039 if (waiting_jobs == 0)
1040 return;
1044 /* Check for recently deceased descendants. */
1045 reap_children (0, 0);
1047 /* Take a job off the waiting list. */
1048 job = waiting_jobs;
1049 waiting_jobs = job->next;
1051 /* Try to start that job. We break out of the loop as soon
1052 as start_waiting_job puts one back on the waiting list. */
1053 } while (start_waiting_job (job) && waiting_jobs != 0);
1056 /* Replace the current process with one executing the command in ARGV.
1057 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1058 the environment of the new program. This function does not return. */
1060 void
1061 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1062 int stdin_fd, stdout_fd;
1063 char **argv, **envp;
1065 if (stdin_fd != 0)
1066 (void) dup2 (stdin_fd, 0);
1067 if (stdout_fd != 1)
1068 (void) dup2 (stdout_fd, 1);
1069 if (stdin_fd != 0)
1070 (void) close (stdin_fd);
1071 if (stdout_fd != 1)
1072 (void) close (stdout_fd);
1074 /* Run the command. */
1075 exec_command (argv, envp);
1078 /* Replace the current process with one running the command in ARGV,
1079 with environment ENVP. This function does not return. */
1081 void
1082 exec_command (argv, envp)
1083 char **argv, **envp;
1085 /* Be the user, permanently. */
1086 child_access ();
1088 /* Run the program. */
1089 environ = envp;
1090 execvp (argv[0], argv);
1092 switch (errno)
1094 case ENOENT:
1095 error ("%s: Command not found", argv[0]);
1096 break;
1097 case ENOEXEC:
1099 /* The file is not executable. Try it as a shell script. */
1100 extern char *getenv ();
1101 char *shell;
1102 char **new_argv;
1103 int argc;
1105 shell = getenv ("SHELL");
1106 if (shell == 0)
1107 shell = default_shell;
1109 argc = 1;
1110 while (argv[argc] != 0)
1111 ++argc;
1113 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1114 new_argv[0] = shell;
1115 new_argv[1] = argv[0];
1116 while (argc > 0)
1118 new_argv[1 + argc] = argv[argc];
1119 --argc;
1122 execvp (shell, new_argv);
1123 if (errno == ENOENT)
1124 error ("%s: Shell program not found", shell);
1125 else
1126 perror_with_name ("execvp: ", shell);
1127 break;
1130 default:
1131 perror_with_name ("execvp: ", argv[0]);
1132 break;
1135 _exit (127);
1138 /* Figure out the argument list necessary to run LINE as a command. Try to
1139 avoid using a shell. This routine handles only ' quoting, and " quoting
1140 when no backslash, $ or ` characters are seen in the quotes. Starting
1141 quotes may be escaped with a backslash. If any of the characters in
1142 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1143 is the first word of a line, the shell is used.
1145 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1146 If *RESTP is NULL, newlines will be ignored.
1148 SHELL is the shell to use, or nil to use the default shell.
1149 IFS is the value of $IFS, or nil (meaning the default). */
1151 static char **
1152 construct_command_argv_internal (line, restp, shell, ifs)
1153 char *line, **restp;
1154 char *shell, *ifs;
1156 #ifdef __MSDOS__
1157 static char sh_chars[] = "\"|<>";
1158 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1159 "copy", "ctty", "date", "del", "dir", "echo",
1160 "erase", "exit", "for", "goto", "if", "if", "md",
1161 "mkdir", "path", "pause", "prompt", "rem", "ren",
1162 "rename", "set", "shift", "time", "type",
1163 "ver", "verify", "vol", ":", 0 };
1164 #else
1165 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1166 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1167 "logout", "set", "umask", "wait", "while", "for",
1168 "case", "if", ":", ".", "break", "continue",
1169 "export", "read", "readonly", "shift", "times",
1170 "trap", "switch", 0 };
1171 #endif
1172 register int i;
1173 register char *p;
1174 register char *ap;
1175 char *end;
1176 int instring, word_has_equals, seen_nonequals;
1177 char **new_argv = 0;
1179 if (restp != NULL)
1180 *restp = NULL;
1182 /* Make sure not to bother processing an empty line. */
1183 while (isblank (*line))
1184 ++line;
1185 if (*line == '\0')
1186 return 0;
1188 /* See if it is safe to parse commands internally. */
1189 if (shell == 0)
1190 shell = default_shell;
1191 else if (strcmp (shell, default_shell))
1192 goto slow;
1194 if (ifs != 0)
1195 for (ap = ifs; *ap != '\0'; ++ap)
1196 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1197 goto slow;
1199 i = strlen (line) + 1;
1201 /* More than 1 arg per character is impossible. */
1202 new_argv = (char **) xmalloc (i * sizeof (char *));
1204 /* All the args can fit in a buffer as big as LINE is. */
1205 ap = new_argv[0] = (char *) xmalloc (i);
1206 end = ap + i;
1208 /* I is how many complete arguments have been found. */
1209 i = 0;
1210 instring = word_has_equals = seen_nonequals = 0;
1211 for (p = line; *p != '\0'; ++p)
1213 if (ap > end)
1214 abort ();
1216 if (instring)
1218 string_char:
1219 /* Inside a string, just copy any char except a closing quote
1220 or a backslash-newline combination. */
1221 if (*p == instring)
1222 instring = 0;
1223 else if (*p == '\\' && p[1] == '\n')
1224 goto swallow_escaped_newline;
1225 else if (*p == '\n' && restp != NULL)
1227 /* End of the command line. */
1228 *restp = p;
1229 goto end_of_line;
1231 /* Backslash, $, and ` are special inside double quotes.
1232 If we see any of those, punt. */
1233 else if (instring == '"' && index ("\\$`", *p) != 0)
1234 goto slow;
1235 else
1236 *ap++ = *p;
1238 else if (index (sh_chars, *p) != 0)
1239 /* Not inside a string, but it's a special char. */
1240 goto slow;
1241 else
1242 /* Not a special char. */
1243 switch (*p)
1245 case '=':
1246 /* Equals is a special character in leading words before the
1247 first word with no equals sign in it. This is not the case
1248 with sh -k, but we never get here when using nonstandard
1249 shell flags. */
1250 if (! seen_nonequals)
1251 goto slow;
1252 word_has_equals = 1;
1253 *ap++ = '=';
1254 break;
1256 case '\\':
1257 /* Backslash-newline combinations are eaten. */
1258 if (p[1] == '\n')
1260 swallow_escaped_newline:
1262 /* Eat the backslash, the newline, and following whitespace,
1263 replacing it all with a single space. */
1264 p += 2;
1266 /* If there is a tab after a backslash-newline,
1267 remove it from the source line which will be echoed,
1268 since it was most likely used to line
1269 up the continued line with the previous one. */
1270 if (*p == '\t')
1271 strcpy (p, p + 1);
1273 if (instring)
1274 goto string_char;
1275 else
1277 if (ap != new_argv[i])
1278 /* Treat this as a space, ending the arg.
1279 But if it's at the beginning of the arg, it should
1280 just get eaten, rather than becoming an empty arg. */
1281 goto end_of_arg;
1282 else
1283 p = next_token (p) - 1;
1286 else if (p[1] != '\0')
1287 /* Copy and skip the following char. */
1288 *ap++ = *++p;
1289 break;
1291 case '\'':
1292 case '"':
1293 instring = *p;
1294 break;
1296 case '\n':
1297 if (restp != NULL)
1299 /* End of the command line. */
1300 *restp = p;
1301 goto end_of_line;
1303 else
1304 /* Newlines are not special. */
1305 *ap++ = '\n';
1306 break;
1308 case ' ':
1309 case '\t':
1310 end_of_arg:
1311 /* We have the end of an argument.
1312 Terminate the text of the argument. */
1313 *ap++ = '\0';
1314 new_argv[++i] = ap;
1316 /* Update SEEN_NONEQUALS, which tells us if every word
1317 heretofore has contained an `='. */
1318 seen_nonequals |= ! word_has_equals;
1319 if (word_has_equals && ! seen_nonequals)
1320 /* An `=' in a word before the first
1321 word without one is magical. */
1322 goto slow;
1323 word_has_equals = 0; /* Prepare for the next word. */
1325 /* If this argument is the command name,
1326 see if it is a built-in shell command.
1327 If so, have the shell handle it. */
1328 if (i == 1)
1330 register int j;
1331 for (j = 0; sh_cmds[j] != 0; ++j)
1332 if (streq (sh_cmds[j], new_argv[0]))
1333 goto slow;
1336 /* Ignore multiple whitespace chars. */
1337 p = next_token (p);
1338 /* Next iteration should examine the first nonwhite char. */
1339 --p;
1340 break;
1342 default:
1343 *ap++ = *p;
1344 break;
1347 end_of_line:
1349 if (instring)
1350 /* Let the shell deal with an unterminated quote. */
1351 goto slow;
1353 /* Terminate the last argument and the argument list. */
1355 *ap = '\0';
1356 if (new_argv[i][0] != '\0')
1357 ++i;
1358 new_argv[i] = 0;
1360 if (i == 1)
1362 register int j;
1363 for (j = 0; sh_cmds[j] != 0; ++j)
1364 if (streq (sh_cmds[j], new_argv[0]))
1365 goto slow;
1368 if (new_argv[0] == 0)
1369 /* Line was empty. */
1370 return 0;
1371 else
1372 return new_argv;
1374 slow:;
1375 /* We must use the shell. */
1377 if (new_argv != 0)
1379 /* Free the old argument list we were working on. */
1380 free (new_argv[0]);
1381 free (new_argv);
1384 #ifdef __MSDOS__
1386 FILE *batch;
1387 dos_batch_file = 1;
1388 if (dos_bname == 0)
1390 dos_bname = tempnam (".", "mk");
1391 for (i = 0; dos_bname[i] != '\0'; ++i)
1392 if (dos_bname[i] == '/')
1393 dos_bname[i] = '\\';
1394 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1395 strcpy (dos_bename, dos_bname);
1396 strcat (dos_bname, ".bat");
1397 strcat (dos_bename, ".err");
1399 batch = fopen (dos_bename, "w"); /* Create a file. */
1400 if (batch != NULL)
1401 fclose (batch);
1402 batch = fopen (dos_bname, "w");
1403 fputs ("@echo off\n", batch);
1404 fputs (line, batch);
1405 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1406 fclose (batch);
1407 new_argv = (char **) xmalloc(2 * sizeof(char *));
1408 new_argv[0] = strdup (dos_bname);
1409 new_argv[1] = 0;
1411 #else /* Not MSDOS. */
1413 /* SHELL may be a multi-word command. Construct a command line
1414 "SHELL -c LINE", with all special chars in LINE escaped.
1415 Then recurse, expanding this command line to get the final
1416 argument list. */
1418 unsigned int shell_len = strlen (shell);
1419 static char minus_c[] = " -c ";
1420 unsigned int line_len = strlen (line);
1422 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1423 + (line_len * 2) + 1);
1425 ap = new_line;
1426 bcopy (shell, ap, shell_len);
1427 ap += shell_len;
1428 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1429 ap += sizeof (minus_c) - 1;
1430 for (p = line; *p != '\0'; ++p)
1432 if (restp != NULL && *p == '\n')
1434 *restp = p;
1435 break;
1437 else if (*p == '\\' && p[1] == '\n')
1439 /* Eat the backslash, the newline, and following whitespace,
1440 replacing it all with a single space (which is escaped
1441 from the shell). */
1442 p += 2;
1444 /* If there is a tab after a backslash-newline,
1445 remove it from the source line which will be echoed,
1446 since it was most likely used to line
1447 up the continued line with the previous one. */
1448 if (*p == '\t')
1449 strcpy (p, p + 1);
1451 p = next_token (p);
1452 --p;
1453 *ap++ = '\\';
1454 *ap++ = ' ';
1455 continue;
1458 if (*p == '\\' || *p == '\'' || *p == '"'
1459 || isspace (*p)
1460 || index (sh_chars, *p) != 0)
1461 *ap++ = '\\';
1462 *ap++ = *p;
1464 *ap = '\0';
1466 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1467 (char *) 0, (char *) 0);
1469 #endif /* MSDOS. */
1471 return new_argv;
1474 /* Figure out the argument list necessary to run LINE as a command. Try to
1475 avoid using a shell. This routine handles only ' quoting, and " quoting
1476 when no backslash, $ or ` characters are seen in the quotes. Starting
1477 quotes may be escaped with a backslash. If any of the characters in
1478 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1479 is the first word of a line, the shell is used.
1481 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1482 If *RESTP is NULL, newlines will be ignored.
1484 FILE is the target whose commands these are. It is used for
1485 variable expansion for $(SHELL) and $(IFS). */
1487 char **
1488 construct_command_argv (line, restp, file)
1489 char *line, **restp;
1490 struct file *file;
1492 char *shell, *ifs;
1493 char **argv;
1496 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1497 int save = warn_undefined_variables_flag;
1498 warn_undefined_variables_flag = 0;
1500 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1501 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1503 warn_undefined_variables_flag = save;
1506 argv = construct_command_argv_internal (line, restp, shell, ifs);
1508 free (shell);
1509 free (ifs);
1511 return argv;
1514 #ifndef HAVE_DUP2
1516 dup2 (old, new)
1517 int old, new;
1519 int fd;
1521 (void) close (new);
1522 fd = dup (old);
1523 if (fd != new)
1525 (void) close (fd);
1526 errno = EMFILE;
1527 return -1;
1530 return fd;
1532 #endif