* Rework jobserver yet one more time.
[make.git] / job.c
blob7c7d5a0e48c1df07fc58d596ca627ebd8dd98ba9
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 /* Specifies whether the current process's reserved job token is in use.
206 '+' means it's available, '-' means it isn't. */
208 static char my_job_token = '+';
210 /* Chain of children waiting to run until the load average goes down. */
212 static struct child *waiting_jobs = 0;
214 /* Non-zero if we use a *real* shell (always so on Unix). */
216 int unixy_shell = 1;
218 /* #define debug_flag 1 */
221 #ifdef WINDOWS32
223 * The macro which references this function is defined in make.h.
225 int w32_kill(int pid, int sig)
227 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
229 #endif /* WINDOWS32 */
232 static void
233 free_job_token (child)
234 struct child *child;
236 switch (child->job_token)
238 case '-':
239 /* If this child doesn't have a token, punt. */
240 return;
242 case '+':
243 /* If this child has the reserved token, take it back. */
244 my_job_token = '+';
245 break;
247 default:
248 /* Write any other job tokens back to the pipe. */
249 while (write (job_fds[1], &child->job_token, 1) != 1)
250 if (!EINTR_SET)
251 pfatal_with_name(_("write jobserver"));
252 break;
255 if (debug_flag)
256 printf (_("Released token `%c' for child 0x%08lx (%s).\n"),
257 child->job_token, (unsigned long int) child, child->file->name);
259 child->job_token = '-';
263 /* Write an error message describing the exit status given in
264 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
265 Append "(ignored)" if IGNORED is nonzero. */
267 static void
268 child_error (target_name, exit_code, exit_sig, coredump, ignored)
269 char *target_name;
270 int exit_code, exit_sig, coredump;
271 int ignored;
273 if (ignored && silent_flag)
274 return;
276 #ifdef VMS
277 if (!(exit_code & 1))
278 error (NILF, _("*** [%s] Error 0x%x%s"), target_name, exit_code, ((ignored)? _(" (ignored)") : ""));
279 #else
280 if (exit_sig == 0)
281 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
282 _("*** [%s] Error %d"),
283 target_name, exit_code);
284 else
285 error (NILF, "*** [%s] %s%s",
286 target_name, strsignal (exit_sig),
287 coredump ? _(" (core dumped)") : "");
288 #endif /* VMS */
291 #ifdef VMS
292 /* Wait for nchildren children to terminate */
293 static void
294 vmsWaitForChildren(int *status)
296 while (1)
298 if (!vms_jobsefnmask)
300 *status = 0;
301 return;
304 *status = sys$wflor (32, vms_jobsefnmask);
306 return;
308 #endif
311 /* Handle a dead child. This handler may or may not ever be installed.
313 If we're using the jobserver feature, we need it. First, installing it
314 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
315 read FD to ensure we don't enter another blocking read without reaping all
316 the dead children. In this case we don't need the dead_children count.
318 If we don't have either waitpid or wait3, then make is unreliable, but we
319 use the dead_children count to reap children as best we can. */
321 static unsigned int dead_children = 0;
323 RETSIGTYPE
324 child_handler (sig)
325 int sig;
327 ++dead_children;
329 #ifdef HAVE_JOBSERVER
330 if (job_rfd >= 0)
332 close (job_rfd);
333 job_rfd = -1;
335 #endif
337 if (debug_flag)
338 printf (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children);
342 extern int shell_function_pid, shell_function_completed;
344 /* Reap all dead children, storing the returned status and the new command
345 state (`cs_finished') in the `file' member of the `struct child' for the
346 dead child, and removing the child from the chain. In addition, if BLOCK
347 nonzero, we block in this function until we've reaped at least one
348 complete child, waiting for it to die if necessary. If ERR is nonzero,
349 print an error message first. */
351 void
352 reap_children (block, err)
353 int block, err;
355 WAIT_T status;
356 #ifdef WAIT_NOHANG
357 /* Initially, assume we have some. */
358 int reap_more = 1;
359 # define REAP_MORE reap_more
360 #else
361 # define REAP_MORE dead_children
362 #endif
364 while ((children != 0 || shell_function_pid != 0) &&
365 (block || REAP_MORE))
367 int remote = 0;
368 register int pid;
369 int exit_code, exit_sig, coredump;
370 register struct child *lastc, *c;
371 int child_failed;
372 int any_remote, any_local;
374 if (err && block)
376 /* We might block for a while, so let the user know why. */
377 fflush (stdout);
378 error (NILF, _("*** Waiting for unfinished jobs...."));
381 /* We have one less dead child to reap. As noted in
382 child_handler() above, this count is completely unimportant for
383 all modern, POSIX-y systems that support wait3() or waitpid().
384 The rest of this comment below applies only to early, broken
385 pre-POSIX systems. We keep the count only because... it's there...
387 The test and decrement are not atomic; if it is compiled into:
388 register = dead_children - 1;
389 dead_children = register;
390 a SIGCHLD could come between the two instructions.
391 child_handler increments dead_children.
392 The second instruction here would lose that increment. But the
393 only effect of dead_children being wrong is that we might wait
394 longer than necessary to reap a child, and lose some parallelism;
395 and we might print the "Waiting for unfinished jobs" message above
396 when not necessary. */
398 if (dead_children > 0)
399 --dead_children;
401 any_remote = 0;
402 any_local = shell_function_pid != 0;
403 for (c = children; c != 0; c = c->next)
405 any_remote |= c->remote;
406 any_local |= ! c->remote;
407 if (debug_flag)
408 printf (_("Live child 0x%08lx (%s) PID %ld token %c%s\n"),
409 (unsigned long int) c, c->file->name,
410 (long) c->pid, c->job_token,
411 c->remote ? _(" (remote)") : "");
412 #ifdef VMS
413 break;
414 #endif
417 /* First, check for remote children. */
418 if (any_remote)
419 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
420 else
421 pid = 0;
423 if (pid > 0)
424 /* We got a remote child. */
425 remote = 1;
426 else if (pid < 0)
428 /* A remote status command failed miserably. Punt. */
429 remote_status_lose:
430 if (EINTR_SET)
431 continue;
433 pfatal_with_name ("remote_status");
435 else
437 /* No remote children. Check for local children. */
438 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
439 if (any_local)
441 local_wait:
442 #ifdef VMS
443 vmsWaitForChildren (&status);
444 pid = c->pid;
445 #else
446 #ifdef WAIT_NOHANG
447 if (!block)
448 pid = WAIT_NOHANG (&status);
449 else
450 #endif
451 pid = wait (&status);
452 #endif /* !VMS */
454 else
455 pid = 0;
457 if (pid < 0)
459 /* The wait*() failed miserably. Punt. */
460 if (EINTR_SET)
461 goto local_wait;
463 pfatal_with_name ("wait");
465 else if (pid > 0)
467 /* We got a child exit; chop the status word up. */
468 exit_code = WEXITSTATUS (status);
469 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
470 coredump = WCOREDUMP (status);
472 else
474 /* No local children are dead. */
475 #ifdef WAIT_NOHANG
476 reap_more = 0;
477 #endif
478 if (block && any_remote)
480 /* Now try a blocking wait for a remote child. */
481 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
482 if (pid < 0)
483 goto remote_status_lose;
484 else if (pid == 0)
485 /* No remote children either. Finally give up. */
486 break;
487 else
488 /* We got a remote child. */
489 remote = 1;
491 else
492 break;
494 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
495 #ifdef __MSDOS__
496 /* Life is very different on MSDOS. */
497 pid = dos_pid - 1;
498 status = dos_status;
499 exit_code = WEXITSTATUS (status);
500 if (exit_code == 0xff)
501 exit_code = -1;
502 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
503 coredump = 0;
504 #endif /* __MSDOS__ */
505 #ifdef _AMIGA
506 /* Same on Amiga */
507 pid = amiga_pid - 1;
508 status = amiga_status;
509 exit_code = amiga_status;
510 exit_sig = 0;
511 coredump = 0;
512 #endif /* _AMIGA */
513 #ifdef WINDOWS32
515 HANDLE hPID;
516 int err;
518 /* wait for anything to finish */
519 if (hPID = process_wait_for_any()) {
521 /* was an error found on this process? */
522 err = process_last_err(hPID);
524 /* get exit data */
525 exit_code = process_exit_code(hPID);
527 if (err)
528 fprintf(stderr, "make (e=%d): %s",
529 exit_code, map_windows32_error_to_string(exit_code));
531 /* signal */
532 exit_sig = process_signal(hPID);
534 /* cleanup process */
535 process_cleanup(hPID);
537 coredump = 0;
539 pid = (int) hPID;
541 #endif /* WINDOWS32 */
544 /* Check if this is the child of the `shell' function. */
545 if (!remote && pid == shell_function_pid)
547 /* It is. Leave an indicator for the `shell' function. */
548 if (exit_sig == 0 && exit_code == 127)
549 shell_function_completed = -1;
550 else
551 shell_function_completed = 1;
552 break;
555 child_failed = exit_sig != 0 || exit_code != 0;
557 /* Search for a child matching the deceased one. */
558 lastc = 0;
559 for (c = children; c != 0; lastc = c, c = c->next)
560 if (c->remote == remote && c->pid == pid)
561 break;
563 if (c == 0)
564 /* An unknown child died.
565 Ignore it; it was inherited from our invoker. */
566 continue;
568 if (debug_flag)
569 printf (_("Reaping %s child 0x%08lx PID %ld token %c%s\n"),
570 child_failed ? _("losing") : _("winning"),
571 (unsigned long int) c, (long) c->pid, c->job_token,
572 c->remote ? _(" (remote)") : "");
574 if (c->sh_batch_file) {
575 if (debug_flag)
576 printf (_("Cleaning up temp batch file %s\n"), c->sh_batch_file);
578 /* just try and remove, don't care if this fails */
579 remove (c->sh_batch_file);
581 /* all done with memory */
582 free (c->sh_batch_file);
583 c->sh_batch_file = NULL;
586 /* If this child had the good stdin, say it is now free. */
587 if (c->good_stdin)
588 good_stdin_used = 0;
590 if (child_failed && !c->noerror && !ignore_errors_flag)
592 /* The commands failed. Write an error message,
593 delete non-precious targets, and abort. */
594 static int delete_on_error = -1;
595 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
596 c->file->update_status = 2;
597 if (delete_on_error == -1)
599 struct file *f = lookup_file (".DELETE_ON_ERROR");
600 delete_on_error = f != 0 && f->is_target;
602 if (exit_sig != 0 || delete_on_error)
603 delete_child_targets (c);
605 else
607 if (child_failed)
609 /* The commands failed, but we don't care. */
610 child_error (c->file->name,
611 exit_code, exit_sig, coredump, 1);
612 child_failed = 0;
615 /* If there are more commands to run, try to start them. */
616 if (job_next_command (c))
618 if (handling_fatal_signal)
620 /* Never start new commands while we are dying.
621 Since there are more commands that wanted to be run,
622 the target was not completely remade. So we treat
623 this as if a command had failed. */
624 c->file->update_status = 2;
626 else
628 /* Check again whether to start remotely.
629 Whether or not we want to changes over time.
630 Also, start_remote_job may need state set up
631 by start_remote_job_p. */
632 c->remote = start_remote_job_p (0);
633 start_job_command (c);
634 /* Fatal signals are left blocked in case we were
635 about to put that child on the chain. But it is
636 already there, so it is safe for a fatal signal to
637 arrive now; it will clean up this child's targets. */
638 unblock_sigs ();
639 if (c->file->command_state == cs_running)
640 /* We successfully started the new command.
641 Loop to reap more children. */
642 continue;
645 if (c->file->update_status != 0)
646 /* We failed to start the commands. */
647 delete_child_targets (c);
649 else
650 /* There are no more commands. We got through them all
651 without an unignored error. Now the target has been
652 successfully updated. */
653 c->file->update_status = 0;
656 /* When we get here, all the commands for C->file are finished
657 (or aborted) and C->file->update_status contains 0 or 2. But
658 C->file->command_state is still cs_running if all the commands
659 ran; notice_finish_file looks for cs_running to tell it that
660 it's interesting to check the file's modtime again now. */
662 if (! handling_fatal_signal)
663 /* Notice if the target of the commands has been changed.
664 This also propagates its values for command_state and
665 update_status to its also_make files. */
666 notice_finished_file (c->file);
668 if (debug_flag)
669 printf (_("Removing child 0x%08lx PID %ld token %c%s from chain.\n"),
670 (unsigned long int) c, (long) c->pid, c->job_token,
671 c->remote ? _(" (remote)") : "");
673 /* Block fatal signals while frobnicating the list, so that
674 children and job_slots_used are always consistent. Otherwise
675 a fatal signal arriving after the child is off the chain and
676 before job_slots_used is decremented would believe a child was
677 live and call reap_children again. */
678 block_sigs ();
680 /* If this job has a token out, return it. */
681 free_job_token(c);
683 /* There is now another slot open. */
684 if (job_slots_used > 0)
685 --job_slots_used;
687 /* Remove the child from the chain and free it. */
688 if (lastc == 0)
689 children = c->next;
690 else
691 lastc->next = c->next;
692 if (! handling_fatal_signal) /* Don't bother if about to die. */
693 free_child (c);
695 unblock_sigs ();
697 /* If the job failed, and the -k flag was not given, die,
698 unless we are already in the process of dying. */
699 if (!err && child_failed && !keep_going_flag &&
700 /* fatal_error_signal will die with the right signal. */
701 !handling_fatal_signal)
702 die (2);
704 /* Only block for one child. */
705 block = 0;
708 return;
711 /* Free the storage allocated for CHILD. */
713 static void
714 free_child (child)
715 register struct child *child;
717 if (child->command_lines != 0)
719 register unsigned int i;
720 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
721 free (child->command_lines[i]);
722 free ((char *) child->command_lines);
725 if (child->environment != 0)
727 register char **ep = child->environment;
728 while (*ep != 0)
729 free (*ep++);
730 free ((char *) child->environment);
733 /* If this child has a token it hasn't relinquished, give it up now.
734 This can happen if the job completes immediately, mainly because
735 all the command lines evaluated to empty strings. */
736 free_job_token(child);
738 free ((char *) child);
741 #ifdef POSIX
742 extern sigset_t fatal_signal_set;
743 #endif
745 void
746 block_sigs ()
748 #ifdef POSIX
749 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
750 #else
751 # ifdef HAVE_SIGSETMASK
752 (void) sigblock (fatal_signal_mask);
753 # endif
754 #endif
757 #ifdef POSIX
758 void
759 unblock_sigs ()
761 sigset_t empty;
762 sigemptyset (&empty);
763 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
765 #endif
767 /* Start a job to run the commands specified in CHILD.
768 CHILD is updated to reflect the commands and ID of the child process.
770 NOTE: On return fatal signals are blocked! The caller is responsible
771 for calling `unblock_sigs', once the new child is safely on the chain so
772 it can be cleaned up in the event of a fatal signal. */
774 static void
775 start_job_command (child)
776 register struct child *child;
778 #ifndef _AMIGA
779 static int bad_stdin = -1;
780 #endif
781 register char *p;
782 int flags;
783 #ifdef VMS
784 char *argv;
785 #else
786 char **argv;
787 #endif
789 /* If we have a completely empty commandset, stop now. */
790 if (!child->command_ptr)
791 goto next_command;
793 /* Combine the flags parsed for the line itself with
794 the flags specified globally for this target. */
795 flags = (child->file->command_flags
796 | child->file->cmds->lines_flags[child->command_line - 1]);
798 p = child->command_ptr;
799 child->noerror = flags & COMMANDS_NOERROR;
801 while (*p != '\0')
803 if (*p == '@')
804 flags |= COMMANDS_SILENT;
805 else if (*p == '+')
806 flags |= COMMANDS_RECURSE;
807 else if (*p == '-')
808 child->noerror = 1;
809 else if (!isblank (*p))
810 break;
811 ++p;
814 /* If -q was given, just say that updating `failed'. The exit status of
815 1 tells the user that -q is saying `something to do'; the exit status
816 for a random error is 2. */
817 if (question_flag && !(flags & COMMANDS_RECURSE))
819 child->file->update_status = 1;
820 notice_finished_file (child->file);
821 return;
824 /* There may be some preceding whitespace left if there
825 was nothing but a backslash on the first line. */
826 p = next_token (p);
828 /* Figure out an argument list from this command line. */
831 char *end = 0;
832 #ifdef VMS
833 argv = p;
834 #else
835 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
836 #endif
837 if (end == NULL)
838 child->command_ptr = NULL;
839 else
841 *end++ = '\0';
842 child->command_ptr = end;
846 if (touch_flag && !(flags & COMMANDS_RECURSE))
848 /* Go on to the next command. It might be the recursive one.
849 We construct ARGV only to find the end of the command line. */
850 #ifndef VMS
851 free (argv[0]);
852 free ((char *) argv);
853 #endif
854 argv = 0;
857 if (argv == 0)
859 next_command:
860 #ifdef __MSDOS__
861 execute_by_shell = 0; /* in case construct_command_argv sets it */
862 #endif
863 /* This line has no commands. Go to the next. */
864 if (job_next_command (child))
865 start_job_command (child);
866 else
868 /* No more commands. Make sure we're "running"; we might not be if
869 (e.g.) all commands were skipped due to -n. */
870 set_command_state (child->file, cs_running);
871 child->file->update_status = 0;
872 notice_finished_file (child->file);
874 return;
877 /* Print out the command. If silent, we call `message' with null so it
878 can log the working directory before the command's own error messages
879 appear. */
881 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
882 ? "%s" : (char *) 0, p);
884 /* Optimize an empty command. People use this for timestamp rules,
885 and forking a useless shell all the time leads to inefficiency. */
887 #if !defined(VMS) && !defined(_AMIGA)
888 if (
889 #ifdef __MSDOS__
890 unixy_shell /* the test is complicated and we already did it */
891 #else
892 (argv[0] && !strcmp(argv[0], "/bin/sh"))
893 #endif
894 && (argv[1] && !strcmp(argv[1], "-c"))
895 && (argv[2] && !strcmp(argv[2], ":"))
896 && argv[3] == NULL)
898 free (argv[0]);
899 free ((char *) argv);
900 goto next_command;
902 #endif /* !VMS && !_AMIGA */
904 /* Tell update_goal_chain that a command has been started on behalf of
905 this target. It is important that this happens here and not in
906 reap_children (where we used to do it), because reap_children might be
907 reaping children from a different target. We want this increment to
908 guaranteedly indicate that a command was started for the dependency
909 chain (i.e., update_file recursion chain) we are processing. */
911 ++commands_started;
913 /* If -n was given, recurse to get the next line in the sequence. */
915 if (just_print_flag && !(flags & COMMANDS_RECURSE))
917 #ifndef VMS
918 free (argv[0]);
919 free ((char *) argv);
920 #endif
921 goto next_command;
924 /* Flush the output streams so they won't have things written twice. */
926 fflush (stdout);
927 fflush (stderr);
929 #ifndef VMS
930 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
932 /* Set up a bad standard input that reads from a broken pipe. */
934 if (bad_stdin == -1)
936 /* Make a file descriptor that is the read end of a broken pipe.
937 This will be used for some children's standard inputs. */
938 int pd[2];
939 if (pipe (pd) == 0)
941 /* Close the write side. */
942 (void) close (pd[1]);
943 /* Save the read side. */
944 bad_stdin = pd[0];
946 /* Set the descriptor to close on exec, so it does not litter any
947 child's descriptor table. When it is dup2'd onto descriptor 0,
948 that descriptor will not close on exec. */
949 CLOSE_ON_EXEC (bad_stdin);
953 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
955 /* Decide whether to give this child the `good' standard input
956 (one that points to the terminal or whatever), or the `bad' one
957 that points to the read side of a broken pipe. */
959 child->good_stdin = !good_stdin_used;
960 if (child->good_stdin)
961 good_stdin_used = 1;
963 #endif /* !VMS */
965 child->deleted = 0;
967 #ifndef _AMIGA
968 /* Set up the environment for the child. */
969 if (child->environment == 0)
970 child->environment = target_environment (child->file);
971 #endif
973 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
975 #ifndef VMS
976 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
977 if (child->remote)
979 int is_remote, id, used_stdin;
980 if (start_remote_job (argv, child->environment,
981 child->good_stdin ? 0 : bad_stdin,
982 &is_remote, &id, &used_stdin))
983 /* Don't give up; remote execution may fail for various reasons. If
984 so, simply run the job locally. */
985 goto run_local;
986 else
988 if (child->good_stdin && !used_stdin)
990 child->good_stdin = 0;
991 good_stdin_used = 0;
993 child->remote = is_remote;
994 child->pid = id;
997 else
998 #endif /* !VMS */
1000 /* Fork the child process. */
1002 char **parent_environ;
1004 run_local:
1005 block_sigs ();
1007 child->remote = 0;
1009 #ifdef VMS
1011 if (!child_execute_job (argv, child)) {
1012 /* Fork failed! */
1013 perror_with_name ("vfork", "");
1014 goto error;
1017 #else
1019 parent_environ = environ;
1020 child->pid = vfork ();
1021 environ = parent_environ; /* Restore value child may have clobbered. */
1022 if (child->pid == 0)
1024 /* We are the child side. */
1025 unblock_sigs ();
1027 /* If we aren't running a recursive command and we have a jobserver
1028 pipe, close it before exec'ing. */
1029 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1031 close (job_fds[0]);
1032 close (job_fds[1]);
1034 if (job_rfd >= 0)
1035 close (job_rfd);
1037 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1038 argv, child->environment);
1040 else if (child->pid < 0)
1042 /* Fork failed! */
1043 unblock_sigs ();
1044 perror_with_name ("vfork", "");
1045 goto error;
1047 #endif /* !VMS */
1050 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1051 #ifdef __MSDOS__
1053 int proc_return;
1055 block_sigs ();
1056 dos_status = 0;
1058 /* We call `system' to do the job of the SHELL, since stock DOS
1059 shell is too dumb. Our `system' knows how to handle long
1060 command lines even if pipes/redirection is needed; it will only
1061 call COMMAND.COM when its internal commands are used. */
1062 if (execute_by_shell)
1064 char *cmdline = argv[0];
1065 /* We don't have a way to pass environment to `system',
1066 so we need to save and restore ours, sigh... */
1067 char **parent_environ = environ;
1069 environ = child->environment;
1071 /* If we have a *real* shell, tell `system' to call
1072 it to do everything for us. */
1073 if (unixy_shell)
1075 /* A *real* shell on MSDOS may not support long
1076 command lines the DJGPP way, so we must use `system'. */
1077 cmdline = argv[2]; /* get past "shell -c" */
1080 dos_command_running = 1;
1081 proc_return = system (cmdline);
1082 environ = parent_environ;
1083 execute_by_shell = 0; /* for the next time */
1085 else
1087 dos_command_running = 1;
1088 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1091 /* Need to unblock signals before turning off
1092 dos_command_running, so that child's signals
1093 will be treated as such (see fatal_error_signal). */
1094 unblock_sigs ();
1095 dos_command_running = 0;
1097 /* If the child got a signal, dos_status has its
1098 high 8 bits set, so be careful not to alter them. */
1099 if (proc_return == -1)
1100 dos_status |= 0xff;
1101 else
1102 dos_status |= (proc_return & 0xff);
1103 ++dead_children;
1104 child->pid = dos_pid++;
1106 #endif /* __MSDOS__ */
1107 #ifdef _AMIGA
1108 amiga_status = MyExecute (argv);
1110 ++dead_children;
1111 child->pid = amiga_pid++;
1112 if (amiga_batch_file)
1114 amiga_batch_file = 0;
1115 DeleteFile (amiga_bname); /* Ignore errors. */
1117 #endif /* Amiga */
1118 #ifdef WINDOWS32
1120 HANDLE hPID;
1121 char* arg0;
1123 /* make UNC paths safe for CreateProcess -- backslash format */
1124 arg0 = argv[0];
1125 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1126 for ( ; arg0 && *arg0; arg0++)
1127 if (*arg0 == '/')
1128 *arg0 = '\\';
1130 /* make sure CreateProcess() has Path it needs */
1131 sync_Path_environment();
1133 hPID = process_easy(argv, child->environment);
1135 if (hPID != INVALID_HANDLE_VALUE)
1136 child->pid = (int) hPID;
1137 else {
1138 int i;
1139 unblock_sigs();
1140 fprintf(stderr,
1141 _("process_easy() failed failed to launch process (e=%d)\n"),
1142 process_last_err(hPID));
1143 for (i = 0; argv[i]; i++)
1144 fprintf(stderr, "%s ", argv[i]);
1145 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1148 #endif /* WINDOWS32 */
1149 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1151 /* We are the parent side. Set the state to
1152 say the commands are running and return. */
1154 set_command_state (child->file, cs_running);
1156 /* Free the storage used by the child's argument list. */
1157 #ifndef VMS
1158 free (argv[0]);
1159 free ((char *) argv);
1160 #endif
1162 return;
1164 error:
1165 child->file->update_status = 2;
1166 notice_finished_file (child->file);
1167 return;
1170 /* Try to start a child running.
1171 Returns nonzero if the child was started (and maybe finished), or zero if
1172 the load was too high and the child was put on the `waiting_jobs' chain. */
1174 static int
1175 start_waiting_job (c)
1176 struct child *c;
1178 struct file *f = c->file;
1180 /* If we can start a job remotely, we always want to, and don't care about
1181 the local load average. We record that the job should be started
1182 remotely in C->remote for start_job_command to test. */
1184 c->remote = start_remote_job_p (1);
1186 /* If we are running at least one job already and the load average
1187 is too high, make this one wait. */
1188 if (!c->remote && job_slots_used > 0 && load_too_high ())
1190 /* Put this child on the chain of children waiting for the load average
1191 to go down. */
1192 set_command_state (f, cs_running);
1193 c->next = waiting_jobs;
1194 waiting_jobs = c;
1195 return 0;
1198 /* Start the first command; reap_children will run later command lines. */
1199 start_job_command (c);
1201 switch (f->command_state)
1203 case cs_running:
1204 c->next = children;
1205 if (debug_flag)
1206 printf (_("Putting child 0x%08lx (%s) PID %ld token %c%s on the chain.\n"),
1207 (unsigned long int) c, c->file->name,
1208 (long) c->pid, c->job_token,
1209 c->remote ? _(" (remote)") : "");
1210 children = c;
1211 /* One more job slot is in use. */
1212 ++job_slots_used;
1213 unblock_sigs ();
1214 break;
1216 case cs_not_started:
1217 /* All the command lines turned out to be empty. */
1218 f->update_status = 0;
1219 /* FALLTHROUGH */
1221 case cs_finished:
1222 notice_finished_file (f);
1223 free_child (c);
1224 break;
1226 default:
1227 assert (f->command_state == cs_finished);
1228 break;
1231 return 1;
1234 /* Create a `struct child' for FILE and start its commands running. */
1236 void
1237 new_job (file)
1238 register struct file *file;
1240 register struct commands *cmds = file->cmds;
1241 register struct child *c;
1242 char **lines;
1243 register unsigned int i;
1245 /* Let any previously decided-upon jobs that are waiting
1246 for the load to go down start before this new one. */
1247 start_waiting_jobs ();
1249 /* Reap any children that might have finished recently. */
1250 reap_children (0, 0);
1252 /* Chop the commands up into lines if they aren't already. */
1253 chop_commands (cmds);
1255 /* Expand the command lines and store the results in LINES. */
1256 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1257 for (i = 0; i < cmds->ncommand_lines; ++i)
1259 /* Collapse backslash-newline combinations that are inside variable
1260 or function references. These are left alone by the parser so
1261 that they will appear in the echoing of commands (where they look
1262 nice); and collapsed by construct_command_argv when it tokenizes.
1263 But letting them survive inside function invocations loses because
1264 we don't want the functions to see them as part of the text. */
1266 char *in, *out, *ref;
1268 /* IN points to where in the line we are scanning.
1269 OUT points to where in the line we are writing.
1270 When we collapse a backslash-newline combination,
1271 IN gets ahead of OUT. */
1273 in = out = cmds->command_lines[i];
1274 while ((ref = index (in, '$')) != 0)
1276 ++ref; /* Move past the $. */
1278 if (out != in)
1279 /* Copy the text between the end of the last chunk
1280 we processed (where IN points) and the new chunk
1281 we are about to process (where REF points). */
1282 bcopy (in, out, ref - in);
1284 /* Move both pointers past the boring stuff. */
1285 out += ref - in;
1286 in = ref;
1288 if (*ref == '(' || *ref == '{')
1290 char openparen = *ref;
1291 char closeparen = openparen == '(' ? ')' : '}';
1292 int count;
1293 char *p;
1295 *out++ = *in++; /* Copy OPENPAREN. */
1296 /* IN now points past the opening paren or brace.
1297 Count parens or braces until it is matched. */
1298 count = 0;
1299 while (*in != '\0')
1301 if (*in == closeparen && --count < 0)
1302 break;
1303 else if (*in == '\\' && in[1] == '\n')
1305 /* We have found a backslash-newline inside a
1306 variable or function reference. Eat it and
1307 any following whitespace. */
1309 int quoted = 0;
1310 for (p = in - 1; p > ref && *p == '\\'; --p)
1311 quoted = !quoted;
1313 if (quoted)
1314 /* There were two or more backslashes, so this is
1315 not really a continuation line. We don't collapse
1316 the quoting backslashes here as is done in
1317 collapse_continuations, because the line will
1318 be collapsed again after expansion. */
1319 *out++ = *in++;
1320 else
1322 /* Skip the backslash, newline and
1323 any following whitespace. */
1324 in = next_token (in + 2);
1326 /* Discard any preceding whitespace that has
1327 already been written to the output. */
1328 while (out > ref && isblank (out[-1]))
1329 --out;
1331 /* Replace it all with a single space. */
1332 *out++ = ' ';
1335 else
1337 if (*in == openparen)
1338 ++count;
1340 *out++ = *in++;
1346 /* There are no more references in this line to worry about.
1347 Copy the remaining uninteresting text to the output. */
1348 if (out != in)
1349 strcpy (out, in);
1351 /* Finally, expand the line. */
1352 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1353 file);
1356 /* Start the command sequence, record it in a new
1357 `struct child', and add that to the chain. */
1359 c = (struct child *) xmalloc (sizeof (struct child));
1360 c->file = file;
1361 c->command_lines = lines;
1362 c->command_line = 0;
1363 c->command_ptr = 0;
1364 c->environment = 0;
1365 c->sh_batch_file = NULL;
1366 c->job_token = '-';
1368 /* Fetch the first command line to be run. */
1369 job_next_command (c);
1371 /* Wait for a job slot to be freed up. If we allow an infinite number
1372 don't bother; also job_slots will == 0 if we're using the jobserver. */
1373 if (job_slots != 0)
1374 while (job_slots_used == job_slots)
1375 reap_children (1, 0);
1376 #ifdef MAKE_JOBSERVER
1377 /* If we are controlling multiple jobs, and we don't yet have one,
1378 obtain a token before starting the child. */
1379 else if (job_fds[0] >= 0)
1381 while (c->job_token == '-')
1382 /* If the reserved token is available, just use that. */
1383 if (my_job_token == '+')
1385 c->job_token = my_job_token;
1386 my_job_token = '-';
1388 /* Read a token. As long as there's no token available we'll block.
1389 If we get a SIGCHLD we'll return with EINTR. If one happened
1390 before we got here we'll return immediately with EBADF because
1391 the signal handler closes the dup'd file descriptor. */
1392 else if (read (job_rfd, &c->job_token, 1) < 1)
1394 if (errno != EINTR && errno != EBADF)
1395 pfatal_with_name (_("read jobs pipe"));
1397 /* Re-dup the read side of the pipe, so the signal handler can
1398 notify us if we miss a child. */
1399 if (job_rfd < 0)
1400 job_rfd = dup (job_fds[0]);
1402 /* Something's done. We don't want to block for a whole child,
1403 just reap whatever's there. */
1404 reap_children (0, 0);
1407 assert(c->job_token != '-');
1408 if (debug_flag)
1409 printf (_("Obtained token `%c' for child 0x%08lx (%s).\n"),
1410 c->job_token, (unsigned long int) c, c->file->name);
1412 #endif
1414 /* The job is now primed. Start it running.
1415 (This will notice if there are in fact no commands.) */
1416 (void)start_waiting_job (c);
1418 if (job_slots == 1)
1419 /* Since there is only one job slot, make things run linearly.
1420 Wait for the child to die, setting the state to `cs_finished'. */
1421 while (file->command_state == cs_running)
1422 reap_children (1, 0);
1424 return;
1427 /* Move CHILD's pointers to the next command for it to execute.
1428 Returns nonzero if there is another command. */
1430 static int
1431 job_next_command (child)
1432 struct child *child;
1434 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1436 /* There are no more lines in the expansion of this line. */
1437 if (child->command_line == child->file->cmds->ncommand_lines)
1439 /* There are no more lines to be expanded. */
1440 child->command_ptr = 0;
1441 return 0;
1443 else
1444 /* Get the next line to run. */
1445 child->command_ptr = child->command_lines[child->command_line++];
1447 return 1;
1450 static int
1451 load_too_high ()
1453 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1454 return 1;
1455 #else
1456 double load;
1458 if (max_load_average < 0)
1459 return 0;
1461 make_access ();
1462 if (getloadavg (&load, 1) != 1)
1464 static int lossage = -1;
1465 /* Complain only once for the same error. */
1466 if (lossage == -1 || errno != lossage)
1468 if (errno == 0)
1469 /* An errno value of zero means getloadavg is just unsupported. */
1470 error (NILF, _("cannot enforce load limits on this operating system"));
1471 else
1472 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1474 lossage = errno;
1475 load = 0;
1477 user_access ();
1479 return load >= max_load_average;
1480 #endif
1483 /* Start jobs that are waiting for the load to be lower. */
1485 void
1486 start_waiting_jobs ()
1488 struct child *job;
1490 if (waiting_jobs == 0)
1491 return;
1495 /* Check for recently deceased descendants. */
1496 reap_children (0, 0);
1498 /* Take a job off the waiting list. */
1499 job = waiting_jobs;
1500 waiting_jobs = job->next;
1502 /* Try to start that job. We break out of the loop as soon
1503 as start_waiting_job puts one back on the waiting list. */
1505 while (start_waiting_job (job) && waiting_jobs != 0);
1507 return;
1510 #ifndef WINDOWS32
1511 #ifdef VMS
1512 #include <descrip.h>
1513 #include <clidef.h>
1515 /* This is called as an AST when a child process dies (it won't get
1516 interrupted by anything except a higher level AST).
1518 int vmsHandleChildTerm(struct child *child)
1520 int status;
1521 register struct child *lastc, *c;
1522 int child_failed;
1524 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1526 lib$free_ef(&child->efn);
1528 (void) sigblock (fatal_signal_mask);
1530 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1532 /* Search for a child matching the deceased one. */
1533 lastc = 0;
1534 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1535 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1536 #else
1537 c = child;
1538 #endif
1540 if (child_failed && !c->noerror && !ignore_errors_flag)
1542 /* The commands failed. Write an error message,
1543 delete non-precious targets, and abort. */
1544 child_error (c->file->name, c->cstatus, 0, 0, 0);
1545 c->file->update_status = 1;
1546 delete_child_targets (c);
1548 else
1550 if (child_failed)
1552 /* The commands failed, but we don't care. */
1553 child_error (c->file->name, c->cstatus, 0, 0, 1);
1554 child_failed = 0;
1557 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1558 /* If there are more commands to run, try to start them. */
1559 start_job (c);
1561 switch (c->file->command_state)
1563 case cs_running:
1564 /* Successfully started. */
1565 break;
1567 case cs_finished:
1568 if (c->file->update_status != 0) {
1569 /* We failed to start the commands. */
1570 delete_child_targets (c);
1572 break;
1574 default:
1575 error (NILF, _("internal error: `%s' command_state"), c->file->name);
1576 abort ();
1577 break;
1579 #endif /* RECURSIVEJOBS */
1582 /* Set the state flag to say the commands have finished. */
1583 c->file->command_state = cs_finished;
1584 notice_finished_file (c->file);
1586 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1587 /* Remove the child from the chain and free it. */
1588 if (lastc == 0)
1589 children = c->next;
1590 else
1591 lastc->next = c->next;
1592 free_child (c);
1593 #endif /* RECURSIVEJOBS */
1595 /* There is now another slot open. */
1596 if (job_slots_used > 0)
1597 --job_slots_used;
1599 /* If the job failed, and the -k flag was not given, die. */
1600 if (child_failed && !keep_going_flag)
1601 die (EXIT_FAILURE);
1603 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1605 return 1;
1608 /* VMS:
1609 Spawn a process executing the command in ARGV and return its pid. */
1611 #define MAXCMDLEN 200
1614 child_execute_job (argv, child)
1615 char *argv;
1616 struct child *child;
1618 int i;
1619 static struct dsc$descriptor_s cmddsc;
1620 #ifndef DONTWAITFORCHILD
1621 int spflags = 0;
1622 #else
1623 int spflags = CLI$M_NOWAIT;
1624 #endif
1625 int status;
1626 char cmd[4096],*p,*c;
1627 char comname[50];
1629 /* Remove backslashes */
1630 for (p = argv, c = cmd; *p; p++,c++)
1632 if (*p == '\\') p++;
1633 *c = *p;
1635 *c = *p;
1637 /* Check for maximum DCL length and create *.com file if neccesary.
1638 Also create a .com file if the command is more than one line long. */
1640 comname[0] = '\0';
1642 if (strlen (cmd) > MAXCMDLEN || strchr (cmd, '\n'))
1644 FILE *outfile;
1645 char tmp;
1647 strcpy (comname, "sys$scratch:CMDXXXXXX.COM");
1648 (void) mktemp (comname);
1650 outfile = fopen (comname, "w");
1651 if (outfile == 0)
1652 pfatal_with_name (comname);
1654 fprintf (outfile, "$ ");
1655 c = cmd;
1657 while (c)
1659 p = strchr (c, ',');
1660 if ((p == NULL) || (p-c > MAXCMDLEN))
1661 p = strchr (c, ' ');
1662 if (p != NULL)
1664 p++;
1665 tmp = *p;
1666 *p = '\0';
1668 else
1669 tmp = '\0';
1670 fprintf (outfile, "%s%s\n", c, (tmp == '\0')?"":" -");
1671 if (p != NULL)
1672 *p = tmp;
1673 c = p;
1676 fclose (outfile);
1678 sprintf (cmd, "$ @%s", comname);
1680 if (debug_flag)
1681 printf (_("Executing %s instead\n"), cmd);
1684 cmddsc.dsc$w_length = strlen(cmd);
1685 cmddsc.dsc$a_pointer = cmd;
1686 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
1687 cmddsc.dsc$b_class = DSC$K_CLASS_S;
1689 child->efn = 0;
1690 while (child->efn < 32 || child->efn > 63)
1692 status = lib$get_ef(&child->efn);
1693 if (!(status & 1))
1694 return 0;
1697 sys$clref(child->efn);
1699 vms_jobsefnmask |= (1 << (child->efn - 32));
1701 #ifndef DONTWAITFORCHILD
1702 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1703 &child->efn,0,0);
1704 vmsHandleChildTerm(child);
1705 #else
1706 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1707 &child->efn,vmsHandleChildTerm,child);
1708 #endif
1710 if (!(status & 1))
1712 printf(_("Error spawning, %d\n"),status);
1713 fflush(stdout);
1716 unlink (comname);
1718 return (status & 1);
1721 #else /* !VMS */
1723 #if !defined (_AMIGA) && !defined (__MSDOS__)
1724 /* UNIX:
1725 Replace the current process with one executing the command in ARGV.
1726 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1727 the environment of the new program. This function does not return. */
1729 void
1730 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1731 int stdin_fd, stdout_fd;
1732 char **argv, **envp;
1734 if (stdin_fd != 0)
1735 (void) dup2 (stdin_fd, 0);
1736 if (stdout_fd != 1)
1737 (void) dup2 (stdout_fd, 1);
1738 if (stdin_fd != 0)
1739 (void) close (stdin_fd);
1740 if (stdout_fd != 1)
1741 (void) close (stdout_fd);
1743 /* Run the command. */
1744 exec_command (argv, envp);
1746 #endif /* !AMIGA && !__MSDOS__ */
1747 #endif /* !VMS */
1748 #endif /* !WINDOWS32 */
1750 #ifndef _AMIGA
1751 /* Replace the current process with one running the command in ARGV,
1752 with environment ENVP. This function does not return. */
1754 void
1755 exec_command (argv, envp)
1756 char **argv, **envp;
1758 #ifdef VMS
1759 /* Run the program. */
1760 execve (argv[0], argv, envp);
1761 perror_with_name ("execve: ", argv[0]);
1762 _exit (EXIT_FAILURE);
1763 #else
1764 #ifdef WINDOWS32
1765 HANDLE hPID;
1766 HANDLE hWaitPID;
1767 int err = 0;
1768 int exit_code = EXIT_FAILURE;
1770 /* make sure CreateProcess() has Path it needs */
1771 sync_Path_environment();
1773 /* launch command */
1774 hPID = process_easy(argv, envp);
1776 /* make sure launch ok */
1777 if (hPID == INVALID_HANDLE_VALUE)
1779 int i;
1780 fprintf(stderr,
1781 _("process_easy() failed failed to launch process (e=%d)\n"),
1782 process_last_err(hPID));
1783 for (i = 0; argv[i]; i++)
1784 fprintf(stderr, "%s ", argv[i]);
1785 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1786 exit(EXIT_FAILURE);
1789 /* wait and reap last child */
1790 while (hWaitPID = process_wait_for_any())
1792 /* was an error found on this process? */
1793 err = process_last_err(hWaitPID);
1795 /* get exit data */
1796 exit_code = process_exit_code(hWaitPID);
1798 if (err)
1799 fprintf(stderr, "make (e=%d, rc=%d): %s",
1800 err, exit_code, map_windows32_error_to_string(err));
1802 /* cleanup process */
1803 process_cleanup(hWaitPID);
1805 /* expect to find only last pid, warn about other pids reaped */
1806 if (hWaitPID == hPID)
1807 break;
1808 else
1809 fprintf(stderr,
1810 _("make reaped child pid %d, still waiting for pid %d\n"),
1811 hWaitPID, hPID);
1814 /* return child's exit code as our exit code */
1815 exit(exit_code);
1817 #else /* !WINDOWS32 */
1819 /* Be the user, permanently. */
1820 child_access ();
1822 /* Run the program. */
1823 environ = envp;
1824 execvp (argv[0], argv);
1826 switch (errno)
1828 case ENOENT:
1829 error (NILF, _("%s: Command not found"), argv[0]);
1830 break;
1831 case ENOEXEC:
1833 /* The file is not executable. Try it as a shell script. */
1834 extern char *getenv ();
1835 char *shell;
1836 char **new_argv;
1837 int argc;
1839 shell = getenv ("SHELL");
1840 if (shell == 0)
1841 shell = default_shell;
1843 argc = 1;
1844 while (argv[argc] != 0)
1845 ++argc;
1847 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1848 new_argv[0] = shell;
1849 new_argv[1] = argv[0];
1850 while (argc > 0)
1852 new_argv[1 + argc] = argv[argc];
1853 --argc;
1856 execvp (shell, new_argv);
1857 if (errno == ENOENT)
1858 error (NILF, _("%s: Shell program not found"), shell);
1859 else
1860 perror_with_name ("execvp: ", shell);
1861 break;
1864 default:
1865 perror_with_name ("execvp: ", argv[0]);
1866 break;
1869 _exit (127);
1870 #endif /* !WINDOWS32 */
1871 #endif /* !VMS */
1873 #else /* On Amiga */
1874 void exec_command (argv)
1875 char **argv;
1877 MyExecute (argv);
1880 void clean_tmp (void)
1882 DeleteFile (amiga_bname);
1885 #endif /* On Amiga */
1887 #ifndef VMS
1888 /* Figure out the argument list necessary to run LINE as a command. Try to
1889 avoid using a shell. This routine handles only ' quoting, and " quoting
1890 when no backslash, $ or ` characters are seen in the quotes. Starting
1891 quotes may be escaped with a backslash. If any of the characters in
1892 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1893 is the first word of a line, the shell is used.
1895 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1896 If *RESTP is NULL, newlines will be ignored.
1898 SHELL is the shell to use, or nil to use the default shell.
1899 IFS is the value of $IFS, or nil (meaning the default). */
1901 static char **
1902 construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr)
1903 char *line, **restp;
1904 char *shell, *ifs;
1905 char **batch_filename_ptr;
1907 #ifdef __MSDOS__
1908 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
1909 We call `system' for anything that requires ``slow'' processing,
1910 because DOS shells are too dumb. When $SHELL points to a real
1911 (unix-style) shell, `system' just calls it to do everything. When
1912 $SHELL points to a DOS shell, `system' does most of the work
1913 internally, calling the shell only for its internal commands.
1914 However, it looks on the $PATH first, so you can e.g. have an
1915 external command named `mkdir'.
1917 Since we call `system', certain characters and commands below are
1918 actually not specific to COMMAND.COM, but to the DJGPP implementation
1919 of `system'. In particular:
1921 The shell wildcard characters are in DOS_CHARS because they will
1922 not be expanded if we call the child via `spawnXX'.
1924 The `;' is in DOS_CHARS, because our `system' knows how to run
1925 multiple commands on a single line.
1927 DOS_CHARS also include characters special to 4DOS/NDOS, so we
1928 won't have to tell one from another and have one more set of
1929 commands and special characters. */
1930 static char sh_chars_dos[] = "*?[];|<>%^&()";
1931 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1932 "copy", "ctty", "date", "del", "dir", "echo",
1933 "erase", "exit", "for", "goto", "if", "md",
1934 "mkdir", "path", "pause", "prompt", "rd",
1935 "rmdir", "rem", "ren", "rename", "set",
1936 "shift", "time", "type", "ver", "verify",
1937 "vol", ":", 0 };
1939 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1940 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
1941 "logout", "set", "umask", "wait", "while",
1942 "for", "case", "if", ":", ".", "break",
1943 "continue", "export", "read", "readonly",
1944 "shift", "times", "trap", "switch", 0 };
1946 char *sh_chars;
1947 char **sh_cmds;
1948 #else
1949 #ifdef _AMIGA
1950 static char sh_chars[] = "#;\"|<>()?*$`";
1951 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
1952 "rename", "set", "setenv", "date", "makedir",
1953 "skip", "else", "endif", "path", "prompt",
1954 "unset", "unsetenv", "version",
1955 0 };
1956 #else
1957 #ifdef WINDOWS32
1958 static char sh_chars_dos[] = "\"|<>";
1959 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1960 "copy", "ctty", "date", "del", "dir", "echo",
1961 "erase", "exit", "for", "goto", "if", "if", "md",
1962 "mkdir", "path", "pause", "prompt", "rem", "ren",
1963 "rename", "set", "shift", "time", "type",
1964 "ver", "verify", "vol", ":", 0 };
1965 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1966 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
1967 "logout", "set", "umask", "wait", "while", "for",
1968 "case", "if", ":", ".", "break", "continue",
1969 "export", "read", "readonly", "shift", "times",
1970 "trap", "switch", "test",
1971 #ifdef BATCH_MODE_ONLY_SHELL
1972 "echo",
1973 #endif
1974 0 };
1975 char* sh_chars;
1976 char** sh_cmds;
1977 #else /* WINDOWS32 */
1978 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1979 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1980 "logout", "set", "umask", "wait", "while", "for",
1981 "case", "if", ":", ".", "break", "continue",
1982 "export", "read", "readonly", "shift", "times",
1983 "trap", "switch", 0 };
1984 #endif /* WINDOWS32 */
1985 #endif /* Amiga */
1986 #endif /* __MSDOS__ */
1987 register int i;
1988 register char *p;
1989 register char *ap;
1990 char *end;
1991 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
1992 char **new_argv = 0;
1993 #ifdef WINDOWS32
1994 int slow_flag = 0;
1996 if (no_default_sh_exe) {
1997 sh_cmds = sh_cmds_dos;
1998 sh_chars = sh_chars_dos;
1999 } else {
2000 sh_cmds = sh_cmds_sh;
2001 sh_chars = sh_chars_sh;
2003 #endif /* WINDOWS32 */
2005 if (restp != NULL)
2006 *restp = NULL;
2008 /* Make sure not to bother processing an empty line. */
2009 while (isblank (*line))
2010 ++line;
2011 if (*line == '\0')
2012 return 0;
2014 /* See if it is safe to parse commands internally. */
2015 if (shell == 0)
2016 shell = default_shell;
2017 #ifdef WINDOWS32
2018 else if (strcmp (shell, default_shell))
2020 char *s1 = _fullpath(NULL, shell, 0);
2021 char *s2 = _fullpath(NULL, default_shell, 0);
2023 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2025 if (s1);
2026 free(s1);
2027 if (s2);
2028 free(s2);
2030 if (slow_flag)
2031 goto slow;
2032 #else /* not WINDOWS32 */
2033 #ifdef __MSDOS__
2034 else if (stricmp (shell, default_shell))
2036 extern int _is_unixy_shell (const char *_path);
2038 message (1, _("$SHELL changed (was `%s', now `%s')"), default_shell, shell);
2039 unixy_shell = _is_unixy_shell (shell);
2040 default_shell = shell;
2042 if (unixy_shell)
2044 sh_chars = sh_chars_sh;
2045 sh_cmds = sh_cmds_sh;
2047 else
2049 sh_chars = sh_chars_dos;
2050 sh_cmds = sh_cmds_dos;
2052 #else /* not __MSDOS__ */
2053 else if (strcmp (shell, default_shell))
2054 goto slow;
2055 #endif /* not __MSDOS__ */
2056 #endif /* not WINDOWS32 */
2058 if (ifs != 0)
2059 for (ap = ifs; *ap != '\0'; ++ap)
2060 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2061 goto slow;
2063 i = strlen (line) + 1;
2065 /* More than 1 arg per character is impossible. */
2066 new_argv = (char **) xmalloc (i * sizeof (char *));
2068 /* All the args can fit in a buffer as big as LINE is. */
2069 ap = new_argv[0] = (char *) xmalloc (i);
2070 end = ap + i;
2072 /* I is how many complete arguments have been found. */
2073 i = 0;
2074 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2075 for (p = line; *p != '\0'; ++p)
2077 if (ap > end)
2078 abort ();
2080 if (instring)
2082 string_char:
2083 /* Inside a string, just copy any char except a closing quote
2084 or a backslash-newline combination. */
2085 if (*p == instring)
2087 instring = 0;
2088 if (ap == new_argv[0] || *(ap-1) == '\0')
2089 last_argument_was_empty = 1;
2091 else if (*p == '\\' && p[1] == '\n')
2092 goto swallow_escaped_newline;
2093 else if (*p == '\n' && restp != NULL)
2095 /* End of the command line. */
2096 *restp = p;
2097 goto end_of_line;
2099 /* Backslash, $, and ` are special inside double quotes.
2100 If we see any of those, punt.
2101 But on MSDOS, if we use COMMAND.COM, double and single
2102 quotes have the same effect. */
2103 else if (instring == '"' && index ("\\$`", *p) != 0 && unixy_shell)
2104 goto slow;
2105 else
2106 *ap++ = *p;
2108 else if (index (sh_chars, *p) != 0)
2109 /* Not inside a string, but it's a special char. */
2110 goto slow;
2111 #ifdef __MSDOS__
2112 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2113 /* `...' is a wildcard in DJGPP. */
2114 goto slow;
2115 #endif
2116 else
2117 /* Not a special char. */
2118 switch (*p)
2120 case '=':
2121 /* Equals is a special character in leading words before the
2122 first word with no equals sign in it. This is not the case
2123 with sh -k, but we never get here when using nonstandard
2124 shell flags. */
2125 if (! seen_nonequals && unixy_shell)
2126 goto slow;
2127 word_has_equals = 1;
2128 *ap++ = '=';
2129 break;
2131 case '\\':
2132 /* Backslash-newline combinations are eaten. */
2133 if (p[1] == '\n')
2135 swallow_escaped_newline:
2137 /* Eat the backslash, the newline, and following whitespace,
2138 replacing it all with a single space. */
2139 p += 2;
2141 /* If there is a tab after a backslash-newline,
2142 remove it from the source line which will be echoed,
2143 since it was most likely used to line
2144 up the continued line with the previous one. */
2145 if (*p == '\t')
2146 /* Note these overlap and strcpy() is undefined for
2147 overlapping objects in ANSI C. The strlen() _IS_ right,
2148 since we need to copy the nul byte too. */
2149 bcopy (p + 1, p, strlen(p));
2151 if (instring)
2152 goto string_char;
2153 else
2155 if (ap != new_argv[i])
2156 /* Treat this as a space, ending the arg.
2157 But if it's at the beginning of the arg, it should
2158 just get eaten, rather than becoming an empty arg. */
2159 goto end_of_arg;
2160 else
2161 p = next_token (p) - 1;
2164 else if (p[1] != '\0')
2166 #if defined(__MSDOS__) || defined(WINDOWS32)
2167 /* Only remove backslashes before characters special
2168 to Unixy shells. All other backslashes are copied
2169 verbatim, since they are probably DOS-style
2170 directory separators. This still leaves a small
2171 window for problems, but at least it should work
2172 for the vast majority of naive users. */
2174 #ifdef __MSDOS__
2175 /* A dot is only special as part of the "..."
2176 wildcard. */
2177 if (strneq (p + 1, ".\\.\\.", 5))
2179 *ap++ = '.';
2180 *ap++ = '.';
2181 p += 4;
2183 else
2184 #endif
2185 if (p[1] != '\\' && p[1] != '\'' && !isspace (p[1])
2186 && (index (sh_chars_sh, p[1]) == 0))
2187 /* back up one notch, to copy the backslash */
2188 --p;
2190 #endif /* __MSDOS__ || WINDOWS32 */
2191 /* Copy and skip the following char. */
2192 *ap++ = *++p;
2194 break;
2196 case '\'':
2197 case '"':
2198 instring = *p;
2199 break;
2201 case '\n':
2202 if (restp != NULL)
2204 /* End of the command line. */
2205 *restp = p;
2206 goto end_of_line;
2208 else
2209 /* Newlines are not special. */
2210 *ap++ = '\n';
2211 break;
2213 case ' ':
2214 case '\t':
2215 end_of_arg:
2216 /* We have the end of an argument.
2217 Terminate the text of the argument. */
2218 *ap++ = '\0';
2219 new_argv[++i] = ap;
2220 last_argument_was_empty = 0;
2222 /* Update SEEN_NONEQUALS, which tells us if every word
2223 heretofore has contained an `='. */
2224 seen_nonequals |= ! word_has_equals;
2225 if (word_has_equals && ! seen_nonequals)
2226 /* An `=' in a word before the first
2227 word without one is magical. */
2228 goto slow;
2229 word_has_equals = 0; /* Prepare for the next word. */
2231 /* If this argument is the command name,
2232 see if it is a built-in shell command.
2233 If so, have the shell handle it. */
2234 if (i == 1)
2236 register int j;
2237 for (j = 0; sh_cmds[j] != 0; ++j)
2238 if (streq (sh_cmds[j], new_argv[0]))
2239 goto slow;
2242 /* Ignore multiple whitespace chars. */
2243 p = next_token (p);
2244 /* Next iteration should examine the first nonwhite char. */
2245 --p;
2246 break;
2248 default:
2249 *ap++ = *p;
2250 break;
2253 end_of_line:
2255 if (instring)
2256 /* Let the shell deal with an unterminated quote. */
2257 goto slow;
2259 /* Terminate the last argument and the argument list. */
2261 *ap = '\0';
2262 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2263 ++i;
2264 new_argv[i] = 0;
2266 if (i == 1)
2268 register int j;
2269 for (j = 0; sh_cmds[j] != 0; ++j)
2270 if (streq (sh_cmds[j], new_argv[0]))
2271 goto slow;
2274 if (new_argv[0] == 0)
2275 /* Line was empty. */
2276 return 0;
2277 else
2278 return new_argv;
2280 slow:;
2281 /* We must use the shell. */
2283 if (new_argv != 0)
2285 /* Free the old argument list we were working on. */
2286 free (new_argv[0]);
2287 free ((void *)new_argv);
2290 #ifdef __MSDOS__
2291 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2292 #endif
2294 #ifdef _AMIGA
2296 char *ptr;
2297 char *buffer;
2298 char *dptr;
2300 buffer = (char *)xmalloc (strlen (line)+1);
2302 ptr = line;
2303 for (dptr=buffer; *ptr; )
2305 if (*ptr == '\\' && ptr[1] == '\n')
2306 ptr += 2;
2307 else if (*ptr == '@') /* Kludge: multiline commands */
2309 ptr += 2;
2310 *dptr++ = '\n';
2312 else
2313 *dptr++ = *ptr++;
2315 *dptr = 0;
2317 new_argv = (char **) xmalloc(2 * sizeof(char *));
2318 new_argv[0] = buffer;
2319 new_argv[1] = 0;
2321 #else /* Not Amiga */
2322 #ifdef WINDOWS32
2324 * Not eating this whitespace caused things like
2326 * sh -c "\n"
2328 * which gave the shell fits. I think we have to eat
2329 * whitespace here, but this code should be considered
2330 * suspicious if things start failing....
2333 /* Make sure not to bother processing an empty line. */
2334 while (isspace (*line))
2335 ++line;
2336 if (*line == '\0')
2337 return 0;
2338 #endif /* WINDOWS32 */
2340 /* SHELL may be a multi-word command. Construct a command line
2341 "SHELL -c LINE", with all special chars in LINE escaped.
2342 Then recurse, expanding this command line to get the final
2343 argument list. */
2345 unsigned int shell_len = strlen (shell);
2346 static char minus_c[] = " -c ";
2347 unsigned int line_len = strlen (line);
2349 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2350 + (line_len * 2) + 1);
2351 char* command_ptr = NULL; /* used for batch_mode_shell mode */
2353 ap = new_line;
2354 bcopy (shell, ap, shell_len);
2355 ap += shell_len;
2356 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2357 ap += sizeof (minus_c) - 1;
2358 command_ptr = ap;
2359 for (p = line; *p != '\0'; ++p)
2361 if (restp != NULL && *p == '\n')
2363 *restp = p;
2364 break;
2366 else if (*p == '\\' && p[1] == '\n')
2368 /* Eat the backslash, the newline, and following whitespace,
2369 replacing it all with a single space (which is escaped
2370 from the shell). */
2371 p += 2;
2373 /* If there is a tab after a backslash-newline,
2374 remove it from the source line which will be echoed,
2375 since it was most likely used to line
2376 up the continued line with the previous one. */
2377 if (*p == '\t')
2378 bcopy (p + 1, p, strlen (p));
2380 p = next_token (p);
2381 --p;
2382 if (unixy_shell && !batch_mode_shell)
2383 *ap++ = '\\';
2384 *ap++ = ' ';
2385 continue;
2388 /* DOS shells don't know about backslash-escaping. */
2389 if (unixy_shell && !batch_mode_shell &&
2390 (*p == '\\' || *p == '\'' || *p == '"'
2391 || isspace (*p)
2392 || index (sh_chars, *p) != 0))
2393 *ap++ = '\\';
2394 #ifdef __MSDOS__
2395 else if (unixy_shell && strneq (p, "...", 3))
2397 /* The case of `...' wildcard again. */
2398 strcpy (ap, "\\.\\.\\");
2399 ap += 5;
2400 p += 2;
2402 #endif
2403 *ap++ = *p;
2405 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2406 /* Line was empty. */
2407 return 0;
2408 *ap = '\0';
2410 #ifdef WINDOWS32
2411 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2412 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2413 cases, run commands via a script file. */
2414 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2415 FILE* batch = NULL;
2416 int id = GetCurrentProcessId();
2417 PATH_VAR(fbuf);
2418 char* fname = NULL;
2420 /* create a file name */
2421 sprintf(fbuf, "make%d", id);
2422 fname = tempnam(".", fbuf);
2424 /* create batch file name */
2425 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
2426 strcpy(*batch_filename_ptr, fname);
2428 /* make sure path name is in DOS backslash format */
2429 if (!unixy_shell) {
2430 fname = *batch_filename_ptr;
2431 for (i = 0; fname[i] != '\0'; ++i)
2432 if (fname[i] == '/')
2433 fname[i] = '\\';
2434 strcat(*batch_filename_ptr, ".bat");
2435 } else {
2436 strcat(*batch_filename_ptr, ".sh");
2439 if (debug_flag)
2440 printf(_("Creating temporary batch file %s\n"), *batch_filename_ptr);
2442 /* create batch file to execute command */
2443 batch = fopen (*batch_filename_ptr, "w");
2444 if (!unixy_shell)
2445 fputs ("@echo off\n", batch);
2446 fputs (command_ptr, batch);
2447 fputc ('\n', batch);
2448 fclose (batch);
2450 /* create argv */
2451 new_argv = (char **) xmalloc(3 * sizeof(char *));
2452 if (unixy_shell) {
2453 new_argv[0] = xstrdup (shell);
2454 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2455 } else {
2456 new_argv[0] = xstrdup (*batch_filename_ptr);
2457 new_argv[1] = NULL;
2459 new_argv[2] = NULL;
2460 } else
2461 #endif /* WINDOWS32 */
2462 if (unixy_shell)
2463 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2464 (char *) 0, (char *) 0,
2465 (char *) 0);
2466 #ifdef __MSDOS__
2467 else
2469 /* With MSDOS shells, we must construct the command line here
2470 instead of recursively calling ourselves, because we
2471 cannot backslash-escape the special characters (see above). */
2472 new_argv = (char **) xmalloc (sizeof (char *));
2473 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2474 new_argv[0] = xmalloc (line_len + 1);
2475 strncpy (new_argv[0],
2476 new_line + shell_len + sizeof (minus_c) - 1, line_len);
2477 new_argv[0][line_len] = '\0';
2479 #else
2480 else
2481 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2482 __FILE__, __LINE__);
2483 #endif
2485 #endif /* ! AMIGA */
2487 return new_argv;
2490 /* Figure out the argument list necessary to run LINE as a command. Try to
2491 avoid using a shell. This routine handles only ' quoting, and " quoting
2492 when no backslash, $ or ` characters are seen in the quotes. Starting
2493 quotes may be escaped with a backslash. If any of the characters in
2494 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2495 is the first word of a line, the shell is used.
2497 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2498 If *RESTP is NULL, newlines will be ignored.
2500 FILE is the target whose commands these are. It is used for
2501 variable expansion for $(SHELL) and $(IFS). */
2503 char **
2504 construct_command_argv (line, restp, file, batch_filename_ptr)
2505 char *line, **restp;
2506 struct file *file;
2507 char** batch_filename_ptr;
2509 char *shell, *ifs;
2510 char **argv;
2513 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2514 int save = warn_undefined_variables_flag;
2515 warn_undefined_variables_flag = 0;
2517 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
2518 #ifdef WINDOWS32
2520 * Convert to forward slashes so that construct_command_argv_internal()
2521 * is not confused.
2523 if (shell) {
2524 char *p = w32ify(shell, 0);
2525 strcpy(shell, p);
2527 #endif
2528 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
2530 warn_undefined_variables_flag = save;
2533 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
2535 free (shell);
2536 free (ifs);
2538 return argv;
2540 #endif /* !VMS */
2542 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2544 dup2 (old, new)
2545 int old, new;
2547 int fd;
2549 (void) close (new);
2550 fd = dup (old);
2551 if (fd != new)
2553 (void) close (fd);
2554 errno = EMFILE;
2555 return -1;
2558 return fd;
2560 #endif /* !HAPE_DUP2 && !_AMIGA */