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)
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. */
27 /* Default shell to use. */
29 char *default_shell
= "sh.exe";
30 int no_default_sh_exe
= 1;
31 int batch_mode_shell
= 1;
34 char default_shell
[] = "";
35 extern int MyExecute (char **);
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;
48 #endif /* WINDOWS32 */
52 static int execute_by_shell
;
53 static int dos_pid
= 123;
55 int dos_command_running
;
56 #endif /* __MSDOS__ */
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
;
68 # include <processes.h>
70 # include <lib$routines.h>
77 # include "sub_proc.h"
79 # include "pathstuff.h"
80 #endif /* WINDOWS32 */
85 # include <sys/file.h>
88 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
89 # include <sys/wait.h>
93 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
94 #else /* Don't have waitpid. */
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)
107 #ifndef HAVE_UNION_WAIT
112 # define WTERMSIG(x) ((x) & 0x7f)
115 # define WCOREDUMP(x) ((x) & 0x80)
118 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
121 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
124 # define WIFEXITED(x) (WTERMSIG (x) == 0)
127 #else /* Have `union wait'. */
129 # define WAIT_T union wait
131 # define WTERMSIG(x) ((x).w_termsig)
134 # define WCOREDUMP(x) ((x).w_coredump)
137 # define WEXITSTATUS(x) ((x).w_retcode)
140 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
143 # define WIFEXITED(x) (WTERMSIG(x) == 0)
146 #endif /* Don't have `union wait'. */
148 /* How to set close-on-exec for a file descriptor. */
151 # define CLOSE_ON_EXEC(_d)
154 # define FD_CLOEXEC 1
156 # define CLOSE_ON_EXEC(_d) (void) fcntl ((_d), F_SETFD, FD_CLOEXEC)
160 static int vms_jobsefnmask
= 0;
163 #ifndef HAVE_UNISTD_H
165 extern int execve ();
166 extern void _exit ();
168 extern int geteuid ();
169 extern int getegid ();
170 extern int setgid ();
171 extern int getgid ();
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
*));
190 static void vmsWaitForChildren
PARAMS ((int *));
193 /* Chain of all live (or recently deceased) children. */
195 struct child
*children
= 0;
197 /* Number of children currently running. */
199 unsigned int job_slots_used
= 0;
201 /* Nonzero if the `good' standard input is in use. */
203 static int good_stdin_used
= 0;
205 /* Specifies whether the current process's reserved job token is in use.
206 '+' means it's available, '-' means it isn't. */
208 static char my_job_token
= '+';
210 /* Chain of children waiting to run until the load average goes down. */
212 static struct child
*waiting_jobs
= 0;
214 /* Non-zero if we use a *real* shell (always so on Unix). */
218 /* #define debug_flag 1 */
223 * The macro which references this function is defined in make.h.
225 int w32_kill(int pid
, int sig
)
227 return ((process_kill(pid
, sig
) == TRUE
) ? 0 : -1);
229 #endif /* WINDOWS32 */
233 free_job_token (child
)
236 switch (child
->job_token
)
239 /* If this child doesn't have a token, punt. */
243 /* If this child has the reserved token, take it back. */
248 /* Write any other job tokens back to the pipe. */
249 while (write (job_fds
[1], &child
->job_token
, 1) != 1)
251 pfatal_with_name(_("write jobserver"));
256 printf (_("Released token `%c' for child 0x%08lx (%s).\n"),
257 child
->job_token
, (unsigned long int) child
, child
->file
->name
);
259 child
->job_token
= '-';
263 /* Write an error message describing the exit status given in
264 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
265 Append "(ignored)" if IGNORED is nonzero. */
268 child_error (target_name
, exit_code
, exit_sig
, coredump
, ignored
)
270 int exit_code
, exit_sig
, coredump
;
273 if (ignored
&& silent_flag
)
277 if (!(exit_code
& 1))
278 error (NILF
, _("*** [%s] Error 0x%x%s"), target_name
, exit_code
, ((ignored
)? _(" (ignored)") : ""));
281 error (NILF
, ignored
? _("[%s] Error %d (ignored)") :
282 _("*** [%s] Error %d"),
283 target_name
, exit_code
);
285 error (NILF
, "*** [%s] %s%s",
286 target_name
, strsignal (exit_sig
),
287 coredump
? _(" (core dumped)") : "");
292 /* Wait for nchildren children to terminate */
294 vmsWaitForChildren(int *status
)
298 if (!vms_jobsefnmask
)
304 *status
= sys$
wflor (32, vms_jobsefnmask
);
311 /* Handle a dead child. This handler may or may not ever be installed.
313 If we're using the jobserver feature, we need it. First, installing it
314 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
315 read FD to ensure we don't enter another blocking read without reaping all
316 the dead children. In this case we don't need the dead_children count.
318 If we don't have either waitpid or wait3, then make is unreliable, but we
319 use the dead_children count to reap children as best we can. */
321 static unsigned int dead_children
= 0;
329 #ifdef HAVE_JOBSERVER
338 printf (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children
);
342 extern int shell_function_pid
, shell_function_completed
;
344 /* Reap all dead children, storing the returned status and the new command
345 state (`cs_finished') in the `file' member of the `struct child' for the
346 dead child, and removing the child from the chain. In addition, if BLOCK
347 nonzero, we block in this function until we've reaped at least one
348 complete child, waiting for it to die if necessary. If ERR is nonzero,
349 print an error message first. */
352 reap_children (block
, err
)
357 /* Initially, assume we have some. */
359 # define REAP_MORE reap_more
361 # define REAP_MORE dead_children
364 while ((children
!= 0 || shell_function_pid
!= 0) &&
365 (block
|| REAP_MORE
))
369 int exit_code
, exit_sig
, coredump
;
370 register struct child
*lastc
, *c
;
372 int any_remote
, any_local
;
376 /* We might block for a while, so let the user know why. */
378 error (NILF
, _("*** Waiting for unfinished jobs...."));
381 /* We have one less dead child to reap. As noted in
382 child_handler() above, this count is completely unimportant for
383 all modern, POSIX-y systems that support wait3() or waitpid().
384 The rest of this comment below applies only to early, broken
385 pre-POSIX systems. We keep the count only because... it's there...
387 The test and decrement are not atomic; if it is compiled into:
388 register = dead_children - 1;
389 dead_children = register;
390 a SIGCHLD could come between the two instructions.
391 child_handler increments dead_children.
392 The second instruction here would lose that increment. But the
393 only effect of dead_children being wrong is that we might wait
394 longer than necessary to reap a child, and lose some parallelism;
395 and we might print the "Waiting for unfinished jobs" message above
396 when not necessary. */
398 if (dead_children
> 0)
402 any_local
= shell_function_pid
!= 0;
403 for (c
= children
; c
!= 0; c
= c
->next
)
405 any_remote
|= c
->remote
;
406 any_local
|= ! c
->remote
;
408 printf (_("Live child 0x%08lx (%s) PID %ld token %c%s\n"),
409 (unsigned long int) c
, c
->file
->name
,
410 (long) c
->pid
, c
->job_token
,
411 c
->remote
? _(" (remote)") : "");
417 /* First, check for remote children. */
419 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 0);
424 /* We got a remote child. */
428 /* A remote status command failed miserably. Punt. */
433 pfatal_with_name ("remote_status");
437 /* No remote children. Check for local children. */
438 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
443 vmsWaitForChildren (&status
);
448 pid
= WAIT_NOHANG (&status
);
451 pid
= wait (&status
);
459 /* The wait*() failed miserably. Punt. */
463 pfatal_with_name ("wait");
467 /* We got a child exit; chop the status word up. */
468 exit_code
= WEXITSTATUS (status
);
469 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
470 coredump
= WCOREDUMP (status
);
474 /* No local children are dead. */
478 if (block
&& any_remote
)
480 /* Now try a blocking wait for a remote child. */
481 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 1);
483 goto remote_status_lose
;
485 /* No remote children either. Finally give up. */
488 /* We got a remote child. */
494 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
496 /* Life is very different on MSDOS. */
499 exit_code
= WEXITSTATUS (status
);
500 if (exit_code
== 0xff)
502 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
504 #endif /* __MSDOS__ */
508 status
= amiga_status
;
509 exit_code
= amiga_status
;
518 /* wait for anything to finish */
519 if (hPID
= process_wait_for_any()) {
521 /* was an error found on this process? */
522 err
= process_last_err(hPID
);
525 exit_code
= process_exit_code(hPID
);
528 fprintf(stderr
, "make (e=%d): %s",
529 exit_code
, map_windows32_error_to_string(exit_code
));
532 exit_sig
= process_signal(hPID
);
534 /* cleanup process */
535 process_cleanup(hPID
);
541 #endif /* WINDOWS32 */
544 /* Check if this is the child of the `shell' function. */
545 if (!remote
&& pid
== shell_function_pid
)
547 /* It is. Leave an indicator for the `shell' function. */
548 if (exit_sig
== 0 && exit_code
== 127)
549 shell_function_completed
= -1;
551 shell_function_completed
= 1;
555 child_failed
= exit_sig
!= 0 || exit_code
!= 0;
557 /* Search for a child matching the deceased one. */
559 for (c
= children
; c
!= 0; lastc
= c
, c
= c
->next
)
560 if (c
->remote
== remote
&& c
->pid
== pid
)
564 /* An unknown child died.
565 Ignore it; it was inherited from our invoker. */
569 printf (_("Reaping %s child 0x%08lx PID %ld token %c%s\n"),
570 child_failed
? _("losing") : _("winning"),
571 (unsigned long int) c
, (long) c
->pid
, c
->job_token
,
572 c
->remote
? _(" (remote)") : "");
574 if (c
->sh_batch_file
) {
576 printf (_("Cleaning up temp batch file %s\n"), c
->sh_batch_file
);
578 /* just try and remove, don't care if this fails */
579 remove (c
->sh_batch_file
);
581 /* all done with memory */
582 free (c
->sh_batch_file
);
583 c
->sh_batch_file
= NULL
;
586 /* If this child had the good stdin, say it is now free. */
590 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
592 /* The commands failed. Write an error message,
593 delete non-precious targets, and abort. */
594 static int delete_on_error
= -1;
595 child_error (c
->file
->name
, exit_code
, exit_sig
, coredump
, 0);
596 c
->file
->update_status
= 2;
597 if (delete_on_error
== -1)
599 struct file
*f
= lookup_file (".DELETE_ON_ERROR");
600 delete_on_error
= f
!= 0 && f
->is_target
;
602 if (exit_sig
!= 0 || delete_on_error
)
603 delete_child_targets (c
);
609 /* The commands failed, but we don't care. */
610 child_error (c
->file
->name
,
611 exit_code
, exit_sig
, coredump
, 1);
615 /* If there are more commands to run, try to start them. */
616 if (job_next_command (c
))
618 if (handling_fatal_signal
)
620 /* Never start new commands while we are dying.
621 Since there are more commands that wanted to be run,
622 the target was not completely remade. So we treat
623 this as if a command had failed. */
624 c
->file
->update_status
= 2;
628 /* Check again whether to start remotely.
629 Whether or not we want to changes over time.
630 Also, start_remote_job may need state set up
631 by start_remote_job_p. */
632 c
->remote
= start_remote_job_p (0);
633 start_job_command (c
);
634 /* Fatal signals are left blocked in case we were
635 about to put that child on the chain. But it is
636 already there, so it is safe for a fatal signal to
637 arrive now; it will clean up this child's targets. */
639 if (c
->file
->command_state
== cs_running
)
640 /* We successfully started the new command.
641 Loop to reap more children. */
645 if (c
->file
->update_status
!= 0)
646 /* We failed to start the commands. */
647 delete_child_targets (c
);
650 /* There are no more commands. We got through them all
651 without an unignored error. Now the target has been
652 successfully updated. */
653 c
->file
->update_status
= 0;
656 /* When we get here, all the commands for C->file are finished
657 (or aborted) and C->file->update_status contains 0 or 2. But
658 C->file->command_state is still cs_running if all the commands
659 ran; notice_finish_file looks for cs_running to tell it that
660 it's interesting to check the file's modtime again now. */
662 if (! handling_fatal_signal
)
663 /* Notice if the target of the commands has been changed.
664 This also propagates its values for command_state and
665 update_status to its also_make files. */
666 notice_finished_file (c
->file
);
669 printf (_("Removing child 0x%08lx PID %ld token %c%s from chain.\n"),
670 (unsigned long int) c
, (long) c
->pid
, c
->job_token
,
671 c
->remote
? _(" (remote)") : "");
673 /* Block fatal signals while frobnicating the list, so that
674 children and job_slots_used are always consistent. Otherwise
675 a fatal signal arriving after the child is off the chain and
676 before job_slots_used is decremented would believe a child was
677 live and call reap_children again. */
680 /* If this job has a token out, return it. */
683 /* There is now another slot open. */
684 if (job_slots_used
> 0)
687 /* Remove the child from the chain and free it. */
691 lastc
->next
= c
->next
;
692 if (! handling_fatal_signal
) /* Don't bother if about to die. */
697 /* If the job failed, and the -k flag was not given, die,
698 unless we are already in the process of dying. */
699 if (!err
&& child_failed
&& !keep_going_flag
&&
700 /* fatal_error_signal will die with the right signal. */
701 !handling_fatal_signal
)
704 /* Only block for one child. */
711 /* Free the storage allocated for CHILD. */
715 register struct child
*child
;
717 if (child
->command_lines
!= 0)
719 register unsigned int i
;
720 for (i
= 0; i
< child
->file
->cmds
->ncommand_lines
; ++i
)
721 free (child
->command_lines
[i
]);
722 free ((char *) child
->command_lines
);
725 if (child
->environment
!= 0)
727 register char **ep
= child
->environment
;
730 free ((char *) child
->environment
);
733 /* If this child has a token it hasn't relinquished, give it up now.
734 This can happen if the job completes immediately, mainly because
735 all the command lines evaluated to empty strings. */
736 free_job_token(child
);
738 free ((char *) child
);
742 extern sigset_t fatal_signal_set
;
749 (void) sigprocmask (SIG_BLOCK
, &fatal_signal_set
, (sigset_t
*) 0);
751 # ifdef HAVE_SIGSETMASK
752 (void) sigblock (fatal_signal_mask
);
762 sigemptyset (&empty
);
763 sigprocmask (SIG_SETMASK
, &empty
, (sigset_t
*) 0);
767 /* Start a job to run the commands specified in CHILD.
768 CHILD is updated to reflect the commands and ID of the child process.
770 NOTE: On return fatal signals are blocked! The caller is responsible
771 for calling `unblock_sigs', once the new child is safely on the chain so
772 it can be cleaned up in the event of a fatal signal. */
775 start_job_command (child
)
776 register struct child
*child
;
779 static int bad_stdin
= -1;
789 /* If we have a completely empty commandset, stop now. */
790 if (!child
->command_ptr
)
793 /* Combine the flags parsed for the line itself with
794 the flags specified globally for this target. */
795 flags
= (child
->file
->command_flags
796 | child
->file
->cmds
->lines_flags
[child
->command_line
- 1]);
798 p
= child
->command_ptr
;
799 child
->noerror
= flags
& COMMANDS_NOERROR
;
804 flags
|= COMMANDS_SILENT
;
806 flags
|= COMMANDS_RECURSE
;
809 else if (!isblank (*p
))
814 /* If -q was given, just say that updating `failed'. The exit status of
815 1 tells the user that -q is saying `something to do'; the exit status
816 for a random error is 2. */
817 if (question_flag
&& !(flags
& COMMANDS_RECURSE
))
819 child
->file
->update_status
= 1;
820 notice_finished_file (child
->file
);
824 /* There may be some preceding whitespace left if there
825 was nothing but a backslash on the first line. */
828 /* Figure out an argument list from this command line. */
835 argv
= construct_command_argv (p
, &end
, child
->file
, &child
->sh_batch_file
);
838 child
->command_ptr
= NULL
;
842 child
->command_ptr
= end
;
846 if (touch_flag
&& !(flags
& COMMANDS_RECURSE
))
848 /* Go on to the next command. It might be the recursive one.
849 We construct ARGV only to find the end of the command line. */
852 free ((char *) argv
);
861 execute_by_shell
= 0; /* in case construct_command_argv sets it */
863 /* This line has no commands. Go to the next. */
864 if (job_next_command (child
))
865 start_job_command (child
);
868 /* No more commands. Make sure we're "running"; we might not be if
869 (e.g.) all commands were skipped due to -n. */
870 set_command_state (child
->file
, cs_running
);
871 child
->file
->update_status
= 0;
872 notice_finished_file (child
->file
);
877 /* Print out the command. If silent, we call `message' with null so it
878 can log the working directory before the command's own error messages
881 message (0, (just_print_flag
|| (!(flags
& COMMANDS_SILENT
) && !silent_flag
))
882 ? "%s" : (char *) 0, p
);
884 /* Optimize an empty command. People use this for timestamp rules,
885 and forking a useless shell all the time leads to inefficiency. */
887 #if !defined(VMS) && !defined(_AMIGA)
890 unixy_shell
/* the test is complicated and we already did it */
892 (argv
[0] && !strcmp(argv
[0], "/bin/sh"))
894 && (argv
[1] && !strcmp(argv
[1], "-c"))
895 && (argv
[2] && !strcmp(argv
[2], ":"))
899 free ((char *) argv
);
902 #endif /* !VMS && !_AMIGA */
904 /* Tell update_goal_chain that a command has been started on behalf of
905 this target. It is important that this happens here and not in
906 reap_children (where we used to do it), because reap_children might be
907 reaping children from a different target. We want this increment to
908 guaranteedly indicate that a command was started for the dependency
909 chain (i.e., update_file recursion chain) we are processing. */
913 /* If -n was given, recurse to get the next line in the sequence. */
915 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
))
919 free ((char *) argv
);
924 /* Flush the output streams so they won't have things written twice. */
930 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
932 /* Set up a bad standard input that reads from a broken pipe. */
936 /* Make a file descriptor that is the read end of a broken pipe.
937 This will be used for some children's standard inputs. */
941 /* Close the write side. */
942 (void) close (pd
[1]);
943 /* Save the read side. */
946 /* Set the descriptor to close on exec, so it does not litter any
947 child's descriptor table. When it is dup2'd onto descriptor 0,
948 that descriptor will not close on exec. */
949 CLOSE_ON_EXEC (bad_stdin
);
953 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
955 /* Decide whether to give this child the `good' standard input
956 (one that points to the terminal or whatever), or the `bad' one
957 that points to the read side of a broken pipe. */
959 child
->good_stdin
= !good_stdin_used
;
960 if (child
->good_stdin
)
968 /* Set up the environment for the child. */
969 if (child
->environment
== 0)
970 child
->environment
= target_environment (child
->file
);
973 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
976 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
979 int is_remote
, id
, used_stdin
;
980 if (start_remote_job (argv
, child
->environment
,
981 child
->good_stdin
? 0 : bad_stdin
,
982 &is_remote
, &id
, &used_stdin
))
983 /* Don't give up; remote execution may fail for various reasons. If
984 so, simply run the job locally. */
988 if (child
->good_stdin
&& !used_stdin
)
990 child
->good_stdin
= 0;
993 child
->remote
= is_remote
;
1000 /* Fork the child process. */
1002 char **parent_environ
;
1011 if (!child_execute_job (argv
, child
)) {
1013 perror_with_name ("vfork", "");
1019 parent_environ
= environ
;
1020 child
->pid
= vfork ();
1021 environ
= parent_environ
; /* Restore value child may have clobbered. */
1022 if (child
->pid
== 0)
1024 /* We are the child side. */
1027 /* If we aren't running a recursive command and we have a jobserver
1028 pipe, close it before exec'ing. */
1029 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1037 child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1038 argv
, child
->environment
);
1040 else if (child
->pid
< 0)
1044 perror_with_name ("vfork", "");
1050 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1058 /* We call `system' to do the job of the SHELL, since stock DOS
1059 shell is too dumb. Our `system' knows how to handle long
1060 command lines even if pipes/redirection is needed; it will only
1061 call COMMAND.COM when its internal commands are used. */
1062 if (execute_by_shell
)
1064 char *cmdline
= argv
[0];
1065 /* We don't have a way to pass environment to `system',
1066 so we need to save and restore ours, sigh... */
1067 char **parent_environ
= environ
;
1069 environ
= child
->environment
;
1071 /* If we have a *real* shell, tell `system' to call
1072 it to do everything for us. */
1075 /* A *real* shell on MSDOS may not support long
1076 command lines the DJGPP way, so we must use `system'. */
1077 cmdline
= argv
[2]; /* get past "shell -c" */
1080 dos_command_running
= 1;
1081 proc_return
= system (cmdline
);
1082 environ
= parent_environ
;
1083 execute_by_shell
= 0; /* for the next time */
1087 dos_command_running
= 1;
1088 proc_return
= spawnvpe (P_WAIT
, argv
[0], argv
, child
->environment
);
1091 /* Need to unblock signals before turning off
1092 dos_command_running, so that child's signals
1093 will be treated as such (see fatal_error_signal). */
1095 dos_command_running
= 0;
1097 /* If the child got a signal, dos_status has its
1098 high 8 bits set, so be careful not to alter them. */
1099 if (proc_return
== -1)
1102 dos_status
|= (proc_return
& 0xff);
1104 child
->pid
= dos_pid
++;
1106 #endif /* __MSDOS__ */
1108 amiga_status
= MyExecute (argv
);
1111 child
->pid
= amiga_pid
++;
1112 if (amiga_batch_file
)
1114 amiga_batch_file
= 0;
1115 DeleteFile (amiga_bname
); /* Ignore errors. */
1123 /* make UNC paths safe for CreateProcess -- backslash format */
1125 if (arg0
&& arg0
[0] == '/' && arg0
[1] == '/')
1126 for ( ; arg0
&& *arg0
; arg0
++)
1130 /* make sure CreateProcess() has Path it needs */
1131 sync_Path_environment();
1133 hPID
= process_easy(argv
, child
->environment
);
1135 if (hPID
!= INVALID_HANDLE_VALUE
)
1136 child
->pid
= (int) hPID
;
1141 _("process_easy() failed failed to launch process (e=%d)\n"),
1142 process_last_err(hPID
));
1143 for (i
= 0; argv
[i
]; i
++)
1144 fprintf(stderr
, "%s ", argv
[i
]);
1145 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
1148 #endif /* WINDOWS32 */
1149 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1151 /* We are the parent side. Set the state to
1152 say the commands are running and return. */
1154 set_command_state (child
->file
, cs_running
);
1156 /* Free the storage used by the child's argument list. */
1159 free ((char *) argv
);
1165 child
->file
->update_status
= 2;
1166 notice_finished_file (child
->file
);
1170 /* Try to start a child running.
1171 Returns nonzero if the child was started (and maybe finished), or zero if
1172 the load was too high and the child was put on the `waiting_jobs' chain. */
1175 start_waiting_job (c
)
1178 struct file
*f
= c
->file
;
1180 /* If we can start a job remotely, we always want to, and don't care about
1181 the local load average. We record that the job should be started
1182 remotely in C->remote for start_job_command to test. */
1184 c
->remote
= start_remote_job_p (1);
1186 /* If we are running at least one job already and the load average
1187 is too high, make this one wait. */
1188 if (!c
->remote
&& job_slots_used
> 0 && load_too_high ())
1190 /* Put this child on the chain of children waiting for the load average
1192 set_command_state (f
, cs_running
);
1193 c
->next
= waiting_jobs
;
1198 /* Start the first command; reap_children will run later command lines. */
1199 start_job_command (c
);
1201 switch (f
->command_state
)
1206 printf (_("Putting child 0x%08lx (%s) PID %ld token %c%s on the chain.\n"),
1207 (unsigned long int) c
, c
->file
->name
,
1208 (long) c
->pid
, c
->job_token
,
1209 c
->remote
? _(" (remote)") : "");
1211 /* One more job slot is in use. */
1216 case cs_not_started
:
1217 /* All the command lines turned out to be empty. */
1218 f
->update_status
= 0;
1222 notice_finished_file (f
);
1227 assert (f
->command_state
== cs_finished
);
1234 /* Create a `struct child' for FILE and start its commands running. */
1238 register struct file
*file
;
1240 register struct commands
*cmds
= file
->cmds
;
1241 register struct child
*c
;
1243 register unsigned int i
;
1245 /* Let any previously decided-upon jobs that are waiting
1246 for the load to go down start before this new one. */
1247 start_waiting_jobs ();
1249 /* Reap any children that might have finished recently. */
1250 reap_children (0, 0);
1252 /* Chop the commands up into lines if they aren't already. */
1253 chop_commands (cmds
);
1255 /* Expand the command lines and store the results in LINES. */
1256 lines
= (char **) xmalloc (cmds
->ncommand_lines
* sizeof (char *));
1257 for (i
= 0; i
< cmds
->ncommand_lines
; ++i
)
1259 /* Collapse backslash-newline combinations that are inside variable
1260 or function references. These are left alone by the parser so
1261 that they will appear in the echoing of commands (where they look
1262 nice); and collapsed by construct_command_argv when it tokenizes.
1263 But letting them survive inside function invocations loses because
1264 we don't want the functions to see them as part of the text. */
1266 char *in
, *out
, *ref
;
1268 /* IN points to where in the line we are scanning.
1269 OUT points to where in the line we are writing.
1270 When we collapse a backslash-newline combination,
1271 IN gets ahead of OUT. */
1273 in
= out
= cmds
->command_lines
[i
];
1274 while ((ref
= index (in
, '$')) != 0)
1276 ++ref
; /* Move past the $. */
1279 /* Copy the text between the end of the last chunk
1280 we processed (where IN points) and the new chunk
1281 we are about to process (where REF points). */
1282 bcopy (in
, out
, ref
- in
);
1284 /* Move both pointers past the boring stuff. */
1288 if (*ref
== '(' || *ref
== '{')
1290 char openparen
= *ref
;
1291 char closeparen
= openparen
== '(' ? ')' : '}';
1295 *out
++ = *in
++; /* Copy OPENPAREN. */
1296 /* IN now points past the opening paren or brace.
1297 Count parens or braces until it is matched. */
1301 if (*in
== closeparen
&& --count
< 0)
1303 else if (*in
== '\\' && in
[1] == '\n')
1305 /* We have found a backslash-newline inside a
1306 variable or function reference. Eat it and
1307 any following whitespace. */
1310 for (p
= in
- 1; p
> ref
&& *p
== '\\'; --p
)
1314 /* There were two or more backslashes, so this is
1315 not really a continuation line. We don't collapse
1316 the quoting backslashes here as is done in
1317 collapse_continuations, because the line will
1318 be collapsed again after expansion. */
1322 /* Skip the backslash, newline and
1323 any following whitespace. */
1324 in
= next_token (in
+ 2);
1326 /* Discard any preceding whitespace that has
1327 already been written to the output. */
1328 while (out
> ref
&& isblank (out
[-1]))
1331 /* Replace it all with a single space. */
1337 if (*in
== openparen
)
1346 /* There are no more references in this line to worry about.
1347 Copy the remaining uninteresting text to the output. */
1351 /* Finally, expand the line. */
1352 lines
[i
] = allocated_variable_expand_for_file (cmds
->command_lines
[i
],
1356 /* Start the command sequence, record it in a new
1357 `struct child', and add that to the chain. */
1359 c
= (struct child
*) xmalloc (sizeof (struct child
));
1361 c
->command_lines
= lines
;
1362 c
->command_line
= 0;
1365 c
->sh_batch_file
= NULL
;
1368 /* Fetch the first command line to be run. */
1369 job_next_command (c
);
1371 /* Wait for a job slot to be freed up. If we allow an infinite number
1372 don't bother; also job_slots will == 0 if we're using the jobserver. */
1374 while (job_slots_used
== job_slots
)
1375 reap_children (1, 0);
1376 #ifdef MAKE_JOBSERVER
1377 /* If we are controlling multiple jobs, and we don't yet have one,
1378 obtain a token before starting the child. */
1379 else if (job_fds
[0] >= 0)
1381 while (c
->job_token
== '-')
1382 /* If the reserved token is available, just use that. */
1383 if (my_job_token
== '+')
1385 c
->job_token
= my_job_token
;
1388 /* Read a token. As long as there's no token available we'll block.
1389 If we get a SIGCHLD we'll return with EINTR. If one happened
1390 before we got here we'll return immediately with EBADF because
1391 the signal handler closes the dup'd file descriptor. */
1392 else if (read (job_rfd
, &c
->job_token
, 1) < 1)
1394 if (errno
!= EINTR
&& errno
!= EBADF
)
1395 pfatal_with_name (_("read jobs pipe"));
1397 /* Re-dup the read side of the pipe, so the signal handler can
1398 notify us if we miss a child. */
1400 job_rfd
= dup (job_fds
[0]);
1402 /* Something's done. We don't want to block for a whole child,
1403 just reap whatever's there. */
1404 reap_children (0, 0);
1407 assert(c
->job_token
!= '-');
1409 printf (_("Obtained token `%c' for child 0x%08lx (%s).\n"),
1410 c
->job_token
, (unsigned long int) c
, c
->file
->name
);
1414 /* The job is now primed. Start it running.
1415 (This will notice if there are in fact no commands.) */
1416 (void)start_waiting_job (c
);
1419 /* Since there is only one job slot, make things run linearly.
1420 Wait for the child to die, setting the state to `cs_finished'. */
1421 while (file
->command_state
== cs_running
)
1422 reap_children (1, 0);
1427 /* Move CHILD's pointers to the next command for it to execute.
1428 Returns nonzero if there is another command. */
1431 job_next_command (child
)
1432 struct child
*child
;
1434 while (child
->command_ptr
== 0 || *child
->command_ptr
== '\0')
1436 /* There are no more lines in the expansion of this line. */
1437 if (child
->command_line
== child
->file
->cmds
->ncommand_lines
)
1439 /* There are no more lines to be expanded. */
1440 child
->command_ptr
= 0;
1444 /* Get the next line to run. */
1445 child
->command_ptr
= child
->command_lines
[child
->command_line
++];
1453 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1458 if (max_load_average
< 0)
1462 if (getloadavg (&load
, 1) != 1)
1464 static int lossage
= -1;
1465 /* Complain only once for the same error. */
1466 if (lossage
== -1 || errno
!= lossage
)
1469 /* An errno value of zero means getloadavg is just unsupported. */
1470 error (NILF
, _("cannot enforce load limits on this operating system"));
1472 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1479 return load
>= max_load_average
;
1483 /* Start jobs that are waiting for the load to be lower. */
1486 start_waiting_jobs ()
1490 if (waiting_jobs
== 0)
1495 /* Check for recently deceased descendants. */
1496 reap_children (0, 0);
1498 /* Take a job off the waiting list. */
1500 waiting_jobs
= job
->next
;
1502 /* Try to start that job. We break out of the loop as soon
1503 as start_waiting_job puts one back on the waiting list. */
1505 while (start_waiting_job (job
) && waiting_jobs
!= 0);
1512 #include <descrip.h>
1515 /* This is called as an AST when a child process dies (it won't get
1516 interrupted by anything except a higher level AST).
1518 int vmsHandleChildTerm(struct child
*child
)
1521 register struct child
*lastc
, *c
;
1524 vms_jobsefnmask
&= ~(1 << (child
->efn
- 32));
1526 lib$
free_ef(&child
->efn
);
1528 (void) sigblock (fatal_signal_mask
);
1530 child_failed
= !(child
->cstatus
& 1 || ((child
->cstatus
& 7) == 0));
1532 /* Search for a child matching the deceased one. */
1534 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1535 for (c
= children
; c
!= 0 && c
!= child
; lastc
= c
, c
= c
->next
);
1540 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
1542 /* The commands failed. Write an error message,
1543 delete non-precious targets, and abort. */
1544 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 0);
1545 c
->file
->update_status
= 1;
1546 delete_child_targets (c
);
1552 /* The commands failed, but we don't care. */
1553 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 1);
1557 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1558 /* If there are more commands to run, try to start them. */
1561 switch (c
->file
->command_state
)
1564 /* Successfully started. */
1568 if (c
->file
->update_status
!= 0) {
1569 /* We failed to start the commands. */
1570 delete_child_targets (c
);
1575 error (NILF
, _("internal error: `%s' command_state"), c
->file
->name
);
1579 #endif /* RECURSIVEJOBS */
1582 /* Set the state flag to say the commands have finished. */
1583 c
->file
->command_state
= cs_finished
;
1584 notice_finished_file (c
->file
);
1586 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1587 /* Remove the child from the chain and free it. */
1591 lastc
->next
= c
->next
;
1593 #endif /* RECURSIVEJOBS */
1595 /* There is now another slot open. */
1596 if (job_slots_used
> 0)
1599 /* If the job failed, and the -k flag was not given, die. */
1600 if (child_failed
&& !keep_going_flag
)
1603 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask
));
1609 Spawn a process executing the command in ARGV and return its pid. */
1611 #define MAXCMDLEN 200
1614 child_execute_job (argv
, child
)
1616 struct child
*child
;
1619 static struct dsc$descriptor_s cmddsc
;
1620 #ifndef DONTWAITFORCHILD
1623 int spflags
= CLI$M_NOWAIT
;
1626 char cmd
[4096],*p
,*c
;
1629 /* Remove backslashes */
1630 for (p
= argv
, c
= cmd
; *p
; p
++,c
++)
1632 if (*p
== '\\') p
++;
1637 /* Check for maximum DCL length and create *.com file if neccesary.
1638 Also create a .com file if the command is more than one line long. */
1642 if (strlen (cmd
) > MAXCMDLEN
|| strchr (cmd
, '\n'))
1647 strcpy (comname
, "sys$scratch:CMDXXXXXX.COM");
1648 (void) mktemp (comname
);
1650 outfile
= fopen (comname
, "w");
1652 pfatal_with_name (comname
);
1654 fprintf (outfile
, "$ ");
1659 p
= strchr (c
, ',');
1660 if ((p
== NULL
) || (p
-c
> MAXCMDLEN
))
1661 p
= strchr (c
, ' ');
1670 fprintf (outfile
, "%s%s\n", c
, (tmp
== '\0')?"":" -");
1678 sprintf (cmd
, "$ @%s", comname
);
1681 printf (_("Executing %s instead\n"), cmd
);
1684 cmddsc
.dsc$w_length
= strlen(cmd
);
1685 cmddsc
.dsc$a_pointer
= cmd
;
1686 cmddsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
1687 cmddsc
.dsc$b_class
= DSC$K_CLASS_S
;
1690 while (child
->efn
< 32 || child
->efn
> 63)
1692 status
= lib$
get_ef(&child
->efn
);
1697 sys$
clref(child
->efn
);
1699 vms_jobsefnmask
|= (1 << (child
->efn
- 32));
1701 #ifndef DONTWAITFORCHILD
1702 status
= lib$
spawn(&cmddsc
,0,0,&spflags
,0,&child
->pid
,&child
->cstatus
,
1704 vmsHandleChildTerm(child
);
1706 status
= lib$
spawn(&cmddsc
,0,0,&spflags
,0,&child
->pid
,&child
->cstatus
,
1707 &child
->efn
,vmsHandleChildTerm
,child
);
1712 printf(_("Error spawning, %d\n"),status
);
1718 return (status
& 1);
1723 #if !defined (_AMIGA) && !defined (__MSDOS__)
1725 Replace the current process with one executing the command in ARGV.
1726 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1727 the environment of the new program. This function does not return. */
1730 child_execute_job (stdin_fd
, stdout_fd
, argv
, envp
)
1731 int stdin_fd
, stdout_fd
;
1732 char **argv
, **envp
;
1735 (void) dup2 (stdin_fd
, 0);
1737 (void) dup2 (stdout_fd
, 1);
1739 (void) close (stdin_fd
);
1741 (void) close (stdout_fd
);
1743 /* Run the command. */
1744 exec_command (argv
, envp
);
1746 #endif /* !AMIGA && !__MSDOS__ */
1748 #endif /* !WINDOWS32 */
1751 /* Replace the current process with one running the command in ARGV,
1752 with environment ENVP. This function does not return. */
1755 exec_command (argv
, envp
)
1756 char **argv
, **envp
;
1759 /* Run the program. */
1760 execve (argv
[0], argv
, envp
);
1761 perror_with_name ("execve: ", argv
[0]);
1762 _exit (EXIT_FAILURE
);
1768 int exit_code
= EXIT_FAILURE
;
1770 /* make sure CreateProcess() has Path it needs */
1771 sync_Path_environment();
1773 /* launch command */
1774 hPID
= process_easy(argv
, envp
);
1776 /* make sure launch ok */
1777 if (hPID
== INVALID_HANDLE_VALUE
)
1781 _("process_easy() failed failed to launch process (e=%d)\n"),
1782 process_last_err(hPID
));
1783 for (i
= 0; argv
[i
]; i
++)
1784 fprintf(stderr
, "%s ", argv
[i
]);
1785 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
1789 /* wait and reap last child */
1790 while (hWaitPID
= process_wait_for_any())
1792 /* was an error found on this process? */
1793 err
= process_last_err(hWaitPID
);
1796 exit_code
= process_exit_code(hWaitPID
);
1799 fprintf(stderr
, "make (e=%d, rc=%d): %s",
1800 err
, exit_code
, map_windows32_error_to_string(err
));
1802 /* cleanup process */
1803 process_cleanup(hWaitPID
);
1805 /* expect to find only last pid, warn about other pids reaped */
1806 if (hWaitPID
== hPID
)
1810 _("make reaped child pid %d, still waiting for pid %d\n"),
1814 /* return child's exit code as our exit code */
1817 #else /* !WINDOWS32 */
1819 /* Be the user, permanently. */
1822 /* Run the program. */
1824 execvp (argv
[0], argv
);
1829 error (NILF
, _("%s: Command not found"), argv
[0]);
1833 /* The file is not executable. Try it as a shell script. */
1834 extern char *getenv ();
1839 shell
= getenv ("SHELL");
1841 shell
= default_shell
;
1844 while (argv
[argc
] != 0)
1847 new_argv
= (char **) alloca ((1 + argc
+ 1) * sizeof (char *));
1848 new_argv
[0] = shell
;
1849 new_argv
[1] = argv
[0];
1852 new_argv
[1 + argc
] = argv
[argc
];
1856 execvp (shell
, new_argv
);
1857 if (errno
== ENOENT
)
1858 error (NILF
, _("%s: Shell program not found"), shell
);
1860 perror_with_name ("execvp: ", shell
);
1865 perror_with_name ("execvp: ", argv
[0]);
1870 #endif /* !WINDOWS32 */
1873 #else /* On Amiga */
1874 void exec_command (argv
)
1880 void clean_tmp (void)
1882 DeleteFile (amiga_bname
);
1885 #endif /* On Amiga */
1888 /* Figure out the argument list necessary to run LINE as a command. Try to
1889 avoid using a shell. This routine handles only ' quoting, and " quoting
1890 when no backslash, $ or ` characters are seen in the quotes. Starting
1891 quotes may be escaped with a backslash. If any of the characters in
1892 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1893 is the first word of a line, the shell is used.
1895 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1896 If *RESTP is NULL, newlines will be ignored.
1898 SHELL is the shell to use, or nil to use the default shell.
1899 IFS is the value of $IFS, or nil (meaning the default). */
1902 construct_command_argv_internal (line
, restp
, shell
, ifs
, batch_filename_ptr
)
1903 char *line
, **restp
;
1905 char **batch_filename_ptr
;
1908 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
1909 We call `system' for anything that requires ``slow'' processing,
1910 because DOS shells are too dumb. When $SHELL points to a real
1911 (unix-style) shell, `system' just calls it to do everything. When
1912 $SHELL points to a DOS shell, `system' does most of the work
1913 internally, calling the shell only for its internal commands.
1914 However, it looks on the $PATH first, so you can e.g. have an
1915 external command named `mkdir'.
1917 Since we call `system', certain characters and commands below are
1918 actually not specific to COMMAND.COM, but to the DJGPP implementation
1919 of `system'. In particular:
1921 The shell wildcard characters are in DOS_CHARS because they will
1922 not be expanded if we call the child via `spawnXX'.
1924 The `;' is in DOS_CHARS, because our `system' knows how to run
1925 multiple commands on a single line.
1927 DOS_CHARS also include characters special to 4DOS/NDOS, so we
1928 won't have to tell one from another and have one more set of
1929 commands and special characters. */
1930 static char sh_chars_dos
[] = "*?[];|<>%^&()";
1931 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1932 "copy", "ctty", "date", "del", "dir", "echo",
1933 "erase", "exit", "for", "goto", "if", "md",
1934 "mkdir", "path", "pause", "prompt", "rd",
1935 "rmdir", "rem", "ren", "rename", "set",
1936 "shift", "time", "type", "ver", "verify",
1939 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
1940 static char *sh_cmds_sh
[] = { "cd", "eval", "exec", "exit", "login",
1941 "logout", "set", "umask", "wait", "while",
1942 "for", "case", "if", ":", ".", "break",
1943 "continue", "export", "read", "readonly",
1944 "shift", "times", "trap", "switch", 0 };
1950 static char sh_chars
[] = "#;\"|<>()?*$`";
1951 static char *sh_cmds
[] = { "cd", "eval", "if", "delete", "echo", "copy",
1952 "rename", "set", "setenv", "date", "makedir",
1953 "skip", "else", "endif", "path", "prompt",
1954 "unset", "unsetenv", "version",
1958 static char sh_chars_dos
[] = "\"|<>";
1959 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1960 "copy", "ctty", "date", "del", "dir", "echo",
1961 "erase", "exit", "for", "goto", "if", "if", "md",
1962 "mkdir", "path", "pause", "prompt", "rem", "ren",
1963 "rename", "set", "shift", "time", "type",
1964 "ver", "verify", "vol", ":", 0 };
1965 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
1966 static char *sh_cmds_sh
[] = { "cd", "eval", "exec", "exit", "login",
1967 "logout", "set", "umask", "wait", "while", "for",
1968 "case", "if", ":", ".", "break", "continue",
1969 "export", "read", "readonly", "shift", "times",
1970 "trap", "switch", "test",
1971 #ifdef BATCH_MODE_ONLY_SHELL
1977 #else /* WINDOWS32 */
1978 static char sh_chars
[] = "#;\"*?[]&|<>(){}$`^";
1979 static char *sh_cmds
[] = { "cd", "eval", "exec", "exit", "login",
1980 "logout", "set", "umask", "wait", "while", "for",
1981 "case", "if", ":", ".", "break", "continue",
1982 "export", "read", "readonly", "shift", "times",
1983 "trap", "switch", 0 };
1984 #endif /* WINDOWS32 */
1986 #endif /* __MSDOS__ */
1991 int instring
, word_has_equals
, seen_nonequals
, last_argument_was_empty
;
1992 char **new_argv
= 0;
1996 if (no_default_sh_exe
) {
1997 sh_cmds
= sh_cmds_dos
;
1998 sh_chars
= sh_chars_dos
;
2000 sh_cmds
= sh_cmds_sh
;
2001 sh_chars
= sh_chars_sh
;
2003 #endif /* WINDOWS32 */
2008 /* Make sure not to bother processing an empty line. */
2009 while (isblank (*line
))
2014 /* See if it is safe to parse commands internally. */
2016 shell
= default_shell
;
2018 else if (strcmp (shell
, default_shell
))
2020 char *s1
= _fullpath(NULL
, shell
, 0);
2021 char *s2
= _fullpath(NULL
, default_shell
, 0);
2023 slow_flag
= strcmp((s1
? s1
: ""), (s2
? s2
: ""));
2032 #else /* not WINDOWS32 */
2034 else if (stricmp (shell
, default_shell
))
2036 extern int _is_unixy_shell (const char *_path
);
2038 message (1, _("$SHELL changed (was `%s', now `%s')"), default_shell
, shell
);
2039 unixy_shell
= _is_unixy_shell (shell
);
2040 default_shell
= shell
;
2044 sh_chars
= sh_chars_sh
;
2045 sh_cmds
= sh_cmds_sh
;
2049 sh_chars
= sh_chars_dos
;
2050 sh_cmds
= sh_cmds_dos
;
2052 #else /* not __MSDOS__ */
2053 else if (strcmp (shell
, default_shell
))
2055 #endif /* not __MSDOS__ */
2056 #endif /* not WINDOWS32 */
2059 for (ap
= ifs
; *ap
!= '\0'; ++ap
)
2060 if (*ap
!= ' ' && *ap
!= '\t' && *ap
!= '\n')
2063 i
= strlen (line
) + 1;
2065 /* More than 1 arg per character is impossible. */
2066 new_argv
= (char **) xmalloc (i
* sizeof (char *));
2068 /* All the args can fit in a buffer as big as LINE is. */
2069 ap
= new_argv
[0] = (char *) xmalloc (i
);
2072 /* I is how many complete arguments have been found. */
2074 instring
= word_has_equals
= seen_nonequals
= last_argument_was_empty
= 0;
2075 for (p
= line
; *p
!= '\0'; ++p
)
2083 /* Inside a string, just copy any char except a closing quote
2084 or a backslash-newline combination. */
2088 if (ap
== new_argv
[0] || *(ap
-1) == '\0')
2089 last_argument_was_empty
= 1;
2091 else if (*p
== '\\' && p
[1] == '\n')
2092 goto swallow_escaped_newline
;
2093 else if (*p
== '\n' && restp
!= NULL
)
2095 /* End of the command line. */
2099 /* Backslash, $, and ` are special inside double quotes.
2100 If we see any of those, punt.
2101 But on MSDOS, if we use COMMAND.COM, double and single
2102 quotes have the same effect. */
2103 else if (instring
== '"' && index ("\\$`", *p
) != 0 && unixy_shell
)
2108 else if (index (sh_chars
, *p
) != 0)
2109 /* Not inside a string, but it's a special char. */
2112 else if (*p
== '.' && p
[1] == '.' && p
[2] == '.' && p
[3] != '.')
2113 /* `...' is a wildcard in DJGPP. */
2117 /* Not a special char. */
2121 /* Equals is a special character in leading words before the
2122 first word with no equals sign in it. This is not the case
2123 with sh -k, but we never get here when using nonstandard
2125 if (! seen_nonequals
&& unixy_shell
)
2127 word_has_equals
= 1;
2132 /* Backslash-newline combinations are eaten. */
2135 swallow_escaped_newline
:
2137 /* Eat the backslash, the newline, and following whitespace,
2138 replacing it all with a single space. */
2141 /* If there is a tab after a backslash-newline,
2142 remove it from the source line which will be echoed,
2143 since it was most likely used to line
2144 up the continued line with the previous one. */
2146 /* Note these overlap and strcpy() is undefined for
2147 overlapping objects in ANSI C. The strlen() _IS_ right,
2148 since we need to copy the nul byte too. */
2149 bcopy (p
+ 1, p
, strlen(p
));
2155 if (ap
!= new_argv
[i
])
2156 /* Treat this as a space, ending the arg.
2157 But if it's at the beginning of the arg, it should
2158 just get eaten, rather than becoming an empty arg. */
2161 p
= next_token (p
) - 1;
2164 else if (p
[1] != '\0')
2166 #if defined(__MSDOS__) || defined(WINDOWS32)
2167 /* Only remove backslashes before characters special
2168 to Unixy shells. All other backslashes are copied
2169 verbatim, since they are probably DOS-style
2170 directory separators. This still leaves a small
2171 window for problems, but at least it should work
2172 for the vast majority of naive users. */
2175 /* A dot is only special as part of the "..."
2177 if (strneq (p
+ 1, ".\\.\\.", 5))
2185 if (p
[1] != '\\' && p
[1] != '\'' && !isspace (p
[1])
2186 && (index (sh_chars_sh
, p
[1]) == 0))
2187 /* back up one notch, to copy the backslash */
2190 #endif /* __MSDOS__ || WINDOWS32 */
2191 /* Copy and skip the following char. */
2204 /* End of the command line. */
2209 /* Newlines are not special. */
2216 /* We have the end of an argument.
2217 Terminate the text of the argument. */
2220 last_argument_was_empty
= 0;
2222 /* Update SEEN_NONEQUALS, which tells us if every word
2223 heretofore has contained an `='. */
2224 seen_nonequals
|= ! word_has_equals
;
2225 if (word_has_equals
&& ! seen_nonequals
)
2226 /* An `=' in a word before the first
2227 word without one is magical. */
2229 word_has_equals
= 0; /* Prepare for the next word. */
2231 /* If this argument is the command name,
2232 see if it is a built-in shell command.
2233 If so, have the shell handle it. */
2237 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2238 if (streq (sh_cmds
[j
], new_argv
[0]))
2242 /* Ignore multiple whitespace chars. */
2244 /* Next iteration should examine the first nonwhite char. */
2256 /* Let the shell deal with an unterminated quote. */
2259 /* Terminate the last argument and the argument list. */
2262 if (new_argv
[i
][0] != '\0' || last_argument_was_empty
)
2269 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2270 if (streq (sh_cmds
[j
], new_argv
[0]))
2274 if (new_argv
[0] == 0)
2275 /* Line was empty. */
2281 /* We must use the shell. */
2285 /* Free the old argument list we were working on. */
2287 free ((void *)new_argv
);
2291 execute_by_shell
= 1; /* actually, call `system' if shell isn't unixy */
2300 buffer
= (char *)xmalloc (strlen (line
)+1);
2303 for (dptr
=buffer
; *ptr
; )
2305 if (*ptr
== '\\' && ptr
[1] == '\n')
2307 else if (*ptr
== '@') /* Kludge: multiline commands */
2317 new_argv
= (char **) xmalloc(2 * sizeof(char *));
2318 new_argv
[0] = buffer
;
2321 #else /* Not Amiga */
2324 * Not eating this whitespace caused things like
2328 * which gave the shell fits. I think we have to eat
2329 * whitespace here, but this code should be considered
2330 * suspicious if things start failing....
2333 /* Make sure not to bother processing an empty line. */
2334 while (isspace (*line
))
2338 #endif /* WINDOWS32 */
2340 /* SHELL may be a multi-word command. Construct a command line
2341 "SHELL -c LINE", with all special chars in LINE escaped.
2342 Then recurse, expanding this command line to get the final
2345 unsigned int shell_len
= strlen (shell
);
2346 static char minus_c
[] = " -c ";
2347 unsigned int line_len
= strlen (line
);
2349 char *new_line
= (char *) alloca (shell_len
+ (sizeof (minus_c
) - 1)
2350 + (line_len
* 2) + 1);
2351 char* command_ptr
= NULL
; /* used for batch_mode_shell mode */
2354 bcopy (shell
, ap
, shell_len
);
2356 bcopy (minus_c
, ap
, sizeof (minus_c
) - 1);
2357 ap
+= sizeof (minus_c
) - 1;
2359 for (p
= line
; *p
!= '\0'; ++p
)
2361 if (restp
!= NULL
&& *p
== '\n')
2366 else if (*p
== '\\' && p
[1] == '\n')
2368 /* Eat the backslash, the newline, and following whitespace,
2369 replacing it all with a single space (which is escaped
2373 /* If there is a tab after a backslash-newline,
2374 remove it from the source line which will be echoed,
2375 since it was most likely used to line
2376 up the continued line with the previous one. */
2378 bcopy (p
+ 1, p
, strlen (p
));
2382 if (unixy_shell
&& !batch_mode_shell
)
2388 /* DOS shells don't know about backslash-escaping. */
2389 if (unixy_shell
&& !batch_mode_shell
&&
2390 (*p
== '\\' || *p
== '\'' || *p
== '"'
2392 || index (sh_chars
, *p
) != 0))
2395 else if (unixy_shell
&& strneq (p
, "...", 3))
2397 /* The case of `...' wildcard again. */
2398 strcpy (ap
, "\\.\\.\\");
2405 if (ap
== new_line
+ shell_len
+ sizeof (minus_c
) - 1)
2406 /* Line was empty. */
2411 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2412 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2413 cases, run commands via a script file. */
2414 if ((no_default_sh_exe
|| batch_mode_shell
) && batch_filename_ptr
) {
2416 int id
= GetCurrentProcessId();
2420 /* create a file name */
2421 sprintf(fbuf
, "make%d", id
);
2422 fname
= tempnam(".", fbuf
);
2424 /* create batch file name */
2425 *batch_filename_ptr
= xmalloc(strlen(fname
) + 5);
2426 strcpy(*batch_filename_ptr
, fname
);
2428 /* make sure path name is in DOS backslash format */
2430 fname
= *batch_filename_ptr
;
2431 for (i
= 0; fname
[i
] != '\0'; ++i
)
2432 if (fname
[i
] == '/')
2434 strcat(*batch_filename_ptr
, ".bat");
2436 strcat(*batch_filename_ptr
, ".sh");
2440 printf(_("Creating temporary batch file %s\n"), *batch_filename_ptr
);
2442 /* create batch file to execute command */
2443 batch
= fopen (*batch_filename_ptr
, "w");
2445 fputs ("@echo off\n", batch
);
2446 fputs (command_ptr
, batch
);
2447 fputc ('\n', batch
);
2451 new_argv
= (char **) xmalloc(3 * sizeof(char *));
2453 new_argv
[0] = xstrdup (shell
);
2454 new_argv
[1] = *batch_filename_ptr
; /* only argv[0] gets freed later */
2456 new_argv
[0] = xstrdup (*batch_filename_ptr
);
2461 #endif /* WINDOWS32 */
2463 new_argv
= construct_command_argv_internal (new_line
, (char **) NULL
,
2464 (char *) 0, (char *) 0,
2469 /* With MSDOS shells, we must construct the command line here
2470 instead of recursively calling ourselves, because we
2471 cannot backslash-escape the special characters (see above). */
2472 new_argv
= (char **) xmalloc (sizeof (char *));
2473 line_len
= strlen (new_line
) - shell_len
- sizeof (minus_c
) + 1;
2474 new_argv
[0] = xmalloc (line_len
+ 1);
2475 strncpy (new_argv
[0],
2476 new_line
+ shell_len
+ sizeof (minus_c
) - 1, line_len
);
2477 new_argv
[0][line_len
] = '\0';
2481 fatal (NILF
, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2482 __FILE__
, __LINE__
);
2485 #endif /* ! AMIGA */
2490 /* Figure out the argument list necessary to run LINE as a command. Try to
2491 avoid using a shell. This routine handles only ' quoting, and " quoting
2492 when no backslash, $ or ` characters are seen in the quotes. Starting
2493 quotes may be escaped with a backslash. If any of the characters in
2494 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2495 is the first word of a line, the shell is used.
2497 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2498 If *RESTP is NULL, newlines will be ignored.
2500 FILE is the target whose commands these are. It is used for
2501 variable expansion for $(SHELL) and $(IFS). */
2504 construct_command_argv (line
, restp
, file
, batch_filename_ptr
)
2505 char *line
, **restp
;
2507 char** batch_filename_ptr
;
2513 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2514 int save
= warn_undefined_variables_flag
;
2515 warn_undefined_variables_flag
= 0;
2517 shell
= allocated_variable_expand_for_file ("$(SHELL)", file
);
2520 * Convert to forward slashes so that construct_command_argv_internal()
2524 char *p
= w32ify(shell
, 0);
2528 ifs
= allocated_variable_expand_for_file ("$(IFS)", file
);
2530 warn_undefined_variables_flag
= save
;
2533 argv
= construct_command_argv_internal (line
, restp
, shell
, ifs
, batch_filename_ptr
);
2542 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2560 #endif /* !HAPE_DUP2 && !_AMIGA */