* Change $(call...) to not expand arguments by default.
[make.git] / job.c
blobc920b9f023bda200294d3fd01711872e0cc540c1
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 <assert.h>
22 #include "make.h"
23 #include "job.h"
24 #include "debug.h"
25 #include "filedef.h"
26 #include "commands.h"
27 #include "variable.h"
28 #include "debug.h"
30 #include <string.h>
32 /* Default shell to use. */
33 #ifdef WINDOWS32
34 char *default_shell = "sh.exe";
35 int no_default_sh_exe = 1;
36 int batch_mode_shell = 1;
37 #else /* WINDOWS32 */
38 # ifdef _AMIGA
39 char default_shell[] = "";
40 extern int MyExecute (char **);
41 # else /* _AMIGA */
42 # ifdef __MSDOS__
43 /* The default shell is a pointer so we can change it if Makefile
44 says so. It is without an explicit path so we get a chance
45 to search the $PATH for it (since MSDOS doesn't have standard
46 directories we could trust). */
47 char *default_shell = "command.com";
48 # else /* __MSDOS__ */
49 char default_shell[] = "/bin/sh";
50 # endif /* __MSDOS__ */
51 int batch_mode_shell = 0;
52 # endif /* _AMIGA */
53 #endif /* WINDOWS32 */
55 #ifdef __MSDOS__
56 # include <process.h>
57 static int execute_by_shell;
58 static int dos_pid = 123;
59 int dos_status;
60 int dos_command_running;
61 #endif /* __MSDOS__ */
63 #ifdef _AMIGA
64 # include <proto/dos.h>
65 static int amiga_pid = 123;
66 static int amiga_status;
67 static char amiga_bname[32];
68 static int amiga_batch_file;
69 #endif /* Amiga. */
71 #ifdef VMS
72 # include <time.h>
73 # include <processes.h>
74 # include <starlet.h>
75 # include <lib$routines.h>
76 #endif
78 #ifdef WINDOWS32
79 # include <windows.h>
80 # include <io.h>
81 # include <process.h>
82 # include "sub_proc.h"
83 # include "w32err.h"
84 # include "pathstuff.h"
85 #endif /* WINDOWS32 */
87 #ifdef HAVE_FCNTL_H
88 # include <fcntl.h>
89 #else
90 # include <sys/file.h>
91 #endif
93 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
94 # include <sys/wait.h>
95 #endif
97 #ifdef HAVE_WAITPID
98 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
99 #else /* Don't have waitpid. */
100 # ifdef HAVE_WAIT3
101 # ifndef wait3
102 extern int wait3 ();
103 # endif
104 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
105 # endif /* Have wait3. */
106 #endif /* Have waitpid. */
108 #if !defined (wait) && !defined (POSIX)
109 extern int wait ();
110 #endif
112 #ifndef HAVE_UNION_WAIT
114 # define WAIT_T int
116 # ifndef WTERMSIG
117 # define WTERMSIG(x) ((x) & 0x7f)
118 # endif
119 # ifndef WCOREDUMP
120 # define WCOREDUMP(x) ((x) & 0x80)
121 # endif
122 # ifndef WEXITSTATUS
123 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
124 # endif
125 # ifndef WIFSIGNALED
126 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
127 # endif
128 # ifndef WIFEXITED
129 # define WIFEXITED(x) (WTERMSIG (x) == 0)
130 # endif
132 #else /* Have `union wait'. */
134 # define WAIT_T union wait
135 # ifndef WTERMSIG
136 # define WTERMSIG(x) ((x).w_termsig)
137 # endif
138 # ifndef WCOREDUMP
139 # define WCOREDUMP(x) ((x).w_coredump)
140 # endif
141 # ifndef WEXITSTATUS
142 # define WEXITSTATUS(x) ((x).w_retcode)
143 # endif
144 # ifndef WIFSIGNALED
145 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
146 # endif
147 # ifndef WIFEXITED
148 # define WIFEXITED(x) (WTERMSIG(x) == 0)
149 # endif
151 #endif /* Don't have `union wait'. */
153 /* How to set close-on-exec for a file descriptor. */
155 #if !defined F_SETFD
156 # define CLOSE_ON_EXEC(_d)
157 #else
158 # ifndef FD_CLOEXEC
159 # define FD_CLOEXEC 1
160 # endif
161 # define CLOSE_ON_EXEC(_d) (void) fcntl ((_d), F_SETFD, FD_CLOEXEC)
162 #endif
164 #ifdef VMS
165 static int vms_jobsefnmask = 0;
166 #endif /* !VMS */
168 #ifndef HAVE_UNISTD_H
169 extern int dup2 ();
170 extern int execve ();
171 extern void _exit ();
172 # ifndef VMS
173 extern int geteuid ();
174 extern int getegid ();
175 extern int setgid ();
176 extern int getgid ();
177 # endif
178 #endif
180 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
182 extern int getloadavg PARAMS ((double loadavg[], int nelem));
183 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
184 int *is_remote, int *id_ptr, int *used_stdin));
185 extern int start_remote_job_p PARAMS ((int));
186 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
187 int *coredump_ptr, int block));
189 static void free_child PARAMS ((struct child *));
190 static void start_job_command PARAMS ((struct child *child));
191 static int load_too_high PARAMS ((void));
192 static int job_next_command PARAMS ((struct child *));
193 static int start_waiting_job PARAMS ((struct child *));
194 #ifdef VMS
195 static void vmsWaitForChildren PARAMS ((int *));
196 #endif
198 /* Chain of all live (or recently deceased) children. */
200 struct child *children = 0;
202 /* Number of children currently running. */
204 unsigned int job_slots_used = 0;
206 /* Nonzero if the `good' standard input is in use. */
208 static int good_stdin_used = 0;
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;
219 #ifdef WINDOWS32
221 * The macro which references this function is defined in make.h.
223 int w32_kill(int pid, int sig)
225 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
227 #endif /* WINDOWS32 */
230 /* Write an error message describing the exit status given in
231 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
232 Append "(ignored)" if IGNORED is nonzero. */
234 static void
235 child_error (target_name, exit_code, exit_sig, coredump, ignored)
236 char *target_name;
237 int exit_code, exit_sig, coredump;
238 int ignored;
240 if (ignored && silent_flag)
241 return;
243 #ifdef VMS
244 if (!(exit_code & 1))
245 error (NILF, _("*** [%s] Error 0x%x%s"), target_name, exit_code, ((ignored)? _(" (ignored)") : ""));
246 #else
247 if (exit_sig == 0)
248 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
249 _("*** [%s] Error %d"),
250 target_name, exit_code);
251 else
252 error (NILF, "*** [%s] %s%s",
253 target_name, strsignal (exit_sig),
254 coredump ? _(" (core dumped)") : "");
255 #endif /* VMS */
258 #ifdef VMS
259 /* Wait for nchildren children to terminate */
260 static void
261 vmsWaitForChildren(int *status)
263 while (1)
265 if (!vms_jobsefnmask)
267 *status = 0;
268 return;
271 *status = sys$wflor (32, vms_jobsefnmask);
273 return;
275 #endif
278 /* Handle a dead child. This handler may or may not ever be installed.
280 If we're using the jobserver feature, we need it. First, installing it
281 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
282 read FD to ensure we don't enter another blocking read without reaping all
283 the dead children. In this case we don't need the dead_children count.
285 If we don't have either waitpid or wait3, then make is unreliable, but we
286 use the dead_children count to reap children as best we can. */
288 static unsigned int dead_children = 0;
290 RETSIGTYPE
291 child_handler (sig)
292 int sig;
294 ++dead_children;
296 if (job_rfd >= 0)
298 close (job_rfd);
299 job_rfd = -1;
302 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
306 extern int shell_function_pid, shell_function_completed;
308 /* Reap all dead children, storing the returned status and the new command
309 state (`cs_finished') in the `file' member of the `struct child' for the
310 dead child, and removing the child from the chain. In addition, if BLOCK
311 nonzero, we block in this function until we've reaped at least one
312 complete child, waiting for it to die if necessary. If ERR is nonzero,
313 print an error message first. */
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 /* As long as:
331 We have at least one child outstanding OR a shell function in progress,
333 We're blocking for a complete child OR there are more children to reap
335 we'll keep reaping children. */
337 while ((children != 0 || shell_function_pid != 0) &&
338 (block || REAP_MORE))
340 int remote = 0;
341 register int pid;
342 int exit_code, exit_sig, coredump;
343 register struct child *lastc, *c;
344 int child_failed;
345 int any_remote, any_local;
347 if (err && block)
349 /* We might block for a while, so let the user know why. */
350 fflush (stdout);
351 error (NILF, _("*** Waiting for unfinished jobs...."));
354 /* We have one less dead child to reap. As noted in
355 child_handler() above, this count is completely unimportant for
356 all modern, POSIX-y systems that support wait3() or waitpid().
357 The rest of this comment below applies only to early, broken
358 pre-POSIX systems. We keep the count only because... it's there...
360 The test and decrement are not atomic; if it is compiled into:
361 register = dead_children - 1;
362 dead_children = register;
363 a SIGCHLD could come between the two instructions.
364 child_handler increments dead_children.
365 The second instruction here would lose that increment. But the
366 only effect of dead_children being wrong is that we might wait
367 longer than necessary to reap a child, and lose some parallelism;
368 and we might print the "Waiting for unfinished jobs" message above
369 when not necessary. */
371 if (dead_children > 0)
372 --dead_children;
374 any_remote = 0;
375 any_local = shell_function_pid != 0;
376 for (c = children; c != 0; c = c->next)
378 any_remote |= c->remote;
379 any_local |= ! c->remote;
380 DB (DB_JOBS, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
381 (unsigned long int) c, c->file->name,
382 (long) c->pid, c->remote ? _(" (remote)") : ""));
383 #ifdef VMS
384 break;
385 #endif
388 /* First, check for remote children. */
389 if (any_remote)
390 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
391 else
392 pid = 0;
394 if (pid > 0)
395 /* We got a remote child. */
396 remote = 1;
397 else if (pid < 0)
399 /* A remote status command failed miserably. Punt. */
400 remote_status_lose:
401 if (EINTR_SET)
402 continue;
404 pfatal_with_name ("remote_status");
406 else
408 /* No remote children. Check for local children. */
409 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
410 if (any_local)
412 local_wait:
413 #ifdef VMS
414 vmsWaitForChildren (&status);
415 pid = c->pid;
416 #else
417 #ifdef WAIT_NOHANG
418 if (!block)
419 pid = WAIT_NOHANG (&status);
420 else
421 #endif
422 pid = wait (&status);
423 #endif /* !VMS */
425 else
426 pid = 0;
428 if (pid < 0)
430 /* EINTR? Try again. */
431 if (EINTR_SET)
432 goto local_wait;
434 /* The wait*() failed miserably. Punt. */
435 pfatal_with_name ("wait");
437 else if (pid > 0)
439 /* We got a child exit; chop the status word up. */
440 exit_code = WEXITSTATUS (status);
441 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
442 coredump = WCOREDUMP (status);
444 else
446 /* No local children are dead. */
447 reap_more = 0;
449 if (!block || !any_remote)
450 break;
452 /* Now try a blocking wait for a remote child. */
453 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
454 if (pid < 0)
455 goto remote_status_lose;
456 else if (pid == 0)
457 /* No remote children either. Finally give up. */
458 break;
460 /* We got a remote child. */
461 remote = 1;
463 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
465 #ifdef __MSDOS__
466 /* Life is very different on MSDOS. */
467 pid = dos_pid - 1;
468 status = dos_status;
469 exit_code = WEXITSTATUS (status);
470 if (exit_code == 0xff)
471 exit_code = -1;
472 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
473 coredump = 0;
474 #endif /* __MSDOS__ */
475 #ifdef _AMIGA
476 /* Same on Amiga */
477 pid = amiga_pid - 1;
478 status = amiga_status;
479 exit_code = amiga_status;
480 exit_sig = 0;
481 coredump = 0;
482 #endif /* _AMIGA */
483 #ifdef WINDOWS32
485 HANDLE hPID;
486 int err;
488 /* wait for anything to finish */
489 if (hPID = process_wait_for_any()) {
491 /* was an error found on this process? */
492 err = process_last_err(hPID);
494 /* get exit data */
495 exit_code = process_exit_code(hPID);
497 if (err)
498 fprintf(stderr, "make (e=%d): %s",
499 exit_code, map_windows32_error_to_string(exit_code));
501 /* signal */
502 exit_sig = process_signal(hPID);
504 /* cleanup process */
505 process_cleanup(hPID);
507 coredump = 0;
509 pid = (int) hPID;
511 #endif /* WINDOWS32 */
514 /* Check if this is the child of the `shell' function. */
515 if (!remote && pid == shell_function_pid)
517 /* It is. Leave an indicator for the `shell' function. */
518 if (exit_sig == 0 && exit_code == 127)
519 shell_function_completed = -1;
520 else
521 shell_function_completed = 1;
522 break;
525 child_failed = exit_sig != 0 || exit_code != 0;
527 /* Search for a child matching the deceased one. */
528 lastc = 0;
529 for (c = children; c != 0; lastc = c, c = c->next)
530 if (c->remote == remote && c->pid == pid)
531 break;
533 if (c == 0)
534 /* An unknown child died.
535 Ignore it; it was inherited from our invoker. */
536 continue;
538 DB (DB_JOBS, (child_failed
539 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
540 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
541 (unsigned long int) c, (long) c->pid,
542 c->remote ? _(" (remote)") : ""));
544 if (c->sh_batch_file) {
545 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
546 c->sh_batch_file));
548 /* just try and remove, don't care if this fails */
549 remove (c->sh_batch_file);
551 /* all done with memory */
552 free (c->sh_batch_file);
553 c->sh_batch_file = NULL;
556 /* If this child had the good stdin, say it is now free. */
557 if (c->good_stdin)
558 good_stdin_used = 0;
560 if (child_failed && !c->noerror && !ignore_errors_flag)
562 /* The commands failed. Write an error message,
563 delete non-precious targets, and abort. */
564 static int delete_on_error = -1;
565 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
566 c->file->update_status = 2;
567 if (delete_on_error == -1)
569 struct file *f = lookup_file (".DELETE_ON_ERROR");
570 delete_on_error = f != 0 && f->is_target;
572 if (exit_sig != 0 || delete_on_error)
573 delete_child_targets (c);
575 else
577 if (child_failed)
579 /* The commands failed, but we don't care. */
580 child_error (c->file->name,
581 exit_code, exit_sig, coredump, 1);
582 child_failed = 0;
585 /* If there are more commands to run, try to start them. */
586 if (job_next_command (c))
588 if (handling_fatal_signal)
590 /* Never start new commands while we are dying.
591 Since there are more commands that wanted to be run,
592 the target was not completely remade. So we treat
593 this as if a command had failed. */
594 c->file->update_status = 2;
596 else
598 /* Check again whether to start remotely.
599 Whether or not we want to changes over time.
600 Also, start_remote_job may need state set up
601 by start_remote_job_p. */
602 c->remote = start_remote_job_p (0);
603 start_job_command (c);
604 /* Fatal signals are left blocked in case we were
605 about to put that child on the chain. But it is
606 already there, so it is safe for a fatal signal to
607 arrive now; it will clean up this child's targets. */
608 unblock_sigs ();
609 if (c->file->command_state == cs_running)
610 /* We successfully started the new command.
611 Loop to reap more children. */
612 continue;
615 if (c->file->update_status != 0)
616 /* We failed to start the commands. */
617 delete_child_targets (c);
619 else
620 /* There are no more commands. We got through them all
621 without an unignored error. Now the target has been
622 successfully updated. */
623 c->file->update_status = 0;
626 /* When we get here, all the commands for C->file are finished
627 (or aborted) and C->file->update_status contains 0 or 2. But
628 C->file->command_state is still cs_running if all the commands
629 ran; notice_finish_file looks for cs_running to tell it that
630 it's interesting to check the file's modtime again now. */
632 if (! handling_fatal_signal)
633 /* Notice if the target of the commands has been changed.
634 This also propagates its values for command_state and
635 update_status to its also_make files. */
636 notice_finished_file (c->file);
638 DB (DB_JOBS, (_("Removing child 0x%08lx PID %ld %s from chain.\n"),
639 (unsigned long int) c, (long) c->pid,
640 c->remote ? _(" (remote)") : ""));
642 /* Block fatal signals while frobnicating the list, so that
643 children and job_slots_used are always consistent. Otherwise
644 a fatal signal arriving after the child is off the chain and
645 before job_slots_used is decremented would believe a child was
646 live and call reap_children again. */
647 block_sigs ();
649 /* There is now another slot open. */
650 if (job_slots_used > 0)
651 --job_slots_used;
653 /* Remove the child from the chain and free it. */
654 if (lastc == 0)
655 children = c->next;
656 else
657 lastc->next = c->next;
659 free_child (c);
661 unblock_sigs ();
663 /* If the job failed, and the -k flag was not given, die,
664 unless we are already in the process of dying. */
665 if (!err && child_failed && !keep_going_flag &&
666 /* fatal_error_signal will die with the right signal. */
667 !handling_fatal_signal)
668 die (2);
670 /* Only block for one child. */
671 block = 0;
674 return;
677 /* Free the storage allocated for CHILD. */
679 static void
680 free_child (child)
681 register struct child *child;
683 /* If this child is the only one it was our "free" job, so don't put a
684 token back for it. This child has already been removed from the list,
685 so if there any left this wasn't the last one. */
687 if (job_fds[1] >= 0 && children)
689 char token = '+';
691 /* Write a job token back to the pipe. */
693 while (write (job_fds[1], &token, 1) != 1)
694 if (!EINTR_SET)
695 pfatal_with_name (_("write jobserver"));
697 DB (DB_JOBS, (_("Released token for child 0x%08lx (%s).\n"),
698 (unsigned long int) child, child->file->name));
701 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
702 return;
704 if (child->command_lines != 0)
706 register unsigned int i;
707 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
708 free (child->command_lines[i]);
709 free ((char *) child->command_lines);
712 if (child->environment != 0)
714 register char **ep = child->environment;
715 while (*ep != 0)
716 free (*ep++);
717 free ((char *) child->environment);
720 free ((char *) child);
723 #ifdef POSIX
724 extern sigset_t fatal_signal_set;
725 #endif
727 void
728 block_sigs ()
730 #ifdef POSIX
731 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
732 #else
733 # ifdef HAVE_SIGSETMASK
734 (void) sigblock (fatal_signal_mask);
735 # endif
736 #endif
739 #ifdef POSIX
740 void
741 unblock_sigs ()
743 sigset_t empty;
744 sigemptyset (&empty);
745 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
747 #endif
749 /* Start a job to run the commands specified in CHILD.
750 CHILD is updated to reflect the commands and ID of the child process.
752 NOTE: On return fatal signals are blocked! The caller is responsible
753 for calling `unblock_sigs', once the new child is safely on the chain so
754 it can be cleaned up in the event of a fatal signal. */
756 static void
757 start_job_command (child)
758 register struct child *child;
760 #ifndef _AMIGA
761 static int bad_stdin = -1;
762 #endif
763 register char *p;
764 int flags;
765 #ifdef VMS
766 char *argv;
767 #else
768 char **argv;
769 #endif
771 /* If we have a completely empty commandset, stop now. */
772 if (!child->command_ptr)
773 goto next_command;
775 /* Combine the flags parsed for the line itself with
776 the flags specified globally for this target. */
777 flags = (child->file->command_flags
778 | child->file->cmds->lines_flags[child->command_line - 1]);
780 p = child->command_ptr;
781 child->noerror = flags & COMMANDS_NOERROR;
783 while (*p != '\0')
785 if (*p == '@')
786 flags |= COMMANDS_SILENT;
787 else if (*p == '+')
788 flags |= COMMANDS_RECURSE;
789 else if (*p == '-')
790 child->noerror = 1;
791 else if (!isblank (*p))
792 break;
793 ++p;
796 /* Update the file's command flags with any new ones we found. */
797 child->file->cmds->lines_flags[child->command_line - 1] |= flags;
799 /* If -q was given, just say that updating `failed'. The exit status of
800 1 tells the user that -q is saying `something to do'; the exit status
801 for a random error is 2. */
802 if (question_flag && !(flags & COMMANDS_RECURSE))
804 child->file->update_status = 1;
805 notice_finished_file (child->file);
806 return;
809 /* There may be some preceding whitespace left if there
810 was nothing but a backslash on the first line. */
811 p = next_token (p);
813 /* Figure out an argument list from this command line. */
816 char *end = 0;
817 #ifdef VMS
818 argv = p;
819 #else
820 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
821 #endif
822 if (end == NULL)
823 child->command_ptr = NULL;
824 else
826 *end++ = '\0';
827 child->command_ptr = end;
831 if (touch_flag && !(flags & COMMANDS_RECURSE))
833 /* Go on to the next command. It might be the recursive one.
834 We construct ARGV only to find the end of the command line. */
835 #ifndef VMS
836 free (argv[0]);
837 free ((char *) argv);
838 #endif
839 argv = 0;
842 if (argv == 0)
844 next_command:
845 #ifdef __MSDOS__
846 execute_by_shell = 0; /* in case construct_command_argv sets it */
847 #endif
848 /* This line has no commands. Go to the next. */
849 if (job_next_command (child))
850 start_job_command (child);
851 else
853 /* No more commands. Make sure we're "running"; we might not be if
854 (e.g.) all commands were skipped due to -n. */
855 set_command_state (child->file, cs_running);
856 child->file->update_status = 0;
857 notice_finished_file (child->file);
859 return;
862 /* Print out the command. If silent, we call `message' with null so it
863 can log the working directory before the command's own error messages
864 appear. */
866 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
867 ? "%s" : (char *) 0, p);
869 /* Optimize an empty command. People use this for timestamp rules,
870 so avoid forking a useless shell. */
872 #if !defined(VMS) && !defined(_AMIGA)
873 if (
874 #ifdef __MSDOS__
875 unixy_shell /* the test is complicated and we already did it */
876 #else
877 (argv[0] && !strcmp (argv[0], "/bin/sh"))
878 #endif
879 && (argv[1]
880 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
881 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
882 && argv[3] == NULL)
884 free (argv[0]);
885 free ((char *) argv);
886 goto next_command;
888 #endif /* !VMS && !_AMIGA */
890 /* Tell update_goal_chain that a command has been started on behalf of
891 this target. It is important that this happens here and not in
892 reap_children (where we used to do it), because reap_children might be
893 reaping children from a different target. We want this increment to
894 guaranteedly indicate that a command was started for the dependency
895 chain (i.e., update_file recursion chain) we are processing. */
897 ++commands_started;
899 /* If -n was given, recurse to get the next line in the sequence. */
901 if (just_print_flag && !(flags & COMMANDS_RECURSE))
903 #ifndef VMS
904 free (argv[0]);
905 free ((char *) argv);
906 #endif
907 goto next_command;
910 /* Flush the output streams so they won't have things written twice. */
912 fflush (stdout);
913 fflush (stderr);
915 #ifndef VMS
916 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
918 /* Set up a bad standard input that reads from a broken pipe. */
920 if (bad_stdin == -1)
922 /* Make a file descriptor that is the read end of a broken pipe.
923 This will be used for some children's standard inputs. */
924 int pd[2];
925 if (pipe (pd) == 0)
927 /* Close the write side. */
928 (void) close (pd[1]);
929 /* Save the read side. */
930 bad_stdin = pd[0];
932 /* Set the descriptor to close on exec, so it does not litter any
933 child's descriptor table. When it is dup2'd onto descriptor 0,
934 that descriptor will not close on exec. */
935 CLOSE_ON_EXEC (bad_stdin);
939 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
941 /* Decide whether to give this child the `good' standard input
942 (one that points to the terminal or whatever), or the `bad' one
943 that points to the read side of a broken pipe. */
945 child->good_stdin = !good_stdin_used;
946 if (child->good_stdin)
947 good_stdin_used = 1;
949 #endif /* !VMS */
951 child->deleted = 0;
953 #ifndef _AMIGA
954 /* Set up the environment for the child. */
955 if (child->environment == 0)
956 child->environment = target_environment (child->file);
957 #endif
959 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
961 #ifndef VMS
962 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
963 if (child->remote)
965 int is_remote, id, used_stdin;
966 if (start_remote_job (argv, child->environment,
967 child->good_stdin ? 0 : bad_stdin,
968 &is_remote, &id, &used_stdin))
969 /* Don't give up; remote execution may fail for various reasons. If
970 so, simply run the job locally. */
971 goto run_local;
972 else
974 if (child->good_stdin && !used_stdin)
976 child->good_stdin = 0;
977 good_stdin_used = 0;
979 child->remote = is_remote;
980 child->pid = id;
983 else
984 #endif /* !VMS */
986 /* Fork the child process. */
988 char **parent_environ;
990 run_local:
991 block_sigs ();
993 child->remote = 0;
995 #ifdef VMS
997 if (!child_execute_job (argv, child)) {
998 /* Fork failed! */
999 perror_with_name ("vfork", "");
1000 goto error;
1003 #else
1005 parent_environ = environ;
1006 child->pid = vfork ();
1007 environ = parent_environ; /* Restore value child may have clobbered. */
1008 if (child->pid == 0)
1010 /* We are the child side. */
1011 unblock_sigs ();
1013 /* If we aren't running a recursive command and we have a jobserver
1014 pipe, close it before exec'ing. */
1015 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1017 close (job_fds[0]);
1018 close (job_fds[1]);
1020 if (job_rfd >= 0)
1021 close (job_rfd);
1023 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1024 argv, child->environment);
1026 else if (child->pid < 0)
1028 /* Fork failed! */
1029 unblock_sigs ();
1030 perror_with_name ("vfork", "");
1031 goto error;
1033 #endif /* !VMS */
1036 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1037 #ifdef __MSDOS__
1039 int proc_return;
1041 block_sigs ();
1042 dos_status = 0;
1044 /* We call `system' to do the job of the SHELL, since stock DOS
1045 shell is too dumb. Our `system' knows how to handle long
1046 command lines even if pipes/redirection is needed; it will only
1047 call COMMAND.COM when its internal commands are used. */
1048 if (execute_by_shell)
1050 char *cmdline = argv[0];
1051 /* We don't have a way to pass environment to `system',
1052 so we need to save and restore ours, sigh... */
1053 char **parent_environ = environ;
1055 environ = child->environment;
1057 /* If we have a *real* shell, tell `system' to call
1058 it to do everything for us. */
1059 if (unixy_shell)
1061 /* A *real* shell on MSDOS may not support long
1062 command lines the DJGPP way, so we must use `system'. */
1063 cmdline = argv[2]; /* get past "shell -c" */
1066 dos_command_running = 1;
1067 proc_return = system (cmdline);
1068 environ = parent_environ;
1069 execute_by_shell = 0; /* for the next time */
1071 else
1073 dos_command_running = 1;
1074 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1077 /* Need to unblock signals before turning off
1078 dos_command_running, so that child's signals
1079 will be treated as such (see fatal_error_signal). */
1080 unblock_sigs ();
1081 dos_command_running = 0;
1083 /* If the child got a signal, dos_status has its
1084 high 8 bits set, so be careful not to alter them. */
1085 if (proc_return == -1)
1086 dos_status |= 0xff;
1087 else
1088 dos_status |= (proc_return & 0xff);
1089 ++dead_children;
1090 child->pid = dos_pid++;
1092 #endif /* __MSDOS__ */
1093 #ifdef _AMIGA
1094 amiga_status = MyExecute (argv);
1096 ++dead_children;
1097 child->pid = amiga_pid++;
1098 if (amiga_batch_file)
1100 amiga_batch_file = 0;
1101 DeleteFile (amiga_bname); /* Ignore errors. */
1103 #endif /* Amiga */
1104 #ifdef WINDOWS32
1106 HANDLE hPID;
1107 char* arg0;
1109 /* make UNC paths safe for CreateProcess -- backslash format */
1110 arg0 = argv[0];
1111 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1112 for ( ; arg0 && *arg0; arg0++)
1113 if (*arg0 == '/')
1114 *arg0 = '\\';
1116 /* make sure CreateProcess() has Path it needs */
1117 sync_Path_environment();
1119 hPID = process_easy(argv, child->environment);
1121 if (hPID != INVALID_HANDLE_VALUE)
1122 child->pid = (int) hPID;
1123 else {
1124 int i;
1125 unblock_sigs();
1126 fprintf(stderr,
1127 _("process_easy() failed failed to launch process (e=%d)\n"),
1128 process_last_err(hPID));
1129 for (i = 0; argv[i]; i++)
1130 fprintf(stderr, "%s ", argv[i]);
1131 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1134 #endif /* WINDOWS32 */
1135 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1137 /* We are the parent side. Set the state to
1138 say the commands are running and return. */
1140 set_command_state (child->file, cs_running);
1142 /* Free the storage used by the child's argument list. */
1143 #ifndef VMS
1144 free (argv[0]);
1145 free ((char *) argv);
1146 #endif
1148 return;
1150 error:
1151 child->file->update_status = 2;
1152 notice_finished_file (child->file);
1153 return;
1156 /* Try to start a child running.
1157 Returns nonzero if the child was started (and maybe finished), or zero if
1158 the load was too high and the child was put on the `waiting_jobs' chain. */
1160 static int
1161 start_waiting_job (c)
1162 struct child *c;
1164 struct file *f = c->file;
1166 /* If we can start a job remotely, we always want to, and don't care about
1167 the local load average. We record that the job should be started
1168 remotely in C->remote for start_job_command to test. */
1170 c->remote = start_remote_job_p (1);
1172 /* If we are running at least one job already and the load average
1173 is too high, make this one wait. */
1174 if (!c->remote && job_slots_used > 0 && load_too_high ())
1176 /* Put this child on the chain of children waiting for the load average
1177 to go down. */
1178 set_command_state (f, cs_running);
1179 c->next = waiting_jobs;
1180 waiting_jobs = c;
1181 return 0;
1184 /* Start the first command; reap_children will run later command lines. */
1185 start_job_command (c);
1187 switch (f->command_state)
1189 case cs_running:
1190 c->next = children;
1191 DB (DB_JOBS, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1192 (unsigned long int) c, c->file->name,
1193 (long) c->pid, c->remote ? _(" (remote)") : ""));
1194 children = c;
1195 /* One more job slot is in use. */
1196 ++job_slots_used;
1197 unblock_sigs ();
1198 break;
1200 case cs_not_started:
1201 /* All the command lines turned out to be empty. */
1202 f->update_status = 0;
1203 /* FALLTHROUGH */
1205 case cs_finished:
1206 notice_finished_file (f);
1207 free_child (c);
1208 break;
1210 default:
1211 assert (f->command_state == cs_finished);
1212 break;
1215 return 1;
1218 /* Create a `struct child' for FILE and start its commands running. */
1220 void
1221 new_job (file)
1222 register struct file *file;
1224 register struct commands *cmds = file->cmds;
1225 register struct child *c;
1226 char **lines;
1227 register unsigned int i;
1229 /* Let any previously decided-upon jobs that are waiting
1230 for the load to go down start before this new one. */
1231 start_waiting_jobs ();
1233 /* Reap any children that might have finished recently. */
1234 reap_children (0, 0);
1236 /* Chop the commands up into lines if they aren't already. */
1237 chop_commands (cmds);
1239 /* Expand the command lines and store the results in LINES. */
1240 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1241 for (i = 0; i < cmds->ncommand_lines; ++i)
1243 /* Collapse backslash-newline combinations that are inside variable
1244 or function references. These are left alone by the parser so
1245 that they will appear in the echoing of commands (where they look
1246 nice); and collapsed by construct_command_argv when it tokenizes.
1247 But letting them survive inside function invocations loses because
1248 we don't want the functions to see them as part of the text. */
1250 char *in, *out, *ref;
1252 /* IN points to where in the line we are scanning.
1253 OUT points to where in the line we are writing.
1254 When we collapse a backslash-newline combination,
1255 IN gets ahead of OUT. */
1257 in = out = cmds->command_lines[i];
1258 while ((ref = strchr (in, '$')) != 0)
1260 ++ref; /* Move past the $. */
1262 if (out != in)
1263 /* Copy the text between the end of the last chunk
1264 we processed (where IN points) and the new chunk
1265 we are about to process (where REF points). */
1266 bcopy (in, out, ref - in);
1268 /* Move both pointers past the boring stuff. */
1269 out += ref - in;
1270 in = ref;
1272 if (*ref == '(' || *ref == '{')
1274 char openparen = *ref;
1275 char closeparen = openparen == '(' ? ')' : '}';
1276 int count;
1277 char *p;
1279 *out++ = *in++; /* Copy OPENPAREN. */
1280 /* IN now points past the opening paren or brace.
1281 Count parens or braces until it is matched. */
1282 count = 0;
1283 while (*in != '\0')
1285 if (*in == closeparen && --count < 0)
1286 break;
1287 else if (*in == '\\' && in[1] == '\n')
1289 /* We have found a backslash-newline inside a
1290 variable or function reference. Eat it and
1291 any following whitespace. */
1293 int quoted = 0;
1294 for (p = in - 1; p > ref && *p == '\\'; --p)
1295 quoted = !quoted;
1297 if (quoted)
1298 /* There were two or more backslashes, so this is
1299 not really a continuation line. We don't collapse
1300 the quoting backslashes here as is done in
1301 collapse_continuations, because the line will
1302 be collapsed again after expansion. */
1303 *out++ = *in++;
1304 else
1306 /* Skip the backslash, newline and
1307 any following whitespace. */
1308 in = next_token (in + 2);
1310 /* Discard any preceding whitespace that has
1311 already been written to the output. */
1312 while (out > ref && isblank (out[-1]))
1313 --out;
1315 /* Replace it all with a single space. */
1316 *out++ = ' ';
1319 else
1321 if (*in == openparen)
1322 ++count;
1324 *out++ = *in++;
1330 /* There are no more references in this line to worry about.
1331 Copy the remaining uninteresting text to the output. */
1332 if (out != in)
1333 strcpy (out, in);
1335 /* Finally, expand the line. */
1336 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1337 file);
1340 /* Start the command sequence, record it in a new
1341 `struct child', and add that to the chain. */
1343 c = (struct child *) xmalloc (sizeof (struct child));
1344 bzero ((char *)c, sizeof (struct child));
1345 c->file = file;
1346 c->command_lines = lines;
1347 c->sh_batch_file = NULL;
1349 /* Fetch the first command line to be run. */
1350 job_next_command (c);
1352 /* Wait for a job slot to be freed up. If we allow an infinite number
1353 don't bother; also job_slots will == 0 if we're using the jobserver. */
1355 if (job_slots != 0)
1356 while (job_slots_used == job_slots)
1357 reap_children (1, 0);
1359 #ifdef MAKE_JOBSERVER
1360 /* If we are controlling multiple jobs make sure we have a token before
1361 starting the child. */
1363 /* This can be inefficient. There's a decent chance that this job won't
1364 actually have to run any subprocesses: the command script may be empty
1365 or otherwise optimized away. It would be nice if we could defer
1366 obtaining a token until just before we need it, in start_job_command.
1367 To do that we'd need to keep track of whether we'd already obtained a
1368 token (since start_job_command is called for each line of the job, not
1369 just once). Also more thought needs to go into the entire algorithm;
1370 this is where the old parallel job code waits, so... */
1372 else if (job_fds[0] >= 0)
1373 while (1)
1375 char token;
1377 /* If we don't already have a job started, use our "free" token. */
1378 if (!children)
1379 break;
1381 /* Read a token. As long as there's no token available we'll block.
1382 If we get a SIGCHLD we'll return with EINTR. If one happened
1383 before we got here we'll return immediately with EBADF because
1384 the signal handler closes the dup'd file descriptor. */
1386 if (read (job_rfd, &token, 1) == 1)
1388 DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1389 (unsigned long int) c, c->file->name));
1390 break;
1393 if (errno != EINTR && errno != EBADF)
1394 pfatal_with_name (_("read jobs pipe"));
1396 /* Re-dup the read side of the pipe, so the signal handler can
1397 notify us if we miss a child. */
1398 if (job_rfd < 0)
1399 job_rfd = dup (job_fds[0]);
1401 /* Something's done. We don't want to block for a whole child,
1402 just reap whatever's there. */
1403 reap_children (0, 0);
1405 #endif
1407 /* The job is now primed. Start it running.
1408 (This will notice if there are in fact no commands.) */
1409 (void) start_waiting_job (c);
1411 if (job_slots == 1 || not_parallel)
1412 /* Since there is only one job slot, make things run linearly.
1413 Wait for the child to die, setting the state to `cs_finished'. */
1414 while (file->command_state == cs_running)
1415 reap_children (1, 0);
1417 return;
1420 /* Move CHILD's pointers to the next command for it to execute.
1421 Returns nonzero if there is another command. */
1423 static int
1424 job_next_command (child)
1425 struct child *child;
1427 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1429 /* There are no more lines in the expansion of this line. */
1430 if (child->command_line == child->file->cmds->ncommand_lines)
1432 /* There are no more lines to be expanded. */
1433 child->command_ptr = 0;
1434 return 0;
1436 else
1437 /* Get the next line to run. */
1438 child->command_ptr = child->command_lines[child->command_line++];
1440 return 1;
1443 static int
1444 load_too_high ()
1446 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1447 return 1;
1448 #else
1449 double load;
1451 if (max_load_average < 0)
1452 return 0;
1454 make_access ();
1455 if (getloadavg (&load, 1) != 1)
1457 static int lossage = -1;
1458 /* Complain only once for the same error. */
1459 if (lossage == -1 || errno != lossage)
1461 if (errno == 0)
1462 /* An errno value of zero means getloadavg is just unsupported. */
1463 error (NILF, _("cannot enforce load limits on this operating system"));
1464 else
1465 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1467 lossage = errno;
1468 load = 0;
1470 user_access ();
1472 return load >= max_load_average;
1473 #endif
1476 /* Start jobs that are waiting for the load to be lower. */
1478 void
1479 start_waiting_jobs ()
1481 struct child *job;
1483 if (waiting_jobs == 0)
1484 return;
1488 /* Check for recently deceased descendants. */
1489 reap_children (0, 0);
1491 /* Take a job off the waiting list. */
1492 job = waiting_jobs;
1493 waiting_jobs = job->next;
1495 /* Try to start that job. We break out of the loop as soon
1496 as start_waiting_job puts one back on the waiting list. */
1498 while (start_waiting_job (job) && waiting_jobs != 0);
1500 return;
1503 #ifndef WINDOWS32
1504 #ifdef VMS
1505 #include <descrip.h>
1506 #include <clidef.h>
1508 /* This is called as an AST when a child process dies (it won't get
1509 interrupted by anything except a higher level AST).
1511 int vmsHandleChildTerm(struct child *child)
1513 int status;
1514 register struct child *lastc, *c;
1515 int child_failed;
1517 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1519 lib$free_ef(&child->efn);
1521 (void) sigblock (fatal_signal_mask);
1523 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1525 /* Search for a child matching the deceased one. */
1526 lastc = 0;
1527 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1528 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1529 #else
1530 c = child;
1531 #endif
1533 if (child_failed && !c->noerror && !ignore_errors_flag)
1535 /* The commands failed. Write an error message,
1536 delete non-precious targets, and abort. */
1537 child_error (c->file->name, c->cstatus, 0, 0, 0);
1538 c->file->update_status = 1;
1539 delete_child_targets (c);
1541 else
1543 if (child_failed)
1545 /* The commands failed, but we don't care. */
1546 child_error (c->file->name, c->cstatus, 0, 0, 1);
1547 child_failed = 0;
1550 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1551 /* If there are more commands to run, try to start them. */
1552 start_job (c);
1554 switch (c->file->command_state)
1556 case cs_running:
1557 /* Successfully started. */
1558 break;
1560 case cs_finished:
1561 if (c->file->update_status != 0) {
1562 /* We failed to start the commands. */
1563 delete_child_targets (c);
1565 break;
1567 default:
1568 error (NILF, _("internal error: `%s' command_state"), c->file->name);
1569 abort ();
1570 break;
1572 #endif /* RECURSIVEJOBS */
1575 /* Set the state flag to say the commands have finished. */
1576 c->file->command_state = cs_finished;
1577 notice_finished_file (c->file);
1579 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1580 /* Remove the child from the chain and free it. */
1581 if (lastc == 0)
1582 children = c->next;
1583 else
1584 lastc->next = c->next;
1585 free_child (c);
1586 #endif /* RECURSIVEJOBS */
1588 /* There is now another slot open. */
1589 if (job_slots_used > 0)
1590 --job_slots_used;
1592 /* If the job failed, and the -k flag was not given, die. */
1593 if (child_failed && !keep_going_flag)
1594 die (EXIT_FAILURE);
1596 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1598 return 1;
1601 /* VMS:
1602 Spawn a process executing the command in ARGV and return its pid. */
1604 #define MAXCMDLEN 200
1607 child_execute_job (argv, child)
1608 char *argv;
1609 struct child *child;
1611 int i;
1612 static struct dsc$descriptor_s cmddsc;
1613 #ifndef DONTWAITFORCHILD
1614 int spflags = 0;
1615 #else
1616 int spflags = CLI$M_NOWAIT;
1617 #endif
1618 int status;
1619 char cmd[4096],*p,*c;
1620 char comname[50];
1622 /* Remove backslashes */
1623 for (p = argv, c = cmd; *p; p++,c++)
1625 if (*p == '\\') p++;
1626 *c = *p;
1628 *c = *p;
1630 /* Check for maximum DCL length and create *.com file if neccesary.
1631 Also create a .com file if the command is more than one line long. */
1633 comname[0] = '\0';
1635 if (strlen (cmd) > MAXCMDLEN || strchr (cmd, '\n'))
1637 FILE *outfile;
1638 char tmp;
1640 strcpy (comname, "sys$scratch:CMDXXXXXX.COM");
1641 (void) mktemp (comname);
1643 outfile = fopen (comname, "w");
1644 if (outfile == 0)
1645 pfatal_with_name (comname);
1647 fprintf (outfile, "$ ");
1648 c = cmd;
1650 while (c)
1652 p = strchr (c, ',');
1653 if ((p == NULL) || (p-c > MAXCMDLEN))
1654 p = strchr (c, ' ');
1655 if (p != NULL)
1657 p++;
1658 tmp = *p;
1659 *p = '\0';
1661 else
1662 tmp = '\0';
1663 fprintf (outfile, "%s%s\n", c, (tmp == '\0')?"":" -");
1664 if (p != NULL)
1665 *p = tmp;
1666 c = p;
1669 fclose (outfile);
1671 sprintf (cmd, "$ @%s", comname);
1673 DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
1676 cmddsc.dsc$w_length = strlen(cmd);
1677 cmddsc.dsc$a_pointer = cmd;
1678 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
1679 cmddsc.dsc$b_class = DSC$K_CLASS_S;
1681 child->efn = 0;
1682 while (child->efn < 32 || child->efn > 63)
1684 status = lib$get_ef(&child->efn);
1685 if (!(status & 1))
1686 return 0;
1689 sys$clref(child->efn);
1691 vms_jobsefnmask |= (1 << (child->efn - 32));
1693 #ifndef DONTWAITFORCHILD
1694 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1695 &child->efn,0,0);
1696 vmsHandleChildTerm(child);
1697 #else
1698 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1699 &child->efn,vmsHandleChildTerm,child);
1700 #endif
1702 if (!(status & 1))
1704 printf(_("Error spawning, %d\n"),status);
1705 fflush(stdout);
1708 unlink (comname);
1710 return (status & 1);
1713 #else /* !VMS */
1715 #if !defined (_AMIGA) && !defined (__MSDOS__)
1716 /* UNIX:
1717 Replace the current process with one executing the command in ARGV.
1718 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1719 the environment of the new program. This function does not return. */
1721 void
1722 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1723 int stdin_fd, stdout_fd;
1724 char **argv, **envp;
1726 if (stdin_fd != 0)
1727 (void) dup2 (stdin_fd, 0);
1728 if (stdout_fd != 1)
1729 (void) dup2 (stdout_fd, 1);
1730 if (stdin_fd != 0)
1731 (void) close (stdin_fd);
1732 if (stdout_fd != 1)
1733 (void) close (stdout_fd);
1735 /* Run the command. */
1736 exec_command (argv, envp);
1738 #endif /* !AMIGA && !__MSDOS__ */
1739 #endif /* !VMS */
1740 #endif /* !WINDOWS32 */
1742 #ifndef _AMIGA
1743 /* Replace the current process with one running the command in ARGV,
1744 with environment ENVP. This function does not return. */
1746 void
1747 exec_command (argv, envp)
1748 char **argv, **envp;
1750 #ifdef VMS
1751 /* Run the program. */
1752 execve (argv[0], argv, envp);
1753 perror_with_name ("execve: ", argv[0]);
1754 _exit (EXIT_FAILURE);
1755 #else
1756 #ifdef WINDOWS32
1757 HANDLE hPID;
1758 HANDLE hWaitPID;
1759 int err = 0;
1760 int exit_code = EXIT_FAILURE;
1762 /* make sure CreateProcess() has Path it needs */
1763 sync_Path_environment();
1765 /* launch command */
1766 hPID = process_easy(argv, envp);
1768 /* make sure launch ok */
1769 if (hPID == INVALID_HANDLE_VALUE)
1771 int i;
1772 fprintf(stderr,
1773 _("process_easy() failed failed to launch process (e=%d)\n"),
1774 process_last_err(hPID));
1775 for (i = 0; argv[i]; i++)
1776 fprintf(stderr, "%s ", argv[i]);
1777 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1778 exit(EXIT_FAILURE);
1781 /* wait and reap last child */
1782 while (hWaitPID = process_wait_for_any())
1784 /* was an error found on this process? */
1785 err = process_last_err(hWaitPID);
1787 /* get exit data */
1788 exit_code = process_exit_code(hWaitPID);
1790 if (err)
1791 fprintf(stderr, "make (e=%d, rc=%d): %s",
1792 err, exit_code, map_windows32_error_to_string(err));
1794 /* cleanup process */
1795 process_cleanup(hWaitPID);
1797 /* expect to find only last pid, warn about other pids reaped */
1798 if (hWaitPID == hPID)
1799 break;
1800 else
1801 fprintf(stderr,
1802 _("make reaped child pid %d, still waiting for pid %d\n"),
1803 hWaitPID, hPID);
1806 /* return child's exit code as our exit code */
1807 exit(exit_code);
1809 #else /* !WINDOWS32 */
1811 /* Be the user, permanently. */
1812 child_access ();
1814 /* Run the program. */
1815 environ = envp;
1816 execvp (argv[0], argv);
1818 switch (errno)
1820 case ENOENT:
1821 error (NILF, _("%s: Command not found"), argv[0]);
1822 break;
1823 case ENOEXEC:
1825 /* The file is not executable. Try it as a shell script. */
1826 extern char *getenv ();
1827 char *shell;
1828 char **new_argv;
1829 int argc;
1831 shell = getenv ("SHELL");
1832 if (shell == 0)
1833 shell = default_shell;
1835 argc = 1;
1836 while (argv[argc] != 0)
1837 ++argc;
1839 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1840 new_argv[0] = shell;
1841 new_argv[1] = argv[0];
1842 while (argc > 0)
1844 new_argv[1 + argc] = argv[argc];
1845 --argc;
1848 execvp (shell, new_argv);
1849 if (errno == ENOENT)
1850 error (NILF, _("%s: Shell program not found"), shell);
1851 else
1852 perror_with_name ("execvp: ", shell);
1853 break;
1856 default:
1857 perror_with_name ("execvp: ", argv[0]);
1858 break;
1861 _exit (127);
1862 #endif /* !WINDOWS32 */
1863 #endif /* !VMS */
1865 #else /* On Amiga */
1866 void exec_command (argv)
1867 char **argv;
1869 MyExecute (argv);
1872 void clean_tmp (void)
1874 DeleteFile (amiga_bname);
1877 #endif /* On Amiga */
1879 #ifndef VMS
1880 /* Figure out the argument list necessary to run LINE as a command. Try to
1881 avoid using a shell. This routine handles only ' quoting, and " quoting
1882 when no backslash, $ or ` characters are seen in the quotes. Starting
1883 quotes may be escaped with a backslash. If any of the characters in
1884 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1885 is the first word of a line, the shell is used.
1887 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1888 If *RESTP is NULL, newlines will be ignored.
1890 SHELL is the shell to use, or nil to use the default shell.
1891 IFS is the value of $IFS, or nil (meaning the default). */
1893 static char **
1894 construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr)
1895 char *line, **restp;
1896 char *shell, *ifs;
1897 char **batch_filename_ptr;
1899 #ifdef __MSDOS__
1900 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
1901 We call `system' for anything that requires ``slow'' processing,
1902 because DOS shells are too dumb. When $SHELL points to a real
1903 (unix-style) shell, `system' just calls it to do everything. When
1904 $SHELL points to a DOS shell, `system' does most of the work
1905 internally, calling the shell only for its internal commands.
1906 However, it looks on the $PATH first, so you can e.g. have an
1907 external command named `mkdir'.
1909 Since we call `system', certain characters and commands below are
1910 actually not specific to COMMAND.COM, but to the DJGPP implementation
1911 of `system'. In particular:
1913 The shell wildcard characters are in DOS_CHARS because they will
1914 not be expanded if we call the child via `spawnXX'.
1916 The `;' is in DOS_CHARS, because our `system' knows how to run
1917 multiple commands on a single line.
1919 DOS_CHARS also include characters special to 4DOS/NDOS, so we
1920 won't have to tell one from another and have one more set of
1921 commands and special characters. */
1922 static char sh_chars_dos[] = "*?[];|<>%^&()";
1923 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1924 "copy", "ctty", "date", "del", "dir", "echo",
1925 "erase", "exit", "for", "goto", "if", "md",
1926 "mkdir", "path", "pause", "prompt", "rd",
1927 "rmdir", "rem", "ren", "rename", "set",
1928 "shift", "time", "type", "ver", "verify",
1929 "vol", ":", 0 };
1931 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1932 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
1933 "logout", "set", "umask", "wait", "while",
1934 "for", "case", "if", ":", ".", "break",
1935 "continue", "export", "read", "readonly",
1936 "shift", "times", "trap", "switch", "unset",
1937 0 };
1939 char *sh_chars;
1940 char **sh_cmds;
1941 #else
1942 #ifdef _AMIGA
1943 static char sh_chars[] = "#;\"|<>()?*$`";
1944 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
1945 "rename", "set", "setenv", "date", "makedir",
1946 "skip", "else", "endif", "path", "prompt",
1947 "unset", "unsetenv", "version",
1948 0 };
1949 #else
1950 #ifdef WINDOWS32
1951 static char sh_chars_dos[] = "\"|<>";
1952 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1953 "copy", "ctty", "date", "del", "dir", "echo",
1954 "erase", "exit", "for", "goto", "if", "if", "md",
1955 "mkdir", "path", "pause", "prompt", "rem", "ren",
1956 "rename", "set", "shift", "time", "type",
1957 "ver", "verify", "vol", ":", 0 };
1958 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1959 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
1960 "logout", "set", "umask", "wait", "while", "for",
1961 "case", "if", ":", ".", "break", "continue",
1962 "export", "read", "readonly", "shift", "times",
1963 "trap", "switch", "test",
1964 #ifdef BATCH_MODE_ONLY_SHELL
1965 "echo",
1966 #endif
1967 0 };
1968 char* sh_chars;
1969 char** sh_cmds;
1970 #else /* WINDOWS32 */
1971 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1972 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1973 "logout", "set", "umask", "wait", "while", "for",
1974 "case", "if", ":", ".", "break", "continue",
1975 "export", "read", "readonly", "shift", "times",
1976 "trap", "switch", 0 };
1977 #endif /* WINDOWS32 */
1978 #endif /* Amiga */
1979 #endif /* __MSDOS__ */
1980 register int i;
1981 register char *p;
1982 register char *ap;
1983 char *end;
1984 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
1985 char **new_argv = 0;
1986 #ifdef WINDOWS32
1987 int slow_flag = 0;
1989 if (no_default_sh_exe) {
1990 sh_cmds = sh_cmds_dos;
1991 sh_chars = sh_chars_dos;
1992 } else {
1993 sh_cmds = sh_cmds_sh;
1994 sh_chars = sh_chars_sh;
1996 #endif /* WINDOWS32 */
1998 if (restp != NULL)
1999 *restp = NULL;
2001 /* Make sure not to bother processing an empty line. */
2002 while (isblank (*line))
2003 ++line;
2004 if (*line == '\0')
2005 return 0;
2007 /* See if it is safe to parse commands internally. */
2008 if (shell == 0)
2009 shell = default_shell;
2010 #ifdef WINDOWS32
2011 else if (strcmp (shell, default_shell))
2013 char *s1 = _fullpath(NULL, shell, 0);
2014 char *s2 = _fullpath(NULL, default_shell, 0);
2016 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2018 if (s1);
2019 free(s1);
2020 if (s2);
2021 free(s2);
2023 if (slow_flag)
2024 goto slow;
2025 #else /* not WINDOWS32 */
2026 #ifdef __MSDOS__
2027 else if (stricmp (shell, default_shell))
2029 extern int _is_unixy_shell (const char *_path);
2031 message (1, _("$SHELL changed (was `%s', now `%s')"), default_shell, shell);
2032 unixy_shell = _is_unixy_shell (shell);
2033 default_shell = shell;
2035 if (unixy_shell)
2037 sh_chars = sh_chars_sh;
2038 sh_cmds = sh_cmds_sh;
2040 else
2042 sh_chars = sh_chars_dos;
2043 sh_cmds = sh_cmds_dos;
2045 #else /* not __MSDOS__ */
2046 else if (strcmp (shell, default_shell))
2047 goto slow;
2048 #endif /* not __MSDOS__ */
2049 #endif /* not WINDOWS32 */
2051 if (ifs != 0)
2052 for (ap = ifs; *ap != '\0'; ++ap)
2053 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2054 goto slow;
2056 i = strlen (line) + 1;
2058 /* More than 1 arg per character is impossible. */
2059 new_argv = (char **) xmalloc (i * sizeof (char *));
2061 /* All the args can fit in a buffer as big as LINE is. */
2062 ap = new_argv[0] = (char *) xmalloc (i);
2063 end = ap + i;
2065 /* I is how many complete arguments have been found. */
2066 i = 0;
2067 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2068 for (p = line; *p != '\0'; ++p)
2070 if (ap > end)
2071 abort ();
2073 if (instring)
2075 string_char:
2076 /* Inside a string, just copy any char except a closing quote
2077 or a backslash-newline combination. */
2078 if (*p == instring)
2080 instring = 0;
2081 if (ap == new_argv[0] || *(ap-1) == '\0')
2082 last_argument_was_empty = 1;
2084 else if (*p == '\\' && p[1] == '\n')
2085 goto swallow_escaped_newline;
2086 else if (*p == '\n' && restp != NULL)
2088 /* End of the command line. */
2089 *restp = p;
2090 goto end_of_line;
2092 /* Backslash, $, and ` are special inside double quotes.
2093 If we see any of those, punt.
2094 But on MSDOS, if we use COMMAND.COM, double and single
2095 quotes have the same effect. */
2096 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2097 goto slow;
2098 else
2099 *ap++ = *p;
2101 else if (strchr (sh_chars, *p) != 0)
2102 /* Not inside a string, but it's a special char. */
2103 goto slow;
2104 #ifdef __MSDOS__
2105 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2106 /* `...' is a wildcard in DJGPP. */
2107 goto slow;
2108 #endif
2109 else
2110 /* Not a special char. */
2111 switch (*p)
2113 case '=':
2114 /* Equals is a special character in leading words before the
2115 first word with no equals sign in it. This is not the case
2116 with sh -k, but we never get here when using nonstandard
2117 shell flags. */
2118 if (! seen_nonequals && unixy_shell)
2119 goto slow;
2120 word_has_equals = 1;
2121 *ap++ = '=';
2122 break;
2124 case '\\':
2125 /* Backslash-newline combinations are eaten. */
2126 if (p[1] == '\n')
2128 swallow_escaped_newline:
2130 /* Eat the backslash, the newline, and following whitespace,
2131 replacing it all with a single space. */
2132 p += 2;
2134 /* If there is a tab after a backslash-newline,
2135 remove it from the source line which will be echoed,
2136 since it was most likely used to line
2137 up the continued line with the previous one. */
2138 if (*p == '\t')
2139 /* Note these overlap and strcpy() is undefined for
2140 overlapping objects in ANSI C. The strlen() _IS_ right,
2141 since we need to copy the nul byte too. */
2142 bcopy (p + 1, p, strlen (p));
2144 if (instring)
2145 goto string_char;
2146 else
2148 if (ap != new_argv[i])
2149 /* Treat this as a space, ending the arg.
2150 But if it's at the beginning of the arg, it should
2151 just get eaten, rather than becoming an empty arg. */
2152 goto end_of_arg;
2153 else
2154 p = next_token (p) - 1;
2157 else if (p[1] != '\0')
2159 #if defined(__MSDOS__) || defined(WINDOWS32)
2160 /* Only remove backslashes before characters special
2161 to Unixy shells. All other backslashes are copied
2162 verbatim, since they are probably DOS-style
2163 directory separators. This still leaves a small
2164 window for problems, but at least it should work
2165 for the vast majority of naive users. */
2167 #ifdef __MSDOS__
2168 /* A dot is only special as part of the "..."
2169 wildcard. */
2170 if (strneq (p + 1, ".\\.\\.", 5))
2172 *ap++ = '.';
2173 *ap++ = '.';
2174 p += 4;
2176 else
2177 #endif
2178 if (p[1] != '\\' && p[1] != '\''
2179 && !isspace ((unsigned char)p[1])
2180 && (strchr (sh_chars_sh, p[1]) == 0))
2181 /* back up one notch, to copy the backslash */
2182 --p;
2184 #endif /* __MSDOS__ || WINDOWS32 */
2185 /* Copy and skip the following char. */
2186 *ap++ = *++p;
2188 break;
2190 case '\'':
2191 case '"':
2192 instring = *p;
2193 break;
2195 case '\n':
2196 if (restp != NULL)
2198 /* End of the command line. */
2199 *restp = p;
2200 goto end_of_line;
2202 else
2203 /* Newlines are not special. */
2204 *ap++ = '\n';
2205 break;
2207 case ' ':
2208 case '\t':
2209 end_of_arg:
2210 /* We have the end of an argument.
2211 Terminate the text of the argument. */
2212 *ap++ = '\0';
2213 new_argv[++i] = ap;
2214 last_argument_was_empty = 0;
2216 /* Update SEEN_NONEQUALS, which tells us if every word
2217 heretofore has contained an `='. */
2218 seen_nonequals |= ! word_has_equals;
2219 if (word_has_equals && ! seen_nonequals)
2220 /* An `=' in a word before the first
2221 word without one is magical. */
2222 goto slow;
2223 word_has_equals = 0; /* Prepare for the next word. */
2225 /* If this argument is the command name,
2226 see if it is a built-in shell command.
2227 If so, have the shell handle it. */
2228 if (i == 1)
2230 register int j;
2231 for (j = 0; sh_cmds[j] != 0; ++j)
2232 if (streq (sh_cmds[j], new_argv[0]))
2233 goto slow;
2236 /* Ignore multiple whitespace chars. */
2237 p = next_token (p);
2238 /* Next iteration should examine the first nonwhite char. */
2239 --p;
2240 break;
2242 default:
2243 *ap++ = *p;
2244 break;
2247 end_of_line:
2249 if (instring)
2250 /* Let the shell deal with an unterminated quote. */
2251 goto slow;
2253 /* Terminate the last argument and the argument list. */
2255 *ap = '\0';
2256 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2257 ++i;
2258 new_argv[i] = 0;
2260 if (i == 1)
2262 register int j;
2263 for (j = 0; sh_cmds[j] != 0; ++j)
2264 if (streq (sh_cmds[j], new_argv[0]))
2265 goto slow;
2268 if (new_argv[0] == 0)
2269 /* Line was empty. */
2270 return 0;
2271 else
2272 return new_argv;
2274 slow:;
2275 /* We must use the shell. */
2277 if (new_argv != 0)
2279 /* Free the old argument list we were working on. */
2280 free (new_argv[0]);
2281 free ((void *)new_argv);
2284 #ifdef __MSDOS__
2285 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2286 #endif
2288 #ifdef _AMIGA
2290 char *ptr;
2291 char *buffer;
2292 char *dptr;
2294 buffer = (char *)xmalloc (strlen (line)+1);
2296 ptr = line;
2297 for (dptr=buffer; *ptr; )
2299 if (*ptr == '\\' && ptr[1] == '\n')
2300 ptr += 2;
2301 else if (*ptr == '@') /* Kludge: multiline commands */
2303 ptr += 2;
2304 *dptr++ = '\n';
2306 else
2307 *dptr++ = *ptr++;
2309 *dptr = 0;
2311 new_argv = (char **) xmalloc (2 * sizeof (char *));
2312 new_argv[0] = buffer;
2313 new_argv[1] = 0;
2315 #else /* Not Amiga */
2316 #ifdef WINDOWS32
2318 * Not eating this whitespace caused things like
2320 * sh -c "\n"
2322 * which gave the shell fits. I think we have to eat
2323 * whitespace here, but this code should be considered
2324 * suspicious if things start failing....
2327 /* Make sure not to bother processing an empty line. */
2328 while (isspace ((unsigned char)*line))
2329 ++line;
2330 if (*line == '\0')
2331 return 0;
2332 #endif /* WINDOWS32 */
2334 /* SHELL may be a multi-word command. Construct a command line
2335 "SHELL -c LINE", with all special chars in LINE escaped.
2336 Then recurse, expanding this command line to get the final
2337 argument list. */
2339 unsigned int shell_len = strlen (shell);
2340 static char minus_c[] = " -c ";
2341 unsigned int line_len = strlen (line);
2343 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2344 + (line_len * 2) + 1);
2345 char *command_ptr = NULL; /* used for batch_mode_shell mode */
2347 ap = new_line;
2348 bcopy (shell, ap, shell_len);
2349 ap += shell_len;
2350 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2351 ap += sizeof (minus_c) - 1;
2352 command_ptr = ap;
2353 for (p = line; *p != '\0'; ++p)
2355 if (restp != NULL && *p == '\n')
2357 *restp = p;
2358 break;
2360 else if (*p == '\\' && p[1] == '\n')
2362 /* Eat the backslash, the newline, and following whitespace,
2363 replacing it all with a single space (which is escaped
2364 from the shell). */
2365 p += 2;
2367 /* If there is a tab after a backslash-newline,
2368 remove it from the source line which will be echoed,
2369 since it was most likely used to line
2370 up the continued line with the previous one. */
2371 if (*p == '\t')
2372 bcopy (p + 1, p, strlen (p));
2374 p = next_token (p);
2375 --p;
2376 if (unixy_shell && !batch_mode_shell)
2377 *ap++ = '\\';
2378 *ap++ = ' ';
2379 continue;
2382 /* DOS shells don't know about backslash-escaping. */
2383 if (unixy_shell && !batch_mode_shell &&
2384 (*p == '\\' || *p == '\'' || *p == '"'
2385 || isspace ((unsigned char)*p)
2386 || strchr (sh_chars, *p) != 0))
2387 *ap++ = '\\';
2388 #ifdef __MSDOS__
2389 else if (unixy_shell && strneq (p, "...", 3))
2391 /* The case of `...' wildcard again. */
2392 strcpy (ap, "\\.\\.\\");
2393 ap += 5;
2394 p += 2;
2396 #endif
2397 *ap++ = *p;
2399 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2400 /* Line was empty. */
2401 return 0;
2402 *ap = '\0';
2404 #ifdef WINDOWS32
2405 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2406 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2407 cases, run commands via a script file. */
2408 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2409 FILE* batch = NULL;
2410 int id = GetCurrentProcessId();
2411 PATH_VAR(fbuf);
2412 char* fname = NULL;
2414 /* create a file name */
2415 sprintf(fbuf, "make%d", id);
2416 fname = tempnam(".", fbuf);
2418 /* create batch file name */
2419 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
2420 strcpy(*batch_filename_ptr, fname);
2422 /* make sure path name is in DOS backslash format */
2423 if (!unixy_shell) {
2424 fname = *batch_filename_ptr;
2425 for (i = 0; fname[i] != '\0'; ++i)
2426 if (fname[i] == '/')
2427 fname[i] = '\\';
2428 strcat(*batch_filename_ptr, ".bat");
2429 } else {
2430 strcat(*batch_filename_ptr, ".sh");
2433 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
2434 *batch_filename_ptr));
2436 /* create batch file to execute command */
2437 batch = fopen (*batch_filename_ptr, "w");
2438 if (!unixy_shell)
2439 fputs ("@echo off\n", batch);
2440 fputs (command_ptr, batch);
2441 fputc ('\n', batch);
2442 fclose (batch);
2444 /* create argv */
2445 new_argv = (char **) xmalloc(3 * sizeof (char *));
2446 if (unixy_shell) {
2447 new_argv[0] = xstrdup (shell);
2448 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2449 } else {
2450 new_argv[0] = xstrdup (*batch_filename_ptr);
2451 new_argv[1] = NULL;
2453 new_argv[2] = NULL;
2454 } else
2455 #endif /* WINDOWS32 */
2456 if (unixy_shell)
2457 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2458 (char *) 0, (char *) 0,
2459 (char **) 0);
2460 #ifdef __MSDOS__
2461 else
2463 /* With MSDOS shells, we must construct the command line here
2464 instead of recursively calling ourselves, because we
2465 cannot backslash-escape the special characters (see above). */
2466 new_argv = (char **) xmalloc (sizeof (char *));
2467 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2468 new_argv[0] = xmalloc (line_len + 1);
2469 strncpy (new_argv[0],
2470 new_line + shell_len + sizeof (minus_c) - 1, line_len);
2471 new_argv[0][line_len] = '\0';
2473 #else
2474 else
2475 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2476 __FILE__, __LINE__);
2477 #endif
2479 #endif /* ! AMIGA */
2481 return new_argv;
2484 /* Figure out the argument list necessary to run LINE as a command. Try to
2485 avoid using a shell. This routine handles only ' quoting, and " quoting
2486 when no backslash, $ or ` characters are seen in the quotes. Starting
2487 quotes may be escaped with a backslash. If any of the characters in
2488 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2489 is the first word of a line, the shell is used.
2491 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2492 If *RESTP is NULL, newlines will be ignored.
2494 FILE is the target whose commands these are. It is used for
2495 variable expansion for $(SHELL) and $(IFS). */
2497 char **
2498 construct_command_argv (line, restp, file, batch_filename_ptr)
2499 char *line, **restp;
2500 struct file *file;
2501 char** batch_filename_ptr;
2503 char *shell, *ifs;
2504 char **argv;
2507 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2508 int save = warn_undefined_variables_flag;
2509 warn_undefined_variables_flag = 0;
2511 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
2512 #ifdef WINDOWS32
2514 * Convert to forward slashes so that construct_command_argv_internal()
2515 * is not confused.
2517 if (shell) {
2518 char *p = w32ify(shell, 0);
2519 strcpy(shell, p);
2521 #endif
2522 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
2524 warn_undefined_variables_flag = save;
2527 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
2529 free (shell);
2530 free (ifs);
2532 return argv;
2534 #endif /* !VMS */
2536 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2538 dup2 (old, new)
2539 int old, new;
2541 int fd;
2543 (void) close (new);
2544 fd = dup (old);
2545 if (fd != new)
2547 (void) close (fd);
2548 errno = EMFILE;
2549 return -1;
2552 return fd;
2554 #endif /* !HAPE_DUP2 && !_AMIGA */