(configure, config.h.in): Uncomment these rules.
[make.git] / job.c
bloba977fb5a7cbdb7d586f584b1c74ef7c916c4b4cc
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. */
39 /* If NGROUPS_MAX == 0 then try other methods for finding a real value. */
40 #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0
41 #undef NGROUPS_MAX
42 #endif /* NGROUPS_MAX == 0 */
44 #ifndef NGROUPS_MAX
45 #ifdef POSIX
46 #define GET_NGROUPS_MAX sysconf (_SC_NGROUPS_MAX)
47 #else /* Not POSIX. */
48 #define NGROUPS_MAX NGROUPS
49 #endif /* POSIX. */
50 #endif
52 #ifdef HAVE_SYS_WAIT_H
53 #include <sys/wait.h>
54 #endif
56 #ifdef HAVE_WAITPID
57 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
58 #else /* Don't have waitpid. */
59 #ifdef HAVE_WAIT3
60 #ifndef wait3
61 extern int wait3 ();
62 #endif
63 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
64 #endif /* Have wait3. */
65 #endif /* Have waitpid. */
67 #if !defined (wait) && !defined (POSIX)
68 extern int wait ();
69 #endif
71 #ifndef HAVE_UNION_WAIT
73 #define WAIT_T int
75 #ifndef WTERMSIG
76 #define WTERMSIG(x) ((x) & 0x7f)
77 #endif
78 #ifndef WCOREDUMP
79 #define WCOREDUMP(x) ((x) & 0x80)
80 #endif
81 #ifndef WEXITSTATUS
82 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
83 #endif
84 #ifndef WIFSIGNALED
85 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
86 #endif
87 #ifndef WIFEXITED
88 #define WIFEXITED(x) (WTERMSIG (x) == 0)
89 #endif
91 #else /* Have `union wait'. */
93 #define WAIT_T union wait
94 #ifndef WTERMSIG
95 #define WTERMSIG(x) ((x).w_termsig)
96 #endif
97 #ifndef WCOREDUMP
98 #define WCOREDUMP(x) ((x).w_coredump)
99 #endif
100 #ifndef WEXITSTATUS
101 #define WEXITSTATUS(x) ((x).w_retcode)
102 #endif
103 #ifndef WIFSIGNALED
104 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
105 #endif
106 #ifndef WIFEXITED
107 #define WIFEXITED(x) (WTERMSIG(x) == 0)
108 #endif
110 #endif /* Don't have `union wait'. */
113 #ifndef HAVE_UNISTD_H
114 extern int dup2 ();
115 extern int execve ();
116 extern void _exit ();
117 extern int geteuid (), getegid ();
118 extern int setgid (), getgid ();
119 #endif
121 #ifndef getdtablesize
122 #ifdef HAVE_GETDTABLESIZE
123 extern int getdtablesize ();
124 #else
125 #ifdef HAVE_SYSCONF_OPEN_MAX
126 #define getdtablesize() ((int) sysconf (_SC_OPEN_MAX))
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
136 #endif
138 extern int getloadavg ();
139 extern int start_remote_job_p ();
140 extern int start_remote_job (), remote_status ();
142 RETSIGTYPE child_handler ();
143 static void free_child (), start_job_command ();
144 static int load_too_high (), job_next_command ();
146 /* Chain of all live (or recently deceased) children. */
148 struct child *children = 0;
150 /* Number of children currently running. */
152 unsigned int job_slots_used = 0;
154 /* Nonzero if the `good' standard input is in use. */
156 static int good_stdin_used = 0;
158 /* Chain of children waiting to run until the load average goes down. */
160 static struct child *waiting_jobs = 0;
162 /* Write an error message describing the exit status given in
163 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
164 Append "(ignored)" if IGNORED is nonzero. */
166 static void
167 child_error (target_name, exit_code, exit_sig, coredump, ignored)
168 char *target_name;
169 int exit_code, exit_sig, coredump;
170 int ignored;
172 if (exit_sig == 0)
173 error (ignored ? "[%s] Error %d (ignored)" :
174 "*** [%s] Error %d",
175 target_name, exit_code);
176 else
177 error ("*** [%s] %s%s",
178 target_name, strsignal (exit_sig),
179 coredump ? " (core dumped)" : "");
182 static unsigned int dead_children = 0;
184 /* Notice that a child died.
185 reap_children should be called when convenient. */
186 RETSIGTYPE
187 child_handler (sig)
188 int sig;
190 ++dead_children;
192 if (debug_flag)
193 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
196 extern int shell_function_pid, shell_function_completed;
198 /* Reap dead children, storing the returned status and the new command
199 state (`cs_finished') in the `file' member of the `struct child' for the
200 dead child, and removing the child from the chain. If BLOCK nonzero,
201 reap at least one child, waiting for it to die if necessary. If ERR is
202 nonzero, print an error message first. */
204 void
205 reap_children (block, err)
206 int block, err;
208 WAIT_T status;
210 while ((children != 0 || shell_function_pid != 0) &&
211 (block || dead_children > 0))
213 int remote = 0;
214 register int pid;
215 int exit_code, exit_sig, coredump;
216 register struct child *lastc, *c;
217 int child_failed;
218 int any_remote, any_local;
220 if (err && dead_children == 0)
222 /* We might block for a while, so let the user know why. */
223 fflush (stdout);
224 error ("*** Waiting for unfinished jobs....");
227 /* We have one less dead child to reap.
228 The test and decrement are not atomic; if it is compiled into:
229 register = dead_children - 1;
230 dead_children = register;
231 a SIGCHLD could come between the two instructions.
232 child_handler increments dead_children.
233 The second instruction here would lose that increment. But the
234 only effect of dead_children being wrong is that we might wait
235 longer than necessary to reap a child, and lose some parallelism;
236 and we might print the "Waiting for unfinished jobs" message above
237 when not necessary. */
239 if (dead_children != 0)
240 --dead_children;
242 any_remote = 0;
243 any_local = shell_function_pid != -1;
244 for (c = children; c != 0; c = c->next)
246 any_remote |= c->remote;
247 any_local |= ! c->remote;
248 if (debug_flag)
249 printf ("Live child 0x%08lx PID %d%s\n",
250 (unsigned long int) c,
251 c->pid, c->remote ? " (remote)" : "");
254 /* First, check for remote children. */
255 if (any_remote)
256 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
257 else
258 pid = 0;
259 if (pid < 0)
261 remote_status_lose:
262 #ifdef EINTR
263 if (errno == EINTR)
264 continue;
265 #endif
266 pfatal_with_name ("remote_status");
268 else if (pid == 0)
270 #ifndef __MSDOS__
271 /* No remote children. Check for local children. */
273 if (any_local)
275 #ifdef WAIT_NOHANG
276 if (!block)
277 pid = WAIT_NOHANG (&status);
278 else
279 #endif
280 pid = wait (&status);
282 else
283 pid = 0;
285 if (pid < 0)
287 #ifdef EINTR
288 if (errno == EINTR)
289 continue;
290 #endif
291 pfatal_with_name ("wait");
293 else if (pid == 0)
295 /* No local children. */
296 if (block && any_remote)
298 /* Now try a blocking wait for a remote child. */
299 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
300 if (pid < 0)
301 goto remote_status_lose;
302 else if (pid == 0)
303 /* No remote children either. Finally give up. */
304 break;
305 else
306 /* We got a remote child. */
307 remote = 1;
309 else
310 break;
312 else
314 /* Chop the status word up. */
315 exit_code = WEXITSTATUS (status);
316 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
317 coredump = WCOREDUMP (status);
319 #else /* MSDOS. */
320 /* Life is very different on MSDOS. */
321 pid = dos_pid - 1;
322 status = dos_status;
323 exit_code = dos_status;
324 exit_sig = 0;
325 coredump = 0;
326 #endif /* Not MSDOS. */
328 else
329 /* We got a remote child. */
330 remote = 1;
332 /* Check if this is the child of the `shell' function. */
333 if (!remote && pid == shell_function_pid)
335 /* It is. Leave an indicator for the `shell' function. */
336 if (exit_sig == 0 && exit_code == 127)
337 shell_function_completed = -1;
338 else
339 shell_function_completed = 1;
340 break;
343 child_failed = exit_sig != 0 || exit_code != 0;
345 /* Search for a child matching the deceased one. */
346 lastc = 0;
347 for (c = children; c != 0; lastc = c, c = c->next)
348 if (c->remote == remote && c->pid == pid)
349 break;
351 if (c == 0)
353 /* An unknown child died. */
354 char buf[100];
355 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
356 if (child_failed)
357 child_error (buf, exit_code, exit_sig, coredump,
358 ignore_errors_flag);
359 else
360 error ("%s finished.", buf);
362 else
364 if (debug_flag)
365 printf ("Reaping %s child 0x%08lx PID %d%s\n",
366 child_failed ? "losing" : "winning",
367 (unsigned long int) c,
368 c->pid, c->remote ? " (remote)" : "");
370 /* If this child had the good stdin, say it is now free. */
371 if (c->good_stdin)
372 good_stdin_used = 0;
374 if (child_failed && !c->noerror && !ignore_errors_flag)
376 /* The commands failed. Write an error message,
377 delete non-precious targets, and abort. */
378 static int delete_on_error = -1;
379 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
380 c->file->update_status = 1;
381 if (delete_on_error == -1)
383 struct file *f = lookup_file (".DELETE_ON_ERROR");
384 delete_on_error = f != 0 && f->is_target;
386 if (exit_sig != 0 || delete_on_error)
387 delete_child_targets (c);
389 else
391 if (child_failed)
393 /* The commands failed, but we don't care. */
394 child_error (c->file->name,
395 exit_code, exit_sig, coredump, 1);
396 child_failed = 0;
399 /* If there are more commands to run, try to start them. */
400 if (job_next_command (c))
402 if (handling_fatal_signal)
404 /* Never start new commands while we are dying.
405 Since there are more commands that wanted to be run,
406 the target was not completely remade. So we treat
407 this as if a command had failed. */
408 c->file->update_status = 1;
410 else
412 /* Check again whether to start remotely.
413 Whether or not we want to changes over time.
414 Also, start_remote_job may need state set up
415 by start_remote_job_p. */
416 c->remote = start_remote_job_p ();
417 start_job_command (c);
418 if (c->file->command_state == cs_running)
419 /* We successfully started the new command.
420 Loop to reap more children. */
421 continue;
424 if (c->file->update_status != 0)
425 /* We failed to start the commands. */
426 delete_child_targets (c);
428 else
429 /* There are no more commands. We got through them all
430 without an unignored error. Now the target has been
431 successfully updated. */
432 c->file->update_status = 0;
435 /* When we get here, all the commands for C->file are finished
436 (or aborted) and C->file->update_status contains 0 or 1. But
437 C->file->command_state is still cs_running if all the commands
438 ran; notice_finish_file looks for cs_running to tell it that
439 it's interesting to check the file's modtime again now. */
441 if (! handling_fatal_signal)
442 /* Notice if the target of the commands has been changed.
443 This also propagates its values for command_state and
444 update_status to its also_make files. */
445 notice_finished_file (c->file);
447 if (debug_flag)
448 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
449 (unsigned long int) c,
450 c->pid, c->remote ? " (remote)" : "");
452 /* Remove the child from the chain and free it. */
453 if (lastc == 0)
454 children = c->next;
455 else
456 lastc->next = c->next;
457 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
458 free_child (c);
460 /* There is now another slot open. */
461 --job_slots_used;
463 /* If the job failed, and the -k flag was not given, die,
464 unless we are already in the process of dying. */
465 if (!err && child_failed && !keep_going_flag)
466 die (2);
469 /* Only block for one child. */
470 block = 0;
474 /* Free the storage allocated for CHILD. */
476 static void
477 free_child (child)
478 register struct child *child;
480 if (child->command_lines != 0)
482 register unsigned int i;
483 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
484 free (child->command_lines[i]);
485 free ((char *) child->command_lines);
488 if (child->environment != 0)
490 register char **ep = child->environment;
491 while (*ep != 0)
492 free (*ep++);
493 free ((char *) child->environment);
496 free ((char *) child);
499 #ifdef POSIX
500 #ifdef __MSDOS__
501 void
502 unblock_sigs ()
504 return;
506 #else
507 extern sigset_t fatal_signal_set;
509 void
510 unblock_sigs ()
512 sigset_t empty;
513 sigemptyset (&empty);
514 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
516 #endif
517 #endif
519 /* Start a job to run the commands specified in CHILD.
520 CHILD is updated to reflect the commands and ID of the child process. */
522 static void
523 start_job_command (child)
524 register struct child *child;
526 static int bad_stdin = -1;
527 register char *p;
528 int flags;
529 char **argv;
531 /* Combine the flags parsed for the line itself with
532 the flags specified globally for this target. */
533 flags = (child->file->command_flags
534 | child->file->cmds->lines_flags[child->command_line - 1]);
536 p = child->command_ptr;
537 child->noerror = flags & COMMANDS_NOERROR;
538 while (*p != '\0')
540 if (*p == '@')
541 flags |= COMMANDS_SILENT;
542 else if (*p == '+')
543 flags |= COMMANDS_RECURSE;
544 else if (*p == '-')
545 child->noerror = 1;
546 else if (!isblank (*p) && *p != '+')
547 break;
548 ++p;
551 /* If -q was given, just say that updating `failed'. The exit status of
552 1 tells the user that -q is saying `something to do'; the exit status
553 for a random error is 2. */
554 if (question_flag && !(flags & COMMANDS_RECURSE))
556 child->file->update_status = 1;
557 notice_finished_file (child->file);
558 return;
561 /* There may be some preceding whitespace left if there
562 was nothing but a backslash on the first line. */
563 p = next_token (p);
565 /* Figure out an argument list from this command line. */
568 char *end;
569 argv = construct_command_argv (p, &end, child->file);
570 if (end == NULL)
571 child->command_ptr = NULL;
572 else
574 *end++ = '\0';
575 child->command_ptr = end;
579 if (touch_flag && !(flags & COMMANDS_RECURSE))
581 /* Go on to the next command. It might be the recursive one.
582 We construct ARGV only to find the end of the command line. */
583 free (argv[0]);
584 free ((char *) argv);
585 argv = 0;
588 if (argv == 0)
590 next_command:
591 /* This line has no commands. Go to the next. */
592 if (job_next_command (child))
593 start_job_command (child);
594 else
596 /* No more commands. All done. */
597 child->file->update_status = 0;
598 notice_finished_file (child->file);
600 return;
603 /* Print out the command. */
605 if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
606 puts (p);
608 /* Tell update_goal_chain that a command has been started on behalf of
609 this target. It is important that this happens here and not in
610 reap_children (where we used to do it), because reap_children might be
611 reaping children from a different target. We want this increment to
612 guaranteedly indicate that a command was started for the dependency
613 chain (i.e., update_file recursion chain) we are processing. */
615 ++commands_started;
617 /* If -n was given, recurse to get the next line in the sequence. */
619 if (just_print_flag && !(flags & COMMANDS_RECURSE))
621 free (argv[0]);
622 free ((char *) argv);
623 goto next_command;
626 /* Flush the output streams so they won't have things written twice. */
628 fflush (stdout);
629 fflush (stderr);
631 /* Set up a bad standard input that reads from a broken pipe. */
633 if (bad_stdin == -1)
635 /* Make a file descriptor that is the read end of a broken pipe.
636 This will be used for some children's standard inputs. */
637 int pd[2];
638 if (pipe (pd) == 0)
640 /* Close the write side. */
641 (void) close (pd[1]);
642 /* Save the read side. */
643 bad_stdin = pd[0];
647 /* Decide whether to give this child the `good' standard input
648 (one that points to the terminal or whatever), or the `bad' one
649 that points to the read side of a broken pipe. */
651 child->good_stdin = !good_stdin_used;
652 if (child->good_stdin)
653 good_stdin_used = 1;
655 child->deleted = 0;
657 /* Set up the environment for the child. */
658 if (child->environment == 0)
659 child->environment = target_environment (child->file);
661 #ifndef __MSDOS__
663 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
664 if (child->remote)
666 int is_remote, id, used_stdin;
667 if (start_remote_job (argv, child->environment,
668 child->good_stdin ? 0 : bad_stdin,
669 &is_remote, &id, &used_stdin))
670 goto error;
671 else
673 if (child->good_stdin && !used_stdin)
675 child->good_stdin = 0;
676 good_stdin_used = 0;
678 child->remote = is_remote;
679 child->pid = id;
682 else
684 /* Fork the child process. */
686 char **parent_environ;
688 #ifdef POSIX
689 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
690 #else
691 #ifdef HAVE_SIGSETMASK
692 (void) sigblock (fatal_signal_mask);
693 #endif
694 #endif
696 child->remote = 0;
697 parent_environ = environ;
698 child->pid = vfork ();
699 environ = parent_environ; /* Restore value child may have clobbered. */
700 if (child->pid == 0)
702 /* We are the child side. */
703 unblock_sigs ();
704 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
705 argv, child->environment);
707 else if (child->pid < 0)
709 /* Fork failed! */
710 unblock_sigs ();
711 perror_with_name ("vfork", "");
712 goto error;
716 #else /* MSDOS. */
717 dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
718 ++dead_children;
719 child->pid = dos_pid++;
720 if (dos_batch_file)
722 dos_batch_file = 0;
723 remove (dos_bname); /* Ignore errors. */
724 if (access (dos_bename, 0))
725 dos_status = 1;
726 else
727 dos_status = 0;
728 remove (dos_bename);
730 #endif /* Not MSDOS. */
732 /* We are the parent side. Set the state to
733 say the commands are running and return. */
735 set_command_state (child->file, cs_running);
737 /* Free the storage used by the child's argument list. */
739 free (argv[0]);
740 free ((char *) argv);
742 return;
744 error:
745 child->file->update_status = 2;
746 notice_finished_file (child->file);
749 /* Try to start a child running.
750 Returns nonzero if the child was started (and maybe finished), or zero if
751 the load was too high and the child was put on the `waiting_jobs' chain. */
753 static int
754 start_waiting_job (c)
755 struct child *c;
757 /* If we can start a job remotely, we always want to, and don't care about
758 the local load average. We record that the job should be started
759 remotely in C->remote for start_job_command to test. */
761 c->remote = start_remote_job_p ();
763 /* If this job is to be started locally, and we are already running
764 some jobs, make this one wait if the load average is too high. */
765 if (!c->remote && job_slots_used > 0 && load_too_high ())
767 /* Put this child on the chain of children waiting
768 for the load average to go down. */
769 set_command_state (c->file, cs_running);
770 c->next = waiting_jobs;
771 waiting_jobs = c;
772 return 0;
775 /* Start the first command; reap_children will run later command lines. */
776 start_job_command (c);
778 switch (c->file->command_state)
780 case cs_running:
781 c->next = children;
782 if (debug_flag)
783 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
784 (unsigned long int) c,
785 c->pid, c->remote ? " (remote)" : "");
786 children = c;
787 /* One more job slot is in use. */
788 ++job_slots_used;
789 unblock_sigs ();
790 break;
792 case cs_not_started:
793 /* All the command lines turned out to be empty. */
794 c->file->update_status = 0;
795 /* FALLTHROUGH */
797 case cs_finished:
798 notice_finished_file (c->file);
799 free_child (c);
800 break;
802 default:
803 assert (c->file->command_state == cs_finished);
804 break;
807 return 1;
810 /* Create a `struct child' for FILE and start its commands running. */
812 void
813 new_job (file)
814 register struct file *file;
816 register struct commands *cmds = file->cmds;
817 register struct child *c;
818 char **lines;
819 register unsigned int i;
821 /* Let any previously decided-upon jobs that are waiting
822 for the load to go down start before this new one. */
823 start_waiting_jobs ();
825 /* Reap any children that might have finished recently. */
826 reap_children (0, 0);
828 /* Chop the commands up into lines if they aren't already. */
829 chop_commands (cmds);
831 if (job_slots != 0)
832 /* Wait for a job slot to be freed up. */
833 while (job_slots_used == job_slots)
834 reap_children (1, 0);
836 /* Expand the command lines and store the results in LINES. */
837 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
838 for (i = 0; i < cmds->ncommand_lines; ++i)
840 /* Collapse backslash-newline combinations that are inside variable
841 or function references. These are left alone by the parser so
842 that they will appear in the echoing of commands (where they look
843 nice); and collapsed by construct_command_argv when it tokenizes.
844 But letting them survive inside function invocations loses because
845 we don't want the functions to see them as part of the text. */
847 char *in, *out, *ref;
849 /* IN points to where in the line we are scanning.
850 OUT points to where in the line we are writing.
851 When we collapse a backslash-newline combination,
852 IN gets ahead out OUT. */
854 in = out = cmds->command_lines[i];
855 while ((ref = index (in, '$')) != 0)
857 ++ref; /* Move past the $. */
859 if (out != in)
860 /* Copy the text between the end of the last chunk
861 we processed (where IN points) and the new chunk
862 we are about to process (where REF points). */
863 bcopy (in, out, ref - in);
865 /* Move both pointers past the boring stuff. */
866 out += ref - in;
867 in = ref;
869 if (*ref == '(' || *ref == '{')
871 char openparen = *ref;
872 char closeparen = openparen == '(' ? ')' : '}';
873 int count;
874 char *p;
876 *out++ = *in++; /* Copy OPENPAREN. */
877 /* IN now points past the opening paren or brace.
878 Count parens or braces until it is matched. */
879 count = 0;
880 while (*in != '\0')
882 if (*in == closeparen && --count < 0)
883 break;
884 else if (*in == '\\' && in[1] == '\n')
886 /* We have found a backslash-newline inside a
887 variable or function reference. Eat it and
888 any following whitespace. */
890 int quoted = 0;
891 for (p = in - 1; p > ref && *p == '\\'; --p)
892 quoted = !quoted;
894 if (quoted)
895 /* There were two or more backslashes, so this is
896 not really a continuation line. We don't collapse
897 the quoting backslashes here as is done in
898 collapse_continuations, because the line will
899 be collapsed again after expansion. */
900 *out++ = *in++;
901 else
903 /* Skip the backslash, newline and
904 any following whitespace. */
905 in = next_token (in + 2);
907 /* Discard any preceding whitespace that has
908 already been written to the output. */
909 while (out > ref && isblank (out[-1]))
910 --out;
912 /* Replace it all with a single space. */
913 *out++ = ' ';
916 else
918 if (*in == openparen)
919 ++count;
921 *out++ = *in++;
927 /* There are no more references in this line to worry about.
928 Copy the remaining uninteresting text to the output. */
929 if (out != in)
930 strcpy (out, in);
932 /* Finally, expand the line. */
933 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
934 file);
937 /* Start the command sequence, record it in a new
938 `struct child', and add that to the chain. */
940 c = (struct child *) xmalloc (sizeof (struct child));
941 c->file = file;
942 c->command_lines = lines;
943 c->command_line = 0;
944 c->command_ptr = 0;
945 c->environment = 0;
947 /* Fetch the first command line to be run. */
948 if (! job_next_command (c))
950 /* There were no commands! */
951 free_child (c);
952 c->file->update_status = 0;
954 else
956 /* The job is now primed. Start it running. */
957 start_waiting_job (c);
959 if (job_slots == 1)
960 /* Since there is only one job slot, make things run linearly.
961 Wait for the child to die, setting the state to `cs_finished'. */
962 while (file->command_state == cs_running)
963 reap_children (1, 0);
967 /* Move CHILD's pointers to the next command for it to execute.
968 Returns nonzero if there is another command. */
970 static int
971 job_next_command (child)
972 struct child *child;
974 if (child->command_ptr == 0 || *child->command_ptr == '\0')
976 /* There are no more lines in the expansion of this line. */
977 if (child->command_line == child->file->cmds->ncommand_lines)
979 /* There are no more lines to be expanded. */
980 child->command_ptr = 0;
981 return 0;
983 else
984 /* Get the next line to run. */
985 child->command_ptr = child->command_lines[child->command_line++];
987 return 1;
990 static int
991 load_too_high ()
993 #ifdef __MSDOS__
994 return 1;
995 #else
996 extern int getloadavg ();
997 double load;
999 if (max_load_average < 0)
1000 return 0;
1002 make_access ();
1003 if (getloadavg (&load, 1) != 1)
1005 static int lossage = -1;
1006 /* Complain only once for the same error. */
1007 if (lossage == -1 || errno != lossage)
1009 if (errno == 0)
1010 /* An errno value of zero means getloadavg is just unsupported. */
1011 error ("cannot enforce load limits on this operating system");
1012 else
1013 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1015 lossage = errno;
1016 load = 0;
1018 user_access ();
1020 return load >= max_load_average;
1021 #endif
1024 /* Start jobs that are waiting for the load to be lower. */
1026 void
1027 start_waiting_jobs ()
1029 struct child *job;
1031 if (waiting_jobs == 0)
1032 return;
1036 /* Check for recently deceased descendants. */
1037 reap_children (0, 0);
1039 /* Take a job off the waiting list. */
1040 job = waiting_jobs;
1041 waiting_jobs = job->next;
1043 /* Try to start that job. We break out of the loop as soon
1044 as start_waiting_job puts one back on the waiting list. */
1045 } while (start_waiting_job (job) && waiting_jobs != 0);
1048 /* Replace the current process with one executing the command in ARGV.
1049 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1050 the environment of the new program. This function does not return. */
1052 void
1053 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1054 int stdin_fd, stdout_fd;
1055 char **argv, **envp;
1057 if (stdin_fd != 0)
1058 (void) dup2 (stdin_fd, 0);
1059 if (stdout_fd != 1)
1060 (void) dup2 (stdout_fd, 1);
1062 /* Free up file descriptors. */
1064 register int d;
1065 int max = getdtablesize ();
1066 for (d = 3; d < max; ++d)
1067 (void) close (d);
1070 /* Run the command. */
1071 exec_command (argv, envp);
1074 #if 0
1076 /* Default path to search for executables. */
1077 static char default_path[] = ":/bin:/usr/bin";
1079 /* Search PATH for FILE.
1080 If successful, store the full pathname in PROGRAM and return 1.
1081 If not sucessful, return zero. */
1083 static int
1084 search_path (file, path, program)
1085 char *file, *path, *program;
1087 if (path == 0 || path[0] == '\0')
1088 path = default_path;
1090 if (
1091 #ifdef __MSDOS__
1092 strpbrk (file, "/\\:")
1093 #else
1094 index (file, '/')
1095 #endif
1096 != 0)
1098 strcpy (program, file);
1099 return 1;
1101 else
1103 unsigned int len;
1105 #ifdef HAVE_GETGROUPS
1106 #ifndef HAVE_UNISTD_H
1107 extern int getgroups ();
1108 #endif
1109 static int ngroups = -1;
1110 #ifdef NGROUPS_MAX
1111 static GETGROUPS_T groups[NGROUPS_MAX];
1112 #define ngroups_max NGROUPS_MAX
1113 #else
1114 static GETGROUPS_T *groups = 0;
1115 static int ngroups_max;
1116 if (groups == 0)
1118 ngroups_max = GET_NGROUPS_MAX;
1119 groups = (GETGROUPS_T *) malloc (ngroups_max * sizeof (GETGROUPS_T));
1121 #endif
1122 if (groups != 0 && ngroups == -1)
1123 ngroups = getgroups (ngroups_max, groups);
1124 #endif /* Have getgroups. */
1126 len = strlen (file) + 1;
1129 struct stat st;
1130 int perm;
1131 char *p;
1133 p = index (path, PATH_SEPARATOR_CHAR);
1134 if (p == 0)
1135 p = path + strlen (path);
1137 if (p == path)
1138 bcopy (file, program, len);
1139 else
1141 bcopy (path, program, p - path);
1142 program[p - path] = '/';
1143 bcopy (file, program + (p - path) + 1, len);
1146 if (safe_stat (program, &st) == 0
1147 && S_ISREG (st.st_mode))
1149 if (st.st_uid == geteuid ())
1150 perm = (st.st_mode & 0100);
1151 else if (st.st_gid == getegid ())
1152 perm = (st.st_mode & 0010);
1153 else
1155 #ifdef HAVE_GETGROUPS
1156 register int i;
1157 for (i = 0; i < ngroups; ++i)
1158 if (groups[i] == st.st_gid)
1159 break;
1160 if (i < ngroups)
1161 perm = (st.st_mode & 0010);
1162 else
1163 #endif /* Have getgroups. */
1164 perm = (st.st_mode & 0001);
1167 if (perm != 0)
1168 return 1;
1171 path = p + 1;
1172 } while (*path != '\0');
1175 return 0;
1177 #endif /* search_path commented out */
1179 /* Replace the current process with one running the command in ARGV,
1180 with environment ENVP. This function does not return. */
1182 void
1183 exec_command (argv, envp)
1184 char **argv, **envp;
1186 /* Be the user, permanently. */
1187 child_access ();
1189 /* Run the program. */
1190 environ = envp;
1191 execvp (argv[0], argv);
1193 switch (errno)
1195 case ENOENT:
1196 error ("%s: Command not found", argv[0]);
1197 break;
1198 case ENOEXEC:
1200 /* The file is not executable. Try it as a shell script. */
1201 extern char *getenv ();
1202 char *shell;
1203 char **new_argv;
1204 int argc;
1206 shell = getenv ("SHELL");
1207 if (shell == 0)
1208 shell = default_shell;
1210 argc = 1;
1211 while (argv[argc] != 0)
1212 ++argc;
1214 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1215 new_argv[0] = shell;
1216 new_argv[1] = program;
1217 while (argc > 0)
1219 new_argv[1 + argc] = argv[argc];
1220 --argc;
1223 execvp (shell, new_argv);
1224 if (errno == ENOENT)
1225 error ("%s: Shell program not found", shell);
1226 else
1227 perror_with_name ("execvp: ", shell);
1228 break;
1231 default:
1232 perror_with_name ("execvp: ", argv[0]);
1233 break;
1236 _exit (127);
1239 /* Figure out the argument list necessary to run LINE as a command. Try to
1240 avoid using a shell. This routine handles only ' quoting, and " quoting
1241 when no backslash, $ or ` characters are seen in the quotes. Starting
1242 quotes may be escaped with a backslash. If any of the characters in
1243 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1244 is the first word of a line, the shell is used.
1246 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1247 If *RESTP is NULL, newlines will be ignored.
1249 SHELL is the shell to use, or nil to use the default shell.
1250 IFS is the value of $IFS, or nil (meaning the default). */
1252 static char **
1253 construct_command_argv_internal (line, restp, shell, ifs)
1254 char *line, **restp;
1255 char *shell, *ifs;
1257 #ifdef __MSDOS__
1258 static char sh_chars[] = "\"|<>";
1259 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1260 "copy", "ctty", "date", "del", "dir", "echo",
1261 "erase", "exit", "for", "goto", "if", "if", "md",
1262 "mkdir", "path", "pause", "prompt", "rem", "ren",
1263 "rename", "set", "shift", "time", "type",
1264 "ver", "verify", "vol", ":", 0 };
1265 #else
1266 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1267 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1268 "logout", "set", "umask", "wait", "while", "for",
1269 "case", "if", ":", ".", "break", "continue",
1270 "export", "read", "readonly", "shift", "times",
1271 "trap", "switch", 0 };
1272 #endif
1273 register int i;
1274 register char *p;
1275 register char *ap;
1276 char *end;
1277 int instring, word_has_equals, seen_nonequals;
1278 char **new_argv = 0;
1280 if (restp != NULL)
1281 *restp = NULL;
1283 /* Make sure not to bother processing an empty line. */
1284 while (isblank (*line))
1285 ++line;
1286 if (*line == '\0')
1287 return 0;
1289 /* See if it is safe to parse commands internally. */
1290 if (shell == 0)
1291 shell = default_shell;
1292 else if (strcmp (shell, default_shell))
1293 goto slow;
1295 if (ifs != 0)
1296 for (ap = ifs; *ap != '\0'; ++ap)
1297 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1298 goto slow;
1300 i = strlen (line) + 1;
1302 /* More than 1 arg per character is impossible. */
1303 new_argv = (char **) xmalloc (i * sizeof (char *));
1305 /* All the args can fit in a buffer as big as LINE is. */
1306 ap = new_argv[0] = (char *) xmalloc (i);
1307 end = ap + i;
1309 /* I is how many complete arguments have been found. */
1310 i = 0;
1311 instring = word_has_equals = seen_nonequals = 0;
1312 for (p = line; *p != '\0'; ++p)
1314 if (ap > end)
1315 abort ();
1317 if (instring)
1319 string_char:
1320 /* Inside a string, just copy any char except a closing quote
1321 or a backslash-newline combination. */
1322 if (*p == instring)
1323 instring = 0;
1324 else if (*p == '\\' && p[1] == '\n')
1325 goto swallow_escaped_newline;
1326 else if (*p == '\n' && restp != NULL)
1328 /* End of the command line. */
1329 *restp = p;
1330 goto end_of_line;
1332 /* Backslash, $, and ` are special inside double quotes.
1333 If we see any of those, punt. */
1334 else if (instring == '"' && index ("\\$`", *p) != 0)
1335 goto slow;
1336 else
1337 *ap++ = *p;
1339 else if (index (sh_chars, *p) != 0)
1340 /* Not inside a string, but it's a special char. */
1341 goto slow;
1342 else
1343 /* Not a special char. */
1344 switch (*p)
1346 case '=':
1347 /* Equals is a special character in leading words before the
1348 first word with no equals sign in it. This is not the case
1349 with sh -k, but we never get here when using nonstandard
1350 shell flags. */
1351 if (! seen_nonequals)
1352 goto slow;
1353 word_has_equals = 1;
1354 *ap++ = '=';
1355 break;
1357 case '\\':
1358 /* Backslash-newline combinations are eaten. */
1359 if (p[1] == '\n')
1361 swallow_escaped_newline:
1363 /* Eat the backslash, the newline, and following whitespace,
1364 replacing it all with a single space. */
1365 p += 2;
1367 /* If there is a tab after a backslash-newline,
1368 remove it from the source line which will be echoed,
1369 since it was most likely used to line
1370 up the continued line with the previous one. */
1371 if (*p == '\t')
1372 strcpy (p, p + 1);
1374 if (instring)
1375 goto string_char;
1376 else
1378 if (ap != new_argv[i])
1379 /* Treat this as a space, ending the arg.
1380 But if it's at the beginning of the arg, it should
1381 just get eaten, rather than becoming an empty arg. */
1382 goto end_of_arg;
1383 else
1384 p = next_token (p) - 1;
1387 else if (p[1] != '\0')
1388 /* Copy and skip the following char. */
1389 *ap++ = *++p;
1390 break;
1392 case '\'':
1393 case '"':
1394 instring = *p;
1395 break;
1397 case '\n':
1398 if (restp != NULL)
1400 /* End of the command line. */
1401 *restp = p;
1402 goto end_of_line;
1404 else
1405 /* Newlines are not special. */
1406 *ap++ = '\n';
1407 break;
1409 case ' ':
1410 case '\t':
1411 end_of_arg:
1412 /* We have the end of an argument.
1413 Terminate the text of the argument. */
1414 *ap++ = '\0';
1415 new_argv[++i] = ap;
1417 /* Update SEEN_NONEQUALS, which tells us if every word
1418 heretofore has contained an `='. */
1419 seen_nonequals |= ! word_has_equals;
1420 if (word_has_equals && ! seen_nonequals)
1421 /* An `=' in a word before the first
1422 word without one is magical. */
1423 goto slow;
1424 word_has_equals = 0; /* Prepare for the next word. */
1426 /* If this argument is the command name,
1427 see if it is a built-in shell command.
1428 If so, have the shell handle it. */
1429 if (i == 1)
1431 register int j;
1432 for (j = 0; sh_cmds[j] != 0; ++j)
1433 if (streq (sh_cmds[j], new_argv[0]))
1434 goto slow;
1437 /* Ignore multiple whitespace chars. */
1438 p = next_token (p);
1439 /* Next iteration should examine the first nonwhite char. */
1440 --p;
1441 break;
1443 default:
1444 *ap++ = *p;
1445 break;
1448 end_of_line:
1450 if (instring)
1451 /* Let the shell deal with an unterminated quote. */
1452 goto slow;
1454 /* Terminate the last argument and the argument list. */
1456 *ap = '\0';
1457 if (new_argv[i][0] != '\0')
1458 ++i;
1459 new_argv[i] = 0;
1461 if (i == 1)
1463 register int j;
1464 for (j = 0; sh_cmds[j] != 0; ++j)
1465 if (streq (sh_cmds[j], new_argv[0]))
1466 goto slow;
1469 if (new_argv[0] == 0)
1470 /* Line was empty. */
1471 return 0;
1472 else
1473 return new_argv;
1475 slow:;
1476 /* We must use the shell. */
1478 if (new_argv != 0)
1480 /* Free the old argument list we were working on. */
1481 free (new_argv[0]);
1482 free (new_argv);
1485 #ifdef __MSDOS__
1487 FILE *batch;
1488 dos_batch_file = 1;
1489 if (dos_bname == 0)
1491 dos_bname = tempnam (".", "mk");
1492 for (i = 0; dos_bname[i] != '\0'; ++i)
1493 if (dos_bname[i] == '/')
1494 dos_bname[i] = '\\';
1495 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1496 strcpy (dos_bename, dos_bname);
1497 strcat (dos_bname, ".bat");
1498 strcat (dos_bename, ".err");
1500 batch = fopen(bename, "w"); /* Create a file. */
1501 if (batch != NULL)
1502 fclose (batch);
1503 batch = fopen (dos_bname, "w");
1504 fputs ("@echo off\n", batch);
1505 fputs (line, batch);
1506 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1507 fclose (batch);
1508 new_argv = (char **) xmalloc(2 * sizeof(char *));
1509 new_argv[0] = strdup (bname);
1510 new_argv[1] = 0;
1512 #else /* Not MSDOS. */
1514 /* SHELL may be a multi-word command. Construct a command line
1515 "SHELL -c LINE", with all special chars in LINE escaped.
1516 Then recurse, expanding this command line to get the final
1517 argument list. */
1519 unsigned int shell_len = strlen (shell);
1520 static char minus_c[] = " -c ";
1521 unsigned int line_len = strlen (line);
1523 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1524 + (line_len * 2) + 1);
1526 ap = new_line;
1527 bcopy (shell, ap, shell_len);
1528 ap += shell_len;
1529 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1530 ap += sizeof (minus_c) - 1;
1531 for (p = line; *p != '\0'; ++p)
1533 if (restp != NULL && *p == '\n')
1535 *restp = p;
1536 break;
1538 else if (*p == '\\' && p[1] == '\n')
1540 /* Eat the backslash, the newline, and following whitespace,
1541 replacing it all with a single space (which is escaped
1542 from the shell). */
1543 p += 2;
1545 /* If there is a tab after a backslash-newline,
1546 remove it from the source line which will be echoed,
1547 since it was most likely used to line
1548 up the continued line with the previous one. */
1549 if (*p == '\t')
1550 strcpy (p, p + 1);
1552 p = next_token (p);
1553 --p;
1554 *ap++ = '\\';
1555 *ap++ = ' ';
1556 continue;
1559 if (*p == '\\' || *p == '\'' || *p == '"'
1560 || isspace (*p)
1561 || index (sh_chars, *p) != 0)
1562 *ap++ = '\\';
1563 *ap++ = *p;
1565 *ap = '\0';
1567 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1568 (char *) 0, (char *) 0);
1570 #endif /* MSDOS. */
1572 return new_argv;
1575 /* Figure out the argument list necessary to run LINE as a command. Try to
1576 avoid using a shell. This routine handles only ' quoting, and " quoting
1577 when no backslash, $ or ` characters are seen in the quotes. Starting
1578 quotes may be escaped with a backslash. If any of the characters in
1579 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1580 is the first word of a line, the shell is used.
1582 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1583 If *RESTP is NULL, newlines will be ignored.
1585 FILE is the target whose commands these are. It is used for
1586 variable expansion for $(SHELL) and $(IFS). */
1588 char **
1589 construct_command_argv (line, restp, file)
1590 char *line, **restp;
1591 struct file *file;
1593 char *shell, *ifs;
1594 char **argv;
1597 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1598 int save = warn_undefined_variables_flag;
1599 warn_undefined_variables_flag = 0;
1601 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1602 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1604 warn_undefined_variables_flag = save;
1607 argv = construct_command_argv_internal (line, restp, shell, ifs);
1609 free (shell);
1610 free (ifs);
1612 return argv;
1615 #ifndef HAVE_DUP2
1617 dup2 (old, new)
1618 int old, new;
1620 int fd;
1622 (void) close (new);
1623 fd = dup (old);
1624 if (fd != new)
1626 (void) close (fd);
1627 errno = EMFILE;
1628 return -1;
1631 return fd;
1633 #endif