* Start rewrite of jobserver to avoid unique tokens for debugging.
[make.git] / job.c
blob34d1ddd8279f0199e96fe4ea9c0c5c028009f1c2
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 static int rc_block, rc_reap_all, rc_got_block, rc_start_rfd, rc_end_rfd;
315 void
316 reap_children (block, err)
317 int block, err;
319 WAIT_T status;
320 /* Initially, assume we have some. */
321 int reap_more = 1;
323 #ifdef WAIT_NOHANG
324 # define REAP_MORE reap_more
325 #else
326 # define REAP_MORE dead_children
327 #endif
329 rc_block = block;
330 rc_reap_all = 0;
331 rc_got_block = 0;
332 rc_start_rfd = job_rfd;
334 /* As long as:
336 We have at least one child outstanding OR a shell function in progress,
338 We're blocking for a complete child OR there are more children to reap
340 we'll keep reaping children. */
342 while ((children != 0 || shell_function_pid != 0) &&
343 (block || REAP_MORE))
345 int remote = 0;
346 register int pid;
347 int exit_code, exit_sig, coredump;
348 register struct child *lastc, *c;
349 int child_failed;
350 int any_remote, any_local;
352 if (err && block)
354 /* We might block for a while, so let the user know why. */
355 fflush (stdout);
356 error (NILF, _("*** Waiting for unfinished jobs...."));
359 /* We have one less dead child to reap. As noted in
360 child_handler() above, this count is completely unimportant for
361 all modern, POSIX-y systems that support wait3() or waitpid().
362 The rest of this comment below applies only to early, broken
363 pre-POSIX systems. We keep the count only because... it's there...
365 The test and decrement are not atomic; if it is compiled into:
366 register = dead_children - 1;
367 dead_children = register;
368 a SIGCHLD could come between the two instructions.
369 child_handler increments dead_children.
370 The second instruction here would lose that increment. But the
371 only effect of dead_children being wrong is that we might wait
372 longer than necessary to reap a child, and lose some parallelism;
373 and we might print the "Waiting for unfinished jobs" message above
374 when not necessary. */
376 if (dead_children > 0)
377 --dead_children;
379 any_remote = 0;
380 any_local = shell_function_pid != 0;
381 for (c = children; c != 0; c = c->next)
383 any_remote |= c->remote;
384 any_local |= ! c->remote;
385 if (debug_flag)
386 printf (_("Live child 0x%08lx (%s) PID %ld %s\n"),
387 (unsigned long int) c, c->file->name,
388 (long) c->pid, c->remote ? _(" (remote)") : "");
389 #ifdef VMS
390 break;
391 #endif
394 /* First, check for remote children. */
395 if (any_remote)
396 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
397 else
398 pid = 0;
400 if (pid > 0)
401 /* We got a remote child. */
402 remote = 1;
403 else if (pid < 0)
405 /* A remote status command failed miserably. Punt. */
406 remote_status_lose:
407 if (EINTR_SET)
408 continue;
410 pfatal_with_name ("remote_status");
412 else
414 /* No remote children. Check for local children. */
415 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
416 if (any_local)
418 local_wait:
419 #ifdef VMS
420 vmsWaitForChildren (&status);
421 pid = c->pid;
422 #else
423 #ifdef WAIT_NOHANG
424 if (!block)
425 pid = WAIT_NOHANG (&status);
426 else
427 #endif
428 pid = wait (&status);
429 #endif /* !VMS */
431 else
432 pid = 0;
434 if (pid < 0)
436 /* EINTR? Try again. */
437 if (EINTR_SET)
438 goto local_wait;
440 /* The wait*() failed miserably. Punt. */
441 pfatal_with_name ("wait");
443 else if (pid > 0)
445 /* We got a child exit; chop the status word up. */
446 exit_code = WEXITSTATUS (status);
447 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
448 coredump = WCOREDUMP (status);
450 else
452 /* No local children are dead. */
453 reap_more = 0;
454 rc_reap_all = 1;
456 if (!block || !any_remote)
457 break;
459 /* Now try a blocking wait for a remote child. */
460 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
461 if (pid < 0)
462 goto remote_status_lose;
463 else if (pid == 0)
464 /* No remote children either. Finally give up. */
465 break;
467 /* We got a remote child. */
468 remote = 1;
470 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
472 #ifdef __MSDOS__
473 /* Life is very different on MSDOS. */
474 pid = dos_pid - 1;
475 status = dos_status;
476 exit_code = WEXITSTATUS (status);
477 if (exit_code == 0xff)
478 exit_code = -1;
479 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
480 coredump = 0;
481 #endif /* __MSDOS__ */
482 #ifdef _AMIGA
483 /* Same on Amiga */
484 pid = amiga_pid - 1;
485 status = amiga_status;
486 exit_code = amiga_status;
487 exit_sig = 0;
488 coredump = 0;
489 #endif /* _AMIGA */
490 #ifdef WINDOWS32
492 HANDLE hPID;
493 int err;
495 /* wait for anything to finish */
496 if (hPID = process_wait_for_any()) {
498 /* was an error found on this process? */
499 err = process_last_err(hPID);
501 /* get exit data */
502 exit_code = process_exit_code(hPID);
504 if (err)
505 fprintf(stderr, "make (e=%d): %s",
506 exit_code, map_windows32_error_to_string(exit_code));
508 /* signal */
509 exit_sig = process_signal(hPID);
511 /* cleanup process */
512 process_cleanup(hPID);
514 coredump = 0;
516 pid = (int) hPID;
518 #endif /* WINDOWS32 */
521 /* Check if this is the child of the `shell' function. */
522 if (!remote && pid == shell_function_pid)
524 /* It is. Leave an indicator for the `shell' function. */
525 if (exit_sig == 0 && exit_code == 127)
526 shell_function_completed = -1;
527 else
528 shell_function_completed = 1;
529 break;
532 child_failed = exit_sig != 0 || exit_code != 0;
534 /* Search for a child matching the deceased one. */
535 lastc = 0;
536 for (c = children; c != 0; lastc = c, c = c->next)
537 if (c->remote == remote && c->pid == pid)
538 break;
540 if (c == 0)
541 /* An unknown child died.
542 Ignore it; it was inherited from our invoker. */
543 continue;
545 if (debug_flag)
546 printf (_("Reaping %s child 0x%08lx PID %ld %s\n"),
547 child_failed ? _("losing") : _("winning"),
548 (unsigned long int) c, (long) c->pid,
549 c->remote ? _(" (remote)") : "");
551 if (c->sh_batch_file) {
552 if (debug_flag)
553 printf (_("Cleaning up temp batch file %s\n"), c->sh_batch_file);
555 /* just try and remove, don't care if this fails */
556 remove (c->sh_batch_file);
558 /* all done with memory */
559 free (c->sh_batch_file);
560 c->sh_batch_file = NULL;
563 /* If this child had the good stdin, say it is now free. */
564 if (c->good_stdin)
565 good_stdin_used = 0;
567 if (child_failed && !c->noerror && !ignore_errors_flag)
569 /* The commands failed. Write an error message,
570 delete non-precious targets, and abort. */
571 static int delete_on_error = -1;
572 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
573 c->file->update_status = 2;
574 if (delete_on_error == -1)
576 struct file *f = lookup_file (".DELETE_ON_ERROR");
577 delete_on_error = f != 0 && f->is_target;
579 if (exit_sig != 0 || delete_on_error)
580 delete_child_targets (c);
582 else
584 if (child_failed)
586 /* The commands failed, but we don't care. */
587 child_error (c->file->name,
588 exit_code, exit_sig, coredump, 1);
589 child_failed = 0;
592 /* If there are more commands to run, try to start them. */
593 if (job_next_command (c))
595 if (handling_fatal_signal)
597 /* Never start new commands while we are dying.
598 Since there are more commands that wanted to be run,
599 the target was not completely remade. So we treat
600 this as if a command had failed. */
601 c->file->update_status = 2;
603 else
605 /* Check again whether to start remotely.
606 Whether or not we want to changes over time.
607 Also, start_remote_job may need state set up
608 by start_remote_job_p. */
609 c->remote = start_remote_job_p (0);
610 start_job_command (c);
611 /* Fatal signals are left blocked in case we were
612 about to put that child on the chain. But it is
613 already there, so it is safe for a fatal signal to
614 arrive now; it will clean up this child's targets. */
615 unblock_sigs ();
616 if (c->file->command_state == cs_running)
617 /* We successfully started the new command.
618 Loop to reap more children. */
619 continue;
622 if (c->file->update_status != 0)
623 /* We failed to start the commands. */
624 delete_child_targets (c);
626 else
627 /* There are no more commands. We got through them all
628 without an unignored error. Now the target has been
629 successfully updated. */
630 c->file->update_status = 0;
633 /* When we get here, all the commands for C->file are finished
634 (or aborted) and C->file->update_status contains 0 or 2. But
635 C->file->command_state is still cs_running if all the commands
636 ran; notice_finish_file looks for cs_running to tell it that
637 it's interesting to check the file's modtime again now. */
639 if (! handling_fatal_signal)
640 /* Notice if the target of the commands has been changed.
641 This also propagates its values for command_state and
642 update_status to its also_make files. */
643 notice_finished_file (c->file);
645 if (debug_flag)
646 printf (_("Removing child 0x%08lx PID %ld %s from chain.\n"),
647 (unsigned long int) c, (long) c->pid,
648 c->remote ? _(" (remote)") : "");
650 /* Block fatal signals while frobnicating the list, so that
651 children and job_slots_used are always consistent. Otherwise
652 a fatal signal arriving after the child is off the chain and
653 before job_slots_used is decremented would believe a child was
654 live and call reap_children again. */
655 block_sigs ();
657 /* There is now another slot open. */
658 if (job_slots_used > 0)
659 --job_slots_used;
661 /* Remove the child from the chain and free it. */
662 if (lastc == 0)
663 children = c->next;
664 else
665 lastc->next = c->next;
667 free_child (c);
669 unblock_sigs ();
671 /* If the job failed, and the -k flag was not given, die,
672 unless we are already in the process of dying. */
673 if (!err && child_failed && !keep_going_flag &&
674 /* fatal_error_signal will die with the right signal. */
675 !handling_fatal_signal)
676 die (2);
678 /* Only block for one child. */
679 block = 0;
680 rc_block = block;
683 rc_end_rfd = job_rfd;
684 return;
687 /* Free the storage allocated for CHILD. */
689 static void
690 free_child (child)
691 register struct child *child;
693 /* If this child is the only one it was our "free" job, so don't put a
694 token back for it. */
696 if (job_fds[1] >= 0 && (child != children || child->next != 0))
698 char *token = '+';
700 /* Write a job token back to the pipe. */
702 while (write (job_fds[1], &token, 1) != 1)
703 if (!EINTR_SET)
704 pfatal_with_name (_("write jobserver"));
706 if (debug_flag)
707 printf (_("Released token for child 0x%08lx (%s).\n"),
708 (unsigned long int) child, child->file->name);
711 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
712 return;
714 if (child->command_lines != 0)
716 register unsigned int i;
717 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
718 free (child->command_lines[i]);
719 free ((char *) child->command_lines);
722 if (child->environment != 0)
724 register char **ep = child->environment;
725 while (*ep != 0)
726 free (*ep++);
727 free ((char *) child->environment);
730 free ((char *) child);
733 #ifdef POSIX
734 extern sigset_t fatal_signal_set;
735 #endif
737 void
738 block_sigs ()
740 #ifdef POSIX
741 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
742 #else
743 # ifdef HAVE_SIGSETMASK
744 (void) sigblock (fatal_signal_mask);
745 # endif
746 #endif
749 #ifdef POSIX
750 void
751 unblock_sigs ()
753 sigset_t empty;
754 sigemptyset (&empty);
755 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
757 #endif
759 /* Start a job to run the commands specified in CHILD.
760 CHILD is updated to reflect the commands and ID of the child process.
762 NOTE: On return fatal signals are blocked! The caller is responsible
763 for calling `unblock_sigs', once the new child is safely on the chain so
764 it can be cleaned up in the event of a fatal signal. */
766 static void
767 start_job_command (child)
768 register struct child *child;
770 #ifndef _AMIGA
771 static int bad_stdin = -1;
772 #endif
773 register char *p;
774 int flags;
775 #ifdef VMS
776 char *argv;
777 #else
778 char **argv;
779 #endif
781 /* If we have a completely empty commandset, stop now. */
782 if (!child->command_ptr)
783 goto next_command;
785 /* Combine the flags parsed for the line itself with
786 the flags specified globally for this target. */
787 flags = (child->file->command_flags
788 | child->file->cmds->lines_flags[child->command_line - 1]);
790 p = child->command_ptr;
791 child->noerror = flags & COMMANDS_NOERROR;
793 while (*p != '\0')
795 if (*p == '@')
796 flags |= COMMANDS_SILENT;
797 else if (*p == '+')
798 flags |= COMMANDS_RECURSE;
799 else if (*p == '-')
800 child->noerror = 1;
801 else if (!isblank (*p))
802 break;
803 ++p;
806 /* If -q was given, just say that updating `failed'. The exit status of
807 1 tells the user that -q is saying `something to do'; the exit status
808 for a random error is 2. */
809 if (question_flag && !(flags & COMMANDS_RECURSE))
811 child->file->update_status = 1;
812 notice_finished_file (child->file);
813 return;
816 /* There may be some preceding whitespace left if there
817 was nothing but a backslash on the first line. */
818 p = next_token (p);
820 /* Figure out an argument list from this command line. */
823 char *end = 0;
824 #ifdef VMS
825 argv = p;
826 #else
827 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
828 #endif
829 if (end == NULL)
830 child->command_ptr = NULL;
831 else
833 *end++ = '\0';
834 child->command_ptr = end;
838 if (touch_flag && !(flags & COMMANDS_RECURSE))
840 /* Go on to the next command. It might be the recursive one.
841 We construct ARGV only to find the end of the command line. */
842 #ifndef VMS
843 free (argv[0]);
844 free ((char *) argv);
845 #endif
846 argv = 0;
849 if (argv == 0)
851 next_command:
852 #ifdef __MSDOS__
853 execute_by_shell = 0; /* in case construct_command_argv sets it */
854 #endif
855 /* This line has no commands. Go to the next. */
856 if (job_next_command (child))
857 start_job_command (child);
858 else
860 /* No more commands. Make sure we're "running"; we might not be if
861 (e.g.) all commands were skipped due to -n. */
862 set_command_state (child->file, cs_running);
863 child->file->update_status = 0;
864 notice_finished_file (child->file);
866 return;
869 /* Print out the command. If silent, we call `message' with null so it
870 can log the working directory before the command's own error messages
871 appear. */
873 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
874 ? "%s" : (char *) 0, p);
876 /* Optimize an empty command. People use this for timestamp rules,
877 and forking a useless shell all the time leads to inefficiency. */
879 #if !defined(VMS) && !defined(_AMIGA)
880 if (
881 #ifdef __MSDOS__
882 unixy_shell /* the test is complicated and we already did it */
883 #else
884 (argv[0] && !strcmp (argv[0], "/bin/sh"))
885 #endif
886 && (argv[1]
887 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
888 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
889 && argv[3] == NULL)
891 free (argv[0]);
892 free ((char *) argv);
893 goto next_command;
895 #endif /* !VMS && !_AMIGA */
897 /* Tell update_goal_chain that a command has been started on behalf of
898 this target. It is important that this happens here and not in
899 reap_children (where we used to do it), because reap_children might be
900 reaping children from a different target. We want this increment to
901 guaranteedly indicate that a command was started for the dependency
902 chain (i.e., update_file recursion chain) we are processing. */
904 ++commands_started;
906 /* If -n was given, recurse to get the next line in the sequence. */
908 if (just_print_flag && !(flags & COMMANDS_RECURSE))
910 #ifndef VMS
911 free (argv[0]);
912 free ((char *) argv);
913 #endif
914 goto next_command;
917 /* Flush the output streams so they won't have things written twice. */
919 fflush (stdout);
920 fflush (stderr);
922 #ifndef VMS
923 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
925 /* Set up a bad standard input that reads from a broken pipe. */
927 if (bad_stdin == -1)
929 /* Make a file descriptor that is the read end of a broken pipe.
930 This will be used for some children's standard inputs. */
931 int pd[2];
932 if (pipe (pd) == 0)
934 /* Close the write side. */
935 (void) close (pd[1]);
936 /* Save the read side. */
937 bad_stdin = pd[0];
939 /* Set the descriptor to close on exec, so it does not litter any
940 child's descriptor table. When it is dup2'd onto descriptor 0,
941 that descriptor will not close on exec. */
942 CLOSE_ON_EXEC (bad_stdin);
946 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
948 /* Decide whether to give this child the `good' standard input
949 (one that points to the terminal or whatever), or the `bad' one
950 that points to the read side of a broken pipe. */
952 child->good_stdin = !good_stdin_used;
953 if (child->good_stdin)
954 good_stdin_used = 1;
956 #endif /* !VMS */
958 child->deleted = 0;
960 #ifndef _AMIGA
961 /* Set up the environment for the child. */
962 if (child->environment == 0)
963 child->environment = target_environment (child->file);
964 #endif
966 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
968 #ifndef VMS
969 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
970 if (child->remote)
972 int is_remote, id, used_stdin;
973 if (start_remote_job (argv, child->environment,
974 child->good_stdin ? 0 : bad_stdin,
975 &is_remote, &id, &used_stdin))
976 /* Don't give up; remote execution may fail for various reasons. If
977 so, simply run the job locally. */
978 goto run_local;
979 else
981 if (child->good_stdin && !used_stdin)
983 child->good_stdin = 0;
984 good_stdin_used = 0;
986 child->remote = is_remote;
987 child->pid = id;
990 else
991 #endif /* !VMS */
993 /* Fork the child process. */
995 char **parent_environ;
997 run_local:
998 block_sigs ();
1000 child->remote = 0;
1002 #ifdef VMS
1004 if (!child_execute_job (argv, child)) {
1005 /* Fork failed! */
1006 perror_with_name ("vfork", "");
1007 goto error;
1010 #else
1012 parent_environ = environ;
1013 child->pid = vfork ();
1014 environ = parent_environ; /* Restore value child may have clobbered. */
1015 if (child->pid == 0)
1017 /* We are the child side. */
1018 unblock_sigs ();
1020 /* If we aren't running a recursive command and we have a jobserver
1021 pipe, close it before exec'ing. */
1022 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1024 close (job_fds[0]);
1025 close (job_fds[1]);
1027 if (job_rfd >= 0)
1028 close (job_rfd);
1030 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1031 argv, child->environment);
1033 else if (child->pid < 0)
1035 /* Fork failed! */
1036 unblock_sigs ();
1037 perror_with_name ("vfork", "");
1038 goto error;
1040 #endif /* !VMS */
1043 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1044 #ifdef __MSDOS__
1046 int proc_return;
1048 block_sigs ();
1049 dos_status = 0;
1051 /* We call `system' to do the job of the SHELL, since stock DOS
1052 shell is too dumb. Our `system' knows how to handle long
1053 command lines even if pipes/redirection is needed; it will only
1054 call COMMAND.COM when its internal commands are used. */
1055 if (execute_by_shell)
1057 char *cmdline = argv[0];
1058 /* We don't have a way to pass environment to `system',
1059 so we need to save and restore ours, sigh... */
1060 char **parent_environ = environ;
1062 environ = child->environment;
1064 /* If we have a *real* shell, tell `system' to call
1065 it to do everything for us. */
1066 if (unixy_shell)
1068 /* A *real* shell on MSDOS may not support long
1069 command lines the DJGPP way, so we must use `system'. */
1070 cmdline = argv[2]; /* get past "shell -c" */
1073 dos_command_running = 1;
1074 proc_return = system (cmdline);
1075 environ = parent_environ;
1076 execute_by_shell = 0; /* for the next time */
1078 else
1080 dos_command_running = 1;
1081 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1084 /* Need to unblock signals before turning off
1085 dos_command_running, so that child's signals
1086 will be treated as such (see fatal_error_signal). */
1087 unblock_sigs ();
1088 dos_command_running = 0;
1090 /* If the child got a signal, dos_status has its
1091 high 8 bits set, so be careful not to alter them. */
1092 if (proc_return == -1)
1093 dos_status |= 0xff;
1094 else
1095 dos_status |= (proc_return & 0xff);
1096 ++dead_children;
1097 child->pid = dos_pid++;
1099 #endif /* __MSDOS__ */
1100 #ifdef _AMIGA
1101 amiga_status = MyExecute (argv);
1103 ++dead_children;
1104 child->pid = amiga_pid++;
1105 if (amiga_batch_file)
1107 amiga_batch_file = 0;
1108 DeleteFile (amiga_bname); /* Ignore errors. */
1110 #endif /* Amiga */
1111 #ifdef WINDOWS32
1113 HANDLE hPID;
1114 char* arg0;
1116 /* make UNC paths safe for CreateProcess -- backslash format */
1117 arg0 = argv[0];
1118 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1119 for ( ; arg0 && *arg0; arg0++)
1120 if (*arg0 == '/')
1121 *arg0 = '\\';
1123 /* make sure CreateProcess() has Path it needs */
1124 sync_Path_environment();
1126 hPID = process_easy(argv, child->environment);
1128 if (hPID != INVALID_HANDLE_VALUE)
1129 child->pid = (int) hPID;
1130 else {
1131 int i;
1132 unblock_sigs();
1133 fprintf(stderr,
1134 _("process_easy() failed failed to launch process (e=%d)\n"),
1135 process_last_err(hPID));
1136 for (i = 0; argv[i]; i++)
1137 fprintf(stderr, "%s ", argv[i]);
1138 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1141 #endif /* WINDOWS32 */
1142 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1144 /* We are the parent side. Set the state to
1145 say the commands are running and return. */
1147 set_command_state (child->file, cs_running);
1149 /* Free the storage used by the child's argument list. */
1150 #ifndef VMS
1151 free (argv[0]);
1152 free ((char *) argv);
1153 #endif
1155 return;
1157 error:
1158 child->file->update_status = 2;
1159 notice_finished_file (child->file);
1160 return;
1163 /* Try to start a child running.
1164 Returns nonzero if the child was started (and maybe finished), or zero if
1165 the load was too high and the child was put on the `waiting_jobs' chain. */
1167 static int
1168 start_waiting_job (c)
1169 struct child *c;
1171 struct file *f = c->file;
1173 /* If we can start a job remotely, we always want to, and don't care about
1174 the local load average. We record that the job should be started
1175 remotely in C->remote for start_job_command to test. */
1177 c->remote = start_remote_job_p (1);
1179 /* If we are running at least one job already and the load average
1180 is too high, make this one wait. */
1181 if (!c->remote && job_slots_used > 0 && load_too_high ())
1183 /* Put this child on the chain of children waiting for the load average
1184 to go down. */
1185 set_command_state (f, cs_running);
1186 c->next = waiting_jobs;
1187 waiting_jobs = c;
1188 return 0;
1191 /* Start the first command; reap_children will run later command lines. */
1192 start_job_command (c);
1194 switch (f->command_state)
1196 case cs_running:
1197 c->next = children;
1198 if (debug_flag)
1199 printf (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1200 (unsigned long int) c, c->file->name,
1201 (long) c->pid, c->remote ? _(" (remote)") : "");
1202 children = c;
1203 /* One more job slot is in use. */
1204 ++job_slots_used;
1205 unblock_sigs ();
1206 break;
1208 case cs_not_started:
1209 /* All the command lines turned out to be empty. */
1210 f->update_status = 0;
1211 /* FALLTHROUGH */
1213 case cs_finished:
1214 notice_finished_file (f);
1215 free_child (c);
1216 break;
1218 default:
1219 assert (f->command_state == cs_finished);
1220 break;
1223 return 1;
1226 /* Create a `struct child' for FILE and start its commands running. */
1228 void
1229 new_job (file)
1230 register struct file *file;
1232 register struct commands *cmds = file->cmds;
1233 register struct child *c;
1234 char **lines;
1235 register unsigned int i;
1237 /* Let any previously decided-upon jobs that are waiting
1238 for the load to go down start before this new one. */
1239 start_waiting_jobs ();
1241 /* Reap any children that might have finished recently. */
1242 reap_children (0, 0);
1244 /* Chop the commands up into lines if they aren't already. */
1245 chop_commands (cmds);
1247 /* Expand the command lines and store the results in LINES. */
1248 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1249 for (i = 0; i < cmds->ncommand_lines; ++i)
1251 /* Collapse backslash-newline combinations that are inside variable
1252 or function references. These are left alone by the parser so
1253 that they will appear in the echoing of commands (where they look
1254 nice); and collapsed by construct_command_argv when it tokenizes.
1255 But letting them survive inside function invocations loses because
1256 we don't want the functions to see them as part of the text. */
1258 char *in, *out, *ref;
1260 /* IN points to where in the line we are scanning.
1261 OUT points to where in the line we are writing.
1262 When we collapse a backslash-newline combination,
1263 IN gets ahead of OUT. */
1265 in = out = cmds->command_lines[i];
1266 while ((ref = index (in, '$')) != 0)
1268 ++ref; /* Move past the $. */
1270 if (out != in)
1271 /* Copy the text between the end of the last chunk
1272 we processed (where IN points) and the new chunk
1273 we are about to process (where REF points). */
1274 bcopy (in, out, ref - in);
1276 /* Move both pointers past the boring stuff. */
1277 out += ref - in;
1278 in = ref;
1280 if (*ref == '(' || *ref == '{')
1282 char openparen = *ref;
1283 char closeparen = openparen == '(' ? ')' : '}';
1284 int count;
1285 char *p;
1287 *out++ = *in++; /* Copy OPENPAREN. */
1288 /* IN now points past the opening paren or brace.
1289 Count parens or braces until it is matched. */
1290 count = 0;
1291 while (*in != '\0')
1293 if (*in == closeparen && --count < 0)
1294 break;
1295 else if (*in == '\\' && in[1] == '\n')
1297 /* We have found a backslash-newline inside a
1298 variable or function reference. Eat it and
1299 any following whitespace. */
1301 int quoted = 0;
1302 for (p = in - 1; p > ref && *p == '\\'; --p)
1303 quoted = !quoted;
1305 if (quoted)
1306 /* There were two or more backslashes, so this is
1307 not really a continuation line. We don't collapse
1308 the quoting backslashes here as is done in
1309 collapse_continuations, because the line will
1310 be collapsed again after expansion. */
1311 *out++ = *in++;
1312 else
1314 /* Skip the backslash, newline and
1315 any following whitespace. */
1316 in = next_token (in + 2);
1318 /* Discard any preceding whitespace that has
1319 already been written to the output. */
1320 while (out > ref && isblank (out[-1]))
1321 --out;
1323 /* Replace it all with a single space. */
1324 *out++ = ' ';
1327 else
1329 if (*in == openparen)
1330 ++count;
1332 *out++ = *in++;
1338 /* There are no more references in this line to worry about.
1339 Copy the remaining uninteresting text to the output. */
1340 if (out != in)
1341 strcpy (out, in);
1343 /* Finally, expand the line. */
1344 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1345 file);
1348 /* Start the command sequence, record it in a new
1349 `struct child', and add that to the chain. */
1351 c = (struct child *) xmalloc (sizeof (struct child));
1352 c->file = file;
1353 c->command_lines = lines;
1354 c->command_line = 0;
1355 c->command_ptr = 0;
1356 c->environment = 0;
1357 c->sh_batch_file = NULL;
1359 /* Fetch the first command line to be run. */
1360 job_next_command (c);
1362 /* Wait for a job slot to be freed up. If we allow an infinite number
1363 don't bother; also job_slots will == 0 if we're using the jobserver. */
1364 if (job_slots != 0)
1365 while (job_slots_used == job_slots)
1366 reap_children (1, 0);
1368 #ifdef MAKE_JOBSERVER
1369 /* If we are controlling multiple jobs make sure we have a token before
1370 starting the child. */
1372 else if (job_fds[0] >= 0)
1373 if (children == 0)
1375 char token = '-';
1377 while (token == '-')
1378 /* If we don't already have a job started, use our "free" token. */
1379 if (children == 0)
1380 token = '+';
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 else if (read (job_rfd, &c->job_token, 1) < 1)
1389 if (errno != EINTR && errno != EBADF)
1390 pfatal_with_name (_("read jobs pipe"));
1392 /* Re-dup the read side of the pipe, so the signal handler can
1393 notify us if we miss a child. */
1394 if (job_rfd < 0)
1395 job_rfd = dup (job_fds[0]);
1397 /* Something's done. We don't want to block for a whole child,
1398 just reap whatever's there. */
1399 reap_children (0, 0);
1402 assert (c->job_token != '-');
1403 if (debug_flag)
1404 printf (_("Obtained token for child 0x%08lx (%s).\n"),
1405 (unsigned long int) c, c->file->name);
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", "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", 0 };
1941 char *sh_chars;
1942 char **sh_cmds;
1943 #else
1944 #ifdef _AMIGA
1945 static char sh_chars[] = "#;\"|<>()?*$`";
1946 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
1947 "rename", "set", "setenv", "date", "makedir",
1948 "skip", "else", "endif", "path", "prompt",
1949 "unset", "unsetenv", "version",
1950 0 };
1951 #else
1952 #ifdef WINDOWS32
1953 static char sh_chars_dos[] = "\"|<>";
1954 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1955 "copy", "ctty", "date", "del", "dir", "echo",
1956 "erase", "exit", "for", "goto", "if", "if", "md",
1957 "mkdir", "path", "pause", "prompt", "rem", "ren",
1958 "rename", "set", "shift", "time", "type",
1959 "ver", "verify", "vol", ":", 0 };
1960 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1961 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
1962 "logout", "set", "umask", "wait", "while", "for",
1963 "case", "if", ":", ".", "break", "continue",
1964 "export", "read", "readonly", "shift", "times",
1965 "trap", "switch", "test",
1966 #ifdef BATCH_MODE_ONLY_SHELL
1967 "echo",
1968 #endif
1969 0 };
1970 char* sh_chars;
1971 char** sh_cmds;
1972 #else /* WINDOWS32 */
1973 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1974 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1975 "logout", "set", "umask", "wait", "while", "for",
1976 "case", "if", ":", ".", "break", "continue",
1977 "export", "read", "readonly", "shift", "times",
1978 "trap", "switch", 0 };
1979 #endif /* WINDOWS32 */
1980 #endif /* Amiga */
1981 #endif /* __MSDOS__ */
1982 register int i;
1983 register char *p;
1984 register char *ap;
1985 char *end;
1986 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
1987 char **new_argv = 0;
1988 #ifdef WINDOWS32
1989 int slow_flag = 0;
1991 if (no_default_sh_exe) {
1992 sh_cmds = sh_cmds_dos;
1993 sh_chars = sh_chars_dos;
1994 } else {
1995 sh_cmds = sh_cmds_sh;
1996 sh_chars = sh_chars_sh;
1998 #endif /* WINDOWS32 */
2000 if (restp != NULL)
2001 *restp = NULL;
2003 /* Make sure not to bother processing an empty line. */
2004 while (isblank (*line))
2005 ++line;
2006 if (*line == '\0')
2007 return 0;
2009 /* See if it is safe to parse commands internally. */
2010 if (shell == 0)
2011 shell = default_shell;
2012 #ifdef WINDOWS32
2013 else if (strcmp (shell, default_shell))
2015 char *s1 = _fullpath(NULL, shell, 0);
2016 char *s2 = _fullpath(NULL, default_shell, 0);
2018 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2020 if (s1);
2021 free(s1);
2022 if (s2);
2023 free(s2);
2025 if (slow_flag)
2026 goto slow;
2027 #else /* not WINDOWS32 */
2028 #ifdef __MSDOS__
2029 else if (stricmp (shell, default_shell))
2031 extern int _is_unixy_shell (const char *_path);
2033 message (1, _("$SHELL changed (was `%s', now `%s')"), default_shell, shell);
2034 unixy_shell = _is_unixy_shell (shell);
2035 default_shell = shell;
2037 if (unixy_shell)
2039 sh_chars = sh_chars_sh;
2040 sh_cmds = sh_cmds_sh;
2042 else
2044 sh_chars = sh_chars_dos;
2045 sh_cmds = sh_cmds_dos;
2047 #else /* not __MSDOS__ */
2048 else if (strcmp (shell, default_shell))
2049 goto slow;
2050 #endif /* not __MSDOS__ */
2051 #endif /* not WINDOWS32 */
2053 if (ifs != 0)
2054 for (ap = ifs; *ap != '\0'; ++ap)
2055 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2056 goto slow;
2058 i = strlen (line) + 1;
2060 /* More than 1 arg per character is impossible. */
2061 new_argv = (char **) xmalloc (i * sizeof (char *));
2063 /* All the args can fit in a buffer as big as LINE is. */
2064 ap = new_argv[0] = (char *) xmalloc (i);
2065 end = ap + i;
2067 /* I is how many complete arguments have been found. */
2068 i = 0;
2069 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2070 for (p = line; *p != '\0'; ++p)
2072 if (ap > end)
2073 abort ();
2075 if (instring)
2077 string_char:
2078 /* Inside a string, just copy any char except a closing quote
2079 or a backslash-newline combination. */
2080 if (*p == instring)
2082 instring = 0;
2083 if (ap == new_argv[0] || *(ap-1) == '\0')
2084 last_argument_was_empty = 1;
2086 else if (*p == '\\' && p[1] == '\n')
2087 goto swallow_escaped_newline;
2088 else if (*p == '\n' && restp != NULL)
2090 /* End of the command line. */
2091 *restp = p;
2092 goto end_of_line;
2094 /* Backslash, $, and ` are special inside double quotes.
2095 If we see any of those, punt.
2096 But on MSDOS, if we use COMMAND.COM, double and single
2097 quotes have the same effect. */
2098 else if (instring == '"' && index ("\\$`", *p) != 0 && unixy_shell)
2099 goto slow;
2100 else
2101 *ap++ = *p;
2103 else if (index (sh_chars, *p) != 0)
2104 /* Not inside a string, but it's a special char. */
2105 goto slow;
2106 #ifdef __MSDOS__
2107 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2108 /* `...' is a wildcard in DJGPP. */
2109 goto slow;
2110 #endif
2111 else
2112 /* Not a special char. */
2113 switch (*p)
2115 case '=':
2116 /* Equals is a special character in leading words before the
2117 first word with no equals sign in it. This is not the case
2118 with sh -k, but we never get here when using nonstandard
2119 shell flags. */
2120 if (! seen_nonequals && unixy_shell)
2121 goto slow;
2122 word_has_equals = 1;
2123 *ap++ = '=';
2124 break;
2126 case '\\':
2127 /* Backslash-newline combinations are eaten. */
2128 if (p[1] == '\n')
2130 swallow_escaped_newline:
2132 /* Eat the backslash, the newline, and following whitespace,
2133 replacing it all with a single space. */
2134 p += 2;
2136 /* If there is a tab after a backslash-newline,
2137 remove it from the source line which will be echoed,
2138 since it was most likely used to line
2139 up the continued line with the previous one. */
2140 if (*p == '\t')
2141 /* Note these overlap and strcpy() is undefined for
2142 overlapping objects in ANSI C. The strlen() _IS_ right,
2143 since we need to copy the nul byte too. */
2144 bcopy (p + 1, p, strlen (p));
2146 if (instring)
2147 goto string_char;
2148 else
2150 if (ap != new_argv[i])
2151 /* Treat this as a space, ending the arg.
2152 But if it's at the beginning of the arg, it should
2153 just get eaten, rather than becoming an empty arg. */
2154 goto end_of_arg;
2155 else
2156 p = next_token (p) - 1;
2159 else if (p[1] != '\0')
2161 #if defined(__MSDOS__) || defined(WINDOWS32)
2162 /* Only remove backslashes before characters special
2163 to Unixy shells. All other backslashes are copied
2164 verbatim, since they are probably DOS-style
2165 directory separators. This still leaves a small
2166 window for problems, but at least it should work
2167 for the vast majority of naive users. */
2169 #ifdef __MSDOS__
2170 /* A dot is only special as part of the "..."
2171 wildcard. */
2172 if (strneq (p + 1, ".\\.\\.", 5))
2174 *ap++ = '.';
2175 *ap++ = '.';
2176 p += 4;
2178 else
2179 #endif
2180 if (p[1] != '\\' && p[1] != '\'' && !isspace (p[1])
2181 && (index (sh_chars_sh, p[1]) == 0))
2182 /* back up one notch, to copy the backslash */
2183 --p;
2185 #endif /* __MSDOS__ || WINDOWS32 */
2186 /* Copy and skip the following char. */
2187 *ap++ = *++p;
2189 break;
2191 case '\'':
2192 case '"':
2193 instring = *p;
2194 break;
2196 case '\n':
2197 if (restp != NULL)
2199 /* End of the command line. */
2200 *restp = p;
2201 goto end_of_line;
2203 else
2204 /* Newlines are not special. */
2205 *ap++ = '\n';
2206 break;
2208 case ' ':
2209 case '\t':
2210 end_of_arg:
2211 /* We have the end of an argument.
2212 Terminate the text of the argument. */
2213 *ap++ = '\0';
2214 new_argv[++i] = ap;
2215 last_argument_was_empty = 0;
2217 /* Update SEEN_NONEQUALS, which tells us if every word
2218 heretofore has contained an `='. */
2219 seen_nonequals |= ! word_has_equals;
2220 if (word_has_equals && ! seen_nonequals)
2221 /* An `=' in a word before the first
2222 word without one is magical. */
2223 goto slow;
2224 word_has_equals = 0; /* Prepare for the next word. */
2226 /* If this argument is the command name,
2227 see if it is a built-in shell command.
2228 If so, have the shell handle it. */
2229 if (i == 1)
2231 register int j;
2232 for (j = 0; sh_cmds[j] != 0; ++j)
2233 if (streq (sh_cmds[j], new_argv[0]))
2234 goto slow;
2237 /* Ignore multiple whitespace chars. */
2238 p = next_token (p);
2239 /* Next iteration should examine the first nonwhite char. */
2240 --p;
2241 break;
2243 default:
2244 *ap++ = *p;
2245 break;
2248 end_of_line:
2250 if (instring)
2251 /* Let the shell deal with an unterminated quote. */
2252 goto slow;
2254 /* Terminate the last argument and the argument list. */
2256 *ap = '\0';
2257 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2258 ++i;
2259 new_argv[i] = 0;
2261 if (i == 1)
2263 register int j;
2264 for (j = 0; sh_cmds[j] != 0; ++j)
2265 if (streq (sh_cmds[j], new_argv[0]))
2266 goto slow;
2269 if (new_argv[0] == 0)
2270 /* Line was empty. */
2271 return 0;
2272 else
2273 return new_argv;
2275 slow:;
2276 /* We must use the shell. */
2278 if (new_argv != 0)
2280 /* Free the old argument list we were working on. */
2281 free (new_argv[0]);
2282 free ((void *)new_argv);
2285 #ifdef __MSDOS__
2286 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2287 #endif
2289 #ifdef _AMIGA
2291 char *ptr;
2292 char *buffer;
2293 char *dptr;
2295 buffer = (char *)xmalloc (strlen (line)+1);
2297 ptr = line;
2298 for (dptr=buffer; *ptr; )
2300 if (*ptr == '\\' && ptr[1] == '\n')
2301 ptr += 2;
2302 else if (*ptr == '@') /* Kludge: multiline commands */
2304 ptr += 2;
2305 *dptr++ = '\n';
2307 else
2308 *dptr++ = *ptr++;
2310 *dptr = 0;
2312 new_argv = (char **) xmalloc (2 * sizeof (char *));
2313 new_argv[0] = buffer;
2314 new_argv[1] = 0;
2316 #else /* Not Amiga */
2317 #ifdef WINDOWS32
2319 * Not eating this whitespace caused things like
2321 * sh -c "\n"
2323 * which gave the shell fits. I think we have to eat
2324 * whitespace here, but this code should be considered
2325 * suspicious if things start failing....
2328 /* Make sure not to bother processing an empty line. */
2329 while (isspace (*line))
2330 ++line;
2331 if (*line == '\0')
2332 return 0;
2333 #endif /* WINDOWS32 */
2335 /* SHELL may be a multi-word command. Construct a command line
2336 "SHELL -c LINE", with all special chars in LINE escaped.
2337 Then recurse, expanding this command line to get the final
2338 argument list. */
2340 unsigned int shell_len = strlen (shell);
2341 static char minus_c[] = " -c ";
2342 unsigned int line_len = strlen (line);
2344 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2345 + (line_len * 2) + 1);
2346 char* command_ptr = NULL; /* used for batch_mode_shell mode */
2348 ap = new_line;
2349 bcopy (shell, ap, shell_len);
2350 ap += shell_len;
2351 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2352 ap += sizeof (minus_c) - 1;
2353 command_ptr = ap;
2354 for (p = line; *p != '\0'; ++p)
2356 if (restp != NULL && *p == '\n')
2358 *restp = p;
2359 break;
2361 else if (*p == '\\' && p[1] == '\n')
2363 /* Eat the backslash, the newline, and following whitespace,
2364 replacing it all with a single space (which is escaped
2365 from the shell). */
2366 p += 2;
2368 /* If there is a tab after a backslash-newline,
2369 remove it from the source line which will be echoed,
2370 since it was most likely used to line
2371 up the continued line with the previous one. */
2372 if (*p == '\t')
2373 bcopy (p + 1, p, strlen (p));
2375 p = next_token (p);
2376 --p;
2377 if (unixy_shell && !batch_mode_shell)
2378 *ap++ = '\\';
2379 *ap++ = ' ';
2380 continue;
2383 /* DOS shells don't know about backslash-escaping. */
2384 if (unixy_shell && !batch_mode_shell &&
2385 (*p == '\\' || *p == '\'' || *p == '"'
2386 || isspace (*p)
2387 || index (sh_chars, *p) != 0))
2388 *ap++ = '\\';
2389 #ifdef __MSDOS__
2390 else if (unixy_shell && strneq (p, "...", 3))
2392 /* The case of `...' wildcard again. */
2393 strcpy (ap, "\\.\\.\\");
2394 ap += 5;
2395 p += 2;
2397 #endif
2398 *ap++ = *p;
2400 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2401 /* Line was empty. */
2402 return 0;
2403 *ap = '\0';
2405 #ifdef WINDOWS32
2406 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2407 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2408 cases, run commands via a script file. */
2409 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2410 FILE* batch = NULL;
2411 int id = GetCurrentProcessId();
2412 PATH_VAR(fbuf);
2413 char* fname = NULL;
2415 /* create a file name */
2416 sprintf(fbuf, "make%d", id);
2417 fname = tempnam(".", fbuf);
2419 /* create batch file name */
2420 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
2421 strcpy(*batch_filename_ptr, fname);
2423 /* make sure path name is in DOS backslash format */
2424 if (!unixy_shell) {
2425 fname = *batch_filename_ptr;
2426 for (i = 0; fname[i] != '\0'; ++i)
2427 if (fname[i] == '/')
2428 fname[i] = '\\';
2429 strcat(*batch_filename_ptr, ".bat");
2430 } else {
2431 strcat(*batch_filename_ptr, ".sh");
2434 if (debug_flag)
2435 printf(_("Creating temporary batch file %s\n"), *batch_filename_ptr);
2437 /* create batch file to execute command */
2438 batch = fopen (*batch_filename_ptr, "w");
2439 if (!unixy_shell)
2440 fputs ("@echo off\n", batch);
2441 fputs (command_ptr, batch);
2442 fputc ('\n', batch);
2443 fclose (batch);
2445 /* create argv */
2446 new_argv = (char **) xmalloc(3 * sizeof(char *));
2447 if (unixy_shell) {
2448 new_argv[0] = xstrdup (shell);
2449 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2450 } else {
2451 new_argv[0] = xstrdup (*batch_filename_ptr);
2452 new_argv[1] = NULL;
2454 new_argv[2] = NULL;
2455 } else
2456 #endif /* WINDOWS32 */
2457 if (unixy_shell)
2458 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2459 (char *) 0, (char *) 0,
2460 (char *) 0);
2461 #ifdef __MSDOS__
2462 else
2464 /* With MSDOS shells, we must construct the command line here
2465 instead of recursively calling ourselves, because we
2466 cannot backslash-escape the special characters (see above). */
2467 new_argv = (char **) xmalloc (sizeof (char *));
2468 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2469 new_argv[0] = xmalloc (line_len + 1);
2470 strncpy (new_argv[0],
2471 new_line + shell_len + sizeof (minus_c) - 1, line_len);
2472 new_argv[0][line_len] = '\0';
2474 #else
2475 else
2476 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2477 __FILE__, __LINE__);
2478 #endif
2480 #endif /* ! AMIGA */
2482 return new_argv;
2485 /* Figure out the argument list necessary to run LINE as a command. Try to
2486 avoid using a shell. This routine handles only ' quoting, and " quoting
2487 when no backslash, $ or ` characters are seen in the quotes. Starting
2488 quotes may be escaped with a backslash. If any of the characters in
2489 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2490 is the first word of a line, the shell is used.
2492 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2493 If *RESTP is NULL, newlines will be ignored.
2495 FILE is the target whose commands these are. It is used for
2496 variable expansion for $(SHELL) and $(IFS). */
2498 char **
2499 construct_command_argv (line, restp, file, batch_filename_ptr)
2500 char *line, **restp;
2501 struct file *file;
2502 char** batch_filename_ptr;
2504 char *shell, *ifs;
2505 char **argv;
2508 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2509 int save = warn_undefined_variables_flag;
2510 warn_undefined_variables_flag = 0;
2512 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
2513 #ifdef WINDOWS32
2515 * Convert to forward slashes so that construct_command_argv_internal()
2516 * is not confused.
2518 if (shell) {
2519 char *p = w32ify(shell, 0);
2520 strcpy(shell, p);
2522 #endif
2523 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
2525 warn_undefined_variables_flag = save;
2528 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
2530 free (shell);
2531 free (ifs);
2533 return argv;
2535 #endif /* !VMS */
2537 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2539 dup2 (old, new)
2540 int old, new;
2542 int fd;
2544 (void) close (new);
2545 fd = dup (old);
2546 if (fd != new)
2548 (void) close (fd);
2549 errno = EMFILE;
2550 return -1;
2553 return fd;
2555 #endif /* !HAPE_DUP2 && !_AMIGA */