Updated from libc
[make.git] / job.c
blob04ff39e59d010317c875f3f0ef9bd193e3da740d
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 != 0;
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 /* Block fatal signals while frobnicating the list, so that
582 children and job_slots_used are always consistent. Otherwise
583 a fatal signal arriving after the child is off the chain and
584 before job_slots_used is decremented would believe a child was
585 live and call reap_children again. */
586 block_sigs ();
588 /* Remove the child from the chain and free it. */
589 if (lastc == 0)
590 children = c->next;
591 else
592 lastc->next = c->next;
593 if (! handling_fatal_signal) /* Don't bother if about to die. */
594 free_child (c);
596 /* There is now another slot open. */
597 if (job_slots_used > 0)
598 --job_slots_used;
600 unblock_sigs ();
602 /* If the job failed, and the -k flag was not given, die,
603 unless we are already in the process of dying. */
604 if (!err && child_failed && !keep_going_flag &&
605 /* fatal_error_signal will die with the right signal. */
606 !handling_fatal_signal)
607 die (2);
610 /* Only block for one child. */
611 block = 0;
613 return;
616 /* Free the storage allocated for CHILD. */
618 static void
619 free_child (child)
620 register struct child *child;
622 if (child->command_lines != 0)
624 register unsigned int i;
625 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
626 free (child->command_lines[i]);
627 free ((char *) child->command_lines);
630 if (child->environment != 0)
632 register char **ep = child->environment;
633 while (*ep != 0)
634 free (*ep++);
635 free ((char *) child->environment);
638 free ((char *) child);
641 #ifdef POSIX
642 extern sigset_t fatal_signal_set;
643 #endif
645 void
646 block_sigs ()
648 #ifdef POSIX
649 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
650 #else
651 #ifdef HAVE_SIGSETMASK
652 (void) sigblock (fatal_signal_mask);
653 #endif
654 #endif
657 #ifdef POSIX
658 #ifdef __MSDOS__
659 void
660 unblock_sigs ()
662 return;
664 #else
665 void
666 unblock_sigs ()
668 sigset_t empty;
669 sigemptyset (&empty);
670 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
672 #endif
673 #endif
675 /* Start a job to run the commands specified in CHILD.
676 CHILD is updated to reflect the commands and ID of the child process.
678 NOTE: On return fatal signals are blocked! The caller is responsible
679 for calling `unblock_sigs', once the new child is safely on the chain so
680 it can be cleaned up in the event of a fatal signal. */
682 static void
683 start_job_command (child)
684 register struct child *child;
686 #ifndef _AMIGA
687 static int bad_stdin = -1;
688 #endif
689 register char *p;
690 int flags;
691 #ifdef VMS
692 char *argv;
693 #else
694 char **argv;
695 #endif
697 /* Combine the flags parsed for the line itself with
698 the flags specified globally for this target. */
699 flags = (child->file->command_flags
700 | child->file->cmds->lines_flags[child->command_line - 1]);
702 p = child->command_ptr;
703 child->noerror = flags & COMMANDS_NOERROR;
705 while (*p != '\0')
707 if (*p == '@')
708 flags |= COMMANDS_SILENT;
709 else if (*p == '+')
710 flags |= COMMANDS_RECURSE;
711 else if (*p == '-')
712 child->noerror = 1;
713 else if (!isblank (*p) && *p != '+')
714 break;
715 ++p;
718 /* If -q was given, just say that updating `failed'. The exit status of
719 1 tells the user that -q is saying `something to do'; the exit status
720 for a random error is 2. */
721 if (question_flag && !(flags & COMMANDS_RECURSE))
723 child->file->update_status = 1;
724 notice_finished_file (child->file);
725 return;
728 /* There may be some preceding whitespace left if there
729 was nothing but a backslash on the first line. */
730 p = next_token (p);
732 /* Figure out an argument list from this command line. */
735 char *end = 0;
736 #ifdef VMS
737 argv = p;
738 #else
739 argv = construct_command_argv (p, &end, child->file);
740 #endif
741 if (end == NULL)
742 child->command_ptr = NULL;
743 else
745 *end++ = '\0';
746 child->command_ptr = end;
750 if (touch_flag && !(flags & COMMANDS_RECURSE))
752 /* Go on to the next command. It might be the recursive one.
753 We construct ARGV only to find the end of the command line. */
754 #ifndef VMS
755 free (argv[0]);
756 free ((char *) argv);
757 #endif
758 argv = 0;
761 if (argv == 0)
763 next_command:
764 /* This line has no commands. Go to the next. */
765 if (job_next_command (child))
766 start_job_command (child);
767 else
769 /* No more commands. All done. */
770 child->file->update_status = 0;
771 notice_finished_file (child->file);
773 return;
776 /* Print out the command. If silent, we call `message' with null so it
777 can log the working directory before the command's own error messages
778 appear. */
780 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
781 ? "%s" : (char *) 0, p);
783 /* Tell update_goal_chain that a command has been started on behalf of
784 this target. It is important that this happens here and not in
785 reap_children (where we used to do it), because reap_children might be
786 reaping children from a different target. We want this increment to
787 guaranteedly indicate that a command was started for the dependency
788 chain (i.e., update_file recursion chain) we are processing. */
790 ++commands_started;
792 /* If -n was given, recurse to get the next line in the sequence. */
794 if (just_print_flag && !(flags & COMMANDS_RECURSE))
796 #ifndef VMS
797 free (argv[0]);
798 free ((char *) argv);
799 #endif
800 goto next_command;
803 /* Flush the output streams so they won't have things written twice. */
805 fflush (stdout);
806 fflush (stderr);
808 #ifndef WIN32
809 #ifndef _AMIGA
810 #ifndef VMS
812 /* Set up a bad standard input that reads from a broken pipe. */
814 if (bad_stdin == -1)
816 /* Make a file descriptor that is the read end of a broken pipe.
817 This will be used for some children's standard inputs. */
818 int pd[2];
819 if (pipe (pd) == 0)
821 /* Close the write side. */
822 (void) close (pd[1]);
823 /* Save the read side. */
824 bad_stdin = pd[0];
826 /* Set the descriptor to close on exec, so it does not litter any
827 child's descriptor table. When it is dup2'd onto descriptor 0,
828 that descriptor will not close on exec. */
829 #ifdef FD_SETFD
830 #ifndef FD_CLOEXEC
831 #define FD_CLOEXEC 1
832 #endif
833 (void) fcntl (bad_stdin, F_SETFD, FD_CLOEXEC);
834 #endif
838 #endif /* !AMIGA */
839 #endif /* !WIN32 */
841 /* Decide whether to give this child the `good' standard input
842 (one that points to the terminal or whatever), or the `bad' one
843 that points to the read side of a broken pipe. */
845 child->good_stdin = !good_stdin_used;
846 if (child->good_stdin)
847 good_stdin_used = 1;
849 #endif /* Not VMS */
851 child->deleted = 0;
853 #ifndef _AMIGA
854 /* Set up the environment for the child. */
855 if (child->environment == 0)
856 child->environment = target_environment (child->file);
857 #endif
859 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WIN32)
861 #ifndef VMS
862 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
863 if (child->remote)
865 int is_remote, id, used_stdin;
866 if (start_remote_job (argv, child->environment,
867 child->good_stdin ? 0 : bad_stdin,
868 &is_remote, &id, &used_stdin))
869 goto error;
870 else
872 if (child->good_stdin && !used_stdin)
874 child->good_stdin = 0;
875 good_stdin_used = 0;
877 child->remote = is_remote;
878 child->pid = id;
881 else
882 #endif /* !VMS */
884 /* Fork the child process. */
886 char **parent_environ;
888 block_sigs ();
890 child->remote = 0;
892 #ifdef VMS
894 if (!child_execute_job (argv, child)) {
895 /* Fork failed! */
896 perror_with_name ("vfork", "");
897 goto error;
900 #else
902 parent_environ = environ;
903 child->pid = vfork ();
904 environ = parent_environ; /* Restore value child may have clobbered. */
905 if (child->pid == 0)
907 /* We are the child side. */
908 unblock_sigs ();
909 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
910 argv, child->environment);
912 else if (child->pid < 0)
914 /* Fork failed! */
915 unblock_sigs ();
916 perror_with_name ("vfork", "");
917 goto error;
919 #endif /* !VMS */
922 #else /* MSDOS or Amiga. */
923 #ifdef __MSDOS__
924 dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
925 ++dead_children;
926 child->pid = dos_pid++;
927 if (dos_batch_file)
929 dos_batch_file = 0;
930 remove (dos_bname); /* Ignore errors. */
931 if (access (dos_bename, 0))
932 dos_status = 1;
933 else
934 dos_status = 0;
935 remove (dos_bename);
937 #endif /* __MSDOS__ */
938 #ifdef _AMIGA
939 amiga_status = MyExecute (argv);
941 ++dead_children;
942 child->pid = amiga_pid++;
943 if (amiga_batch_file)
945 amiga_batch_file = 0;
946 DeleteFile (amiga_bname); /* Ignore errors. */
948 #endif /* Not Amiga */
949 #ifdef WIN32
951 HANDLE hPID;
952 char* arg0;
954 /* make UNC paths safe for CreateProcess -- backslash format */
955 arg0 = argv[0];
956 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
957 for ( ; arg0 && *arg0; arg0++)
958 if (*arg0 == '/')
959 *arg0 = '\\';
961 /* make sure CreateProcess() has Path it needs */
962 sync_Path_environment();
964 hPID = process_easy(argv, child->environment);
966 if (hPID != INVALID_HANDLE_VALUE)
967 child->pid = (int) hPID;
968 else {
969 int i;
970 unblock_sigs();
971 fprintf(stderr,
972 "process_easy() failed failed to launch process (e=%d)\n",
973 process_last_err(hPID));
974 for (i = 0; argv[i]; i++)
975 fprintf(stderr, "%s ", argv[i]);
976 fprintf(stderr, "\nCounted %d args in failed launch\n", i);
979 #endif /* WIN32 */
980 #endif /* Not MSDOS. */
982 /* We are the parent side. Set the state to
983 say the commands are running and return. */
985 set_command_state (child->file, cs_running);
987 /* Free the storage used by the child's argument list. */
988 #ifndef VMS
989 free (argv[0]);
990 free ((char *) argv);
991 #endif
993 return;
995 error:
996 child->file->update_status = 2;
997 notice_finished_file (child->file);
998 return;
1001 /* Try to start a child running.
1002 Returns nonzero if the child was started (and maybe finished), or zero if
1003 the load was too high and the child was put on the `waiting_jobs' chain. */
1005 static int
1006 start_waiting_job (c)
1007 struct child *c;
1009 /* If we can start a job remotely, we always want to, and don't care about
1010 the local load average. We record that the job should be started
1011 remotely in C->remote for start_job_command to test. */
1013 c->remote = start_remote_job_p ();
1015 /* If this job is to be started locally, and we are already running
1016 some jobs, make this one wait if the load average is too high. */
1017 if (!c->remote && job_slots_used > 0 && load_too_high ())
1019 /* Put this child on the chain of children waiting
1020 for the load average to go down. */
1021 set_command_state (c->file, cs_running);
1022 c->next = waiting_jobs;
1023 waiting_jobs = c;
1024 return 0;
1027 /* Start the first command; reap_children will run later command lines. */
1028 start_job_command (c);
1030 switch (c->file->command_state)
1032 case cs_running:
1033 c->next = children;
1034 if (debug_flag)
1035 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
1036 (unsigned long int) c,
1037 c->pid, c->remote ? " (remote)" : "");
1038 children = c;
1039 /* One more job slot is in use. */
1040 ++job_slots_used;
1041 unblock_sigs ();
1042 break;
1044 case cs_not_started:
1045 /* All the command lines turned out to be empty. */
1046 c->file->update_status = 0;
1047 /* FALLTHROUGH */
1049 case cs_finished:
1050 notice_finished_file (c->file);
1051 free_child (c);
1052 break;
1054 default:
1055 assert (c->file->command_state == cs_finished);
1056 break;
1059 return 1;
1062 /* Create a `struct child' for FILE and start its commands running. */
1064 void
1065 new_job (file)
1066 register struct file *file;
1068 register struct commands *cmds = file->cmds;
1069 register struct child *c;
1070 char **lines;
1071 register unsigned int i;
1073 /* Let any previously decided-upon jobs that are waiting
1074 for the load to go down start before this new one. */
1075 start_waiting_jobs ();
1077 /* Reap any children that might have finished recently. */
1078 reap_children (0, 0);
1080 /* Chop the commands up into lines if they aren't already. */
1081 chop_commands (cmds);
1083 if (job_slots != 0)
1084 /* Wait for a job slot to be freed up. */
1085 while (job_slots_used == job_slots)
1086 reap_children (1, 0);
1088 /* Expand the command lines and store the results in LINES. */
1089 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1090 for (i = 0; i < cmds->ncommand_lines; ++i)
1092 /* Collapse backslash-newline combinations that are inside variable
1093 or function references. These are left alone by the parser so
1094 that they will appear in the echoing of commands (where they look
1095 nice); and collapsed by construct_command_argv when it tokenizes.
1096 But letting them survive inside function invocations loses because
1097 we don't want the functions to see them as part of the text. */
1099 char *in, *out, *ref;
1101 /* IN points to where in the line we are scanning.
1102 OUT points to where in the line we are writing.
1103 When we collapse a backslash-newline combination,
1104 IN gets ahead out OUT. */
1106 in = out = cmds->command_lines[i];
1107 while ((ref = index (in, '$')) != 0)
1109 ++ref; /* Move past the $. */
1111 if (out != in)
1112 /* Copy the text between the end of the last chunk
1113 we processed (where IN points) and the new chunk
1114 we are about to process (where REF points). */
1115 bcopy (in, out, ref - in);
1117 /* Move both pointers past the boring stuff. */
1118 out += ref - in;
1119 in = ref;
1121 if (*ref == '(' || *ref == '{')
1123 char openparen = *ref;
1124 char closeparen = openparen == '(' ? ')' : '}';
1125 int count;
1126 char *p;
1128 *out++ = *in++; /* Copy OPENPAREN. */
1129 /* IN now points past the opening paren or brace.
1130 Count parens or braces until it is matched. */
1131 count = 0;
1132 while (*in != '\0')
1134 if (*in == closeparen && --count < 0)
1135 break;
1136 else if (*in == '\\' && in[1] == '\n')
1138 /* We have found a backslash-newline inside a
1139 variable or function reference. Eat it and
1140 any following whitespace. */
1142 int quoted = 0;
1143 for (p = in - 1; p > ref && *p == '\\'; --p)
1144 quoted = !quoted;
1146 if (quoted)
1147 /* There were two or more backslashes, so this is
1148 not really a continuation line. We don't collapse
1149 the quoting backslashes here as is done in
1150 collapse_continuations, because the line will
1151 be collapsed again after expansion. */
1152 *out++ = *in++;
1153 else
1155 /* Skip the backslash, newline and
1156 any following whitespace. */
1157 in = next_token (in + 2);
1159 /* Discard any preceding whitespace that has
1160 already been written to the output. */
1161 while (out > ref && isblank (out[-1]))
1162 --out;
1164 /* Replace it all with a single space. */
1165 *out++ = ' ';
1168 else
1170 if (*in == openparen)
1171 ++count;
1173 *out++ = *in++;
1179 /* There are no more references in this line to worry about.
1180 Copy the remaining uninteresting text to the output. */
1181 if (out != in)
1182 strcpy (out, in);
1184 /* Finally, expand the line. */
1185 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1186 file);
1189 /* Start the command sequence, record it in a new
1190 `struct child', and add that to the chain. */
1192 c = (struct child *) xmalloc (sizeof (struct child));
1193 c->file = file;
1194 c->command_lines = lines;
1195 c->command_line = 0;
1196 c->command_ptr = 0;
1197 c->environment = 0;
1199 /* Fetch the first command line to be run. */
1200 job_next_command (c);
1202 /* The job is now primed. Start it running.
1203 (This will notice if there are in fact no commands.) */
1204 (void)start_waiting_job (c);
1206 if (job_slots == 1)
1207 /* Since there is only one job slot, make things run linearly.
1208 Wait for the child to die, setting the state to `cs_finished'. */
1209 while (file->command_state == cs_running)
1210 reap_children (1, 0);
1212 return;
1215 /* Move CHILD's pointers to the next command for it to execute.
1216 Returns nonzero if there is another command. */
1218 static int
1219 job_next_command (child)
1220 struct child *child;
1222 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1224 /* There are no more lines in the expansion of this line. */
1225 if (child->command_line == child->file->cmds->ncommand_lines)
1227 /* There are no more lines to be expanded. */
1228 child->command_ptr = 0;
1229 return 0;
1231 else
1232 /* Get the next line to run. */
1233 child->command_ptr = child->command_lines[child->command_line++];
1235 return 1;
1238 static int
1239 load_too_high ()
1241 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1242 return 1;
1243 #else
1244 double load;
1246 if (max_load_average < 0)
1247 return 0;
1249 make_access ();
1250 if (getloadavg (&load, 1) != 1)
1252 static int lossage = -1;
1253 /* Complain only once for the same error. */
1254 if (lossage == -1 || errno != lossage)
1256 if (errno == 0)
1257 /* An errno value of zero means getloadavg is just unsupported. */
1258 error ("cannot enforce load limits on this operating system");
1259 else
1260 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1262 lossage = errno;
1263 load = 0;
1265 user_access ();
1267 return load >= max_load_average;
1268 #endif
1271 /* Start jobs that are waiting for the load to be lower. */
1273 void
1274 start_waiting_jobs ()
1276 struct child *job;
1278 if (waiting_jobs == 0)
1279 return;
1283 /* Check for recently deceased descendants. */
1284 reap_children (0, 0);
1286 /* Take a job off the waiting list. */
1287 job = waiting_jobs;
1288 waiting_jobs = job->next;
1290 /* Try to start that job. We break out of the loop as soon
1291 as start_waiting_job puts one back on the waiting list. */
1293 while (start_waiting_job (job) && waiting_jobs != 0);
1295 return;
1298 #ifndef WIN32
1299 #ifdef VMS
1300 #include <descrip.h>
1301 #include <clidef.h>
1303 /* This is called as an AST when a child process dies (it won't get
1304 interrupted by anything except a higher level AST).
1306 int vmsHandleChildTerm(struct child *child)
1308 int status;
1309 register struct child *lastc, *c;
1310 int child_failed;
1312 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1314 lib$free_ef(&child->efn);
1316 (void) sigblock (fatal_signal_mask);
1318 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1320 /* Search for a child matching the deceased one. */
1321 lastc = 0;
1322 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1323 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1324 #else
1325 c = child;
1326 #endif
1328 if (child_failed && !c->noerror && !ignore_errors_flag)
1330 /* The commands failed. Write an error message,
1331 delete non-precious targets, and abort. */
1332 child_error (c->file->name, c->cstatus, 0, 0, 0);
1333 c->file->update_status = 1;
1334 delete_child_targets (c);
1336 else
1338 if (child_failed)
1340 /* The commands failed, but we don't care. */
1341 child_error (c->file->name, c->cstatus, 0, 0, 1);
1342 child_failed = 0;
1345 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1346 /* If there are more commands to run, try to start them. */
1347 start_job (c);
1349 switch (c->file->command_state)
1351 case cs_running:
1352 /* Successfully started. */
1353 break;
1355 case cs_finished:
1356 if (c->file->update_status != 0) {
1357 /* We failed to start the commands. */
1358 delete_child_targets (c);
1360 break;
1362 default:
1363 error ("internal error: `%s' command_state \
1364 %d in child_handler", c->file->name);
1365 abort ();
1366 break;
1368 #endif /* RECURSIVEJOBS */
1371 /* Set the state flag to say the commands have finished. */
1372 c->file->command_state = cs_finished;
1373 notice_finished_file (c->file);
1375 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1376 /* Remove the child from the chain and free it. */
1377 if (lastc == 0)
1378 children = c->next;
1379 else
1380 lastc->next = c->next;
1381 free_child (c);
1382 #endif /* RECURSIVEJOBS */
1384 /* There is now another slot open. */
1385 if (job_slots_used > 0)
1386 --job_slots_used;
1388 /* If the job failed, and the -k flag was not given, die. */
1389 if (child_failed && !keep_going_flag)
1390 die (EXIT_FAILURE);
1392 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1394 return 1;
1397 /* VMS:
1398 Spawn a process executing the command in ARGV and return its pid. */
1400 #define MAXCMDLEN 200
1403 child_execute_job (argv, child)
1404 char *argv;
1405 struct child *child;
1407 int i;
1408 static struct dsc$descriptor_s cmddsc;
1409 #ifndef DONTWAITFORCHILD
1410 int spflags = 0;
1411 #else
1412 int spflags = CLI$M_NOWAIT;
1413 #endif
1414 int status;
1415 char cmd[4096],*p,*c;
1416 char comname[50];
1418 /* Remove backslashes */
1419 for (p = argv, c = cmd; *p; p++,c++)
1421 if (*p == '\\') p++;
1422 *c = *p;
1424 *c = *p;
1426 /* check for maximum dcl length and create *.com file if neccesary */
1428 comname[0] = '\0';
1430 if (strlen (cmd) > MAXCMDLEN)
1432 FILE *outfile;
1433 char tmp;
1435 strcpy (comname, "sys$scratch:CMDXXXXXX.COM");
1436 (void) mktemp (comname);
1438 outfile = fopen (comname, "w");
1439 if (outfile == 0)
1440 pfatal_with_name (comname);
1442 fprintf (outfile, "$ ");
1443 c = cmd;
1445 while (c)
1447 p = strchr (c, ',');
1448 if ((p == NULL) || (p-c > MAXCMDLEN))
1449 p = strchr (c, ' ');
1450 if (p != NULL)
1452 p++;
1453 tmp = *p;
1454 *p = '\0';
1456 else
1457 tmp = '\0';
1458 fprintf (outfile, "%s%s\n", c, (tmp == '\0')?"":" -");
1459 if (p != NULL)
1460 *p = tmp;
1461 c = p;
1464 fclose (outfile);
1466 sprintf (cmd, "$ @%s", comname);
1468 if (debug_flag)
1469 printf ("Executing %s instead\n", cmd);
1472 cmddsc.dsc$w_length = strlen(cmd);
1473 cmddsc.dsc$a_pointer = cmd;
1474 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
1475 cmddsc.dsc$b_class = DSC$K_CLASS_S;
1477 child->efn = 0;
1478 while (child->efn < 32 || child->efn > 63)
1480 status = lib$get_ef(&child->efn);
1481 if (!(status & 1))
1482 return 0;
1485 sys$clref(child->efn);
1487 vms_jobsefnmask |= (1 << (child->efn - 32));
1489 #ifndef DONTWAITFORCHILD
1490 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1491 &child->efn,0,0);
1492 vmsHandleChildTerm(child);
1493 #else
1494 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1495 &child->efn,vmsHandleChildTerm,child);
1496 #endif
1498 if (!(status & 1))
1500 printf("Error spawning, %d\n",status);
1501 fflush(stdout);
1504 unlink (comname);
1506 return (status & 1);
1509 #else /* !VMS */
1511 #ifndef _AMIGA
1512 /* UNIX:
1513 Replace the current process with one executing the command in ARGV.
1514 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1515 the environment of the new program. This function does not return. */
1517 void
1518 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1519 int stdin_fd, stdout_fd;
1520 char **argv, **envp;
1522 if (stdin_fd != 0)
1523 (void) dup2 (stdin_fd, 0);
1524 if (stdout_fd != 1)
1525 (void) dup2 (stdout_fd, 1);
1526 if (stdin_fd != 0)
1527 (void) close (stdin_fd);
1528 if (stdout_fd != 1)
1529 (void) close (stdout_fd);
1531 /* Run the command. */
1532 exec_command (argv, envp);
1534 #endif /* !AMIGA */
1535 #endif /* !VMS */
1536 #endif /* !WIN32 */
1538 #ifndef _AMIGA
1539 /* Replace the current process with one running the command in ARGV,
1540 with environment ENVP. This function does not return. */
1542 void
1543 exec_command (argv, envp)
1544 char **argv, **envp;
1546 #ifdef VMS
1547 /* Run the program. */
1548 execve (argv[0], argv, envp);
1549 perror_with_name ("execve: ", argv[0]);
1550 _exit (EXIT_FAILURE);
1551 #else
1552 /* Be the user, permanently. */
1553 child_access ();
1555 /* Run the program. */
1556 environ = envp;
1557 execvp (argv[0], argv);
1559 switch (errno)
1561 case ENOENT:
1562 error ("%s: Command not found", argv[0]);
1563 break;
1564 case ENOEXEC:
1566 /* The file is not executable. Try it as a shell script. */
1567 extern char *getenv ();
1568 char *shell;
1569 char **new_argv;
1570 int argc;
1572 shell = getenv ("SHELL");
1573 if (shell == 0)
1574 shell = default_shell;
1576 argc = 1;
1577 while (argv[argc] != 0)
1578 ++argc;
1580 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1581 new_argv[0] = shell;
1582 new_argv[1] = argv[0];
1583 while (argc > 0)
1585 new_argv[1 + argc] = argv[argc];
1586 --argc;
1589 execvp (shell, new_argv);
1590 if (errno == ENOENT)
1591 error ("%s: Shell program not found", shell);
1592 else
1593 perror_with_name ("execvp: ", shell);
1594 break;
1597 default:
1598 perror_with_name ("execvp: ", argv[0]);
1599 break;
1602 _exit (127);
1603 #endif /* !VMS */
1605 #else /* On Amiga */
1606 void exec_command (argv)
1607 char **argv;
1609 MyExecute (argv);
1612 void clean_tmp (void)
1614 DeleteFile (amiga_bname);
1617 #endif /* An Amiga */
1619 #ifndef VMS
1620 /* Figure out the argument list necessary to run LINE as a command. Try to
1621 avoid using a shell. This routine handles only ' quoting, and " quoting
1622 when no backslash, $ or ` characters are seen in the quotes. Starting
1623 quotes may be escaped with a backslash. If any of the characters in
1624 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1625 is the first word of a line, the shell is used.
1627 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1628 If *RESTP is NULL, newlines will be ignored.
1630 SHELL is the shell to use, or nil to use the default shell.
1631 IFS is the value of $IFS, or nil (meaning the default). */
1633 static char **
1634 construct_command_argv_internal (line, restp, shell, ifs)
1635 char *line, **restp;
1636 char *shell, *ifs;
1638 #ifdef __MSDOS__
1639 static char sh_chars[] = "\"|<>";
1640 static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1641 "copy", "ctty", "date", "del", "dir", "echo",
1642 "erase", "exit", "for", "goto", "if", "if", "md",
1643 "mkdir", "path", "pause", "prompt", "rem", "ren",
1644 "rename", "set", "shift", "time", "type",
1645 "ver", "verify", "vol", ":", 0 };
1646 #else
1647 #ifdef _AMIGA
1648 static char sh_chars[] = "#;\"|<>()?*$`";
1649 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
1650 "rename", "set", "setenv", "date", "makedir",
1651 "skip", "else", "endif", "path", "prompt",
1652 "unset", "unsetenv", "version",
1653 0 };
1654 #else
1655 #ifdef WIN32
1656 static char sh_chars_dos[] = "\"|<>";
1657 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1658 "copy", "ctty", "date", "del", "dir", "echo",
1659 "erase", "exit", "for", "goto", "if", "if", "md",
1660 "mkdir", "path", "pause", "prompt", "rem", "ren",
1661 "rename", "set", "shift", "time", "type",
1662 "ver", "verify", "vol", ":", 0 };
1663 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1664 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
1665 "logout", "set", "umask", "wait", "while", "for",
1666 "case", "if", ":", ".", "break", "continue",
1667 "export", "read", "readonly", "shift", "times",
1668 "trap", "switch", "test", 0 };
1669 char* sh_chars;
1670 char** sh_cmds;
1671 #else /* WIN32 */
1672 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1673 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1674 "logout", "set", "umask", "wait", "while", "for",
1675 "case", "if", ":", ".", "break", "continue",
1676 "export", "read", "readonly", "shift", "times",
1677 "trap", "switch", 0 };
1678 #endif /* WIN32 */
1679 #endif /* Amiga */
1680 #endif /* MSDOS */
1681 register int i;
1682 register char *p;
1683 register char *ap;
1684 char *end;
1685 int instring, word_has_equals, seen_nonequals;
1686 char **new_argv = 0;
1687 #ifdef WIN32
1688 int slow_flag = 0;
1690 if (no_default_sh_exe) {
1691 sh_cmds = sh_cmds_dos;
1692 sh_chars = sh_chars_dos;
1693 } else {
1694 sh_cmds = sh_cmds_sh;
1695 sh_chars = sh_chars_sh;
1697 #endif
1699 if (restp != NULL)
1700 *restp = NULL;
1702 /* Make sure not to bother processing an empty line. */
1703 while (isblank (*line))
1704 ++line;
1705 if (*line == '\0')
1706 return 0;
1708 /* See if it is safe to parse commands internally. */
1709 if (shell == 0)
1710 shell = default_shell;
1711 else if (strcmp (shell, default_shell))
1712 #ifdef WIN32
1714 char *s1 = _fullpath(NULL, shell, 0);
1715 char *s2 = _fullpath(NULL, default_shell, 0);
1717 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
1719 if (s1);
1720 free(s1);
1721 if (s2);
1722 free(s2);
1724 if (slow_flag)
1725 #endif /* WIN32 */
1726 goto slow;
1728 if (ifs != 0)
1729 for (ap = ifs; *ap != '\0'; ++ap)
1730 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1731 goto slow;
1733 i = strlen (line) + 1;
1735 /* More than 1 arg per character is impossible. */
1736 new_argv = (char **) xmalloc (i * sizeof (char *));
1738 /* All the args can fit in a buffer as big as LINE is. */
1739 ap = new_argv[0] = (char *) xmalloc (i);
1740 end = ap + i;
1742 /* I is how many complete arguments have been found. */
1743 i = 0;
1744 instring = word_has_equals = seen_nonequals = 0;
1745 for (p = line; *p != '\0'; ++p)
1747 if (ap > end)
1748 abort ();
1750 if (instring)
1752 string_char:
1753 /* Inside a string, just copy any char except a closing quote
1754 or a backslash-newline combination. */
1755 if (*p == instring)
1756 instring = 0;
1757 else if (*p == '\\' && p[1] == '\n')
1758 goto swallow_escaped_newline;
1759 else if (*p == '\n' && restp != NULL)
1761 /* End of the command line. */
1762 *restp = p;
1763 goto end_of_line;
1765 /* Backslash, $, and ` are special inside double quotes.
1766 If we see any of those, punt. */
1767 else if (instring == '"' && index ("\\$`", *p) != 0)
1768 goto slow;
1769 else
1770 *ap++ = *p;
1772 else if (index (sh_chars, *p) != 0)
1773 /* Not inside a string, but it's a special char. */
1774 goto slow;
1775 else
1776 /* Not a special char. */
1777 switch (*p)
1779 case '=':
1780 /* Equals is a special character in leading words before the
1781 first word with no equals sign in it. This is not the case
1782 with sh -k, but we never get here when using nonstandard
1783 shell flags. */
1784 if (! seen_nonequals)
1785 goto slow;
1786 word_has_equals = 1;
1787 *ap++ = '=';
1788 break;
1790 case '\\':
1791 /* Backslash-newline combinations are eaten. */
1792 if (p[1] == '\n')
1794 swallow_escaped_newline:
1796 /* Eat the backslash, the newline, and following whitespace,
1797 replacing it all with a single space. */
1798 p += 2;
1800 /* If there is a tab after a backslash-newline,
1801 remove it from the source line which will be echoed,
1802 since it was most likely used to line
1803 up the continued line with the previous one. */
1804 if (*p == '\t')
1805 strcpy (p, p + 1);
1807 if (instring)
1808 goto string_char;
1809 else
1811 if (ap != new_argv[i])
1812 /* Treat this as a space, ending the arg.
1813 But if it's at the beginning of the arg, it should
1814 just get eaten, rather than becoming an empty arg. */
1815 goto end_of_arg;
1816 else
1817 p = next_token (p) - 1;
1820 else if (p[1] != '\0')
1821 /* Copy and skip the following char. */
1822 *ap++ = *++p;
1823 break;
1825 case '\'':
1826 case '"':
1827 instring = *p;
1828 break;
1830 case '\n':
1831 if (restp != NULL)
1833 /* End of the command line. */
1834 *restp = p;
1835 goto end_of_line;
1837 else
1838 /* Newlines are not special. */
1839 *ap++ = '\n';
1840 break;
1842 case ' ':
1843 case '\t':
1844 end_of_arg:
1845 /* We have the end of an argument.
1846 Terminate the text of the argument. */
1847 *ap++ = '\0';
1848 new_argv[++i] = ap;
1850 /* Update SEEN_NONEQUALS, which tells us if every word
1851 heretofore has contained an `='. */
1852 seen_nonequals |= ! word_has_equals;
1853 if (word_has_equals && ! seen_nonequals)
1854 /* An `=' in a word before the first
1855 word without one is magical. */
1856 goto slow;
1857 word_has_equals = 0; /* Prepare for the next word. */
1859 /* If this argument is the command name,
1860 see if it is a built-in shell command.
1861 If so, have the shell handle it. */
1862 if (i == 1)
1864 register int j;
1865 for (j = 0; sh_cmds[j] != 0; ++j)
1866 if (streq (sh_cmds[j], new_argv[0]))
1867 goto slow;
1870 /* Ignore multiple whitespace chars. */
1871 p = next_token (p);
1872 /* Next iteration should examine the first nonwhite char. */
1873 --p;
1874 break;
1876 default:
1877 *ap++ = *p;
1878 break;
1881 end_of_line:
1883 if (instring)
1884 /* Let the shell deal with an unterminated quote. */
1885 goto slow;
1887 /* Terminate the last argument and the argument list. */
1889 *ap = '\0';
1890 if (new_argv[i][0] != '\0')
1891 ++i;
1892 new_argv[i] = 0;
1894 if (i == 1)
1896 register int j;
1897 for (j = 0; sh_cmds[j] != 0; ++j)
1898 if (streq (sh_cmds[j], new_argv[0]))
1899 goto slow;
1902 if (new_argv[0] == 0)
1903 /* Line was empty. */
1904 return 0;
1905 else
1906 return new_argv;
1908 slow:;
1909 /* We must use the shell. */
1911 if (new_argv != 0)
1913 /* Free the old argument list we were working on. */
1914 free (new_argv[0]);
1915 free ((void *)new_argv);
1917 #ifdef WIN32
1919 * Not eating this whitespace caused things like
1921 * sh -c "\n"
1923 * which gave the shell fits. I think we have to eat
1924 * whitespace here, but this code should be considered
1925 * suspicious if things start failing....
1928 /* Make sure not to bother processing an empty line. */
1929 while (isspace (*line))
1930 ++line;
1931 if (*line == '\0')
1932 return 0;
1933 #endif
1935 #if defined(__MSDOS__) || defined(WIN32)
1936 #ifdef WIN32
1938 * only come here if no sh.exe command
1940 if (no_default_sh_exe)
1941 #endif
1943 FILE *batch;
1944 dos_batch_file = 1;
1945 if (dos_bname == 0)
1947 dos_bname = tempnam (".", "mk");
1948 for (i = 0; dos_bname[i] != '\0'; ++i)
1949 if (dos_bname[i] == '/')
1950 dos_bname[i] = '\\';
1951 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
1952 strcpy (dos_bename, dos_bname);
1953 strcat (dos_bname, ".bat");
1954 strcat (dos_bename, ".err");
1956 batch = fopen (dos_bename, "w"); /* Create a file. */
1957 if (batch != NULL)
1958 fclose (batch);
1959 batch = fopen (dos_bname, "w");
1960 fputs ("@echo off\n", batch);
1961 fputs (line, batch);
1962 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
1963 fclose (batch);
1964 new_argv = (char **) xmalloc(2 * sizeof(char *));
1965 new_argv[0] = strdup (dos_bname);
1966 new_argv[1] = 0;
1968 #endif /* MSDOS. */
1969 #ifdef _AMIGA
1971 char *ptr;
1972 char *buffer;
1973 char *dptr;
1975 buffer = (char *)xmalloc (strlen (line)+1);
1977 ptr = line;
1978 for (dptr=buffer; *ptr; )
1980 if (*ptr == '\\' && ptr[1] == '\n')
1981 ptr += 2;
1982 else if (*ptr == '@') /* Kludge: multiline commands */
1984 ptr += 2;
1985 *dptr++ = '\n';
1987 else
1988 *dptr++ = *ptr++;
1990 *dptr = 0;
1992 new_argv = (char **) xmalloc(2 * sizeof(char *));
1993 new_argv[0] = buffer;
1994 new_argv[1] = 0;
1996 #else /* Not MSDOS or Amiga */
1997 #ifdef WIN32
1999 * This is technically an else to the above 'if (no_default_sh_exe)',
2000 * but (IMHO) coding if-else across ifdef is dangerous.
2002 if (!no_default_sh_exe)
2003 #endif
2005 /* SHELL may be a multi-word command. Construct a command line
2006 "SHELL -c LINE", with all special chars in LINE escaped.
2007 Then recurse, expanding this command line to get the final
2008 argument list. */
2010 unsigned int shell_len = strlen (shell);
2011 static char minus_c[] = " -c ";
2012 unsigned int line_len = strlen (line);
2014 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2015 + (line_len * 2) + 1);
2017 ap = new_line;
2018 bcopy (shell, ap, shell_len);
2019 ap += shell_len;
2020 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2021 ap += sizeof (minus_c) - 1;
2022 for (p = line; *p != '\0'; ++p)
2024 if (restp != NULL && *p == '\n')
2026 *restp = p;
2027 break;
2029 else if (*p == '\\' && p[1] == '\n')
2031 /* Eat the backslash, the newline, and following whitespace,
2032 replacing it all with a single space (which is escaped
2033 from the shell). */
2034 p += 2;
2036 /* If there is a tab after a backslash-newline,
2037 remove it from the source line which will be echoed,
2038 since it was most likely used to line
2039 up the continued line with the previous one. */
2040 if (*p == '\t')
2041 strcpy (p, p + 1);
2043 p = next_token (p);
2044 --p;
2045 *ap++ = '\\';
2046 *ap++ = ' ';
2047 continue;
2050 if (*p == '\\' || *p == '\'' || *p == '"'
2051 || isspace (*p)
2052 || index (sh_chars, *p) != 0)
2053 *ap++ = '\\';
2054 *ap++ = *p;
2056 *ap = '\0';
2058 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2059 (char *) 0, (char *) 0);
2061 #endif /* Not MSDOS nor Amiga. */
2063 return new_argv;
2066 /* Figure out the argument list necessary to run LINE as a command. Try to
2067 avoid using a shell. This routine handles only ' quoting, and " quoting
2068 when no backslash, $ or ` characters are seen in the quotes. Starting
2069 quotes may be escaped with a backslash. If any of the characters in
2070 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2071 is the first word of a line, the shell is used.
2073 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2074 If *RESTP is NULL, newlines will be ignored.
2076 FILE is the target whose commands these are. It is used for
2077 variable expansion for $(SHELL) and $(IFS). */
2079 char **
2080 construct_command_argv (line, restp, file)
2081 char *line, **restp;
2082 struct file *file;
2084 char *shell, *ifs;
2085 char **argv;
2088 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2089 int save = warn_undefined_variables_flag;
2090 warn_undefined_variables_flag = 0;
2092 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
2093 #ifdef WIN32
2095 * Convert to forward slashes so that construct_command_argv_internal()
2096 * is not confused.
2098 if (shell) {
2099 char *p = w32ify(shell, 0);
2100 strcpy(shell, p);
2102 #endif
2103 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
2105 warn_undefined_variables_flag = save;
2108 argv = construct_command_argv_internal (line, restp, shell, ifs);
2110 free (shell);
2111 free (ifs);
2113 return argv;
2115 #endif /* !VMS */
2117 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2119 dup2 (old, new)
2120 int old, new;
2122 int fd;
2124 (void) close (new);
2125 fd = dup (old);
2126 if (fd != new)
2128 (void) close (fd);
2129 errno = EMFILE;
2130 return -1;
2133 return fd;
2135 #endif /* !HAPE_DUP2 && !_AMIGA */