Sat Jun 15 20:30:01 1996 Andreas Schwab <schwab@issan.informatik.uni-dortmund.de>
[make.git] / job.c
blobcc098108ae6864a077d102c7c45e27e3ab2fc735
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988, 89, 90, 91, 92, 93, 94, 95, 96
3 Free Software Foundation, Inc.
4 This file is part of GNU Make.
6 GNU Make is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Make is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Make; see the file COPYING. If not, write to
18 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
20 #include "make.h"
21 #include "job.h"
22 #include "filedef.h"
23 #include "commands.h"
24 #include "variable.h"
25 #include <assert.h>
27 /* Default shell to use. */
28 #ifdef WIN32
29 char *default_shell = "sh.exe";
30 int no_default_sh_exe = 1;
31 #else /* WIN32 */
32 #ifndef _AMIGA
33 char default_shell[] = "/bin/sh";
34 #else
35 char default_shell[] = "";
36 extern int MyExecute (char **);
37 #endif
38 #endif /* WIN32 */
40 #ifdef __MSDOS__
41 #include <process.h>
42 static int dos_pid = 123;
43 static int dos_status;
44 static char *dos_bname;
45 static char *dos_bename;
46 static int dos_batch_file;
47 #endif /* MSDOS. */
49 #ifdef _AMIGA
50 #include <proto/dos.h>
51 static int amiga_pid = 123;
52 static int amiga_status;
53 static char amiga_bname[32];
54 static int amiga_batch_file;
55 #endif /* Amiga. */
57 #ifdef VMS
58 #include <time.h>
59 #include <processes.h>
60 #include <starlet.h>
61 #include <lib$routines.h>
62 #endif
64 #ifdef WIN32
65 #include <windows.h>
66 #include <io.h>
67 #include <process.h>
68 #include "sub_proc.h"
69 #include "w32err.h"
70 #include "pathstuff.h"
72 /* this stuff used if no sh.exe is around */
73 static char *dos_bname;
74 static char *dos_bename;
75 static int dos_batch_file;
76 #endif /* WIN32 */
78 #ifdef HAVE_FCNTL_H
79 #include <fcntl.h>
80 #else
81 #include <sys/file.h>
82 #endif
84 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
85 #include <sys/wait.h>
86 #endif
88 #ifdef HAVE_WAITPID
89 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
90 #else /* Don't have waitpid. */
91 #ifdef HAVE_WAIT3
92 #ifndef wait3
93 extern int wait3 ();
94 #endif
95 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
96 #endif /* Have wait3. */
97 #endif /* Have waitpid. */
99 #if !defined (wait) && !defined (POSIX)
100 extern int wait ();
101 #endif
103 #ifndef HAVE_UNION_WAIT
105 #define WAIT_T int
107 #ifndef WTERMSIG
108 #define WTERMSIG(x) ((x) & 0x7f)
109 #endif
110 #ifndef WCOREDUMP
111 #define WCOREDUMP(x) ((x) & 0x80)
112 #endif
113 #ifndef WEXITSTATUS
114 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
115 #endif
116 #ifndef WIFSIGNALED
117 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
118 #endif
119 #ifndef WIFEXITED
120 #define WIFEXITED(x) (WTERMSIG (x) == 0)
121 #endif
123 #else /* Have `union wait'. */
125 #define WAIT_T union wait
126 #ifndef WTERMSIG
127 #define WTERMSIG(x) ((x).w_termsig)
128 #endif
129 #ifndef WCOREDUMP
130 #define WCOREDUMP(x) ((x).w_coredump)
131 #endif
132 #ifndef WEXITSTATUS
133 #define WEXITSTATUS(x) ((x).w_retcode)
134 #endif
135 #ifndef WIFSIGNALED
136 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
137 #endif
138 #ifndef WIFEXITED
139 #define WIFEXITED(x) (WTERMSIG(x) == 0)
140 #endif
142 #endif /* Don't have `union wait'. */
144 #ifdef VMS
145 static int vms_jobsefnmask=0;
146 #endif /* !VMS */
148 #ifndef HAVE_UNISTD_H
149 extern int dup2 ();
150 extern int execve ();
151 extern void _exit ();
152 #ifndef VMS
153 extern int geteuid ();
154 extern int getegid ();
155 extern int setgid ();
156 extern int getgid ();
157 #endif
158 #endif
160 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
162 extern int getloadavg PARAMS ((double loadavg[], int nelem));
163 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
164 int *is_remote, int *id_ptr, int *used_stdin));
165 extern int start_remote_job_p PARAMS ((void));
166 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
167 int *coredump_ptr, int block));
169 RETSIGTYPE child_handler PARAMS ((int));
170 static void free_child PARAMS ((struct child *));
171 static void start_job_command PARAMS ((struct child *child));
172 static int load_too_high PARAMS ((void));
173 static int job_next_command PARAMS ((struct child *));
174 static int start_waiting_job PARAMS ((struct child *));
175 #ifdef VMS
176 static void vmsWaitForChildren PARAMS ((int *));
177 #endif
179 /* Chain of all live (or recently deceased) children. */
181 struct child *children = 0;
183 /* Number of children currently running. */
185 unsigned int job_slots_used = 0;
187 /* Nonzero if the `good' standard input is in use. */
189 static int good_stdin_used = 0;
191 /* Chain of children waiting to run until the load average goes down. */
193 static struct child *waiting_jobs = 0;
195 #ifdef WIN32
197 * The macro which references this function is defined in make.h.
199 int w32_kill(int pid, int sig)
201 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
203 #endif /* WIN32 */
205 /* Write an error message describing the exit status given in
206 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
207 Append "(ignored)" if IGNORED is nonzero. */
209 static void
210 child_error (target_name, exit_code, exit_sig, coredump, ignored)
211 char *target_name;
212 int exit_code, exit_sig, coredump;
213 int ignored;
215 if (ignored && silent_flag)
216 return;
218 #ifdef VMS
219 if (!(exit_code & 1))
220 error("*** [%s] Error 0x%x%s", target_name, exit_code, ((ignored)? " (ignored)" : ""));
221 #else
222 if (exit_sig == 0)
223 error (ignored ? "[%s] Error %d (ignored)" :
224 "*** [%s] Error %d",
225 target_name, exit_code);
226 else
227 error ("*** [%s] %s%s",
228 target_name, strsignal (exit_sig),
229 coredump ? " (core dumped)" : "");
230 #endif /* VMS */
233 static unsigned int dead_children = 0;
235 #ifdef VMS
236 /* Wait for nchildren children to terminate */
237 static void
238 vmsWaitForChildren(int *status)
240 while (1)
242 if (!vms_jobsefnmask)
244 *status = 0;
245 return;
248 *status = sys$wflor (32, vms_jobsefnmask);
250 return;
252 #endif
255 /* Notice that a child died.
256 reap_children should be called when convenient. */
257 RETSIGTYPE
258 child_handler (sig)
259 int sig;
261 ++dead_children;
263 if (debug_flag)
264 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
267 extern int shell_function_pid, shell_function_completed;
269 /* Reap dead children, storing the returned status and the new command
270 state (`cs_finished') in the `file' member of the `struct child' for the
271 dead child, and removing the child from the chain. If BLOCK nonzero,
272 reap at least one child, waiting for it to die if necessary. If ERR is
273 nonzero, print an error message first. */
275 void
276 reap_children (block, err)
277 int block, err;
279 WAIT_T status;
281 while ((children != 0 || shell_function_pid != 0) &&
282 (block || dead_children > 0))
284 int remote = 0;
285 register int pid;
286 int exit_code, exit_sig, coredump;
287 register struct child *lastc, *c;
288 int child_failed;
289 int any_remote, any_local;
291 if (err && dead_children == 0)
293 /* We might block for a while, so let the user know why. */
294 fflush (stdout);
295 error ("*** Waiting for unfinished jobs....");
298 /* We have one less dead child to reap.
299 The test and decrement are not atomic; if it is compiled into:
300 register = dead_children - 1;
301 dead_children = register;
302 a SIGCHLD could come between the two instructions.
303 child_handler increments dead_children.
304 The second instruction here would lose that increment. But the
305 only effect of dead_children being wrong is that we might wait
306 longer than necessary to reap a child, and lose some parallelism;
307 and we might print the "Waiting for unfinished jobs" message above
308 when not necessary. */
310 if (dead_children > 0)
311 --dead_children;
313 any_remote = 0;
314 any_local = shell_function_pid != -1;
315 for (c = children; c != 0; c = c->next)
317 any_remote |= c->remote;
318 any_local |= ! c->remote;
319 if (debug_flag)
320 printf ("Live child 0x%08lx PID %d%s\n",
321 (unsigned long int) c,
322 c->pid, c->remote ? " (remote)" : "");
323 #ifdef VMS
324 break;
325 #endif
328 /* First, check for remote children. */
329 if (any_remote)
330 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
331 else
332 pid = 0;
334 if (pid < 0)
336 remote_status_lose:
337 #ifdef EINTR
338 if (errno == EINTR)
339 continue;
340 #endif
341 pfatal_with_name ("remote_status");
343 else if (pid == 0)
345 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WIN32)
346 /* No remote children. Check for local children. */
348 if (any_local)
350 #ifdef VMS
351 vmsWaitForChildren (&status);
352 pid = c->pid;
353 #else
354 #ifdef WAIT_NOHANG
355 if (!block)
356 pid = WAIT_NOHANG (&status);
357 else
358 #endif
359 pid = wait (&status);
360 #endif /* !VMS */
362 else
363 pid = 0;
365 if (pid < 0)
367 #ifdef EINTR
368 if (errno == EINTR)
369 continue;
370 #endif
371 pfatal_with_name ("wait");
373 else if (pid == 0)
375 /* No local children. */
376 if (block && any_remote)
378 /* Now try a blocking wait for a remote child. */
379 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
380 if (pid < 0)
381 goto remote_status_lose;
382 else if (pid == 0)
383 /* No remote children either. Finally give up. */
384 break;
385 else
386 /* We got a remote child. */
387 remote = 1;
389 else
390 break;
392 else
394 /* Chop the status word up. */
395 exit_code = WEXITSTATUS (status);
396 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
397 coredump = WCOREDUMP (status);
399 #else /* MSDOS, Amiga, WIN32. */
400 #ifdef __MSDOS__
401 /* Life is very different on MSDOS. */
402 pid = dos_pid - 1;
403 status = dos_status;
404 exit_code = dos_status;
405 exit_sig = 0;
406 coredump = 0;
407 #endif /* __MSDOS__ */
408 #ifdef _AMIGA
409 /* Same on Amiga */
410 pid = amiga_pid - 1;
411 status = amiga_status;
412 exit_code = amiga_status;
413 exit_sig = 0;
414 coredump = 0;
415 #endif /* _AMIGA */
416 #ifdef WIN32
418 HANDLE hPID;
419 int err;
421 /* wait for anything to finish */
422 if (hPID = process_wait_for_any()) {
424 /* was an error found on this process? */
425 err = process_last_err(hPID);
427 /* get exit data */
428 exit_code = process_exit_code(hPID);
430 if (err)
431 fprintf(stderr, "make (e=%d): %s",
432 exit_code, map_win32_error_to_string(exit_code));
434 exit_sig = process_signal(hPID);
436 /* cleanup process */
437 process_cleanup(hPID);
439 if (dos_batch_file) {
440 remove (dos_bname);
441 remove (dos_bename);
442 dos_batch_file = 0;
445 coredump = 0;
447 pid = (int) hPID;
449 #endif /* WIN32 */
450 #endif /* Not MSDOS. */
452 else
453 /* We got a remote child. */
454 remote = 1;
456 /* Check if this is the child of the `shell' function. */
457 if (!remote && pid == shell_function_pid)
459 /* It is. Leave an indicator for the `shell' function. */
460 if (exit_sig == 0 && exit_code == 127)
461 shell_function_completed = -1;
462 else
463 shell_function_completed = 1;
464 break;
467 child_failed = exit_sig != 0 || exit_code != 0;
469 /* Search for a child matching the deceased one. */
470 lastc = 0;
471 for (c = children; c != 0; lastc = c, c = c->next)
472 if (c->remote == remote && c->pid == pid)
473 break;
475 if (c == 0)
477 /* An unknown child died. */
478 char buf[100];
479 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
480 if (child_failed)
481 child_error (buf, exit_code, exit_sig, coredump,
482 ignore_errors_flag);
483 else
484 error ("%s finished.", buf);
486 else
488 if (debug_flag)
489 printf ("Reaping %s child 0x%08lx PID %d%s\n",
490 child_failed ? "losing" : "winning",
491 (unsigned long int) c,
492 c->pid, c->remote ? " (remote)" : "");
494 /* If this child had the good stdin, say it is now free. */
495 if (c->good_stdin)
496 good_stdin_used = 0;
498 if (child_failed && !c->noerror && !ignore_errors_flag)
500 /* The commands failed. Write an error message,
501 delete non-precious targets, and abort. */
502 static int delete_on_error = -1;
503 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
504 c->file->update_status = 2;
505 if (delete_on_error == -1)
507 struct file *f = lookup_file (".DELETE_ON_ERROR");
508 delete_on_error = f != 0 && f->is_target;
510 if (exit_sig != 0 || delete_on_error)
511 delete_child_targets (c);
513 else
515 if (child_failed)
517 /* The commands failed, but we don't care. */
518 child_error (c->file->name,
519 exit_code, exit_sig, coredump, 1);
520 child_failed = 0;
523 /* If there are more commands to run, try to start them. */
524 if (job_next_command (c))
526 if (handling_fatal_signal)
528 /* Never start new commands while we are dying.
529 Since there are more commands that wanted to be run,
530 the target was not completely remade. So we treat
531 this as if a command had failed. */
532 c->file->update_status = 2;
534 else
536 /* Check again whether to start remotely.
537 Whether or not we want to changes over time.
538 Also, start_remote_job may need state set up
539 by start_remote_job_p. */
540 c->remote = start_remote_job_p ();
541 start_job_command (c);
542 /* Fatal signals are left blocked in case we were
543 about to put that child on the chain. But it is
544 already there, so it is safe for a fatal signal to
545 arrive now; it will clean up this child's targets. */
546 unblock_sigs ();
547 if (c->file->command_state == cs_running)
548 /* We successfully started the new command.
549 Loop to reap more children. */
550 continue;
553 if (c->file->update_status != 0)
554 /* We failed to start the commands. */
555 delete_child_targets (c);
557 else
558 /* There are no more commands. We got through them all
559 without an unignored error. Now the target has been
560 successfully updated. */
561 c->file->update_status = 0;
564 /* When we get here, all the commands for C->file are finished
565 (or aborted) and C->file->update_status contains 0 or 2. But
566 C->file->command_state is still cs_running if all the commands
567 ran; notice_finish_file looks for cs_running to tell it that
568 it's interesting to check the file's modtime again now. */
570 if (! handling_fatal_signal)
571 /* Notice if the target of the commands has been changed.
572 This also propagates its values for command_state and
573 update_status to its also_make files. */
574 notice_finished_file (c->file);
576 if (debug_flag)
577 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
578 (unsigned long int) c,
579 c->pid, c->remote ? " (remote)" : "");
581 /* Remove the child from the chain and free it. */
582 if (lastc == 0)
583 children = c->next;
584 else
585 lastc->next = c->next;
586 if (! handling_fatal_signal) /* Avoid nonreentrancy. */
587 free_child (c);
589 /* There is now another slot open. */
590 if (job_slots_used > 0)
591 --job_slots_used;
593 /* If the job failed, and the -k flag was not given, die,
594 unless we are already in the process of dying. */
595 if (!err && child_failed && !keep_going_flag)
596 die (2);
599 /* Only block for one child. */
600 block = 0;
602 return;
605 /* Free the storage allocated for CHILD. */
607 static void
608 free_child (child)
609 register struct child *child;
611 if (child->command_lines != 0)
613 register unsigned int i;
614 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
615 free (child->command_lines[i]);
616 free ((char *) child->command_lines);
619 if (child->environment != 0)
621 register char **ep = child->environment;
622 while (*ep != 0)
623 free (*ep++);
624 free ((char *) child->environment);
627 free ((char *) child);
630 #ifdef POSIX
631 #ifdef __MSDOS__
632 void
633 unblock_sigs ()
635 return;
637 #else
638 extern sigset_t fatal_signal_set;
640 void
641 unblock_sigs ()
643 sigset_t empty;
644 sigemptyset (&empty);
645 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
647 #endif
648 #endif
650 /* Start a job to run the commands specified in CHILD.
651 CHILD is updated to reflect the commands and ID of the child process.
653 NOTE: On return fatal signals are blocked! The caller is responsible
654 for calling `unblock_sigs', once the new child is safely on the chain so
655 it can be cleaned up in the event of a fatal signal. */
657 static void
658 start_job_command (child)
659 register struct child *child;
661 #ifndef _AMIGA
662 static int bad_stdin = -1;
663 #endif
664 register char *p;
665 int flags;
666 #ifdef VMS
667 char *argv;
668 #else
669 char **argv;
670 #endif
672 /* Combine the flags parsed for the line itself with
673 the flags specified globally for this target. */
674 flags = (child->file->command_flags
675 | child->file->cmds->lines_flags[child->command_line - 1]);
677 p = child->command_ptr;
678 child->noerror = flags & COMMANDS_NOERROR;
680 while (*p != '\0')
682 if (*p == '@')
683 flags |= COMMANDS_SILENT;
684 else if (*p == '+')
685 flags |= COMMANDS_RECURSE;
686 else if (*p == '-')
687 child->noerror = 1;
688 else if (!isblank (*p) && *p != '+')
689 break;
690 ++p;
693 /* If -q was given, just say that updating `failed'. The exit status of
694 1 tells the user that -q is saying `something to do'; the exit status
695 for a random error is 2. */
696 if (question_flag && !(flags & COMMANDS_RECURSE))
698 child->file->update_status = 1;
699 notice_finished_file (child->file);
700 return;
703 /* There may be some preceding whitespace left if there
704 was nothing but a backslash on the first line. */
705 p = next_token (p);
707 /* Figure out an argument list from this command line. */
710 char *end = 0;
711 #ifdef VMS
712 argv = p;
713 #else
714 argv = construct_command_argv (p, &end, child->file);
715 #endif
716 if (end == NULL)
717 child->command_ptr = NULL;
718 else
720 *end++ = '\0';
721 child->command_ptr = end;
725 if (touch_flag && !(flags & COMMANDS_RECURSE))
727 /* Go on to the next command. It might be the recursive one.
728 We construct ARGV only to find the end of the command line. */
729 #ifndef VMS
730 free (argv[0]);
731 free ((char *) argv);
732 #endif
733 argv = 0;
736 if (argv == 0)
738 next_command:
739 /* This line has no commands. Go to the next. */
740 if (job_next_command (child))
741 start_job_command (child);
742 else
744 /* No more commands. All done. */
745 child->file->update_status = 0;
746 notice_finished_file (child->file);
748 return;
751 /* Print out the command. If silent, we call `message' with null so it
752 can log the working directory before the command's own error messages
753 appear. */
755 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
756 ? "%s" : (char *) 0, p);
758 /* Tell update_goal_chain that a command has been started on behalf of
759 this target. It is important that this happens here and not in
760 reap_children (where we used to do it), because reap_children might be
761 reaping children from a different target. We want this increment to
762 guaranteedly indicate that a command was started for the dependency
763 chain (i.e., update_file recursion chain) we are processing. */
765 ++commands_started;
767 /* If -n was given, recurse to get the next line in the sequence. */
769 if (just_print_flag && !(flags & COMMANDS_RECURSE))
771 #ifndef VMS
772 free (argv[0]);
773 free ((char *) argv);
774 #endif
775 goto next_command;
778 /* Flush the output streams so they won't have things written twice. */
780 fflush (stdout);
781 fflush (stderr);
783 #ifndef WIN32
784 #ifndef _AMIGA
785 #ifndef VMS
787 /* Set up a bad standard input that reads from a broken pipe. */
789 if (bad_stdin == -1)
791 /* Make a file descriptor that is the read end of a broken pipe.
792 This will be used for some children's standard inputs. */
793 int pd[2];
794 if (pipe (pd) == 0)
796 /* Close the write side. */
797 (void) close (pd[1]);
798 /* Save the read side. */
799 bad_stdin = pd[0];
801 /* Set the descriptor to close on exec, so it does not litter any
802 child's descriptor table. When it is dup2'd onto descriptor 0,
803 that descriptor will not close on exec. */
804 #ifdef FD_SETFD
805 #ifndef FD_CLOEXEC
806 #define FD_CLOEXEC 1
807 #endif
808 (void) fcntl (bad_stdin, F_SETFD, FD_CLOEXEC);
809 #endif
813 #endif /* !AMIGA */
814 #endif /* !WIN32 */
816 /* Decide whether to give this child the `good' standard input
817 (one that points to the terminal or whatever), or the `bad' one
818 that points to the read side of a broken pipe. */
820 child->good_stdin = !good_stdin_used;
821 if (child->good_stdin)
822 good_stdin_used = 1;
824 #endif /* Not VMS */
826 child->deleted = 0;
828 #ifndef _AMIGA
829 /* Set up the environment for the child. */
830 if (child->environment == 0)
831 child->environment = target_environment (child->file);
832 #endif
834 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WIN32)
836 #ifndef VMS
837 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
838 if (child->remote)
840 int is_remote, id, used_stdin;
841 if (start_remote_job (argv, child->environment,
842 child->good_stdin ? 0 : bad_stdin,
843 &is_remote, &id, &used_stdin))
844 goto error;
845 else
847 if (child->good_stdin && !used_stdin)
849 child->good_stdin = 0;
850 good_stdin_used = 0;
852 child->remote = is_remote;
853 child->pid = id;
856 else
857 #endif /* !VMS */
859 /* Fork the child process. */
861 char **parent_environ;
863 #ifdef POSIX
864 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
865 #else
866 #ifdef HAVE_SIGSETMASK
867 (void) sigblock (fatal_signal_mask);
868 #endif
869 #endif
871 child->remote = 0;
873 #ifdef VMS
875 if (!child_execute_job (argv, child)) {
876 /* Fork failed! */
877 perror_with_name ("vfork", "");
878 goto error;
881 #else
883 parent_environ = environ;
884 child->pid = vfork ();
885 environ = parent_environ; /* Restore value child may have clobbered. */
886 if (child->pid == 0)
888 /* We are the child side. */
889 unblock_sigs ();
890 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
891 argv, child->environment);
893 else if (child->pid < 0)
895 /* Fork failed! */
896 unblock_sigs ();
897 perror_with_name ("vfork", "");
898 goto error;
900 #endif /* !VMS */
903 #else /* MSDOS or Amiga. */
904 #ifdef __MSDOS__
905 dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
906 ++dead_children;
907 child->pid = dos_pid++;
908 if (dos_batch_file)
910 dos_batch_file = 0;
911 remove (dos_bname); /* Ignore errors. */
912 if (access (dos_bename, 0))
913 dos_status = 1;
914 else
915 dos_status = 0;
916 remove (dos_bename);
918 #endif /* __MSDOS__ */
919 #ifdef _AMIGA
920 amiga_status = MyExecute (argv);
922 ++dead_children;
923 child->pid = amiga_pid++;
924 if (amiga_batch_file)
926 amiga_batch_file = 0;
927 DeleteFile (amiga_bname); /* Ignore errors. */
929 #endif /* Not Amiga */
930 #ifdef WIN32
932 HANDLE hPID;
933 char* arg0;
935 /* make UNC paths safe for CreateProcess -- backslash format */
936 arg0 = argv[0];
937 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
938 for ( ; arg0 && *arg0; arg0++)
939 if (*arg0 == '/')
940 *arg0 = '\\';
942 /* make sure CreateProcess() has Path it needs */
943 sync_Path_environment();
945 hPID = process_easy(argv, child->environment);
947 if (hPID != INVALID_HANDLE_VALUE)
948 child->pid = (int) hPID;
949 else {
950 int i;
951 unblock_sigs();
952 fprintf(stderr,
953 "process_easy() failed failed to launch process (e=%d)\n",
954 process_last_err(hPID));
955 for (i = 0; argv[i]; i++)
956 fprintf(stderr, "%s ", argv[i]);
957 fprintf(stderr, "\nCounted %d args in failed launch\n", i);
960 #endif /* WIN32 */
961 #endif /* Not MSDOS. */
963 /* We are the parent side. Set the state to
964 say the commands are running and return. */
966 set_command_state (child->file, cs_running);
968 /* Free the storage used by the child's argument list. */
969 #ifndef VMS
970 free (argv[0]);
971 free ((char *) argv);
972 #endif
974 return;
976 error:
977 child->file->update_status = 2;
978 notice_finished_file (child->file);
979 return;
982 /* Try to start a child running.
983 Returns nonzero if the child was started (and maybe finished), or zero if
984 the load was too high and the child was put on the `waiting_jobs' chain. */
986 static int
987 start_waiting_job (c)
988 struct child *c;
990 /* If we can start a job remotely, we always want to, and don't care about
991 the local load average. We record that the job should be started
992 remotely in C->remote for start_job_command to test. */
994 c->remote = start_remote_job_p ();
996 /* If this job is to be started locally, and we are already running
997 some jobs, make this one wait if the load average is too high. */
998 if (!c->remote && job_slots_used > 0 && load_too_high ())
1000 /* Put this child on the chain of children waiting
1001 for the load average to go down. */
1002 set_command_state (c->file, cs_running);
1003 c->next = waiting_jobs;
1004 waiting_jobs = c;
1005 return 0;
1008 /* Start the first command; reap_children will run later command lines. */
1009 start_job_command (c);
1011 switch (c->file->command_state)
1013 case cs_running:
1014 c->next = children;
1015 if (debug_flag)
1016 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
1017 (unsigned long int) c,
1018 c->pid, c->remote ? " (remote)" : "");
1019 children = c;
1020 /* One more job slot is in use. */
1021 ++job_slots_used;
1022 unblock_sigs ();
1023 break;
1025 case cs_not_started:
1026 /* All the command lines turned out to be empty. */
1027 c->file->update_status = 0;
1028 /* FALLTHROUGH */
1030 case cs_finished:
1031 notice_finished_file (c->file);
1032 free_child (c);
1033 break;
1035 default:
1036 assert (c->file->command_state == cs_finished);
1037 break;
1040 return 1;
1043 /* Create a `struct child' for FILE and start its commands running. */
1045 void
1046 new_job (file)
1047 register struct file *file;
1049 register struct commands *cmds = file->cmds;
1050 register struct child *c;
1051 char **lines;
1052 register unsigned int i;
1054 /* Let any previously decided-upon jobs that are waiting
1055 for the load to go down start before this new one. */
1056 start_waiting_jobs ();
1058 /* Reap any children that might have finished recently. */
1059 reap_children (0, 0);
1061 /* Chop the commands up into lines if they aren't already. */
1062 chop_commands (cmds);
1064 if (job_slots != 0)
1065 /* Wait for a job slot to be freed up. */
1066 while (job_slots_used == job_slots)
1067 reap_children (1, 0);
1069 /* Expand the command lines and store the results in LINES. */
1070 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1071 for (i = 0; i < cmds->ncommand_lines; ++i)
1073 /* Collapse backslash-newline combinations that are inside variable
1074 or function references. These are left alone by the parser so
1075 that they will appear in the echoing of commands (where they look
1076 nice); and collapsed by construct_command_argv when it tokenizes.
1077 But letting them survive inside function invocations loses because
1078 we don't want the functions to see them as part of the text. */
1080 char *in, *out, *ref;
1082 /* IN points to where in the line we are scanning.
1083 OUT points to where in the line we are writing.
1084 When we collapse a backslash-newline combination,
1085 IN gets ahead out OUT. */
1087 in = out = cmds->command_lines[i];
1088 while ((ref = index (in, '$')) != 0)
1090 ++ref; /* Move past the $. */
1092 if (out != in)
1093 /* Copy the text between the end of the last chunk
1094 we processed (where IN points) and the new chunk
1095 we are about to process (where REF points). */
1096 bcopy (in, out, ref - in);
1098 /* Move both pointers past the boring stuff. */
1099 out += ref - in;
1100 in = ref;
1102 if (*ref == '(' || *ref == '{')
1104 char openparen = *ref;
1105 char closeparen = openparen == '(' ? ')' : '}';
1106 int count;
1107 char *p;
1109 *out++ = *in++; /* Copy OPENPAREN. */
1110 /* IN now points past the opening paren or brace.
1111 Count parens or braces until it is matched. */
1112 count = 0;
1113 while (*in != '\0')
1115 if (*in == closeparen && --count < 0)
1116 break;
1117 else if (*in == '\\' && in[1] == '\n')
1119 /* We have found a backslash-newline inside a
1120 variable or function reference. Eat it and
1121 any following whitespace. */
1123 int quoted = 0;
1124 for (p = in - 1; p > ref && *p == '\\'; --p)
1125 quoted = !quoted;
1127 if (quoted)
1128 /* There were two or more backslashes, so this is
1129 not really a continuation line. We don't collapse
1130 the quoting backslashes here as is done in
1131 collapse_continuations, because the line will
1132 be collapsed again after expansion. */
1133 *out++ = *in++;
1134 else
1136 /* Skip the backslash, newline and
1137 any following whitespace. */
1138 in = next_token (in + 2);
1140 /* Discard any preceding whitespace that has
1141 already been written to the output. */
1142 while (out > ref && isblank (out[-1]))
1143 --out;
1145 /* Replace it all with a single space. */
1146 *out++ = ' ';
1149 else
1151 if (*in == openparen)
1152 ++count;
1154 *out++ = *in++;
1160 /* There are no more references in this line to worry about.
1161 Copy the remaining uninteresting text to the output. */
1162 if (out != in)
1163 strcpy (out, in);
1165 /* Finally, expand the line. */
1166 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1167 file);
1170 /* Start the command sequence, record it in a new
1171 `struct child', and add that to the chain. */
1173 c = (struct child *) xmalloc (sizeof (struct child));
1174 c->file = file;
1175 c->command_lines = lines;
1176 c->command_line = 0;
1177 c->command_ptr = 0;
1178 c->environment = 0;
1180 /* Fetch the first command line to be run. */
1181 job_next_command (c);
1183 /* The job is now primed. Start it running.
1184 (This will notice if there are in fact no commands.) */
1185 (void)start_waiting_job (c);
1187 if (job_slots == 1)
1188 /* Since there is only one job slot, make things run linearly.
1189 Wait for the child to die, setting the state to `cs_finished'. */
1190 while (file->command_state == cs_running)
1191 reap_children (1, 0);
1193 return;
1196 /* Move CHILD's pointers to the next command for it to execute.
1197 Returns nonzero if there is another command. */
1199 static int
1200 job_next_command (child)
1201 struct child *child;
1203 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1205 /* There are no more lines in the expansion of this line. */
1206 if (child->command_line == child->file->cmds->ncommand_lines)
1208 /* There are no more lines to be expanded. */
1209 child->command_ptr = 0;
1210 return 0;
1212 else
1213 /* Get the next line to run. */
1214 child->command_ptr = child->command_lines[child->command_line++];
1216 return 1;
1219 static int
1220 load_too_high ()
1222 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1223 return 1;
1224 #else
1225 double load;
1227 if (max_load_average < 0)
1228 return 0;
1230 make_access ();
1231 if (getloadavg (&load, 1) != 1)
1233 static int lossage = -1;
1234 /* Complain only once for the same error. */
1235 if (lossage == -1 || errno != lossage)
1237 if (errno == 0)
1238 /* An errno value of zero means getloadavg is just unsupported. */
1239 error ("cannot enforce load limits on this operating system");
1240 else
1241 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1243 lossage = errno;
1244 load = 0;
1246 user_access ();
1248 return load >= max_load_average;
1249 #endif
1252 /* Start jobs that are waiting for the load to be lower. */
1254 void
1255 start_waiting_jobs ()
1257 struct child *job;
1259 if (waiting_jobs == 0)
1260 return;
1264 /* Check for recently deceased descendants. */
1265 reap_children (0, 0);
1267 /* Take a job off the waiting list. */
1268 job = waiting_jobs;
1269 waiting_jobs = job->next;
1271 /* Try to start that job. We break out of the loop as soon
1272 as start_waiting_job puts one back on the waiting list. */
1274 while (start_waiting_job (job) && waiting_jobs != 0);
1276 return;
1279 #ifndef WIN32
1280 #ifdef VMS
1281 #include <descrip.h>
1282 #include <clidef.h>
1284 /* This is called as an AST when a child process dies (it won't get
1285 interrupted by anything except a higher level AST).
1287 int vmsHandleChildTerm(struct child *child)
1289 int status;
1290 register struct child *lastc, *c;
1291 int child_failed;
1293 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1295 lib$free_ef(&child->efn);
1297 (void) sigblock (fatal_signal_mask);
1299 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1301 /* Search for a child matching the deceased one. */
1302 lastc = 0;
1303 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1304 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1305 #else
1306 c = child;
1307 #endif
1309 if (child_failed && !c->noerror && !ignore_errors_flag)
1311 /* The commands failed. Write an error message,
1312 delete non-precious targets, and abort. */
1313 child_error (c->file->name, c->cstatus, 0, 0, 0);
1314 c->file->update_status = 1;
1315 delete_child_targets (c);
1317 else
1319 if (child_failed)
1321 /* The commands failed, but we don't care. */
1322 child_error (c->file->name, c->cstatus, 0, 0, 1);
1323 child_failed = 0;
1326 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1327 /* If there are more commands to run, try to start them. */
1328 start_job (c);
1330 switch (c->file->command_state)
1332 case cs_running:
1333 /* Successfully started. */
1334 break;
1336 case cs_finished:
1337 if (c->file->update_status != 0) {
1338 /* We failed to start the commands. */
1339 delete_child_targets (c);
1341 break;
1343 default:
1344 error ("internal error: `%s' command_state \
1345 %d in child_handler", c->file->name);
1346 abort ();
1347 break;
1349 #endif /* RECURSIVEJOBS */
1352 /* Set the state flag to say the commands have finished. */
1353 c->file->command_state = cs_finished;
1354 notice_finished_file (c->file);
1356 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1357 /* Remove the child from the chain and free it. */
1358 if (lastc == 0)
1359 children = c->next;
1360 else
1361 lastc->next = c->next;
1362 free_child (c);
1363 #endif /* RECURSIVEJOBS */
1365 /* There is now another slot open. */
1366 if (job_slots_used > 0)
1367 --job_slots_used;
1369 /* If the job failed, and the -k flag was not given, die. */
1370 if (child_failed && !keep_going_flag)
1371 die (EXIT_FAILURE);
1373 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1375 return 1;
1378 /* VMS:
1379 Spawn a process executing the command in ARGV and return its pid. */
1381 #define MAXCMDLEN 200
1384 child_execute_job (argv, child)
1385 char *argv;
1386 struct child *child;
1388 int i;
1389 static struct dsc$descriptor_s cmddsc;
1390 #ifndef DONTWAITFORCHILD
1391 int spflags = 0;
1392 #else
1393 int spflags = CLI$M_NOWAIT;
1394 #endif
1395 int status;
1396 char cmd[4096],*p,*c;
1397 char comname[50];
1399 /* Remove backslashes */
1400 for (p = argv, c = cmd; *p; p++,c++)
1402 if (*p == '\\') p++;
1403 *c = *p;
1405 *c = *p;
1407 /* check for maximum dcl length and create *.com file if neccesary */
1409 comname[0] = '\0';
1411 if (strlen (cmd) > MAXCMDLEN)
1413 FILE *outfile;
1414 char tmp;
1416 strcpy (comname, "sys$scratch:CMDXXXXXX.COM");
1417 (void) mktemp (comname);
1419 outfile = fopen (comname, "w");
1420 if (outfile == 0)
1421 pfatal_with_name (comname);
1423 fprintf (outfile, "$ ");
1424 c = cmd;
1426 while (c)
1428 p = strchr (c, ',');
1429 if ((p == NULL) || (p-c > MAXCMDLEN))
1430 p = strchr (c, ' ');
1431 if (p != NULL)
1433 p++;
1434 tmp = *p;
1435 *p = '\0';
1437 else
1438 tmp = '\0';
1439 fprintf (outfile, "%s%s\n", c, (tmp == '\0')?"":" -");
1440 if (p != NULL)
1441 *p = tmp;
1442 c = p;
1445 fclose (outfile);
1447 sprintf (cmd, "$ @%s", comname);
1449 if (debug_flag)
1450 printf ("Executing %s instead\n", cmd);
1453 cmddsc.dsc$w_length = strlen(cmd);
1454 cmddsc.dsc$a_pointer = cmd;
1455 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
1456 cmddsc.dsc$b_class = DSC$K_CLASS_S;
1458 child->efn = 0;
1459 while (child->efn < 32 || child->efn > 63)
1461 status = lib$get_ef(&child->efn);
1462 if (!(status & 1))
1463 return 0;
1466 sys$clref(child->efn);
1468 vms_jobsefnmask |= (1 << (child->efn - 32));
1470 #ifndef DONTWAITFORCHILD
1471 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1472 &child->efn,0,0);
1473 vmsHandleChildTerm(child);
1474 #else
1475 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1476 &child->efn,vmsHandleChildTerm,child);
1477 #endif
1479 if (!(status & 1))
1481 printf("Error spawning, %d\n",status);
1482 fflush(stdout);
1485 unlink (comname);
1487 return (status & 1);
1490 #else /* !VMS */
1492 #ifndef _AMIGA
1493 /* UNIX:
1494 Replace the current process with one executing the command in ARGV.
1495 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1496 the environment of the new program. This function does not return. */
1498 void
1499 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1500 int stdin_fd, stdout_fd;
1501 char **argv, **envp;
1503 if (stdin_fd != 0)
1504 (void) dup2 (stdin_fd, 0);
1505 if (stdout_fd != 1)
1506 (void) dup2 (stdout_fd, 1);
1507 if (stdin_fd != 0)
1508 (void) close (stdin_fd);
1509 if (stdout_fd != 1)
1510 (void) close (stdout_fd);
1512 /* Run the command. */
1513 exec_command (argv, envp);
1515 #endif /* !AMIGA */
1516 #endif /* !VMS */
1517 #endif /* !WIN32 */
1519 #ifndef _AMIGA
1520 /* Replace the current process with one running the command in ARGV,
1521 with environment ENVP. This function does not return. */
1523 void
1524 exec_command (argv, envp)
1525 char **argv, **envp;
1527 #ifdef VMS
1528 /* Run the program. */
1529 execve (argv[0], argv, envp);
1530 perror_with_name ("execve: ", argv[0]);
1531 _exit (EXIT_FAILURE);
1532 #else
1533 /* Be the user, permanently. */
1534 child_access ();
1536 /* Run the program. */
1537 environ = envp;
1538 execvp (argv[0], argv);
1540 switch (errno)
1542 case ENOENT:
1543 error ("%s: Command not found", argv[0]);
1544 break;
1545 case ENOEXEC:
1547 /* The file is not executable. Try it as a shell script. */
1548 extern char *getenv ();
1549 char *shell;
1550 char **new_argv;
1551 int argc;
1553 shell = getenv ("SHELL");
1554 if (shell == 0)
1555 shell = default_shell;
1557 argc = 1;
1558 while (argv[argc] != 0)
1559 ++argc;
1561 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1562 new_argv[0] = shell;
1563 new_argv[1] = argv[0];
1564 while (argc > 0)
1566 new_argv[1 + argc] = argv[argc];
1567 --argc;
1570 execvp (shell, new_argv);
1571 if (errno == ENOENT)
1572 error ("%s: Shell program not found", shell);
1573 else
1574 perror_with_name ("execvp: ", shell);
1575 break;
1578 default:
1579 perror_with_name ("execvp: ", argv[0]);
1580 break;
1583 _exit (127);
1584 #endif /* !VMS */
1586 #else /* On Amiga */
1587 void exec_command (argv)
1588 char **argv;
1590 MyExecute (argv);
1593 void clean_tmp (void)
1595 DeleteFile (amiga_bname);
1598 #endif /* An Amiga */
1600 #ifndef VMS
1601 /* Figure out the argument list necessary to run LINE as a command. Try to
1602 avoid using a shell. This routine handles only ' quoting, and " quoting
1603 when no backslash, $ or ` characters are seen in the quotes. Starting
1604 quotes may be escaped with a backslash. If any of the characters in
1605 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1606 is the first word of a line, the shell is used.
1608 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1609 If *RESTP is NULL, newlines will be ignored.
1611 SHELL is the shell to use, or nil to use the default shell.
1612 IFS is the value of $IFS, or nil (meaning the default). */
1614 static char **
1615 construct_command_argv_internal (line, restp, shell, ifs)
1616 char *line, **restp;
1617 char *shell, *ifs;
1619 #ifdef __MSDOS__
1620 static char sh_chars[] = "\"|<>";
1621 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1622 "copy", "ctty", "date", "del", "dir", "echo",
1623 "erase", "exit", "for", "goto", "if", "if", "md",
1624 "mkdir", "path", "pause", "prompt", "rem", "ren",
1625 "rename", "set", "shift", "time", "type",
1626 "ver", "verify", "vol", ":", 0 };
1627 #endif
1628 #ifdef _AMIGA
1629 static char sh_chars[] = "#;\"|<>()?*$`";
1630 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
1631 "rename", "set", "setenv", "date", "makedir",
1632 "skip", "else", "endif", "path", "prompt",
1633 "unset", "unsetenv", "version",
1634 0 };
1635 #else
1636 #ifdef WIN32
1637 static char sh_chars_dos[] = "\"|<>";
1638 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1639 "copy", "ctty", "date", "del", "dir", "echo",
1640 "erase", "exit", "for", "goto", "if", "if", "md",
1641 "mkdir", "path", "pause", "prompt", "rem", "ren",
1642 "rename", "set", "shift", "time", "type",
1643 "ver", "verify", "vol", ":", 0 };
1644 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1645 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
1646 "logout", "set", "umask", "wait", "while", "for",
1647 "case", "if", ":", ".", "break", "continue",
1648 "export", "read", "readonly", "shift", "times",
1649 "trap", "switch", "test", 0 };
1650 char* sh_chars;
1651 char** sh_cmds;
1652 #else /* WIN32 */
1653 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1654 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1655 "logout", "set", "umask", "wait", "while", "for",
1656 "case", "if", ":", ".", "break", "continue",
1657 "export", "read", "readonly", "shift", "times",
1658 "trap", "switch", 0 };
1659 #endif /* WIN32 */
1660 #endif
1661 register int i;
1662 register char *p;
1663 register char *ap;
1664 char *end;
1665 int instring, word_has_equals, seen_nonequals;
1666 char **new_argv = 0;
1667 #ifdef WIN32
1668 int slow_flag = 0;
1670 if (no_default_sh_exe) {
1671 sh_cmds = sh_cmds_dos;
1672 sh_chars = sh_chars_dos;
1673 } else {
1674 sh_cmds = sh_cmds_sh;
1675 sh_chars = sh_chars_sh;
1677 #endif
1679 if (restp != NULL)
1680 *restp = NULL;
1682 /* Make sure not to bother processing an empty line. */
1683 while (isblank (*line))
1684 ++line;
1685 if (*line == '\0')
1686 return 0;
1688 /* See if it is safe to parse commands internally. */
1689 if (shell == 0)
1690 shell = default_shell;
1691 else if (strcmp (shell, default_shell))
1692 #ifdef WIN32
1694 char *s1 = _fullpath(NULL, shell, 0);
1695 char *s2 = _fullpath(NULL, default_shell, 0);
1697 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
1699 if (s1);
1700 free(s1);
1701 if (s2);
1702 free(s2);
1704 if (slow_flag)
1705 #endif /* WIN32 */
1706 goto slow;
1708 if (ifs != 0)
1709 for (ap = ifs; *ap != '\0'; ++ap)
1710 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1711 goto slow;
1713 i = strlen (line) + 1;
1715 /* More than 1 arg per character is impossible. */
1716 new_argv = (char **) xmalloc (i * sizeof (char *));
1718 /* All the args can fit in a buffer as big as LINE is. */
1719 ap = new_argv[0] = (char *) xmalloc (i);
1720 end = ap + i;
1722 /* I is how many complete arguments have been found. */
1723 i = 0;
1724 instring = word_has_equals = seen_nonequals = 0;
1725 for (p = line; *p != '\0'; ++p)
1727 if (ap > end)
1728 abort ();
1730 if (instring)
1732 string_char:
1733 /* Inside a string, just copy any char except a closing quote
1734 or a backslash-newline combination. */
1735 if (*p == instring)
1736 instring = 0;
1737 else if (*p == '\\' && p[1] == '\n')
1738 goto swallow_escaped_newline;
1739 else if (*p == '\n' && restp != NULL)
1741 /* End of the command line. */
1742 *restp = p;
1743 goto end_of_line;
1745 /* Backslash, $, and ` are special inside double quotes.
1746 If we see any of those, punt. */
1747 else if (instring == '"' && index ("\\$`", *p) != 0)
1748 goto slow;
1749 else
1750 *ap++ = *p;
1752 else if (index (sh_chars, *p) != 0)
1753 /* Not inside a string, but it's a special char. */
1754 goto slow;
1755 else
1756 /* Not a special char. */
1757 switch (*p)
1759 case '=':
1760 /* Equals is a special character in leading words before the
1761 first word with no equals sign in it. This is not the case
1762 with sh -k, but we never get here when using nonstandard
1763 shell flags. */
1764 if (! seen_nonequals)
1765 goto slow;
1766 word_has_equals = 1;
1767 *ap++ = '=';
1768 break;
1770 case '\\':
1771 /* Backslash-newline combinations are eaten. */
1772 if (p[1] == '\n')
1774 swallow_escaped_newline:
1776 /* Eat the backslash, the newline, and following whitespace,
1777 replacing it all with a single space. */
1778 p += 2;
1780 /* If there is a tab after a backslash-newline,
1781 remove it from the source line which will be echoed,
1782 since it was most likely used to line
1783 up the continued line with the previous one. */
1784 if (*p == '\t')
1785 strcpy (p, p + 1);
1787 if (instring)
1788 goto string_char;
1789 else
1791 if (ap != new_argv[i])
1792 /* Treat this as a space, ending the arg.
1793 But if it's at the beginning of the arg, it should
1794 just get eaten, rather than becoming an empty arg. */
1795 goto end_of_arg;
1796 else
1797 p = next_token (p) - 1;
1800 else if (p[1] != '\0')
1801 /* Copy and skip the following char. */
1802 *ap++ = *++p;
1803 break;
1805 case '\'':
1806 case '"':
1807 instring = *p;
1808 break;
1810 case '\n':
1811 if (restp != NULL)
1813 /* End of the command line. */
1814 *restp = p;
1815 goto end_of_line;
1817 else
1818 /* Newlines are not special. */
1819 *ap++ = '\n';
1820 break;
1822 case ' ':
1823 case '\t':
1824 end_of_arg:
1825 /* We have the end of an argument.
1826 Terminate the text of the argument. */
1827 *ap++ = '\0';
1828 new_argv[++i] = ap;
1830 /* Update SEEN_NONEQUALS, which tells us if every word
1831 heretofore has contained an `='. */
1832 seen_nonequals |= ! word_has_equals;
1833 if (word_has_equals && ! seen_nonequals)
1834 /* An `=' in a word before the first
1835 word without one is magical. */
1836 goto slow;
1837 word_has_equals = 0; /* Prepare for the next word. */
1839 /* If this argument is the command name,
1840 see if it is a built-in shell command.
1841 If so, have the shell handle it. */
1842 if (i == 1)
1844 register int j;
1845 for (j = 0; sh_cmds[j] != 0; ++j)
1846 if (streq (sh_cmds[j], new_argv[0]))
1847 goto slow;
1850 /* Ignore multiple whitespace chars. */
1851 p = next_token (p);
1852 /* Next iteration should examine the first nonwhite char. */
1853 --p;
1854 break;
1856 default:
1857 *ap++ = *p;
1858 break;
1861 end_of_line:
1863 if (instring)
1864 /* Let the shell deal with an unterminated quote. */
1865 goto slow;
1867 /* Terminate the last argument and the argument list. */
1869 *ap = '\0';
1870 if (new_argv[i][0] != '\0')
1871 ++i;
1872 new_argv[i] = 0;
1874 if (i == 1)
1876 register int j;
1877 for (j = 0; sh_cmds[j] != 0; ++j)
1878 if (streq (sh_cmds[j], new_argv[0]))
1879 goto slow;
1882 if (new_argv[0] == 0)
1883 /* Line was empty. */
1884 return 0;
1885 else
1886 return new_argv;
1888 slow:;
1889 /* We must use the shell. */
1891 if (new_argv != 0)
1893 /* Free the old argument list we were working on. */
1894 free (new_argv[0]);
1895 free ((void *)new_argv);
1897 #ifdef WIN32
1899 * Not eating this whitespace caused things like
1901 * sh -c "\n"
1903 * which gave the shell fits. I think we have to eat
1904 * whitespace here, but this code should be considered
1905 * suspicious if things start failing....
1908 /* Make sure not to bother processing an empty line. */
1909 while (isspace (*line))
1910 ++line;
1911 if (*line == '\0')
1912 return 0;
1913 #endif
1915 #if defined(__MSDOS__) || defined(WIN32)
1916 #ifdef WIN32
1918 * only come here if no sh.exe command
1920 if (no_default_sh_exe)
1921 #endif
1923 FILE *batch;
1924 dos_batch_file = 1;
1925 if (dos_bname == 0)
1927 dos_bname = tempnam (".", "mk");
1928 for (i = 0; dos_bname[i] != '\0'; ++i)
1929 if (dos_bname[i] == '/')
1930 dos_bname[i] = '\\';
1931 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1932 strcpy (dos_bename, dos_bname);
1933 strcat (dos_bname, ".bat");
1934 strcat (dos_bename, ".err");
1936 batch = fopen (dos_bename, "w"); /* Create a file. */
1937 if (batch != NULL)
1938 fclose (batch);
1939 batch = fopen (dos_bname, "w");
1940 fputs ("@echo off\n", batch);
1941 fputs (line, batch);
1942 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1943 fclose (batch);
1944 new_argv = (char **) xmalloc(2 * sizeof(char *));
1945 new_argv[0] = strdup (dos_bname);
1946 new_argv[1] = 0;
1948 #endif /* MSDOS. */
1949 #ifdef _AMIGA
1951 char *ptr;
1952 char *buffer;
1953 char *dptr;
1955 buffer = (char *)xmalloc (strlen (line)+1);
1957 ptr = line;
1958 for (dptr=buffer; *ptr; )
1960 if (*ptr == '\\' && ptr[1] == '\n')
1961 ptr += 2;
1962 else if (*ptr == '@') /* Kludge: multiline commands */
1964 ptr += 2;
1965 *dptr++ = '\n';
1967 else
1968 *dptr++ = *ptr++;
1970 *dptr = 0;
1972 new_argv = (char **) xmalloc(2 * sizeof(char *));
1973 new_argv[0] = buffer;
1974 new_argv[1] = 0;
1976 #else /* Not MSDOS or Amiga */
1977 #ifdef WIN32
1979 * This is technically an else to the above 'if (no_default_sh_exe)',
1980 * but (IMHO) coding if-else across ifdef is dangerous.
1982 if (!no_default_sh_exe)
1983 #endif
1985 /* SHELL may be a multi-word command. Construct a command line
1986 "SHELL -c LINE", with all special chars in LINE escaped.
1987 Then recurse, expanding this command line to get the final
1988 argument list. */
1990 unsigned int shell_len = strlen (shell);
1991 static char minus_c[] = " -c ";
1992 unsigned int line_len = strlen (line);
1994 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
1995 + (line_len * 2) + 1);
1997 ap = new_line;
1998 bcopy (shell, ap, shell_len);
1999 ap += shell_len;
2000 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2001 ap += sizeof (minus_c) - 1;
2002 for (p = line; *p != '\0'; ++p)
2004 if (restp != NULL && *p == '\n')
2006 *restp = p;
2007 break;
2009 else if (*p == '\\' && p[1] == '\n')
2011 /* Eat the backslash, the newline, and following whitespace,
2012 replacing it all with a single space (which is escaped
2013 from the shell). */
2014 p += 2;
2016 /* If there is a tab after a backslash-newline,
2017 remove it from the source line which will be echoed,
2018 since it was most likely used to line
2019 up the continued line with the previous one. */
2020 if (*p == '\t')
2021 strcpy (p, p + 1);
2023 p = next_token (p);
2024 --p;
2025 *ap++ = '\\';
2026 *ap++ = ' ';
2027 continue;
2030 if (*p == '\\' || *p == '\'' || *p == '"'
2031 || isspace (*p)
2032 || index (sh_chars, *p) != 0)
2033 *ap++ = '\\';
2034 *ap++ = *p;
2036 *ap = '\0';
2038 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2039 (char *) 0, (char *) 0);
2041 #endif /* Not MSDOS nor Amiga. */
2043 return new_argv;
2046 /* Figure out the argument list necessary to run LINE as a command. Try to
2047 avoid using a shell. This routine handles only ' quoting, and " quoting
2048 when no backslash, $ or ` characters are seen in the quotes. Starting
2049 quotes may be escaped with a backslash. If any of the characters in
2050 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2051 is the first word of a line, the shell is used.
2053 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2054 If *RESTP is NULL, newlines will be ignored.
2056 FILE is the target whose commands these are. It is used for
2057 variable expansion for $(SHELL) and $(IFS). */
2059 char **
2060 construct_command_argv (line, restp, file)
2061 char *line, **restp;
2062 struct file *file;
2064 char *shell, *ifs;
2065 char **argv;
2068 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2069 int save = warn_undefined_variables_flag;
2070 warn_undefined_variables_flag = 0;
2072 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
2073 #ifdef WIN32
2075 * Convert to forward slashes so that construct_command_argv_internal()
2076 * is not confused.
2078 if (shell) {
2079 char *p = w32ify(shell, 0);
2080 strcpy(shell, p);
2082 #endif
2083 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
2085 warn_undefined_variables_flag = save;
2088 argv = construct_command_argv_internal (line, restp, shell, ifs);
2090 free (shell);
2091 free (ifs);
2093 return argv;
2095 #endif /* !VMS */
2097 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2099 dup2 (old, new)
2100 int old, new;
2102 int fd;
2104 (void) close (new);
2105 fd = dup (old);
2106 if (fd != new)
2108 (void) close (fd);
2109 errno = EMFILE;
2110 return -1;
2113 return fd;
2115 #endif /* !HAPE_DUP2 && !_AMIGA */