RMS documented his .SECONDARY feature.
[make.git] / job.c
blobe5d4d1c542ab037c4a826f48fcfad6ee61c764f7
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988, 89, 90, 91, 92, 93, 94, 95, 96
3 Free Software Foundation, Inc.
4 This file is part of GNU Make.
6 GNU Make is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Make is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Make; see the file COPYING. If not, write to
18 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
20 #include "make.h"
21 #include "commands.h"
22 #include "job.h"
23 #include "file.h"
24 #include "variable.h"
25 #include <assert.h>
27 /* Default shell to use. */
28 char default_shell[] = "/bin/sh";
30 #ifdef __MSDOS__
31 #include <process.h>
32 static int dos_pid = 123;
33 static int dos_status;
34 static char *dos_bname;
35 static char *dos_bename;
36 static int dos_batch_file;
37 #endif /* MSDOS. */
39 #ifdef HAVE_FCNTL_H
40 #include <fcntl.h>
41 #else
42 #include <sys/file.h>
43 #endif
45 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
46 #include <sys/wait.h>
47 #endif
49 #ifdef HAVE_WAITPID
50 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
51 #else /* Don't have waitpid. */
52 #ifdef HAVE_WAIT3
53 #ifndef wait3
54 extern int wait3 ();
55 #endif
56 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
57 #endif /* Have wait3. */
58 #endif /* Have waitpid. */
60 #if !defined (wait) && !defined (POSIX)
61 extern int wait ();
62 #endif
64 #ifndef HAVE_UNION_WAIT
66 #define WAIT_T int
68 #ifndef WTERMSIG
69 #define WTERMSIG(x) ((x) & 0x7f)
70 #endif
71 #ifndef WCOREDUMP
72 #define WCOREDUMP(x) ((x) & 0x80)
73 #endif
74 #ifndef WEXITSTATUS
75 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
76 #endif
77 #ifndef WIFSIGNALED
78 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
79 #endif
80 #ifndef WIFEXITED
81 #define WIFEXITED(x) (WTERMSIG (x) == 0)
82 #endif
84 #else /* Have `union wait'. */
86 #define WAIT_T union wait
87 #ifndef WTERMSIG
88 #define WTERMSIG(x) ((x).w_termsig)
89 #endif
90 #ifndef WCOREDUMP
91 #define WCOREDUMP(x) ((x).w_coredump)
92 #endif
93 #ifndef WEXITSTATUS
94 #define WEXITSTATUS(x) ((x).w_retcode)
95 #endif
96 #ifndef WIFSIGNALED
97 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
98 #endif
99 #ifndef WIFEXITED
100 #define WIFEXITED(x) (WTERMSIG(x) == 0)
101 #endif
103 #endif /* Don't have `union wait'. */
106 #ifndef HAVE_UNISTD_H
107 extern int dup2 ();
108 extern int execve ();
109 extern void _exit ();
110 extern int geteuid (), getegid ();
111 extern int setgid (), getgid ();
112 #endif
114 extern int getloadavg ();
115 extern int start_remote_job_p ();
116 extern int start_remote_job (), remote_status ();
118 RETSIGTYPE child_handler ();
119 static void free_child (), start_job_command ();
120 static int load_too_high (), job_next_command ();
122 /* Chain of all live (or recently deceased) children. */
124 struct child *children = 0;
126 /* Number of children currently running. */
128 unsigned int job_slots_used = 0;
130 /* Nonzero if the `good' standard input is in use. */
132 static int good_stdin_used = 0;
134 /* Chain of children waiting to run until the load average goes down. */
136 static struct child *waiting_jobs = 0;
138 /* Write an error message describing the exit status given in
139 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
140 Append "(ignored)" if IGNORED is nonzero. */
142 static void
143 child_error (target_name, exit_code, exit_sig, coredump, ignored)
144 char *target_name;
145 int exit_code, exit_sig, coredump;
146 int ignored;
148 if (ignored && silent_flag)
149 return;
151 if (exit_sig == 0)
152 error (ignored ? "[%s] Error %d (ignored)" :
153 "*** [%s] Error %d",
154 target_name, exit_code);
155 else
156 error ("*** [%s] %s%s",
157 target_name, strsignal (exit_sig),
158 coredump ? " (core dumped)" : "");
161 static unsigned int dead_children = 0;
163 /* Notice that a child died.
164 reap_children should be called when convenient. */
165 RETSIGTYPE
166 child_handler (sig)
167 int sig;
169 ++dead_children;
171 if (debug_flag)
172 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
175 extern int shell_function_pid, shell_function_completed;
177 /* Reap dead children, storing the returned status and the new command
178 state (`cs_finished') in the `file' member of the `struct child' for the
179 dead child, and removing the child from the chain. If BLOCK nonzero,
180 reap at least one child, waiting for it to die if necessary. If ERR is
181 nonzero, print an error message first. */
183 void
184 reap_children (block, err)
185 int block, err;
187 WAIT_T status;
189 while ((children != 0 || shell_function_pid != 0) &&
190 (block || dead_children > 0))
192 int remote = 0;
193 register int pid;
194 int exit_code, exit_sig, coredump;
195 register struct child *lastc, *c;
196 int child_failed;
197 int any_remote, any_local;
199 if (err && dead_children == 0)
201 /* We might block for a while, so let the user know why. */
202 fflush (stdout);
203 error ("*** Waiting for unfinished jobs....");
206 /* We have one less dead child to reap.
207 The test and decrement are not atomic; if it is compiled into:
208 register = dead_children - 1;
209 dead_children = register;
210 a SIGCHLD could come between the two instructions.
211 child_handler increments dead_children.
212 The second instruction here would lose that increment. But the
213 only effect of dead_children being wrong is that we might wait
214 longer than necessary to reap a child, and lose some parallelism;
215 and we might print the "Waiting for unfinished jobs" message above
216 when not necessary. */
218 if (dead_children != 0)
219 --dead_children;
221 any_remote = 0;
222 any_local = shell_function_pid != -1;
223 for (c = children; c != 0; c = c->next)
225 any_remote |= c->remote;
226 any_local |= ! c->remote;
227 if (debug_flag)
228 printf ("Live child 0x%08lx PID %d%s\n",
229 (unsigned long int) c,
230 c->pid, c->remote ? " (remote)" : "");
233 /* First, check for remote children. */
234 if (any_remote)
235 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
236 else
237 pid = 0;
238 if (pid < 0)
240 remote_status_lose:
241 #ifdef EINTR
242 if (errno == EINTR)
243 continue;
244 #endif
245 pfatal_with_name ("remote_status");
247 else if (pid == 0)
249 #ifndef __MSDOS__
250 /* No remote children. Check for local children. */
252 if (any_local)
254 #ifdef WAIT_NOHANG
255 if (!block)
256 pid = WAIT_NOHANG (&status);
257 else
258 #endif
259 pid = wait (&status);
261 else
262 pid = 0;
264 if (pid < 0)
266 #ifdef EINTR
267 if (errno == EINTR)
268 continue;
269 #endif
270 pfatal_with_name ("wait");
272 else if (pid == 0)
274 /* No local children. */
275 if (block && any_remote)
277 /* Now try a blocking wait for a remote child. */
278 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
279 if (pid < 0)
280 goto remote_status_lose;
281 else if (pid == 0)
282 /* No remote children either. Finally give up. */
283 break;
284 else
285 /* We got a remote child. */
286 remote = 1;
288 else
289 break;
291 else
293 /* Chop the status word up. */
294 exit_code = WEXITSTATUS (status);
295 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
296 coredump = WCOREDUMP (status);
298 #else /* MSDOS. */
299 /* Life is very different on MSDOS. */
300 pid = dos_pid - 1;
301 status = dos_status;
302 exit_code = dos_status;
303 exit_sig = 0;
304 coredump = 0;
305 #endif /* Not MSDOS. */
307 else
308 /* We got a remote child. */
309 remote = 1;
311 /* Check if this is the child of the `shell' function. */
312 if (!remote && pid == shell_function_pid)
314 /* It is. Leave an indicator for the `shell' function. */
315 if (exit_sig == 0 && exit_code == 127)
316 shell_function_completed = -1;
317 else
318 shell_function_completed = 1;
319 break;
322 child_failed = exit_sig != 0 || exit_code != 0;
324 /* Search for a child matching the deceased one. */
325 lastc = 0;
326 for (c = children; c != 0; lastc = c, c = c->next)
327 if (c->remote == remote && c->pid == pid)
328 break;
330 if (c == 0)
332 /* An unknown child died. */
333 char buf[100];
334 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
335 if (child_failed)
336 child_error (buf, exit_code, exit_sig, coredump,
337 ignore_errors_flag);
338 else
339 error ("%s finished.", buf);
341 else
343 if (debug_flag)
344 printf ("Reaping %s child 0x%08lx PID %d%s\n",
345 child_failed ? "losing" : "winning",
346 (unsigned long int) c,
347 c->pid, c->remote ? " (remote)" : "");
349 /* If this child had the good stdin, say it is now free. */
350 if (c->good_stdin)
351 good_stdin_used = 0;
353 if (child_failed && !c->noerror && !ignore_errors_flag)
355 /* The commands failed. Write an error message,
356 delete non-precious targets, and abort. */
357 static int delete_on_error = -1;
358 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
359 c->file->update_status = 2;
360 if (delete_on_error == -1)
362 struct file *f = lookup_file (".DELETE_ON_ERROR");
363 delete_on_error = f != 0 && f->is_target;
365 if (exit_sig != 0 || delete_on_error)
366 delete_child_targets (c);
368 else
370 if (child_failed)
372 /* The commands failed, but we don't care. */
373 child_error (c->file->name,
374 exit_code, exit_sig, coredump, 1);
375 child_failed = 0;
378 /* If there are more commands to run, try to start them. */
379 if (job_next_command (c))
381 if (handling_fatal_signal)
383 /* Never start new commands while we are dying.
384 Since there are more commands that wanted to be run,
385 the target was not completely remade. So we treat
386 this as if a command had failed. */
387 c->file->update_status = 2;
389 else
391 /* Check again whether to start remotely.
392 Whether or not we want to changes over time.
393 Also, start_remote_job may need state set up
394 by start_remote_job_p. */
395 c->remote = start_remote_job_p ();
396 start_job_command (c);
397 /* Fatal signals are left blocked in case we were
398 about to put that child on the chain. But it is
399 already there, so it is safe for a fatal signal to
400 arrive now; it will clean up this child's targets. */
401 unblock_sigs ();
402 if (c->file->command_state == cs_running)
403 /* We successfully started the new command.
404 Loop to reap more children. */
405 continue;
408 if (c->file->update_status != 0)
409 /* We failed to start the commands. */
410 delete_child_targets (c);
412 else
413 /* There are no more commands. We got through them all
414 without an unignored error. Now the target has been
415 successfully updated. */
416 c->file->update_status = 0;
419 /* When we get here, all the commands for C->file are finished
420 (or aborted) and C->file->update_status contains 0 or 2. But
421 C->file->command_state is still cs_running if all the commands
422 ran; notice_finish_file looks for cs_running to tell it that
423 it's interesting to check the file's modtime again now. */
425 if (! handling_fatal_signal)
426 /* Notice if the target of the commands has been changed.
427 This also propagates its values for command_state and
428 update_status to its also_make files. */
429 notice_finished_file (c->file);
431 if (debug_flag)
432 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
433 (unsigned long int) c,
434 c->pid, c->remote ? " (remote)" : "");
436 /* Remove the child from the chain and free it. */
437 if (lastc == 0)
438 children = c->next;
439 else
440 lastc->next = c->next;
441 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
442 free_child (c);
444 /* There is now another slot open. */
445 --job_slots_used;
447 /* If the job failed, and the -k flag was not given, die,
448 unless we are already in the process of dying. */
449 if (!err && child_failed && !keep_going_flag)
450 die (2);
453 /* Only block for one child. */
454 block = 0;
458 /* Free the storage allocated for CHILD. */
460 static void
461 free_child (child)
462 register struct child *child;
464 if (child->command_lines != 0)
466 register unsigned int i;
467 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
468 free (child->command_lines[i]);
469 free ((char *) child->command_lines);
472 if (child->environment != 0)
474 register char **ep = child->environment;
475 while (*ep != 0)
476 free (*ep++);
477 free ((char *) child->environment);
480 free ((char *) child);
483 #ifdef POSIX
484 #ifdef __MSDOS__
485 void
486 unblock_sigs ()
488 return;
490 #else
491 extern sigset_t fatal_signal_set;
493 void
494 unblock_sigs ()
496 sigset_t empty;
497 sigemptyset (&empty);
498 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
500 #endif
501 #endif
503 /* Start a job to run the commands specified in CHILD.
504 CHILD is updated to reflect the commands and ID of the child process.
506 NOTE: On return fatal signals are blocked! The caller is responsible
507 for calling `unblock_sigs', once the new child is safely on the chain so
508 it can be cleaned up in the event of a fatal signal. */
510 static void
511 start_job_command (child)
512 register struct child *child;
514 static int bad_stdin = -1;
515 register char *p;
516 int flags;
517 char **argv;
519 /* Combine the flags parsed for the line itself with
520 the flags specified globally for this target. */
521 flags = (child->file->command_flags
522 | child->file->cmds->lines_flags[child->command_line - 1]);
524 p = child->command_ptr;
525 child->noerror = flags & COMMANDS_NOERROR;
526 while (*p != '\0')
528 if (*p == '@')
529 flags |= COMMANDS_SILENT;
530 else if (*p == '+')
531 flags |= COMMANDS_RECURSE;
532 else if (*p == '-')
533 child->noerror = 1;
534 else if (!isblank (*p) && *p != '+')
535 break;
536 ++p;
539 /* If -q was given, just say that updating `failed'. The exit status of
540 1 tells the user that -q is saying `something to do'; the exit status
541 for a random error is 2. */
542 if (question_flag && !(flags & COMMANDS_RECURSE))
544 child->file->update_status = 1;
545 notice_finished_file (child->file);
546 return;
549 /* There may be some preceding whitespace left if there
550 was nothing but a backslash on the first line. */
551 p = next_token (p);
553 /* Figure out an argument list from this command line. */
556 char *end;
557 argv = construct_command_argv (p, &end, child->file);
558 if (end == NULL)
559 child->command_ptr = NULL;
560 else
562 *end++ = '\0';
563 child->command_ptr = end;
567 if (touch_flag && !(flags & COMMANDS_RECURSE))
569 /* Go on to the next command. It might be the recursive one.
570 We construct ARGV only to find the end of the command line. */
571 free (argv[0]);
572 free ((char *) argv);
573 argv = 0;
576 if (argv == 0)
578 next_command:
579 /* This line has no commands. Go to the next. */
580 if (job_next_command (child))
581 start_job_command (child);
582 else
584 /* No more commands. All done. */
585 child->file->update_status = 0;
586 notice_finished_file (child->file);
588 return;
591 /* Print out the command. If silent, we call `message' with null so it
592 can log the working directory before the command's own error messages
593 appear. */
595 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
596 ? "%s" : (char *) 0, p);
598 /* Tell update_goal_chain that a command has been started on behalf of
599 this target. It is important that this happens here and not in
600 reap_children (where we used to do it), because reap_children might be
601 reaping children from a different target. We want this increment to
602 guaranteedly indicate that a command was started for the dependency
603 chain (i.e., update_file recursion chain) we are processing. */
605 ++commands_started;
607 /* If -n was given, recurse to get the next line in the sequence. */
609 if (just_print_flag && !(flags & COMMANDS_RECURSE))
611 free (argv[0]);
612 free ((char *) argv);
613 goto next_command;
616 /* Flush the output streams so they won't have things written twice. */
618 fflush (stdout);
619 fflush (stderr);
621 /* Set up a bad standard input that reads from a broken pipe. */
623 if (bad_stdin == -1)
625 /* Make a file descriptor that is the read end of a broken pipe.
626 This will be used for some children's standard inputs. */
627 int pd[2];
628 if (pipe (pd) == 0)
630 /* Close the write side. */
631 (void) close (pd[1]);
632 /* Save the read side. */
633 bad_stdin = pd[0];
635 /* Set the descriptor to close on exec, so it does not litter any
636 child's descriptor table. When it is dup2'd onto descriptor 0,
637 that descriptor will not close on exec. */
638 #ifdef FD_SETFD
639 #ifndef FD_CLOEXEC
640 #define FD_CLOEXEC 1
641 #endif
642 (void) fcntl (bad_stdin, F_SETFD, FD_CLOEXEC);
643 #endif
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 job_next_command (c);
950 /* The job is now primed. Start it running.
951 (This will notice if there are in fact no commands.) */
952 start_waiting_job (c);
954 if (job_slots == 1)
955 /* Since there is only one job slot, make things run linearly.
956 Wait for the child to die, setting the state to `cs_finished'. */
957 while (file->command_state == cs_running)
958 reap_children (1, 0);
961 /* Move CHILD's pointers to the next command for it to execute.
962 Returns nonzero if there is another command. */
964 static int
965 job_next_command (child)
966 struct child *child;
968 while (child->command_ptr == 0 || *child->command_ptr == '\0')
970 /* There are no more lines in the expansion of this line. */
971 if (child->command_line == child->file->cmds->ncommand_lines)
973 /* There are no more lines to be expanded. */
974 child->command_ptr = 0;
975 return 0;
977 else
978 /* Get the next line to run. */
979 child->command_ptr = child->command_lines[child->command_line++];
981 return 1;
984 static int
985 load_too_high ()
987 #ifdef __MSDOS__
988 return 1;
989 #else
990 extern int getloadavg ();
991 double load;
993 if (max_load_average < 0)
994 return 0;
996 make_access ();
997 if (getloadavg (&load, 1) != 1)
999 static int lossage = -1;
1000 /* Complain only once for the same error. */
1001 if (lossage == -1 || errno != lossage)
1003 if (errno == 0)
1004 /* An errno value of zero means getloadavg is just unsupported. */
1005 error ("cannot enforce load limits on this operating system");
1006 else
1007 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1009 lossage = errno;
1010 load = 0;
1012 user_access ();
1014 return load >= max_load_average;
1015 #endif
1018 /* Start jobs that are waiting for the load to be lower. */
1020 void
1021 start_waiting_jobs ()
1023 struct child *job;
1025 if (waiting_jobs == 0)
1026 return;
1030 /* Check for recently deceased descendants. */
1031 reap_children (0, 0);
1033 /* Take a job off the waiting list. */
1034 job = waiting_jobs;
1035 waiting_jobs = job->next;
1037 /* Try to start that job. We break out of the loop as soon
1038 as start_waiting_job puts one back on the waiting list. */
1039 } while (start_waiting_job (job) && waiting_jobs != 0);
1042 /* Replace the current process with one executing the command in ARGV.
1043 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1044 the environment of the new program. This function does not return. */
1046 void
1047 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1048 int stdin_fd, stdout_fd;
1049 char **argv, **envp;
1051 if (stdin_fd != 0)
1052 (void) dup2 (stdin_fd, 0);
1053 if (stdout_fd != 1)
1054 (void) dup2 (stdout_fd, 1);
1055 if (stdin_fd != 0)
1056 (void) close (stdin_fd);
1057 if (stdout_fd != 1)
1058 (void) close (stdout_fd);
1060 /* Run the command. */
1061 exec_command (argv, envp);
1064 /* Replace the current process with one running the command in ARGV,
1065 with environment ENVP. This function does not return. */
1067 void
1068 exec_command (argv, envp)
1069 char **argv, **envp;
1071 /* Be the user, permanently. */
1072 child_access ();
1074 /* Run the program. */
1075 environ = envp;
1076 execvp (argv[0], argv);
1078 switch (errno)
1080 case ENOENT:
1081 error ("%s: Command not found", argv[0]);
1082 break;
1083 case ENOEXEC:
1085 /* The file is not executable. Try it as a shell script. */
1086 extern char *getenv ();
1087 char *shell;
1088 char **new_argv;
1089 int argc;
1091 shell = getenv ("SHELL");
1092 if (shell == 0)
1093 shell = default_shell;
1095 argc = 1;
1096 while (argv[argc] != 0)
1097 ++argc;
1099 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1100 new_argv[0] = shell;
1101 new_argv[1] = argv[0];
1102 while (argc > 0)
1104 new_argv[1 + argc] = argv[argc];
1105 --argc;
1108 execvp (shell, new_argv);
1109 if (errno == ENOENT)
1110 error ("%s: Shell program not found", shell);
1111 else
1112 perror_with_name ("execvp: ", shell);
1113 break;
1116 default:
1117 perror_with_name ("execvp: ", argv[0]);
1118 break;
1121 _exit (127);
1124 /* Figure out the argument list necessary to run LINE as a command. Try to
1125 avoid using a shell. This routine handles only ' quoting, and " quoting
1126 when no backslash, $ or ` characters are seen in the quotes. Starting
1127 quotes may be escaped with a backslash. If any of the characters in
1128 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1129 is the first word of a line, the shell is used.
1131 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1132 If *RESTP is NULL, newlines will be ignored.
1134 SHELL is the shell to use, or nil to use the default shell.
1135 IFS is the value of $IFS, or nil (meaning the default). */
1137 static char **
1138 construct_command_argv_internal (line, restp, shell, ifs)
1139 char *line, **restp;
1140 char *shell, *ifs;
1142 #ifdef __MSDOS__
1143 static char sh_chars[] = "\"|<>";
1144 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1145 "copy", "ctty", "date", "del", "dir", "echo",
1146 "erase", "exit", "for", "goto", "if", "if", "md",
1147 "mkdir", "path", "pause", "prompt", "rem", "ren",
1148 "rename", "set", "shift", "time", "type",
1149 "ver", "verify", "vol", ":", 0 };
1150 #else
1151 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1152 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1153 "logout", "set", "umask", "wait", "while", "for",
1154 "case", "if", ":", ".", "break", "continue",
1155 "export", "read", "readonly", "shift", "times",
1156 "trap", "switch", 0 };
1157 #endif
1158 register int i;
1159 register char *p;
1160 register char *ap;
1161 char *end;
1162 int instring, word_has_equals, seen_nonequals;
1163 char **new_argv = 0;
1165 if (restp != NULL)
1166 *restp = NULL;
1168 /* Make sure not to bother processing an empty line. */
1169 while (isblank (*line))
1170 ++line;
1171 if (*line == '\0')
1172 return 0;
1174 /* See if it is safe to parse commands internally. */
1175 if (shell == 0)
1176 shell = default_shell;
1177 else if (strcmp (shell, default_shell))
1178 goto slow;
1180 if (ifs != 0)
1181 for (ap = ifs; *ap != '\0'; ++ap)
1182 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1183 goto slow;
1185 i = strlen (line) + 1;
1187 /* More than 1 arg per character is impossible. */
1188 new_argv = (char **) xmalloc (i * sizeof (char *));
1190 /* All the args can fit in a buffer as big as LINE is. */
1191 ap = new_argv[0] = (char *) xmalloc (i);
1192 end = ap + i;
1194 /* I is how many complete arguments have been found. */
1195 i = 0;
1196 instring = word_has_equals = seen_nonequals = 0;
1197 for (p = line; *p != '\0'; ++p)
1199 if (ap > end)
1200 abort ();
1202 if (instring)
1204 string_char:
1205 /* Inside a string, just copy any char except a closing quote
1206 or a backslash-newline combination. */
1207 if (*p == instring)
1208 instring = 0;
1209 else if (*p == '\\' && p[1] == '\n')
1210 goto swallow_escaped_newline;
1211 else if (*p == '\n' && restp != NULL)
1213 /* End of the command line. */
1214 *restp = p;
1215 goto end_of_line;
1217 /* Backslash, $, and ` are special inside double quotes.
1218 If we see any of those, punt. */
1219 else if (instring == '"' && index ("\\$`", *p) != 0)
1220 goto slow;
1221 else
1222 *ap++ = *p;
1224 else if (index (sh_chars, *p) != 0)
1225 /* Not inside a string, but it's a special char. */
1226 goto slow;
1227 else
1228 /* Not a special char. */
1229 switch (*p)
1231 case '=':
1232 /* Equals is a special character in leading words before the
1233 first word with no equals sign in it. This is not the case
1234 with sh -k, but we never get here when using nonstandard
1235 shell flags. */
1236 if (! seen_nonequals)
1237 goto slow;
1238 word_has_equals = 1;
1239 *ap++ = '=';
1240 break;
1242 case '\\':
1243 /* Backslash-newline combinations are eaten. */
1244 if (p[1] == '\n')
1246 swallow_escaped_newline:
1248 /* Eat the backslash, the newline, and following whitespace,
1249 replacing it all with a single space. */
1250 p += 2;
1252 /* If there is a tab after a backslash-newline,
1253 remove it from the source line which will be echoed,
1254 since it was most likely used to line
1255 up the continued line with the previous one. */
1256 if (*p == '\t')
1257 strcpy (p, p + 1);
1259 if (instring)
1260 goto string_char;
1261 else
1263 if (ap != new_argv[i])
1264 /* Treat this as a space, ending the arg.
1265 But if it's at the beginning of the arg, it should
1266 just get eaten, rather than becoming an empty arg. */
1267 goto end_of_arg;
1268 else
1269 p = next_token (p) - 1;
1272 else if (p[1] != '\0')
1273 /* Copy and skip the following char. */
1274 *ap++ = *++p;
1275 break;
1277 case '\'':
1278 case '"':
1279 instring = *p;
1280 break;
1282 case '\n':
1283 if (restp != NULL)
1285 /* End of the command line. */
1286 *restp = p;
1287 goto end_of_line;
1289 else
1290 /* Newlines are not special. */
1291 *ap++ = '\n';
1292 break;
1294 case ' ':
1295 case '\t':
1296 end_of_arg:
1297 /* We have the end of an argument.
1298 Terminate the text of the argument. */
1299 *ap++ = '\0';
1300 new_argv[++i] = ap;
1302 /* Update SEEN_NONEQUALS, which tells us if every word
1303 heretofore has contained an `='. */
1304 seen_nonequals |= ! word_has_equals;
1305 if (word_has_equals && ! seen_nonequals)
1306 /* An `=' in a word before the first
1307 word without one is magical. */
1308 goto slow;
1309 word_has_equals = 0; /* Prepare for the next word. */
1311 /* If this argument is the command name,
1312 see if it is a built-in shell command.
1313 If so, have the shell handle it. */
1314 if (i == 1)
1316 register int j;
1317 for (j = 0; sh_cmds[j] != 0; ++j)
1318 if (streq (sh_cmds[j], new_argv[0]))
1319 goto slow;
1322 /* Ignore multiple whitespace chars. */
1323 p = next_token (p);
1324 /* Next iteration should examine the first nonwhite char. */
1325 --p;
1326 break;
1328 default:
1329 *ap++ = *p;
1330 break;
1333 end_of_line:
1335 if (instring)
1336 /* Let the shell deal with an unterminated quote. */
1337 goto slow;
1339 /* Terminate the last argument and the argument list. */
1341 *ap = '\0';
1342 if (new_argv[i][0] != '\0')
1343 ++i;
1344 new_argv[i] = 0;
1346 if (i == 1)
1348 register int j;
1349 for (j = 0; sh_cmds[j] != 0; ++j)
1350 if (streq (sh_cmds[j], new_argv[0]))
1351 goto slow;
1354 if (new_argv[0] == 0)
1355 /* Line was empty. */
1356 return 0;
1357 else
1358 return new_argv;
1360 slow:;
1361 /* We must use the shell. */
1363 if (new_argv != 0)
1365 /* Free the old argument list we were working on. */
1366 free (new_argv[0]);
1367 free (new_argv);
1370 #ifdef __MSDOS__
1372 FILE *batch;
1373 dos_batch_file = 1;
1374 if (dos_bname == 0)
1376 dos_bname = tempnam (".", "mk");
1377 for (i = 0; dos_bname[i] != '\0'; ++i)
1378 if (dos_bname[i] == '/')
1379 dos_bname[i] = '\\';
1380 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1381 strcpy (dos_bename, dos_bname);
1382 strcat (dos_bname, ".bat");
1383 strcat (dos_bename, ".err");
1385 batch = fopen (dos_bename, "w"); /* Create a file. */
1386 if (batch != NULL)
1387 fclose (batch);
1388 batch = fopen (dos_bname, "w");
1389 fputs ("@echo off\n", batch);
1390 fputs (line, batch);
1391 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1392 fclose (batch);
1393 new_argv = (char **) xmalloc(2 * sizeof(char *));
1394 new_argv[0] = strdup (dos_bname);
1395 new_argv[1] = 0;
1397 #else /* Not MSDOS. */
1399 /* SHELL may be a multi-word command. Construct a command line
1400 "SHELL -c LINE", with all special chars in LINE escaped.
1401 Then recurse, expanding this command line to get the final
1402 argument list. */
1404 unsigned int shell_len = strlen (shell);
1405 static char minus_c[] = " -c ";
1406 unsigned int line_len = strlen (line);
1408 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1409 + (line_len * 2) + 1);
1411 ap = new_line;
1412 bcopy (shell, ap, shell_len);
1413 ap += shell_len;
1414 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1415 ap += sizeof (minus_c) - 1;
1416 for (p = line; *p != '\0'; ++p)
1418 if (restp != NULL && *p == '\n')
1420 *restp = p;
1421 break;
1423 else if (*p == '\\' && p[1] == '\n')
1425 /* Eat the backslash, the newline, and following whitespace,
1426 replacing it all with a single space (which is escaped
1427 from the shell). */
1428 p += 2;
1430 /* If there is a tab after a backslash-newline,
1431 remove it from the source line which will be echoed,
1432 since it was most likely used to line
1433 up the continued line with the previous one. */
1434 if (*p == '\t')
1435 strcpy (p, p + 1);
1437 p = next_token (p);
1438 --p;
1439 *ap++ = '\\';
1440 *ap++ = ' ';
1441 continue;
1444 if (*p == '\\' || *p == '\'' || *p == '"'
1445 || isspace (*p)
1446 || index (sh_chars, *p) != 0)
1447 *ap++ = '\\';
1448 *ap++ = *p;
1450 *ap = '\0';
1452 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1453 (char *) 0, (char *) 0);
1455 #endif /* MSDOS. */
1457 return new_argv;
1460 /* Figure out the argument list necessary to run LINE as a command. Try to
1461 avoid using a shell. This routine handles only ' quoting, and " quoting
1462 when no backslash, $ or ` characters are seen in the quotes. Starting
1463 quotes may be escaped with a backslash. If any of the characters in
1464 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1465 is the first word of a line, the shell is used.
1467 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1468 If *RESTP is NULL, newlines will be ignored.
1470 FILE is the target whose commands these are. It is used for
1471 variable expansion for $(SHELL) and $(IFS). */
1473 char **
1474 construct_command_argv (line, restp, file)
1475 char *line, **restp;
1476 struct file *file;
1478 char *shell, *ifs;
1479 char **argv;
1482 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1483 int save = warn_undefined_variables_flag;
1484 warn_undefined_variables_flag = 0;
1486 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1487 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1489 warn_undefined_variables_flag = save;
1492 argv = construct_command_argv_internal (line, restp, shell, ifs);
1494 free (shell);
1495 free (ifs);
1497 return argv;
1500 #ifndef HAVE_DUP2
1502 dup2 (old, new)
1503 int old, new;
1505 int fd;
1507 (void) close (new);
1508 fd = dup (old);
1509 if (fd != new)
1511 (void) close (fd);
1512 errno = EMFILE;
1513 return -1;
1516 return fd;
1518 #endif