[alliant && i860] (LOAD_AVE_TYPE, FSCALE, NLIST_STRUCT): Define.
[make.git] / job.c
blobc9d289646cde44a2847baff734162b0cf9f48b7e
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 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
383 c->file->update_status = 1;
384 if (exit_sig != 0)
385 delete_child_targets (c);
387 else
389 if (child_failed)
391 /* The commands failed, but we don't care. */
392 child_error (c->file->name,
393 exit_code, exit_sig, coredump, 1);
394 child_failed = 0;
397 /* If there are more commands to run, try to start them. */
398 if (job_next_command (c))
400 if (handling_fatal_signal)
402 /* Never start new commands while we are dying.
403 Since there are more commands that wanted to be run,
404 the target was not completely remade. So we treat
405 this as if a command had failed. */
406 c->file->update_status = 1;
408 else
410 /* Check again whether to start remotely.
411 Whether or not we want to changes over time.
412 Also, start_remote_job may need state set up
413 by start_remote_job_p. */
414 c->remote = start_remote_job_p ();
415 start_job_command (c);
416 if (c->file->command_state == cs_running)
417 /* We successfully started the new command.
418 Loop to reap more children. */
419 continue;
422 if (c->file->update_status != 0)
423 /* We failed to start the commands. */
424 delete_child_targets (c);
426 else
427 /* There are no more commands. We got through them all
428 without an unignored error. Now the target has been
429 successfully updated. */
430 c->file->update_status = 0;
433 /* When we get here, all the commands for C->file are finished
434 (or aborted) and C->file->update_status contains 0 or 1. But
435 C->file->command_state is still cs_running if all the commands
436 ran; notice_finish_file looks for cs_running to tell it that
437 it's interesting to check the file's modtime again now. */
439 if (! handling_fatal_signal)
440 /* Notice if the target of the commands has been changed.
441 This also propagates its values for command_state and
442 update_status to its also_make files. */
443 notice_finished_file (c->file);
445 if (debug_flag)
446 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
447 (unsigned long int) c,
448 c->pid, c->remote ? " (remote)" : "");
450 /* Remove the child from the chain and free it. */
451 if (lastc == 0)
452 children = c->next;
453 else
454 lastc->next = c->next;
455 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
456 free_child (c);
458 /* There is now another slot open. */
459 --job_slots_used;
461 /* If the job failed, and the -k flag was not given, die,
462 unless we are already in the process of dying. */
463 if (!err && child_failed && !keep_going_flag)
464 die (2);
467 /* Only block for one child. */
468 block = 0;
472 /* Free the storage allocated for CHILD. */
474 static void
475 free_child (child)
476 register struct child *child;
478 if (child->command_lines != 0)
480 register unsigned int i;
481 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
482 free (child->command_lines[i]);
483 free ((char *) child->command_lines);
486 if (child->environment != 0)
488 register char **ep = child->environment;
489 while (*ep != 0)
490 free (*ep++);
491 free ((char *) child->environment);
494 free ((char *) child);
497 #ifdef POSIX
498 #ifdef __MSDOS__
499 void
500 unblock_sigs ()
502 return;
504 #else
505 extern sigset_t fatal_signal_set;
507 void
508 unblock_sigs ()
510 sigset_t empty;
511 sigemptyset (&empty);
512 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
514 #endif
515 #endif
517 /* Start a job to run the commands specified in CHILD.
518 CHILD is updated to reflect the commands and ID of the child process. */
520 static void
521 start_job_command (child)
522 register struct child *child;
524 static int bad_stdin = -1;
525 register char *p;
526 int flags = child->file->cmds->lines_flags[child->command_line - 1];
527 char **argv;
529 p = child->command_ptr;
530 child->noerror = flags & COMMANDS_NOERROR;
531 while (*p != '\0')
533 if (*p == '@')
534 flags |= COMMANDS_SILENT;
535 else if (*p == '+')
536 flags |= COMMANDS_RECURSE;
537 else if (*p == '-')
538 child->noerror = 1;
539 else if (!isblank (*p) && *p != '+')
540 break;
541 ++p;
544 /* If -q was given, just say that updating `failed'. The exit status of
545 1 tells the user that -q is saying `something to do'; the exit status
546 for a random error is 2. */
547 if (question_flag && !(flags & COMMANDS_RECURSE))
549 child->file->update_status = 1;
550 notice_finished_file (child->file);
551 return;
554 /* There may be some preceding whitespace left if there
555 was nothing but a backslash on the first line. */
556 p = next_token (p);
558 /* Figure out an argument list from this command line. */
561 char *end;
562 argv = construct_command_argv (p, &end, child->file);
563 if (end == NULL)
564 child->command_ptr = NULL;
565 else
567 *end++ = '\0';
568 child->command_ptr = end;
572 if (touch_flag && !(flags & COMMANDS_RECURSE))
574 /* Go on to the next command. It might be the recursive one.
575 We construct ARGV only to find the end of the command line. */
576 free (argv[0]);
577 free ((char *) argv);
578 argv = 0;
581 if (argv == 0)
583 /* This line has no commands. Go to the next. */
584 if (job_next_command (child))
585 start_job_command (child);
586 child->file->update_status = 0;
587 return;
590 /* Print out the command. */
592 if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
593 puts (p);
595 /* Tell update_goal_chain that a command has been started on behalf of
596 this target. It is important that this happens here and not in
597 reap_children (where we used to do it), because reap_children might be
598 reaping children from a different target. We want this increment to
599 guaranteedly indicate that a command was started for the dependency
600 chain (i.e., update_file recursion chain) we are processing. */
602 ++commands_started;
604 /* If -n was given, recurse to get the next line in the sequence. */
606 if (just_print_flag && !(flags & COMMANDS_RECURSE))
608 free (argv[0]);
609 free ((char *) argv);
610 if (job_next_command (child))
611 start_job_command (child);
612 child->file->update_status = 0;
613 return;
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];
637 /* Decide whether to give this child the `good' standard input
638 (one that points to the terminal or whatever), or the `bad' one
639 that points to the read side of a broken pipe. */
641 child->good_stdin = !good_stdin_used;
642 if (child->good_stdin)
643 good_stdin_used = 1;
645 child->deleted = 0;
647 /* Set up the environment for the child. */
648 if (child->environment == 0)
649 child->environment = target_environment (child->file);
651 #ifndef __MSDOS__
653 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
654 if (child->remote)
656 int is_remote, id, used_stdin;
657 if (start_remote_job (argv, child->environment,
658 child->good_stdin ? 0 : bad_stdin,
659 &is_remote, &id, &used_stdin))
660 goto error;
661 else
663 if (child->good_stdin && !used_stdin)
665 child->good_stdin = 0;
666 good_stdin_used = 0;
668 child->remote = is_remote;
669 child->pid = id;
672 else
674 /* Fork the child process. */
676 #ifdef POSIX
677 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
678 #else
679 #ifdef HAVE_SIGSETMASK
680 (void) sigblock (fatal_signal_mask);
681 #endif
682 #endif
684 child->remote = 0;
685 child->pid = vfork ();
686 if (child->pid == 0)
688 /* We are the child side. */
689 unblock_sigs ();
690 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
691 argv, child->environment);
693 else if (child->pid < 0)
695 /* Fork failed! */
696 unblock_sigs ();
697 perror_with_name ("vfork", "");
698 goto error;
702 #else /* MSDOS. */
703 dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
704 ++dead_children;
705 child->pid = dos_pid++;
706 if (dos_batch_file)
708 dos_batch_file = 0;
709 remove (dos_bname); /* Ignore errors. */
710 if (access (dos_bename, 0))
711 dos_status = 1;
712 else
713 dos_status = 0;
714 remove (dos_bename);
716 #endif /* Not MSDOS. */
718 /* We are the parent side. Set the state to
719 say the commands are running and return. */
721 set_command_state (child->file, cs_running);
723 /* Free the storage used by the child's argument list. */
725 free (argv[0]);
726 free ((char *) argv);
728 return;
730 error:
731 child->file->update_status = 2;
732 notice_finished_file (child->file);
735 /* Try to start a child running.
736 Returns nonzero if the child was started (and maybe finished), or zero if
737 the load was too high and the child was put on the `waiting_jobs' chain. */
739 static int
740 start_waiting_job (c)
741 struct child *c;
743 /* If we can start a job remotely, we always want to, and don't care about
744 the local load average. We record that the job should be started
745 remotely in C->remote for start_job_command to test. */
747 c->remote = start_remote_job_p ();
749 /* If this job is to be started locally, and we are already running
750 some jobs, make this one wait if the load average is too high. */
751 if (!c->remote && job_slots_used > 0 && load_too_high ())
753 /* Put this child on the chain of children waiting
754 for the load average to go down. */
755 c->file->command_state = cs_running;
756 c->next = waiting_jobs;
757 waiting_jobs = c;
758 return 0;
761 /* Start the first command; reap_children will run later command lines. */
762 start_job_command (c);
764 switch (c->file->command_state)
766 case cs_running:
767 c->next = children;
768 if (debug_flag)
769 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
770 (unsigned long int) c,
771 c->pid, c->remote ? " (remote)" : "");
772 children = c;
773 /* One more job slot is in use. */
774 ++job_slots_used;
775 unblock_sigs ();
776 break;
778 case cs_not_started:
779 /* All the command lines turned out to be empty. */
780 c->file->update_status = 0;
781 /* FALLTHROUGH */
783 case cs_finished:
784 notice_finished_file (c->file);
785 free_child (c);
786 break;
788 default:
789 assert (c->file->command_state == cs_finished);
790 break;
793 return 1;
796 /* Create a `struct child' for FILE and start its commands running. */
798 void
799 new_job (file)
800 register struct file *file;
802 register struct commands *cmds = file->cmds;
803 register struct child *c;
804 char **lines;
805 register unsigned int i;
807 /* Let any previously decided-upon jobs that are waiting
808 for the load to go down start before this new one. */
809 start_waiting_jobs ();
811 /* Reap any children that might have finished recently. */
812 reap_children (0, 0);
814 /* Chop the commands up into lines if they aren't already. */
815 chop_commands (cmds);
817 if (job_slots != 0)
818 /* Wait for a job slot to be freed up. */
819 while (job_slots_used == job_slots)
820 reap_children (1, 0);
822 /* Expand the command lines and store the results in LINES. */
823 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
824 for (i = 0; i < cmds->ncommand_lines; ++i)
826 /* Collapse backslash-newline combinations that are inside variable
827 or function references. These are left alone by the parser so
828 that they will appear in the echoing of commands (where they look
829 nice); and collapsed by construct_command_argv when it tokenizes.
830 But letting them survive inside function invocations loses because
831 we don't want the functions to see them as part of the text. */
833 char *in, *out, *ref;
835 /* IN points to where in the line we are scanning.
836 OUT points to where in the line we are writing.
837 When we collapse a backslash-newline combination,
838 IN gets ahead out OUT. */
840 in = out = cmds->command_lines[i];
841 while ((ref = index (in, '$')) != 0)
843 ++ref; /* Move past the $. */
845 if (out != in)
846 /* Copy the text between the end of the last chunk
847 we processed (where IN points) and the new chunk
848 we are about to process (where REF points). */
849 bcopy (in, out, ref - in);
851 /* Move both pointers past the boring stuff. */
852 out += ref - in;
853 in = ref;
855 if (*ref == '(' || *ref == '{')
857 char openparen = *ref;
858 char closeparen = openparen == '(' ? ')' : '}';
859 int count;
860 char *p;
862 *out++ = *in++; /* Copy OPENPAREN. */
863 /* IN now points past the opening paren or brace.
864 Count parens or braces until it is matched. */
865 count = 0;
866 while (*in != '\0')
868 if (*in == closeparen && --count < 0)
869 break;
870 else if (*in == '\\' && in[1] == '\n')
872 /* We have found a backslash-newline inside a
873 variable or function reference. Eat it and
874 any following whitespace. */
876 int quoted = 0;
877 for (p = in - 1; p > ref && *p == '\\'; --p)
878 quoted = !quoted;
880 if (quoted)
881 /* There were two or more backslashes, so this is
882 not really a continuation line. We don't collapse
883 the quoting backslashes here as is done in
884 collapse_continuations, because the line will
885 be collapsed again after expansion. */
886 *out++ = *in++;
887 else
889 /* Skip the backslash, newline and
890 any following whitespace. */
891 in = next_token (in + 2);
893 /* Discard any preceding whitespace that has
894 already been written to the output. */
895 while (out > ref && isblank (out[-1]))
896 --out;
898 /* Replace it all with a single space. */
899 *out++ = ' ';
902 else
904 if (*in == openparen)
905 ++count;
907 *out++ = *in++;
913 /* There are no more references in this line to worry about.
914 Copy the remaining uninteresting text to the output. */
915 if (out != in)
916 strcpy (out, in);
918 /* Finally, expand the line. */
919 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
920 file);
923 /* Start the command sequence, record it in a new
924 `struct child', and add that to the chain. */
926 c = (struct child *) xmalloc (sizeof (struct child));
927 c->file = file;
928 c->command_lines = lines;
929 c->command_line = 0;
930 c->command_ptr = 0;
931 c->environment = 0;
933 /* Fetch the first command line to be run. */
934 if (! job_next_command (c))
936 /* There were no commands! */
937 free_child (c);
938 c->file->update_status = 0;
940 else
942 /* The job is now primed. Start it running. */
943 start_waiting_job (c);
945 if (job_slots == 1)
946 /* Since there is only one job slot, make things run linearly.
947 Wait for the child to die, setting the state to `cs_finished'. */
948 while (file->command_state == cs_running)
949 reap_children (1, 0);
953 /* Move CHILD's pointers to the next command for it to execute.
954 Returns nonzero if there is another command. */
956 static int
957 job_next_command (child)
958 struct child *child;
960 if (child->command_ptr == 0 || *child->command_ptr == '\0')
962 /* There are no more lines in the expansion of this line. */
963 if (child->command_line == child->file->cmds->ncommand_lines)
965 /* There are no more lines to be expanded. */
966 child->command_ptr = 0;
967 return 0;
969 else
970 /* Get the next line to run. */
971 child->command_ptr = child->command_lines[child->command_line++];
973 return 1;
976 static int
977 load_too_high ()
979 #ifdef __MSDOS__
980 return 1;
981 #else
982 extern int getloadavg ();
983 double load;
985 if (max_load_average < 0)
986 return 0;
988 make_access ();
989 if (getloadavg (&load, 1) != 1)
991 static int lossage = -1;
992 /* Complain only once for the same error. */
993 if (lossage == -1 || errno != lossage)
995 if (errno == 0)
996 /* An errno value of zero means getloadavg is just unsupported. */
997 error ("cannot enforce load limits on this operating system");
998 else
999 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1001 lossage = errno;
1002 load = 0;
1004 user_access ();
1006 return load >= max_load_average;
1007 #endif
1010 /* Start jobs that are waiting for the load to be lower. */
1012 void
1013 start_waiting_jobs ()
1015 struct child *job;
1017 if (waiting_jobs == 0)
1018 return;
1022 /* Check for recently deceased descendants. */
1023 reap_children (0, 0);
1025 /* Take a job off the waiting list. */
1026 job = waiting_jobs;
1027 waiting_jobs = job->next;
1029 /* Try to start that job. We break out of the loop as soon
1030 as start_waiting_job puts one back on the waiting list. */
1031 } while (start_waiting_job (job) && waiting_jobs != 0);
1034 /* Replace the current process with one executing the command in ARGV.
1035 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1036 the environment of the new program. This function does not return. */
1038 void
1039 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1040 int stdin_fd, stdout_fd;
1041 char **argv, **envp;
1043 if (stdin_fd != 0)
1044 (void) dup2 (stdin_fd, 0);
1045 if (stdout_fd != 1)
1046 (void) dup2 (stdout_fd, 1);
1048 /* Free up file descriptors. */
1050 register int d;
1051 int max = getdtablesize ();
1052 for (d = 3; d < max; ++d)
1053 (void) close (d);
1056 /* Run the command. */
1057 exec_command (argv, envp);
1060 /* Search PATH for FILE.
1061 If successful, store the full pathname in PROGRAM and return 1.
1062 If not sucessful, return zero. */
1064 static int
1065 search_path (file, path, program)
1066 char *file, *path, *program;
1068 if (path == 0 || path[0] == '\0')
1069 path = default_path;
1071 if (
1072 #ifdef __MSDOS__
1073 strpbrk (file, "/\\:")
1074 #else
1075 index (file, '/')
1076 #endif
1077 != 0)
1079 strcpy (program, file);
1080 return 1;
1082 else
1084 unsigned int len;
1086 #ifdef HAVE_GETGROUPS
1087 #ifndef HAVE_UNISTD_H
1088 extern int getgroups ();
1089 #endif
1090 static int ngroups = -1;
1091 #ifdef NGROUPS_MAX
1092 static GETGROUPS_T groups[NGROUPS_MAX];
1093 #define ngroups_max NGROUPS_MAX
1094 #else
1095 static GETGROUPS_T *groups = 0;
1096 static int ngroups_max;
1097 if (groups == 0)
1099 ngroups_max = GET_NGROUPS_MAX;
1100 groups = (GETGROUPS_T *) malloc (ngroups_max * sizeof (GETGROUPS_T));
1102 #endif
1103 if (groups != 0 && ngroups == -1)
1104 ngroups = getgroups (ngroups_max, groups);
1105 #endif /* Have getgroups. */
1107 len = strlen (file) + 1;
1110 struct stat st;
1111 int perm;
1112 char *p;
1114 p = index (path, PATH_SEPARATOR_CHAR);
1115 if (p == 0)
1116 p = path + strlen (path);
1118 if (p == path)
1119 bcopy (file, program, len);
1120 else
1122 bcopy (path, program, p - path);
1123 program[p - path] = '/';
1124 bcopy (file, program + (p - path) + 1, len);
1127 if (safe_stat (program, &st) == 0
1128 && S_ISREG (st.st_mode))
1130 if (st.st_uid == geteuid ())
1131 perm = (st.st_mode & 0100);
1132 else if (st.st_gid == getegid ())
1133 perm = (st.st_mode & 0010);
1134 else
1136 #ifdef HAVE_GETGROUPS
1137 register int i;
1138 for (i = 0; i < ngroups; ++i)
1139 if (groups[i] == st.st_gid)
1140 break;
1141 if (i < ngroups)
1142 perm = (st.st_mode & 0010);
1143 else
1144 #endif /* Have getgroups. */
1145 perm = (st.st_mode & 0001);
1148 if (perm != 0)
1149 return 1;
1152 path = p + 1;
1153 } while (*path != '\0');
1156 return 0;
1159 /* Replace the current process with one running the command in ARGV,
1160 with environment ENVP. This function does not return. */
1162 void
1163 exec_command (argv, envp)
1164 char **argv, **envp;
1166 char *shell, *path;
1167 PATH_VAR (program);
1168 register char **ep;
1170 shell = path = 0;
1171 for (ep = envp; *ep != 0; ++ep)
1173 if (shell == 0 && !strncmp(*ep, "SHELL=", 6))
1174 shell = &(*ep)[6];
1175 else if (path == 0 && !strncmp(*ep, "PATH=", 5))
1176 path = &(*ep)[5];
1177 else if (path != 0 && shell != 0)
1178 break;
1181 /* Be the user, permanently. */
1182 child_access ();
1184 if (!search_path (argv[0], path, program))
1185 error ("%s: Command not found", argv[0]);
1186 else
1188 /* Run the program. */
1189 execve (program, argv, envp);
1191 if (errno == ENOEXEC)
1193 PATH_VAR (shell_program);
1194 char *shell_path;
1195 if (shell == 0)
1196 shell_path = default_shell;
1197 else
1199 if (search_path (shell, path, shell_program))
1200 shell_path = shell_program;
1201 else
1203 shell_path = 0;
1204 error ("%s: Shell program not found", shell);
1208 if (shell_path != 0)
1210 char **new_argv;
1211 int argc;
1213 argc = 1;
1214 while (argv[argc] != 0)
1215 ++argc;
1217 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1218 new_argv[0] = shell_path;
1219 new_argv[1] = program;
1220 while (argc > 0)
1222 new_argv[1 + argc] = argv[argc];
1223 --argc;
1226 execve (shell_path, new_argv, envp);
1227 perror_with_name ("execve: ", shell_path);
1230 else
1231 perror_with_name ("execve: ", program);
1234 _exit (127);
1237 /* Figure out the argument list necessary to run LINE as a command.
1238 Try to avoid using a shell. This routine handles only ' quoting.
1239 Starting quotes may be escaped with a backslash. If any of the
1240 characters in sh_chars[] is seen, or any of the builtin commands
1241 listed in sh_cmds[] is the first word of a line, the shell is used.
1243 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1244 If *RESTP is NULL, newlines will be ignored.
1246 SHELL is the shell to use, or nil to use the default shell.
1247 IFS is the value of $IFS, or nil (meaning the default). */
1249 static char **
1250 construct_command_argv_internal (line, restp, shell, ifs)
1251 char *line, **restp;
1252 char *shell, *ifs;
1254 #ifdef __MSDOS__
1255 static char sh_chars[] = "\"|<>";
1256 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1257 "copy", "ctty", "date", "del", "dir", "echo",
1258 "erase", "exit", "for", "goto", "if", "if", "md",
1259 "mkdir", "path", "pause", "prompt", "rem", "ren",
1260 "rename", "set", "shift", "time", "type",
1261 "ver", "verify", "vol", ":", 0 };
1262 #else
1263 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1264 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1265 "logout", "set", "umask", "wait", "while", "for",
1266 "case", "if", ":", ".", "break", "continue",
1267 "export", "read", "readonly", "shift", "times",
1268 "trap", "switch", 0 };
1269 #endif
1270 register int i;
1271 register char *p;
1272 register char *ap;
1273 char *end;
1274 int instring, word_has_equals, seen_nonequals;
1275 char **new_argv = 0;
1277 if (restp != NULL)
1278 *restp = NULL;
1280 /* Make sure not to bother processing an empty line. */
1281 while (isblank (*line))
1282 ++line;
1283 if (*line == '\0')
1284 return 0;
1286 /* See if it is safe to parse commands internally. */
1287 if (shell == 0)
1288 shell = default_shell;
1289 else if (strcmp (shell, default_shell))
1290 goto slow;
1292 if (ifs != 0)
1293 for (ap = ifs; *ap != '\0'; ++ap)
1294 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1295 goto slow;
1297 i = strlen (line) + 1;
1299 /* More than 1 arg per character is impossible. */
1300 new_argv = (char **) xmalloc (i * sizeof (char *));
1302 /* All the args can fit in a buffer as big as LINE is. */
1303 ap = new_argv[0] = (char *) xmalloc (i);
1304 end = ap + i;
1306 /* I is how many complete arguments have been found. */
1307 i = 0;
1308 instring = word_has_equals = seen_nonequals = 0;
1309 for (p = line; *p != '\0'; ++p)
1311 if (ap > end)
1312 abort ();
1314 if (instring)
1316 string_char:
1317 /* Inside a string, just copy any char except a closing quote
1318 or a backslash-newline combination. */
1319 if (*p == '\'')
1320 instring = 0;
1321 else if (*p == '\\' && p[1] == '\n')
1322 goto swallow_escaped_newline;
1323 else if (*p == '\n' && restp != NULL)
1325 /* End of the command line. */
1326 *restp = p;
1327 goto end_of_line;
1329 else
1330 *ap++ = *p;
1332 else if (index (sh_chars, *p) != 0)
1333 /* Not inside a string, but it's a special char. */
1334 goto slow;
1335 else
1336 /* Not a special char. */
1337 switch (*p)
1339 case '=':
1340 /* Equals is a special character in leading words before the
1341 first word with no equals sign in it. This is not the case
1342 with sh -k, but we never get here when using nonstandard
1343 shell flags. */
1344 if (! seen_nonequals)
1345 goto slow;
1346 word_has_equals = 1;
1347 *ap++ = '=';
1348 break;
1350 case '\\':
1351 /* Backslash-newline combinations are eaten. */
1352 if (p[1] == '\n')
1354 swallow_escaped_newline:
1356 /* Eat the backslash, the newline, and following whitespace,
1357 replacing it all with a single space. */
1358 p += 2;
1360 /* If there is a tab after a backslash-newline,
1361 remove it from the source line which will be echoed,
1362 since it was most likely used to line
1363 up the continued line with the previous one. */
1364 if (*p == '\t')
1365 strcpy (p, p + 1);
1367 if (instring)
1368 goto string_char;
1369 else
1371 if (ap != new_argv[i])
1372 /* Treat this as a space, ending the arg.
1373 But if it's at the beginning of the arg, it should
1374 just get eaten, rather than becoming an empty arg. */
1375 goto end_of_arg;
1376 else
1377 p = next_token (p) - 1;
1380 else if (p[1] != '\0')
1381 /* Copy and skip the following char. */
1382 *ap++ = *++p;
1383 break;
1385 case '\'':
1386 instring = 1;
1387 break;
1389 case '\n':
1390 if (restp != NULL)
1392 /* End of the command line. */
1393 *restp = p;
1394 goto end_of_line;
1396 else
1397 /* Newlines are not special. */
1398 *ap++ = '\n';
1399 break;
1401 case ' ':
1402 case '\t':
1403 end_of_arg:
1404 /* We have the end of an argument.
1405 Terminate the text of the argument. */
1406 *ap++ = '\0';
1407 new_argv[++i] = ap;
1409 /* Update SEEN_NONEQUALS, which tells us if every word
1410 heretofore has contained an `='. */
1411 seen_nonequals |= ! word_has_equals;
1412 if (word_has_equals && ! seen_nonequals)
1413 /* An `=' in a word before the first
1414 word without one is magical. */
1415 goto slow;
1416 word_has_equals = 0; /* Prepare for the next word. */
1418 /* If this argument is the command name,
1419 see if it is a built-in shell command.
1420 If so, have the shell handle it. */
1421 if (i == 1)
1423 register int j;
1424 for (j = 0; sh_cmds[j] != 0; ++j)
1425 if (streq (sh_cmds[j], new_argv[0]))
1426 goto slow;
1429 /* Ignore multiple whitespace chars. */
1430 p = next_token (p);
1431 /* Next iteration should examine the first nonwhite char. */
1432 --p;
1433 break;
1435 default:
1436 *ap++ = *p;
1437 break;
1440 end_of_line:
1442 if (instring)
1443 /* Let the shell deal with an unterminated quote. */
1444 goto slow;
1446 /* Terminate the last argument and the argument list. */
1448 *ap = '\0';
1449 if (new_argv[i][0] != '\0')
1450 ++i;
1451 new_argv[i] = 0;
1453 if (i == 1)
1455 register int j;
1456 for (j = 0; sh_cmds[j] != 0; ++j)
1457 if (streq (sh_cmds[j], new_argv[0]))
1458 goto slow;
1461 if (new_argv[0] == 0)
1462 /* Line was empty. */
1463 return 0;
1464 else
1465 return new_argv;
1467 slow:;
1468 /* We must use the shell. */
1470 if (new_argv != 0)
1472 /* Free the old argument list we were working on. */
1473 free (new_argv[0]);
1474 free (new_argv);
1477 #ifdef __MSDOS__
1479 FILE *batch;
1480 dos_batch_file = 1;
1481 if (dos_bname == 0)
1483 dos_bname = tempnam (".", "mk");
1484 for (i = 0; dos_bname[i] != '\0'; ++i)
1485 if (dos_bname[i] == '/')
1486 dos_bname[i] = '\\';
1487 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1488 strcpy (dos_bename, dos_bname);
1489 strcat (dos_bname, ".bat");
1490 strcat (dos_bename, ".err");
1492 batch = fopen(bename, "w"); /* Create a file. */
1493 if (batch != NULL)
1494 fclose (batch);
1495 batch = fopen (dos_bname, "w");
1496 fputs ("@echo off\n", batch);
1497 fputs (line, batch);
1498 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1499 fclose (batch);
1500 new_argv = (char **) xmalloc(2 * sizeof(char *));
1501 new_argv[0] = strdup (bname);
1502 new_argv[1] = 0;
1504 #else /* Not MSDOS. */
1506 /* SHELL may be a multi-word command. Construct a command line
1507 "SHELL -c LINE", with all special chars in LINE escaped.
1508 Then recurse, expanding this command line to get the final
1509 argument list. */
1511 unsigned int shell_len = strlen (shell);
1512 static char minus_c[] = " -c ";
1513 unsigned int line_len = strlen (line);
1515 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1516 + (line_len * 2) + 1);
1518 ap = new_line;
1519 bcopy (shell, ap, shell_len);
1520 ap += shell_len;
1521 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1522 ap += sizeof (minus_c) - 1;
1523 for (p = line; *p != '\0'; ++p)
1525 if (restp != NULL && *p == '\n')
1527 *restp = p;
1528 break;
1530 else if (*p == '\\' && p[1] == '\n')
1532 /* Eat the backslash, the newline, and following whitespace,
1533 replacing it all with a single space (which is escaped
1534 from the shell). */
1535 p += 2;
1537 /* If there is a tab after a backslash-newline,
1538 remove it from the source line which will be echoed,
1539 since it was most likely used to line
1540 up the continued line with the previous one. */
1541 if (*p == '\t')
1542 strcpy (p, p + 1);
1544 p = next_token (p);
1545 --p;
1546 *ap++ = '\\';
1547 *ap++ = ' ';
1548 continue;
1551 if (*p == '\\' || *p == '\''
1552 || isspace (*p)
1553 || index (sh_chars, *p) != 0)
1554 *ap++ = '\\';
1555 *ap++ = *p;
1557 *ap = '\0';
1559 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1560 (char *) 0, (char *) 0);
1562 #endif /* MSDOS. */
1564 return new_argv;
1567 /* Figure out the argument list necessary to run LINE as a command.
1568 Try to avoid using a shell. This routine handles only ' quoting.
1569 Starting quotes may be escaped with a backslash. If any of the
1570 characters in sh_chars[] is seen, or any of the builtin commands
1571 listed in sh_cmds[] is the first word of a line, the shell is used.
1573 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1574 If *RESTP is NULL, newlines will be ignored.
1576 FILE is the target whose commands these are. It is used for
1577 variable expansion for $(SHELL) and $(IFS). */
1579 char **
1580 construct_command_argv (line, restp, file)
1581 char *line, **restp;
1582 struct file *file;
1584 char *shell, *ifs;
1585 char **argv;
1588 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1589 int save = warn_undefined_variables_flag;
1590 warn_undefined_variables_flag = 0;
1592 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1593 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1595 warn_undefined_variables_flag = save;
1598 argv = construct_command_argv_internal (line, restp, shell, ifs);
1600 free (shell);
1601 free (ifs);
1603 return argv;
1606 #ifndef HAVE_DUP2
1608 dup2 (old, new)
1609 int old, new;
1611 int fd;
1613 (void) close (new);
1614 fd = dup (old);
1615 if (fd != new)
1617 (void) close (fd);
1618 errno = EMFILE;
1619 return -1;
1622 return fd;
1624 #endif