[__MSDOS__]: Include <process.h>.
[make.git] / job.c
blobc850d7e1c93320d2865cbce0fea1aa9ad6764de6
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"
25 /* Default path to search for executables. */
26 static char default_path[] = ":/bin:/usr/bin";
28 /* Default shell to use. */
29 char default_shell[] = "/bin/sh";
31 #ifdef __MSDOS__
32 #include <process.h>
33 static int dos_pid = 123;
34 static int dos_status;
35 static char *dos_bname;
36 static char *dos_bename;
37 static int dos_batch_file;
38 #define PATH_SEPARATOR_CHAR ';'
39 #else /* Not MSDOS. */
40 #define PATH_SEPARATOR_CHAR ':'
41 #endif /* MSDOS. */
44 /* If NGROUPS_MAX == 0 then try other methods for finding a real value. */
45 #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0
46 #undef NGROUPS_MAX
47 #endif /* NGROUPS_MAX == 0 */
49 #ifndef NGROUPS_MAX
50 #ifdef POSIX
51 #define GET_NGROUPS_MAX sysconf (_SC_NGROUPS_MAX)
52 #else /* Not POSIX. */
53 #define NGROUPS_MAX NGROUPS
54 #endif /* POSIX. */
55 #endif
57 #ifdef HAVE_SYS_WAIT_H
58 #include <sys/wait.h>
59 #endif
61 #ifdef HAVE_WAITPID
62 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
63 #else /* Don't have waitpid. */
64 #ifdef HAVE_WAIT3
65 #ifndef wait3
66 extern int wait3 ();
67 #endif
68 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
69 #endif /* Have wait3. */
70 #endif /* Have waitpid. */
72 #if !defined (wait) && !defined (POSIX)
73 extern int wait ();
74 #endif
76 #ifndef HAVE_UNION_WAIT
78 #define WAIT_T int
80 #ifndef WTERMSIG
81 #define WTERMSIG(x) ((x) & 0x7f)
82 #endif
83 #ifndef WCOREDUMP
84 #define WCOREDUMP(x) ((x) & 0x80)
85 #endif
86 #ifndef WEXITSTATUS
87 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
88 #endif
89 #ifndef WIFSIGNALED
90 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
91 #endif
92 #ifndef WIFEXITED
93 #define WIFEXITED(x) (WTERMSIG (x) == 0)
94 #endif
96 #else /* Have `union wait'. */
98 #define WAIT_T union wait
99 #ifndef WTERMSIG
100 #define WTERMSIG(x) ((x).w_termsig)
101 #endif
102 #ifndef WCOREDUMP
103 #define WCOREDUMP(x) ((x).w_coredump)
104 #endif
105 #ifndef WEXITSTATUS
106 #define WEXITSTATUS(x) ((x).w_retcode)
107 #endif
108 #ifndef WIFSIGNALED
109 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
110 #endif
111 #ifndef WIFEXITED
112 #define WIFEXITED(x) (WTERMSIG(x) == 0)
113 #endif
115 #endif /* Don't have `union wait'. */
118 #ifndef HAVE_UNISTD_H
119 extern int dup2 ();
120 extern int execve ();
121 extern void _exit ();
122 extern int geteuid (), getegid ();
123 extern int setgid (), getgid ();
124 #endif
126 #ifndef getdtablesize
127 #ifdef HAVE_GETDTABLESIZE
128 extern int getdtablesize ();
129 #else
130 #include <sys/param.h>
131 #define getdtablesize() NOFILE
132 #if !defined (NOFILE) && defined (NOFILES_MAX)
133 /* SCO 3.2 "devsys 4.2" defines NOFILES_{MIN,MAX} in lieu of NOFILE. */
134 #define NOFILE NOFILES_MAX
135 #endif
136 #endif
137 #endif
139 extern int getloadavg ();
140 extern int start_remote_job_p ();
141 extern int start_remote_job (), remote_status ();
143 RETSIGTYPE child_handler ();
144 static void free_child (), start_job_command ();
145 static int load_too_high (), job_next_command ();
147 /* Chain of all live (or recently deceased) children. */
149 struct child *children = 0;
151 /* Number of children currently running. */
153 unsigned int job_slots_used = 0;
155 /* Nonzero if the `good' standard input is in use. */
157 static int good_stdin_used = 0;
159 /* Chain of children waiting to run until the load average goes down. */
161 static struct child *waiting_jobs = 0;
163 /* Write an error message describing the exit status given in
164 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
165 Append "(ignored)" if IGNORED is nonzero. */
167 static void
168 child_error (target_name, exit_code, exit_sig, coredump, ignored)
169 char *target_name;
170 int exit_code, exit_sig, coredump;
171 int ignored;
173 if (exit_sig == 0)
174 error (ignored ? "[%s] Error %d (ignored)" :
175 "*** [%s] Error %d",
176 target_name, exit_code);
177 else
179 char *coredump_string = coredump ? " (core dumped)" : "";
180 if (exit_sig > 0 && exit_sig < NSIG)
181 error ("*** [%s] %s%s",
182 target_name, sys_siglist[exit_sig], coredump_string);
183 else
184 error ("*** [%s] Signal %d%s", target_name, exit_sig, coredump_string);
188 static unsigned int dead_children = 0;
190 /* Notice that a child died.
191 reap_children should be called when convenient. */
192 RETSIGTYPE
193 child_handler (sig)
194 int sig;
196 ++dead_children;
198 if (debug_flag)
199 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
202 extern int shell_function_pid, shell_function_completed;
204 /* Reap dead children, storing the returned status and the new command
205 state (`cs_finished') in the `file' member of the `struct child' for the
206 dead child, and removing the child from the chain. If BLOCK nonzero,
207 reap at least one child, waiting for it to die if necessary. If ERR is
208 nonzero, print an error message first. */
210 void
211 reap_children (block, err)
212 int block, err;
214 WAIT_T status;
216 while ((children != 0 || shell_function_pid != 0) &&
217 (block || dead_children > 0))
219 int remote = 0;
220 register int pid;
221 int exit_code, exit_sig, coredump;
222 register struct child *lastc, *c;
223 int child_failed;
224 int any_remote, any_local;
226 if (err && dead_children == 0)
228 /* We might block for a while, so let the user know why. */
229 fflush (stdout);
230 error ("*** Waiting for unfinished jobs....");
233 /* We have one less dead child to reap.
234 The test and decrement are not atomic; if it is compiled into:
235 register = dead_children - 1;
236 dead_children = register;
237 a SIGCHLD could come between the two instructions.
238 child_handler increments dead_children.
239 The second instruction here would lose that increment. But the
240 only effect of dead_children being wrong is that we might wait
241 longer than necessary to reap a child, and lose some parallelism;
242 and we might print the "Waiting for unfinished jobs" message above
243 when not necessary. */
245 if (dead_children != 0)
246 --dead_children;
248 any_remote = 0;
249 any_local = shell_function_pid != -1;
250 for (c = children; c != 0; c = c->next)
252 any_remote |= c->remote;
253 any_local |= ! c->remote;
254 if (debug_flag)
255 printf ("Live child 0x%08lx PID %d%s\n",
256 (unsigned long int) c,
257 c->pid, c->remote ? " (remote)" : "");
260 /* First, check for remote children. */
261 if (any_remote)
262 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
263 else
264 pid = 0;
265 if (pid < 0)
267 remote_status_lose:
268 #ifdef EINTR
269 if (errno == EINTR)
270 continue;
271 #endif
272 pfatal_with_name ("remote_status");
274 else if (pid == 0)
276 #ifndef __MSDOS__
277 /* No remote children. Check for local children. */
279 if (any_local)
281 #ifdef WAIT_NOHANG
282 if (!block)
283 pid = WAIT_NOHANG (&status);
284 else
285 #endif
286 pid = wait (&status);
288 else
289 pid = 0;
291 if (pid < 0)
293 #ifdef EINTR
294 if (errno == EINTR)
295 continue;
296 #endif
297 pfatal_with_name ("wait");
299 else if (pid == 0)
301 /* No local children. */
302 if (block && any_remote)
304 /* Now try a blocking wait for a remote child. */
305 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
306 if (pid < 0)
307 goto remote_status_lose;
308 else if (pid == 0)
309 /* No remote children either. Finally give up. */
310 break;
311 else
312 /* We got a remote child. */
313 remote = 1;
315 else
316 break;
318 else
320 /* Chop the status word up. */
321 exit_code = WEXITSTATUS (status);
322 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
323 coredump = WCOREDUMP (status);
325 #else /* MSDOS. */
326 /* Life is very different on MSDOS. */
327 pid = dos_pid - 1;
328 status = dos_status;
329 exit_code = dos_status;
330 exit_sig = 0;
331 coredump = 0;
332 #endif /* Not MSDOS. */
334 else
335 /* We got a remote child. */
336 remote = 1;
338 /* Check if this is the child of the `shell' function. */
339 if (!remote && pid == shell_function_pid)
341 /* It is. Leave an indicator for the `shell' function. */
342 if (exit_sig == 0 && exit_code == 127)
343 shell_function_completed = -1;
344 else
345 shell_function_completed = 1;
346 break;
349 child_failed = exit_sig != 0 || exit_code != 0;
351 /* Search for a child matching the deceased one. */
352 lastc = 0;
353 for (c = children; c != 0; lastc = c, c = c->next)
354 if (c->remote == remote && c->pid == pid)
355 break;
357 if (c == 0)
359 /* An unknown child died. */
360 char buf[100];
361 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
362 if (child_failed)
363 child_error (buf, exit_code, exit_sig, coredump,
364 ignore_errors_flag);
365 else
366 error ("%s finished.", buf);
368 else
370 if (debug_flag)
371 printf ("Reaping %s child 0x%08lx PID %d%s\n",
372 child_failed ? "losing" : "winning",
373 (unsigned long int) c,
374 c->pid, c->remote ? " (remote)" : "");
376 /* If this child had the good stdin, say it is now free. */
377 if (c->good_stdin)
378 good_stdin_used = 0;
380 if (child_failed && !c->noerror && !ignore_errors_flag)
382 /* The commands failed. Write an error message,
383 delete non-precious targets, and abort. */
384 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
385 c->file->update_status = 1;
386 if (exit_sig != 0)
387 delete_child_targets (c);
389 else
391 if (child_failed)
393 /* The commands failed, but we don't care. */
394 child_error (c->file->name,
395 exit_code, exit_sig, coredump, 1);
396 child_failed = 0;
399 /* If there are more commands to run, try to start them. */
400 if (job_next_command (c))
402 if (handling_fatal_signal)
404 /* Never start new commands while we are dying.
405 Since there are more commands that wanted to be run,
406 the target was not completely remade. So we treat
407 this as if a command had failed. */
408 c->file->command_state = cs_finished;
409 c->file->update_status = 1;
411 else
413 /* Check again whether to start remotely.
414 Whether or not we want to changes over time.
415 Also, start_remote_job may need state set up
416 by start_remote_job_p. */
417 c->remote = start_remote_job_p ();
418 start_job_command (c);
422 switch (c->file->command_state)
424 case cs_running:
425 /* Successfully started. Loop to reap more children. */
426 continue;
428 case cs_finished:
429 if (c->file->update_status != 0)
430 /* We failed to start the commands. */
431 delete_child_targets (c);
432 break;
434 default:
435 error ("internal error: `%s' has bogus command_state \
436 %d in reap_children",
437 c->file->name, (int) c->file->command_state);
438 abort ();
439 break;
443 if (! handling_fatal_signal)
444 /* Notice if the target of the commands has been changed. */
445 notice_finished_file (c->file);
447 if (debug_flag)
448 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
449 (unsigned long int) c,
450 c->pid, c->remote ? " (remote)" : "");
452 /* Remove the child from the chain and free it. */
453 if (lastc == 0)
454 children = c->next;
455 else
456 lastc->next = c->next;
457 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
458 free_child (c);
460 /* There is now another slot open. */
461 --job_slots_used;
463 /* If the job failed, and the -k flag was not given, die,
464 unless we are already in the process of dying. */
465 if (!err && child_failed && !keep_going_flag)
466 die (2);
469 /* Only block for one child. */
470 block = 0;
474 /* Free the storage allocated for CHILD. */
476 static void
477 free_child (child)
478 register struct child *child;
480 if (child->command_lines != 0)
482 register unsigned int i;
483 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
484 free (child->command_lines[i]);
485 free ((char *) child->command_lines);
488 if (child->environment != 0)
490 register char **ep = child->environment;
491 while (*ep != 0)
492 free (*ep++);
493 free ((char *) child->environment);
496 free ((char *) child);
499 #ifdef POSIX
500 #ifdef __MSDOS__
501 void
502 unblock_sigs ()
504 return;
506 #else
507 extern sigset_t fatal_signal_set;
509 void
510 unblock_sigs ()
512 sigset_t empty;
513 sigemptyset (&empty);
514 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
516 #endif
517 #endif
519 /* Start a job to run the commands specified in CHILD.
520 CHILD is updated to reflect the commands and ID of the child process. */
522 static void
523 start_job_command (child)
524 register struct child *child;
526 static int bad_stdin = -1;
527 register char *p;
528 int flags = child->file->cmds->lines_flags[child->command_line - 1];
529 char **argv;
531 p = child->command_ptr;
532 child->noerror = flags & COMMANDS_NOERROR;
533 while (*p != '\0')
535 if (*p == '@')
536 flags |= COMMANDS_SILENT;
537 else if (*p == '+')
538 flags |= COMMANDS_RECURSE;
539 else if (*p == '-')
540 child->noerror = 1;
541 else if (!isblank (*p) && *p != '+')
542 break;
543 ++p;
546 /* If -q was given, just say that updating `failed'. The exit status of
547 1 tells the user that -q is saying `something to do'; the exit status
548 for a random error is 2. */
549 if (question_flag && !(flags & COMMANDS_RECURSE))
551 child->file->update_status = 1;
552 child->file->command_state = cs_finished;
553 return;
556 /* There may be some preceding whitespace left if there
557 was nothing but a backslash on the first line. */
558 p = next_token (p);
560 /* Figure out an argument list from this command line. */
563 char *end;
564 argv = construct_command_argv (p, &end, child->file);
565 if (end == NULL)
566 child->command_ptr = NULL;
567 else
569 *end++ = '\0';
570 child->command_ptr = end;
574 if (touch_flag && !(flags & COMMANDS_RECURSE))
576 /* Go on to the next command. It might be the recursive one.
577 We construct ARGV only to find the end of the command line. */
578 free (argv[0]);
579 free ((char *) argv);
580 argv = 0;
583 if (argv == 0)
585 /* This line has no commands. Go to the next. */
586 if (job_next_command (child))
587 start_job_command (child);
588 return;
591 /* Print out the command. */
593 if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
594 puts (p);
596 /* Tell update_goal_chain that a command has been started on behalf of
597 this target. It is important that this happens here and not in
598 reap_children (where we used to do it), because reap_children might be
599 reaping children from a different target. We want this increment to
600 guaranteedly indicate that a command was started for the dependency
601 chain (i.e., update_file recursion chain) we are processing. */
603 ++commands_started;
605 /* If -n was given, recurse to get the next line in the sequence. */
607 if (just_print_flag && !(flags & COMMANDS_RECURSE))
609 free (argv[0]);
610 free ((char *) argv);
611 if (job_next_command (child))
612 start_job_command (child);
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 child->file->command_state = 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 child->file->command_state = cs_finished;
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_finished:
779 notice_finished_file (c->file);
780 free_child (c);
781 break;
783 default:
784 error ("internal error: `%s' command_state == %d in new_job",
785 c->file->name, (int) c->file->command_state);
786 abort ();
787 break;
790 return 1;
793 /* Create a `struct child' for FILE and start its commands running. */
795 void
796 new_job (file)
797 register struct file *file;
799 register struct commands *cmds = file->cmds;
800 register struct child *c;
801 char **lines;
802 register unsigned int i;
804 /* Let any previously decided-upon jobs that are waiting
805 for the load to go down start before this new one. */
806 start_waiting_jobs ();
808 /* Reap any children that might have finished recently. */
809 reap_children (0, 0);
811 /* Chop the commands up into lines if they aren't already. */
812 chop_commands (cmds);
814 if (job_slots != 0)
815 /* Wait for a job slot to be freed up. */
816 while (job_slots_used == job_slots)
817 reap_children (1, 0);
819 /* Expand the command lines and store the results in LINES. */
820 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
821 for (i = 0; i < cmds->ncommand_lines; ++i)
823 /* Collapse backslash-newline combinations that are inside variable
824 or function references. These are left alone by the parser so
825 that they will appear in the echoing of commands (where they look
826 nice); and collapsed by construct_command_argv when it tokenizes.
827 But letting them survive inside function invocations loses because
828 we don't want the functions to see them as part of the text. */
830 char *in, *out, *ref;
832 /* IN points to where in the line we are scanning.
833 OUT points to where in the line we are writing.
834 When we collapse a backslash-newline combination,
835 IN gets ahead out OUT. */
837 in = out = cmds->command_lines[i];
838 while ((ref = index (in, '$')) != 0)
840 ++ref; /* Move past the $. */
842 if (out != in)
843 /* Copy the text between the end of the last chunk
844 we processed (where IN points) and the new chunk
845 we are about to process (where REF points). */
846 bcopy (in, out, ref - in);
848 /* Move both pointers past the boring stuff. */
849 out += ref - in;
850 in = ref;
852 if (*ref == '(' || *ref == '{')
854 char openparen = *ref;
855 char closeparen = openparen == '(' ? ')' : '}';
856 int count;
857 char *p;
859 *out++ = *in++; /* Copy OPENPAREN. */
860 /* IN now points past the opening paren or brace.
861 Count parens or braces until it is matched. */
862 count = 0;
863 while (*in != '\0')
865 if (*in == closeparen && --count < 0)
866 break;
867 else if (*in == '\\' && in[1] == '\n')
869 /* We have found a backslash-newline inside a
870 variable or function reference. Eat it and
871 any following whitespace. */
873 int quoted = 0;
874 for (p = in - 1; p > ref && *p == '\\'; --p)
875 quoted = !quoted;
877 if (quoted)
878 /* There were two or more backslashes, so this is
879 not really a continuation line. We don't collapse
880 the quoting backslashes here as is done in
881 collapse_continuations, because the line will
882 be collapsed again after expansion. */
883 *out++ = *in++;
884 else
886 /* Skip the backslash, newline and
887 any following whitespace. */
888 in = next_token (in + 2);
890 /* Discard any preceding whitespace that has
891 already been written to the output. */
892 while (out > ref && isblank (out[-1]))
893 --out;
895 /* Replace it all with a single space. */
896 *out++ = ' ';
899 else
901 if (*in == openparen)
902 ++count;
904 *out++ = *in++;
910 /* There are no more references in this line to worry about.
911 Copy the remaining uninteresting text to the output. */
912 if (out != in)
913 strcpy (out, in);
915 /* Finally, expand the line. */
916 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
917 file);
920 /* Start the command sequence, record it in a new
921 `struct child', and add that to the chain. */
923 c = (struct child *) xmalloc (sizeof (struct child));
924 c->file = file;
925 c->command_lines = lines;
926 c->command_line = 0;
927 c->command_ptr = 0;
928 c->environment = 0;
930 /* Fetch the first command line to be run. */
931 if (! job_next_command (c))
932 /* There were no commands! */
933 free_child (c);
934 else
936 /* The job is now primed. Start it running. */
937 start_waiting_job (c);
939 if (job_slots == 1)
940 /* Since there is only one job slot, make things run linearly.
941 Wait for the child to die, setting the state to `cs_finished'. */
942 while (file->command_state == cs_running)
943 reap_children (1, 0);
947 /* Move CHILD's pointers to the next command for it to execute.
948 Returns nonzero if there is another command. */
950 static int
951 job_next_command (child)
952 struct child *child;
954 if (child->command_ptr == 0 || *child->command_ptr == '\0')
956 /* There are no more lines in the expansion of this line. */
957 if (child->command_line == child->file->cmds->ncommand_lines)
959 /* There are no more lines to be expanded. */
960 child->command_ptr = 0;
961 child->file->command_state = cs_finished;
962 child->file->update_status = 0;
963 return 0;
965 else
966 /* Get the next line to run. */
967 child->command_ptr = child->command_lines[child->command_line++];
969 return 1;
972 static int
973 load_too_high ()
975 #ifdef __MSDOS__
976 return 1;
977 #else
978 extern int getloadavg ();
979 double load;
981 if (max_load_average < 0)
982 return 0;
984 make_access ();
985 if (getloadavg (&load, 1) != 1)
987 static int lossage = -1;
988 /* Complain only once for the same error. */
989 if (lossage == -1 || errno != lossage)
991 if (errno == 0)
992 /* An errno value of zero means getloadavg is just unsupported. */
993 error ("cannot enforce load limits on this operating system");
994 else
995 perror_with_name ("cannot enforce load limit: ", "getloadavg");
997 lossage = errno;
998 load = 0;
1000 user_access ();
1002 return load >= max_load_average;
1003 #endif
1006 /* Start jobs that are waiting for the load to be lower. */
1008 void
1009 start_waiting_jobs ()
1011 struct child *job;
1013 if (waiting_jobs == 0)
1014 return;
1018 /* Check for recently deceased descendants. */
1019 reap_children (0, 0);
1021 /* Take a job off the waiting list. */
1022 job = waiting_jobs;
1023 waiting_jobs = job->next;
1025 /* Try to start that job. We break out of the loop as soon
1026 as start_waiting_job puts one back on the waiting list. */
1027 } while (start_waiting_job (job) && waiting_jobs != 0);
1030 /* Replace the current process with one executing the command in ARGV.
1031 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1032 the environment of the new program. This function does not return. */
1034 void
1035 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1036 int stdin_fd, stdout_fd;
1037 char **argv, **envp;
1039 if (stdin_fd != 0)
1040 (void) dup2 (stdin_fd, 0);
1041 if (stdout_fd != 1)
1042 (void) dup2 (stdout_fd, 1);
1044 /* Free up file descriptors. */
1046 register int d;
1047 int max = getdtablesize ();
1048 for (d = 3; d < max; ++d)
1049 (void) close (d);
1052 /* Run the command. */
1053 exec_command (argv, envp);
1056 /* Search PATH for FILE.
1057 If successful, store the full pathname in PROGRAM and return 1.
1058 If not sucessful, return zero. */
1060 static int
1061 search_path (file, path, program)
1062 char *file, *path, *program;
1064 if (path == 0 || path[0] == '\0')
1065 path = default_path;
1067 if (
1068 #ifdef __MSDOS__
1069 strpbrk (file, "/\\:")
1070 #else
1071 index (file, '/')
1072 #endif
1073 != 0)
1075 strcpy (program, file);
1076 return 1;
1078 else
1080 unsigned int len;
1082 #ifdef HAVE_GETGROUPS
1083 #ifndef HAVE_UNISTD_H
1084 extern int getgroups ();
1085 #endif
1086 static int ngroups = -1;
1087 #ifdef NGROUPS_MAX
1088 static GETGROUPS_T groups[NGROUPS_MAX];
1089 #define ngroups_max NGROUPS_MAX
1090 #else
1091 static GETGROUPS_T *groups = 0;
1092 static int ngroups_max;
1093 if (groups == 0)
1095 ngroups_max = GET_NGROUPS_MAX;
1096 groups = (GETGROUPS_T *) malloc (ngroups_max * sizeof (GETGROUPS_T));
1098 #endif
1099 if (groups != 0 && ngroups == -1)
1100 ngroups = getgroups (ngroups_max, groups);
1101 #endif /* Have getgroups. */
1103 len = strlen (file) + 1;
1106 struct stat st;
1107 int perm;
1108 char *p;
1110 p = index (path, PATH_SEPARATOR_CHAR);
1111 if (p == 0)
1112 p = path + strlen (path);
1114 if (p == path)
1115 bcopy (file, program, len);
1116 else
1118 bcopy (path, program, p - path);
1119 program[p - path] = '/';
1120 bcopy (file, program + (p - path) + 1, len);
1123 if (safe_stat (program, &st) == 0
1124 && S_ISREG (st.st_mode))
1126 if (st.st_uid == geteuid ())
1127 perm = (st.st_mode & 0100);
1128 else if (st.st_gid == getegid ())
1129 perm = (st.st_mode & 0010);
1130 else
1132 #ifdef HAVE_GETGROUPS
1133 register int i;
1134 for (i = 0; i < ngroups; ++i)
1135 if (groups[i] == st.st_gid)
1136 break;
1137 if (i < ngroups)
1138 perm = (st.st_mode & 0010);
1139 else
1140 #endif /* Have getgroups. */
1141 perm = (st.st_mode & 0001);
1144 if (perm != 0)
1145 return 1;
1148 path = p + 1;
1149 } while (*path != '\0');
1152 return 0;
1155 /* Replace the current process with one running the command in ARGV,
1156 with environment ENVP. This function does not return. */
1158 void
1159 exec_command (argv, envp)
1160 char **argv, **envp;
1162 char *shell, *path;
1163 PATH_VAR (program);
1164 register char **ep;
1166 shell = path = 0;
1167 for (ep = envp; *ep != 0; ++ep)
1169 if (shell == 0 && !strncmp(*ep, "SHELL=", 6))
1170 shell = &(*ep)[6];
1171 else if (path == 0 && !strncmp(*ep, "PATH=", 5))
1172 path = &(*ep)[5];
1173 else if (path != 0 && shell != 0)
1174 break;
1177 /* Be the user, permanently. */
1178 child_access ();
1180 if (!search_path (argv[0], path, program))
1181 error ("%s: Command not found", argv[0]);
1182 else
1184 /* Run the program. */
1185 execve (program, argv, envp);
1187 if (errno == ENOEXEC)
1189 PATH_VAR (shell_program);
1190 char *shell_path;
1191 if (shell == 0)
1192 shell_path = default_shell;
1193 else
1195 if (search_path (shell, path, shell_program))
1196 shell_path = shell_program;
1197 else
1199 shell_path = 0;
1200 error ("%s: Shell program not found", shell);
1204 if (shell_path != 0)
1206 char **new_argv;
1207 int argc;
1209 argc = 1;
1210 while (argv[argc] != 0)
1211 ++argc;
1213 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1214 new_argv[0] = shell_path;
1215 new_argv[1] = program;
1216 while (argc > 0)
1218 new_argv[1 + argc] = argv[argc];
1219 --argc;
1222 execve (shell_path, new_argv, envp);
1223 perror_with_name ("execve: ", shell_path);
1226 else
1227 perror_with_name ("execve: ", program);
1230 _exit (127);
1233 /* Figure out the argument list necessary to run LINE as a command.
1234 Try to avoid using a shell. This routine handles only ' quoting.
1235 Starting quotes may be escaped with a backslash. If any of the
1236 characters in sh_chars[] is seen, or any of the builtin commands
1237 listed in sh_cmds[] is the first word of a line, the shell is used.
1239 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1240 If *RESTP is NULL, newlines will be ignored.
1242 SHELL is the shell to use, or nil to use the default shell.
1243 IFS is the value of $IFS, or nil (meaning the default). */
1245 static char **
1246 construct_command_argv_internal (line, restp, shell, ifs)
1247 char *line, **restp;
1248 char *shell, *ifs;
1250 #ifdef __MSDOS__
1251 static char sh_chars[] = "\"|<>";
1252 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1253 "copy", "ctty", "date", "del", "dir", "echo",
1254 "erase", "exit", "for", "goto", "if", "if", "md",
1255 "mkdir", "path", "pause", "prompt", "rem", "ren",
1256 "rename", "set", "shift", "time", "type",
1257 "ver", "verify", "vol", ":", 0 };
1258 #else
1259 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1260 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1261 "logout", "set", "umask", "wait", "while", "for",
1262 "case", "if", ":", ".", "break", "continue",
1263 "export", "read", "readonly", "shift", "times",
1264 "trap", "switch", 0 };
1265 #endif
1266 register int i;
1267 register char *p;
1268 register char *ap;
1269 char *end;
1270 int instring, word_has_equals, seen_nonequals;
1271 char **new_argv = 0;
1273 if (restp != NULL)
1274 *restp = NULL;
1276 /* Make sure not to bother processing an empty line. */
1277 while (isblank (*line))
1278 ++line;
1279 if (*line == '\0')
1280 return 0;
1282 /* See if it is safe to parse commands internally. */
1283 if (shell == 0)
1284 shell = default_shell;
1285 else if (strcmp (shell, default_shell))
1286 goto slow;
1288 if (ifs != 0)
1289 for (ap = ifs; *ap != '\0'; ++ap)
1290 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1291 goto slow;
1293 i = strlen (line) + 1;
1295 /* More than 1 arg per character is impossible. */
1296 new_argv = (char **) xmalloc (i * sizeof (char *));
1298 /* All the args can fit in a buffer as big as LINE is. */
1299 ap = new_argv[0] = (char *) xmalloc (i);
1300 end = ap + i;
1302 /* I is how many complete arguments have been found. */
1303 i = 0;
1304 instring = word_has_equals = seen_nonequals = 0;
1305 for (p = line; *p != '\0'; ++p)
1307 if (ap > end)
1308 abort ();
1310 if (instring)
1312 string_char:
1313 /* Inside a string, just copy any char except a closing quote
1314 or a backslash-newline combination. */
1315 if (*p == '\'')
1316 instring = 0;
1317 else if (*p == '\\' && p[1] == '\n')
1318 goto swallow_escaped_newline;
1319 else if (*p == '\n' && restp != NULL)
1321 /* End of the command line. */
1322 *restp = p;
1323 goto end_of_line;
1325 else
1326 *ap++ = *p;
1328 else if (index (sh_chars, *p) != 0)
1329 /* Not inside a string, but it's a special char. */
1330 goto slow;
1331 else
1332 /* Not a special char. */
1333 switch (*p)
1335 case '=':
1336 /* Equals is a special character in leading words before the
1337 first word with no equals sign in it. This is not the case
1338 with sh -k, but we never get here when using nonstandard
1339 shell flags. */
1340 if (! seen_nonequals)
1341 goto slow;
1342 word_has_equals = 1;
1343 *ap++ = '=';
1344 break;
1346 case '\\':
1347 /* Backslash-newline combinations are eaten. */
1348 if (p[1] == '\n')
1350 swallow_escaped_newline:
1352 /* Eat the backslash, the newline, and following whitespace,
1353 replacing it all with a single space. */
1354 p += 2;
1356 /* If there is a tab after a backslash-newline,
1357 remove it from the source line which will be echoed,
1358 since it was most likely used to line
1359 up the continued line with the previous one. */
1360 if (*p == '\t')
1361 strcpy (p, p + 1);
1363 if (instring)
1364 goto string_char;
1365 else
1367 if (ap != new_argv[i])
1368 /* Treat this as a space, ending the arg.
1369 But if it's at the beginning of the arg, it should
1370 just get eaten, rather than becoming an empty arg. */
1371 goto end_of_arg;
1372 else
1373 p = next_token (p) - 1;
1376 else if (p[1] != '\0')
1377 /* Copy and skip the following char. */
1378 *ap++ = *++p;
1379 break;
1381 case '\'':
1382 instring = 1;
1383 break;
1385 case '\n':
1386 if (restp != NULL)
1388 /* End of the command line. */
1389 *restp = p;
1390 goto end_of_line;
1392 else
1393 /* Newlines are not special. */
1394 *ap++ = '\n';
1395 break;
1397 case ' ':
1398 case '\t':
1399 end_of_arg:
1400 /* We have the end of an argument.
1401 Terminate the text of the argument. */
1402 *ap++ = '\0';
1403 new_argv[++i] = ap;
1405 /* Update SEEN_NONEQUALS, which tells us if every word
1406 heretofore has contained an `='. */
1407 seen_nonequals |= ! word_has_equals;
1408 if (word_has_equals && ! seen_nonequals)
1409 /* An `=' in a word before the first
1410 word without one is magical. */
1411 goto slow;
1412 word_has_equals = 0; /* Prepare for the next word. */
1414 /* If this argument is the command name,
1415 see if it is a built-in shell command.
1416 If so, have the shell handle it. */
1417 if (i == 1)
1419 register int j;
1420 for (j = 0; sh_cmds[j] != 0; ++j)
1421 if (streq (sh_cmds[j], new_argv[0]))
1422 goto slow;
1425 /* Ignore multiple whitespace chars. */
1426 p = next_token (p);
1427 /* Next iteration should examine the first nonwhite char. */
1428 --p;
1429 break;
1431 default:
1432 *ap++ = *p;
1433 break;
1436 end_of_line:
1438 if (instring)
1439 /* Let the shell deal with an unterminated quote. */
1440 goto slow;
1442 /* Terminate the last argument and the argument list. */
1444 *ap = '\0';
1445 if (new_argv[i][0] != '\0')
1446 ++i;
1447 new_argv[i] = 0;
1449 if (i == 1)
1451 register int j;
1452 for (j = 0; sh_cmds[j] != 0; ++j)
1453 if (streq (sh_cmds[j], new_argv[0]))
1454 goto slow;
1457 if (new_argv[0] == 0)
1458 /* Line was empty. */
1459 return 0;
1460 else
1461 return new_argv;
1463 slow:;
1464 /* We must use the shell. */
1466 if (new_argv != 0)
1468 /* Free the old argument list we were working on. */
1469 free (new_argv[0]);
1470 free (new_argv);
1473 #ifdef __MSDOS__
1475 FILE *batch;
1476 dos_batch_file = 1;
1477 if (dos_bname == 0)
1479 dos_bname = tempnam (".", "mk");
1480 for (i = 0; dos_bname[i] != '\0'; ++i)
1481 if (dos_bname[i] == '/')
1482 dos_bname[i] = '\\';
1483 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1484 strcpy (dos_bename, dos_bname);
1485 strcat (dos_bname, ".bat");
1486 strcat (dos_bename, ".err");
1488 batch = fopen(bename, "w"); /* Create a file. */
1489 if (batch != NULL)
1490 fclose (batch);
1491 batch = fopen (dos_bname, "w");
1492 fputs ("@echo off\n", batch);
1493 fputs (line, batch);
1494 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1495 fclose (batch);
1496 new_argv = (char **) xmalloc(2 * sizeof(char *));
1497 new_argv[0] = strdup (bname);
1498 new_argv[1] = 0;
1500 #else /* Not MSDOS. */
1502 /* SHELL may be a multi-word command. Construct a command line
1503 "SHELL -c LINE", with all special chars in LINE escaped.
1504 Then recurse, expanding this command line to get the final
1505 argument list. */
1507 unsigned int shell_len = strlen (shell);
1508 static char minus_c[] = " -c ";
1509 unsigned int line_len = strlen (line);
1511 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1512 + (line_len * 2) + 1);
1514 ap = new_line;
1515 bcopy (shell, ap, shell_len);
1516 ap += shell_len;
1517 bcopy (minus_c, ap, sizeof (minus_c) - 1);
1518 ap += sizeof (minus_c) - 1;
1519 for (p = line; *p != '\0'; ++p)
1521 if (restp != NULL && *p == '\n')
1523 *restp = p;
1524 break;
1526 else if (*p == '\\' && p[1] == '\n')
1528 /* Eat the backslash, the newline, and following whitespace,
1529 replacing it all with a single space (which is escaped
1530 from the shell). */
1531 p += 2;
1533 /* If there is a tab after a backslash-newline,
1534 remove it from the source line which will be echoed,
1535 since it was most likely used to line
1536 up the continued line with the previous one. */
1537 if (*p == '\t')
1538 strcpy (p, p + 1);
1540 p = next_token (p);
1541 --p;
1542 *ap++ = '\\';
1543 *ap++ = ' ';
1544 continue;
1547 if (*p == '\\' || *p == '\''
1548 || isspace (*p)
1549 || index (sh_chars, *p) != 0)
1550 *ap++ = '\\';
1551 *ap++ = *p;
1553 *ap = '\0';
1555 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
1556 (char *) 0, (char *) 0);
1558 #endif /* MSDOS. */
1560 return new_argv;
1563 /* Figure out the argument list necessary to run LINE as a command.
1564 Try to avoid using a shell. This routine handles only ' quoting.
1565 Starting quotes may be escaped with a backslash. If any of the
1566 characters in sh_chars[] is seen, or any of the builtin commands
1567 listed in sh_cmds[] is the first word of a line, the shell is used.
1569 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1570 If *RESTP is NULL, newlines will be ignored.
1572 FILE is the target whose commands these are. It is used for
1573 variable expansion for $(SHELL) and $(IFS). */
1575 char **
1576 construct_command_argv (line, restp, file)
1577 char *line, **restp;
1578 struct file *file;
1580 char *shell, *ifs;
1581 char **argv;
1584 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
1585 int save = warn_undefined_variables_flag;
1586 warn_undefined_variables_flag = 0;
1588 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
1589 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
1591 warn_undefined_variables_flag = save;
1594 argv = construct_command_argv_internal (line, restp, shell, ifs);
1596 free (shell);
1597 free (ifs);
1599 return argv;
1602 #ifndef HAVE_DUP2
1604 dup2 (old, new)
1605 int old, new;
1607 int fd;
1609 (void) close (new);
1610 fd = dup (old);
1611 if (fd != new)
1613 (void) close (fd);
1614 errno = EMFILE;
1615 return -1;
1618 return fd;
1620 #endif