Updates for GNU make 3.75.92.
[make.git] / job.c
blob09b946939b208f619f370415b3324bfd149127d0
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988,89,90,91,92,93,94,95,96,97 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 GNU Make is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNU Make; see the file COPYING. If not, write to
17 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
19 #include "make.h"
20 #include "job.h"
21 #include "filedef.h"
22 #include "commands.h"
23 #include "variable.h"
24 #include <assert.h>
26 /* Default shell to use. */
27 #ifdef WINDOWS32
28 char *default_shell = "sh.exe";
29 int no_default_sh_exe = 1;
30 #else /* WINDOWS32 */
31 #ifdef _AMIGA
32 char default_shell[] = "";
33 extern int MyExecute (char **);
34 #else
35 #ifdef __MSDOS__
36 /* The default shell is a pointer so we can change it if Makefile
37 says so. It is without an explicit path so we get a chance
38 to search the $PATH for it (since MSDOS doesn't have standard
39 directories we could trust). */
40 char *default_shell = "command.com";
41 #else /* __MSDOS__ */
42 char default_shell[] = "/bin/sh";
43 #endif /* __MSDOS__ */
44 #endif /* _AMIGA */
45 #endif /* WINDOWS32 */
47 #ifdef __MSDOS__
48 #include <process.h>
49 static int execute_by_shell;
50 static int dos_pid = 123;
51 int dos_status;
52 int dos_command_running;
53 #endif /* __MSDOS__ */
55 #ifdef _AMIGA
56 #include <proto/dos.h>
57 static int amiga_pid = 123;
58 static int amiga_status;
59 static char amiga_bname[32];
60 static int amiga_batch_file;
61 #endif /* Amiga. */
63 #ifdef VMS
64 #include <time.h>
65 #include <processes.h>
66 #include <starlet.h>
67 #include <lib$routines.h>
68 #endif
70 #ifdef WINDOWS32
71 #include <windows.h>
72 #include <io.h>
73 #include <process.h>
74 #include "sub_proc.h"
75 #include "w32err.h"
76 #include "pathstuff.h"
78 /* this stuff used if no sh.exe is around */
79 static char *dos_bname;
80 static char *dos_bename;
81 static int dos_batch_file;
82 #endif /* WINDOWS32 */
84 #ifdef HAVE_FCNTL_H
85 #include <fcntl.h>
86 #else
87 #include <sys/file.h>
88 #endif
90 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
91 #include <sys/wait.h>
92 #endif
94 #ifdef HAVE_WAITPID
95 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
96 #else /* Don't have waitpid. */
97 #ifdef HAVE_WAIT3
98 #ifndef wait3
99 extern int wait3 ();
100 #endif
101 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
102 #endif /* Have wait3. */
103 #endif /* Have waitpid. */
105 #if !defined (wait) && !defined (POSIX)
106 extern int wait ();
107 #endif
109 #ifndef HAVE_UNION_WAIT
111 #define WAIT_T int
113 #ifndef WTERMSIG
114 #define WTERMSIG(x) ((x) & 0x7f)
115 #endif
116 #ifndef WCOREDUMP
117 #define WCOREDUMP(x) ((x) & 0x80)
118 #endif
119 #ifndef WEXITSTATUS
120 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
121 #endif
122 #ifndef WIFSIGNALED
123 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
124 #endif
125 #ifndef WIFEXITED
126 #define WIFEXITED(x) (WTERMSIG (x) == 0)
127 #endif
129 #else /* Have `union wait'. */
131 #define WAIT_T union wait
132 #ifndef WTERMSIG
133 #define WTERMSIG(x) ((x).w_termsig)
134 #endif
135 #ifndef WCOREDUMP
136 #define WCOREDUMP(x) ((x).w_coredump)
137 #endif
138 #ifndef WEXITSTATUS
139 #define WEXITSTATUS(x) ((x).w_retcode)
140 #endif
141 #ifndef WIFSIGNALED
142 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
143 #endif
144 #ifndef WIFEXITED
145 #define WIFEXITED(x) (WTERMSIG(x) == 0)
146 #endif
148 #endif /* Don't have `union wait'. */
150 #ifdef VMS
151 static int vms_jobsefnmask=0;
152 #endif /* !VMS */
154 #ifndef HAVE_UNISTD_H
155 extern int dup2 ();
156 extern int execve ();
157 extern void _exit ();
158 #ifndef VMS
159 extern int geteuid ();
160 extern int getegid ();
161 extern int setgid ();
162 extern int getgid ();
163 #endif
164 #endif
166 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
168 extern int getloadavg PARAMS ((double loadavg[], int nelem));
169 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
170 int *is_remote, int *id_ptr, int *used_stdin));
171 extern int start_remote_job_p PARAMS ((void));
172 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
173 int *coredump_ptr, int block));
175 RETSIGTYPE child_handler PARAMS ((int));
176 static void free_child PARAMS ((struct child *));
177 static void start_job_command PARAMS ((struct child *child));
178 static int load_too_high PARAMS ((void));
179 static int job_next_command PARAMS ((struct child *));
180 static int start_waiting_job PARAMS ((struct child *));
181 #ifdef VMS
182 static void vmsWaitForChildren PARAMS ((int *));
183 #endif
185 /* Chain of all live (or recently deceased) children. */
187 struct child *children = 0;
189 /* Number of children currently running. */
191 unsigned int job_slots_used = 0;
193 /* Nonzero if the `good' standard input is in use. */
195 static int good_stdin_used = 0;
197 /* Chain of children waiting to run until the load average goes down. */
199 static struct child *waiting_jobs = 0;
201 /* Non-zero if we use a *real* shell (always so on Unix). */
203 int unixy_shell = 1;
205 #ifdef WINDOWS32
207 * The macro which references this function is defined in make.h.
209 int w32_kill(int pid, int sig)
211 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
213 #endif /* WINDOWS32 */
215 /* Write an error message describing the exit status given in
216 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
217 Append "(ignored)" if IGNORED is nonzero. */
219 static void
220 child_error (target_name, exit_code, exit_sig, coredump, ignored)
221 char *target_name;
222 int exit_code, exit_sig, coredump;
223 int ignored;
225 if (ignored && silent_flag)
226 return;
228 #ifdef VMS
229 if (!(exit_code & 1))
230 error("*** [%s] Error 0x%x%s", target_name, exit_code, ((ignored)? " (ignored)" : ""));
231 #else
232 if (exit_sig == 0)
233 error (ignored ? "[%s] Error %d (ignored)" :
234 "*** [%s] Error %d",
235 target_name, exit_code);
236 else
237 error ("*** [%s] %s%s",
238 target_name, strsignal (exit_sig),
239 coredump ? " (core dumped)" : "");
240 #endif /* VMS */
243 static unsigned int dead_children = 0;
245 #ifdef VMS
246 /* Wait for nchildren children to terminate */
247 static void
248 vmsWaitForChildren(int *status)
250 while (1)
252 if (!vms_jobsefnmask)
254 *status = 0;
255 return;
258 *status = sys$wflor (32, vms_jobsefnmask);
260 return;
262 #endif
265 /* Notice that a child died.
266 reap_children should be called when convenient. */
267 RETSIGTYPE
268 child_handler (sig)
269 int sig;
271 ++dead_children;
273 if (debug_flag)
274 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
277 extern int shell_function_pid, shell_function_completed;
279 /* Reap dead children, storing the returned status and the new command
280 state (`cs_finished') in the `file' member of the `struct child' for the
281 dead child, and removing the child from the chain. If BLOCK nonzero,
282 reap at least one child, waiting for it to die if necessary. If ERR is
283 nonzero, print an error message first. */
285 void
286 reap_children (block, err)
287 int block, err;
289 WAIT_T status;
291 while ((children != 0 || shell_function_pid != 0) &&
292 (block || dead_children > 0))
294 int remote = 0;
295 register int pid;
296 int exit_code, exit_sig, coredump;
297 register struct child *lastc, *c;
298 int child_failed;
299 int any_remote, any_local;
301 if (err && dead_children == 0)
303 /* We might block for a while, so let the user know why. */
304 fflush (stdout);
305 error ("*** Waiting for unfinished jobs....");
308 /* We have one less dead child to reap.
309 The test and decrement are not atomic; if it is compiled into:
310 register = dead_children - 1;
311 dead_children = register;
312 a SIGCHLD could come between the two instructions.
313 child_handler increments dead_children.
314 The second instruction here would lose that increment. But the
315 only effect of dead_children being wrong is that we might wait
316 longer than necessary to reap a child, and lose some parallelism;
317 and we might print the "Waiting for unfinished jobs" message above
318 when not necessary. */
320 if (dead_children > 0)
321 --dead_children;
323 any_remote = 0;
324 any_local = shell_function_pid != 0;
325 for (c = children; c != 0; c = c->next)
327 any_remote |= c->remote;
328 any_local |= ! c->remote;
329 if (debug_flag)
330 printf ("Live child 0x%08lx PID %d%s\n",
331 (unsigned long int) c,
332 c->pid, c->remote ? " (remote)" : "");
333 #ifdef VMS
334 break;
335 #endif
338 /* First, check for remote children. */
339 if (any_remote)
340 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
341 else
342 pid = 0;
344 if (pid < 0)
346 remote_status_lose:
347 #ifdef EINTR
348 if (errno == EINTR)
349 continue;
350 #endif
351 pfatal_with_name ("remote_status");
353 else if (pid == 0)
355 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
356 /* No remote children. Check for local children. */
358 if (any_local)
360 #ifdef VMS
361 vmsWaitForChildren (&status);
362 pid = c->pid;
363 #else
364 #ifdef WAIT_NOHANG
365 if (!block)
366 pid = WAIT_NOHANG (&status);
367 else
368 #endif
369 pid = wait (&status);
370 #endif /* !VMS */
372 else
373 pid = 0;
375 if (pid < 0)
377 #ifdef EINTR
378 if (errno == EINTR)
379 continue;
380 #endif
381 pfatal_with_name ("wait");
383 else if (pid == 0)
385 /* No local children. */
386 if (block && any_remote)
388 /* Now try a blocking wait for a remote child. */
389 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
390 if (pid < 0)
391 goto remote_status_lose;
392 else if (pid == 0)
393 /* No remote children either. Finally give up. */
394 break;
395 else
396 /* We got a remote child. */
397 remote = 1;
399 else
400 break;
402 else
404 /* Chop the status word up. */
405 exit_code = WEXITSTATUS (status);
406 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
407 coredump = WCOREDUMP (status);
409 #else /* __MSDOS__, Amiga, WINDOWS32. */
410 #ifdef __MSDOS__
411 /* Life is very different on MSDOS. */
412 pid = dos_pid - 1;
413 status = dos_status;
414 exit_code = WEXITSTATUS (status);
415 if (exit_code == 0xff)
416 exit_code = -1;
417 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
418 coredump = 0;
419 #endif /* __MSDOS__ */
420 #ifdef _AMIGA
421 /* Same on Amiga */
422 pid = amiga_pid - 1;
423 status = amiga_status;
424 exit_code = amiga_status;
425 exit_sig = 0;
426 coredump = 0;
427 #endif /* _AMIGA */
428 #ifdef WINDOWS32
430 HANDLE hPID;
431 int err;
433 /* wait for anything to finish */
434 if (hPID = process_wait_for_any()) {
436 /* was an error found on this process? */
437 err = process_last_err(hPID);
439 /* get exit data */
440 exit_code = process_exit_code(hPID);
442 if (err)
443 fprintf(stderr, "make (e=%d): %s",
444 exit_code, map_windows32_error_to_string(exit_code));
446 exit_sig = process_signal(hPID);
448 /* cleanup process */
449 process_cleanup(hPID);
451 if (dos_batch_file) {
452 remove (dos_bname);
453 remove (dos_bename);
454 dos_batch_file = 0;
457 coredump = 0;
459 pid = (int) hPID;
461 #endif /* WINDOWS32 */
462 #endif /* Not __MSDOS__ */
464 else
465 /* We got a remote child. */
466 remote = 1;
468 /* Check if this is the child of the `shell' function. */
469 if (!remote && pid == shell_function_pid)
471 /* It is. Leave an indicator for the `shell' function. */
472 if (exit_sig == 0 && exit_code == 127)
473 shell_function_completed = -1;
474 else
475 shell_function_completed = 1;
476 break;
479 child_failed = exit_sig != 0 || exit_code != 0;
481 /* Search for a child matching the deceased one. */
482 lastc = 0;
483 for (c = children; c != 0; lastc = c, c = c->next)
484 if (c->remote == remote && c->pid == pid)
485 break;
487 if (c == 0)
489 /* An unknown child died. */
490 char buf[100];
491 sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
492 if (child_failed)
493 child_error (buf, exit_code, exit_sig, coredump,
494 ignore_errors_flag);
495 else
496 error ("%s finished.", buf);
498 else
500 if (debug_flag)
501 printf ("Reaping %s child 0x%08lx PID %d%s\n",
502 child_failed ? "losing" : "winning",
503 (unsigned long int) c,
504 c->pid, c->remote ? " (remote)" : "");
506 /* If this child had the good stdin, say it is now free. */
507 if (c->good_stdin)
508 good_stdin_used = 0;
510 if (child_failed && !c->noerror && !ignore_errors_flag)
512 /* The commands failed. Write an error message,
513 delete non-precious targets, and abort. */
514 static int delete_on_error = -1;
515 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
516 c->file->update_status = 2;
517 if (delete_on_error == -1)
519 struct file *f = lookup_file (".DELETE_ON_ERROR");
520 delete_on_error = f != 0 && f->is_target;
522 if (exit_sig != 0 || delete_on_error)
523 delete_child_targets (c);
525 else
527 if (child_failed)
529 /* The commands failed, but we don't care. */
530 child_error (c->file->name,
531 exit_code, exit_sig, coredump, 1);
532 child_failed = 0;
535 /* If there are more commands to run, try to start them. */
536 if (job_next_command (c))
538 if (handling_fatal_signal)
540 /* Never start new commands while we are dying.
541 Since there are more commands that wanted to be run,
542 the target was not completely remade. So we treat
543 this as if a command had failed. */
544 c->file->update_status = 2;
546 else
548 /* Check again whether to start remotely.
549 Whether or not we want to changes over time.
550 Also, start_remote_job may need state set up
551 by start_remote_job_p. */
552 c->remote = start_remote_job_p ();
553 start_job_command (c);
554 /* Fatal signals are left blocked in case we were
555 about to put that child on the chain. But it is
556 already there, so it is safe for a fatal signal to
557 arrive now; it will clean up this child's targets. */
558 unblock_sigs ();
559 if (c->file->command_state == cs_running)
560 /* We successfully started the new command.
561 Loop to reap more children. */
562 continue;
565 if (c->file->update_status != 0)
566 /* We failed to start the commands. */
567 delete_child_targets (c);
569 else
570 /* There are no more commands. We got through them all
571 without an unignored error. Now the target has been
572 successfully updated. */
573 c->file->update_status = 0;
576 /* When we get here, all the commands for C->file are finished
577 (or aborted) and C->file->update_status contains 0 or 2. But
578 C->file->command_state is still cs_running if all the commands
579 ran; notice_finish_file looks for cs_running to tell it that
580 it's interesting to check the file's modtime again now. */
582 if (! handling_fatal_signal)
583 /* Notice if the target of the commands has been changed.
584 This also propagates its values for command_state and
585 update_status to its also_make files. */
586 notice_finished_file (c->file);
588 if (debug_flag)
589 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
590 (unsigned long int) c,
591 c->pid, c->remote ? " (remote)" : "");
593 /* Block fatal signals while frobnicating the list, so that
594 children and job_slots_used are always consistent. Otherwise
595 a fatal signal arriving after the child is off the chain and
596 before job_slots_used is decremented would believe a child was
597 live and call reap_children again. */
598 block_sigs ();
600 /* Remove the child from the chain and free it. */
601 if (lastc == 0)
602 children = c->next;
603 else
604 lastc->next = c->next;
605 if (! handling_fatal_signal) /* Don't bother if about to die. */
606 free_child (c);
608 /* There is now another slot open. */
609 if (job_slots_used > 0)
610 --job_slots_used;
612 unblock_sigs ();
614 /* If the job failed, and the -k flag was not given, die,
615 unless we are already in the process of dying. */
616 if (!err && child_failed && !keep_going_flag &&
617 /* fatal_error_signal will die with the right signal. */
618 !handling_fatal_signal)
619 die (2);
622 /* Only block for one child. */
623 block = 0;
625 return;
628 /* Free the storage allocated for CHILD. */
630 static void
631 free_child (child)
632 register struct child *child;
634 if (child->command_lines != 0)
636 register unsigned int i;
637 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
638 free (child->command_lines[i]);
639 free ((char *) child->command_lines);
642 if (child->environment != 0)
644 register char **ep = child->environment;
645 while (*ep != 0)
646 free (*ep++);
647 free ((char *) child->environment);
650 free ((char *) child);
653 #ifdef POSIX
654 extern sigset_t fatal_signal_set;
655 #endif
657 void
658 block_sigs ()
660 #ifdef POSIX
661 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
662 #else
663 #ifdef HAVE_SIGSETMASK
664 (void) sigblock (fatal_signal_mask);
665 #endif
666 #endif
669 #ifdef POSIX
670 void
671 unblock_sigs ()
673 sigset_t empty;
674 sigemptyset (&empty);
675 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
677 #endif
679 /* Start a job to run the commands specified in CHILD.
680 CHILD is updated to reflect the commands and ID of the child process.
682 NOTE: On return fatal signals are blocked! The caller is responsible
683 for calling `unblock_sigs', once the new child is safely on the chain so
684 it can be cleaned up in the event of a fatal signal. */
686 static void
687 start_job_command (child)
688 register struct child *child;
690 #ifndef _AMIGA
691 static int bad_stdin = -1;
692 #endif
693 register char *p;
694 int flags;
695 #ifdef VMS
696 char *argv;
697 #else
698 char **argv;
699 #endif
701 /* Combine the flags parsed for the line itself with
702 the flags specified globally for this target. */
703 flags = (child->file->command_flags
704 | child->file->cmds->lines_flags[child->command_line - 1]);
706 p = child->command_ptr;
707 child->noerror = flags & COMMANDS_NOERROR;
709 while (*p != '\0')
711 if (*p == '@')
712 flags |= COMMANDS_SILENT;
713 else if (*p == '+')
714 flags |= COMMANDS_RECURSE;
715 else if (*p == '-')
716 child->noerror = 1;
717 else if (!isblank (*p) && *p != '+')
718 break;
719 ++p;
722 /* If -q was given, just say that updating `failed'. The exit status of
723 1 tells the user that -q is saying `something to do'; the exit status
724 for a random error is 2. */
725 if (question_flag && !(flags & COMMANDS_RECURSE))
727 child->file->update_status = 1;
728 notice_finished_file (child->file);
729 return;
732 /* There may be some preceding whitespace left if there
733 was nothing but a backslash on the first line. */
734 p = next_token (p);
736 /* Figure out an argument list from this command line. */
739 char *end = 0;
740 #ifdef VMS
741 argv = p;
742 #else
743 argv = construct_command_argv (p, &end, child->file);
744 #endif
745 if (end == NULL)
746 child->command_ptr = NULL;
747 else
749 *end++ = '\0';
750 child->command_ptr = end;
754 if (touch_flag && !(flags & COMMANDS_RECURSE))
756 /* Go on to the next command. It might be the recursive one.
757 We construct ARGV only to find the end of the command line. */
758 #ifndef VMS
759 free (argv[0]);
760 free ((char *) argv);
761 #endif
762 argv = 0;
765 if (argv == 0)
767 next_command:
768 /* This line has no commands. Go to the next. */
769 if (job_next_command (child))
770 start_job_command (child);
771 else
773 /* No more commands. All done. */
774 child->file->update_status = 0;
775 notice_finished_file (child->file);
777 return;
780 /* Print out the command. If silent, we call `message' with null so it
781 can log the working directory before the command's own error messages
782 appear. */
784 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
785 ? "%s" : (char *) 0, p);
787 /* Optimize an empty command. People use this for timestamp rules,
788 and forking a useless shell all the time leads to inefficiency. */
790 if (
791 #ifdef __MSDOS__
792 unixy_shell /* the test is complicated and we already did it */
793 #else
794 (argv[0] && !strcmp(argv[0], "/bin/sh"))
795 #endif
796 && (argv[1] && !strcmp(argv[1], "-c"))
797 && (argv[2] && !strcmp(argv[2], ":"))
798 && argv[3] == NULL)
800 set_command_state (child->file, cs_running);
801 goto next_command;
804 /* Tell update_goal_chain that a command has been started on behalf of
805 this target. It is important that this happens here and not in
806 reap_children (where we used to do it), because reap_children might be
807 reaping children from a different target. We want this increment to
808 guaranteedly indicate that a command was started for the dependency
809 chain (i.e., update_file recursion chain) we are processing. */
811 ++commands_started;
813 /* If -n was given, recurse to get the next line in the sequence. */
815 if (just_print_flag && !(flags & COMMANDS_RECURSE))
817 #ifndef VMS
818 free (argv[0]);
819 free ((char *) argv);
820 #endif
821 goto next_command;
824 /* Flush the output streams so they won't have things written twice. */
826 fflush (stdout);
827 fflush (stderr);
829 #ifndef VMS
830 #ifndef WINDOWS32
831 #ifndef _AMIGA
832 #ifndef __MSDOS__
834 /* Set up a bad standard input that reads from a broken pipe. */
836 if (bad_stdin == -1)
838 /* Make a file descriptor that is the read end of a broken pipe.
839 This will be used for some children's standard inputs. */
840 int pd[2];
841 if (pipe (pd) == 0)
843 /* Close the write side. */
844 (void) close (pd[1]);
845 /* Save the read side. */
846 bad_stdin = pd[0];
848 /* Set the descriptor to close on exec, so it does not litter any
849 child's descriptor table. When it is dup2'd onto descriptor 0,
850 that descriptor will not close on exec. */
851 #ifdef FD_SETFD
852 #ifndef FD_CLOEXEC
853 #define FD_CLOEXEC 1
854 #endif
855 (void) fcntl (bad_stdin, F_SETFD, FD_CLOEXEC);
856 #endif
860 #endif /* !AMIGA */
861 #endif /* !WINDOWS32 */
862 #endif /* !__MSDOS__ */
864 /* Decide whether to give this child the `good' standard input
865 (one that points to the terminal or whatever), or the `bad' one
866 that points to the read side of a broken pipe. */
868 child->good_stdin = !good_stdin_used;
869 if (child->good_stdin)
870 good_stdin_used = 1;
872 #endif /* Not VMS */
874 child->deleted = 0;
876 #ifndef _AMIGA
877 /* Set up the environment for the child. */
878 if (child->environment == 0)
879 child->environment = target_environment (child->file);
880 #endif
882 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
884 #ifndef VMS
885 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
886 if (child->remote)
888 int is_remote, id, used_stdin;
889 if (start_remote_job (argv, child->environment,
890 child->good_stdin ? 0 : bad_stdin,
891 &is_remote, &id, &used_stdin))
892 goto error;
893 else
895 if (child->good_stdin && !used_stdin)
897 child->good_stdin = 0;
898 good_stdin_used = 0;
900 child->remote = is_remote;
901 child->pid = id;
904 else
905 #endif /* !VMS */
907 /* Fork the child process. */
909 char **parent_environ;
911 block_sigs ();
913 child->remote = 0;
915 #ifdef VMS
917 if (!child_execute_job (argv, child)) {
918 /* Fork failed! */
919 perror_with_name ("vfork", "");
920 goto error;
923 #else
925 parent_environ = environ;
926 child->pid = vfork ();
927 environ = parent_environ; /* Restore value child may have clobbered. */
928 if (child->pid == 0)
930 /* We are the child side. */
931 unblock_sigs ();
932 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
933 argv, child->environment);
935 else if (child->pid < 0)
937 /* Fork failed! */
938 unblock_sigs ();
939 perror_with_name ("vfork", "");
940 goto error;
942 #endif /* !VMS */
945 #else /* __MSDOS__ or Amiga or WINDOWS32 */
946 #ifdef __MSDOS__
948 int proc_return;
950 block_sigs ();
951 dos_status = 0;
953 /* We call `system' to do the job of the SHELL, since stock DOS
954 shell is too dumb. Our `system' knows how to handle long
955 command lines even if pipes/redirection is needed; it will only
956 call COMMAND.COM when its internal commands are used. */
957 if (execute_by_shell)
959 char *cmdline = argv[0];
960 /* We don't have a way to pass environment to `system',
961 so we need to save and restore ours, sigh... */
962 char **parent_environ = environ;
964 environ = child->environment;
966 /* If we have a *real* shell, tell `system' to call
967 it to do everything for us. */
968 if (unixy_shell)
970 /* A *real* shell on MSDOS may not support long
971 command lines the DJGPP way, so we must use `system'. */
972 cmdline = argv[2]; /* get past "shell -c" */
975 dos_command_running = 1;
976 proc_return = system (cmdline);
977 dos_command_running = 0;
978 environ = parent_environ;
979 execute_by_shell = 0; /* for the next time */
981 else
983 dos_command_running = 1;
984 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
985 dos_command_running = 0;
988 if (proc_return == -1)
989 dos_status |= 0xff;
990 else
991 dos_status |= (proc_return & 0xff);
992 ++dead_children;
993 child->pid = dos_pid++;
995 #endif /* __MSDOS__ */
996 #ifdef _AMIGA
997 amiga_status = MyExecute (argv);
999 ++dead_children;
1000 child->pid = amiga_pid++;
1001 if (amiga_batch_file)
1003 amiga_batch_file = 0;
1004 DeleteFile (amiga_bname); /* Ignore errors. */
1006 #endif /* Amiga */
1007 #ifdef WINDOWS32
1009 HANDLE hPID;
1010 char* arg0;
1012 /* make UNC paths safe for CreateProcess -- backslash format */
1013 arg0 = argv[0];
1014 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1015 for ( ; arg0 && *arg0; arg0++)
1016 if (*arg0 == '/')
1017 *arg0 = '\\';
1019 /* make sure CreateProcess() has Path it needs */
1020 sync_Path_environment();
1022 hPID = process_easy(argv, child->environment);
1024 if (hPID != INVALID_HANDLE_VALUE)
1025 child->pid = (int) hPID;
1026 else {
1027 int i;
1028 unblock_sigs();
1029 fprintf(stderr,
1030 "process_easy() failed failed to launch process (e=%d)\n",
1031 process_last_err(hPID));
1032 for (i = 0; argv[i]; i++)
1033 fprintf(stderr, "%s ", argv[i]);
1034 fprintf(stderr, "\nCounted %d args in failed launch\n", i);
1037 #endif /* WINDOWS32 */
1038 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1040 /* We are the parent side. Set the state to
1041 say the commands are running and return. */
1043 set_command_state (child->file, cs_running);
1045 /* Free the storage used by the child's argument list. */
1046 #ifndef VMS
1047 free (argv[0]);
1048 free ((char *) argv);
1049 #endif
1051 return;
1053 error:
1054 child->file->update_status = 2;
1055 notice_finished_file (child->file);
1056 return;
1059 /* Try to start a child running.
1060 Returns nonzero if the child was started (and maybe finished), or zero if
1061 the load was too high and the child was put on the `waiting_jobs' chain. */
1063 static int
1064 start_waiting_job (c)
1065 struct child *c;
1067 /* If we can start a job remotely, we always want to, and don't care about
1068 the local load average. We record that the job should be started
1069 remotely in C->remote for start_job_command to test. */
1071 c->remote = start_remote_job_p ();
1073 /* If this job is to be started locally, and we are already running
1074 some jobs, make this one wait if the load average is too high. */
1075 if (!c->remote && job_slots_used > 0 && load_too_high ())
1077 /* Put this child on the chain of children waiting
1078 for the load average to go down. */
1079 set_command_state (c->file, cs_running);
1080 c->next = waiting_jobs;
1081 waiting_jobs = c;
1082 return 0;
1085 /* Start the first command; reap_children will run later command lines. */
1086 start_job_command (c);
1088 switch (c->file->command_state)
1090 case cs_running:
1091 c->next = children;
1092 if (debug_flag)
1093 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
1094 (unsigned long int) c,
1095 c->pid, c->remote ? " (remote)" : "");
1096 children = c;
1097 /* One more job slot is in use. */
1098 ++job_slots_used;
1099 unblock_sigs ();
1100 break;
1102 case cs_not_started:
1103 /* All the command lines turned out to be empty. */
1104 c->file->update_status = 0;
1105 /* FALLTHROUGH */
1107 case cs_finished:
1108 notice_finished_file (c->file);
1109 free_child (c);
1110 break;
1112 default:
1113 assert (c->file->command_state == cs_finished);
1114 break;
1117 return 1;
1120 /* Create a `struct child' for FILE and start its commands running. */
1122 void
1123 new_job (file)
1124 register struct file *file;
1126 register struct commands *cmds = file->cmds;
1127 register struct child *c;
1128 char **lines;
1129 register unsigned int i;
1131 /* Let any previously decided-upon jobs that are waiting
1132 for the load to go down start before this new one. */
1133 start_waiting_jobs ();
1135 /* Reap any children that might have finished recently. */
1136 reap_children (0, 0);
1138 /* Chop the commands up into lines if they aren't already. */
1139 chop_commands (cmds);
1141 if (job_slots != 0)
1142 /* Wait for a job slot to be freed up. */
1143 while (job_slots_used == job_slots)
1144 reap_children (1, 0);
1146 /* Expand the command lines and store the results in LINES. */
1147 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1148 for (i = 0; i < cmds->ncommand_lines; ++i)
1150 /* Collapse backslash-newline combinations that are inside variable
1151 or function references. These are left alone by the parser so
1152 that they will appear in the echoing of commands (where they look
1153 nice); and collapsed by construct_command_argv when it tokenizes.
1154 But letting them survive inside function invocations loses because
1155 we don't want the functions to see them as part of the text. */
1157 char *in, *out, *ref;
1159 /* IN points to where in the line we are scanning.
1160 OUT points to where in the line we are writing.
1161 When we collapse a backslash-newline combination,
1162 IN gets ahead of OUT. */
1164 in = out = cmds->command_lines[i];
1165 while ((ref = index (in, '$')) != 0)
1167 ++ref; /* Move past the $. */
1169 if (out != in)
1170 /* Copy the text between the end of the last chunk
1171 we processed (where IN points) and the new chunk
1172 we are about to process (where REF points). */
1173 bcopy (in, out, ref - in);
1175 /* Move both pointers past the boring stuff. */
1176 out += ref - in;
1177 in = ref;
1179 if (*ref == '(' || *ref == '{')
1181 char openparen = *ref;
1182 char closeparen = openparen == '(' ? ')' : '}';
1183 int count;
1184 char *p;
1186 *out++ = *in++; /* Copy OPENPAREN. */
1187 /* IN now points past the opening paren or brace.
1188 Count parens or braces until it is matched. */
1189 count = 0;
1190 while (*in != '\0')
1192 if (*in == closeparen && --count < 0)
1193 break;
1194 else if (*in == '\\' && in[1] == '\n')
1196 /* We have found a backslash-newline inside a
1197 variable or function reference. Eat it and
1198 any following whitespace. */
1200 int quoted = 0;
1201 for (p = in - 1; p > ref && *p == '\\'; --p)
1202 quoted = !quoted;
1204 if (quoted)
1205 /* There were two or more backslashes, so this is
1206 not really a continuation line. We don't collapse
1207 the quoting backslashes here as is done in
1208 collapse_continuations, because the line will
1209 be collapsed again after expansion. */
1210 *out++ = *in++;
1211 else
1213 /* Skip the backslash, newline and
1214 any following whitespace. */
1215 in = next_token (in + 2);
1217 /* Discard any preceding whitespace that has
1218 already been written to the output. */
1219 while (out > ref && isblank (out[-1]))
1220 --out;
1222 /* Replace it all with a single space. */
1223 *out++ = ' ';
1226 else
1228 if (*in == openparen)
1229 ++count;
1231 *out++ = *in++;
1237 /* There are no more references in this line to worry about.
1238 Copy the remaining uninteresting text to the output. */
1239 if (out != in)
1240 strcpy (out, in);
1242 /* Finally, expand the line. */
1243 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1244 file);
1247 /* Start the command sequence, record it in a new
1248 `struct child', and add that to the chain. */
1250 c = (struct child *) xmalloc (sizeof (struct child));
1251 c->file = file;
1252 c->command_lines = lines;
1253 c->command_line = 0;
1254 c->command_ptr = 0;
1255 c->environment = 0;
1257 /* Fetch the first command line to be run. */
1258 job_next_command (c);
1260 /* The job is now primed. Start it running.
1261 (This will notice if there are in fact no commands.) */
1262 (void)start_waiting_job (c);
1264 if (job_slots == 1)
1265 /* Since there is only one job slot, make things run linearly.
1266 Wait for the child to die, setting the state to `cs_finished'. */
1267 while (file->command_state == cs_running)
1268 reap_children (1, 0);
1270 return;
1273 /* Move CHILD's pointers to the next command for it to execute.
1274 Returns nonzero if there is another command. */
1276 static int
1277 job_next_command (child)
1278 struct child *child;
1280 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1282 /* There are no more lines in the expansion of this line. */
1283 if (child->command_line == child->file->cmds->ncommand_lines)
1285 /* There are no more lines to be expanded. */
1286 child->command_ptr = 0;
1287 return 0;
1289 else
1290 /* Get the next line to run. */
1291 child->command_ptr = child->command_lines[child->command_line++];
1293 return 1;
1296 static int
1297 load_too_high ()
1299 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1300 return 1;
1301 #else
1302 double load;
1304 if (max_load_average < 0)
1305 return 0;
1307 make_access ();
1308 if (getloadavg (&load, 1) != 1)
1310 static int lossage = -1;
1311 /* Complain only once for the same error. */
1312 if (lossage == -1 || errno != lossage)
1314 if (errno == 0)
1315 /* An errno value of zero means getloadavg is just unsupported. */
1316 error ("cannot enforce load limits on this operating system");
1317 else
1318 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1320 lossage = errno;
1321 load = 0;
1323 user_access ();
1325 return load >= max_load_average;
1326 #endif
1329 /* Start jobs that are waiting for the load to be lower. */
1331 void
1332 start_waiting_jobs ()
1334 struct child *job;
1336 if (waiting_jobs == 0)
1337 return;
1341 /* Check for recently deceased descendants. */
1342 reap_children (0, 0);
1344 /* Take a job off the waiting list. */
1345 job = waiting_jobs;
1346 waiting_jobs = job->next;
1348 /* Try to start that job. We break out of the loop as soon
1349 as start_waiting_job puts one back on the waiting list. */
1351 while (start_waiting_job (job) && waiting_jobs != 0);
1353 return;
1356 #ifndef WINDOWS32
1357 #ifdef VMS
1358 #include <descrip.h>
1359 #include <clidef.h>
1361 /* This is called as an AST when a child process dies (it won't get
1362 interrupted by anything except a higher level AST).
1364 int vmsHandleChildTerm(struct child *child)
1366 int status;
1367 register struct child *lastc, *c;
1368 int child_failed;
1370 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1372 lib$free_ef(&child->efn);
1374 (void) sigblock (fatal_signal_mask);
1376 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1378 /* Search for a child matching the deceased one. */
1379 lastc = 0;
1380 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1381 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1382 #else
1383 c = child;
1384 #endif
1386 if (child_failed && !c->noerror && !ignore_errors_flag)
1388 /* The commands failed. Write an error message,
1389 delete non-precious targets, and abort. */
1390 child_error (c->file->name, c->cstatus, 0, 0, 0);
1391 c->file->update_status = 1;
1392 delete_child_targets (c);
1394 else
1396 if (child_failed)
1398 /* The commands failed, but we don't care. */
1399 child_error (c->file->name, c->cstatus, 0, 0, 1);
1400 child_failed = 0;
1403 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1404 /* If there are more commands to run, try to start them. */
1405 start_job (c);
1407 switch (c->file->command_state)
1409 case cs_running:
1410 /* Successfully started. */
1411 break;
1413 case cs_finished:
1414 if (c->file->update_status != 0) {
1415 /* We failed to start the commands. */
1416 delete_child_targets (c);
1418 break;
1420 default:
1421 error ("internal error: `%s' command_state \
1422 %d in child_handler", c->file->name);
1423 abort ();
1424 break;
1426 #endif /* RECURSIVEJOBS */
1429 /* Set the state flag to say the commands have finished. */
1430 c->file->command_state = cs_finished;
1431 notice_finished_file (c->file);
1433 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1434 /* Remove the child from the chain and free it. */
1435 if (lastc == 0)
1436 children = c->next;
1437 else
1438 lastc->next = c->next;
1439 free_child (c);
1440 #endif /* RECURSIVEJOBS */
1442 /* There is now another slot open. */
1443 if (job_slots_used > 0)
1444 --job_slots_used;
1446 /* If the job failed, and the -k flag was not given, die. */
1447 if (child_failed && !keep_going_flag)
1448 die (EXIT_FAILURE);
1450 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1452 return 1;
1455 /* VMS:
1456 Spawn a process executing the command in ARGV and return its pid. */
1458 #define MAXCMDLEN 200
1461 child_execute_job (argv, child)
1462 char *argv;
1463 struct child *child;
1465 int i;
1466 static struct dsc$descriptor_s cmddsc;
1467 #ifndef DONTWAITFORCHILD
1468 int spflags = 0;
1469 #else
1470 int spflags = CLI$M_NOWAIT;
1471 #endif
1472 int status;
1473 char cmd[4096],*p,*c;
1474 char comname[50];
1476 /* Remove backslashes */
1477 for (p = argv, c = cmd; *p; p++,c++)
1479 if (*p == '\\') p++;
1480 *c = *p;
1482 *c = *p;
1484 /* check for maximum dcl length and create *.com file if neccesary */
1486 comname[0] = '\0';
1488 if (strlen (cmd) > MAXCMDLEN)
1490 FILE *outfile;
1491 char tmp;
1493 strcpy (comname, "sys$scratch:CMDXXXXXX.COM");
1494 (void) mktemp (comname);
1496 outfile = fopen (comname, "w");
1497 if (outfile == 0)
1498 pfatal_with_name (comname);
1500 fprintf (outfile, "$ ");
1501 c = cmd;
1503 while (c)
1505 p = strchr (c, ',');
1506 if ((p == NULL) || (p-c > MAXCMDLEN))
1507 p = strchr (c, ' ');
1508 if (p != NULL)
1510 p++;
1511 tmp = *p;
1512 *p = '\0';
1514 else
1515 tmp = '\0';
1516 fprintf (outfile, "%s%s\n", c, (tmp == '\0')?"":" -");
1517 if (p != NULL)
1518 *p = tmp;
1519 c = p;
1522 fclose (outfile);
1524 sprintf (cmd, "$ @%s", comname);
1526 if (debug_flag)
1527 printf ("Executing %s instead\n", cmd);
1530 cmddsc.dsc$w_length = strlen(cmd);
1531 cmddsc.dsc$a_pointer = cmd;
1532 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
1533 cmddsc.dsc$b_class = DSC$K_CLASS_S;
1535 child->efn = 0;
1536 while (child->efn < 32 || child->efn > 63)
1538 status = lib$get_ef(&child->efn);
1539 if (!(status & 1))
1540 return 0;
1543 sys$clref(child->efn);
1545 vms_jobsefnmask |= (1 << (child->efn - 32));
1547 #ifndef DONTWAITFORCHILD
1548 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1549 &child->efn,0,0);
1550 vmsHandleChildTerm(child);
1551 #else
1552 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1553 &child->efn,vmsHandleChildTerm,child);
1554 #endif
1556 if (!(status & 1))
1558 printf("Error spawning, %d\n",status);
1559 fflush(stdout);
1562 unlink (comname);
1564 return (status & 1);
1567 #else /* !VMS */
1569 #if !defined (_AMIGA) && !defined (__MSDOS__)
1570 /* UNIX:
1571 Replace the current process with one executing the command in ARGV.
1572 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1573 the environment of the new program. This function does not return. */
1575 void
1576 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1577 int stdin_fd, stdout_fd;
1578 char **argv, **envp;
1580 if (stdin_fd != 0)
1581 (void) dup2 (stdin_fd, 0);
1582 if (stdout_fd != 1)
1583 (void) dup2 (stdout_fd, 1);
1584 if (stdin_fd != 0)
1585 (void) close (stdin_fd);
1586 if (stdout_fd != 1)
1587 (void) close (stdout_fd);
1589 /* Run the command. */
1590 exec_command (argv, envp);
1592 #endif /* !AMIGA && !__MSDOS__ */
1593 #endif /* !VMS */
1594 #endif /* !WINDOWS32 */
1596 #ifndef _AMIGA
1597 /* Replace the current process with one running the command in ARGV,
1598 with environment ENVP. This function does not return. */
1600 void
1601 exec_command (argv, envp)
1602 char **argv, **envp;
1604 #ifdef VMS
1605 /* Run the program. */
1606 execve (argv[0], argv, envp);
1607 perror_with_name ("execve: ", argv[0]);
1608 _exit (EXIT_FAILURE);
1609 #else
1610 /* Be the user, permanently. */
1611 child_access ();
1613 /* Run the program. */
1614 environ = envp;
1615 execvp (argv[0], argv);
1617 switch (errno)
1619 case ENOENT:
1620 error ("%s: Command not found", argv[0]);
1621 break;
1622 case ENOEXEC:
1624 /* The file is not executable. Try it as a shell script. */
1625 extern char *getenv ();
1626 char *shell;
1627 char **new_argv;
1628 int argc;
1630 shell = getenv ("SHELL");
1631 if (shell == 0)
1632 shell = default_shell;
1634 argc = 1;
1635 while (argv[argc] != 0)
1636 ++argc;
1638 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1639 new_argv[0] = shell;
1640 new_argv[1] = argv[0];
1641 while (argc > 0)
1643 new_argv[1 + argc] = argv[argc];
1644 --argc;
1647 execvp (shell, new_argv);
1648 if (errno == ENOENT)
1649 error ("%s: Shell program not found", shell);
1650 else
1651 perror_with_name ("execvp: ", shell);
1652 break;
1655 default:
1656 perror_with_name ("execvp: ", argv[0]);
1657 break;
1660 _exit (127);
1661 #endif /* !VMS */
1663 #else /* On Amiga */
1664 void exec_command (argv)
1665 char **argv;
1667 MyExecute (argv);
1670 void clean_tmp (void)
1672 DeleteFile (amiga_bname);
1675 #endif /* On Amiga */
1677 #ifndef VMS
1678 /* Figure out the argument list necessary to run LINE as a command. Try to
1679 avoid using a shell. This routine handles only ' quoting, and " quoting
1680 when no backslash, $ or ` characters are seen in the quotes. Starting
1681 quotes may be escaped with a backslash. If any of the characters in
1682 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1683 is the first word of a line, the shell is used.
1685 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1686 If *RESTP is NULL, newlines will be ignored.
1688 SHELL is the shell to use, or nil to use the default shell.
1689 IFS is the value of $IFS, or nil (meaning the default). */
1691 static char **
1692 construct_command_argv_internal (line, restp, shell, ifs)
1693 char *line, **restp;
1694 char *shell, *ifs;
1696 #ifdef __MSDOS__
1697 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
1698 We call `system' for anything that requires ``slow'' processing,
1699 because DOS shells are too dumb. When $SHELL points to a real
1700 (unix-style) shell, `system' just calls it to do everything. When
1701 $SHELL points to a DOS shell, `system' does most of the work
1702 internally, calling the shell only for its internal commands.
1703 However, it looks on the $PATH first, so you can e.g. have an
1704 external command named `mkdir'.
1706 Since we call `system', certain characters and commands below are
1707 actually not specific to COMMAND.COM, but to the DJGPP implementation
1708 of `system'. In particular:
1710 The shell wildcard characters are in DOS_CHARS because they will
1711 not be expanded if we call the child via `spawnXX'.
1713 The `;' is in DOS_CHARS, because our `system' knows how to run
1714 multiple commands on a single line.
1716 DOS_CHARS also include characters special to 4DOS/NDOS, so we
1717 won't have to tell one from another and have one more set of
1718 commands and special characters. */
1719 static char sh_chars_dos[] = "*?[];|<>%^&()";
1720 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1721 "copy", "ctty", "date", "del", "dir", "echo",
1722 "erase", "exit", "for", "goto", "if", "md",
1723 "mkdir", "path", "pause", "prompt", "rd",
1724 "rmdir", "rem", "ren", "rename", "set",
1725 "shift", "time", "type", "ver", "verify",
1726 "vol", ":", 0 };
1728 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1729 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
1730 "logout", "set", "umask", "wait", "while",
1731 "for", "case", "if", ":", ".", "break",
1732 "continue", "export", "read", "readonly",
1733 "shift", "times", "trap", "switch", 0 };
1735 char *sh_chars;
1736 char **sh_cmds;
1737 #else
1738 #ifdef _AMIGA
1739 static char sh_chars[] = "#;\"|<>()?*$`";
1740 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
1741 "rename", "set", "setenv", "date", "makedir",
1742 "skip", "else", "endif", "path", "prompt",
1743 "unset", "unsetenv", "version",
1744 0 };
1745 #else
1746 #ifdef WINDOWS32
1747 static char sh_chars_dos[] = "\"|<>";
1748 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1749 "copy", "ctty", "date", "del", "dir", "echo",
1750 "erase", "exit", "for", "goto", "if", "if", "md",
1751 "mkdir", "path", "pause", "prompt", "rem", "ren",
1752 "rename", "set", "shift", "time", "type",
1753 "ver", "verify", "vol", ":", 0 };
1754 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1755 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
1756 "logout", "set", "umask", "wait", "while", "for",
1757 "case", "if", ":", ".", "break", "continue",
1758 "export", "read", "readonly", "shift", "times",
1759 "trap", "switch", "test", 0 };
1760 char* sh_chars;
1761 char** sh_cmds;
1762 #else /* WINDOWS32 */
1763 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1764 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1765 "logout", "set", "umask", "wait", "while", "for",
1766 "case", "if", ":", ".", "break", "continue",
1767 "export", "read", "readonly", "shift", "times",
1768 "trap", "switch", 0 };
1769 #endif /* WINDOWS32 */
1770 #endif /* Amiga */
1771 #endif /* __MSDOS__ */
1772 register int i;
1773 register char *p;
1774 register char *ap;
1775 char *end;
1776 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
1777 char **new_argv = 0;
1778 #ifdef WINDOWS32
1779 int slow_flag = 0;
1781 if (no_default_sh_exe) {
1782 sh_cmds = sh_cmds_dos;
1783 sh_chars = sh_chars_dos;
1784 } else {
1785 sh_cmds = sh_cmds_sh;
1786 sh_chars = sh_chars_sh;
1788 #endif /* WINDOWS32 */
1790 if (restp != NULL)
1791 *restp = NULL;
1793 /* Make sure not to bother processing an empty line. */
1794 while (isblank (*line))
1795 ++line;
1796 if (*line == '\0')
1797 return 0;
1799 /* See if it is safe to parse commands internally. */
1800 if (shell == 0)
1801 shell = default_shell;
1802 #ifdef WINDOWS32
1803 else if (strcmp (shell, default_shell))
1805 char *s1 = _fullpath(NULL, shell, 0);
1806 char *s2 = _fullpath(NULL, default_shell, 0);
1808 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
1810 if (s1);
1811 free(s1);
1812 if (s2);
1813 free(s2);
1815 if (slow_flag)
1816 goto slow;
1817 #else /* not WINDOWS32 */
1818 #ifdef __MSDOS__
1819 else if (stricmp (shell, default_shell))
1821 extern int _is_unixy_shell (const char *_path);
1823 message (1, "$SHELL changed (was `%s', now `%s')", default_shell, shell);
1824 unixy_shell = _is_unixy_shell (shell);
1825 default_shell = shell;
1827 if (unixy_shell)
1829 sh_chars = sh_chars_sh;
1830 sh_cmds = sh_cmds_sh;
1832 else
1834 sh_chars = sh_chars_dos;
1835 sh_cmds = sh_cmds_dos;
1837 #else /* not __MSDOS__ */
1838 else if (strcmp (shell, default_shell))
1839 goto slow;
1840 #endif /* not __MSDOS__ */
1841 #endif /* not WINDOWS32 */
1843 if (ifs != 0)
1844 for (ap = ifs; *ap != '\0'; ++ap)
1845 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1846 goto slow;
1848 i = strlen (line) + 1;
1850 /* More than 1 arg per character is impossible. */
1851 new_argv = (char **) xmalloc (i * sizeof (char *));
1853 /* All the args can fit in a buffer as big as LINE is. */
1854 ap = new_argv[0] = (char *) xmalloc (i);
1855 end = ap + i;
1857 /* I is how many complete arguments have been found. */
1858 i = 0;
1859 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
1860 for (p = line; *p != '\0'; ++p)
1862 if (ap > end)
1863 abort ();
1865 if (instring)
1867 string_char:
1868 /* Inside a string, just copy any char except a closing quote
1869 or a backslash-newline combination. */
1870 if (*p == instring)
1872 instring = 0;
1873 if (ap == new_argv[0] || *(ap-1) == '\0')
1874 last_argument_was_empty = 1;
1876 else if (*p == '\\' && p[1] == '\n')
1877 goto swallow_escaped_newline;
1878 else if (*p == '\n' && restp != NULL)
1880 /* End of the command line. */
1881 *restp = p;
1882 goto end_of_line;
1884 /* Backslash, $, and ` are special inside double quotes.
1885 If we see any of those, punt.
1886 But on MSDOS, if we use COMMAND.COM, double and single
1887 quotes have the same effect. */
1888 else if (instring == '"' && index ("\\$`", *p) != 0 && unixy_shell)
1889 goto slow;
1890 else
1891 *ap++ = *p;
1893 else if (index (sh_chars, *p) != 0)
1894 /* Not inside a string, but it's a special char. */
1895 goto slow;
1896 #ifdef __MSDOS__
1897 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
1898 /* `...' is a wildcard in DJGPP. */
1899 goto slow;
1900 #endif
1901 else
1902 /* Not a special char. */
1903 switch (*p)
1905 case '=':
1906 /* Equals is a special character in leading words before the
1907 first word with no equals sign in it. This is not the case
1908 with sh -k, but we never get here when using nonstandard
1909 shell flags. */
1910 if (! seen_nonequals && unixy_shell)
1911 goto slow;
1912 word_has_equals = 1;
1913 *ap++ = '=';
1914 break;
1916 case '\\':
1917 /* Backslash-newline combinations are eaten. */
1918 if (p[1] == '\n')
1920 swallow_escaped_newline:
1922 /* Eat the backslash, the newline, and following whitespace,
1923 replacing it all with a single space. */
1924 p += 2;
1926 /* If there is a tab after a backslash-newline,
1927 remove it from the source line which will be echoed,
1928 since it was most likely used to line
1929 up the continued line with the previous one. */
1930 if (*p == '\t')
1931 strcpy (p, p + 1);
1933 if (instring)
1934 goto string_char;
1935 else
1937 if (ap != new_argv[i])
1938 /* Treat this as a space, ending the arg.
1939 But if it's at the beginning of the arg, it should
1940 just get eaten, rather than becoming an empty arg. */
1941 goto end_of_arg;
1942 else
1943 p = next_token (p) - 1;
1946 else if (p[1] != '\0')
1947 /* Copy and skip the following char. */
1948 *ap++ = *++p;
1949 break;
1951 case '\'':
1952 case '"':
1953 instring = *p;
1954 break;
1956 case '\n':
1957 if (restp != NULL)
1959 /* End of the command line. */
1960 *restp = p;
1961 goto end_of_line;
1963 else
1964 /* Newlines are not special. */
1965 *ap++ = '\n';
1966 break;
1968 case ' ':
1969 case '\t':
1970 end_of_arg:
1971 /* We have the end of an argument.
1972 Terminate the text of the argument. */
1973 *ap++ = '\0';
1974 new_argv[++i] = ap;
1975 last_argument_was_empty = 0;
1977 /* Update SEEN_NONEQUALS, which tells us if every word
1978 heretofore has contained an `='. */
1979 seen_nonequals |= ! word_has_equals;
1980 if (word_has_equals && ! seen_nonequals)
1981 /* An `=' in a word before the first
1982 word without one is magical. */
1983 goto slow;
1984 word_has_equals = 0; /* Prepare for the next word. */
1986 /* If this argument is the command name,
1987 see if it is a built-in shell command.
1988 If so, have the shell handle it. */
1989 if (i == 1)
1991 register int j;
1992 for (j = 0; sh_cmds[j] != 0; ++j)
1993 if (streq (sh_cmds[j], new_argv[0]))
1994 goto slow;
1997 /* Ignore multiple whitespace chars. */
1998 p = next_token (p);
1999 /* Next iteration should examine the first nonwhite char. */
2000 --p;
2001 break;
2003 default:
2004 *ap++ = *p;
2005 break;
2008 end_of_line:
2010 if (instring)
2011 /* Let the shell deal with an unterminated quote. */
2012 goto slow;
2014 /* Terminate the last argument and the argument list. */
2016 *ap = '\0';
2017 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2018 ++i;
2019 new_argv[i] = 0;
2021 if (i == 1)
2023 register int j;
2024 for (j = 0; sh_cmds[j] != 0; ++j)
2025 if (streq (sh_cmds[j], new_argv[0]))
2026 goto slow;
2029 if (new_argv[0] == 0)
2030 /* Line was empty. */
2031 return 0;
2032 else
2033 return new_argv;
2035 slow:;
2036 /* We must use the shell. */
2038 if (new_argv != 0)
2040 /* Free the old argument list we were working on. */
2041 free (new_argv[0]);
2042 free ((void *)new_argv);
2045 #ifdef __MSDOS__
2046 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2047 #endif
2049 #ifdef _AMIGA
2051 char *ptr;
2052 char *buffer;
2053 char *dptr;
2055 buffer = (char *)xmalloc (strlen (line)+1);
2057 ptr = line;
2058 for (dptr=buffer; *ptr; )
2060 if (*ptr == '\\' && ptr[1] == '\n')
2061 ptr += 2;
2062 else if (*ptr == '@') /* Kludge: multiline commands */
2064 ptr += 2;
2065 *dptr++ = '\n';
2067 else
2068 *dptr++ = *ptr++;
2070 *dptr = 0;
2072 new_argv = (char **) xmalloc(2 * sizeof(char *));
2073 new_argv[0] = buffer;
2074 new_argv[1] = 0;
2076 #else /* Not Amiga */
2077 #ifdef WINDOWS32
2079 * Not eating this whitespace caused things like
2081 * sh -c "\n"
2083 * which gave the shell fits. I think we have to eat
2084 * whitespace here, but this code should be considered
2085 * suspicious if things start failing....
2088 /* Make sure not to bother processing an empty line. */
2089 while (isspace (*line))
2090 ++line;
2091 if (*line == '\0')
2092 return 0;
2095 * only come here if no sh.exe command
2097 if (no_default_sh_exe)
2099 FILE *batch;
2100 dos_batch_file = 1;
2101 if (dos_bname == 0)
2103 dos_bname = tempnam (".", "mk");
2104 for (i = 0; dos_bname[i] != '\0'; ++i)
2105 if (dos_bname[i] == '/')
2106 dos_bname[i] = '\\';
2107 dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
2108 strcpy (dos_bename, dos_bname);
2109 strcat (dos_bname, ".bat");
2110 strcat (dos_bename, ".err");
2112 batch = fopen (dos_bename, "w"); /* Create a file. */
2113 if (batch != NULL)
2114 fclose (batch);
2115 batch = fopen (dos_bname, "w");
2116 fputs ("@echo off\n", batch);
2117 fputs (line, batch);
2118 fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
2119 fclose (batch);
2120 new_argv = (char **) xmalloc(2 * sizeof(char *));
2121 new_argv[0] = strdup (dos_bname);
2122 new_argv[1] = 0;
2124 else
2125 #endif /* WINDOWS32 */
2127 /* SHELL may be a multi-word command. Construct a command line
2128 "SHELL -c LINE", with all special chars in LINE escaped.
2129 Then recurse, expanding this command line to get the final
2130 argument list. */
2132 unsigned int shell_len = strlen (shell);
2133 static char minus_c[] = " -c ";
2134 unsigned int line_len = strlen (line);
2136 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2137 + (line_len * 2) + 1);
2139 ap = new_line;
2140 bcopy (shell, ap, shell_len);
2141 ap += shell_len;
2142 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2143 ap += sizeof (minus_c) - 1;
2144 for (p = line; *p != '\0'; ++p)
2146 if (restp != NULL && *p == '\n')
2148 *restp = p;
2149 break;
2151 else if (*p == '\\' && p[1] == '\n')
2153 /* Eat the backslash, the newline, and following whitespace,
2154 replacing it all with a single space (which is escaped
2155 from the shell). */
2156 p += 2;
2158 /* If there is a tab after a backslash-newline,
2159 remove it from the source line which will be echoed,
2160 since it was most likely used to line
2161 up the continued line with the previous one. */
2162 if (*p == '\t')
2163 bcopy (p + 1, p, strlen (p));
2165 p = next_token (p);
2166 --p;
2167 if (unixy_shell)
2168 *ap++ = '\\';
2169 *ap++ = ' ';
2170 continue;
2173 /* DOS shells don't know about backslash-escaping. */
2174 if (unixy_shell &&
2175 (*p == '\\' || *p == '\'' || *p == '"'
2176 || isspace (*p)
2177 || index (sh_chars, *p) != 0))
2178 *ap++ = '\\';
2179 #ifdef __MSDOS__
2180 else if (unixy_shell && strncmp (p, "...", 3) == 0)
2182 /* The case of `...' wildcard again. */
2183 strcpy (ap, "\\.\\.\\");
2184 ap += 5;
2185 p += 2;
2187 #endif
2188 *ap++ = *p;
2190 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2191 /* Line was empty. */
2192 return 0;
2193 *ap = '\0';
2195 if (unixy_shell)
2196 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2197 (char *) 0, (char *) 0);
2198 #ifdef __MSDOS__
2199 else
2201 /* With MSDOS shells, we must construct the command line here
2202 instead of recursively calling ourselves, because we
2203 cannot backslash-escape the special characters (see above). */
2204 new_argv = (char **) xmalloc (sizeof (char *));
2205 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2206 new_argv[0] = xmalloc (line_len + 1);
2207 strncpy (new_argv[0],
2208 new_line + shell_len + sizeof (minus_c) - 1, line_len);
2209 new_argv[0][line_len] = '\0';
2211 #endif
2213 #endif /* ! AMIGA */
2215 return new_argv;
2218 /* Figure out the argument list necessary to run LINE as a command. Try to
2219 avoid using a shell. This routine handles only ' quoting, and " quoting
2220 when no backslash, $ or ` characters are seen in the quotes. Starting
2221 quotes may be escaped with a backslash. If any of the characters in
2222 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2223 is the first word of a line, the shell is used.
2225 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2226 If *RESTP is NULL, newlines will be ignored.
2228 FILE is the target whose commands these are. It is used for
2229 variable expansion for $(SHELL) and $(IFS). */
2231 char **
2232 construct_command_argv (line, restp, file)
2233 char *line, **restp;
2234 struct file *file;
2236 char *shell, *ifs;
2237 char **argv;
2240 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2241 int save = warn_undefined_variables_flag;
2242 warn_undefined_variables_flag = 0;
2244 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
2245 #ifdef WINDOWS32
2247 * Convert to forward slashes so that construct_command_argv_internal()
2248 * is not confused.
2250 if (shell) {
2251 char *p = w32ify(shell, 0);
2252 strcpy(shell, p);
2254 #endif
2255 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
2257 warn_undefined_variables_flag = save;
2260 argv = construct_command_argv_internal (line, restp, shell, ifs);
2262 free (shell);
2263 free (ifs);
2265 return argv;
2267 #endif /* !VMS */
2269 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2271 dup2 (old, new)
2272 int old, new;
2274 int fd;
2276 (void) close (new);
2277 fd = dup (old);
2278 if (fd != new)
2280 (void) close (fd);
2281 errno = EMFILE;
2282 return -1;
2285 return fd;
2287 #endif /* !HAPE_DUP2 && !_AMIGA */