(Commands): Add warning about "blank" line starting with a tab.
[make.git] / job.c
blob43379357b19d9279f420bcf6e6ff2420aa9caecb
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988, 89, 90, 91, 92, 93, 94 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 GNU Make is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNU Make; see the file COPYING. If not, write to
17 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
19 #include "make.h"
20 #include "commands.h"
21 #include "job.h"
22 #include "file.h"
23 #include "variable.h"
24 #include <assert.h>
26 /* Default path to search for executables. */
27 static char default_path[] = ":/bin:/usr/bin";
29 /* Default shell to use. */
30 char default_shell[] = "/bin/sh";
32 #ifdef __MSDOS__
33 #include <process.h>
34 static int dos_pid = 123;
35 static int dos_status;
36 static char *dos_bname;
37 static char *dos_bename;
38 static int dos_batch_file;
39 #endif /* MSDOS. */
42 /* If NGROUPS_MAX == 0 then try other methods for finding a real value. */
43 #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0
44 #undef NGROUPS_MAX
45 #endif /* NGROUPS_MAX == 0 */
47 #ifndef NGROUPS_MAX
48 #ifdef POSIX
49 #define GET_NGROUPS_MAX sysconf (_SC_NGROUPS_MAX)
50 #else /* Not POSIX. */
51 #define NGROUPS_MAX NGROUPS
52 #endif /* POSIX. */
53 #endif
55 #ifdef HAVE_SYS_WAIT_H
56 #include <sys/wait.h>
57 #endif
59 #ifdef HAVE_WAITPID
60 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
61 #else /* Don't have waitpid. */
62 #ifdef HAVE_WAIT3
63 #ifndef wait3
64 extern int wait3 ();
65 #endif
66 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
67 #endif /* Have wait3. */
68 #endif /* Have waitpid. */
70 #if !defined (wait) && !defined (POSIX)
71 extern int wait ();
72 #endif
74 #ifndef HAVE_UNION_WAIT
76 #define WAIT_T int
78 #ifndef WTERMSIG
79 #define WTERMSIG(x) ((x) & 0x7f)
80 #endif
81 #ifndef WCOREDUMP
82 #define WCOREDUMP(x) ((x) & 0x80)
83 #endif
84 #ifndef WEXITSTATUS
85 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
86 #endif
87 #ifndef WIFSIGNALED
88 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
89 #endif
90 #ifndef WIFEXITED
91 #define WIFEXITED(x) (WTERMSIG (x) == 0)
92 #endif
94 #else /* Have `union wait'. */
96 #define WAIT_T union wait
97 #ifndef WTERMSIG
98 #define WTERMSIG(x) ((x).w_termsig)
99 #endif
100 #ifndef WCOREDUMP
101 #define WCOREDUMP(x) ((x).w_coredump)
102 #endif
103 #ifndef WEXITSTATUS
104 #define WEXITSTATUS(x) ((x).w_retcode)
105 #endif
106 #ifndef WIFSIGNALED
107 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
108 #endif
109 #ifndef WIFEXITED
110 #define WIFEXITED(x) (WTERMSIG(x) == 0)
111 #endif
113 #endif /* Don't have `union wait'. */
116 #ifndef HAVE_UNISTD_H
117 extern int dup2 ();
118 extern int execve ();
119 extern void _exit ();
120 extern int geteuid (), getegid ();
121 extern int setgid (), getgid ();
122 #endif
124 #ifndef getdtablesize
125 #ifdef HAVE_GETDTABLESIZE
126 extern int getdtablesize ();
127 #else
128 #include <sys/param.h>
129 #define getdtablesize() NOFILE
130 #if !defined (NOFILE) && defined (NOFILES_MAX)
131 /* SCO 3.2 "devsys 4.2" defines NOFILES_{MIN,MAX} in lieu of NOFILE. */
132 #define NOFILE NOFILES_MAX
133 #endif
134 #endif
135 #endif
137 extern int getloadavg ();
138 extern int start_remote_job_p ();
139 extern int start_remote_job (), remote_status ();
141 RETSIGTYPE child_handler ();
142 static void free_child (), start_job_command ();
143 static int load_too_high (), job_next_command ();
145 /* Chain of all live (or recently deceased) children. */
147 struct child *children = 0;
149 /* Number of children currently running. */
151 unsigned int job_slots_used = 0;
153 /* Nonzero if the `good' standard input is in use. */
155 static int good_stdin_used = 0;
157 /* Chain of children waiting to run until the load average goes down. */
159 static struct child *waiting_jobs = 0;
161 /* Write an error message describing the exit status given in
162 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
163 Append "(ignored)" if IGNORED is nonzero. */
165 static void
166 child_error (target_name, exit_code, exit_sig, coredump, ignored)
167 char *target_name;
168 int exit_code, exit_sig, coredump;
169 int ignored;
171 if (exit_sig == 0)
172 error (ignored ? "[%s] Error %d (ignored)" :
173 "*** [%s] Error %d",
174 target_name, exit_code);
175 else
177 char *coredump_string = coredump ? " (core dumped)" : "";
178 if (exit_sig > 0 && exit_sig < NSIG)
179 error ("*** [%s] %s%s",
180 target_name, sys_siglist[exit_sig], coredump_string);
181 else
182 error ("*** [%s] Signal %d%s", target_name, exit_sig, coredump_string);
186 static unsigned int dead_children = 0;
188 /* Notice that a child died.
189 reap_children should be called when convenient. */
190 RETSIGTYPE
191 child_handler (sig)
192 int sig;
194 ++dead_children;
196 if (debug_flag)
197 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
200 extern int shell_function_pid, shell_function_completed;
202 /* Reap dead children, storing the returned status and the new command
203 state (`cs_finished') in the `file' member of the `struct child' for the
204 dead child, and removing the child from the chain. If BLOCK nonzero,
205 reap at least one child, waiting for it to die if necessary. If ERR is
206 nonzero, print an error message first. */
208 void
209 reap_children (block, err)
210 int block, err;
212 WAIT_T status;
214 while ((children != 0 || shell_function_pid != 0) &&
215 (block || dead_children > 0))
217 int remote = 0;
218 register int pid;
219 int exit_code, exit_sig, coredump;
220 register struct child *lastc, *c;
221 int child_failed;
222 int any_remote, any_local;
224 if (err && dead_children == 0)
226 /* We might block for a while, so let the user know why. */
227 fflush (stdout);
228 error ("*** Waiting for unfinished jobs....");
231 /* We have one less dead child to reap.
232 The test and decrement are not atomic; if it is compiled into:
233 register = dead_children - 1;
234 dead_children = register;
235 a SIGCHLD could come between the two instructions.
236 child_handler increments dead_children.
237 The second instruction here would lose that increment. But the
238 only effect of dead_children being wrong is that we might wait
239 longer than necessary to reap a child, and lose some parallelism;
240 and we might print the "Waiting for unfinished jobs" message above
241 when not necessary. */
243 if (dead_children != 0)
244 --dead_children;
246 any_remote = 0;
247 any_local = shell_function_pid != -1;
248 for (c = children; c != 0; c = c->next)
250 any_remote |= c->remote;
251 any_local |= ! c->remote;
252 if (debug_flag)
253 printf ("Live child 0x%08lx PID %d%s\n",
254 (unsigned long int) c,
255 c->pid, c->remote ? " (remote)" : "");
258 /* First, check for remote children. */
259 if (any_remote)
260 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
261 else
262 pid = 0;
263 if (pid < 0)
265 remote_status_lose:
266 #ifdef EINTR
267 if (errno == EINTR)
268 continue;
269 #endif
270 pfatal_with_name ("remote_status");
272 else if (pid == 0)
274 #ifndef __MSDOS__
275 /* No remote children. Check for local children. */
277 if (any_local)
279 #ifdef WAIT_NOHANG
280 if (!block)
281 pid = WAIT_NOHANG (&status);
282 else
283 #endif
284 pid = wait (&status);
286 else
287 pid = 0;
289 if (pid < 0)
291 #ifdef EINTR
292 if (errno == EINTR)
293 continue;
294 #endif
295 pfatal_with_name ("wait");
297 else if (pid == 0)
299 /* No local children. */
300 if (block && any_remote)
302 /* Now try a blocking wait for a remote child. */
303 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
304 if (pid < 0)
305 goto remote_status_lose;
306 else if (pid == 0)
307 /* No remote children either. Finally give up. */
308 break;
309 else
310 /* We got a remote child. */
311 remote = 1;
313 else
314 break;
316 else
318 /* Chop the status word up. */
319 exit_code = WEXITSTATUS (status);
320 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
321 coredump = WCOREDUMP (status);
323 #else /* MSDOS. */
324 /* Life is very different on MSDOS. */
325 pid = dos_pid - 1;
326 status = dos_status;
327 exit_code = dos_status;
328 exit_sig = 0;
329 coredump = 0;
330 #endif /* Not MSDOS. */
332 else
333 /* We got a remote child. */
334 remote = 1;
336 /* Check if this is the child of the `shell' function. */
337 if (!remote && pid == shell_function_pid)
339 /* It is. Leave an indicator for the `shell' function. */
340 if (exit_sig == 0 && exit_code == 127)
341 shell_function_completed = -1;
342 else
343 shell_function_completed = 1;
344 break;
347 child_failed = exit_sig != 0 || exit_code != 0;
349 /* Search for a child matching the deceased one. */
350 lastc = 0;
351 for (c = children; c != 0; lastc = c, c = c->next)
352 if (c->remote == remote && c->pid == pid)
353 break;
355 if (c == 0)
357 /* An unknown child died. */
358 char buf[100];
359 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
360 if (child_failed)
361 child_error (buf, exit_code, exit_sig, coredump,
362 ignore_errors_flag);
363 else
364 error ("%s finished.", buf);
366 else
368 if (debug_flag)
369 printf ("Reaping %s child 0x%08lx PID %d%s\n",
370 child_failed ? "losing" : "winning",
371 (unsigned long int) c,
372 c->pid, c->remote ? " (remote)" : "");
374 /* If this child had the good stdin, say it is now free. */
375 if (c->good_stdin)
376 good_stdin_used = 0;
378 if (child_failed && !c->noerror && !ignore_errors_flag)
380 /* The commands failed. Write an error message,
381 delete non-precious targets, and abort. */
382 static int delete_on_error = -1;
383 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
384 c->file->update_status = 1;
385 if (delete_on_error == -1)
387 struct file *f = lookup_file (".DELETE_ON_ERROR");
388 delete_on_error = f != 0 && f->is_target;
390 if (exit_sig != 0 || delete_on_error)
391 delete_child_targets (c);
393 else
395 if (child_failed)
397 /* The commands failed, but we don't care. */
398 child_error (c->file->name,
399 exit_code, exit_sig, coredump, 1);
400 child_failed = 0;
403 /* If there are more commands to run, try to start them. */
404 if (job_next_command (c))
406 if (handling_fatal_signal)
408 /* Never start new commands while we are dying.
409 Since there are more commands that wanted to be run,
410 the target was not completely remade. So we treat
411 this as if a command had failed. */
412 c->file->update_status = 1;
414 else
416 /* Check again whether to start remotely.
417 Whether or not we want to changes over time.
418 Also, start_remote_job may need state set up
419 by start_remote_job_p. */
420 c->remote = start_remote_job_p ();
421 start_job_command (c);
422 if (c->file->command_state == cs_running)
423 /* We successfully started the new command.
424 Loop to reap more children. */
425 continue;
428 if (c->file->update_status != 0)
429 /* We failed to start the commands. */
430 delete_child_targets (c);
432 else
433 /* There are no more commands. We got through them all
434 without an unignored error. Now the target has been
435 successfully updated. */
436 c->file->update_status = 0;
439 /* When we get here, all the commands for C->file are finished
440 (or aborted) and C->file->update_status contains 0 or 1. But
441 C->file->command_state is still cs_running if all the commands
442 ran; notice_finish_file looks for cs_running to tell it that
443 it's interesting to check the file's modtime again now. */
445 if (! handling_fatal_signal)
446 /* Notice if the target of the commands has been changed.
447 This also propagates its values for command_state and
448 update_status to its also_make files. */
449 notice_finished_file (c->file);
451 if (debug_flag)
452 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
453 (unsigned long int) c,
454 c->pid, c->remote ? " (remote)" : "");
456 /* Remove the child from the chain and free it. */
457 if (lastc == 0)
458 children = c->next;
459 else
460 lastc->next = c->next;
461 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
462 free_child (c);
464 /* There is now another slot open. */
465 --job_slots_used;
467 /* If the job failed, and the -k flag was not given, die,
468 unless we are already in the process of dying. */
469 if (!err && child_failed && !keep_going_flag)
470 die (2);
473 /* Only block for one child. */
474 block = 0;
478 /* Free the storage allocated for CHILD. */
480 static void
481 free_child (child)
482 register struct child *child;
484 if (child->command_lines != 0)
486 register unsigned int i;
487 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
488 free (child->command_lines[i]);
489 free ((char *) child->command_lines);
492 if (child->environment != 0)
494 register char **ep = child->environment;
495 while (*ep != 0)
496 free (*ep++);
497 free ((char *) child->environment);
500 free ((char *) child);
503 #ifdef POSIX
504 #ifdef __MSDOS__
505 void
506 unblock_sigs ()
508 return;
510 #else
511 extern sigset_t fatal_signal_set;
513 void
514 unblock_sigs ()
516 sigset_t empty;
517 sigemptyset (&empty);
518 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
520 #endif
521 #endif
523 /* Start a job to run the commands specified in CHILD.
524 CHILD is updated to reflect the commands and ID of the child process. */
526 static void
527 start_job_command (child)
528 register struct child *child;
530 static int bad_stdin = -1;
531 register char *p;
532 int flags = child->file->cmds->lines_flags[child->command_line - 1];
533 char **argv;
535 p = child->command_ptr;
536 child->noerror = flags & COMMANDS_NOERROR;
537 while (*p != '\0')
539 if (*p == '@')
540 flags |= COMMANDS_SILENT;
541 else if (*p == '+')
542 flags |= COMMANDS_RECURSE;
543 else if (*p == '-')
544 child->noerror = 1;
545 else if (!isblank (*p) && *p != '+')
546 break;
547 ++p;
550 /* If -q was given, just say that updating `failed'. The exit status of
551 1 tells the user that -q is saying `something to do'; the exit status
552 for a random error is 2. */
553 if (question_flag && !(flags & COMMANDS_RECURSE))
555 child->file->update_status = 1;
556 notice_finished_file (child->file);
557 return;
560 /* There may be some preceding whitespace left if there
561 was nothing but a backslash on the first line. */
562 p = next_token (p);
564 /* Figure out an argument list from this command line. */
567 char *end;
568 argv = construct_command_argv (p, &end, child->file);
569 if (end == NULL)
570 child->command_ptr = NULL;
571 else
573 *end++ = '\0';
574 child->command_ptr = end;
578 if (touch_flag && !(flags & COMMANDS_RECURSE))
580 /* Go on to the next command. It might be the recursive one.
581 We construct ARGV only to find the end of the command line. */
582 free (argv[0]);
583 free ((char *) argv);
584 argv = 0;
587 if (argv == 0)
589 /* This line has no commands. Go to the next. */
590 if (job_next_command (child))
591 start_job_command (child);
592 child->file->update_status = 0;
593 return;
596 /* Print out the command. */
598 if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
599 puts (p);
601 /* Tell update_goal_chain that a command has been started on behalf of
602 this target. It is important that this happens here and not in
603 reap_children (where we used to do it), because reap_children might be
604 reaping children from a different target. We want this increment to
605 guaranteedly indicate that a command was started for the dependency
606 chain (i.e., update_file recursion chain) we are processing. */
608 ++commands_started;
610 /* If -n was given, recurse to get the next line in the sequence. */
612 if (just_print_flag && !(flags & COMMANDS_RECURSE))
614 free (argv[0]);
615 free ((char *) argv);
616 if (job_next_command (child))
617 start_job_command (child);
618 child->file->update_status = 0;
619 return;
622 /* Flush the output streams so they won't have things written twice. */
624 fflush (stdout);
625 fflush (stderr);
627 /* Set up a bad standard input that reads from a broken pipe. */
629 if (bad_stdin == -1)
631 /* Make a file descriptor that is the read end of a broken pipe.
632 This will be used for some children's standard inputs. */
633 int pd[2];
634 if (pipe (pd) == 0)
636 /* Close the write side. */
637 (void) close (pd[1]);
638 /* Save the read side. */
639 bad_stdin = pd[0];
643 /* Decide whether to give this child the `good' standard input
644 (one that points to the terminal or whatever), or the `bad' one
645 that points to the read side of a broken pipe. */
647 child->good_stdin = !good_stdin_used;
648 if (child->good_stdin)
649 good_stdin_used = 1;
651 child->deleted = 0;
653 /* Set up the environment for the child. */
654 if (child->environment == 0)
655 child->environment = target_environment (child->file);
657 #ifndef __MSDOS__
659 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
660 if (child->remote)
662 int is_remote, id, used_stdin;
663 if (start_remote_job (argv, child->environment,
664 child->good_stdin ? 0 : bad_stdin,
665 &is_remote, &id, &used_stdin))
666 goto error;
667 else
669 if (child->good_stdin && !used_stdin)
671 child->good_stdin = 0;
672 good_stdin_used = 0;
674 child->remote = is_remote;
675 child->pid = id;
678 else
680 /* Fork the child process. */
682 #ifdef POSIX
683 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
684 #else
685 #ifdef HAVE_SIGSETMASK
686 (void) sigblock (fatal_signal_mask);
687 #endif
688 #endif
690 child->remote = 0;
691 child->pid = vfork ();
692 if (child->pid == 0)
694 /* We are the child side. */
695 unblock_sigs ();
696 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
697 argv, child->environment);
699 else if (child->pid < 0)
701 /* Fork failed! */
702 unblock_sigs ();
703 perror_with_name ("vfork", "");
704 goto error;
708 #else /* MSDOS. */
709 dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
710 ++dead_children;
711 child->pid = dos_pid++;
712 if (dos_batch_file)
714 dos_batch_file = 0;
715 remove (dos_bname); /* Ignore errors. */
716 if (access (dos_bename, 0))
717 dos_status = 1;
718 else
719 dos_status = 0;
720 remove (dos_bename);
722 #endif /* Not MSDOS. */
724 /* We are the parent side. Set the state to
725 say the commands are running and return. */
727 set_command_state (child->file, cs_running);
729 /* Free the storage used by the child's argument list. */
731 free (argv[0]);
732 free ((char *) argv);
734 return;
736 error:
737 child->file->update_status = 2;
738 notice_finished_file (child->file);
741 /* Try to start a child running.
742 Returns nonzero if the child was started (and maybe finished), or zero if
743 the load was too high and the child was put on the `waiting_jobs' chain. */
745 static int
746 start_waiting_job (c)
747 struct child *c;
749 /* If we can start a job remotely, we always want to, and don't care about
750 the local load average. We record that the job should be started
751 remotely in C->remote for start_job_command to test. */
753 c->remote = start_remote_job_p ();
755 /* If this job is to be started locally, and we are already running
756 some jobs, make this one wait if the load average is too high. */
757 if (!c->remote && job_slots_used > 0 && load_too_high ())
759 /* Put this child on the chain of children waiting
760 for the load average to go down. */
761 c->file->command_state = cs_running;
762 c->next = waiting_jobs;
763 waiting_jobs = c;
764 return 0;
767 /* Start the first command; reap_children will run later command lines. */
768 start_job_command (c);
770 switch (c->file->command_state)
772 case cs_running:
773 c->next = children;
774 if (debug_flag)
775 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
776 (unsigned long int) c,
777 c->pid, c->remote ? " (remote)" : "");
778 children = c;
779 /* One more job slot is in use. */
780 ++job_slots_used;
781 unblock_sigs ();
782 break;
784 case cs_not_started:
785 /* All the command lines turned out to be empty. */
786 c->file->update_status = 0;
787 /* FALLTHROUGH */
789 case cs_finished:
790 notice_finished_file (c->file);
791 free_child (c);
792 break;
794 default:
795 assert (c->file->command_state == cs_finished);
796 break;
799 return 1;
802 /* Create a `struct child' for FILE and start its commands running. */
804 void
805 new_job (file)
806 register struct file *file;
808 register struct commands *cmds = file->cmds;
809 register struct child *c;
810 char **lines;
811 register unsigned int i;
813 /* Let any previously decided-upon jobs that are waiting
814 for the load to go down start before this new one. */
815 start_waiting_jobs ();
817 /* Reap any children that might have finished recently. */
818 reap_children (0, 0);
820 /* Chop the commands up into lines if they aren't already. */
821 chop_commands (cmds);
823 if (job_slots != 0)
824 /* Wait for a job slot to be freed up. */
825 while (job_slots_used == job_slots)
826 reap_children (1, 0);
828 /* Expand the command lines and store the results in LINES. */
829 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
830 for (i = 0; i < cmds->ncommand_lines; ++i)
832 /* Collapse backslash-newline combinations that are inside variable
833 or function references. These are left alone by the parser so
834 that they will appear in the echoing of commands (where they look
835 nice); and collapsed by construct_command_argv when it tokenizes.
836 But letting them survive inside function invocations loses because
837 we don't want the functions to see them as part of the text. */
839 char *in, *out, *ref;
841 /* IN points to where in the line we are scanning.
842 OUT points to where in the line we are writing.
843 When we collapse a backslash-newline combination,
844 IN gets ahead out OUT. */
846 in = out = cmds->command_lines[i];
847 while ((ref = index (in, '$')) != 0)
849 ++ref; /* Move past the $. */
851 if (out != in)
852 /* Copy the text between the end of the last chunk
853 we processed (where IN points) and the new chunk
854 we are about to process (where REF points). */
855 bcopy (in, out, ref - in);
857 /* Move both pointers past the boring stuff. */
858 out += ref - in;
859 in = ref;
861 if (*ref == '(' || *ref == '{')
863 char openparen = *ref;
864 char closeparen = openparen == '(' ? ')' : '}';
865 int count;
866 char *p;
868 *out++ = *in++; /* Copy OPENPAREN. */
869 /* IN now points past the opening paren or brace.
870 Count parens or braces until it is matched. */
871 count = 0;
872 while (*in != '\0')
874 if (*in == closeparen && --count < 0)
875 break;
876 else if (*in == '\\' && in[1] == '\n')
878 /* We have found a backslash-newline inside a
879 variable or function reference. Eat it and
880 any following whitespace. */
882 int quoted = 0;
883 for (p = in - 1; p > ref && *p == '\\'; --p)
884 quoted = !quoted;
886 if (quoted)
887 /* There were two or more backslashes, so this is
888 not really a continuation line. We don't collapse
889 the quoting backslashes here as is done in
890 collapse_continuations, because the line will
891 be collapsed again after expansion. */
892 *out++ = *in++;
893 else
895 /* Skip the backslash, newline and
896 any following whitespace. */
897 in = next_token (in + 2);
899 /* Discard any preceding whitespace that has
900 already been written to the output. */
901 while (out > ref && isblank (out[-1]))
902 --out;
904 /* Replace it all with a single space. */
905 *out++ = ' ';
908 else
910 if (*in == openparen)
911 ++count;
913 *out++ = *in++;
919 /* There are no more references in this line to worry about.
920 Copy the remaining uninteresting text to the output. */
921 if (out != in)
922 strcpy (out, in);
924 /* Finally, expand the line. */
925 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
926 file);
929 /* Start the command sequence, record it in a new
930 `struct child', and add that to the chain. */
932 c = (struct child *) xmalloc (sizeof (struct child));
933 c->file = file;
934 c->command_lines = lines;
935 c->command_line = 0;
936 c->command_ptr = 0;
937 c->environment = 0;
939 /* Fetch the first command line to be run. */
940 if (! job_next_command (c))
942 /* There were no commands! */
943 free_child (c);
944 c->file->update_status = 0;
946 else
948 /* The job is now primed. Start it running. */
949 start_waiting_job (c);
951 if (job_slots == 1)
952 /* Since there is only one job slot, make things run linearly.
953 Wait for the child to die, setting the state to `cs_finished'. */
954 while (file->command_state == cs_running)
955 reap_children (1, 0);
959 /* Move CHILD's pointers to the next command for it to execute.
960 Returns nonzero if there is another command. */
962 static int
963 job_next_command (child)
964 struct child *child;
966 if (child->command_ptr == 0 || *child->command_ptr == '\0')
968 /* There are no more lines in the expansion of this line. */
969 if (child->command_line == child->file->cmds->ncommand_lines)
971 /* There are no more lines to be expanded. */
972 child->command_ptr = 0;
973 return 0;
975 else
976 /* Get the next line to run. */
977 child->command_ptr = child->command_lines[child->command_line++];
979 return 1;
982 static int
983 load_too_high ()
985 #ifdef __MSDOS__
986 return 1;
987 #else
988 extern int getloadavg ();
989 double load;
991 if (max_load_average < 0)
992 return 0;
994 make_access ();
995 if (getloadavg (&load, 1) != 1)
997 static int lossage = -1;
998 /* Complain only once for the same error. */
999 if (lossage == -1 || errno != lossage)
1001 if (errno == 0)
1002 /* An errno value of zero means getloadavg is just unsupported. */
1003 error ("cannot enforce load limits on this operating system");
1004 else
1005 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1007 lossage = errno;
1008 load = 0;
1010 user_access ();
1012 return load >= max_load_average;
1013 #endif
1016 /* Start jobs that are waiting for the load to be lower. */
1018 void
1019 start_waiting_jobs ()
1021 struct child *job;
1023 if (waiting_jobs == 0)
1024 return;
1028 /* Check for recently deceased descendants. */
1029 reap_children (0, 0);
1031 /* Take a job off the waiting list. */
1032 job = waiting_jobs;
1033 waiting_jobs = job->next;
1035 /* Try to start that job. We break out of the loop as soon
1036 as start_waiting_job puts one back on the waiting list. */
1037 } while (start_waiting_job (job) && waiting_jobs != 0);
1040 /* Replace the current process with one executing the command in ARGV.
1041 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1042 the environment of the new program. This function does not return. */
1044 void
1045 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1046 int stdin_fd, stdout_fd;
1047 char **argv, **envp;
1049 if (stdin_fd != 0)
1050 (void) dup2 (stdin_fd, 0);
1051 if (stdout_fd != 1)
1052 (void) dup2 (stdout_fd, 1);
1054 /* Free up file descriptors. */
1056 register int d;
1057 int max = getdtablesize ();
1058 for (d = 3; d < max; ++d)
1059 (void) close (d);
1062 /* Run the command. */
1063 exec_command (argv, envp);
1066 /* Search PATH for FILE.
1067 If successful, store the full pathname in PROGRAM and return 1.
1068 If not sucessful, return zero. */
1070 static int
1071 search_path (file, path, program)
1072 char *file, *path, *program;
1074 if (path == 0 || path[0] == '\0')
1075 path = default_path;
1077 if (
1078 #ifdef __MSDOS__
1079 strpbrk (file, "/\\:")
1080 #else
1081 index (file, '/')
1082 #endif
1083 != 0)
1085 strcpy (program, file);
1086 return 1;
1088 else
1090 unsigned int len;
1092 #ifdef HAVE_GETGROUPS
1093 #ifndef HAVE_UNISTD_H
1094 extern int getgroups ();
1095 #endif
1096 static int ngroups = -1;
1097 #ifdef NGROUPS_MAX
1098 static GETGROUPS_T groups[NGROUPS_MAX];
1099 #define ngroups_max NGROUPS_MAX
1100 #else
1101 static GETGROUPS_T *groups = 0;
1102 static int ngroups_max;
1103 if (groups == 0)
1105 ngroups_max = GET_NGROUPS_MAX;
1106 groups = (GETGROUPS_T *) malloc (ngroups_max * sizeof (GETGROUPS_T));
1108 #endif
1109 if (groups != 0 && ngroups == -1)
1110 ngroups = getgroups (ngroups_max, groups);
1111 #endif /* Have getgroups. */
1113 len = strlen (file) + 1;
1116 struct stat st;
1117 int perm;
1118 char *p;
1120 p = index (path, PATH_SEPARATOR_CHAR);
1121 if (p == 0)
1122 p = path + strlen (path);
1124 if (p == path)
1125 bcopy (file, program, len);
1126 else
1128 bcopy (path, program, p - path);
1129 program[p - path] = '/';
1130 bcopy (file, program + (p - path) + 1, len);
1133 if (safe_stat (program, &st) == 0
1134 && S_ISREG (st.st_mode))
1136 if (st.st_uid == geteuid ())
1137 perm = (st.st_mode & 0100);
1138 else if (st.st_gid == getegid ())
1139 perm = (st.st_mode & 0010);
1140 else
1142 #ifdef HAVE_GETGROUPS
1143 register int i;
1144 for (i = 0; i < ngroups; ++i)
1145 if (groups[i] == st.st_gid)
1146 break;
1147 if (i < ngroups)
1148 perm = (st.st_mode & 0010);
1149 else
1150 #endif /* Have getgroups. */
1151 perm = (st.st_mode & 0001);
1154 if (perm != 0)
1155 return 1;
1158 path = p + 1;
1159 } while (*path != '\0');
1162 return 0;
1165 /* Replace the current process with one running the command in ARGV,
1166 with environment ENVP. This function does not return. */
1168 void
1169 exec_command (argv, envp)
1170 char **argv, **envp;
1172 char *shell, *path;
1173 PATH_VAR (program);
1174 register char **ep;
1176 shell = path = 0;
1177 for (ep = envp; *ep != 0; ++ep)
1179 if (shell == 0 && !strncmp(*ep, "SHELL=", 6))
1180 shell = &(*ep)[6];
1181 else if (path == 0 && !strncmp(*ep, "PATH=", 5))
1182 path = &(*ep)[5];
1183 else if (path != 0 && shell != 0)
1184 break;
1187 /* Be the user, permanently. */
1188 child_access ();
1190 if (!search_path (argv[0], path, program))
1191 error ("%s: Command not found", argv[0]);
1192 else
1194 /* Run the program. */
1195 execve (program, argv, envp);
1197 if (errno == ENOEXEC)
1199 PATH_VAR (shell_program);
1200 char *shell_path;
1201 if (shell == 0)
1202 shell_path = default_shell;
1203 else
1205 if (search_path (shell, path, shell_program))
1206 shell_path = shell_program;
1207 else
1209 shell_path = 0;
1210 error ("%s: Shell program not found", shell);
1214 if (shell_path != 0)
1216 char **new_argv;
1217 int argc;
1219 argc = 1;
1220 while (argv[argc] != 0)
1221 ++argc;
1223 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1224 new_argv[0] = shell_path;
1225 new_argv[1] = program;
1226 while (argc > 0)
1228 new_argv[1 + argc] = argv[argc];
1229 --argc;
1232 execve (shell_path, new_argv, envp);
1233 perror_with_name ("execve: ", shell_path);
1236 else
1237 perror_with_name ("execve: ", program);
1240 _exit (127);
1243 /* Figure out the argument list necessary to run LINE as a command.
1244 Try to avoid using a shell. This routine handles only ' quoting.
1245 Starting quotes may be escaped with a backslash. If any of the
1246 characters in sh_chars[] is seen, or any of the builtin commands
1247 listed in sh_cmds[] is the first word of a line, the shell is used.
1249 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1250 If *RESTP is NULL, newlines will be ignored.
1252 SHELL is the shell to use, or nil to use the default shell.
1253 IFS is the value of $IFS, or nil (meaning the default). */
1255 static char **
1256 construct_command_argv_internal (line, restp, shell, ifs)
1257 char *line, **restp;
1258 char *shell, *ifs;
1260 #ifdef __MSDOS__
1261 static char sh_chars[] = "\"|<>";
1262 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1263 "copy", "ctty", "date", "del", "dir", "echo",
1264 "erase", "exit", "for", "goto", "if", "if", "md",
1265 "mkdir", "path", "pause", "prompt", "rem", "ren",
1266 "rename", "set", "shift", "time", "type",
1267 "ver", "verify", "vol", ":", 0 };
1268 #else
1269 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1270 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1271 "logout", "set", "umask", "wait", "while", "for",
1272 "case", "if", ":", ".", "break", "continue",
1273 "export", "read", "readonly", "shift", "times",
1274 "trap", "switch", 0 };
1275 #endif
1276 register int i;
1277 register char *p;
1278 register char *ap;
1279 char *end;
1280 int instring, word_has_equals, seen_nonequals;
1281 char **new_argv = 0;
1283 if (restp != NULL)
1284 *restp = NULL;
1286 /* Make sure not to bother processing an empty line. */
1287 while (isblank (*line))
1288 ++line;
1289 if (*line == '\0')
1290 return 0;
1292 /* See if it is safe to parse commands internally. */
1293 if (shell == 0)
1294 shell = default_shell;
1295 else if (strcmp (shell, default_shell))
1296 goto slow;
1298 if (ifs != 0)
1299 for (ap = ifs; *ap != '\0'; ++ap)
1300 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1301 goto slow;
1303 i = strlen (line) + 1;
1305 /* More than 1 arg per character is impossible. */
1306 new_argv = (char **) xmalloc (i * sizeof (char *));
1308 /* All the args can fit in a buffer as big as LINE is. */
1309 ap = new_argv[0] = (char *) xmalloc (i);
1310 end = ap + i;
1312 /* I is how many complete arguments have been found. */
1313 i = 0;
1314 instring = word_has_equals = seen_nonequals = 0;
1315 for (p = line; *p != '\0'; ++p)
1317 if (ap > end)
1318 abort ();
1320 if (instring)
1322 string_char:
1323 /* Inside a string, just copy any char except a closing quote
1324 or a backslash-newline combination. */
1325 if (*p == '\'')
1326 instring = 0;
1327 else if (*p == '\\' && p[1] == '\n')
1328 goto swallow_escaped_newline;
1329 else if (*p == '\n' && restp != NULL)
1331 /* End of the command line. */
1332 *restp = p;
1333 goto end_of_line;
1335 else
1336 *ap++ = *p;
1338 else if (index (sh_chars, *p) != 0)
1339 /* Not inside a string, but it's a special char. */
1340 goto slow;
1341 else
1342 /* Not a special char. */
1343 switch (*p)
1345 case '=':
1346 /* Equals is a special character in leading words before the
1347 first word with no equals sign in it. This is not the case
1348 with sh -k, but we never get here when using nonstandard
1349 shell flags. */
1350 if (! seen_nonequals)
1351 goto slow;
1352 word_has_equals = 1;
1353 *ap++ = '=';
1354 break;
1356 case '\\':
1357 /* Backslash-newline combinations are eaten. */
1358 if (p[1] == '\n')
1360 swallow_escaped_newline:
1362 /* Eat the backslash, the newline, and following whitespace,
1363 replacing it all with a single space. */
1364 p += 2;
1366 /* If there is a tab after a backslash-newline,
1367 remove it from the source line which will be echoed,
1368 since it was most likely used to line
1369 up the continued line with the previous one. */
1370 if (*p == '\t')
1371 strcpy (p, p + 1);
1373 if (instring)
1374 goto string_char;
1375 else
1377 if (ap != new_argv[i])
1378 /* Treat this as a space, ending the arg.
1379 But if it's at the beginning of the arg, it should
1380 just get eaten, rather than becoming an empty arg. */
1381 goto end_of_arg;
1382 else
1383 p = next_token (p) - 1;
1386 else if (p[1] != '\0')
1387 /* Copy and skip the following char. */
1388 *ap++ = *++p;
1389 break;
1391 case '\'':
1392 instring = 1;
1393 break;
1395 case '\n':
1396 if (restp != NULL)
1398 /* End of the command line. */
1399 *restp = p;
1400 goto end_of_line;
1402 else
1403 /* Newlines are not special. */
1404 *ap++ = '\n';
1405 break;
1407 case ' ':
1408 case '\t':
1409 end_of_arg:
1410 /* We have the end of an argument.
1411 Terminate the text of the argument. */
1412 *ap++ = '\0';
1413 new_argv[++i] = ap;
1415 /* Update SEEN_NONEQUALS, which tells us if every word
1416 heretofore has contained an `='. */
1417 seen_nonequals |= ! word_has_equals;
1418 if (word_has_equals && ! seen_nonequals)
1419 /* An `=' in a word before the first
1420 word without one is magical. */
1421 goto slow;
1422 word_has_equals = 0; /* Prepare for the next word. */
1424 /* If this argument is the command name,
1425 see if it is a built-in shell command.
1426 If so, have the shell handle it. */
1427 if (i == 1)
1429 register int j;
1430 for (j = 0; sh_cmds[j] != 0; ++j)
1431 if (streq (sh_cmds[j], new_argv[0]))
1432 goto slow;
1435 /* Ignore multiple whitespace chars. */
1436 p = next_token (p);
1437 /* Next iteration should examine the first nonwhite char. */
1438 --p;
1439 break;
1441 default:
1442 *ap++ = *p;
1443 break;
1446 end_of_line:
1448 if (instring)
1449 /* Let the shell deal with an unterminated quote. */
1450 goto slow;
1452 /* Terminate the last argument and the argument list. */
1454 *ap = '\0';
1455 if (new_argv[i][0] != '\0')
1456 ++i;
1457 new_argv[i] = 0;
1459 if (i == 1)
1461 register int j;
1462 for (j = 0; sh_cmds[j] != 0; ++j)
1463 if (streq (sh_cmds[j], new_argv[0]))
1464 goto slow;
1467 if (new_argv[0] == 0)
1468 /* Line was empty. */
1469 return 0;
1470 else
1471 return new_argv;
1473 slow:;
1474 /* We must use the shell. */
1476 if (new_argv != 0)
1478 /* Free the old argument list we were working on. */
1479 free (new_argv[0]);
1480 free (new_argv);
1483 #ifdef __MSDOS__
1485 FILE *batch;
1486 dos_batch_file = 1;
1487 if (dos_bname == 0)
1489 dos_bname = tempnam (".", "mk");
1490 for (i = 0; dos_bname[i] != '\0'; ++i)
1491 if (dos_bname[i] == '/')
1492 dos_bname[i] = '\\';
1493 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1494 strcpy (dos_bename, dos_bname);
1495 strcat (dos_bname, ".bat");
1496 strcat (dos_bename, ".err");
1498 batch = fopen(bename, "w"); /* Create a file. */
1499 if (batch != NULL)
1500 fclose (batch);
1501 batch = fopen (dos_bname, "w");
1502 fputs ("@echo off\n", batch);
1503 fputs (line, batch);
1504 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1505 fclose (batch);
1506 new_argv = (char **) xmalloc(2 * sizeof(char *));
1507 new_argv[0] = strdup (bname);
1508 new_argv[1] = 0;
1510 #else /* Not MSDOS. */
1512 /* SHELL may be a multi-word command. Construct a command line
1513 "SHELL -c LINE", with all special chars in LINE escaped.
1514 Then recurse, expanding this command line to get the final
1515 argument list. */
1517 unsigned int shell_len = strlen (shell);
1518 static char minus_c[] = " -c ";
1519 unsigned int line_len = strlen (line);
1521 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1522 + (line_len * 2) + 1);
1524 ap = new_line;
1525 bcopy (shell, ap, shell_len);
1526 ap += shell_len;
1527 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1528 ap += sizeof (minus_c) - 1;
1529 for (p = line; *p != '\0'; ++p)
1531 if (restp != NULL && *p == '\n')
1533 *restp = p;
1534 break;
1536 else if (*p == '\\' && p[1] == '\n')
1538 /* Eat the backslash, the newline, and following whitespace,
1539 replacing it all with a single space (which is escaped
1540 from the shell). */
1541 p += 2;
1543 /* If there is a tab after a backslash-newline,
1544 remove it from the source line which will be echoed,
1545 since it was most likely used to line
1546 up the continued line with the previous one. */
1547 if (*p == '\t')
1548 strcpy (p, p + 1);
1550 p = next_token (p);
1551 --p;
1552 *ap++ = '\\';
1553 *ap++ = ' ';
1554 continue;
1557 if (*p == '\\' || *p == '\''
1558 || isspace (*p)
1559 || index (sh_chars, *p) != 0)
1560 *ap++ = '\\';
1561 *ap++ = *p;
1563 *ap = '\0';
1565 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1566 (char *) 0, (char *) 0);
1568 #endif /* MSDOS. */
1570 return new_argv;
1573 /* Figure out the argument list necessary to run LINE as a command.
1574 Try to avoid using a shell. This routine handles only ' quoting.
1575 Starting quotes may be escaped with a backslash. If any of the
1576 characters in sh_chars[] is seen, or any of the builtin commands
1577 listed in sh_cmds[] is the first word of a line, the shell is used.
1579 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1580 If *RESTP is NULL, newlines will be ignored.
1582 FILE is the target whose commands these are. It is used for
1583 variable expansion for $(SHELL) and $(IFS). */
1585 char **
1586 construct_command_argv (line, restp, file)
1587 char *line, **restp;
1588 struct file *file;
1590 char *shell, *ifs;
1591 char **argv;
1594 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1595 int save = warn_undefined_variables_flag;
1596 warn_undefined_variables_flag = 0;
1598 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1599 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1601 warn_undefined_variables_flag = save;
1604 argv = construct_command_argv_internal (line, restp, shell, ifs);
1606 free (shell);
1607 free (ifs);
1609 return argv;
1612 #ifndef HAVE_DUP2
1614 dup2 (old, new)
1615 int old, new;
1617 int fd;
1619 (void) close (new);
1620 fd = dup (old);
1621 if (fd != new)
1623 (void) close (fd);
1624 errno = EMFILE;
1625 return -1;
1628 return fd;
1630 #endif