* Added the test suite to the main distribution.
[make.git] / job.c
blobb656d6cefd308ff5f6ad0c98cf0d1ce924ab3310
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988,89,90,91,92,93,94,95,96,97,99 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 /* How to set close-on-exec for a file descriptor. */
150 #if !defined F_SETFD
151 # define CLOSE_ON_EXEC(_d)
152 #else
153 # ifndef FD_CLOEXEC
154 # define FD_CLOEXEC 1
155 # endif
156 # define CLOSE_ON_EXEC(_d) (void) fcntl ((_d), F_SETFD, FD_CLOEXEC)
157 #endif
159 #ifdef VMS
160 static int vms_jobsefnmask = 0;
161 #endif /* !VMS */
163 #ifndef HAVE_UNISTD_H
164 extern int dup2 ();
165 extern int execve ();
166 extern void _exit ();
167 # ifndef VMS
168 extern int geteuid ();
169 extern int getegid ();
170 extern int setgid ();
171 extern int getgid ();
172 # endif
173 #endif
175 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
177 extern int getloadavg PARAMS ((double loadavg[], int nelem));
178 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
179 int *is_remote, int *id_ptr, int *used_stdin));
180 extern int start_remote_job_p PARAMS ((int));
181 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
182 int *coredump_ptr, int block));
184 static void free_child PARAMS ((struct child *));
185 static void start_job_command PARAMS ((struct child *child));
186 static int load_too_high PARAMS ((void));
187 static int job_next_command PARAMS ((struct child *));
188 static int start_waiting_job PARAMS ((struct child *));
189 #ifdef VMS
190 static void vmsWaitForChildren PARAMS ((int *));
191 #endif
193 /* Chain of all live (or recently deceased) children. */
195 struct child *children = 0;
197 /* Number of children currently running. */
199 unsigned int job_slots_used = 0;
201 /* Nonzero if the `good' standard input is in use. */
203 static int good_stdin_used = 0;
205 /* Chain of children waiting to run until the load average goes down. */
207 static struct child *waiting_jobs = 0;
209 /* Non-zero if we use a *real* shell (always so on Unix). */
211 int unixy_shell = 1;
213 /* #define debug_flag 1 */
216 #ifdef WINDOWS32
218 * The macro which references this function is defined in make.h.
220 int w32_kill(int pid, int sig)
222 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
224 #endif /* WINDOWS32 */
227 /* Write an error message describing the exit status given in
228 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
229 Append "(ignored)" if IGNORED is nonzero. */
231 static void
232 child_error (target_name, exit_code, exit_sig, coredump, ignored)
233 char *target_name;
234 int exit_code, exit_sig, coredump;
235 int ignored;
237 if (ignored && silent_flag)
238 return;
240 #ifdef VMS
241 if (!(exit_code & 1))
242 error (NILF, _("*** [%s] Error 0x%x%s"), target_name, exit_code, ((ignored)? _(" (ignored)") : ""));
243 #else
244 if (exit_sig == 0)
245 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
246 _("*** [%s] Error %d"),
247 target_name, exit_code);
248 else
249 error (NILF, "*** [%s] %s%s",
250 target_name, strsignal (exit_sig),
251 coredump ? _(" (core dumped)") : "");
252 #endif /* VMS */
255 #ifdef VMS
256 /* Wait for nchildren children to terminate */
257 static void
258 vmsWaitForChildren(int *status)
260 while (1)
262 if (!vms_jobsefnmask)
264 *status = 0;
265 return;
268 *status = sys$wflor (32, vms_jobsefnmask);
270 return;
272 #endif
275 /* Handle a dead child. This handler may or may not ever be installed.
277 If we're using the jobserver feature, we need it. First, installing it
278 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
279 read FD to ensure we don't enter another blocking read without reaping all
280 the dead children. In this case we don't need the dead_children count.
282 If we don't have either waitpid or wait3, then make is unreliable, but we
283 use the dead_children count to reap children as best we can. */
285 static unsigned int dead_children = 0;
287 RETSIGTYPE
288 child_handler (sig)
289 int sig;
291 ++dead_children;
293 if (job_rfd >= 0)
295 close (job_rfd);
296 job_rfd = -1;
299 if (debug_flag)
300 printf (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children);
304 extern int shell_function_pid, shell_function_completed;
306 /* Reap all dead children, storing the returned status and the new command
307 state (`cs_finished') in the `file' member of the `struct child' for the
308 dead child, and removing the child from the chain. In addition, if BLOCK
309 nonzero, we block in this function until we've reaped at least one
310 complete child, waiting for it to die if necessary. If ERR is nonzero,
311 print an error message first. */
313 void
314 reap_children (block, err)
315 int block, err;
317 WAIT_T status;
318 /* Initially, assume we have some. */
319 int reap_more = 1;
321 #ifdef WAIT_NOHANG
322 # define REAP_MORE reap_more
323 #else
324 # define REAP_MORE dead_children
325 #endif
327 /* As long as:
329 We have at least one child outstanding OR a shell function in progress,
331 We're blocking for a complete child OR there are more children to reap
333 we'll keep reaping children. */
335 while ((children != 0 || shell_function_pid != 0) &&
336 (block || REAP_MORE))
338 int remote = 0;
339 register int pid;
340 int exit_code, exit_sig, coredump;
341 register struct child *lastc, *c;
342 int child_failed;
343 int any_remote, any_local;
345 if (err && block)
347 /* We might block for a while, so let the user know why. */
348 fflush (stdout);
349 error (NILF, _("*** Waiting for unfinished jobs...."));
352 /* We have one less dead child to reap. As noted in
353 child_handler() above, this count is completely unimportant for
354 all modern, POSIX-y systems that support wait3() or waitpid().
355 The rest of this comment below applies only to early, broken
356 pre-POSIX systems. We keep the count only because... it's there...
358 The test and decrement are not atomic; if it is compiled into:
359 register = dead_children - 1;
360 dead_children = register;
361 a SIGCHLD could come between the two instructions.
362 child_handler increments dead_children.
363 The second instruction here would lose that increment. But the
364 only effect of dead_children being wrong is that we might wait
365 longer than necessary to reap a child, and lose some parallelism;
366 and we might print the "Waiting for unfinished jobs" message above
367 when not necessary. */
369 if (dead_children > 0)
370 --dead_children;
372 any_remote = 0;
373 any_local = shell_function_pid != 0;
374 for (c = children; c != 0; c = c->next)
376 any_remote |= c->remote;
377 any_local |= ! c->remote;
378 if (debug_flag)
379 printf (_("Live child 0x%08lx (%s) PID %ld %s\n"),
380 (unsigned long int) c, c->file->name,
381 (long) c->pid, c->remote ? _(" (remote)") : "");
382 #ifdef VMS
383 break;
384 #endif
387 /* First, check for remote children. */
388 if (any_remote)
389 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
390 else
391 pid = 0;
393 if (pid > 0)
394 /* We got a remote child. */
395 remote = 1;
396 else if (pid < 0)
398 /* A remote status command failed miserably. Punt. */
399 remote_status_lose:
400 if (EINTR_SET)
401 continue;
403 pfatal_with_name ("remote_status");
405 else
407 /* No remote children. Check for local children. */
408 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
409 if (any_local)
411 local_wait:
412 #ifdef VMS
413 vmsWaitForChildren (&status);
414 pid = c->pid;
415 #else
416 #ifdef WAIT_NOHANG
417 if (!block)
418 pid = WAIT_NOHANG (&status);
419 else
420 #endif
421 pid = wait (&status);
422 #endif /* !VMS */
424 else
425 pid = 0;
427 if (pid < 0)
429 /* EINTR? Try again. */
430 if (EINTR_SET)
431 goto local_wait;
433 /* The wait*() failed miserably. Punt. */
434 pfatal_with_name ("wait");
436 else if (pid > 0)
438 /* We got a child exit; chop the status word up. */
439 exit_code = WEXITSTATUS (status);
440 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
441 coredump = WCOREDUMP (status);
443 else
445 /* No local children are dead. */
446 reap_more = 0;
448 if (!block || !any_remote)
449 break;
451 /* Now try a blocking wait for a remote child. */
452 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
453 if (pid < 0)
454 goto remote_status_lose;
455 else if (pid == 0)
456 /* No remote children either. Finally give up. */
457 break;
459 /* We got a remote child. */
460 remote = 1;
462 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
464 #ifdef __MSDOS__
465 /* Life is very different on MSDOS. */
466 pid = dos_pid - 1;
467 status = dos_status;
468 exit_code = WEXITSTATUS (status);
469 if (exit_code == 0xff)
470 exit_code = -1;
471 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
472 coredump = 0;
473 #endif /* __MSDOS__ */
474 #ifdef _AMIGA
475 /* Same on Amiga */
476 pid = amiga_pid - 1;
477 status = amiga_status;
478 exit_code = amiga_status;
479 exit_sig = 0;
480 coredump = 0;
481 #endif /* _AMIGA */
482 #ifdef WINDOWS32
484 HANDLE hPID;
485 int err;
487 /* wait for anything to finish */
488 if (hPID = process_wait_for_any()) {
490 /* was an error found on this process? */
491 err = process_last_err(hPID);
493 /* get exit data */
494 exit_code = process_exit_code(hPID);
496 if (err)
497 fprintf(stderr, "make (e=%d): %s",
498 exit_code, map_windows32_error_to_string(exit_code));
500 /* signal */
501 exit_sig = process_signal(hPID);
503 /* cleanup process */
504 process_cleanup(hPID);
506 coredump = 0;
508 pid = (int) hPID;
510 #endif /* WINDOWS32 */
513 /* Check if this is the child of the `shell' function. */
514 if (!remote && pid == shell_function_pid)
516 /* It is. Leave an indicator for the `shell' function. */
517 if (exit_sig == 0 && exit_code == 127)
518 shell_function_completed = -1;
519 else
520 shell_function_completed = 1;
521 break;
524 child_failed = exit_sig != 0 || exit_code != 0;
526 /* Search for a child matching the deceased one. */
527 lastc = 0;
528 for (c = children; c != 0; lastc = c, c = c->next)
529 if (c->remote == remote && c->pid == pid)
530 break;
532 if (c == 0)
533 /* An unknown child died.
534 Ignore it; it was inherited from our invoker. */
535 continue;
537 if (debug_flag)
538 printf (_("Reaping %s child 0x%08lx PID %ld %s\n"),
539 child_failed ? _("losing") : _("winning"),
540 (unsigned long int) c, (long) c->pid,
541 c->remote ? _(" (remote)") : "");
543 if (c->sh_batch_file) {
544 if (debug_flag)
545 printf (_("Cleaning up temp batch file %s\n"), c->sh_batch_file);
547 /* just try and remove, don't care if this fails */
548 remove (c->sh_batch_file);
550 /* all done with memory */
551 free (c->sh_batch_file);
552 c->sh_batch_file = NULL;
555 /* If this child had the good stdin, say it is now free. */
556 if (c->good_stdin)
557 good_stdin_used = 0;
559 if (child_failed && !c->noerror && !ignore_errors_flag)
561 /* The commands failed. Write an error message,
562 delete non-precious targets, and abort. */
563 static int delete_on_error = -1;
564 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
565 c->file->update_status = 2;
566 if (delete_on_error == -1)
568 struct file *f = lookup_file (".DELETE_ON_ERROR");
569 delete_on_error = f != 0 && f->is_target;
571 if (exit_sig != 0 || delete_on_error)
572 delete_child_targets (c);
574 else
576 if (child_failed)
578 /* The commands failed, but we don't care. */
579 child_error (c->file->name,
580 exit_code, exit_sig, coredump, 1);
581 child_failed = 0;
584 /* If there are more commands to run, try to start them. */
585 if (job_next_command (c))
587 if (handling_fatal_signal)
589 /* Never start new commands while we are dying.
590 Since there are more commands that wanted to be run,
591 the target was not completely remade. So we treat
592 this as if a command had failed. */
593 c->file->update_status = 2;
595 else
597 /* Check again whether to start remotely.
598 Whether or not we want to changes over time.
599 Also, start_remote_job may need state set up
600 by start_remote_job_p. */
601 c->remote = start_remote_job_p (0);
602 start_job_command (c);
603 /* Fatal signals are left blocked in case we were
604 about to put that child on the chain. But it is
605 already there, so it is safe for a fatal signal to
606 arrive now; it will clean up this child's targets. */
607 unblock_sigs ();
608 if (c->file->command_state == cs_running)
609 /* We successfully started the new command.
610 Loop to reap more children. */
611 continue;
614 if (c->file->update_status != 0)
615 /* We failed to start the commands. */
616 delete_child_targets (c);
618 else
619 /* There are no more commands. We got through them all
620 without an unignored error. Now the target has been
621 successfully updated. */
622 c->file->update_status = 0;
625 /* When we get here, all the commands for C->file are finished
626 (or aborted) and C->file->update_status contains 0 or 2. But
627 C->file->command_state is still cs_running if all the commands
628 ran; notice_finish_file looks for cs_running to tell it that
629 it's interesting to check the file's modtime again now. */
631 if (! handling_fatal_signal)
632 /* Notice if the target of the commands has been changed.
633 This also propagates its values for command_state and
634 update_status to its also_make files. */
635 notice_finished_file (c->file);
637 if (debug_flag)
638 printf (_("Removing child 0x%08lx PID %ld %s from chain.\n"),
639 (unsigned long int) c, (long) c->pid,
640 c->remote ? _(" (remote)") : "");
642 /* Block fatal signals while frobnicating the list, so that
643 children and job_slots_used are always consistent. Otherwise
644 a fatal signal arriving after the child is off the chain and
645 before job_slots_used is decremented would believe a child was
646 live and call reap_children again. */
647 block_sigs ();
649 /* There is now another slot open. */
650 if (job_slots_used > 0)
651 --job_slots_used;
653 /* Remove the child from the chain and free it. */
654 if (lastc == 0)
655 children = c->next;
656 else
657 lastc->next = c->next;
659 free_child (c);
661 unblock_sigs ();
663 /* If the job failed, and the -k flag was not given, die,
664 unless we are already in the process of dying. */
665 if (!err && child_failed && !keep_going_flag &&
666 /* fatal_error_signal will die with the right signal. */
667 !handling_fatal_signal)
668 die (2);
670 /* Only block for one child. */
671 block = 0;
674 return;
677 /* Free the storage allocated for CHILD. */
679 static void
680 free_child (child)
681 register struct child *child;
683 /* If this child is the only one it was our "free" job, so don't put a
684 token back for it. This child has already been removed from the list,
685 so if there any left this wasn't the last one. */
687 if (job_fds[1] >= 0 && children)
689 char token = '+';
691 /* Write a job token back to the pipe. */
693 while (write (job_fds[1], &token, 1) != 1)
694 if (!EINTR_SET)
695 pfatal_with_name (_("write jobserver"));
697 if (debug_flag)
698 printf (_("Released token for child 0x%08lx (%s).\n"),
699 (unsigned long int) child, child->file->name);
702 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
703 return;
705 if (child->command_lines != 0)
707 register unsigned int i;
708 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
709 free (child->command_lines[i]);
710 free ((char *) child->command_lines);
713 if (child->environment != 0)
715 register char **ep = child->environment;
716 while (*ep != 0)
717 free (*ep++);
718 free ((char *) child->environment);
721 free ((char *) child);
724 #ifdef POSIX
725 extern sigset_t fatal_signal_set;
726 #endif
728 void
729 block_sigs ()
731 #ifdef POSIX
732 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
733 #else
734 # ifdef HAVE_SIGSETMASK
735 (void) sigblock (fatal_signal_mask);
736 # endif
737 #endif
740 #ifdef POSIX
741 void
742 unblock_sigs ()
744 sigset_t empty;
745 sigemptyset (&empty);
746 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
748 #endif
750 /* Start a job to run the commands specified in CHILD.
751 CHILD is updated to reflect the commands and ID of the child process.
753 NOTE: On return fatal signals are blocked! The caller is responsible
754 for calling `unblock_sigs', once the new child is safely on the chain so
755 it can be cleaned up in the event of a fatal signal. */
757 static void
758 start_job_command (child)
759 register struct child *child;
761 #ifndef _AMIGA
762 static int bad_stdin = -1;
763 #endif
764 register char *p;
765 int flags;
766 #ifdef VMS
767 char *argv;
768 #else
769 char **argv;
770 #endif
772 /* If we have a completely empty commandset, stop now. */
773 if (!child->command_ptr)
774 goto next_command;
776 /* Combine the flags parsed for the line itself with
777 the flags specified globally for this target. */
778 flags = (child->file->command_flags
779 | child->file->cmds->lines_flags[child->command_line - 1]);
781 p = child->command_ptr;
782 child->noerror = flags & COMMANDS_NOERROR;
784 while (*p != '\0')
786 if (*p == '@')
787 flags |= COMMANDS_SILENT;
788 else if (*p == '+')
789 flags |= COMMANDS_RECURSE;
790 else if (*p == '-')
791 child->noerror = 1;
792 else if (!isblank (*p))
793 break;
794 ++p;
797 /* If -q was given, just say that updating `failed'. The exit status of
798 1 tells the user that -q is saying `something to do'; the exit status
799 for a random error is 2. */
800 if (question_flag && !(flags & COMMANDS_RECURSE))
802 child->file->update_status = 1;
803 notice_finished_file (child->file);
804 return;
807 /* There may be some preceding whitespace left if there
808 was nothing but a backslash on the first line. */
809 p = next_token (p);
811 /* Figure out an argument list from this command line. */
814 char *end = 0;
815 #ifdef VMS
816 argv = p;
817 #else
818 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
819 #endif
820 if (end == NULL)
821 child->command_ptr = NULL;
822 else
824 *end++ = '\0';
825 child->command_ptr = end;
829 if (touch_flag && !(flags & COMMANDS_RECURSE))
831 /* Go on to the next command. It might be the recursive one.
832 We construct ARGV only to find the end of the command line. */
833 #ifndef VMS
834 free (argv[0]);
835 free ((char *) argv);
836 #endif
837 argv = 0;
840 if (argv == 0)
842 next_command:
843 #ifdef __MSDOS__
844 execute_by_shell = 0; /* in case construct_command_argv sets it */
845 #endif
846 /* This line has no commands. Go to the next. */
847 if (job_next_command (child))
848 start_job_command (child);
849 else
851 /* No more commands. Make sure we're "running"; we might not be if
852 (e.g.) all commands were skipped due to -n. */
853 set_command_state (child->file, cs_running);
854 child->file->update_status = 0;
855 notice_finished_file (child->file);
857 return;
860 /* Print out the command. If silent, we call `message' with null so it
861 can log the working directory before the command's own error messages
862 appear. */
864 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
865 ? "%s" : (char *) 0, p);
867 /* Optimize an empty command. People use this for timestamp rules,
868 so avoid forking a useless shell. */
870 #if !defined(VMS) && !defined(_AMIGA)
871 if (
872 #ifdef __MSDOS__
873 unixy_shell /* the test is complicated and we already did it */
874 #else
875 (argv[0] && !strcmp (argv[0], "/bin/sh"))
876 #endif
877 && (argv[1]
878 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
879 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
880 && argv[3] == NULL)
882 free (argv[0]);
883 free ((char *) argv);
884 goto next_command;
886 #endif /* !VMS && !_AMIGA */
888 /* Tell update_goal_chain that a command has been started on behalf of
889 this target. It is important that this happens here and not in
890 reap_children (where we used to do it), because reap_children might be
891 reaping children from a different target. We want this increment to
892 guaranteedly indicate that a command was started for the dependency
893 chain (i.e., update_file recursion chain) we are processing. */
895 ++commands_started;
897 /* If -n was given, recurse to get the next line in the sequence. */
899 if (just_print_flag && !(flags & COMMANDS_RECURSE))
901 #ifndef VMS
902 free (argv[0]);
903 free ((char *) argv);
904 #endif
905 goto next_command;
908 /* Flush the output streams so they won't have things written twice. */
910 fflush (stdout);
911 fflush (stderr);
913 #ifndef VMS
914 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
916 /* Set up a bad standard input that reads from a broken pipe. */
918 if (bad_stdin == -1)
920 /* Make a file descriptor that is the read end of a broken pipe.
921 This will be used for some children's standard inputs. */
922 int pd[2];
923 if (pipe (pd) == 0)
925 /* Close the write side. */
926 (void) close (pd[1]);
927 /* Save the read side. */
928 bad_stdin = pd[0];
930 /* Set the descriptor to close on exec, so it does not litter any
931 child's descriptor table. When it is dup2'd onto descriptor 0,
932 that descriptor will not close on exec. */
933 CLOSE_ON_EXEC (bad_stdin);
937 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
939 /* Decide whether to give this child the `good' standard input
940 (one that points to the terminal or whatever), or the `bad' one
941 that points to the read side of a broken pipe. */
943 child->good_stdin = !good_stdin_used;
944 if (child->good_stdin)
945 good_stdin_used = 1;
947 #endif /* !VMS */
949 child->deleted = 0;
951 #ifndef _AMIGA
952 /* Set up the environment for the child. */
953 if (child->environment == 0)
954 child->environment = target_environment (child->file);
955 #endif
957 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
959 #ifndef VMS
960 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
961 if (child->remote)
963 int is_remote, id, used_stdin;
964 if (start_remote_job (argv, child->environment,
965 child->good_stdin ? 0 : bad_stdin,
966 &is_remote, &id, &used_stdin))
967 /* Don't give up; remote execution may fail for various reasons. If
968 so, simply run the job locally. */
969 goto run_local;
970 else
972 if (child->good_stdin && !used_stdin)
974 child->good_stdin = 0;
975 good_stdin_used = 0;
977 child->remote = is_remote;
978 child->pid = id;
981 else
982 #endif /* !VMS */
984 /* Fork the child process. */
986 char **parent_environ;
988 run_local:
989 block_sigs ();
991 child->remote = 0;
993 #ifdef VMS
995 if (!child_execute_job (argv, child)) {
996 /* Fork failed! */
997 perror_with_name ("vfork", "");
998 goto error;
1001 #else
1003 parent_environ = environ;
1004 child->pid = vfork ();
1005 environ = parent_environ; /* Restore value child may have clobbered. */
1006 if (child->pid == 0)
1008 /* We are the child side. */
1009 unblock_sigs ();
1011 /* If we aren't running a recursive command and we have a jobserver
1012 pipe, close it before exec'ing. */
1013 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1015 close (job_fds[0]);
1016 close (job_fds[1]);
1018 if (job_rfd >= 0)
1019 close (job_rfd);
1021 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1022 argv, child->environment);
1024 else if (child->pid < 0)
1026 /* Fork failed! */
1027 unblock_sigs ();
1028 perror_with_name ("vfork", "");
1029 goto error;
1031 #endif /* !VMS */
1034 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1035 #ifdef __MSDOS__
1037 int proc_return;
1039 block_sigs ();
1040 dos_status = 0;
1042 /* We call `system' to do the job of the SHELL, since stock DOS
1043 shell is too dumb. Our `system' knows how to handle long
1044 command lines even if pipes/redirection is needed; it will only
1045 call COMMAND.COM when its internal commands are used. */
1046 if (execute_by_shell)
1048 char *cmdline = argv[0];
1049 /* We don't have a way to pass environment to `system',
1050 so we need to save and restore ours, sigh... */
1051 char **parent_environ = environ;
1053 environ = child->environment;
1055 /* If we have a *real* shell, tell `system' to call
1056 it to do everything for us. */
1057 if (unixy_shell)
1059 /* A *real* shell on MSDOS may not support long
1060 command lines the DJGPP way, so we must use `system'. */
1061 cmdline = argv[2]; /* get past "shell -c" */
1064 dos_command_running = 1;
1065 proc_return = system (cmdline);
1066 environ = parent_environ;
1067 execute_by_shell = 0; /* for the next time */
1069 else
1071 dos_command_running = 1;
1072 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1075 /* Need to unblock signals before turning off
1076 dos_command_running, so that child's signals
1077 will be treated as such (see fatal_error_signal). */
1078 unblock_sigs ();
1079 dos_command_running = 0;
1081 /* If the child got a signal, dos_status has its
1082 high 8 bits set, so be careful not to alter them. */
1083 if (proc_return == -1)
1084 dos_status |= 0xff;
1085 else
1086 dos_status |= (proc_return & 0xff);
1087 ++dead_children;
1088 child->pid = dos_pid++;
1090 #endif /* __MSDOS__ */
1091 #ifdef _AMIGA
1092 amiga_status = MyExecute (argv);
1094 ++dead_children;
1095 child->pid = amiga_pid++;
1096 if (amiga_batch_file)
1098 amiga_batch_file = 0;
1099 DeleteFile (amiga_bname); /* Ignore errors. */
1101 #endif /* Amiga */
1102 #ifdef WINDOWS32
1104 HANDLE hPID;
1105 char* arg0;
1107 /* make UNC paths safe for CreateProcess -- backslash format */
1108 arg0 = argv[0];
1109 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1110 for ( ; arg0 && *arg0; arg0++)
1111 if (*arg0 == '/')
1112 *arg0 = '\\';
1114 /* make sure CreateProcess() has Path it needs */
1115 sync_Path_environment();
1117 hPID = process_easy(argv, child->environment);
1119 if (hPID != INVALID_HANDLE_VALUE)
1120 child->pid = (int) hPID;
1121 else {
1122 int i;
1123 unblock_sigs();
1124 fprintf(stderr,
1125 _("process_easy() failed failed to launch process (e=%d)\n"),
1126 process_last_err(hPID));
1127 for (i = 0; argv[i]; i++)
1128 fprintf(stderr, "%s ", argv[i]);
1129 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1132 #endif /* WINDOWS32 */
1133 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1135 /* We are the parent side. Set the state to
1136 say the commands are running and return. */
1138 set_command_state (child->file, cs_running);
1140 /* Free the storage used by the child's argument list. */
1141 #ifndef VMS
1142 free (argv[0]);
1143 free ((char *) argv);
1144 #endif
1146 return;
1148 error:
1149 child->file->update_status = 2;
1150 notice_finished_file (child->file);
1151 return;
1154 /* Try to start a child running.
1155 Returns nonzero if the child was started (and maybe finished), or zero if
1156 the load was too high and the child was put on the `waiting_jobs' chain. */
1158 static int
1159 start_waiting_job (c)
1160 struct child *c;
1162 struct file *f = c->file;
1164 /* If we can start a job remotely, we always want to, and don't care about
1165 the local load average. We record that the job should be started
1166 remotely in C->remote for start_job_command to test. */
1168 c->remote = start_remote_job_p (1);
1170 /* If we are running at least one job already and the load average
1171 is too high, make this one wait. */
1172 if (!c->remote && job_slots_used > 0 && load_too_high ())
1174 /* Put this child on the chain of children waiting for the load average
1175 to go down. */
1176 set_command_state (f, cs_running);
1177 c->next = waiting_jobs;
1178 waiting_jobs = c;
1179 return 0;
1182 /* Start the first command; reap_children will run later command lines. */
1183 start_job_command (c);
1185 switch (f->command_state)
1187 case cs_running:
1188 c->next = children;
1189 if (debug_flag)
1190 printf (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1191 (unsigned long int) c, c->file->name,
1192 (long) c->pid, c->remote ? _(" (remote)") : "");
1193 children = c;
1194 /* One more job slot is in use. */
1195 ++job_slots_used;
1196 unblock_sigs ();
1197 break;
1199 case cs_not_started:
1200 /* All the command lines turned out to be empty. */
1201 f->update_status = 0;
1202 /* FALLTHROUGH */
1204 case cs_finished:
1205 notice_finished_file (f);
1206 free_child (c);
1207 break;
1209 default:
1210 assert (f->command_state == cs_finished);
1211 break;
1214 return 1;
1217 /* Create a `struct child' for FILE and start its commands running. */
1219 void
1220 new_job (file)
1221 register struct file *file;
1223 register struct commands *cmds = file->cmds;
1224 register struct child *c;
1225 char **lines;
1226 register unsigned int i;
1228 /* Let any previously decided-upon jobs that are waiting
1229 for the load to go down start before this new one. */
1230 start_waiting_jobs ();
1232 /* Reap any children that might have finished recently. */
1233 reap_children (0, 0);
1235 /* Chop the commands up into lines if they aren't already. */
1236 chop_commands (cmds);
1238 /* Expand the command lines and store the results in LINES. */
1239 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1240 for (i = 0; i < cmds->ncommand_lines; ++i)
1242 /* Collapse backslash-newline combinations that are inside variable
1243 or function references. These are left alone by the parser so
1244 that they will appear in the echoing of commands (where they look
1245 nice); and collapsed by construct_command_argv when it tokenizes.
1246 But letting them survive inside function invocations loses because
1247 we don't want the functions to see them as part of the text. */
1249 char *in, *out, *ref;
1251 /* IN points to where in the line we are scanning.
1252 OUT points to where in the line we are writing.
1253 When we collapse a backslash-newline combination,
1254 IN gets ahead of OUT. */
1256 in = out = cmds->command_lines[i];
1257 while ((ref = index (in, '$')) != 0)
1259 ++ref; /* Move past the $. */
1261 if (out != in)
1262 /* Copy the text between the end of the last chunk
1263 we processed (where IN points) and the new chunk
1264 we are about to process (where REF points). */
1265 bcopy (in, out, ref - in);
1267 /* Move both pointers past the boring stuff. */
1268 out += ref - in;
1269 in = ref;
1271 if (*ref == '(' || *ref == '{')
1273 char openparen = *ref;
1274 char closeparen = openparen == '(' ? ')' : '}';
1275 int count;
1276 char *p;
1278 *out++ = *in++; /* Copy OPENPAREN. */
1279 /* IN now points past the opening paren or brace.
1280 Count parens or braces until it is matched. */
1281 count = 0;
1282 while (*in != '\0')
1284 if (*in == closeparen && --count < 0)
1285 break;
1286 else if (*in == '\\' && in[1] == '\n')
1288 /* We have found a backslash-newline inside a
1289 variable or function reference. Eat it and
1290 any following whitespace. */
1292 int quoted = 0;
1293 for (p = in - 1; p > ref && *p == '\\'; --p)
1294 quoted = !quoted;
1296 if (quoted)
1297 /* There were two or more backslashes, so this is
1298 not really a continuation line. We don't collapse
1299 the quoting backslashes here as is done in
1300 collapse_continuations, because the line will
1301 be collapsed again after expansion. */
1302 *out++ = *in++;
1303 else
1305 /* Skip the backslash, newline and
1306 any following whitespace. */
1307 in = next_token (in + 2);
1309 /* Discard any preceding whitespace that has
1310 already been written to the output. */
1311 while (out > ref && isblank (out[-1]))
1312 --out;
1314 /* Replace it all with a single space. */
1315 *out++ = ' ';
1318 else
1320 if (*in == openparen)
1321 ++count;
1323 *out++ = *in++;
1329 /* There are no more references in this line to worry about.
1330 Copy the remaining uninteresting text to the output. */
1331 if (out != in)
1332 strcpy (out, in);
1334 /* Finally, expand the line. */
1335 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1336 file);
1339 /* Start the command sequence, record it in a new
1340 `struct child', and add that to the chain. */
1342 c = (struct child *) xmalloc (sizeof (struct child));
1343 c->file = file;
1344 c->command_lines = lines;
1345 c->command_line = 0;
1346 c->command_ptr = 0;
1347 c->environment = 0;
1348 c->sh_batch_file = NULL;
1350 /* Fetch the first command line to be run. */
1351 job_next_command (c);
1353 /* Wait for a job slot to be freed up. If we allow an infinite number
1354 don't bother; also job_slots will == 0 if we're using the jobserver. */
1356 if (job_slots != 0)
1357 while (job_slots_used == job_slots)
1358 reap_children (1, 0);
1360 #ifdef MAKE_JOBSERVER
1361 /* If we are controlling multiple jobs make sure we have a token before
1362 starting the child. */
1364 /* This can be inefficient. There's a decent chance that this job won't
1365 actually have to run any subprocesses: the command script may be empty
1366 or otherwise optimized away. It would be nice if we could defer
1367 obtaining a token until just before we need it, in start_job_command.
1368 To do that we'd need to keep track of whether we'd already obtained a
1369 token (since start_job_command is called for each line of the job, not
1370 just once). Also more thought needs to go into the entire algorithm;
1371 this is where the old parallel job code waits, so... */
1373 else if (job_fds[0] >= 0)
1374 while (1)
1376 char token;
1378 /* If we don't already have a job started, use our "free" token. */
1379 if (!children)
1380 break;
1382 /* Read a token. As long as there's no token available we'll block.
1383 If we get a SIGCHLD we'll return with EINTR. If one happened
1384 before we got here we'll return immediately with EBADF because
1385 the signal handler closes the dup'd file descriptor. */
1387 if (read (job_rfd, &token, 1) == 1)
1389 if (debug_flag)
1390 printf (_("Obtained token for child 0x%08lx (%s).\n"),
1391 (unsigned long int) c, c->file->name);
1392 break;
1395 if (errno != EINTR && errno != EBADF)
1396 pfatal_with_name (_("read jobs pipe"));
1398 /* Re-dup the read side of the pipe, so the signal handler can
1399 notify us if we miss a child. */
1400 if (job_rfd < 0)
1401 job_rfd = dup (job_fds[0]);
1403 /* Something's done. We don't want to block for a whole child,
1404 just reap whatever's there. */
1405 reap_children (0, 0);
1407 #endif
1409 /* The job is now primed. Start it running.
1410 (This will notice if there are in fact no commands.) */
1411 (void) start_waiting_job (c);
1413 if (job_slots == 1)
1414 /* Since there is only one job slot, make things run linearly.
1415 Wait for the child to die, setting the state to `cs_finished'. */
1416 while (file->command_state == cs_running)
1417 reap_children (1, 0);
1419 return;
1422 /* Move CHILD's pointers to the next command for it to execute.
1423 Returns nonzero if there is another command. */
1425 static int
1426 job_next_command (child)
1427 struct child *child;
1429 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1431 /* There are no more lines in the expansion of this line. */
1432 if (child->command_line == child->file->cmds->ncommand_lines)
1434 /* There are no more lines to be expanded. */
1435 child->command_ptr = 0;
1436 return 0;
1438 else
1439 /* Get the next line to run. */
1440 child->command_ptr = child->command_lines[child->command_line++];
1442 return 1;
1445 static int
1446 load_too_high ()
1448 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1449 return 1;
1450 #else
1451 double load;
1453 if (max_load_average < 0)
1454 return 0;
1456 make_access ();
1457 if (getloadavg (&load, 1) != 1)
1459 static int lossage = -1;
1460 /* Complain only once for the same error. */
1461 if (lossage == -1 || errno != lossage)
1463 if (errno == 0)
1464 /* An errno value of zero means getloadavg is just unsupported. */
1465 error (NILF, _("cannot enforce load limits on this operating system"));
1466 else
1467 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1469 lossage = errno;
1470 load = 0;
1472 user_access ();
1474 return load >= max_load_average;
1475 #endif
1478 /* Start jobs that are waiting for the load to be lower. */
1480 void
1481 start_waiting_jobs ()
1483 struct child *job;
1485 if (waiting_jobs == 0)
1486 return;
1490 /* Check for recently deceased descendants. */
1491 reap_children (0, 0);
1493 /* Take a job off the waiting list. */
1494 job = waiting_jobs;
1495 waiting_jobs = job->next;
1497 /* Try to start that job. We break out of the loop as soon
1498 as start_waiting_job puts one back on the waiting list. */
1500 while (start_waiting_job (job) && waiting_jobs != 0);
1502 return;
1505 #ifndef WINDOWS32
1506 #ifdef VMS
1507 #include <descrip.h>
1508 #include <clidef.h>
1510 /* This is called as an AST when a child process dies (it won't get
1511 interrupted by anything except a higher level AST).
1513 int vmsHandleChildTerm(struct child *child)
1515 int status;
1516 register struct child *lastc, *c;
1517 int child_failed;
1519 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1521 lib$free_ef(&child->efn);
1523 (void) sigblock (fatal_signal_mask);
1525 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1527 /* Search for a child matching the deceased one. */
1528 lastc = 0;
1529 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1530 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1531 #else
1532 c = child;
1533 #endif
1535 if (child_failed && !c->noerror && !ignore_errors_flag)
1537 /* The commands failed. Write an error message,
1538 delete non-precious targets, and abort. */
1539 child_error (c->file->name, c->cstatus, 0, 0, 0);
1540 c->file->update_status = 1;
1541 delete_child_targets (c);
1543 else
1545 if (child_failed)
1547 /* The commands failed, but we don't care. */
1548 child_error (c->file->name, c->cstatus, 0, 0, 1);
1549 child_failed = 0;
1552 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1553 /* If there are more commands to run, try to start them. */
1554 start_job (c);
1556 switch (c->file->command_state)
1558 case cs_running:
1559 /* Successfully started. */
1560 break;
1562 case cs_finished:
1563 if (c->file->update_status != 0) {
1564 /* We failed to start the commands. */
1565 delete_child_targets (c);
1567 break;
1569 default:
1570 error (NILF, _("internal error: `%s' command_state"), c->file->name);
1571 abort ();
1572 break;
1574 #endif /* RECURSIVEJOBS */
1577 /* Set the state flag to say the commands have finished. */
1578 c->file->command_state = cs_finished;
1579 notice_finished_file (c->file);
1581 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1582 /* Remove the child from the chain and free it. */
1583 if (lastc == 0)
1584 children = c->next;
1585 else
1586 lastc->next = c->next;
1587 free_child (c);
1588 #endif /* RECURSIVEJOBS */
1590 /* There is now another slot open. */
1591 if (job_slots_used > 0)
1592 --job_slots_used;
1594 /* If the job failed, and the -k flag was not given, die. */
1595 if (child_failed && !keep_going_flag)
1596 die (EXIT_FAILURE);
1598 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1600 return 1;
1603 /* VMS:
1604 Spawn a process executing the command in ARGV and return its pid. */
1606 #define MAXCMDLEN 200
1609 child_execute_job (argv, child)
1610 char *argv;
1611 struct child *child;
1613 int i;
1614 static struct dsc$descriptor_s cmddsc;
1615 #ifndef DONTWAITFORCHILD
1616 int spflags = 0;
1617 #else
1618 int spflags = CLI$M_NOWAIT;
1619 #endif
1620 int status;
1621 char cmd[4096],*p,*c;
1622 char comname[50];
1624 /* Remove backslashes */
1625 for (p = argv, c = cmd; *p; p++,c++)
1627 if (*p == '\\') p++;
1628 *c = *p;
1630 *c = *p;
1632 /* Check for maximum DCL length and create *.com file if neccesary.
1633 Also create a .com file if the command is more than one line long. */
1635 comname[0] = '\0';
1637 if (strlen (cmd) > MAXCMDLEN || strchr (cmd, '\n'))
1639 FILE *outfile;
1640 char tmp;
1642 strcpy (comname, "sys$scratch:CMDXXXXXX.COM");
1643 (void) mktemp (comname);
1645 outfile = fopen (comname, "w");
1646 if (outfile == 0)
1647 pfatal_with_name (comname);
1649 fprintf (outfile, "$ ");
1650 c = cmd;
1652 while (c)
1654 p = strchr (c, ',');
1655 if ((p == NULL) || (p-c > MAXCMDLEN))
1656 p = strchr (c, ' ');
1657 if (p != NULL)
1659 p++;
1660 tmp = *p;
1661 *p = '\0';
1663 else
1664 tmp = '\0';
1665 fprintf (outfile, "%s%s\n", c, (tmp == '\0')?"":" -");
1666 if (p != NULL)
1667 *p = tmp;
1668 c = p;
1671 fclose (outfile);
1673 sprintf (cmd, "$ @%s", comname);
1675 if (debug_flag)
1676 printf (_("Executing %s instead\n"), cmd);
1679 cmddsc.dsc$w_length = strlen(cmd);
1680 cmddsc.dsc$a_pointer = cmd;
1681 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
1682 cmddsc.dsc$b_class = DSC$K_CLASS_S;
1684 child->efn = 0;
1685 while (child->efn < 32 || child->efn > 63)
1687 status = lib$get_ef(&child->efn);
1688 if (!(status & 1))
1689 return 0;
1692 sys$clref(child->efn);
1694 vms_jobsefnmask |= (1 << (child->efn - 32));
1696 #ifndef DONTWAITFORCHILD
1697 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1698 &child->efn,0,0);
1699 vmsHandleChildTerm(child);
1700 #else
1701 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1702 &child->efn,vmsHandleChildTerm,child);
1703 #endif
1705 if (!(status & 1))
1707 printf(_("Error spawning, %d\n"),status);
1708 fflush(stdout);
1711 unlink (comname);
1713 return (status & 1);
1716 #else /* !VMS */
1718 #if !defined (_AMIGA) && !defined (__MSDOS__)
1719 /* UNIX:
1720 Replace the current process with one executing the command in ARGV.
1721 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1722 the environment of the new program. This function does not return. */
1724 void
1725 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1726 int stdin_fd, stdout_fd;
1727 char **argv, **envp;
1729 if (stdin_fd != 0)
1730 (void) dup2 (stdin_fd, 0);
1731 if (stdout_fd != 1)
1732 (void) dup2 (stdout_fd, 1);
1733 if (stdin_fd != 0)
1734 (void) close (stdin_fd);
1735 if (stdout_fd != 1)
1736 (void) close (stdout_fd);
1738 /* Run the command. */
1739 exec_command (argv, envp);
1741 #endif /* !AMIGA && !__MSDOS__ */
1742 #endif /* !VMS */
1743 #endif /* !WINDOWS32 */
1745 #ifndef _AMIGA
1746 /* Replace the current process with one running the command in ARGV,
1747 with environment ENVP. This function does not return. */
1749 void
1750 exec_command (argv, envp)
1751 char **argv, **envp;
1753 #ifdef VMS
1754 /* Run the program. */
1755 execve (argv[0], argv, envp);
1756 perror_with_name ("execve: ", argv[0]);
1757 _exit (EXIT_FAILURE);
1758 #else
1759 #ifdef WINDOWS32
1760 HANDLE hPID;
1761 HANDLE hWaitPID;
1762 int err = 0;
1763 int exit_code = EXIT_FAILURE;
1765 /* make sure CreateProcess() has Path it needs */
1766 sync_Path_environment();
1768 /* launch command */
1769 hPID = process_easy(argv, envp);
1771 /* make sure launch ok */
1772 if (hPID == INVALID_HANDLE_VALUE)
1774 int i;
1775 fprintf(stderr,
1776 _("process_easy() failed failed to launch process (e=%d)\n"),
1777 process_last_err(hPID));
1778 for (i = 0; argv[i]; i++)
1779 fprintf(stderr, "%s ", argv[i]);
1780 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1781 exit(EXIT_FAILURE);
1784 /* wait and reap last child */
1785 while (hWaitPID = process_wait_for_any())
1787 /* was an error found on this process? */
1788 err = process_last_err(hWaitPID);
1790 /* get exit data */
1791 exit_code = process_exit_code(hWaitPID);
1793 if (err)
1794 fprintf(stderr, "make (e=%d, rc=%d): %s",
1795 err, exit_code, map_windows32_error_to_string(err));
1797 /* cleanup process */
1798 process_cleanup(hWaitPID);
1800 /* expect to find only last pid, warn about other pids reaped */
1801 if (hWaitPID == hPID)
1802 break;
1803 else
1804 fprintf(stderr,
1805 _("make reaped child pid %d, still waiting for pid %d\n"),
1806 hWaitPID, hPID);
1809 /* return child's exit code as our exit code */
1810 exit(exit_code);
1812 #else /* !WINDOWS32 */
1814 /* Be the user, permanently. */
1815 child_access ();
1817 /* Run the program. */
1818 environ = envp;
1819 execvp (argv[0], argv);
1821 switch (errno)
1823 case ENOENT:
1824 error (NILF, _("%s: Command not found"), argv[0]);
1825 break;
1826 case ENOEXEC:
1828 /* The file is not executable. Try it as a shell script. */
1829 extern char *getenv ();
1830 char *shell;
1831 char **new_argv;
1832 int argc;
1834 shell = getenv ("SHELL");
1835 if (shell == 0)
1836 shell = default_shell;
1838 argc = 1;
1839 while (argv[argc] != 0)
1840 ++argc;
1842 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1843 new_argv[0] = shell;
1844 new_argv[1] = argv[0];
1845 while (argc > 0)
1847 new_argv[1 + argc] = argv[argc];
1848 --argc;
1851 execvp (shell, new_argv);
1852 if (errno == ENOENT)
1853 error (NILF, _("%s: Shell program not found"), shell);
1854 else
1855 perror_with_name ("execvp: ", shell);
1856 break;
1859 default:
1860 perror_with_name ("execvp: ", argv[0]);
1861 break;
1864 _exit (127);
1865 #endif /* !WINDOWS32 */
1866 #endif /* !VMS */
1868 #else /* On Amiga */
1869 void exec_command (argv)
1870 char **argv;
1872 MyExecute (argv);
1875 void clean_tmp (void)
1877 DeleteFile (amiga_bname);
1880 #endif /* On Amiga */
1882 #ifndef VMS
1883 /* Figure out the argument list necessary to run LINE as a command. Try to
1884 avoid using a shell. This routine handles only ' quoting, and " quoting
1885 when no backslash, $ or ` characters are seen in the quotes. Starting
1886 quotes may be escaped with a backslash. If any of the characters in
1887 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1888 is the first word of a line, the shell is used.
1890 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1891 If *RESTP is NULL, newlines will be ignored.
1893 SHELL is the shell to use, or nil to use the default shell.
1894 IFS is the value of $IFS, or nil (meaning the default). */
1896 static char **
1897 construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr)
1898 char *line, **restp;
1899 char *shell, *ifs;
1900 char **batch_filename_ptr;
1902 #ifdef __MSDOS__
1903 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
1904 We call `system' for anything that requires ``slow'' processing,
1905 because DOS shells are too dumb. When $SHELL points to a real
1906 (unix-style) shell, `system' just calls it to do everything. When
1907 $SHELL points to a DOS shell, `system' does most of the work
1908 internally, calling the shell only for its internal commands.
1909 However, it looks on the $PATH first, so you can e.g. have an
1910 external command named `mkdir'.
1912 Since we call `system', certain characters and commands below are
1913 actually not specific to COMMAND.COM, but to the DJGPP implementation
1914 of `system'. In particular:
1916 The shell wildcard characters are in DOS_CHARS because they will
1917 not be expanded if we call the child via `spawnXX'.
1919 The `;' is in DOS_CHARS, because our `system' knows how to run
1920 multiple commands on a single line.
1922 DOS_CHARS also include characters special to 4DOS/NDOS, so we
1923 won't have to tell one from another and have one more set of
1924 commands and special characters. */
1925 static char sh_chars_dos[] = "*?[];|<>%^&()";
1926 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1927 "copy", "ctty", "date", "del", "dir", "echo",
1928 "erase", "exit", "for", "goto", "if", "md",
1929 "mkdir", "path", "pause", "prompt", "rd",
1930 "rmdir", "rem", "ren", "rename", "set",
1931 "shift", "time", "type", "ver", "verify",
1932 "vol", ":", 0 };
1934 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1935 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
1936 "logout", "set", "umask", "wait", "while",
1937 "for", "case", "if", ":", ".", "break",
1938 "continue", "export", "read", "readonly",
1939 "shift", "times", "trap", "switch", "unset",
1940 0 };
1942 char *sh_chars;
1943 char **sh_cmds;
1944 #else
1945 #ifdef _AMIGA
1946 static char sh_chars[] = "#;\"|<>()?*$`";
1947 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
1948 "rename", "set", "setenv", "date", "makedir",
1949 "skip", "else", "endif", "path", "prompt",
1950 "unset", "unsetenv", "version",
1951 0 };
1952 #else
1953 #ifdef WINDOWS32
1954 static char sh_chars_dos[] = "\"|<>";
1955 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1956 "copy", "ctty", "date", "del", "dir", "echo",
1957 "erase", "exit", "for", "goto", "if", "if", "md",
1958 "mkdir", "path", "pause", "prompt", "rem", "ren",
1959 "rename", "set", "shift", "time", "type",
1960 "ver", "verify", "vol", ":", 0 };
1961 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1962 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
1963 "logout", "set", "umask", "wait", "while", "for",
1964 "case", "if", ":", ".", "break", "continue",
1965 "export", "read", "readonly", "shift", "times",
1966 "trap", "switch", "test",
1967 #ifdef BATCH_MODE_ONLY_SHELL
1968 "echo",
1969 #endif
1970 0 };
1971 char* sh_chars;
1972 char** sh_cmds;
1973 #else /* WINDOWS32 */
1974 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1975 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1976 "logout", "set", "umask", "wait", "while", "for",
1977 "case", "if", ":", ".", "break", "continue",
1978 "export", "read", "readonly", "shift", "times",
1979 "trap", "switch", 0 };
1980 #endif /* WINDOWS32 */
1981 #endif /* Amiga */
1982 #endif /* __MSDOS__ */
1983 register int i;
1984 register char *p;
1985 register char *ap;
1986 char *end;
1987 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
1988 char **new_argv = 0;
1989 #ifdef WINDOWS32
1990 int slow_flag = 0;
1992 if (no_default_sh_exe) {
1993 sh_cmds = sh_cmds_dos;
1994 sh_chars = sh_chars_dos;
1995 } else {
1996 sh_cmds = sh_cmds_sh;
1997 sh_chars = sh_chars_sh;
1999 #endif /* WINDOWS32 */
2001 if (restp != NULL)
2002 *restp = NULL;
2004 /* Make sure not to bother processing an empty line. */
2005 while (isblank (*line))
2006 ++line;
2007 if (*line == '\0')
2008 return 0;
2010 /* See if it is safe to parse commands internally. */
2011 if (shell == 0)
2012 shell = default_shell;
2013 #ifdef WINDOWS32
2014 else if (strcmp (shell, default_shell))
2016 char *s1 = _fullpath(NULL, shell, 0);
2017 char *s2 = _fullpath(NULL, default_shell, 0);
2019 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2021 if (s1);
2022 free(s1);
2023 if (s2);
2024 free(s2);
2026 if (slow_flag)
2027 goto slow;
2028 #else /* not WINDOWS32 */
2029 #ifdef __MSDOS__
2030 else if (stricmp (shell, default_shell))
2032 extern int _is_unixy_shell (const char *_path);
2034 message (1, _("$SHELL changed (was `%s', now `%s')"), default_shell, shell);
2035 unixy_shell = _is_unixy_shell (shell);
2036 default_shell = shell;
2038 if (unixy_shell)
2040 sh_chars = sh_chars_sh;
2041 sh_cmds = sh_cmds_sh;
2043 else
2045 sh_chars = sh_chars_dos;
2046 sh_cmds = sh_cmds_dos;
2048 #else /* not __MSDOS__ */
2049 else if (strcmp (shell, default_shell))
2050 goto slow;
2051 #endif /* not __MSDOS__ */
2052 #endif /* not WINDOWS32 */
2054 if (ifs != 0)
2055 for (ap = ifs; *ap != '\0'; ++ap)
2056 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2057 goto slow;
2059 i = strlen (line) + 1;
2061 /* More than 1 arg per character is impossible. */
2062 new_argv = (char **) xmalloc (i * sizeof (char *));
2064 /* All the args can fit in a buffer as big as LINE is. */
2065 ap = new_argv[0] = (char *) xmalloc (i);
2066 end = ap + i;
2068 /* I is how many complete arguments have been found. */
2069 i = 0;
2070 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2071 for (p = line; *p != '\0'; ++p)
2073 if (ap > end)
2074 abort ();
2076 if (instring)
2078 string_char:
2079 /* Inside a string, just copy any char except a closing quote
2080 or a backslash-newline combination. */
2081 if (*p == instring)
2083 instring = 0;
2084 if (ap == new_argv[0] || *(ap-1) == '\0')
2085 last_argument_was_empty = 1;
2087 else if (*p == '\\' && p[1] == '\n')
2088 goto swallow_escaped_newline;
2089 else if (*p == '\n' && restp != NULL)
2091 /* End of the command line. */
2092 *restp = p;
2093 goto end_of_line;
2095 /* Backslash, $, and ` are special inside double quotes.
2096 If we see any of those, punt.
2097 But on MSDOS, if we use COMMAND.COM, double and single
2098 quotes have the same effect. */
2099 else if (instring == '"' && index ("\\$`", *p) != 0 && unixy_shell)
2100 goto slow;
2101 else
2102 *ap++ = *p;
2104 else if (index (sh_chars, *p) != 0)
2105 /* Not inside a string, but it's a special char. */
2106 goto slow;
2107 #ifdef __MSDOS__
2108 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2109 /* `...' is a wildcard in DJGPP. */
2110 goto slow;
2111 #endif
2112 else
2113 /* Not a special char. */
2114 switch (*p)
2116 case '=':
2117 /* Equals is a special character in leading words before the
2118 first word with no equals sign in it. This is not the case
2119 with sh -k, but we never get here when using nonstandard
2120 shell flags. */
2121 if (! seen_nonequals && unixy_shell)
2122 goto slow;
2123 word_has_equals = 1;
2124 *ap++ = '=';
2125 break;
2127 case '\\':
2128 /* Backslash-newline combinations are eaten. */
2129 if (p[1] == '\n')
2131 swallow_escaped_newline:
2133 /* Eat the backslash, the newline, and following whitespace,
2134 replacing it all with a single space. */
2135 p += 2;
2137 /* If there is a tab after a backslash-newline,
2138 remove it from the source line which will be echoed,
2139 since it was most likely used to line
2140 up the continued line with the previous one. */
2141 if (*p == '\t')
2142 /* Note these overlap and strcpy() is undefined for
2143 overlapping objects in ANSI C. The strlen() _IS_ right,
2144 since we need to copy the nul byte too. */
2145 bcopy (p + 1, p, strlen (p));
2147 if (instring)
2148 goto string_char;
2149 else
2151 if (ap != new_argv[i])
2152 /* Treat this as a space, ending the arg.
2153 But if it's at the beginning of the arg, it should
2154 just get eaten, rather than becoming an empty arg. */
2155 goto end_of_arg;
2156 else
2157 p = next_token (p) - 1;
2160 else if (p[1] != '\0')
2162 #if defined(__MSDOS__) || defined(WINDOWS32)
2163 /* Only remove backslashes before characters special
2164 to Unixy shells. All other backslashes are copied
2165 verbatim, since they are probably DOS-style
2166 directory separators. This still leaves a small
2167 window for problems, but at least it should work
2168 for the vast majority of naive users. */
2170 #ifdef __MSDOS__
2171 /* A dot is only special as part of the "..."
2172 wildcard. */
2173 if (strneq (p + 1, ".\\.\\.", 5))
2175 *ap++ = '.';
2176 *ap++ = '.';
2177 p += 4;
2179 else
2180 #endif
2181 if (p[1] != '\\' && p[1] != '\'' && !isspace (p[1])
2182 && (index (sh_chars_sh, p[1]) == 0))
2183 /* back up one notch, to copy the backslash */
2184 --p;
2186 #endif /* __MSDOS__ || WINDOWS32 */
2187 /* Copy and skip the following char. */
2188 *ap++ = *++p;
2190 break;
2192 case '\'':
2193 case '"':
2194 instring = *p;
2195 break;
2197 case '\n':
2198 if (restp != NULL)
2200 /* End of the command line. */
2201 *restp = p;
2202 goto end_of_line;
2204 else
2205 /* Newlines are not special. */
2206 *ap++ = '\n';
2207 break;
2209 case ' ':
2210 case '\t':
2211 end_of_arg:
2212 /* We have the end of an argument.
2213 Terminate the text of the argument. */
2214 *ap++ = '\0';
2215 new_argv[++i] = ap;
2216 last_argument_was_empty = 0;
2218 /* Update SEEN_NONEQUALS, which tells us if every word
2219 heretofore has contained an `='. */
2220 seen_nonequals |= ! word_has_equals;
2221 if (word_has_equals && ! seen_nonequals)
2222 /* An `=' in a word before the first
2223 word without one is magical. */
2224 goto slow;
2225 word_has_equals = 0; /* Prepare for the next word. */
2227 /* If this argument is the command name,
2228 see if it is a built-in shell command.
2229 If so, have the shell handle it. */
2230 if (i == 1)
2232 register int j;
2233 for (j = 0; sh_cmds[j] != 0; ++j)
2234 if (streq (sh_cmds[j], new_argv[0]))
2235 goto slow;
2238 /* Ignore multiple whitespace chars. */
2239 p = next_token (p);
2240 /* Next iteration should examine the first nonwhite char. */
2241 --p;
2242 break;
2244 default:
2245 *ap++ = *p;
2246 break;
2249 end_of_line:
2251 if (instring)
2252 /* Let the shell deal with an unterminated quote. */
2253 goto slow;
2255 /* Terminate the last argument and the argument list. */
2257 *ap = '\0';
2258 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2259 ++i;
2260 new_argv[i] = 0;
2262 if (i == 1)
2264 register int j;
2265 for (j = 0; sh_cmds[j] != 0; ++j)
2266 if (streq (sh_cmds[j], new_argv[0]))
2267 goto slow;
2270 if (new_argv[0] == 0)
2271 /* Line was empty. */
2272 return 0;
2273 else
2274 return new_argv;
2276 slow:;
2277 /* We must use the shell. */
2279 if (new_argv != 0)
2281 /* Free the old argument list we were working on. */
2282 free (new_argv[0]);
2283 free ((void *)new_argv);
2286 #ifdef __MSDOS__
2287 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2288 #endif
2290 #ifdef _AMIGA
2292 char *ptr;
2293 char *buffer;
2294 char *dptr;
2296 buffer = (char *)xmalloc (strlen (line)+1);
2298 ptr = line;
2299 for (dptr=buffer; *ptr; )
2301 if (*ptr == '\\' && ptr[1] == '\n')
2302 ptr += 2;
2303 else if (*ptr == '@') /* Kludge: multiline commands */
2305 ptr += 2;
2306 *dptr++ = '\n';
2308 else
2309 *dptr++ = *ptr++;
2311 *dptr = 0;
2313 new_argv = (char **) xmalloc (2 * sizeof (char *));
2314 new_argv[0] = buffer;
2315 new_argv[1] = 0;
2317 #else /* Not Amiga */
2318 #ifdef WINDOWS32
2320 * Not eating this whitespace caused things like
2322 * sh -c "\n"
2324 * which gave the shell fits. I think we have to eat
2325 * whitespace here, but this code should be considered
2326 * suspicious if things start failing....
2329 /* Make sure not to bother processing an empty line. */
2330 while (isspace (*line))
2331 ++line;
2332 if (*line == '\0')
2333 return 0;
2334 #endif /* WINDOWS32 */
2336 /* SHELL may be a multi-word command. Construct a command line
2337 "SHELL -c LINE", with all special chars in LINE escaped.
2338 Then recurse, expanding this command line to get the final
2339 argument list. */
2341 unsigned int shell_len = strlen (shell);
2342 static char minus_c[] = " -c ";
2343 unsigned int line_len = strlen (line);
2345 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2346 + (line_len * 2) + 1);
2347 char* command_ptr = NULL; /* used for batch_mode_shell mode */
2349 ap = new_line;
2350 bcopy (shell, ap, shell_len);
2351 ap += shell_len;
2352 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2353 ap += sizeof (minus_c) - 1;
2354 command_ptr = ap;
2355 for (p = line; *p != '\0'; ++p)
2357 if (restp != NULL && *p == '\n')
2359 *restp = p;
2360 break;
2362 else if (*p == '\\' && p[1] == '\n')
2364 /* Eat the backslash, the newline, and following whitespace,
2365 replacing it all with a single space (which is escaped
2366 from the shell). */
2367 p += 2;
2369 /* If there is a tab after a backslash-newline,
2370 remove it from the source line which will be echoed,
2371 since it was most likely used to line
2372 up the continued line with the previous one. */
2373 if (*p == '\t')
2374 bcopy (p + 1, p, strlen (p));
2376 p = next_token (p);
2377 --p;
2378 if (unixy_shell && !batch_mode_shell)
2379 *ap++ = '\\';
2380 *ap++ = ' ';
2381 continue;
2384 /* DOS shells don't know about backslash-escaping. */
2385 if (unixy_shell && !batch_mode_shell &&
2386 (*p == '\\' || *p == '\'' || *p == '"'
2387 || isspace (*p)
2388 || index (sh_chars, *p) != 0))
2389 *ap++ = '\\';
2390 #ifdef __MSDOS__
2391 else if (unixy_shell && strneq (p, "...", 3))
2393 /* The case of `...' wildcard again. */
2394 strcpy (ap, "\\.\\.\\");
2395 ap += 5;
2396 p += 2;
2398 #endif
2399 *ap++ = *p;
2401 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2402 /* Line was empty. */
2403 return 0;
2404 *ap = '\0';
2406 #ifdef WINDOWS32
2407 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2408 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2409 cases, run commands via a script file. */
2410 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2411 FILE* batch = NULL;
2412 int id = GetCurrentProcessId();
2413 PATH_VAR(fbuf);
2414 char* fname = NULL;
2416 /* create a file name */
2417 sprintf(fbuf, "make%d", id);
2418 fname = tempnam(".", fbuf);
2420 /* create batch file name */
2421 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
2422 strcpy(*batch_filename_ptr, fname);
2424 /* make sure path name is in DOS backslash format */
2425 if (!unixy_shell) {
2426 fname = *batch_filename_ptr;
2427 for (i = 0; fname[i] != '\0'; ++i)
2428 if (fname[i] == '/')
2429 fname[i] = '\\';
2430 strcat(*batch_filename_ptr, ".bat");
2431 } else {
2432 strcat(*batch_filename_ptr, ".sh");
2435 if (debug_flag)
2436 printf(_("Creating temporary batch file %s\n"), *batch_filename_ptr);
2438 /* create batch file to execute command */
2439 batch = fopen (*batch_filename_ptr, "w");
2440 if (!unixy_shell)
2441 fputs ("@echo off\n", batch);
2442 fputs (command_ptr, batch);
2443 fputc ('\n', batch);
2444 fclose (batch);
2446 /* create argv */
2447 new_argv = (char **) xmalloc(3 * sizeof(char *));
2448 if (unixy_shell) {
2449 new_argv[0] = xstrdup (shell);
2450 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2451 } else {
2452 new_argv[0] = xstrdup (*batch_filename_ptr);
2453 new_argv[1] = NULL;
2455 new_argv[2] = NULL;
2456 } else
2457 #endif /* WINDOWS32 */
2458 if (unixy_shell)
2459 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2460 (char *) 0, (char *) 0,
2461 (char *) 0);
2462 #ifdef __MSDOS__
2463 else
2465 /* With MSDOS shells, we must construct the command line here
2466 instead of recursively calling ourselves, because we
2467 cannot backslash-escape the special characters (see above). */
2468 new_argv = (char **) xmalloc (sizeof (char *));
2469 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2470 new_argv[0] = xmalloc (line_len + 1);
2471 strncpy (new_argv[0],
2472 new_line + shell_len + sizeof (minus_c) - 1, line_len);
2473 new_argv[0][line_len] = '\0';
2475 #else
2476 else
2477 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2478 __FILE__, __LINE__);
2479 #endif
2481 #endif /* ! AMIGA */
2483 return new_argv;
2486 /* Figure out the argument list necessary to run LINE as a command. Try to
2487 avoid using a shell. This routine handles only ' quoting, and " quoting
2488 when no backslash, $ or ` characters are seen in the quotes. Starting
2489 quotes may be escaped with a backslash. If any of the characters in
2490 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2491 is the first word of a line, the shell is used.
2493 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2494 If *RESTP is NULL, newlines will be ignored.
2496 FILE is the target whose commands these are. It is used for
2497 variable expansion for $(SHELL) and $(IFS). */
2499 char **
2500 construct_command_argv (line, restp, file, batch_filename_ptr)
2501 char *line, **restp;
2502 struct file *file;
2503 char** batch_filename_ptr;
2505 char *shell, *ifs;
2506 char **argv;
2509 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2510 int save = warn_undefined_variables_flag;
2511 warn_undefined_variables_flag = 0;
2513 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
2514 #ifdef WINDOWS32
2516 * Convert to forward slashes so that construct_command_argv_internal()
2517 * is not confused.
2519 if (shell) {
2520 char *p = w32ify(shell, 0);
2521 strcpy(shell, p);
2523 #endif
2524 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
2526 warn_undefined_variables_flag = save;
2529 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
2531 free (shell);
2532 free (ifs);
2534 return argv;
2536 #endif /* !VMS */
2538 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2540 dup2 (old, new)
2541 int old, new;
2543 int fd;
2545 (void) close (new);
2546 fd = dup (old);
2547 if (fd != new)
2549 (void) close (fd);
2550 errno = EMFILE;
2551 return -1;
2554 return fd;
2556 #endif /* !HAPE_DUP2 && !_AMIGA */