* Ensure -Iglob comes before any user-specified CPPFLAGS.
[make.git] / job.c
blob263bc3d1edacc7ad289bd3c0ce7b70625b068866
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988,89,90,91,92,93,94,95,96,97,99 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 GNU Make is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNU Make; see the file COPYING. If not, write to
17 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 #include "make.h"
21 #include "job.h"
22 #include "filedef.h"
23 #include "commands.h"
24 #include "variable.h"
25 #include <assert.h>
27 /* Default shell to use. */
28 #ifdef WINDOWS32
29 char *default_shell = "sh.exe";
30 int no_default_sh_exe = 1;
31 int batch_mode_shell = 1;
32 #else /* WINDOWS32 */
33 # ifdef _AMIGA
34 char default_shell[] = "";
35 extern int MyExecute (char **);
36 # else /* _AMIGA */
37 # ifdef __MSDOS__
38 /* The default shell is a pointer so we can change it if Makefile
39 says so. It is without an explicit path so we get a chance
40 to search the $PATH for it (since MSDOS doesn't have standard
41 directories we could trust). */
42 char *default_shell = "command.com";
43 # else /* __MSDOS__ */
44 char default_shell[] = "/bin/sh";
45 # endif /* __MSDOS__ */
46 int batch_mode_shell = 0;
47 # endif /* _AMIGA */
48 #endif /* WINDOWS32 */
50 #ifdef __MSDOS__
51 # include <process.h>
52 static int execute_by_shell;
53 static int dos_pid = 123;
54 int dos_status;
55 int dos_command_running;
56 #endif /* __MSDOS__ */
58 #ifdef _AMIGA
59 # include <proto/dos.h>
60 static int amiga_pid = 123;
61 static int amiga_status;
62 static char amiga_bname[32];
63 static int amiga_batch_file;
64 #endif /* Amiga. */
66 #ifdef VMS
67 # include <time.h>
68 # include <processes.h>
69 # include <starlet.h>
70 # include <lib$routines.h>
71 #endif
73 #ifdef WINDOWS32
74 # include <windows.h>
75 # include <io.h>
76 # include <process.h>
77 # include "sub_proc.h"
78 # include "w32err.h"
79 # include "pathstuff.h"
80 #endif /* WINDOWS32 */
82 #ifdef HAVE_FCNTL_H
83 # include <fcntl.h>
84 #else
85 # include <sys/file.h>
86 #endif
88 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
89 # include <sys/wait.h>
90 #endif
92 #ifdef HAVE_WAITPID
93 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
94 #else /* Don't have waitpid. */
95 # ifdef HAVE_WAIT3
96 # ifndef wait3
97 extern int wait3 ();
98 # endif
99 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
100 # endif /* Have wait3. */
101 #endif /* Have waitpid. */
103 #if !defined (wait) && !defined (POSIX)
104 extern int wait ();
105 #endif
107 #ifndef HAVE_UNION_WAIT
109 # define WAIT_T int
111 # ifndef WTERMSIG
112 # define WTERMSIG(x) ((x) & 0x7f)
113 # endif
114 # ifndef WCOREDUMP
115 # define WCOREDUMP(x) ((x) & 0x80)
116 # endif
117 # ifndef WEXITSTATUS
118 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
119 # endif
120 # ifndef WIFSIGNALED
121 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
122 # endif
123 # ifndef WIFEXITED
124 # define WIFEXITED(x) (WTERMSIG (x) == 0)
125 # endif
127 #else /* Have `union wait'. */
129 # define WAIT_T union wait
130 # ifndef WTERMSIG
131 # define WTERMSIG(x) ((x).w_termsig)
132 # endif
133 # ifndef WCOREDUMP
134 # define WCOREDUMP(x) ((x).w_coredump)
135 # endif
136 # ifndef WEXITSTATUS
137 # define WEXITSTATUS(x) ((x).w_retcode)
138 # endif
139 # ifndef WIFSIGNALED
140 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
141 # endif
142 # ifndef WIFEXITED
143 # define WIFEXITED(x) (WTERMSIG(x) == 0)
144 # endif
146 #endif /* Don't have `union wait'. */
148 /* How to set close-on-exec for a file descriptor. */
150 #if !defined F_SETFD
151 # define CLOSE_ON_EXEC(_d)
152 #else
153 # ifndef FD_CLOEXEC
154 # define FD_CLOEXEC 1
155 # endif
156 # define CLOSE_ON_EXEC(_d) (void) fcntl ((_d), F_SETFD, FD_CLOEXEC)
157 #endif
159 #ifdef VMS
160 static int vms_jobsefnmask = 0;
161 #endif /* !VMS */
163 #ifndef HAVE_UNISTD_H
164 extern int dup2 ();
165 extern int execve ();
166 extern void _exit ();
167 # ifndef VMS
168 extern int geteuid ();
169 extern int getegid ();
170 extern int setgid ();
171 extern int getgid ();
172 # endif
173 #endif
175 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
177 extern int getloadavg PARAMS ((double loadavg[], int nelem));
178 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
179 int *is_remote, int *id_ptr, int *used_stdin));
180 extern int start_remote_job_p PARAMS ((int));
181 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
182 int *coredump_ptr, int block));
184 static void free_child PARAMS ((struct child *));
185 static void start_job_command PARAMS ((struct child *child));
186 static int load_too_high PARAMS ((void));
187 static int job_next_command PARAMS ((struct child *));
188 static int start_waiting_job PARAMS ((struct child *));
189 #ifdef VMS
190 static void vmsWaitForChildren PARAMS ((int *));
191 #endif
193 /* Chain of all live (or recently deceased) children. */
195 struct child *children = 0;
197 /* Number of children currently running. */
199 unsigned int job_slots_used = 0;
201 /* Nonzero if the `good' standard input is in use. */
203 static int good_stdin_used = 0;
205 /* Chain of children waiting to run until the load average goes down. */
207 static struct child *waiting_jobs = 0;
209 /* Non-zero if we use a *real* shell (always so on Unix). */
211 int unixy_shell = 1;
213 /* #define debug_flag 1 */
216 #ifdef WINDOWS32
218 * The macro which references this function is defined in make.h.
220 int w32_kill(int pid, int sig)
222 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
224 #endif /* WINDOWS32 */
227 /* Write an error message describing the exit status given in
228 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
229 Append "(ignored)" if IGNORED is nonzero. */
231 static void
232 child_error (target_name, exit_code, exit_sig, coredump, ignored)
233 char *target_name;
234 int exit_code, exit_sig, coredump;
235 int ignored;
237 if (ignored && silent_flag)
238 return;
240 #ifdef VMS
241 if (!(exit_code & 1))
242 error (NILF, _("*** [%s] Error 0x%x%s"), target_name, exit_code, ((ignored)? _(" (ignored)") : ""));
243 #else
244 if (exit_sig == 0)
245 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
246 _("*** [%s] Error %d"),
247 target_name, exit_code);
248 else
249 error (NILF, "*** [%s] %s%s",
250 target_name, strsignal (exit_sig),
251 coredump ? _(" (core dumped)") : "");
252 #endif /* VMS */
255 #ifdef VMS
256 /* Wait for nchildren children to terminate */
257 static void
258 vmsWaitForChildren(int *status)
260 while (1)
262 if (!vms_jobsefnmask)
264 *status = 0;
265 return;
268 *status = sys$wflor (32, vms_jobsefnmask);
270 return;
272 #endif
275 /* Handle a dead child. This handler may or may not ever be installed.
277 If we're using the jobserver feature, we need it. First, installing it
278 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
279 read FD to ensure we don't enter another blocking read without reaping all
280 the dead children. In this case we don't need the dead_children count.
282 If we don't have either waitpid or wait3, then make is unreliable, but we
283 use the dead_children count to reap children as best we can. */
285 static unsigned int dead_children = 0;
287 RETSIGTYPE
288 child_handler (sig)
289 int sig;
291 ++dead_children;
293 if (job_rfd >= 0)
295 close (job_rfd);
296 job_rfd = -1;
299 if (debug_flag)
300 printf (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children);
304 extern int shell_function_pid, shell_function_completed;
306 /* Reap all dead children, storing the returned status and the new command
307 state (`cs_finished') in the `file' member of the `struct child' for the
308 dead child, and removing the child from the chain. In addition, if BLOCK
309 nonzero, we block in this function until we've reaped at least one
310 complete child, waiting for it to die if necessary. If ERR is nonzero,
311 print an error message first. */
313 void
314 reap_children (block, err)
315 int block, err;
317 WAIT_T status;
318 /* Initially, assume we have some. */
319 int reap_more = 1;
321 #ifdef WAIT_NOHANG
322 # define REAP_MORE reap_more
323 #else
324 # define REAP_MORE dead_children
325 #endif
327 /* As long as:
329 We have at least one child outstanding OR a shell function in progress,
331 We're blocking for a complete child OR there are more children to reap
333 we'll keep reaping children. */
335 while ((children != 0 || shell_function_pid != 0) &&
336 (block || REAP_MORE))
338 int remote = 0;
339 register int pid;
340 int exit_code, exit_sig, coredump;
341 register struct child *lastc, *c;
342 int child_failed;
343 int any_remote, any_local;
345 if (err && block)
347 /* We might block for a while, so let the user know why. */
348 fflush (stdout);
349 error (NILF, _("*** Waiting for unfinished jobs...."));
352 /* We have one less dead child to reap. As noted in
353 child_handler() above, this count is completely unimportant for
354 all modern, POSIX-y systems that support wait3() or waitpid().
355 The rest of this comment below applies only to early, broken
356 pre-POSIX systems. We keep the count only because... it's there...
358 The test and decrement are not atomic; if it is compiled into:
359 register = dead_children - 1;
360 dead_children = register;
361 a SIGCHLD could come between the two instructions.
362 child_handler increments dead_children.
363 The second instruction here would lose that increment. But the
364 only effect of dead_children being wrong is that we might wait
365 longer than necessary to reap a child, and lose some parallelism;
366 and we might print the "Waiting for unfinished jobs" message above
367 when not necessary. */
369 if (dead_children > 0)
370 --dead_children;
372 any_remote = 0;
373 any_local = shell_function_pid != 0;
374 for (c = children; c != 0; c = c->next)
376 any_remote |= c->remote;
377 any_local |= ! c->remote;
378 if (debug_flag)
379 printf (_("Live child 0x%08lx (%s) PID %ld %s\n"),
380 (unsigned long int) c, c->file->name,
381 (long) c->pid, c->remote ? _(" (remote)") : "");
382 #ifdef VMS
383 break;
384 #endif
387 /* First, check for remote children. */
388 if (any_remote)
389 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
390 else
391 pid = 0;
393 if (pid > 0)
394 /* We got a remote child. */
395 remote = 1;
396 else if (pid < 0)
398 /* A remote status command failed miserably. Punt. */
399 remote_status_lose:
400 if (EINTR_SET)
401 continue;
403 pfatal_with_name ("remote_status");
405 else
407 /* No remote children. Check for local children. */
408 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
409 if (any_local)
411 local_wait:
412 #ifdef VMS
413 vmsWaitForChildren (&status);
414 pid = c->pid;
415 #else
416 #ifdef WAIT_NOHANG
417 if (!block)
418 pid = WAIT_NOHANG (&status);
419 else
420 #endif
421 pid = wait (&status);
422 #endif /* !VMS */
424 else
425 pid = 0;
427 if (pid < 0)
429 /* EINTR? Try again. */
430 if (EINTR_SET)
431 goto local_wait;
433 /* The wait*() failed miserably. Punt. */
434 pfatal_with_name ("wait");
436 else if (pid > 0)
438 /* We got a child exit; chop the status word up. */
439 exit_code = WEXITSTATUS (status);
440 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
441 coredump = WCOREDUMP (status);
443 else
445 /* No local children are dead. */
446 reap_more = 0;
448 if (!block || !any_remote)
449 break;
451 /* Now try a blocking wait for a remote child. */
452 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
453 if (pid < 0)
454 goto remote_status_lose;
455 else if (pid == 0)
456 /* No remote children either. Finally give up. */
457 break;
459 /* We got a remote child. */
460 remote = 1;
462 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
464 #ifdef __MSDOS__
465 /* Life is very different on MSDOS. */
466 pid = dos_pid - 1;
467 status = dos_status;
468 exit_code = WEXITSTATUS (status);
469 if (exit_code == 0xff)
470 exit_code = -1;
471 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
472 coredump = 0;
473 #endif /* __MSDOS__ */
474 #ifdef _AMIGA
475 /* Same on Amiga */
476 pid = amiga_pid - 1;
477 status = amiga_status;
478 exit_code = amiga_status;
479 exit_sig = 0;
480 coredump = 0;
481 #endif /* _AMIGA */
482 #ifdef WINDOWS32
484 HANDLE hPID;
485 int err;
487 /* wait for anything to finish */
488 if (hPID = process_wait_for_any()) {
490 /* was an error found on this process? */
491 err = process_last_err(hPID);
493 /* get exit data */
494 exit_code = process_exit_code(hPID);
496 if (err)
497 fprintf(stderr, "make (e=%d): %s",
498 exit_code, map_windows32_error_to_string(exit_code));
500 /* signal */
501 exit_sig = process_signal(hPID);
503 /* cleanup process */
504 process_cleanup(hPID);
506 coredump = 0;
508 pid = (int) hPID;
510 #endif /* WINDOWS32 */
513 /* Check if this is the child of the `shell' function. */
514 if (!remote && pid == shell_function_pid)
516 /* It is. Leave an indicator for the `shell' function. */
517 if (exit_sig == 0 && exit_code == 127)
518 shell_function_completed = -1;
519 else
520 shell_function_completed = 1;
521 break;
524 child_failed = exit_sig != 0 || exit_code != 0;
526 /* Search for a child matching the deceased one. */
527 lastc = 0;
528 for (c = children; c != 0; lastc = c, c = c->next)
529 if (c->remote == remote && c->pid == pid)
530 break;
532 if (c == 0)
533 /* An unknown child died.
534 Ignore it; it was inherited from our invoker. */
535 continue;
537 if (debug_flag)
538 printf (_("Reaping %s child 0x%08lx PID %ld %s\n"),
539 child_failed ? _("losing") : _("winning"),
540 (unsigned long int) c, (long) c->pid,
541 c->remote ? _(" (remote)") : "");
543 if (c->sh_batch_file) {
544 if (debug_flag)
545 printf (_("Cleaning up temp batch file %s\n"), c->sh_batch_file);
547 /* just try and remove, don't care if this fails */
548 remove (c->sh_batch_file);
550 /* all done with memory */
551 free (c->sh_batch_file);
552 c->sh_batch_file = NULL;
555 /* If this child had the good stdin, say it is now free. */
556 if (c->good_stdin)
557 good_stdin_used = 0;
559 if (child_failed && !c->noerror && !ignore_errors_flag)
561 /* The commands failed. Write an error message,
562 delete non-precious targets, and abort. */
563 static int delete_on_error = -1;
564 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
565 c->file->update_status = 2;
566 if (delete_on_error == -1)
568 struct file *f = lookup_file (".DELETE_ON_ERROR");
569 delete_on_error = f != 0 && f->is_target;
571 if (exit_sig != 0 || delete_on_error)
572 delete_child_targets (c);
574 else
576 if (child_failed)
578 /* The commands failed, but we don't care. */
579 child_error (c->file->name,
580 exit_code, exit_sig, coredump, 1);
581 child_failed = 0;
584 /* If there are more commands to run, try to start them. */
585 if (job_next_command (c))
587 if (handling_fatal_signal)
589 /* Never start new commands while we are dying.
590 Since there are more commands that wanted to be run,
591 the target was not completely remade. So we treat
592 this as if a command had failed. */
593 c->file->update_status = 2;
595 else
597 /* Check again whether to start remotely.
598 Whether or not we want to changes over time.
599 Also, start_remote_job may need state set up
600 by start_remote_job_p. */
601 c->remote = start_remote_job_p (0);
602 start_job_command (c);
603 /* Fatal signals are left blocked in case we were
604 about to put that child on the chain. But it is
605 already there, so it is safe for a fatal signal to
606 arrive now; it will clean up this child's targets. */
607 unblock_sigs ();
608 if (c->file->command_state == cs_running)
609 /* We successfully started the new command.
610 Loop to reap more children. */
611 continue;
614 if (c->file->update_status != 0)
615 /* We failed to start the commands. */
616 delete_child_targets (c);
618 else
619 /* There are no more commands. We got through them all
620 without an unignored error. Now the target has been
621 successfully updated. */
622 c->file->update_status = 0;
625 /* When we get here, all the commands for C->file are finished
626 (or aborted) and C->file->update_status contains 0 or 2. But
627 C->file->command_state is still cs_running if all the commands
628 ran; notice_finish_file looks for cs_running to tell it that
629 it's interesting to check the file's modtime again now. */
631 if (! handling_fatal_signal)
632 /* Notice if the target of the commands has been changed.
633 This also propagates its values for command_state and
634 update_status to its also_make files. */
635 notice_finished_file (c->file);
637 if (debug_flag)
638 printf (_("Removing child 0x%08lx PID %ld %s from chain.\n"),
639 (unsigned long int) c, (long) c->pid,
640 c->remote ? _(" (remote)") : "");
642 /* Block fatal signals while frobnicating the list, so that
643 children and job_slots_used are always consistent. Otherwise
644 a fatal signal arriving after the child is off the chain and
645 before job_slots_used is decremented would believe a child was
646 live and call reap_children again. */
647 block_sigs ();
649 /* There is now another slot open. */
650 if (job_slots_used > 0)
651 --job_slots_used;
653 /* Remove the child from the chain and free it. */
654 if (lastc == 0)
655 children = c->next;
656 else
657 lastc->next = c->next;
659 free_child (c);
661 unblock_sigs ();
663 /* If the job failed, and the -k flag was not given, die,
664 unless we are already in the process of dying. */
665 if (!err && child_failed && !keep_going_flag &&
666 /* fatal_error_signal will die with the right signal. */
667 !handling_fatal_signal)
668 die (2);
670 /* Only block for one child. */
671 block = 0;
674 return;
677 /* Free the storage allocated for CHILD. */
679 static void
680 free_child (child)
681 register struct child *child;
683 /* If this child is the only one it was our "free" job, so don't put a
684 token back for it. This child has already been removed from the list,
685 so if there any left this wasn't the last one. */
687 if (job_fds[1] >= 0 && children)
689 char token = '+';
691 /* Write a job token back to the pipe. */
693 while (write (job_fds[1], &token, 1) != 1)
694 if (!EINTR_SET)
695 pfatal_with_name (_("write jobserver"));
697 if (debug_flag)
698 printf (_("Released token for child 0x%08lx (%s).\n"),
699 (unsigned long int) child, child->file->name);
702 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
703 return;
705 if (child->command_lines != 0)
707 register unsigned int i;
708 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
709 free (child->command_lines[i]);
710 free ((char *) child->command_lines);
713 if (child->environment != 0)
715 register char **ep = child->environment;
716 while (*ep != 0)
717 free (*ep++);
718 free ((char *) child->environment);
721 free ((char *) child);
724 #ifdef POSIX
725 extern sigset_t fatal_signal_set;
726 #endif
728 void
729 block_sigs ()
731 #ifdef POSIX
732 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
733 #else
734 # ifdef HAVE_SIGSETMASK
735 (void) sigblock (fatal_signal_mask);
736 # endif
737 #endif
740 #ifdef POSIX
741 void
742 unblock_sigs ()
744 sigset_t empty;
745 sigemptyset (&empty);
746 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
748 #endif
750 /* Start a job to run the commands specified in CHILD.
751 CHILD is updated to reflect the commands and ID of the child process.
753 NOTE: On return fatal signals are blocked! The caller is responsible
754 for calling `unblock_sigs', once the new child is safely on the chain so
755 it can be cleaned up in the event of a fatal signal. */
757 static void
758 start_job_command (child)
759 register struct child *child;
761 #ifndef _AMIGA
762 static int bad_stdin = -1;
763 #endif
764 register char *p;
765 int flags;
766 #ifdef VMS
767 char *argv;
768 #else
769 char **argv;
770 #endif
772 /* If we have a completely empty commandset, stop now. */
773 if (!child->command_ptr)
774 goto next_command;
776 /* Combine the flags parsed for the line itself with
777 the flags specified globally for this target. */
778 flags = (child->file->command_flags
779 | child->file->cmds->lines_flags[child->command_line - 1]);
781 p = child->command_ptr;
782 child->noerror = flags & COMMANDS_NOERROR;
784 while (*p != '\0')
786 if (*p == '@')
787 flags |= COMMANDS_SILENT;
788 else if (*p == '+')
789 flags |= COMMANDS_RECURSE;
790 else if (*p == '-')
791 child->noerror = 1;
792 else if (!isblank (*p))
793 break;
794 ++p;
797 /* Update the file's command flags with any new ones we found. */
798 child->file->cmds->lines_flags[child->command_line - 1] |= flags;
800 /* If -q was given, just say that updating `failed'. The exit status of
801 1 tells the user that -q is saying `something to do'; the exit status
802 for a random error is 2. */
803 if (question_flag && !(flags & COMMANDS_RECURSE))
805 child->file->update_status = 1;
806 notice_finished_file (child->file);
807 return;
810 /* There may be some preceding whitespace left if there
811 was nothing but a backslash on the first line. */
812 p = next_token (p);
814 /* Figure out an argument list from this command line. */
817 char *end = 0;
818 #ifdef VMS
819 argv = p;
820 #else
821 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
822 #endif
823 if (end == NULL)
824 child->command_ptr = NULL;
825 else
827 *end++ = '\0';
828 child->command_ptr = end;
832 if (touch_flag && !(flags & COMMANDS_RECURSE))
834 /* Go on to the next command. It might be the recursive one.
835 We construct ARGV only to find the end of the command line. */
836 #ifndef VMS
837 free (argv[0]);
838 free ((char *) argv);
839 #endif
840 argv = 0;
843 if (argv == 0)
845 next_command:
846 #ifdef __MSDOS__
847 execute_by_shell = 0; /* in case construct_command_argv sets it */
848 #endif
849 /* This line has no commands. Go to the next. */
850 if (job_next_command (child))
851 start_job_command (child);
852 else
854 /* No more commands. Make sure we're "running"; we might not be if
855 (e.g.) all commands were skipped due to -n. */
856 set_command_state (child->file, cs_running);
857 child->file->update_status = 0;
858 notice_finished_file (child->file);
860 return;
863 /* Print out the command. If silent, we call `message' with null so it
864 can log the working directory before the command's own error messages
865 appear. */
867 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
868 ? "%s" : (char *) 0, p);
870 /* Optimize an empty command. People use this for timestamp rules,
871 so avoid forking a useless shell. */
873 #if !defined(VMS) && !defined(_AMIGA)
874 if (
875 #ifdef __MSDOS__
876 unixy_shell /* the test is complicated and we already did it */
877 #else
878 (argv[0] && !strcmp (argv[0], "/bin/sh"))
879 #endif
880 && (argv[1]
881 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
882 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
883 && argv[3] == NULL)
885 free (argv[0]);
886 free ((char *) argv);
887 goto next_command;
889 #endif /* !VMS && !_AMIGA */
891 /* Tell update_goal_chain that a command has been started on behalf of
892 this target. It is important that this happens here and not in
893 reap_children (where we used to do it), because reap_children might be
894 reaping children from a different target. We want this increment to
895 guaranteedly indicate that a command was started for the dependency
896 chain (i.e., update_file recursion chain) we are processing. */
898 ++commands_started;
900 /* If -n was given, recurse to get the next line in the sequence. */
902 if (just_print_flag && !(flags & COMMANDS_RECURSE))
904 #ifndef VMS
905 free (argv[0]);
906 free ((char *) argv);
907 #endif
908 goto next_command;
911 /* Flush the output streams so they won't have things written twice. */
913 fflush (stdout);
914 fflush (stderr);
916 #ifndef VMS
917 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
919 /* Set up a bad standard input that reads from a broken pipe. */
921 if (bad_stdin == -1)
923 /* Make a file descriptor that is the read end of a broken pipe.
924 This will be used for some children's standard inputs. */
925 int pd[2];
926 if (pipe (pd) == 0)
928 /* Close the write side. */
929 (void) close (pd[1]);
930 /* Save the read side. */
931 bad_stdin = pd[0];
933 /* Set the descriptor to close on exec, so it does not litter any
934 child's descriptor table. When it is dup2'd onto descriptor 0,
935 that descriptor will not close on exec. */
936 CLOSE_ON_EXEC (bad_stdin);
940 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
942 /* Decide whether to give this child the `good' standard input
943 (one that points to the terminal or whatever), or the `bad' one
944 that points to the read side of a broken pipe. */
946 child->good_stdin = !good_stdin_used;
947 if (child->good_stdin)
948 good_stdin_used = 1;
950 #endif /* !VMS */
952 child->deleted = 0;
954 #ifndef _AMIGA
955 /* Set up the environment for the child. */
956 if (child->environment == 0)
957 child->environment = target_environment (child->file);
958 #endif
960 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
962 #ifndef VMS
963 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
964 if (child->remote)
966 int is_remote, id, used_stdin;
967 if (start_remote_job (argv, child->environment,
968 child->good_stdin ? 0 : bad_stdin,
969 &is_remote, &id, &used_stdin))
970 /* Don't give up; remote execution may fail for various reasons. If
971 so, simply run the job locally. */
972 goto run_local;
973 else
975 if (child->good_stdin && !used_stdin)
977 child->good_stdin = 0;
978 good_stdin_used = 0;
980 child->remote = is_remote;
981 child->pid = id;
984 else
985 #endif /* !VMS */
987 /* Fork the child process. */
989 char **parent_environ;
991 run_local:
992 block_sigs ();
994 child->remote = 0;
996 #ifdef VMS
998 if (!child_execute_job (argv, child)) {
999 /* Fork failed! */
1000 perror_with_name ("vfork", "");
1001 goto error;
1004 #else
1006 parent_environ = environ;
1007 child->pid = vfork ();
1008 environ = parent_environ; /* Restore value child may have clobbered. */
1009 if (child->pid == 0)
1011 /* We are the child side. */
1012 unblock_sigs ();
1014 /* If we aren't running a recursive command and we have a jobserver
1015 pipe, close it before exec'ing. */
1016 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1018 close (job_fds[0]);
1019 close (job_fds[1]);
1021 if (job_rfd >= 0)
1022 close (job_rfd);
1024 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1025 argv, child->environment);
1027 else if (child->pid < 0)
1029 /* Fork failed! */
1030 unblock_sigs ();
1031 perror_with_name ("vfork", "");
1032 goto error;
1034 #endif /* !VMS */
1037 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1038 #ifdef __MSDOS__
1040 int proc_return;
1042 block_sigs ();
1043 dos_status = 0;
1045 /* We call `system' to do the job of the SHELL, since stock DOS
1046 shell is too dumb. Our `system' knows how to handle long
1047 command lines even if pipes/redirection is needed; it will only
1048 call COMMAND.COM when its internal commands are used. */
1049 if (execute_by_shell)
1051 char *cmdline = argv[0];
1052 /* We don't have a way to pass environment to `system',
1053 so we need to save and restore ours, sigh... */
1054 char **parent_environ = environ;
1056 environ = child->environment;
1058 /* If we have a *real* shell, tell `system' to call
1059 it to do everything for us. */
1060 if (unixy_shell)
1062 /* A *real* shell on MSDOS may not support long
1063 command lines the DJGPP way, so we must use `system'. */
1064 cmdline = argv[2]; /* get past "shell -c" */
1067 dos_command_running = 1;
1068 proc_return = system (cmdline);
1069 environ = parent_environ;
1070 execute_by_shell = 0; /* for the next time */
1072 else
1074 dos_command_running = 1;
1075 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1078 /* Need to unblock signals before turning off
1079 dos_command_running, so that child's signals
1080 will be treated as such (see fatal_error_signal). */
1081 unblock_sigs ();
1082 dos_command_running = 0;
1084 /* If the child got a signal, dos_status has its
1085 high 8 bits set, so be careful not to alter them. */
1086 if (proc_return == -1)
1087 dos_status |= 0xff;
1088 else
1089 dos_status |= (proc_return & 0xff);
1090 ++dead_children;
1091 child->pid = dos_pid++;
1093 #endif /* __MSDOS__ */
1094 #ifdef _AMIGA
1095 amiga_status = MyExecute (argv);
1097 ++dead_children;
1098 child->pid = amiga_pid++;
1099 if (amiga_batch_file)
1101 amiga_batch_file = 0;
1102 DeleteFile (amiga_bname); /* Ignore errors. */
1104 #endif /* Amiga */
1105 #ifdef WINDOWS32
1107 HANDLE hPID;
1108 char* arg0;
1110 /* make UNC paths safe for CreateProcess -- backslash format */
1111 arg0 = argv[0];
1112 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1113 for ( ; arg0 && *arg0; arg0++)
1114 if (*arg0 == '/')
1115 *arg0 = '\\';
1117 /* make sure CreateProcess() has Path it needs */
1118 sync_Path_environment();
1120 hPID = process_easy(argv, child->environment);
1122 if (hPID != INVALID_HANDLE_VALUE)
1123 child->pid = (int) hPID;
1124 else {
1125 int i;
1126 unblock_sigs();
1127 fprintf(stderr,
1128 _("process_easy() failed failed to launch process (e=%d)\n"),
1129 process_last_err(hPID));
1130 for (i = 0; argv[i]; i++)
1131 fprintf(stderr, "%s ", argv[i]);
1132 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1135 #endif /* WINDOWS32 */
1136 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1138 /* We are the parent side. Set the state to
1139 say the commands are running and return. */
1141 set_command_state (child->file, cs_running);
1143 /* Free the storage used by the child's argument list. */
1144 #ifndef VMS
1145 free (argv[0]);
1146 free ((char *) argv);
1147 #endif
1149 return;
1151 error:
1152 child->file->update_status = 2;
1153 notice_finished_file (child->file);
1154 return;
1157 /* Try to start a child running.
1158 Returns nonzero if the child was started (and maybe finished), or zero if
1159 the load was too high and the child was put on the `waiting_jobs' chain. */
1161 static int
1162 start_waiting_job (c)
1163 struct child *c;
1165 struct file *f = c->file;
1167 /* If we can start a job remotely, we always want to, and don't care about
1168 the local load average. We record that the job should be started
1169 remotely in C->remote for start_job_command to test. */
1171 c->remote = start_remote_job_p (1);
1173 /* If we are running at least one job already and the load average
1174 is too high, make this one wait. */
1175 if (!c->remote && job_slots_used > 0 && load_too_high ())
1177 /* Put this child on the chain of children waiting for the load average
1178 to go down. */
1179 set_command_state (f, cs_running);
1180 c->next = waiting_jobs;
1181 waiting_jobs = c;
1182 return 0;
1185 /* Start the first command; reap_children will run later command lines. */
1186 start_job_command (c);
1188 switch (f->command_state)
1190 case cs_running:
1191 c->next = children;
1192 if (debug_flag)
1193 printf (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1194 (unsigned long int) c, c->file->name,
1195 (long) c->pid, c->remote ? _(" (remote)") : "");
1196 children = c;
1197 /* One more job slot is in use. */
1198 ++job_slots_used;
1199 unblock_sigs ();
1200 break;
1202 case cs_not_started:
1203 /* All the command lines turned out to be empty. */
1204 f->update_status = 0;
1205 /* FALLTHROUGH */
1207 case cs_finished:
1208 notice_finished_file (f);
1209 free_child (c);
1210 break;
1212 default:
1213 assert (f->command_state == cs_finished);
1214 break;
1217 return 1;
1220 /* Create a `struct child' for FILE and start its commands running. */
1222 void
1223 new_job (file)
1224 register struct file *file;
1226 register struct commands *cmds = file->cmds;
1227 register struct child *c;
1228 char **lines;
1229 register unsigned int i;
1231 /* Let any previously decided-upon jobs that are waiting
1232 for the load to go down start before this new one. */
1233 start_waiting_jobs ();
1235 /* Reap any children that might have finished recently. */
1236 reap_children (0, 0);
1238 /* Chop the commands up into lines if they aren't already. */
1239 chop_commands (cmds);
1241 /* Expand the command lines and store the results in LINES. */
1242 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1243 for (i = 0; i < cmds->ncommand_lines; ++i)
1245 /* Collapse backslash-newline combinations that are inside variable
1246 or function references. These are left alone by the parser so
1247 that they will appear in the echoing of commands (where they look
1248 nice); and collapsed by construct_command_argv when it tokenizes.
1249 But letting them survive inside function invocations loses because
1250 we don't want the functions to see them as part of the text. */
1252 char *in, *out, *ref;
1254 /* IN points to where in the line we are scanning.
1255 OUT points to where in the line we are writing.
1256 When we collapse a backslash-newline combination,
1257 IN gets ahead of OUT. */
1259 in = out = cmds->command_lines[i];
1260 while ((ref = index (in, '$')) != 0)
1262 ++ref; /* Move past the $. */
1264 if (out != in)
1265 /* Copy the text between the end of the last chunk
1266 we processed (where IN points) and the new chunk
1267 we are about to process (where REF points). */
1268 bcopy (in, out, ref - in);
1270 /* Move both pointers past the boring stuff. */
1271 out += ref - in;
1272 in = ref;
1274 if (*ref == '(' || *ref == '{')
1276 char openparen = *ref;
1277 char closeparen = openparen == '(' ? ')' : '}';
1278 int count;
1279 char *p;
1281 *out++ = *in++; /* Copy OPENPAREN. */
1282 /* IN now points past the opening paren or brace.
1283 Count parens or braces until it is matched. */
1284 count = 0;
1285 while (*in != '\0')
1287 if (*in == closeparen && --count < 0)
1288 break;
1289 else if (*in == '\\' && in[1] == '\n')
1291 /* We have found a backslash-newline inside a
1292 variable or function reference. Eat it and
1293 any following whitespace. */
1295 int quoted = 0;
1296 for (p = in - 1; p > ref && *p == '\\'; --p)
1297 quoted = !quoted;
1299 if (quoted)
1300 /* There were two or more backslashes, so this is
1301 not really a continuation line. We don't collapse
1302 the quoting backslashes here as is done in
1303 collapse_continuations, because the line will
1304 be collapsed again after expansion. */
1305 *out++ = *in++;
1306 else
1308 /* Skip the backslash, newline and
1309 any following whitespace. */
1310 in = next_token (in + 2);
1312 /* Discard any preceding whitespace that has
1313 already been written to the output. */
1314 while (out > ref && isblank (out[-1]))
1315 --out;
1317 /* Replace it all with a single space. */
1318 *out++ = ' ';
1321 else
1323 if (*in == openparen)
1324 ++count;
1326 *out++ = *in++;
1332 /* There are no more references in this line to worry about.
1333 Copy the remaining uninteresting text to the output. */
1334 if (out != in)
1335 strcpy (out, in);
1337 /* Finally, expand the line. */
1338 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1339 file);
1342 /* Start the command sequence, record it in a new
1343 `struct child', and add that to the chain. */
1345 c = (struct child *) xmalloc (sizeof (struct child));
1346 c->file = file;
1347 c->command_lines = lines;
1348 c->command_line = 0;
1349 c->command_ptr = 0;
1350 c->environment = 0;
1351 c->sh_batch_file = NULL;
1353 /* Fetch the first command line to be run. */
1354 job_next_command (c);
1356 /* Wait for a job slot to be freed up. If we allow an infinite number
1357 don't bother; also job_slots will == 0 if we're using the jobserver. */
1359 if (job_slots != 0)
1360 while (job_slots_used == job_slots)
1361 reap_children (1, 0);
1363 #ifdef MAKE_JOBSERVER
1364 /* If we are controlling multiple jobs make sure we have a token before
1365 starting the child. */
1367 /* This can be inefficient. There's a decent chance that this job won't
1368 actually have to run any subprocesses: the command script may be empty
1369 or otherwise optimized away. It would be nice if we could defer
1370 obtaining a token until just before we need it, in start_job_command.
1371 To do that we'd need to keep track of whether we'd already obtained a
1372 token (since start_job_command is called for each line of the job, not
1373 just once). Also more thought needs to go into the entire algorithm;
1374 this is where the old parallel job code waits, so... */
1376 else if (job_fds[0] >= 0)
1377 while (1)
1379 char token;
1381 /* If we don't already have a job started, use our "free" token. */
1382 if (!children)
1383 break;
1385 /* Read a token. As long as there's no token available we'll block.
1386 If we get a SIGCHLD we'll return with EINTR. If one happened
1387 before we got here we'll return immediately with EBADF because
1388 the signal handler closes the dup'd file descriptor. */
1390 if (read (job_rfd, &token, 1) == 1)
1392 if (debug_flag)
1393 printf (_("Obtained token for child 0x%08lx (%s).\n"),
1394 (unsigned long int) c, c->file->name);
1395 break;
1398 if (errno != EINTR && errno != EBADF)
1399 pfatal_with_name (_("read jobs pipe"));
1401 /* Re-dup the read side of the pipe, so the signal handler can
1402 notify us if we miss a child. */
1403 if (job_rfd < 0)
1404 job_rfd = dup (job_fds[0]);
1406 /* Something's done. We don't want to block for a whole child,
1407 just reap whatever's there. */
1408 reap_children (0, 0);
1410 #endif
1412 /* The job is now primed. Start it running.
1413 (This will notice if there are in fact no commands.) */
1414 (void) start_waiting_job (c);
1416 if (job_slots == 1)
1417 /* Since there is only one job slot, make things run linearly.
1418 Wait for the child to die, setting the state to `cs_finished'. */
1419 while (file->command_state == cs_running)
1420 reap_children (1, 0);
1422 return;
1425 /* Move CHILD's pointers to the next command for it to execute.
1426 Returns nonzero if there is another command. */
1428 static int
1429 job_next_command (child)
1430 struct child *child;
1432 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1434 /* There are no more lines in the expansion of this line. */
1435 if (child->command_line == child->file->cmds->ncommand_lines)
1437 /* There are no more lines to be expanded. */
1438 child->command_ptr = 0;
1439 return 0;
1441 else
1442 /* Get the next line to run. */
1443 child->command_ptr = child->command_lines[child->command_line++];
1445 return 1;
1448 static int
1449 load_too_high ()
1451 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1452 return 1;
1453 #else
1454 double load;
1456 if (max_load_average < 0)
1457 return 0;
1459 make_access ();
1460 if (getloadavg (&load, 1) != 1)
1462 static int lossage = -1;
1463 /* Complain only once for the same error. */
1464 if (lossage == -1 || errno != lossage)
1466 if (errno == 0)
1467 /* An errno value of zero means getloadavg is just unsupported. */
1468 error (NILF, _("cannot enforce load limits on this operating system"));
1469 else
1470 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1472 lossage = errno;
1473 load = 0;
1475 user_access ();
1477 return load >= max_load_average;
1478 #endif
1481 /* Start jobs that are waiting for the load to be lower. */
1483 void
1484 start_waiting_jobs ()
1486 struct child *job;
1488 if (waiting_jobs == 0)
1489 return;
1493 /* Check for recently deceased descendants. */
1494 reap_children (0, 0);
1496 /* Take a job off the waiting list. */
1497 job = waiting_jobs;
1498 waiting_jobs = job->next;
1500 /* Try to start that job. We break out of the loop as soon
1501 as start_waiting_job puts one back on the waiting list. */
1503 while (start_waiting_job (job) && waiting_jobs != 0);
1505 return;
1508 #ifndef WINDOWS32
1509 #ifdef VMS
1510 #include <descrip.h>
1511 #include <clidef.h>
1513 /* This is called as an AST when a child process dies (it won't get
1514 interrupted by anything except a higher level AST).
1516 int vmsHandleChildTerm(struct child *child)
1518 int status;
1519 register struct child *lastc, *c;
1520 int child_failed;
1522 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1524 lib$free_ef(&child->efn);
1526 (void) sigblock (fatal_signal_mask);
1528 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1530 /* Search for a child matching the deceased one. */
1531 lastc = 0;
1532 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1533 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1534 #else
1535 c = child;
1536 #endif
1538 if (child_failed && !c->noerror && !ignore_errors_flag)
1540 /* The commands failed. Write an error message,
1541 delete non-precious targets, and abort. */
1542 child_error (c->file->name, c->cstatus, 0, 0, 0);
1543 c->file->update_status = 1;
1544 delete_child_targets (c);
1546 else
1548 if (child_failed)
1550 /* The commands failed, but we don't care. */
1551 child_error (c->file->name, c->cstatus, 0, 0, 1);
1552 child_failed = 0;
1555 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1556 /* If there are more commands to run, try to start them. */
1557 start_job (c);
1559 switch (c->file->command_state)
1561 case cs_running:
1562 /* Successfully started. */
1563 break;
1565 case cs_finished:
1566 if (c->file->update_status != 0) {
1567 /* We failed to start the commands. */
1568 delete_child_targets (c);
1570 break;
1572 default:
1573 error (NILF, _("internal error: `%s' command_state"), c->file->name);
1574 abort ();
1575 break;
1577 #endif /* RECURSIVEJOBS */
1580 /* Set the state flag to say the commands have finished. */
1581 c->file->command_state = cs_finished;
1582 notice_finished_file (c->file);
1584 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1585 /* Remove the child from the chain and free it. */
1586 if (lastc == 0)
1587 children = c->next;
1588 else
1589 lastc->next = c->next;
1590 free_child (c);
1591 #endif /* RECURSIVEJOBS */
1593 /* There is now another slot open. */
1594 if (job_slots_used > 0)
1595 --job_slots_used;
1597 /* If the job failed, and the -k flag was not given, die. */
1598 if (child_failed && !keep_going_flag)
1599 die (EXIT_FAILURE);
1601 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1603 return 1;
1606 /* VMS:
1607 Spawn a process executing the command in ARGV and return its pid. */
1609 #define MAXCMDLEN 200
1612 child_execute_job (argv, child)
1613 char *argv;
1614 struct child *child;
1616 int i;
1617 static struct dsc$descriptor_s cmddsc;
1618 #ifndef DONTWAITFORCHILD
1619 int spflags = 0;
1620 #else
1621 int spflags = CLI$M_NOWAIT;
1622 #endif
1623 int status;
1624 char cmd[4096],*p,*c;
1625 char comname[50];
1627 /* Remove backslashes */
1628 for (p = argv, c = cmd; *p; p++,c++)
1630 if (*p == '\\') p++;
1631 *c = *p;
1633 *c = *p;
1635 /* Check for maximum DCL length and create *.com file if neccesary.
1636 Also create a .com file if the command is more than one line long. */
1638 comname[0] = '\0';
1640 if (strlen (cmd) > MAXCMDLEN || strchr (cmd, '\n'))
1642 FILE *outfile;
1643 char tmp;
1645 strcpy (comname, "sys$scratch:CMDXXXXXX.COM");
1646 (void) mktemp (comname);
1648 outfile = fopen (comname, "w");
1649 if (outfile == 0)
1650 pfatal_with_name (comname);
1652 fprintf (outfile, "$ ");
1653 c = cmd;
1655 while (c)
1657 p = strchr (c, ',');
1658 if ((p == NULL) || (p-c > MAXCMDLEN))
1659 p = strchr (c, ' ');
1660 if (p != NULL)
1662 p++;
1663 tmp = *p;
1664 *p = '\0';
1666 else
1667 tmp = '\0';
1668 fprintf (outfile, "%s%s\n", c, (tmp == '\0')?"":" -");
1669 if (p != NULL)
1670 *p = tmp;
1671 c = p;
1674 fclose (outfile);
1676 sprintf (cmd, "$ @%s", comname);
1678 if (debug_flag)
1679 printf (_("Executing %s instead\n"), cmd);
1682 cmddsc.dsc$w_length = strlen(cmd);
1683 cmddsc.dsc$a_pointer = cmd;
1684 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
1685 cmddsc.dsc$b_class = DSC$K_CLASS_S;
1687 child->efn = 0;
1688 while (child->efn < 32 || child->efn > 63)
1690 status = lib$get_ef(&child->efn);
1691 if (!(status & 1))
1692 return 0;
1695 sys$clref(child->efn);
1697 vms_jobsefnmask |= (1 << (child->efn - 32));
1699 #ifndef DONTWAITFORCHILD
1700 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1701 &child->efn,0,0);
1702 vmsHandleChildTerm(child);
1703 #else
1704 status = lib$spawn(&cmddsc,0,0,&spflags,0,&child->pid,&child->cstatus,
1705 &child->efn,vmsHandleChildTerm,child);
1706 #endif
1708 if (!(status & 1))
1710 printf(_("Error spawning, %d\n"),status);
1711 fflush(stdout);
1714 unlink (comname);
1716 return (status & 1);
1719 #else /* !VMS */
1721 #if !defined (_AMIGA) && !defined (__MSDOS__)
1722 /* UNIX:
1723 Replace the current process with one executing the command in ARGV.
1724 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1725 the environment of the new program. This function does not return. */
1727 void
1728 child_execute_job (stdin_fd, stdout_fd, argv, envp)
1729 int stdin_fd, stdout_fd;
1730 char **argv, **envp;
1732 if (stdin_fd != 0)
1733 (void) dup2 (stdin_fd, 0);
1734 if (stdout_fd != 1)
1735 (void) dup2 (stdout_fd, 1);
1736 if (stdin_fd != 0)
1737 (void) close (stdin_fd);
1738 if (stdout_fd != 1)
1739 (void) close (stdout_fd);
1741 /* Run the command. */
1742 exec_command (argv, envp);
1744 #endif /* !AMIGA && !__MSDOS__ */
1745 #endif /* !VMS */
1746 #endif /* !WINDOWS32 */
1748 #ifndef _AMIGA
1749 /* Replace the current process with one running the command in ARGV,
1750 with environment ENVP. This function does not return. */
1752 void
1753 exec_command (argv, envp)
1754 char **argv, **envp;
1756 #ifdef VMS
1757 /* Run the program. */
1758 execve (argv[0], argv, envp);
1759 perror_with_name ("execve: ", argv[0]);
1760 _exit (EXIT_FAILURE);
1761 #else
1762 #ifdef WINDOWS32
1763 HANDLE hPID;
1764 HANDLE hWaitPID;
1765 int err = 0;
1766 int exit_code = EXIT_FAILURE;
1768 /* make sure CreateProcess() has Path it needs */
1769 sync_Path_environment();
1771 /* launch command */
1772 hPID = process_easy(argv, envp);
1774 /* make sure launch ok */
1775 if (hPID == INVALID_HANDLE_VALUE)
1777 int i;
1778 fprintf(stderr,
1779 _("process_easy() failed failed to launch process (e=%d)\n"),
1780 process_last_err(hPID));
1781 for (i = 0; argv[i]; i++)
1782 fprintf(stderr, "%s ", argv[i]);
1783 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1784 exit(EXIT_FAILURE);
1787 /* wait and reap last child */
1788 while (hWaitPID = process_wait_for_any())
1790 /* was an error found on this process? */
1791 err = process_last_err(hWaitPID);
1793 /* get exit data */
1794 exit_code = process_exit_code(hWaitPID);
1796 if (err)
1797 fprintf(stderr, "make (e=%d, rc=%d): %s",
1798 err, exit_code, map_windows32_error_to_string(err));
1800 /* cleanup process */
1801 process_cleanup(hWaitPID);
1803 /* expect to find only last pid, warn about other pids reaped */
1804 if (hWaitPID == hPID)
1805 break;
1806 else
1807 fprintf(stderr,
1808 _("make reaped child pid %d, still waiting for pid %d\n"),
1809 hWaitPID, hPID);
1812 /* return child's exit code as our exit code */
1813 exit(exit_code);
1815 #else /* !WINDOWS32 */
1817 /* Be the user, permanently. */
1818 child_access ();
1820 /* Run the program. */
1821 environ = envp;
1822 execvp (argv[0], argv);
1824 switch (errno)
1826 case ENOENT:
1827 error (NILF, _("%s: Command not found"), argv[0]);
1828 break;
1829 case ENOEXEC:
1831 /* The file is not executable. Try it as a shell script. */
1832 extern char *getenv ();
1833 char *shell;
1834 char **new_argv;
1835 int argc;
1837 shell = getenv ("SHELL");
1838 if (shell == 0)
1839 shell = default_shell;
1841 argc = 1;
1842 while (argv[argc] != 0)
1843 ++argc;
1845 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
1846 new_argv[0] = shell;
1847 new_argv[1] = argv[0];
1848 while (argc > 0)
1850 new_argv[1 + argc] = argv[argc];
1851 --argc;
1854 execvp (shell, new_argv);
1855 if (errno == ENOENT)
1856 error (NILF, _("%s: Shell program not found"), shell);
1857 else
1858 perror_with_name ("execvp: ", shell);
1859 break;
1862 default:
1863 perror_with_name ("execvp: ", argv[0]);
1864 break;
1867 _exit (127);
1868 #endif /* !WINDOWS32 */
1869 #endif /* !VMS */
1871 #else /* On Amiga */
1872 void exec_command (argv)
1873 char **argv;
1875 MyExecute (argv);
1878 void clean_tmp (void)
1880 DeleteFile (amiga_bname);
1883 #endif /* On Amiga */
1885 #ifndef VMS
1886 /* Figure out the argument list necessary to run LINE as a command. Try to
1887 avoid using a shell. This routine handles only ' quoting, and " quoting
1888 when no backslash, $ or ` characters are seen in the quotes. Starting
1889 quotes may be escaped with a backslash. If any of the characters in
1890 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1891 is the first word of a line, the shell is used.
1893 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1894 If *RESTP is NULL, newlines will be ignored.
1896 SHELL is the shell to use, or nil to use the default shell.
1897 IFS is the value of $IFS, or nil (meaning the default). */
1899 static char **
1900 construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr)
1901 char *line, **restp;
1902 char *shell, *ifs;
1903 char **batch_filename_ptr;
1905 #ifdef __MSDOS__
1906 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
1907 We call `system' for anything that requires ``slow'' processing,
1908 because DOS shells are too dumb. When $SHELL points to a real
1909 (unix-style) shell, `system' just calls it to do everything. When
1910 $SHELL points to a DOS shell, `system' does most of the work
1911 internally, calling the shell only for its internal commands.
1912 However, it looks on the $PATH first, so you can e.g. have an
1913 external command named `mkdir'.
1915 Since we call `system', certain characters and commands below are
1916 actually not specific to COMMAND.COM, but to the DJGPP implementation
1917 of `system'. In particular:
1919 The shell wildcard characters are in DOS_CHARS because they will
1920 not be expanded if we call the child via `spawnXX'.
1922 The `;' is in DOS_CHARS, because our `system' knows how to run
1923 multiple commands on a single line.
1925 DOS_CHARS also include characters special to 4DOS/NDOS, so we
1926 won't have to tell one from another and have one more set of
1927 commands and special characters. */
1928 static char sh_chars_dos[] = "*?[];|<>%^&()";
1929 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1930 "copy", "ctty", "date", "del", "dir", "echo",
1931 "erase", "exit", "for", "goto", "if", "md",
1932 "mkdir", "path", "pause", "prompt", "rd",
1933 "rmdir", "rem", "ren", "rename", "set",
1934 "shift", "time", "type", "ver", "verify",
1935 "vol", ":", 0 };
1937 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1938 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
1939 "logout", "set", "umask", "wait", "while",
1940 "for", "case", "if", ":", ".", "break",
1941 "continue", "export", "read", "readonly",
1942 "shift", "times", "trap", "switch", "unset",
1943 0 };
1945 char *sh_chars;
1946 char **sh_cmds;
1947 #else
1948 #ifdef _AMIGA
1949 static char sh_chars[] = "#;\"|<>()?*$`";
1950 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
1951 "rename", "set", "setenv", "date", "makedir",
1952 "skip", "else", "endif", "path", "prompt",
1953 "unset", "unsetenv", "version",
1954 0 };
1955 #else
1956 #ifdef WINDOWS32
1957 static char sh_chars_dos[] = "\"|<>";
1958 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1959 "copy", "ctty", "date", "del", "dir", "echo",
1960 "erase", "exit", "for", "goto", "if", "if", "md",
1961 "mkdir", "path", "pause", "prompt", "rem", "ren",
1962 "rename", "set", "shift", "time", "type",
1963 "ver", "verify", "vol", ":", 0 };
1964 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
1965 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
1966 "logout", "set", "umask", "wait", "while", "for",
1967 "case", "if", ":", ".", "break", "continue",
1968 "export", "read", "readonly", "shift", "times",
1969 "trap", "switch", "test",
1970 #ifdef BATCH_MODE_ONLY_SHELL
1971 "echo",
1972 #endif
1973 0 };
1974 char* sh_chars;
1975 char** sh_cmds;
1976 #else /* WINDOWS32 */
1977 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
1978 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
1979 "logout", "set", "umask", "wait", "while", "for",
1980 "case", "if", ":", ".", "break", "continue",
1981 "export", "read", "readonly", "shift", "times",
1982 "trap", "switch", 0 };
1983 #endif /* WINDOWS32 */
1984 #endif /* Amiga */
1985 #endif /* __MSDOS__ */
1986 register int i;
1987 register char *p;
1988 register char *ap;
1989 char *end;
1990 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
1991 char **new_argv = 0;
1992 #ifdef WINDOWS32
1993 int slow_flag = 0;
1995 if (no_default_sh_exe) {
1996 sh_cmds = sh_cmds_dos;
1997 sh_chars = sh_chars_dos;
1998 } else {
1999 sh_cmds = sh_cmds_sh;
2000 sh_chars = sh_chars_sh;
2002 #endif /* WINDOWS32 */
2004 if (restp != NULL)
2005 *restp = NULL;
2007 /* Make sure not to bother processing an empty line. */
2008 while (isblank (*line))
2009 ++line;
2010 if (*line == '\0')
2011 return 0;
2013 /* See if it is safe to parse commands internally. */
2014 if (shell == 0)
2015 shell = default_shell;
2016 #ifdef WINDOWS32
2017 else if (strcmp (shell, default_shell))
2019 char *s1 = _fullpath(NULL, shell, 0);
2020 char *s2 = _fullpath(NULL, default_shell, 0);
2022 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2024 if (s1);
2025 free(s1);
2026 if (s2);
2027 free(s2);
2029 if (slow_flag)
2030 goto slow;
2031 #else /* not WINDOWS32 */
2032 #ifdef __MSDOS__
2033 else if (stricmp (shell, default_shell))
2035 extern int _is_unixy_shell (const char *_path);
2037 message (1, _("$SHELL changed (was `%s', now `%s')"), default_shell, shell);
2038 unixy_shell = _is_unixy_shell (shell);
2039 default_shell = shell;
2041 if (unixy_shell)
2043 sh_chars = sh_chars_sh;
2044 sh_cmds = sh_cmds_sh;
2046 else
2048 sh_chars = sh_chars_dos;
2049 sh_cmds = sh_cmds_dos;
2051 #else /* not __MSDOS__ */
2052 else if (strcmp (shell, default_shell))
2053 goto slow;
2054 #endif /* not __MSDOS__ */
2055 #endif /* not WINDOWS32 */
2057 if (ifs != 0)
2058 for (ap = ifs; *ap != '\0'; ++ap)
2059 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2060 goto slow;
2062 i = strlen (line) + 1;
2064 /* More than 1 arg per character is impossible. */
2065 new_argv = (char **) xmalloc (i * sizeof (char *));
2067 /* All the args can fit in a buffer as big as LINE is. */
2068 ap = new_argv[0] = (char *) xmalloc (i);
2069 end = ap + i;
2071 /* I is how many complete arguments have been found. */
2072 i = 0;
2073 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2074 for (p = line; *p != '\0'; ++p)
2076 if (ap > end)
2077 abort ();
2079 if (instring)
2081 string_char:
2082 /* Inside a string, just copy any char except a closing quote
2083 or a backslash-newline combination. */
2084 if (*p == instring)
2086 instring = 0;
2087 if (ap == new_argv[0] || *(ap-1) == '\0')
2088 last_argument_was_empty = 1;
2090 else if (*p == '\\' && p[1] == '\n')
2091 goto swallow_escaped_newline;
2092 else if (*p == '\n' && restp != NULL)
2094 /* End of the command line. */
2095 *restp = p;
2096 goto end_of_line;
2098 /* Backslash, $, and ` are special inside double quotes.
2099 If we see any of those, punt.
2100 But on MSDOS, if we use COMMAND.COM, double and single
2101 quotes have the same effect. */
2102 else if (instring == '"' && index ("\\$`", *p) != 0 && unixy_shell)
2103 goto slow;
2104 else
2105 *ap++ = *p;
2107 else if (index (sh_chars, *p) != 0)
2108 /* Not inside a string, but it's a special char. */
2109 goto slow;
2110 #ifdef __MSDOS__
2111 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2112 /* `...' is a wildcard in DJGPP. */
2113 goto slow;
2114 #endif
2115 else
2116 /* Not a special char. */
2117 switch (*p)
2119 case '=':
2120 /* Equals is a special character in leading words before the
2121 first word with no equals sign in it. This is not the case
2122 with sh -k, but we never get here when using nonstandard
2123 shell flags. */
2124 if (! seen_nonequals && unixy_shell)
2125 goto slow;
2126 word_has_equals = 1;
2127 *ap++ = '=';
2128 break;
2130 case '\\':
2131 /* Backslash-newline combinations are eaten. */
2132 if (p[1] == '\n')
2134 swallow_escaped_newline:
2136 /* Eat the backslash, the newline, and following whitespace,
2137 replacing it all with a single space. */
2138 p += 2;
2140 /* If there is a tab after a backslash-newline,
2141 remove it from the source line which will be echoed,
2142 since it was most likely used to line
2143 up the continued line with the previous one. */
2144 if (*p == '\t')
2145 /* Note these overlap and strcpy() is undefined for
2146 overlapping objects in ANSI C. The strlen() _IS_ right,
2147 since we need to copy the nul byte too. */
2148 bcopy (p + 1, p, strlen (p));
2150 if (instring)
2151 goto string_char;
2152 else
2154 if (ap != new_argv[i])
2155 /* Treat this as a space, ending the arg.
2156 But if it's at the beginning of the arg, it should
2157 just get eaten, rather than becoming an empty arg. */
2158 goto end_of_arg;
2159 else
2160 p = next_token (p) - 1;
2163 else if (p[1] != '\0')
2165 #if defined(__MSDOS__) || defined(WINDOWS32)
2166 /* Only remove backslashes before characters special
2167 to Unixy shells. All other backslashes are copied
2168 verbatim, since they are probably DOS-style
2169 directory separators. This still leaves a small
2170 window for problems, but at least it should work
2171 for the vast majority of naive users. */
2173 #ifdef __MSDOS__
2174 /* A dot is only special as part of the "..."
2175 wildcard. */
2176 if (strneq (p + 1, ".\\.\\.", 5))
2178 *ap++ = '.';
2179 *ap++ = '.';
2180 p += 4;
2182 else
2183 #endif
2184 if (p[1] != '\\' && p[1] != '\'' && !isspace (p[1])
2185 && (index (sh_chars_sh, p[1]) == 0))
2186 /* back up one notch, to copy the backslash */
2187 --p;
2189 #endif /* __MSDOS__ || WINDOWS32 */
2190 /* Copy and skip the following char. */
2191 *ap++ = *++p;
2193 break;
2195 case '\'':
2196 case '"':
2197 instring = *p;
2198 break;
2200 case '\n':
2201 if (restp != NULL)
2203 /* End of the command line. */
2204 *restp = p;
2205 goto end_of_line;
2207 else
2208 /* Newlines are not special. */
2209 *ap++ = '\n';
2210 break;
2212 case ' ':
2213 case '\t':
2214 end_of_arg:
2215 /* We have the end of an argument.
2216 Terminate the text of the argument. */
2217 *ap++ = '\0';
2218 new_argv[++i] = ap;
2219 last_argument_was_empty = 0;
2221 /* Update SEEN_NONEQUALS, which tells us if every word
2222 heretofore has contained an `='. */
2223 seen_nonequals |= ! word_has_equals;
2224 if (word_has_equals && ! seen_nonequals)
2225 /* An `=' in a word before the first
2226 word without one is magical. */
2227 goto slow;
2228 word_has_equals = 0; /* Prepare for the next word. */
2230 /* If this argument is the command name,
2231 see if it is a built-in shell command.
2232 If so, have the shell handle it. */
2233 if (i == 1)
2235 register int j;
2236 for (j = 0; sh_cmds[j] != 0; ++j)
2237 if (streq (sh_cmds[j], new_argv[0]))
2238 goto slow;
2241 /* Ignore multiple whitespace chars. */
2242 p = next_token (p);
2243 /* Next iteration should examine the first nonwhite char. */
2244 --p;
2245 break;
2247 default:
2248 *ap++ = *p;
2249 break;
2252 end_of_line:
2254 if (instring)
2255 /* Let the shell deal with an unterminated quote. */
2256 goto slow;
2258 /* Terminate the last argument and the argument list. */
2260 *ap = '\0';
2261 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2262 ++i;
2263 new_argv[i] = 0;
2265 if (i == 1)
2267 register int j;
2268 for (j = 0; sh_cmds[j] != 0; ++j)
2269 if (streq (sh_cmds[j], new_argv[0]))
2270 goto slow;
2273 if (new_argv[0] == 0)
2274 /* Line was empty. */
2275 return 0;
2276 else
2277 return new_argv;
2279 slow:;
2280 /* We must use the shell. */
2282 if (new_argv != 0)
2284 /* Free the old argument list we were working on. */
2285 free (new_argv[0]);
2286 free ((void *)new_argv);
2289 #ifdef __MSDOS__
2290 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2291 #endif
2293 #ifdef _AMIGA
2295 char *ptr;
2296 char *buffer;
2297 char *dptr;
2299 buffer = (char *)xmalloc (strlen (line)+1);
2301 ptr = line;
2302 for (dptr=buffer; *ptr; )
2304 if (*ptr == '\\' && ptr[1] == '\n')
2305 ptr += 2;
2306 else if (*ptr == '@') /* Kludge: multiline commands */
2308 ptr += 2;
2309 *dptr++ = '\n';
2311 else
2312 *dptr++ = *ptr++;
2314 *dptr = 0;
2316 new_argv = (char **) xmalloc (2 * sizeof (char *));
2317 new_argv[0] = buffer;
2318 new_argv[1] = 0;
2320 #else /* Not Amiga */
2321 #ifdef WINDOWS32
2323 * Not eating this whitespace caused things like
2325 * sh -c "\n"
2327 * which gave the shell fits. I think we have to eat
2328 * whitespace here, but this code should be considered
2329 * suspicious if things start failing....
2332 /* Make sure not to bother processing an empty line. */
2333 while (isspace (*line))
2334 ++line;
2335 if (*line == '\0')
2336 return 0;
2337 #endif /* WINDOWS32 */
2339 /* SHELL may be a multi-word command. Construct a command line
2340 "SHELL -c LINE", with all special chars in LINE escaped.
2341 Then recurse, expanding this command line to get the final
2342 argument list. */
2344 unsigned int shell_len = strlen (shell);
2345 static char minus_c[] = " -c ";
2346 unsigned int line_len = strlen (line);
2348 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2349 + (line_len * 2) + 1);
2350 char* command_ptr = NULL; /* used for batch_mode_shell mode */
2352 ap = new_line;
2353 bcopy (shell, ap, shell_len);
2354 ap += shell_len;
2355 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2356 ap += sizeof (minus_c) - 1;
2357 command_ptr = ap;
2358 for (p = line; *p != '\0'; ++p)
2360 if (restp != NULL && *p == '\n')
2362 *restp = p;
2363 break;
2365 else if (*p == '\\' && p[1] == '\n')
2367 /* Eat the backslash, the newline, and following whitespace,
2368 replacing it all with a single space (which is escaped
2369 from the shell). */
2370 p += 2;
2372 /* If there is a tab after a backslash-newline,
2373 remove it from the source line which will be echoed,
2374 since it was most likely used to line
2375 up the continued line with the previous one. */
2376 if (*p == '\t')
2377 bcopy (p + 1, p, strlen (p));
2379 p = next_token (p);
2380 --p;
2381 if (unixy_shell && !batch_mode_shell)
2382 *ap++ = '\\';
2383 *ap++ = ' ';
2384 continue;
2387 /* DOS shells don't know about backslash-escaping. */
2388 if (unixy_shell && !batch_mode_shell &&
2389 (*p == '\\' || *p == '\'' || *p == '"'
2390 || isspace (*p)
2391 || index (sh_chars, *p) != 0))
2392 *ap++ = '\\';
2393 #ifdef __MSDOS__
2394 else if (unixy_shell && strneq (p, "...", 3))
2396 /* The case of `...' wildcard again. */
2397 strcpy (ap, "\\.\\.\\");
2398 ap += 5;
2399 p += 2;
2401 #endif
2402 *ap++ = *p;
2404 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2405 /* Line was empty. */
2406 return 0;
2407 *ap = '\0';
2409 #ifdef WINDOWS32
2410 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2411 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2412 cases, run commands via a script file. */
2413 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2414 FILE* batch = NULL;
2415 int id = GetCurrentProcessId();
2416 PATH_VAR(fbuf);
2417 char* fname = NULL;
2419 /* create a file name */
2420 sprintf(fbuf, "make%d", id);
2421 fname = tempnam(".", fbuf);
2423 /* create batch file name */
2424 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
2425 strcpy(*batch_filename_ptr, fname);
2427 /* make sure path name is in DOS backslash format */
2428 if (!unixy_shell) {
2429 fname = *batch_filename_ptr;
2430 for (i = 0; fname[i] != '\0'; ++i)
2431 if (fname[i] == '/')
2432 fname[i] = '\\';
2433 strcat(*batch_filename_ptr, ".bat");
2434 } else {
2435 strcat(*batch_filename_ptr, ".sh");
2438 if (debug_flag)
2439 printf(_("Creating temporary batch file %s\n"), *batch_filename_ptr);
2441 /* create batch file to execute command */
2442 batch = fopen (*batch_filename_ptr, "w");
2443 if (!unixy_shell)
2444 fputs ("@echo off\n", batch);
2445 fputs (command_ptr, batch);
2446 fputc ('\n', batch);
2447 fclose (batch);
2449 /* create argv */
2450 new_argv = (char **) xmalloc(3 * sizeof(char *));
2451 if (unixy_shell) {
2452 new_argv[0] = xstrdup (shell);
2453 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2454 } else {
2455 new_argv[0] = xstrdup (*batch_filename_ptr);
2456 new_argv[1] = NULL;
2458 new_argv[2] = NULL;
2459 } else
2460 #endif /* WINDOWS32 */
2461 if (unixy_shell)
2462 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2463 (char *) 0, (char *) 0,
2464 (char *) 0);
2465 #ifdef __MSDOS__
2466 else
2468 /* With MSDOS shells, we must construct the command line here
2469 instead of recursively calling ourselves, because we
2470 cannot backslash-escape the special characters (see above). */
2471 new_argv = (char **) xmalloc (sizeof (char *));
2472 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2473 new_argv[0] = xmalloc (line_len + 1);
2474 strncpy (new_argv[0],
2475 new_line + shell_len + sizeof (minus_c) - 1, line_len);
2476 new_argv[0][line_len] = '\0';
2478 #else
2479 else
2480 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2481 __FILE__, __LINE__);
2482 #endif
2484 #endif /* ! AMIGA */
2486 return new_argv;
2489 /* Figure out the argument list necessary to run LINE as a command. Try to
2490 avoid using a shell. This routine handles only ' quoting, and " quoting
2491 when no backslash, $ or ` characters are seen in the quotes. Starting
2492 quotes may be escaped with a backslash. If any of the characters in
2493 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2494 is the first word of a line, the shell is used.
2496 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2497 If *RESTP is NULL, newlines will be ignored.
2499 FILE is the target whose commands these are. It is used for
2500 variable expansion for $(SHELL) and $(IFS). */
2502 char **
2503 construct_command_argv (line, restp, file, batch_filename_ptr)
2504 char *line, **restp;
2505 struct file *file;
2506 char** batch_filename_ptr;
2508 char *shell, *ifs;
2509 char **argv;
2512 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2513 int save = warn_undefined_variables_flag;
2514 warn_undefined_variables_flag = 0;
2516 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
2517 #ifdef WINDOWS32
2519 * Convert to forward slashes so that construct_command_argv_internal()
2520 * is not confused.
2522 if (shell) {
2523 char *p = w32ify(shell, 0);
2524 strcpy(shell, p);
2526 #endif
2527 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
2529 warn_undefined_variables_flag = save;
2532 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
2534 free (shell);
2535 free (ifs);
2537 return argv;
2539 #endif /* !VMS */
2541 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2543 dup2 (old, new)
2544 int old, new;
2546 int fd;
2548 (void) close (new);
2549 fd = dup (old);
2550 if (fd != new)
2552 (void) close (fd);
2553 errno = EMFILE;
2554 return -1;
2557 return fd;
2559 #endif /* !HAPE_DUP2 && !_AMIGA */