Added #undef HAVE_SYSCONF_OPEN_MAX.
[make.git] / job.c
blob5b3af833a6485be487776b7676447c0084a1e876
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988, 89, 90, 91, 92, 93, 94, 1995 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 GNU Make is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNU Make; see the file COPYING. If not, write to
17 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
19 #include "make.h"
20 #include "commands.h"
21 #include "job.h"
22 #include "file.h"
23 #include "variable.h"
24 #include <assert.h>
26 /* Default shell to use. */
27 char default_shell[] = "/bin/sh";
29 #ifdef __MSDOS__
30 #include <process.h>
31 static int dos_pid = 123;
32 static int dos_status;
33 static char *dos_bname;
34 static char *dos_bename;
35 static int dos_batch_file;
36 #endif /* MSDOS. */
39 /* If NGROUPS_MAX == 0 then try other methods for finding a real value. */
40 #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0
41 #undef NGROUPS_MAX
42 #endif /* NGROUPS_MAX == 0 */
44 #ifndef NGROUPS_MAX
45 #ifdef POSIX
46 #define GET_NGROUPS_MAX sysconf (_SC_NGROUPS_MAX)
47 #else /* Not POSIX. */
48 #define NGROUPS_MAX NGROUPS
49 #endif /* POSIX. */
50 #endif
52 #ifdef HAVE_SYS_WAIT_H
53 #include <sys/wait.h>
54 #endif
56 #ifdef HAVE_WAITPID
57 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
58 #else /* Don't have waitpid. */
59 #ifdef HAVE_WAIT3
60 #ifndef wait3
61 extern int wait3 ();
62 #endif
63 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
64 #endif /* Have wait3. */
65 #endif /* Have waitpid. */
67 #if !defined (wait) && !defined (POSIX)
68 extern int wait ();
69 #endif
71 #ifndef HAVE_UNION_WAIT
73 #define WAIT_T int
75 #ifndef WTERMSIG
76 #define WTERMSIG(x) ((x) & 0x7f)
77 #endif
78 #ifndef WCOREDUMP
79 #define WCOREDUMP(x) ((x) & 0x80)
80 #endif
81 #ifndef WEXITSTATUS
82 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
83 #endif
84 #ifndef WIFSIGNALED
85 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
86 #endif
87 #ifndef WIFEXITED
88 #define WIFEXITED(x) (WTERMSIG (x) == 0)
89 #endif
91 #else /* Have `union wait'. */
93 #define WAIT_T union wait
94 #ifndef WTERMSIG
95 #define WTERMSIG(x) ((x).w_termsig)
96 #endif
97 #ifndef WCOREDUMP
98 #define WCOREDUMP(x) ((x).w_coredump)
99 #endif
100 #ifndef WEXITSTATUS
101 #define WEXITSTATUS(x) ((x).w_retcode)
102 #endif
103 #ifndef WIFSIGNALED
104 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
105 #endif
106 #ifndef WIFEXITED
107 #define WIFEXITED(x) (WTERMSIG(x) == 0)
108 #endif
110 #endif /* Don't have `union wait'. */
113 #ifndef HAVE_UNISTD_H
114 extern int dup2 ();
115 extern int execve ();
116 extern void _exit ();
117 extern int geteuid (), getegid ();
118 extern int setgid (), getgid ();
119 #endif
121 #ifndef getdtablesize
122 #ifdef HAVE_GETDTABLESIZE
123 extern int getdtablesize ();
124 #else
125 #ifdef HAVE_SYSCONF_OPEN_MAX
126 #define getdtablesize() ((int) sysconf (_SC_OPEN_MAX))
127 #else
128 #include <sys/param.h>
129 #define getdtablesize() NOFILE
130 #if !defined (NOFILE) && defined (NOFILES_MAX)
131 /* SCO 3.2 "devsys 4.2" defines NOFILES_{MIN,MAX} in lieu of NOFILE. */
132 #define NOFILE NOFILES_MAX
133 #endif
134 #endif
135 #endif
136 #endif
138 extern int getloadavg ();
139 extern int start_remote_job_p ();
140 extern int start_remote_job (), remote_status ();
142 RETSIGTYPE child_handler ();
143 static void free_child (), start_job_command ();
144 static int load_too_high (), job_next_command ();
146 /* Chain of all live (or recently deceased) children. */
148 struct child *children = 0;
150 /* Number of children currently running. */
152 unsigned int job_slots_used = 0;
154 /* Nonzero if the `good' standard input is in use. */
156 static int good_stdin_used = 0;
158 /* Chain of children waiting to run until the load average goes down. */
160 static struct child *waiting_jobs = 0;
162 /* Write an error message describing the exit status given in
163 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
164 Append "(ignored)" if IGNORED is nonzero. */
166 static void
167 child_error (target_name, exit_code, exit_sig, coredump, ignored)
168 char *target_name;
169 int exit_code, exit_sig, coredump;
170 int ignored;
172 if (exit_sig == 0)
173 error (ignored ? "[%s] Error %d (ignored)" :
174 "*** [%s] Error %d",
175 target_name, exit_code);
176 else
178 char *coredump_string = coredump ? " (core dumped)" : "";
179 if (exit_sig > 0 && exit_sig < NSIG)
180 error ("*** [%s] %s%s",
181 target_name, sys_siglist[exit_sig], coredump_string);
182 else
183 error ("*** [%s] Signal %d%s", target_name, exit_sig, coredump_string);
187 static unsigned int dead_children = 0;
189 /* Notice that a child died.
190 reap_children should be called when convenient. */
191 RETSIGTYPE
192 child_handler (sig)
193 int sig;
195 ++dead_children;
197 if (debug_flag)
198 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
201 extern int shell_function_pid, shell_function_completed;
203 /* Reap dead children, storing the returned status and the new command
204 state (`cs_finished') in the `file' member of the `struct child' for the
205 dead child, and removing the child from the chain. If BLOCK nonzero,
206 reap at least one child, waiting for it to die if necessary. If ERR is
207 nonzero, print an error message first. */
209 void
210 reap_children (block, err)
211 int block, err;
213 WAIT_T status;
215 while ((children != 0 || shell_function_pid != 0) &&
216 (block || dead_children > 0))
218 int remote = 0;
219 register int pid;
220 int exit_code, exit_sig, coredump;
221 register struct child *lastc, *c;
222 int child_failed;
223 int any_remote, any_local;
225 if (err && dead_children == 0)
227 /* We might block for a while, so let the user know why. */
228 fflush (stdout);
229 error ("*** Waiting for unfinished jobs....");
232 /* We have one less dead child to reap.
233 The test and decrement are not atomic; if it is compiled into:
234 register = dead_children - 1;
235 dead_children = register;
236 a SIGCHLD could come between the two instructions.
237 child_handler increments dead_children.
238 The second instruction here would lose that increment. But the
239 only effect of dead_children being wrong is that we might wait
240 longer than necessary to reap a child, and lose some parallelism;
241 and we might print the "Waiting for unfinished jobs" message above
242 when not necessary. */
244 if (dead_children != 0)
245 --dead_children;
247 any_remote = 0;
248 any_local = shell_function_pid != -1;
249 for (c = children; c != 0; c = c->next)
251 any_remote |= c->remote;
252 any_local |= ! c->remote;
253 if (debug_flag)
254 printf ("Live child 0x%08lx PID %d%s\n",
255 (unsigned long int) c,
256 c->pid, c->remote ? " (remote)" : "");
259 /* First, check for remote children. */
260 if (any_remote)
261 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
262 else
263 pid = 0;
264 if (pid < 0)
266 remote_status_lose:
267 #ifdef EINTR
268 if (errno == EINTR)
269 continue;
270 #endif
271 pfatal_with_name ("remote_status");
273 else if (pid == 0)
275 #ifndef __MSDOS__
276 /* No remote children. Check for local children. */
278 if (any_local)
280 #ifdef WAIT_NOHANG
281 if (!block)
282 pid = WAIT_NOHANG (&status);
283 else
284 #endif
285 pid = wait (&status);
287 else
288 pid = 0;
290 if (pid < 0)
292 #ifdef EINTR
293 if (errno == EINTR)
294 continue;
295 #endif
296 pfatal_with_name ("wait");
298 else if (pid == 0)
300 /* No local children. */
301 if (block && any_remote)
303 /* Now try a blocking wait for a remote child. */
304 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
305 if (pid < 0)
306 goto remote_status_lose;
307 else if (pid == 0)
308 /* No remote children either. Finally give up. */
309 break;
310 else
311 /* We got a remote child. */
312 remote = 1;
314 else
315 break;
317 else
319 /* Chop the status word up. */
320 exit_code = WEXITSTATUS (status);
321 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
322 coredump = WCOREDUMP (status);
324 #else /* MSDOS. */
325 /* Life is very different on MSDOS. */
326 pid = dos_pid - 1;
327 status = dos_status;
328 exit_code = dos_status;
329 exit_sig = 0;
330 coredump = 0;
331 #endif /* Not MSDOS. */
333 else
334 /* We got a remote child. */
335 remote = 1;
337 /* Check if this is the child of the `shell' function. */
338 if (!remote && pid == shell_function_pid)
340 /* It is. Leave an indicator for the `shell' function. */
341 if (exit_sig == 0 && exit_code == 127)
342 shell_function_completed = -1;
343 else
344 shell_function_completed = 1;
345 break;
348 child_failed = exit_sig != 0 || exit_code != 0;
350 /* Search for a child matching the deceased one. */
351 lastc = 0;
352 for (c = children; c != 0; lastc = c, c = c->next)
353 if (c->remote == remote && c->pid == pid)
354 break;
356 if (c == 0)
358 /* An unknown child died. */
359 char buf[100];
360 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
361 if (child_failed)
362 child_error (buf, exit_code, exit_sig, coredump,
363 ignore_errors_flag);
364 else
365 error ("%s finished.", buf);
367 else
369 if (debug_flag)
370 printf ("Reaping %s child 0x%08lx PID %d%s\n",
371 child_failed ? "losing" : "winning",
372 (unsigned long int) c,
373 c->pid, c->remote ? " (remote)" : "");
375 /* If this child had the good stdin, say it is now free. */
376 if (c->good_stdin)
377 good_stdin_used = 0;
379 if (child_failed && !c->noerror && !ignore_errors_flag)
381 /* The commands failed. Write an error message,
382 delete non-precious targets, and abort. */
383 static int delete_on_error = -1;
384 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
385 c->file->update_status = 1;
386 if (delete_on_error == -1)
388 struct file *f = lookup_file (".DELETE_ON_ERROR");
389 delete_on_error = f != 0 && f->is_target;
391 if (exit_sig != 0 || delete_on_error)
392 delete_child_targets (c);
394 else
396 if (child_failed)
398 /* The commands failed, but we don't care. */
399 child_error (c->file->name,
400 exit_code, exit_sig, coredump, 1);
401 child_failed = 0;
404 /* If there are more commands to run, try to start them. */
405 if (job_next_command (c))
407 if (handling_fatal_signal)
409 /* Never start new commands while we are dying.
410 Since there are more commands that wanted to be run,
411 the target was not completely remade. So we treat
412 this as if a command had failed. */
413 c->file->update_status = 1;
415 else
417 /* Check again whether to start remotely.
418 Whether or not we want to changes over time.
419 Also, start_remote_job may need state set up
420 by start_remote_job_p. */
421 c->remote = start_remote_job_p ();
422 start_job_command (c);
423 if (c->file->command_state == cs_running)
424 /* We successfully started the new command.
425 Loop to reap more children. */
426 continue;
429 if (c->file->update_status != 0)
430 /* We failed to start the commands. */
431 delete_child_targets (c);
433 else
434 /* There are no more commands. We got through them all
435 without an unignored error. Now the target has been
436 successfully updated. */
437 c->file->update_status = 0;
440 /* When we get here, all the commands for C->file are finished
441 (or aborted) and C->file->update_status contains 0 or 1. But
442 C->file->command_state is still cs_running if all the commands
443 ran; notice_finish_file looks for cs_running to tell it that
444 it's interesting to check the file's modtime again now. */
446 if (! handling_fatal_signal)
447 /* Notice if the target of the commands has been changed.
448 This also propagates its values for command_state and
449 update_status to its also_make files. */
450 notice_finished_file (c->file);
452 if (debug_flag)
453 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
454 (unsigned long int) c,
455 c->pid, c->remote ? " (remote)" : "");
457 /* Remove the child from the chain and free it. */
458 if (lastc == 0)
459 children = c->next;
460 else
461 lastc->next = c->next;
462 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
463 free_child (c);
465 /* There is now another slot open. */
466 --job_slots_used;
468 /* If the job failed, and the -k flag was not given, die,
469 unless we are already in the process of dying. */
470 if (!err && child_failed && !keep_going_flag)
471 die (2);
474 /* Only block for one child. */
475 block = 0;
479 /* Free the storage allocated for CHILD. */
481 static void
482 free_child (child)
483 register struct child *child;
485 if (child->command_lines != 0)
487 register unsigned int i;
488 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
489 free (child->command_lines[i]);
490 free ((char *) child->command_lines);
493 if (child->environment != 0)
495 register char **ep = child->environment;
496 while (*ep != 0)
497 free (*ep++);
498 free ((char *) child->environment);
501 free ((char *) child);
504 #ifdef POSIX
505 #ifdef __MSDOS__
506 void
507 unblock_sigs ()
509 return;
511 #else
512 extern sigset_t fatal_signal_set;
514 void
515 unblock_sigs ()
517 sigset_t empty;
518 sigemptyset (&empty);
519 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
521 #endif
522 #endif
524 /* Start a job to run the commands specified in CHILD.
525 CHILD is updated to reflect the commands and ID of the child process. */
527 static void
528 start_job_command (child)
529 register struct child *child;
531 static int bad_stdin = -1;
532 register char *p;
533 int flags;
534 char **argv;
536 /* Combine the flags parsed for the line itself with
537 the flags specified globally for this target. */
538 flags = (child->file->command_flags
539 | child->file->cmds->lines_flags[child->command_line - 1]);
541 p = child->command_ptr;
542 child->noerror = flags & COMMANDS_NOERROR;
543 while (*p != '\0')
545 if (*p == '@')
546 flags |= COMMANDS_SILENT;
547 else if (*p == '+')
548 flags |= COMMANDS_RECURSE;
549 else if (*p == '-')
550 child->noerror = 1;
551 else if (!isblank (*p) && *p != '+')
552 break;
553 ++p;
556 /* If -q was given, just say that updating `failed'. The exit status of
557 1 tells the user that -q is saying `something to do'; the exit status
558 for a random error is 2. */
559 if (question_flag && !(flags & COMMANDS_RECURSE))
561 child->file->update_status = 1;
562 notice_finished_file (child->file);
563 return;
566 /* There may be some preceding whitespace left if there
567 was nothing but a backslash on the first line. */
568 p = next_token (p);
570 /* Figure out an argument list from this command line. */
573 char *end;
574 argv = construct_command_argv (p, &end, child->file);
575 if (end == NULL)
576 child->command_ptr = NULL;
577 else
579 *end++ = '\0';
580 child->command_ptr = end;
584 if (touch_flag && !(flags & COMMANDS_RECURSE))
586 /* Go on to the next command. It might be the recursive one.
587 We construct ARGV only to find the end of the command line. */
588 free (argv[0]);
589 free ((char *) argv);
590 argv = 0;
593 if (argv == 0)
595 /* This line has no commands. Go to the next. */
596 if (job_next_command (child))
597 start_job_command (child);
598 else
600 /* No more commands. All done. */
601 child->file->update_status = 0;
602 notice_finished_file (child->file);
604 return;
607 /* Print out the command. */
609 if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
610 puts (p);
612 /* Tell update_goal_chain that a command has been started on behalf of
613 this target. It is important that this happens here and not in
614 reap_children (where we used to do it), because reap_children might be
615 reaping children from a different target. We want this increment to
616 guaranteedly indicate that a command was started for the dependency
617 chain (i.e., update_file recursion chain) we are processing. */
619 ++commands_started;
621 /* If -n was given, recurse to get the next line in the sequence. */
623 if (just_print_flag && !(flags & COMMANDS_RECURSE))
625 free (argv[0]);
626 free ((char *) argv);
627 if (job_next_command (child))
628 start_job_command (child);
629 child->file->update_status = 0;
630 return;
633 /* Flush the output streams so they won't have things written twice. */
635 fflush (stdout);
636 fflush (stderr);
638 /* Set up a bad standard input that reads from a broken pipe. */
640 if (bad_stdin == -1)
642 /* Make a file descriptor that is the read end of a broken pipe.
643 This will be used for some children's standard inputs. */
644 int pd[2];
645 if (pipe (pd) == 0)
647 /* Close the write side. */
648 (void) close (pd[1]);
649 /* Save the read side. */
650 bad_stdin = pd[0];
654 /* Decide whether to give this child the `good' standard input
655 (one that points to the terminal or whatever), or the `bad' one
656 that points to the read side of a broken pipe. */
658 child->good_stdin = !good_stdin_used;
659 if (child->good_stdin)
660 good_stdin_used = 1;
662 child->deleted = 0;
664 /* Set up the environment for the child. */
665 if (child->environment == 0)
666 child->environment = target_environment (child->file);
668 #ifndef __MSDOS__
670 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
671 if (child->remote)
673 int is_remote, id, used_stdin;
674 if (start_remote_job (argv, child->environment,
675 child->good_stdin ? 0 : bad_stdin,
676 &is_remote, &id, &used_stdin))
677 goto error;
678 else
680 if (child->good_stdin && !used_stdin)
682 child->good_stdin = 0;
683 good_stdin_used = 0;
685 child->remote = is_remote;
686 child->pid = id;
689 else
691 /* Fork the child process. */
693 char **parent_environ;
695 #ifdef POSIX
696 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
697 #else
698 #ifdef HAVE_SIGSETMASK
699 (void) sigblock (fatal_signal_mask);
700 #endif
701 #endif
703 child->remote = 0;
704 parent_environ = environ;
705 child->pid = vfork ();
706 environ = parent_environ; /* Restore value child may have clobbered. */
707 if (child->pid == 0)
709 /* We are the child side. */
710 unblock_sigs ();
711 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
712 argv, child->environment);
714 else if (child->pid < 0)
716 /* Fork failed! */
717 unblock_sigs ();
718 perror_with_name ("vfork", "");
719 goto error;
723 #else /* MSDOS. */
724 dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
725 ++dead_children;
726 child->pid = dos_pid++;
727 if (dos_batch_file)
729 dos_batch_file = 0;
730 remove (dos_bname); /* Ignore errors. */
731 if (access (dos_bename, 0))
732 dos_status = 1;
733 else
734 dos_status = 0;
735 remove (dos_bename);
737 #endif /* Not MSDOS. */
739 /* We are the parent side. Set the state to
740 say the commands are running and return. */
742 set_command_state (child->file, cs_running);
744 /* Free the storage used by the child's argument list. */
746 free (argv[0]);
747 free ((char *) argv);
749 return;
751 error:
752 child->file->update_status = 2;
753 notice_finished_file (child->file);
756 /* Try to start a child running.
757 Returns nonzero if the child was started (and maybe finished), or zero if
758 the load was too high and the child was put on the `waiting_jobs' chain. */
760 static int
761 start_waiting_job (c)
762 struct child *c;
764 /* If we can start a job remotely, we always want to, and don't care about
765 the local load average. We record that the job should be started
766 remotely in C->remote for start_job_command to test. */
768 c->remote = start_remote_job_p ();
770 /* If this job is to be started locally, and we are already running
771 some jobs, make this one wait if the load average is too high. */
772 if (!c->remote && job_slots_used > 0 && load_too_high ())
774 /* Put this child on the chain of children waiting
775 for the load average to go down. */
776 set_command_state (c->file, cs_running);
777 c->next = waiting_jobs;
778 waiting_jobs = c;
779 return 0;
782 /* Start the first command; reap_children will run later command lines. */
783 start_job_command (c);
785 switch (c->file->command_state)
787 case cs_running:
788 c->next = children;
789 if (debug_flag)
790 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
791 (unsigned long int) c,
792 c->pid, c->remote ? " (remote)" : "");
793 children = c;
794 /* One more job slot is in use. */
795 ++job_slots_used;
796 unblock_sigs ();
797 break;
799 case cs_not_started:
800 /* All the command lines turned out to be empty. */
801 c->file->update_status = 0;
802 /* FALLTHROUGH */
804 case cs_finished:
805 notice_finished_file (c->file);
806 free_child (c);
807 break;
809 default:
810 assert (c->file->command_state == cs_finished);
811 break;
814 return 1;
817 /* Create a `struct child' for FILE and start its commands running. */
819 void
820 new_job (file)
821 register struct file *file;
823 register struct commands *cmds = file->cmds;
824 register struct child *c;
825 char **lines;
826 register unsigned int i;
828 /* Let any previously decided-upon jobs that are waiting
829 for the load to go down start before this new one. */
830 start_waiting_jobs ();
832 /* Reap any children that might have finished recently. */
833 reap_children (0, 0);
835 /* Chop the commands up into lines if they aren't already. */
836 chop_commands (cmds);
838 if (job_slots != 0)
839 /* Wait for a job slot to be freed up. */
840 while (job_slots_used == job_slots)
841 reap_children (1, 0);
843 /* Expand the command lines and store the results in LINES. */
844 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
845 for (i = 0; i < cmds->ncommand_lines; ++i)
847 /* Collapse backslash-newline combinations that are inside variable
848 or function references. These are left alone by the parser so
849 that they will appear in the echoing of commands (where they look
850 nice); and collapsed by construct_command_argv when it tokenizes.
851 But letting them survive inside function invocations loses because
852 we don't want the functions to see them as part of the text. */
854 char *in, *out, *ref;
856 /* IN points to where in the line we are scanning.
857 OUT points to where in the line we are writing.
858 When we collapse a backslash-newline combination,
859 IN gets ahead out OUT. */
861 in = out = cmds->command_lines[i];
862 while ((ref = index (in, '$')) != 0)
864 ++ref; /* Move past the $. */
866 if (out != in)
867 /* Copy the text between the end of the last chunk
868 we processed (where IN points) and the new chunk
869 we are about to process (where REF points). */
870 bcopy (in, out, ref - in);
872 /* Move both pointers past the boring stuff. */
873 out += ref - in;
874 in = ref;
876 if (*ref == '(' || *ref == '{')
878 char openparen = *ref;
879 char closeparen = openparen == '(' ? ')' : '}';
880 int count;
881 char *p;
883 *out++ = *in++; /* Copy OPENPAREN. */
884 /* IN now points past the opening paren or brace.
885 Count parens or braces until it is matched. */
886 count = 0;
887 while (*in != '\0')
889 if (*in == closeparen && --count < 0)
890 break;
891 else if (*in == '\\' && in[1] == '\n')
893 /* We have found a backslash-newline inside a
894 variable or function reference. Eat it and
895 any following whitespace. */
897 int quoted = 0;
898 for (p = in - 1; p > ref && *p == '\\'; --p)
899 quoted = !quoted;
901 if (quoted)
902 /* There were two or more backslashes, so this is
903 not really a continuation line. We don't collapse
904 the quoting backslashes here as is done in
905 collapse_continuations, because the line will
906 be collapsed again after expansion. */
907 *out++ = *in++;
908 else
910 /* Skip the backslash, newline and
911 any following whitespace. */
912 in = next_token (in + 2);
914 /* Discard any preceding whitespace that has
915 already been written to the output. */
916 while (out > ref && isblank (out[-1]))
917 --out;
919 /* Replace it all with a single space. */
920 *out++ = ' ';
923 else
925 if (*in == openparen)
926 ++count;
928 *out++ = *in++;
934 /* There are no more references in this line to worry about.
935 Copy the remaining uninteresting text to the output. */
936 if (out != in)
937 strcpy (out, in);
939 /* Finally, expand the line. */
940 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
941 file);
944 /* Start the command sequence, record it in a new
945 `struct child', and add that to the chain. */
947 c = (struct child *) xmalloc (sizeof (struct child));
948 c->file = file;
949 c->command_lines = lines;
950 c->command_line = 0;
951 c->command_ptr = 0;
952 c->environment = 0;
954 /* Fetch the first command line to be run. */
955 if (! job_next_command (c))
957 /* There were no commands! */
958 free_child (c);
959 c->file->update_status = 0;
961 else
963 /* The job is now primed. Start it running. */
964 start_waiting_job (c);
966 if (job_slots == 1)
967 /* Since there is only one job slot, make things run linearly.
968 Wait for the child to die, setting the state to `cs_finished'. */
969 while (file->command_state == cs_running)
970 reap_children (1, 0);
974 /* Move CHILD's pointers to the next command for it to execute.
975 Returns nonzero if there is another command. */
977 static int
978 job_next_command (child)
979 struct child *child;
981 if (child->command_ptr == 0 || *child->command_ptr == '\0')
983 /* There are no more lines in the expansion of this line. */
984 if (child->command_line == child->file->cmds->ncommand_lines)
986 /* There are no more lines to be expanded. */
987 child->command_ptr = 0;
988 return 0;
990 else
991 /* Get the next line to run. */
992 child->command_ptr = child->command_lines[child->command_line++];
994 return 1;
997 static int
998 load_too_high ()
1000 #ifdef __MSDOS__
1001 return 1;
1002 #else
1003 extern int getloadavg ();
1004 double load;
1006 if (max_load_average < 0)
1007 return 0;
1009 make_access ();
1010 if (getloadavg (&load, 1) != 1)
1012 static int lossage = -1;
1013 /* Complain only once for the same error. */
1014 if (lossage == -1 || errno != lossage)
1016 if (errno == 0)
1017 /* An errno value of zero means getloadavg is just unsupported. */
1018 error ("cannot enforce load limits on this operating system");
1019 else
1020 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1022 lossage = errno;
1023 load = 0;
1025 user_access ();
1027 return load >= max_load_average;
1028 #endif
1031 /* Start jobs that are waiting for the load to be lower. */
1033 void
1034 start_waiting_jobs ()
1036 struct child *job;
1038 if (waiting_jobs == 0)
1039 return;
1043 /* Check for recently deceased descendants. */
1044 reap_children (0, 0);
1046 /* Take a job off the waiting list. */
1047 job = waiting_jobs;
1048 waiting_jobs = job->next;
1050 /* Try to start that job. We break out of the loop as soon
1051 as start_waiting_job puts one back on the waiting list. */
1052 } while (start_waiting_job (job) && waiting_jobs != 0);
1055 /* Replace the current process with one executing the command in ARGV.
1056 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1057 the environment of the new program. This function does not return. */
1059 void
1060 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1061 int stdin_fd, stdout_fd;
1062 char **argv, **envp;
1064 if (stdin_fd != 0)
1065 (void) dup2 (stdin_fd, 0);
1066 if (stdout_fd != 1)
1067 (void) dup2 (stdout_fd, 1);
1069 /* Free up file descriptors. */
1071 register int d;
1072 int max = getdtablesize ();
1073 for (d = 3; d < max; ++d)
1074 (void) close (d);
1077 /* Run the command. */
1078 exec_command (argv, envp);
1081 #if 0
1083 /* Default path to search for executables. */
1084 static char default_path[] = ":/bin:/usr/bin";
1086 /* Search PATH for FILE.
1087 If successful, store the full pathname in PROGRAM and return 1.
1088 If not sucessful, return zero. */
1090 static int
1091 search_path (file, path, program)
1092 char *file, *path, *program;
1094 if (path == 0 || path[0] == '\0')
1095 path = default_path;
1097 if (
1098 #ifdef __MSDOS__
1099 strpbrk (file, "/\\:")
1100 #else
1101 index (file, '/')
1102 #endif
1103 != 0)
1105 strcpy (program, file);
1106 return 1;
1108 else
1110 unsigned int len;
1112 #ifdef HAVE_GETGROUPS
1113 #ifndef HAVE_UNISTD_H
1114 extern int getgroups ();
1115 #endif
1116 static int ngroups = -1;
1117 #ifdef NGROUPS_MAX
1118 static GETGROUPS_T groups[NGROUPS_MAX];
1119 #define ngroups_max NGROUPS_MAX
1120 #else
1121 static GETGROUPS_T *groups = 0;
1122 static int ngroups_max;
1123 if (groups == 0)
1125 ngroups_max = GET_NGROUPS_MAX;
1126 groups = (GETGROUPS_T *) malloc (ngroups_max * sizeof (GETGROUPS_T));
1128 #endif
1129 if (groups != 0 && ngroups == -1)
1130 ngroups = getgroups (ngroups_max, groups);
1131 #endif /* Have getgroups. */
1133 len = strlen (file) + 1;
1136 struct stat st;
1137 int perm;
1138 char *p;
1140 p = index (path, PATH_SEPARATOR_CHAR);
1141 if (p == 0)
1142 p = path + strlen (path);
1144 if (p == path)
1145 bcopy (file, program, len);
1146 else
1148 bcopy (path, program, p - path);
1149 program[p - path] = '/';
1150 bcopy (file, program + (p - path) + 1, len);
1153 if (safe_stat (program, &st) == 0
1154 && S_ISREG (st.st_mode))
1156 if (st.st_uid == geteuid ())
1157 perm = (st.st_mode & 0100);
1158 else if (st.st_gid == getegid ())
1159 perm = (st.st_mode & 0010);
1160 else
1162 #ifdef HAVE_GETGROUPS
1163 register int i;
1164 for (i = 0; i < ngroups; ++i)
1165 if (groups[i] == st.st_gid)
1166 break;
1167 if (i < ngroups)
1168 perm = (st.st_mode & 0010);
1169 else
1170 #endif /* Have getgroups. */
1171 perm = (st.st_mode & 0001);
1174 if (perm != 0)
1175 return 1;
1178 path = p + 1;
1179 } while (*path != '\0');
1182 return 0;
1184 #endif /* search_path commented out */
1186 /* Replace the current process with one running the command in ARGV,
1187 with environment ENVP. This function does not return. */
1189 void
1190 exec_command (argv, envp)
1191 char **argv, **envp;
1193 /* Be the user, permanently. */
1194 child_access ();
1196 /* Run the program. */
1197 environ = envp;
1198 execvp (argv[0], argv);
1200 switch (errno)
1202 case ENOENT:
1203 error ("%s: Command not found", argv[0]);
1204 break;
1205 case ENOEXEC:
1207 /* The file is not executable. Try it as a shell script. */
1208 extern char *getenv ();
1209 char *shell;
1210 char **new_argv;
1211 int argc;
1213 shell = getenv ("SHELL");
1214 if (shell == 0)
1215 shell = default_shell;
1217 argc = 1;
1218 while (argv[argc] != 0)
1219 ++argc;
1221 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1222 new_argv[0] = shell;
1223 new_argv[1] = program;
1224 while (argc > 0)
1226 new_argv[1 + argc] = argv[argc];
1227 --argc;
1230 execvp (shell, new_argv);
1231 if (errno == ENOENT)
1232 error ("%s: Shell program not found", shell);
1233 else
1234 perror_with_name ("execvp: ", shell);
1235 break;
1238 default:
1239 perror_with_name ("execvp: ", argv[0]);
1240 break;
1243 _exit (127);
1246 /* Figure out the argument list necessary to run LINE as a command. Try to
1247 avoid using a shell. This routine handles only ' quoting, and " quoting
1248 when no backslash, $ or ` characters are seen in the quotes. Starting
1249 quotes may be escaped with a backslash. If any of the characters in
1250 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1251 is the first word of a line, the shell is used.
1253 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1254 If *RESTP is NULL, newlines will be ignored.
1256 SHELL is the shell to use, or nil to use the default shell.
1257 IFS is the value of $IFS, or nil (meaning the default). */
1259 static char **
1260 construct_command_argv_internal (line, restp, shell, ifs)
1261 char *line, **restp;
1262 char *shell, *ifs;
1264 #ifdef __MSDOS__
1265 static char sh_chars[] = "\"|<>";
1266 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1267 "copy", "ctty", "date", "del", "dir", "echo",
1268 "erase", "exit", "for", "goto", "if", "if", "md",
1269 "mkdir", "path", "pause", "prompt", "rem", "ren",
1270 "rename", "set", "shift", "time", "type",
1271 "ver", "verify", "vol", ":", 0 };
1272 #else
1273 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1274 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1275 "logout", "set", "umask", "wait", "while", "for",
1276 "case", "if", ":", ".", "break", "continue",
1277 "export", "read", "readonly", "shift", "times",
1278 "trap", "switch", 0 };
1279 #endif
1280 register int i;
1281 register char *p;
1282 register char *ap;
1283 char *end;
1284 int instring, word_has_equals, seen_nonequals;
1285 char **new_argv = 0;
1287 if (restp != NULL)
1288 *restp = NULL;
1290 /* Make sure not to bother processing an empty line. */
1291 while (isblank (*line))
1292 ++line;
1293 if (*line == '\0')
1294 return 0;
1296 /* See if it is safe to parse commands internally. */
1297 if (shell == 0)
1298 shell = default_shell;
1299 else if (strcmp (shell, default_shell))
1300 goto slow;
1302 if (ifs != 0)
1303 for (ap = ifs; *ap != '\0'; ++ap)
1304 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1305 goto slow;
1307 i = strlen (line) + 1;
1309 /* More than 1 arg per character is impossible. */
1310 new_argv = (char **) xmalloc (i * sizeof (char *));
1312 /* All the args can fit in a buffer as big as LINE is. */
1313 ap = new_argv[0] = (char *) xmalloc (i);
1314 end = ap + i;
1316 /* I is how many complete arguments have been found. */
1317 i = 0;
1318 instring = word_has_equals = seen_nonequals = 0;
1319 for (p = line; *p != '\0'; ++p)
1321 if (ap > end)
1322 abort ();
1324 if (instring)
1326 string_char:
1327 /* Inside a string, just copy any char except a closing quote
1328 or a backslash-newline combination. */
1329 if (*p == instring)
1330 instring = 0;
1331 else if (*p == '\\' && p[1] == '\n')
1332 goto swallow_escaped_newline;
1333 else if (*p == '\n' && restp != NULL)
1335 /* End of the command line. */
1336 *restp = p;
1337 goto end_of_line;
1339 /* Backslash, $, and ` are special inside double quotes.
1340 If we see any of those, punt. */
1341 else if (instring == '"' && index ("\\$`", *p) != 0)
1342 goto slow;
1343 else
1344 *ap++ = *p;
1346 else if (index (sh_chars, *p) != 0)
1347 /* Not inside a string, but it's a special char. */
1348 goto slow;
1349 else
1350 /* Not a special char. */
1351 switch (*p)
1353 case '=':
1354 /* Equals is a special character in leading words before the
1355 first word with no equals sign in it. This is not the case
1356 with sh -k, but we never get here when using nonstandard
1357 shell flags. */
1358 if (! seen_nonequals)
1359 goto slow;
1360 word_has_equals = 1;
1361 *ap++ = '=';
1362 break;
1364 case '\\':
1365 /* Backslash-newline combinations are eaten. */
1366 if (p[1] == '\n')
1368 swallow_escaped_newline:
1370 /* Eat the backslash, the newline, and following whitespace,
1371 replacing it all with a single space. */
1372 p += 2;
1374 /* If there is a tab after a backslash-newline,
1375 remove it from the source line which will be echoed,
1376 since it was most likely used to line
1377 up the continued line with the previous one. */
1378 if (*p == '\t')
1379 strcpy (p, p + 1);
1381 if (instring)
1382 goto string_char;
1383 else
1385 if (ap != new_argv[i])
1386 /* Treat this as a space, ending the arg.
1387 But if it's at the beginning of the arg, it should
1388 just get eaten, rather than becoming an empty arg. */
1389 goto end_of_arg;
1390 else
1391 p = next_token (p) - 1;
1394 else if (p[1] != '\0')
1395 /* Copy and skip the following char. */
1396 *ap++ = *++p;
1397 break;
1399 case '\'':
1400 case '"':
1401 instring = *p;
1402 break;
1404 case '\n':
1405 if (restp != NULL)
1407 /* End of the command line. */
1408 *restp = p;
1409 goto end_of_line;
1411 else
1412 /* Newlines are not special. */
1413 *ap++ = '\n';
1414 break;
1416 case ' ':
1417 case '\t':
1418 end_of_arg:
1419 /* We have the end of an argument.
1420 Terminate the text of the argument. */
1421 *ap++ = '\0';
1422 new_argv[++i] = ap;
1424 /* Update SEEN_NONEQUALS, which tells us if every word
1425 heretofore has contained an `='. */
1426 seen_nonequals |= ! word_has_equals;
1427 if (word_has_equals && ! seen_nonequals)
1428 /* An `=' in a word before the first
1429 word without one is magical. */
1430 goto slow;
1431 word_has_equals = 0; /* Prepare for the next word. */
1433 /* If this argument is the command name,
1434 see if it is a built-in shell command.
1435 If so, have the shell handle it. */
1436 if (i == 1)
1438 register int j;
1439 for (j = 0; sh_cmds[j] != 0; ++j)
1440 if (streq (sh_cmds[j], new_argv[0]))
1441 goto slow;
1444 /* Ignore multiple whitespace chars. */
1445 p = next_token (p);
1446 /* Next iteration should examine the first nonwhite char. */
1447 --p;
1448 break;
1450 default:
1451 *ap++ = *p;
1452 break;
1455 end_of_line:
1457 if (instring)
1458 /* Let the shell deal with an unterminated quote. */
1459 goto slow;
1461 /* Terminate the last argument and the argument list. */
1463 *ap = '\0';
1464 if (new_argv[i][0] != '\0')
1465 ++i;
1466 new_argv[i] = 0;
1468 if (i == 1)
1470 register int j;
1471 for (j = 0; sh_cmds[j] != 0; ++j)
1472 if (streq (sh_cmds[j], new_argv[0]))
1473 goto slow;
1476 if (new_argv[0] == 0)
1477 /* Line was empty. */
1478 return 0;
1479 else
1480 return new_argv;
1482 slow:;
1483 /* We must use the shell. */
1485 if (new_argv != 0)
1487 /* Free the old argument list we were working on. */
1488 free (new_argv[0]);
1489 free (new_argv);
1492 #ifdef __MSDOS__
1494 FILE *batch;
1495 dos_batch_file = 1;
1496 if (dos_bname == 0)
1498 dos_bname = tempnam (".", "mk");
1499 for (i = 0; dos_bname[i] != '\0'; ++i)
1500 if (dos_bname[i] == '/')
1501 dos_bname[i] = '\\';
1502 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1503 strcpy (dos_bename, dos_bname);
1504 strcat (dos_bname, ".bat");
1505 strcat (dos_bename, ".err");
1507 batch = fopen(bename, "w"); /* Create a file. */
1508 if (batch != NULL)
1509 fclose (batch);
1510 batch = fopen (dos_bname, "w");
1511 fputs ("@echo off\n", batch);
1512 fputs (line, batch);
1513 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1514 fclose (batch);
1515 new_argv = (char **) xmalloc(2 * sizeof(char *));
1516 new_argv[0] = strdup (bname);
1517 new_argv[1] = 0;
1519 #else /* Not MSDOS. */
1521 /* SHELL may be a multi-word command. Construct a command line
1522 "SHELL -c LINE", with all special chars in LINE escaped.
1523 Then recurse, expanding this command line to get the final
1524 argument list. */
1526 unsigned int shell_len = strlen (shell);
1527 static char minus_c[] = " -c ";
1528 unsigned int line_len = strlen (line);
1530 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1531 + (line_len * 2) + 1);
1533 ap = new_line;
1534 bcopy (shell, ap, shell_len);
1535 ap += shell_len;
1536 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1537 ap += sizeof (minus_c) - 1;
1538 for (p = line; *p != '\0'; ++p)
1540 if (restp != NULL && *p == '\n')
1542 *restp = p;
1543 break;
1545 else if (*p == '\\' && p[1] == '\n')
1547 /* Eat the backslash, the newline, and following whitespace,
1548 replacing it all with a single space (which is escaped
1549 from the shell). */
1550 p += 2;
1552 /* If there is a tab after a backslash-newline,
1553 remove it from the source line which will be echoed,
1554 since it was most likely used to line
1555 up the continued line with the previous one. */
1556 if (*p == '\t')
1557 strcpy (p, p + 1);
1559 p = next_token (p);
1560 --p;
1561 *ap++ = '\\';
1562 *ap++ = ' ';
1563 continue;
1566 if (*p == '\\' || *p == '\'' || *p == '"'
1567 || isspace (*p)
1568 || index (sh_chars, *p) != 0)
1569 *ap++ = '\\';
1570 *ap++ = *p;
1572 *ap = '\0';
1574 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1575 (char *) 0, (char *) 0);
1577 #endif /* MSDOS. */
1579 return new_argv;
1582 /* Figure out the argument list necessary to run LINE as a command. Try to
1583 avoid using a shell. This routine handles only ' quoting, and " quoting
1584 when no backslash, $ or ` characters are seen in the quotes. Starting
1585 quotes may be escaped with a backslash. If any of the characters in
1586 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1587 is the first word of a line, the shell is used.
1589 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1590 If *RESTP is NULL, newlines will be ignored.
1592 FILE is the target whose commands these are. It is used for
1593 variable expansion for $(SHELL) and $(IFS). */
1595 char **
1596 construct_command_argv (line, restp, file)
1597 char *line, **restp;
1598 struct file *file;
1600 char *shell, *ifs;
1601 char **argv;
1604 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1605 int save = warn_undefined_variables_flag;
1606 warn_undefined_variables_flag = 0;
1608 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1609 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1611 warn_undefined_variables_flag = save;
1614 argv = construct_command_argv_internal (line, restp, shell, ifs);
1616 free (shell);
1617 free (ifs);
1619 return argv;
1622 #ifndef HAVE_DUP2
1624 dup2 (old, new)
1625 int old, new;
1627 int fd;
1629 (void) close (new);
1630 fd = dup (old);
1631 if (fd != new)
1633 (void) close (fd);
1634 errno = EMFILE;
1635 return -1;
1638 return fd;
1640 #endif