* Ignore CR in CRLF line terminators for compatibility with DOSsy
[make.git] / job.c
blob59995586708b713a481e94981dbae81b70ab8254
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, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, 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 WINDOWS32
29 char *default_shell = "sh.exe";
30 int no_default_sh_exe = 1;
31 int batch_mode_shell = 1;
32 #else /* WINDOWS32 */
33 # ifdef _AMIGA
34 char default_shell[] = "";
35 extern int MyExecute (char **);
36 # else /* _AMIGA */
37 # ifdef __MSDOS__
38 /* The default shell is a pointer so we can change it if Makefile
39 says so. It is without an explicit path so we get a chance
40 to search the $PATH for it (since MSDOS doesn't have standard
41 directories we could trust). */
42 char *default_shell = "command.com";
43 # else /* __MSDOS__ */
44 char default_shell[] = "/bin/sh";
45 # endif /* __MSDOS__ */
46 int batch_mode_shell = 0;
47 # endif /* _AMIGA */
48 #endif /* WINDOWS32 */
50 #ifdef __MSDOS__
51 # include <process.h>
52 static int execute_by_shell;
53 static int dos_pid = 123;
54 int dos_status;
55 int dos_command_running;
56 #endif /* __MSDOS__ */
58 #ifdef _AMIGA
59 # include <proto/dos.h>
60 static int amiga_pid = 123;
61 static int amiga_status;
62 static char amiga_bname[32];
63 static int amiga_batch_file;
64 #endif /* Amiga. */
66 #ifdef VMS
67 # include <time.h>
68 # include <processes.h>
69 # include <starlet.h>
70 # include <lib$routines.h>
71 #endif
73 #ifdef WINDOWS32
74 # include <windows.h>
75 # include <io.h>
76 # include <process.h>
77 # include "sub_proc.h"
78 # include "w32err.h"
79 # include "pathstuff.h"
80 #endif /* WINDOWS32 */
82 #ifdef HAVE_FCNTL_H
83 # include <fcntl.h>
84 #else
85 # include <sys/file.h>
86 #endif
88 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
89 # include <sys/wait.h>
90 #endif
92 #ifdef HAVE_WAITPID
93 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
94 #else /* Don't have waitpid. */
95 # ifdef HAVE_WAIT3
96 # ifndef wait3
97 extern int wait3 ();
98 # endif
99 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
100 # endif /* Have wait3. */
101 #endif /* Have waitpid. */
103 #if !defined (wait) && !defined (POSIX)
104 extern int wait ();
105 #endif
107 #ifndef HAVE_UNION_WAIT
109 # define WAIT_T int
111 # ifndef WTERMSIG
112 # define WTERMSIG(x) ((x) & 0x7f)
113 # endif
114 # ifndef WCOREDUMP
115 # define WCOREDUMP(x) ((x) & 0x80)
116 # endif
117 # ifndef WEXITSTATUS
118 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
119 # endif
120 # ifndef WIFSIGNALED
121 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
122 # endif
123 # ifndef WIFEXITED
124 # define WIFEXITED(x) (WTERMSIG (x) == 0)
125 # endif
127 #else /* Have `union wait'. */
129 # define WAIT_T union wait
130 # ifndef WTERMSIG
131 # define WTERMSIG(x) ((x).w_termsig)
132 # endif
133 # ifndef WCOREDUMP
134 # define WCOREDUMP(x) ((x).w_coredump)
135 # endif
136 # ifndef WEXITSTATUS
137 # define WEXITSTATUS(x) ((x).w_retcode)
138 # endif
139 # ifndef WIFSIGNALED
140 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
141 # endif
142 # ifndef WIFEXITED
143 # define WIFEXITED(x) (WTERMSIG(x) == 0)
144 # endif
146 #endif /* Don't have `union wait'. */
148 #ifdef VMS
149 static int vms_jobsefnmask = 0;
150 #endif /* !VMS */
152 #ifndef HAVE_UNISTD_H
153 extern int dup2 ();
154 extern int execve ();
155 extern void _exit ();
156 # ifndef VMS
157 extern int geteuid ();
158 extern int getegid ();
159 extern int setgid ();
160 extern int getgid ();
161 # endif
162 #endif
164 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
166 extern int getloadavg PARAMS ((double loadavg[], int nelem));
167 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
168 int *is_remote, int *id_ptr, int *used_stdin));
169 extern int start_remote_job_p PARAMS ((int));
170 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
171 int *coredump_ptr, int block));
173 static void free_child PARAMS ((struct child *));
174 static void start_job_command PARAMS ((struct child *child));
175 static int load_too_high PARAMS ((void));
176 static int job_next_command PARAMS ((struct child *));
177 static int start_waiting_job PARAMS ((struct child *));
178 #ifdef VMS
179 static void vmsWaitForChildren PARAMS ((int *));
180 #endif
182 /* Chain of all live (or recently deceased) children. */
184 struct child *children = 0;
186 /* Number of children currently running. */
188 unsigned int job_slots_used = 0;
190 /* Nonzero if the `good' standard input is in use. */
192 static int good_stdin_used = 0;
194 /* Chain of children waiting to run until the load average goes down. */
196 static struct child *waiting_jobs = 0;
198 /* Non-zero if we use a *real* shell (always so on Unix). */
200 int unixy_shell = 1;
202 #ifdef WINDOWS32
204 * The macro which references this function is defined in make.h.
206 int w32_kill(int pid, int sig)
208 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
210 #endif /* WINDOWS32 */
212 /* Write an error message describing the exit status given in
213 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
214 Append "(ignored)" if IGNORED is nonzero. */
216 static void
217 child_error (target_name, exit_code, exit_sig, coredump, ignored)
218 char *target_name;
219 int exit_code, exit_sig, coredump;
220 int ignored;
222 if (ignored && silent_flag)
223 return;
225 #ifdef VMS
226 if (!(exit_code & 1))
227 error (NILF, "*** [%s] Error 0x%x%s", target_name, exit_code, ((ignored)? " (ignored)" : ""));
228 #else
229 if (exit_sig == 0)
230 error (NILF, ignored ? "[%s] Error %d (ignored)" :
231 "*** [%s] Error %d",
232 target_name, exit_code);
233 else
234 error (NILF, "*** [%s] %s%s",
235 target_name, strsignal (exit_sig),
236 coredump ? " (core dumped)" : "");
237 #endif /* VMS */
240 #ifdef VMS
241 /* Wait for nchildren children to terminate */
242 static void
243 vmsWaitForChildren(int *status)
245 while (1)
247 if (!vms_jobsefnmask)
249 *status = 0;
250 return;
253 *status = sys$wflor (32, vms_jobsefnmask);
255 return;
257 #endif
260 /* If we can't use waitpid() or wait3(), then we use a signal handler
261 to track the number of SIGCHLD's we got. This is less robust. */
263 #ifndef WAIT_NOHANG
265 static unsigned int dead_children = 0;
267 /* Notice that a child died.
268 reap_children should be called when convenient. */
269 RETSIGTYPE
270 child_handler (sig)
271 int sig;
273 ++dead_children;
275 if (debug_flag)
276 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
279 #endif /* WAIT_NOHANG */
281 extern int shell_function_pid, shell_function_completed;
283 /* Reap dead children, storing the returned status and the new command
284 state (`cs_finished') in the `file' member of the `struct child' for the
285 dead child, and removing the child from the chain. If BLOCK nonzero,
286 reap at least one child, waiting for it to die if necessary. If ERR is
287 nonzero, print an error message first. */
289 void
290 reap_children (block, err)
291 int block, err;
293 WAIT_T status;
294 #ifdef WAIT_NOHANG
295 int dead_children = 1; /* Initially, assume we have some. */
296 #endif
298 while ((children != 0 || shell_function_pid != 0) &&
299 (block || dead_children))
301 int remote = 0;
302 register int pid;
303 int exit_code, exit_sig, coredump;
304 register struct child *lastc, *c;
305 int child_failed;
306 int any_remote, any_local;
308 if (err && block)
310 /* We might block for a while, so let the user know why. */
311 fflush (stdout);
312 error (NILF, "*** Waiting for unfinished jobs....");
315 #ifndef WAIT_NOHANG
316 /* We have one less dead child to reap.
317 The test and decrement are not atomic; if it is compiled into:
318 register = dead_children - 1;
319 dead_children = register;
320 a SIGCHLD could come between the two instructions.
321 child_handler increments dead_children.
322 The second instruction here would lose that increment. But the
323 only effect of dead_children being wrong is that we might wait
324 longer than necessary to reap a child, and lose some parallelism;
325 and we might print the "Waiting for unfinished jobs" message above
326 when not necessary. */
328 if (dead_children > 0)
329 --dead_children;
330 #endif
332 any_remote = 0;
333 any_local = shell_function_pid != 0;
334 for (c = children; c != 0; c = c->next)
336 any_remote |= c->remote;
337 any_local |= ! c->remote;
338 if (debug_flag)
339 printf ("Live child 0x%08lx PID %ld%s\n",
340 (unsigned long int) c,
341 (long) c->pid, c->remote ? " (remote)" : "");
342 #ifdef VMS
343 break;
344 #endif
347 /* First, check for remote children. */
348 if (any_remote)
349 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
350 else
351 pid = 0;
353 if (pid > 0)
354 /* We got a remote child. */
355 remote = 1;
356 else if (pid < 0)
358 /* A remote status command failed miserably. Punt. */
359 remote_status_lose:
360 #ifdef EINTR
361 if (errno == EINTR)
362 continue;
363 #endif
364 pfatal_with_name ("remote_status");
366 else
368 /* No remote children. Check for local children. */
370 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
371 if (any_local)
373 #ifdef VMS
374 vmsWaitForChildren (&status);
375 pid = c->pid;
376 #else
377 #ifdef WAIT_NOHANG
378 if (!block)
379 pid = WAIT_NOHANG (&status);
380 else
381 #endif
382 pid = wait (&status);
383 #endif /* !VMS */
385 else
386 pid = 0;
388 if (pid < 0)
390 /* The wait*() failed miserably. Punt. */
391 #ifdef EINTR
392 if (errno == EINTR)
393 continue;
394 #endif
395 pfatal_with_name ("wait");
397 else if (pid > 0)
399 /* We got one; chop the status word up. */
400 exit_code = WEXITSTATUS (status);
401 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
402 coredump = WCOREDUMP (status);
404 else
406 /* No local children are dead. */
407 #ifdef WAIT_NOHANG
408 dead_children = 0;
409 #endif
410 if (block && any_remote)
412 /* Now try a blocking wait for a remote child. */
413 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
414 if (pid < 0)
415 goto remote_status_lose;
416 else if (pid == 0)
417 /* No remote children either. Finally give up. */
418 break;
419 else
420 /* We got a remote child. */
421 remote = 1;
423 else
424 break;
426 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
427 #ifdef __MSDOS__
428 /* Life is very different on MSDOS. */
429 pid = dos_pid - 1;
430 status = dos_status;
431 exit_code = WEXITSTATUS (status);
432 if (exit_code == 0xff)
433 exit_code = -1;
434 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
435 coredump = 0;
436 #endif /* __MSDOS__ */
437 #ifdef _AMIGA
438 /* Same on Amiga */
439 pid = amiga_pid - 1;
440 status = amiga_status;
441 exit_code = amiga_status;
442 exit_sig = 0;
443 coredump = 0;
444 #endif /* _AMIGA */
445 #ifdef WINDOWS32
447 HANDLE hPID;
448 int err;
450 /* wait for anything to finish */
451 if (hPID = process_wait_for_any()) {
453 /* was an error found on this process? */
454 err = process_last_err(hPID);
456 /* get exit data */
457 exit_code = process_exit_code(hPID);
459 if (err)
460 fprintf(stderr, "make (e=%d): %s",
461 exit_code, map_windows32_error_to_string(exit_code));
463 /* signal */
464 exit_sig = process_signal(hPID);
466 /* cleanup process */
467 process_cleanup(hPID);
469 coredump = 0;
471 pid = (int) hPID;
473 #endif /* WINDOWS32 */
476 /* Check if this is the child of the `shell' function. */
477 if (!remote && pid == shell_function_pid)
479 /* It is. Leave an indicator for the `shell' function. */
480 if (exit_sig == 0 && exit_code == 127)
481 shell_function_completed = -1;
482 else
483 shell_function_completed = 1;
484 break;
487 child_failed = exit_sig != 0 || exit_code != 0;
489 /* Search for a child matching the deceased one. */
490 lastc = 0;
491 for (c = children; c != 0; lastc = c, c = c->next)
492 if (c->remote == remote && c->pid == pid)
493 break;
495 if (c == 0)
497 /* An unknown child died.
498 Ignore it; it was inherited from our invoker. */
499 continue;
501 else
503 if (debug_flag)
504 printf ("Reaping %s child 0x%08lx PID %ld%s\n",
505 child_failed ? "losing" : "winning",
506 (unsigned long int) c,
507 (long) c->pid, c->remote ? " (remote)" : "");
509 if (c->sh_batch_file) {
510 if (debug_flag)
511 printf("Cleaning up temp batch file %s\n", c->sh_batch_file);
513 /* just try and remove, don't care if this fails */
514 remove(c->sh_batch_file);
516 /* all done with memory */
517 free(c->sh_batch_file);
518 c->sh_batch_file = NULL;
521 /* If this child had the good stdin, say it is now free. */
522 if (c->good_stdin)
523 good_stdin_used = 0;
525 if (child_failed && !c->noerror && !ignore_errors_flag)
527 /* The commands failed. Write an error message,
528 delete non-precious targets, and abort. */
529 static int delete_on_error = -1;
530 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
531 c->file->update_status = 2;
532 if (delete_on_error == -1)
534 struct file *f = lookup_file (".DELETE_ON_ERROR");
535 delete_on_error = f != 0 && f->is_target;
537 if (exit_sig != 0 || delete_on_error)
538 delete_child_targets (c);
540 else
542 if (child_failed)
544 /* The commands failed, but we don't care. */
545 child_error (c->file->name,
546 exit_code, exit_sig, coredump, 1);
547 child_failed = 0;
550 /* If there are more commands to run, try to start them. */
551 if (job_next_command (c))
553 if (handling_fatal_signal)
555 /* Never start new commands while we are dying.
556 Since there are more commands that wanted to be run,
557 the target was not completely remade. So we treat
558 this as if a command had failed. */
559 c->file->update_status = 2;
561 else
563 /* Check again whether to start remotely.
564 Whether or not we want to changes over time.
565 Also, start_remote_job may need state set up
566 by start_remote_job_p. */
567 c->remote = start_remote_job_p (0);
568 start_job_command (c);
569 /* Fatal signals are left blocked in case we were
570 about to put that child on the chain. But it is
571 already there, so it is safe for a fatal signal to
572 arrive now; it will clean up this child's targets. */
573 unblock_sigs ();
574 if (c->file->command_state == cs_running)
575 /* We successfully started the new command.
576 Loop to reap more children. */
577 continue;
580 if (c->file->update_status != 0)
581 /* We failed to start the commands. */
582 delete_child_targets (c);
584 else
585 /* There are no more commands. We got through them all
586 without an unignored error. Now the target has been
587 successfully updated. */
588 c->file->update_status = 0;
591 /* When we get here, all the commands for C->file are finished
592 (or aborted) and C->file->update_status contains 0 or 2. But
593 C->file->command_state is still cs_running if all the commands
594 ran; notice_finish_file looks for cs_running to tell it that
595 it's interesting to check the file's modtime again now. */
597 if (! handling_fatal_signal)
598 /* Notice if the target of the commands has been changed.
599 This also propagates its values for command_state and
600 update_status to its also_make files. */
601 notice_finished_file (c->file);
603 if (debug_flag)
604 printf ("Removing child 0x%08lx PID %ld%s from chain.\n",
605 (unsigned long int) c,
606 (long) c->pid, c->remote ? " (remote)" : "");
608 /* Block fatal signals while frobnicating the list, so that
609 children and job_slots_used are always consistent. Otherwise
610 a fatal signal arriving after the child is off the chain and
611 before job_slots_used is decremented would believe a child was
612 live and call reap_children again. */
613 block_sigs ();
615 /* Remove the child from the chain and free it. */
616 if (lastc == 0)
617 children = c->next;
618 else
619 lastc->next = c->next;
620 if (! handling_fatal_signal) /* Don't bother if about to die. */
621 free_child (c);
623 /* There is now another slot open. */
624 if (job_slots_used > 0)
625 --job_slots_used;
627 unblock_sigs ();
629 /* If the job failed, and the -k flag was not given, die,
630 unless we are already in the process of dying. */
631 if (!err && child_failed && !keep_going_flag &&
632 /* fatal_error_signal will die with the right signal. */
633 !handling_fatal_signal)
634 die (2);
637 /* Only block for one child. */
638 block = 0;
640 return;
643 /* Free the storage allocated for CHILD. */
645 static void
646 free_child (child)
647 register struct child *child;
649 if (child->command_lines != 0)
651 register unsigned int i;
652 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
653 free (child->command_lines[i]);
654 free ((char *) child->command_lines);
657 if (child->environment != 0)
659 register char **ep = child->environment;
660 while (*ep != 0)
661 free (*ep++);
662 free ((char *) child->environment);
665 free ((char *) child);
668 #ifdef POSIX
669 extern sigset_t fatal_signal_set;
670 #endif
672 void
673 block_sigs ()
675 #ifdef POSIX
676 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
677 #else
678 # ifdef HAVE_SIGSETMASK
679 (void) sigblock (fatal_signal_mask);
680 # endif
681 #endif
684 #ifdef POSIX
685 void
686 unblock_sigs ()
688 sigset_t empty;
689 sigemptyset (&empty);
690 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
692 #endif
694 /* Start a job to run the commands specified in CHILD.
695 CHILD is updated to reflect the commands and ID of the child process.
697 NOTE: On return fatal signals are blocked! The caller is responsible
698 for calling `unblock_sigs', once the new child is safely on the chain so
699 it can be cleaned up in the event of a fatal signal. */
701 static void
702 start_job_command (child)
703 register struct child *child;
705 #ifndef _AMIGA
706 static int bad_stdin = -1;
707 #endif
708 register char *p;
709 int flags;
710 #ifdef VMS
711 char *argv;
712 #else
713 char **argv;
714 #endif
716 /* Combine the flags parsed for the line itself with
717 the flags specified globally for this target. */
718 flags = (child->file->command_flags
719 | child->file->cmds->lines_flags[child->command_line - 1]);
721 p = child->command_ptr;
722 child->noerror = flags & COMMANDS_NOERROR;
724 while (*p != '\0')
726 if (*p == '@')
727 flags |= COMMANDS_SILENT;
728 else if (*p == '+')
729 flags |= COMMANDS_RECURSE;
730 else if (*p == '-')
731 child->noerror = 1;
732 else if (!isblank (*p) && *p != '+')
733 break;
734 ++p;
737 /* If -q was given, just say that updating `failed'. The exit status of
738 1 tells the user that -q is saying `something to do'; the exit status
739 for a random error is 2. */
740 if (question_flag && !(flags & COMMANDS_RECURSE))
742 child->file->update_status = 1;
743 notice_finished_file (child->file);
744 return;
747 /* There may be some preceding whitespace left if there
748 was nothing but a backslash on the first line. */
749 p = next_token (p);
751 /* Figure out an argument list from this command line. */
754 char *end = 0;
755 #ifdef VMS
756 argv = p;
757 #else
758 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
759 #endif
760 if (end == NULL)
761 child->command_ptr = NULL;
762 else
764 *end++ = '\0';
765 child->command_ptr = end;
769 if (touch_flag && !(flags & COMMANDS_RECURSE))
771 /* Go on to the next command. It might be the recursive one.
772 We construct ARGV only to find the end of the command line. */
773 #ifndef VMS
774 free (argv[0]);
775 free ((char *) argv);
776 #endif
777 argv = 0;
780 if (argv == 0)
782 next_command:
783 #ifdef __MSDOS__
784 execute_by_shell = 0; /* in case construct_command_argv sets it */
785 #endif
786 /* This line has no commands. Go to the next. */
787 if (job_next_command (child))
788 start_job_command (child);
789 else
791 /* No more commands. All done. */
792 child->file->update_status = 0;
793 notice_finished_file (child->file);
795 return;
798 /* Print out the command. If silent, we call `message' with null so it
799 can log the working directory before the command's own error messages
800 appear. */
802 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
803 ? "%s" : (char *) 0, p);
805 /* Optimize an empty command. People use this for timestamp rules,
806 and forking a useless shell all the time leads to inefficiency. */
808 #if !defined(VMS) && !defined(_AMIGA)
809 if (
810 #ifdef __MSDOS__
811 unixy_shell /* the test is complicated and we already did it */
812 #else
813 (argv[0] && !strcmp(argv[0], "/bin/sh"))
814 #endif
815 && (argv[1] && !strcmp(argv[1], "-c"))
816 && (argv[2] && !strcmp(argv[2], ":"))
817 && argv[3] == NULL)
819 set_command_state (child->file, cs_running);
820 goto next_command;
822 #endif /* !VMS && !_AMIGA */
824 /* Tell update_goal_chain that a command has been started on behalf of
825 this target. It is important that this happens here and not in
826 reap_children (where we used to do it), because reap_children might be
827 reaping children from a different target. We want this increment to
828 guaranteedly indicate that a command was started for the dependency
829 chain (i.e., update_file recursion chain) we are processing. */
831 ++commands_started;
833 /* If -n was given, recurse to get the next line in the sequence. */
835 if (just_print_flag && !(flags & COMMANDS_RECURSE))
837 #ifndef VMS
838 free (argv[0]);
839 free ((char *) argv);
840 #endif
841 goto next_command;
844 /* Flush the output streams so they won't have things written twice. */
846 fflush (stdout);
847 fflush (stderr);
849 #ifndef VMS
850 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
852 /* Set up a bad standard input that reads from a broken pipe. */
854 if (bad_stdin == -1)
856 /* Make a file descriptor that is the read end of a broken pipe.
857 This will be used for some children's standard inputs. */
858 int pd[2];
859 if (pipe (pd) == 0)
861 /* Close the write side. */
862 (void) close (pd[1]);
863 /* Save the read side. */
864 bad_stdin = pd[0];
866 /* Set the descriptor to close on exec, so it does not litter any
867 child's descriptor table. When it is dup2'd onto descriptor 0,
868 that descriptor will not close on exec. */
869 #ifdef FD_SETFD
870 #ifndef FD_CLOEXEC
871 #define FD_CLOEXEC 1
872 #endif
873 (void) fcntl (bad_stdin, F_SETFD, FD_CLOEXEC);
874 #endif
878 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
880 /* Decide whether to give this child the `good' standard input
881 (one that points to the terminal or whatever), or the `bad' one
882 that points to the read side of a broken pipe. */
884 child->good_stdin = !good_stdin_used;
885 if (child->good_stdin)
886 good_stdin_used = 1;
888 #endif /* !VMS */
890 child->deleted = 0;
892 #ifndef _AMIGA
893 /* Set up the environment for the child. */
894 if (child->environment == 0)
895 child->environment = target_environment (child->file);
896 #endif
898 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
900 #ifndef VMS
901 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
902 if (child->remote)
904 int is_remote, id, used_stdin;
905 if (start_remote_job (argv, child->environment,
906 child->good_stdin ? 0 : bad_stdin,
907 &is_remote, &id, &used_stdin))
908 /* Don't give up; remote execution may fail for various reasons. If
909 so, simply run the job locally. */
910 goto run_local;
911 else
913 if (child->good_stdin && !used_stdin)
915 child->good_stdin = 0;
916 good_stdin_used = 0;
918 child->remote = is_remote;
919 child->pid = id;
922 else
923 #endif /* !VMS */
925 /* Fork the child process. */
927 char **parent_environ;
929 run_local:
930 block_sigs ();
932 child->remote = 0;
934 #ifdef VMS
936 if (!child_execute_job (argv, child)) {
937 /* Fork failed! */
938 perror_with_name ("vfork", "");
939 goto error;
942 #else
944 parent_environ = environ;
945 child->pid = vfork ();
946 environ = parent_environ; /* Restore value child may have clobbered. */
947 if (child->pid == 0)
949 /* We are the child side. */
950 unblock_sigs ();
951 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
952 argv, child->environment);
954 else if (child->pid < 0)
956 /* Fork failed! */
957 unblock_sigs ();
958 perror_with_name ("vfork", "");
959 goto error;
961 #endif /* !VMS */
964 #else /* __MSDOS__ or Amiga or WINDOWS32 */
965 #ifdef __MSDOS__
967 int proc_return;
969 block_sigs ();
970 dos_status = 0;
972 /* We call `system' to do the job of the SHELL, since stock DOS
973 shell is too dumb. Our `system' knows how to handle long
974 command lines even if pipes/redirection is needed; it will only
975 call COMMAND.COM when its internal commands are used. */
976 if (execute_by_shell)
978 char *cmdline = argv[0];
979 /* We don't have a way to pass environment to `system',
980 so we need to save and restore ours, sigh... */
981 char **parent_environ = environ;
983 environ = child->environment;
985 /* If we have a *real* shell, tell `system' to call
986 it to do everything for us. */
987 if (unixy_shell)
989 /* A *real* shell on MSDOS may not support long
990 command lines the DJGPP way, so we must use `system'. */
991 cmdline = argv[2]; /* get past "shell -c" */
994 dos_command_running = 1;
995 proc_return = system (cmdline);
996 dos_command_running = 0;
997 environ = parent_environ;
998 execute_by_shell = 0; /* for the next time */
1000 else
1002 dos_command_running = 1;
1003 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1004 dos_command_running = 0;
1007 if (proc_return == -1)
1008 dos_status |= 0xff;
1009 else
1010 dos_status |= (proc_return & 0xff);
1011 ++dead_children;
1012 child->pid = dos_pid++;
1014 #endif /* __MSDOS__ */
1015 #ifdef _AMIGA
1016 amiga_status = MyExecute (argv);
1018 ++dead_children;
1019 child->pid = amiga_pid++;
1020 if (amiga_batch_file)
1022 amiga_batch_file = 0;
1023 DeleteFile (amiga_bname); /* Ignore errors. */
1025 #endif /* Amiga */
1026 #ifdef WINDOWS32
1028 HANDLE hPID;
1029 char* arg0;
1031 /* make UNC paths safe for CreateProcess -- backslash format */
1032 arg0 = argv[0];
1033 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1034 for ( ; arg0 && *arg0; arg0++)
1035 if (*arg0 == '/')
1036 *arg0 = '\\';
1038 /* make sure CreateProcess() has Path it needs */
1039 sync_Path_environment();
1041 hPID = process_easy(argv, child->environment);
1043 if (hPID != INVALID_HANDLE_VALUE)
1044 child->pid = (int) hPID;
1045 else {
1046 int i;
1047 unblock_sigs();
1048 fprintf(stderr,
1049 "process_easy() failed failed to launch process (e=%d)\n",
1050 process_last_err(hPID));
1051 for (i = 0; argv[i]; i++)
1052 fprintf(stderr, "%s ", argv[i]);
1053 fprintf(stderr, "\nCounted %d args in failed launch\n", i);
1056 #endif /* WINDOWS32 */
1057 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1059 /* We are the parent side. Set the state to
1060 say the commands are running and return. */
1062 set_command_state (child->file, cs_running);
1064 /* Free the storage used by the child's argument list. */
1065 #ifndef VMS
1066 free (argv[0]);
1067 free ((char *) argv);
1068 #endif
1070 return;
1072 error:
1073 child->file->update_status = 2;
1074 notice_finished_file (child->file);
1075 return;
1078 /* Try to start a child running.
1079 Returns nonzero if the child was started (and maybe finished), or zero if
1080 the load was too high and the child was put on the `waiting_jobs' chain. */
1082 static int
1083 start_waiting_job (c)
1084 struct child *c;
1086 /* If we can start a job remotely, we always want to, and don't care about
1087 the local load average. We record that the job should be started
1088 remotely in C->remote for start_job_command to test. */
1090 c->remote = start_remote_job_p (1);
1092 /* If this job is to be started locally, and we are already running
1093 some jobs, make this one wait if the load average is too high. */
1094 if (!c->remote && job_slots_used > 0 && load_too_high ())
1096 /* Put this child on the chain of children waiting
1097 for the load average to go down. */
1098 set_command_state (c->file, cs_running);
1099 c->next = waiting_jobs;
1100 waiting_jobs = c;
1101 return 0;
1104 /* Start the first command; reap_children will run later command lines. */
1105 start_job_command (c);
1107 switch (c->file->command_state)
1109 case cs_running:
1110 c->next = children;
1111 if (debug_flag)
1112 printf ("Putting child 0x%08lx PID %ld%s on the chain.\n",
1113 (unsigned long int) c,
1114 (long) c->pid, c->remote ? " (remote)" : "");
1115 children = c;
1116 /* One more job slot is in use. */
1117 ++job_slots_used;
1118 unblock_sigs ();
1119 break;
1121 case cs_not_started:
1122 /* All the command lines turned out to be empty. */
1123 c->file->update_status = 0;
1124 /* FALLTHROUGH */
1126 case cs_finished:
1127 notice_finished_file (c->file);
1128 free_child (c);
1129 break;
1131 default:
1132 assert (c->file->command_state == cs_finished);
1133 break;
1136 return 1;
1139 /* Create a `struct child' for FILE and start its commands running. */
1141 void
1142 new_job (file)
1143 register struct file *file;
1145 register struct commands *cmds = file->cmds;
1146 register struct child *c;
1147 char **lines;
1148 register unsigned int i;
1150 /* Let any previously decided-upon jobs that are waiting
1151 for the load to go down start before this new one. */
1152 start_waiting_jobs ();
1154 /* Reap any children that might have finished recently. */
1155 reap_children (0, 0);
1157 /* Chop the commands up into lines if they aren't already. */
1158 chop_commands (cmds);
1160 if (job_slots != 0)
1161 /* Wait for a job slot to be freed up. */
1162 while (job_slots_used == job_slots)
1163 reap_children (1, 0);
1165 /* Expand the command lines and store the results in LINES. */
1166 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1167 for (i = 0; i < cmds->ncommand_lines; ++i)
1169 /* Collapse backslash-newline combinations that are inside variable
1170 or function references. These are left alone by the parser so
1171 that they will appear in the echoing of commands (where they look
1172 nice); and collapsed by construct_command_argv when it tokenizes.
1173 But letting them survive inside function invocations loses because
1174 we don't want the functions to see them as part of the text. */
1176 char *in, *out, *ref;
1178 /* IN points to where in the line we are scanning.
1179 OUT points to where in the line we are writing.
1180 When we collapse a backslash-newline combination,
1181 IN gets ahead of OUT. */
1183 in = out = cmds->command_lines[i];
1184 while ((ref = index (in, '$')) != 0)
1186 ++ref; /* Move past the $. */
1188 if (out != in)
1189 /* Copy the text between the end of the last chunk
1190 we processed (where IN points) and the new chunk
1191 we are about to process (where REF points). */
1192 bcopy (in, out, ref - in);
1194 /* Move both pointers past the boring stuff. */
1195 out += ref - in;
1196 in = ref;
1198 if (*ref == '(' || *ref == '{')
1200 char openparen = *ref;
1201 char closeparen = openparen == '(' ? ')' : '}';
1202 int count;
1203 char *p;
1205 *out++ = *in++; /* Copy OPENPAREN. */
1206 /* IN now points past the opening paren or brace.
1207 Count parens or braces until it is matched. */
1208 count = 0;
1209 while (*in != '\0')
1211 if (*in == closeparen && --count < 0)
1212 break;
1213 else if (*in == '\\' && in[1] == '\n')
1215 /* We have found a backslash-newline inside a
1216 variable or function reference. Eat it and
1217 any following whitespace. */
1219 int quoted = 0;
1220 for (p = in - 1; p > ref && *p == '\\'; --p)
1221 quoted = !quoted;
1223 if (quoted)
1224 /* There were two or more backslashes, so this is
1225 not really a continuation line. We don't collapse
1226 the quoting backslashes here as is done in
1227 collapse_continuations, because the line will
1228 be collapsed again after expansion. */
1229 *out++ = *in++;
1230 else
1232 /* Skip the backslash, newline and
1233 any following whitespace. */
1234 in = next_token (in + 2);
1236 /* Discard any preceding whitespace that has
1237 already been written to the output. */
1238 while (out > ref && isblank (out[-1]))
1239 --out;
1241 /* Replace it all with a single space. */
1242 *out++ = ' ';
1245 else
1247 if (*in == openparen)
1248 ++count;
1250 *out++ = *in++;
1256 /* There are no more references in this line to worry about.
1257 Copy the remaining uninteresting text to the output. */
1258 if (out != in)
1259 strcpy (out, in);
1261 /* Finally, expand the line. */
1262 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1263 file);
1266 /* Start the command sequence, record it in a new
1267 `struct child', and add that to the chain. */
1269 c = (struct child *) xmalloc (sizeof (struct child));
1270 c->file = file;
1271 c->command_lines = lines;
1272 c->command_line = 0;
1273 c->command_ptr = 0;
1274 c->environment = 0;
1275 c->sh_batch_file = NULL;
1277 /* Fetch the first command line to be run. */
1278 if (job_next_command (c))
1279 /* The job is now primed. Start it running. */
1280 (void)start_waiting_job (c);
1281 else
1283 /* There were no commands (variable expands to empty?). All done. */
1284 c->file->update_status = 0;
1285 notice_finished_file(c->file);
1286 free_child (c);
1289 if (job_slots == 1)
1290 /* Since there is only one job slot, make things run linearly.
1291 Wait for the child to die, setting the state to `cs_finished'. */
1292 while (file->command_state == cs_running)
1293 reap_children (1, 0);
1295 return;
1298 /* Move CHILD's pointers to the next command for it to execute.
1299 Returns nonzero if there is another command. */
1301 static int
1302 job_next_command (child)
1303 struct child *child;
1305 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1307 /* There are no more lines in the expansion of this line. */
1308 if (child->command_line == child->file->cmds->ncommand_lines)
1310 /* There are no more lines to be expanded. */
1311 child->command_ptr = 0;
1312 return 0;
1314 else
1315 /* Get the next line to run. */
1316 child->command_ptr = child->command_lines[child->command_line++];
1318 return 1;
1321 static int
1322 load_too_high ()
1324 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1325 return 1;
1326 #else
1327 double load;
1329 if (max_load_average < 0)
1330 return 0;
1332 make_access ();
1333 if (getloadavg (&load, 1) != 1)
1335 static int lossage = -1;
1336 /* Complain only once for the same error. */
1337 if (lossage == -1 || errno != lossage)
1339 if (errno == 0)
1340 /* An errno value of zero means getloadavg is just unsupported. */
1341 error (NILF, "cannot enforce load limits on this operating system");
1342 else
1343 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1345 lossage = errno;
1346 load = 0;
1348 user_access ();
1350 return load >= max_load_average;
1351 #endif
1354 /* Start jobs that are waiting for the load to be lower. */
1356 void
1357 start_waiting_jobs ()
1359 struct child *job;
1361 if (waiting_jobs == 0)
1362 return;
1366 /* Check for recently deceased descendants. */
1367 reap_children (0, 0);
1369 /* Take a job off the waiting list. */
1370 job = waiting_jobs;
1371 waiting_jobs = job->next;
1373 /* Try to start that job. We break out of the loop as soon
1374 as start_waiting_job puts one back on the waiting list. */
1376 while (start_waiting_job (job) && waiting_jobs != 0);
1378 return;
1381 #ifndef WINDOWS32
1382 #ifdef VMS
1383 #include <descrip.h>
1384 #include <clidef.h>
1386 /* This is called as an AST when a child process dies (it won't get
1387 interrupted by anything except a higher level AST).
1389 int vmsHandleChildTerm(struct child *child)
1391 int status;
1392 register struct child *lastc, *c;
1393 int child_failed;
1395 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1397 lib$free_ef(&child->efn);
1399 (void) sigblock (fatal_signal_mask);
1401 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1403 /* Search for a child matching the deceased one. */
1404 lastc = 0;
1405 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1406 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1407 #else
1408 c = child;
1409 #endif
1411 if (child_failed && !c->noerror && !ignore_errors_flag)
1413 /* The commands failed. Write an error message,
1414 delete non-precious targets, and abort. */
1415 child_error (c->file->name, c->cstatus, 0, 0, 0);
1416 c->file->update_status = 1;
1417 delete_child_targets (c);
1419 else
1421 if (child_failed)
1423 /* The commands failed, but we don't care. */
1424 child_error (c->file->name, c->cstatus, 0, 0, 1);
1425 child_failed = 0;
1428 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1429 /* If there are more commands to run, try to start them. */
1430 start_job (c);
1432 switch (c->file->command_state)
1434 case cs_running:
1435 /* Successfully started. */
1436 break;
1438 case cs_finished:
1439 if (c->file->update_status != 0) {
1440 /* We failed to start the commands. */
1441 delete_child_targets (c);
1443 break;
1445 default:
1446 error (NILF, "internal error: `%s' command_state", c->file->name);
1447 abort ();
1448 break;
1450 #endif /* RECURSIVEJOBS */
1453 /* Set the state flag to say the commands have finished. */
1454 c->file->command_state = cs_finished;
1455 notice_finished_file (c->file);
1457 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1458 /* Remove the child from the chain and free it. */
1459 if (lastc == 0)
1460 children = c->next;
1461 else
1462 lastc->next = c->next;
1463 free_child (c);
1464 #endif /* RECURSIVEJOBS */
1466 /* There is now another slot open. */
1467 if (job_slots_used > 0)
1468 --job_slots_used;
1470 /* If the job failed, and the -k flag was not given, die. */
1471 if (child_failed && !keep_going_flag)
1472 die (EXIT_FAILURE);
1474 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1476 return 1;
1479 /* VMS:
1480 Spawn a process executing the command in ARGV and return its pid. */
1482 #define MAXCMDLEN 200
1485 child_execute_job (argv, child)
1486 char *argv;
1487 struct child *child;
1489 int i;
1490 static struct dsc$descriptor_s cmddsc;
1491 #ifndef DONTWAITFORCHILD
1492 int spflags = 0;
1493 #else
1494 int spflags = CLI$M_NOWAIT;
1495 #endif
1496 int status;
1497 char cmd[4096],*p,*c;
1498 char comname[50];
1500 /* Remove backslashes */
1501 for (p = argv, c = cmd; *p; p++,c++)
1503 if (*p == '\\') p++;
1504 *c = *p;
1506 *c = *p;
1508 /* Check for maximum DCL length and create *.com file if neccesary.
1509 Also create a .com file if the command is more than one line long. */
1511 comname[0] = '\0';
1513 if (strlen (cmd) > MAXCMDLEN || strchr (cmd, '\n'))
1515 FILE *outfile;
1516 char tmp;
1518 strcpy (comname, "sys$scratch:CMDXXXXXX.COM");
1519 (void) mktemp (comname);
1521 outfile = fopen (comname, "w");
1522 if (outfile == 0)
1523 pfatal_with_name (comname);
1525 fprintf (outfile, "$ ");
1526 c = cmd;
1528 while (c)
1530 p = strchr (c, ',');
1531 if ((p == NULL) || (p-c > MAXCMDLEN))
1532 p = strchr (c, ' ');
1533 if (p != NULL)
1535 p++;
1536 tmp = *p;
1537 *p = '\0';
1539 else
1540 tmp = '\0';
1541 fprintf (outfile, "%s%s\n", c, (tmp == '\0')?"":" -");
1542 if (p != NULL)
1543 *p = tmp;
1544 c = p;
1547 fclose (outfile);
1549 sprintf (cmd, "$ @%s", comname);
1551 if (debug_flag)
1552 printf ("Executing %s instead\n", cmd);
1555 cmddsc.dsc$w_length = strlen(cmd);
1556 cmddsc.dsc$a_pointer = cmd;
1557 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
1558 cmddsc.dsc$b_class = DSC$K_CLASS_S;
1560 child->efn = 0;
1561 while (child->efn < 32 || child->efn > 63)
1563 status = lib$get_ef(&child->efn);
1564 if (!(status & 1))
1565 return 0;
1568 sys$clref(child->efn);
1570 vms_jobsefnmask |= (1 << (child->efn - 32));
1572 #ifndef DONTWAITFORCHILD
1573 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1574 &child->efn,0,0);
1575 vmsHandleChildTerm(child);
1576 #else
1577 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1578 &child->efn,vmsHandleChildTerm,child);
1579 #endif
1581 if (!(status & 1))
1583 printf("Error spawning, %d\n",status);
1584 fflush(stdout);
1587 unlink (comname);
1589 return (status & 1);
1592 #else /* !VMS */
1594 #if !defined (_AMIGA) && !defined (__MSDOS__)
1595 /* UNIX:
1596 Replace the current process with one executing the command in ARGV.
1597 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1598 the environment of the new program. This function does not return. */
1600 void
1601 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1602 int stdin_fd, stdout_fd;
1603 char **argv, **envp;
1605 if (stdin_fd != 0)
1606 (void) dup2 (stdin_fd, 0);
1607 if (stdout_fd != 1)
1608 (void) dup2 (stdout_fd, 1);
1609 if (stdin_fd != 0)
1610 (void) close (stdin_fd);
1611 if (stdout_fd != 1)
1612 (void) close (stdout_fd);
1614 /* Run the command. */
1615 exec_command (argv, envp);
1617 #endif /* !AMIGA && !__MSDOS__ */
1618 #endif /* !VMS */
1619 #endif /* !WINDOWS32 */
1621 #ifndef _AMIGA
1622 /* Replace the current process with one running the command in ARGV,
1623 with environment ENVP. This function does not return. */
1625 void
1626 exec_command (argv, envp)
1627 char **argv, **envp;
1629 #ifdef VMS
1630 /* Run the program. */
1631 execve (argv[0], argv, envp);
1632 perror_with_name ("execve: ", argv[0]);
1633 _exit (EXIT_FAILURE);
1634 #else
1635 #ifdef WINDOWS32
1636 HANDLE hPID;
1637 HANDLE hWaitPID;
1638 int err = 0;
1639 int exit_code = EXIT_FAILURE;
1641 /* make sure CreateProcess() has Path it needs */
1642 sync_Path_environment();
1644 /* launch command */
1645 hPID = process_easy(argv, envp);
1647 /* make sure launch ok */
1648 if (hPID == INVALID_HANDLE_VALUE)
1650 int i;
1651 fprintf(stderr,
1652 "process_easy() failed failed to launch process (e=%d)\n",
1653 process_last_err(hPID));
1654 for (i = 0; argv[i]; i++)
1655 fprintf(stderr, "%s ", argv[i]);
1656 fprintf(stderr, "\nCounted %d args in failed launch\n", i);
1657 exit(EXIT_FAILURE);
1660 /* wait and reap last child */
1661 while (hWaitPID = process_wait_for_any())
1663 /* was an error found on this process? */
1664 err = process_last_err(hWaitPID);
1666 /* get exit data */
1667 exit_code = process_exit_code(hWaitPID);
1669 if (err)
1670 fprintf(stderr, "make (e=%d, rc=%d): %s",
1671 err, exit_code, map_windows32_error_to_string(err));
1673 /* cleanup process */
1674 process_cleanup(hWaitPID);
1676 /* expect to find only last pid, warn about other pids reaped */
1677 if (hWaitPID == hPID)
1678 break;
1679 else
1680 fprintf(stderr,
1681 "make reaped child pid %d, still waiting for pid %d\n",
1682 hWaitPID, hPID);
1685 /* return child's exit code as our exit code */
1686 exit(exit_code);
1688 #else /* !WINDOWS32 */
1690 /* Be the user, permanently. */
1691 child_access ();
1693 /* Run the program. */
1694 environ = envp;
1695 execvp (argv[0], argv);
1697 switch (errno)
1699 case ENOENT:
1700 error (NILF, "%s: Command not found", argv[0]);
1701 break;
1702 case ENOEXEC:
1704 /* The file is not executable. Try it as a shell script. */
1705 extern char *getenv ();
1706 char *shell;
1707 char **new_argv;
1708 int argc;
1710 shell = getenv ("SHELL");
1711 if (shell == 0)
1712 shell = default_shell;
1714 argc = 1;
1715 while (argv[argc] != 0)
1716 ++argc;
1718 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1719 new_argv[0] = shell;
1720 new_argv[1] = argv[0];
1721 while (argc > 0)
1723 new_argv[1 + argc] = argv[argc];
1724 --argc;
1727 execvp (shell, new_argv);
1728 if (errno == ENOENT)
1729 error (NILF, "%s: Shell program not found", shell);
1730 else
1731 perror_with_name ("execvp: ", shell);
1732 break;
1735 default:
1736 perror_with_name ("execvp: ", argv[0]);
1737 break;
1740 _exit (127);
1741 #endif /* !WINDOWS32 */
1742 #endif /* !VMS */
1744 #else /* On Amiga */
1745 void exec_command (argv)
1746 char **argv;
1748 MyExecute (argv);
1751 void clean_tmp (void)
1753 DeleteFile (amiga_bname);
1756 #endif /* On Amiga */
1758 #ifndef VMS
1759 /* Figure out the argument list necessary to run LINE as a command. Try to
1760 avoid using a shell. This routine handles only ' quoting, and " quoting
1761 when no backslash, $ or ` characters are seen in the quotes. Starting
1762 quotes may be escaped with a backslash. If any of the characters in
1763 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1764 is the first word of a line, the shell is used.
1766 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1767 If *RESTP is NULL, newlines will be ignored.
1769 SHELL is the shell to use, or nil to use the default shell.
1770 IFS is the value of $IFS, or nil (meaning the default). */
1772 static char **
1773 construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr)
1774 char *line, **restp;
1775 char *shell, *ifs;
1776 char **batch_filename_ptr;
1778 #ifdef __MSDOS__
1779 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
1780 We call `system' for anything that requires ``slow'' processing,
1781 because DOS shells are too dumb. When $SHELL points to a real
1782 (unix-style) shell, `system' just calls it to do everything. When
1783 $SHELL points to a DOS shell, `system' does most of the work
1784 internally, calling the shell only for its internal commands.
1785 However, it looks on the $PATH first, so you can e.g. have an
1786 external command named `mkdir'.
1788 Since we call `system', certain characters and commands below are
1789 actually not specific to COMMAND.COM, but to the DJGPP implementation
1790 of `system'. In particular:
1792 The shell wildcard characters are in DOS_CHARS because they will
1793 not be expanded if we call the child via `spawnXX'.
1795 The `;' is in DOS_CHARS, because our `system' knows how to run
1796 multiple commands on a single line.
1798 DOS_CHARS also include characters special to 4DOS/NDOS, so we
1799 won't have to tell one from another and have one more set of
1800 commands and special characters. */
1801 static char sh_chars_dos[] = "*?[];|<>%^&()";
1802 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1803 "copy", "ctty", "date", "del", "dir", "echo",
1804 "erase", "exit", "for", "goto", "if", "md",
1805 "mkdir", "path", "pause", "prompt", "rd",
1806 "rmdir", "rem", "ren", "rename", "set",
1807 "shift", "time", "type", "ver", "verify",
1808 "vol", ":", 0 };
1810 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1811 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
1812 "logout", "set", "umask", "wait", "while",
1813 "for", "case", "if", ":", ".", "break",
1814 "continue", "export", "read", "readonly",
1815 "shift", "times", "trap", "switch", 0 };
1817 char *sh_chars;
1818 char **sh_cmds;
1819 #else
1820 #ifdef _AMIGA
1821 static char sh_chars[] = "#;\"|<>()?*$`";
1822 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
1823 "rename", "set", "setenv", "date", "makedir",
1824 "skip", "else", "endif", "path", "prompt",
1825 "unset", "unsetenv", "version",
1826 0 };
1827 #else
1828 #ifdef WINDOWS32
1829 static char sh_chars_dos[] = "\"|<>";
1830 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1831 "copy", "ctty", "date", "del", "dir", "echo",
1832 "erase", "exit", "for", "goto", "if", "if", "md",
1833 "mkdir", "path", "pause", "prompt", "rem", "ren",
1834 "rename", "set", "shift", "time", "type",
1835 "ver", "verify", "vol", ":", 0 };
1836 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1837 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
1838 "logout", "set", "umask", "wait", "while", "for",
1839 "case", "if", ":", ".", "break", "continue",
1840 "export", "read", "readonly", "shift", "times",
1841 "trap", "switch", "test",
1842 #ifdef BATCH_MODE_ONLY_SHELL
1843 "echo",
1844 #endif
1845 0 };
1846 char* sh_chars;
1847 char** sh_cmds;
1848 #else /* WINDOWS32 */
1849 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1850 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1851 "logout", "set", "umask", "wait", "while", "for",
1852 "case", "if", ":", ".", "break", "continue",
1853 "export", "read", "readonly", "shift", "times",
1854 "trap", "switch", 0 };
1855 #endif /* WINDOWS32 */
1856 #endif /* Amiga */
1857 #endif /* __MSDOS__ */
1858 register int i;
1859 register char *p;
1860 register char *ap;
1861 char *end;
1862 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
1863 char **new_argv = 0;
1864 #ifdef WINDOWS32
1865 int slow_flag = 0;
1867 if (no_default_sh_exe) {
1868 sh_cmds = sh_cmds_dos;
1869 sh_chars = sh_chars_dos;
1870 } else {
1871 sh_cmds = sh_cmds_sh;
1872 sh_chars = sh_chars_sh;
1874 #endif /* WINDOWS32 */
1876 if (restp != NULL)
1877 *restp = NULL;
1879 /* Make sure not to bother processing an empty line. */
1880 while (isblank (*line))
1881 ++line;
1882 if (*line == '\0')
1883 return 0;
1885 /* See if it is safe to parse commands internally. */
1886 if (shell == 0)
1887 shell = default_shell;
1888 #ifdef WINDOWS32
1889 else if (strcmp (shell, default_shell))
1891 char *s1 = _fullpath(NULL, shell, 0);
1892 char *s2 = _fullpath(NULL, default_shell, 0);
1894 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
1896 if (s1);
1897 free(s1);
1898 if (s2);
1899 free(s2);
1901 if (slow_flag)
1902 goto slow;
1903 #else /* not WINDOWS32 */
1904 #ifdef __MSDOS__
1905 else if (stricmp (shell, default_shell))
1907 extern int _is_unixy_shell (const char *_path);
1909 message (1, "$SHELL changed (was `%s', now `%s')", default_shell, shell);
1910 unixy_shell = _is_unixy_shell (shell);
1911 default_shell = shell;
1913 if (unixy_shell)
1915 sh_chars = sh_chars_sh;
1916 sh_cmds = sh_cmds_sh;
1918 else
1920 sh_chars = sh_chars_dos;
1921 sh_cmds = sh_cmds_dos;
1923 #else /* not __MSDOS__ */
1924 else if (strcmp (shell, default_shell))
1925 goto slow;
1926 #endif /* not __MSDOS__ */
1927 #endif /* not WINDOWS32 */
1929 if (ifs != 0)
1930 for (ap = ifs; *ap != '\0'; ++ap)
1931 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
1932 goto slow;
1934 i = strlen (line) + 1;
1936 /* More than 1 arg per character is impossible. */
1937 new_argv = (char **) xmalloc (i * sizeof (char *));
1939 /* All the args can fit in a buffer as big as LINE is. */
1940 ap = new_argv[0] = (char *) xmalloc (i);
1941 end = ap + i;
1943 /* I is how many complete arguments have been found. */
1944 i = 0;
1945 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
1946 for (p = line; *p != '\0'; ++p)
1948 if (ap > end)
1949 abort ();
1951 if (instring)
1953 string_char:
1954 /* Inside a string, just copy any char except a closing quote
1955 or a backslash-newline combination. */
1956 if (*p == instring)
1958 instring = 0;
1959 if (ap == new_argv[0] || *(ap-1) == '\0')
1960 last_argument_was_empty = 1;
1962 else if (*p == '\\' && p[1] == '\n')
1963 goto swallow_escaped_newline;
1964 else if (*p == '\n' && restp != NULL)
1966 /* End of the command line. */
1967 *restp = p;
1968 goto end_of_line;
1970 /* Backslash, $, and ` are special inside double quotes.
1971 If we see any of those, punt.
1972 But on MSDOS, if we use COMMAND.COM, double and single
1973 quotes have the same effect. */
1974 else if (instring == '"' && index ("\\$`", *p) != 0 && unixy_shell)
1975 goto slow;
1976 else
1977 *ap++ = *p;
1979 else if (index (sh_chars, *p) != 0)
1980 /* Not inside a string, but it's a special char. */
1981 goto slow;
1982 #ifdef __MSDOS__
1983 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
1984 /* `...' is a wildcard in DJGPP. */
1985 goto slow;
1986 #endif
1987 else
1988 /* Not a special char. */
1989 switch (*p)
1991 case '=':
1992 /* Equals is a special character in leading words before the
1993 first word with no equals sign in it. This is not the case
1994 with sh -k, but we never get here when using nonstandard
1995 shell flags. */
1996 if (! seen_nonequals && unixy_shell)
1997 goto slow;
1998 word_has_equals = 1;
1999 *ap++ = '=';
2000 break;
2002 case '\\':
2003 /* Backslash-newline combinations are eaten. */
2004 if (p[1] == '\n')
2006 swallow_escaped_newline:
2008 /* Eat the backslash, the newline, and following whitespace,
2009 replacing it all with a single space. */
2010 p += 2;
2012 /* If there is a tab after a backslash-newline,
2013 remove it from the source line which will be echoed,
2014 since it was most likely used to line
2015 up the continued line with the previous one. */
2016 if (*p == '\t')
2017 strcpy (p, p + 1);
2019 if (instring)
2020 goto string_char;
2021 else
2023 if (ap != new_argv[i])
2024 /* Treat this as a space, ending the arg.
2025 But if it's at the beginning of the arg, it should
2026 just get eaten, rather than becoming an empty arg. */
2027 goto end_of_arg;
2028 else
2029 p = next_token (p) - 1;
2032 else if (p[1] != '\0')
2034 #if defined(__MSDOS__) || defined(WINDOWS32)
2035 /* Only remove backslashes before characters special
2036 to Unixy shells. All other backslashes are copied
2037 verbatim, since they are probably DOS-style
2038 directory separators. This still leaves a small
2039 window for problems, but at least it should work
2040 for the vast majority of naive users. */
2042 #ifdef __MSDOS__
2043 /* A dot is only special as part of the "..."
2044 wildcard. */
2045 if (strncmp (p + 1, ".\\.\\.", 5) == 0)
2047 *ap++ = '.';
2048 *ap++ = '.';
2049 p += 4;
2051 else
2052 #endif
2053 if (p[1] != '\\' && p[1] != '\'' && !isspace (p[1])
2054 && (index (sh_chars_sh, p[1]) == 0))
2055 /* back up one notch, to copy the backslash */
2056 --p;
2058 #endif /* __MSDOS__ || WINDOWS32 */
2059 /* Copy and skip the following char. */
2060 *ap++ = *++p;
2062 break;
2064 case '\'':
2065 case '"':
2066 instring = *p;
2067 break;
2069 case '\n':
2070 if (restp != NULL)
2072 /* End of the command line. */
2073 *restp = p;
2074 goto end_of_line;
2076 else
2077 /* Newlines are not special. */
2078 *ap++ = '\n';
2079 break;
2081 case ' ':
2082 case '\t':
2083 end_of_arg:
2084 /* We have the end of an argument.
2085 Terminate the text of the argument. */
2086 *ap++ = '\0';
2087 new_argv[++i] = ap;
2088 last_argument_was_empty = 0;
2090 /* Update SEEN_NONEQUALS, which tells us if every word
2091 heretofore has contained an `='. */
2092 seen_nonequals |= ! word_has_equals;
2093 if (word_has_equals && ! seen_nonequals)
2094 /* An `=' in a word before the first
2095 word without one is magical. */
2096 goto slow;
2097 word_has_equals = 0; /* Prepare for the next word. */
2099 /* If this argument is the command name,
2100 see if it is a built-in shell command.
2101 If so, have the shell handle it. */
2102 if (i == 1)
2104 register int j;
2105 for (j = 0; sh_cmds[j] != 0; ++j)
2106 if (streq (sh_cmds[j], new_argv[0]))
2107 goto slow;
2110 /* Ignore multiple whitespace chars. */
2111 p = next_token (p);
2112 /* Next iteration should examine the first nonwhite char. */
2113 --p;
2114 break;
2116 default:
2117 *ap++ = *p;
2118 break;
2121 end_of_line:
2123 if (instring)
2124 /* Let the shell deal with an unterminated quote. */
2125 goto slow;
2127 /* Terminate the last argument and the argument list. */
2129 *ap = '\0';
2130 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2131 ++i;
2132 new_argv[i] = 0;
2134 if (i == 1)
2136 register int j;
2137 for (j = 0; sh_cmds[j] != 0; ++j)
2138 if (streq (sh_cmds[j], new_argv[0]))
2139 goto slow;
2142 if (new_argv[0] == 0)
2143 /* Line was empty. */
2144 return 0;
2145 else
2146 return new_argv;
2148 slow:;
2149 /* We must use the shell. */
2151 if (new_argv != 0)
2153 /* Free the old argument list we were working on. */
2154 free (new_argv[0]);
2155 free ((void *)new_argv);
2158 #ifdef __MSDOS__
2159 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2160 #endif
2162 #ifdef _AMIGA
2164 char *ptr;
2165 char *buffer;
2166 char *dptr;
2168 buffer = (char *)xmalloc (strlen (line)+1);
2170 ptr = line;
2171 for (dptr=buffer; *ptr; )
2173 if (*ptr == '\\' && ptr[1] == '\n')
2174 ptr += 2;
2175 else if (*ptr == '@') /* Kludge: multiline commands */
2177 ptr += 2;
2178 *dptr++ = '\n';
2180 else
2181 *dptr++ = *ptr++;
2183 *dptr = 0;
2185 new_argv = (char **) xmalloc(2 * sizeof(char *));
2186 new_argv[0] = buffer;
2187 new_argv[1] = 0;
2189 #else /* Not Amiga */
2190 #ifdef WINDOWS32
2192 * Not eating this whitespace caused things like
2194 * sh -c "\n"
2196 * which gave the shell fits. I think we have to eat
2197 * whitespace here, but this code should be considered
2198 * suspicious if things start failing....
2201 /* Make sure not to bother processing an empty line. */
2202 while (isspace (*line))
2203 ++line;
2204 if (*line == '\0')
2205 return 0;
2206 #endif /* WINDOWS32 */
2208 /* SHELL may be a multi-word command. Construct a command line
2209 "SHELL -c LINE", with all special chars in LINE escaped.
2210 Then recurse, expanding this command line to get the final
2211 argument list. */
2213 unsigned int shell_len = strlen (shell);
2214 static char minus_c[] = " -c ";
2215 unsigned int line_len = strlen (line);
2217 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2218 + (line_len * 2) + 1);
2219 char* command_ptr = NULL; /* used for batch_mode_shell mode */
2221 ap = new_line;
2222 bcopy (shell, ap, shell_len);
2223 ap += shell_len;
2224 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2225 ap += sizeof (minus_c) - 1;
2226 command_ptr = ap;
2227 for (p = line; *p != '\0'; ++p)
2229 if (restp != NULL && *p == '\n')
2231 *restp = p;
2232 break;
2234 else if (*p == '\\' && p[1] == '\n')
2236 /* Eat the backslash, the newline, and following whitespace,
2237 replacing it all with a single space (which is escaped
2238 from the shell). */
2239 p += 2;
2241 /* If there is a tab after a backslash-newline,
2242 remove it from the source line which will be echoed,
2243 since it was most likely used to line
2244 up the continued line with the previous one. */
2245 if (*p == '\t')
2246 bcopy (p + 1, p, strlen (p));
2248 p = next_token (p);
2249 --p;
2250 if (unixy_shell && !batch_mode_shell)
2251 *ap++ = '\\';
2252 *ap++ = ' ';
2253 continue;
2256 /* DOS shells don't know about backslash-escaping. */
2257 if (unixy_shell && !batch_mode_shell &&
2258 (*p == '\\' || *p == '\'' || *p == '"'
2259 || isspace (*p)
2260 || index (sh_chars, *p) != 0))
2261 *ap++ = '\\';
2262 #ifdef __MSDOS__
2263 else if (unixy_shell && strncmp (p, "...", 3) == 0)
2265 /* The case of `...' wildcard again. */
2266 strcpy (ap, "\\.\\.\\");
2267 ap += 5;
2268 p += 2;
2270 #endif
2271 *ap++ = *p;
2273 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2274 /* Line was empty. */
2275 return 0;
2276 *ap = '\0';
2278 #ifdef WINDOWS32
2279 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2280 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2281 cases, run commands via a script file. */
2282 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2283 FILE* batch = NULL;
2284 int id = GetCurrentProcessId();
2285 PATH_VAR(fbuf);
2286 char* fname = NULL;
2288 /* create a file name */
2289 sprintf(fbuf, "make%d", id);
2290 fname = tempnam(".", fbuf);
2292 /* create batch file name */
2293 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
2294 strcpy(*batch_filename_ptr, fname);
2296 /* make sure path name is in DOS backslash format */
2297 if (!unixy_shell) {
2298 fname = *batch_filename_ptr;
2299 for (i = 0; fname[i] != '\0'; ++i)
2300 if (fname[i] == '/')
2301 fname[i] = '\\';
2302 strcat(*batch_filename_ptr, ".bat");
2303 } else {
2304 strcat(*batch_filename_ptr, ".sh");
2307 if (debug_flag)
2308 printf("Creating temporary batch file %s\n", *batch_filename_ptr);
2310 /* create batch file to execute command */
2311 batch = fopen (*batch_filename_ptr, "w");
2312 if (!unixy_shell)
2313 fputs ("@echo off\n", batch);
2314 fputs (command_ptr, batch);
2315 fputc ('\n', batch);
2316 fclose (batch);
2318 /* create argv */
2319 new_argv = (char **) xmalloc(3 * sizeof(char *));
2320 if (unixy_shell) {
2321 new_argv[0] = xstrdup (shell);
2322 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2323 } else {
2324 new_argv[0] = xstrdup (*batch_filename_ptr);
2325 new_argv[1] = NULL;
2327 new_argv[2] = NULL;
2328 } else
2329 #endif /* WINDOWS32 */
2330 if (unixy_shell)
2331 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2332 (char *) 0, (char *) 0,
2333 (char *) 0);
2334 #ifdef __MSDOS__
2335 else
2337 /* With MSDOS shells, we must construct the command line here
2338 instead of recursively calling ourselves, because we
2339 cannot backslash-escape the special characters (see above). */
2340 new_argv = (char **) xmalloc (sizeof (char *));
2341 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2342 new_argv[0] = xmalloc (line_len + 1);
2343 strncpy (new_argv[0],
2344 new_line + shell_len + sizeof (minus_c) - 1, line_len);
2345 new_argv[0][line_len] = '\0';
2347 #else
2348 else
2349 fatal (NILF, "%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n",
2350 __FILE__, __LINE__);
2351 #endif
2353 #endif /* ! AMIGA */
2355 return new_argv;
2358 /* Figure out the argument list necessary to run LINE as a command. Try to
2359 avoid using a shell. This routine handles only ' quoting, and " quoting
2360 when no backslash, $ or ` characters are seen in the quotes. Starting
2361 quotes may be escaped with a backslash. If any of the characters in
2362 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2363 is the first word of a line, the shell is used.
2365 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2366 If *RESTP is NULL, newlines will be ignored.
2368 FILE is the target whose commands these are. It is used for
2369 variable expansion for $(SHELL) and $(IFS). */
2371 char **
2372 construct_command_argv (line, restp, file, batch_filename_ptr)
2373 char *line, **restp;
2374 struct file *file;
2375 char** batch_filename_ptr;
2377 char *shell, *ifs;
2378 char **argv;
2381 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2382 int save = warn_undefined_variables_flag;
2383 warn_undefined_variables_flag = 0;
2385 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
2386 #ifdef WINDOWS32
2388 * Convert to forward slashes so that construct_command_argv_internal()
2389 * is not confused.
2391 if (shell) {
2392 char *p = w32ify(shell, 0);
2393 strcpy(shell, p);
2395 #endif
2396 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
2398 warn_undefined_variables_flag = save;
2401 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
2403 free (shell);
2404 free (ifs);
2406 return argv;
2408 #endif /* !VMS */
2410 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2412 dup2 (old, new)
2413 int old, new;
2415 int fd;
2417 (void) close (new);
2418 fd = dup (old);
2419 if (fd != new)
2421 (void) close (fd);
2422 errno = EMFILE;
2423 return -1;
2426 return fd;
2428 #endif /* !HAPE_DUP2 && !_AMIGA */