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 /* 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). */
213 /* #define debug_flag 1 */
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. */
232 child_error (target_name
, exit_code
, exit_sig
, coredump
, ignored
)
234 int exit_code
, exit_sig
, coredump
;
237 if (ignored
&& silent_flag
)
241 if (!(exit_code
& 1))
242 error (NILF
, _("*** [%s] Error 0x%x%s"), target_name
, exit_code
, ((ignored
)? _(" (ignored)") : ""));
245 error (NILF
, ignored
? _("[%s] Error %d (ignored)") :
246 _("*** [%s] Error %d"),
247 target_name
, exit_code
);
249 error (NILF
, "*** [%s] %s%s",
250 target_name
, strsignal (exit_sig
),
251 coredump
? _(" (core dumped)") : "");
256 /* Wait for nchildren children to terminate */
258 vmsWaitForChildren(int *status
)
262 if (!vms_jobsefnmask
)
268 *status
= sys$
wflor (32, vms_jobsefnmask
);
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;
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. */
314 reap_children (block
, err
)
318 /* Initially, assume we have some. */
322 # define REAP_MORE reap_more
324 # define REAP_MORE dead_children
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
))
340 int exit_code
, exit_sig
, coredump
;
341 register struct child
*lastc
, *c
;
343 int any_remote
, any_local
;
347 /* We might block for a while, so let the user know why. */
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)
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
;
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)") : "");
387 /* First, check for remote children. */
389 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 0);
394 /* We got a remote child. */
398 /* A remote status command failed miserably. Punt. */
403 pfatal_with_name ("remote_status");
407 /* No remote children. Check for local children. */
408 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
413 vmsWaitForChildren (&status
);
418 pid
= WAIT_NOHANG (&status
);
421 pid
= wait (&status
);
429 /* EINTR? Try again. */
433 /* The wait*() failed miserably. Punt. */
434 pfatal_with_name ("wait");
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
);
445 /* No local children are dead. */
448 if (!block
|| !any_remote
)
451 /* Now try a blocking wait for a remote child. */
452 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 1);
454 goto remote_status_lose
;
456 /* No remote children either. Finally give up. */
459 /* We got a remote child. */
462 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
465 /* Life is very different on MSDOS. */
468 exit_code
= WEXITSTATUS (status
);
469 if (exit_code
== 0xff)
471 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
473 #endif /* __MSDOS__ */
477 status
= amiga_status
;
478 exit_code
= amiga_status
;
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
);
494 exit_code
= process_exit_code(hPID
);
497 fprintf(stderr
, "make (e=%d): %s",
498 exit_code
, map_windows32_error_to_string(exit_code
));
501 exit_sig
= process_signal(hPID
);
503 /* cleanup process */
504 process_cleanup(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;
520 shell_function_completed
= 1;
524 child_failed
= exit_sig
!= 0 || exit_code
!= 0;
526 /* Search for a child matching the deceased one. */
528 for (c
= children
; c
!= 0; lastc
= c
, c
= c
->next
)
529 if (c
->remote
== remote
&& c
->pid
== pid
)
533 /* An unknown child died.
534 Ignore it; it was inherited from our invoker. */
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
) {
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. */
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
);
578 /* The commands failed, but we don't care. */
579 child_error (c
->file
->name
,
580 exit_code
, exit_sig
, coredump
, 1);
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;
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. */
608 if (c
->file
->command_state
== cs_running
)
609 /* We successfully started the new command.
610 Loop to reap more children. */
614 if (c
->file
->update_status
!= 0)
615 /* We failed to start the commands. */
616 delete_child_targets (c
);
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
);
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. */
649 /* There is now another slot open. */
650 if (job_slots_used
> 0)
653 /* Remove the child from the chain and free it. */
657 lastc
->next
= c
->next
;
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
)
670 /* Only block for one child. */
677 /* Free the storage allocated for 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
)
691 /* Write a job token back to the pipe. */
693 while (write (job_fds
[1], &token
, 1) != 1)
695 pfatal_with_name (_("write jobserver"));
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. */
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
;
718 free ((char *) child
->environment
);
721 free ((char *) child
);
725 extern sigset_t fatal_signal_set
;
732 (void) sigprocmask (SIG_BLOCK
, &fatal_signal_set
, (sigset_t
*) 0);
734 # ifdef HAVE_SIGSETMASK
735 (void) sigblock (fatal_signal_mask
);
745 sigemptyset (&empty
);
746 sigprocmask (SIG_SETMASK
, &empty
, (sigset_t
*) 0);
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. */
758 start_job_command (child
)
759 register struct child
*child
;
762 static int bad_stdin
= -1;
772 /* If we have a completely empty commandset, stop now. */
773 if (!child
->command_ptr
)
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
;
787 flags
|= COMMANDS_SILENT
;
789 flags
|= COMMANDS_RECURSE
;
792 else if (!isblank (*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
);
810 /* There may be some preceding whitespace left if there
811 was nothing but a backslash on the first line. */
814 /* Figure out an argument list from this command line. */
821 argv
= construct_command_argv (p
, &end
, child
->file
, &child
->sh_batch_file
);
824 child
->command_ptr
= NULL
;
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. */
838 free ((char *) argv
);
847 execute_by_shell
= 0; /* in case construct_command_argv sets it */
849 /* This line has no commands. Go to the next. */
850 if (job_next_command (child
))
851 start_job_command (child
);
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
);
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
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)
876 unixy_shell
/* the test is complicated and we already did it */
878 (argv
[0] && !strcmp (argv
[0], "/bin/sh"))
881 && argv
[1][0] == '-' && argv
[1][1] == 'c' && argv
[1][2] == '\0')
882 && (argv
[2] && argv
[2][0] == ':' && argv
[2][1] == '\0')
886 free ((char *) argv
);
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. */
900 /* If -n was given, recurse to get the next line in the sequence. */
902 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
))
906 free ((char *) argv
);
911 /* Flush the output streams so they won't have things written twice. */
917 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
919 /* Set up a bad standard input that reads from a broken pipe. */
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. */
928 /* Close the write side. */
929 (void) close (pd
[1]);
930 /* Save the read side. */
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
)
955 /* Set up the environment for the child. */
956 if (child
->environment
== 0)
957 child
->environment
= target_environment (child
->file
);
960 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
963 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
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. */
975 if (child
->good_stdin
&& !used_stdin
)
977 child
->good_stdin
= 0;
980 child
->remote
= is_remote
;
987 /* Fork the child process. */
989 char **parent_environ
;
998 if (!child_execute_job (argv
, child
)) {
1000 perror_with_name ("vfork", "");
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. */
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)
1024 child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1025 argv
, child
->environment
);
1027 else if (child
->pid
< 0)
1031 perror_with_name ("vfork", "");
1037 #else /* __MSDOS__ or Amiga or WINDOWS32 */
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. */
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 */
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). */
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)
1089 dos_status
|= (proc_return
& 0xff);
1091 child
->pid
= dos_pid
++;
1093 #endif /* __MSDOS__ */
1095 amiga_status
= MyExecute (argv
);
1098 child
->pid
= amiga_pid
++;
1099 if (amiga_batch_file
)
1101 amiga_batch_file
= 0;
1102 DeleteFile (amiga_bname
); /* Ignore errors. */
1110 /* make UNC paths safe for CreateProcess -- backslash format */
1112 if (arg0
&& arg0
[0] == '/' && arg0
[1] == '/')
1113 for ( ; arg0
&& *arg0
; 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
;
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. */
1146 free ((char *) argv
);
1152 child
->file
->update_status
= 2;
1153 notice_finished_file (child
->file
);
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. */
1162 start_waiting_job (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
1179 set_command_state (f
, cs_running
);
1180 c
->next
= waiting_jobs
;
1185 /* Start the first command; reap_children will run later command lines. */
1186 start_job_command (c
);
1188 switch (f
->command_state
)
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)") : "");
1197 /* One more job slot is in use. */
1202 case cs_not_started
:
1203 /* All the command lines turned out to be empty. */
1204 f
->update_status
= 0;
1208 notice_finished_file (f
);
1213 assert (f
->command_state
== cs_finished
);
1220 /* Create a `struct child' for FILE and start its commands running. */
1224 register struct file
*file
;
1226 register struct commands
*cmds
= file
->cmds
;
1227 register struct child
*c
;
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 $. */
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. */
1274 if (*ref
== '(' || *ref
== '{')
1276 char openparen
= *ref
;
1277 char closeparen
= openparen
== '(' ? ')' : '}';
1281 *out
++ = *in
++; /* Copy OPENPAREN. */
1282 /* IN now points past the opening paren or brace.
1283 Count parens or braces until it is matched. */
1287 if (*in
== closeparen
&& --count
< 0)
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. */
1296 for (p
= in
- 1; p
> ref
&& *p
== '\\'; --p
)
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. */
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]))
1317 /* Replace it all with a single space. */
1323 if (*in
== openparen
)
1332 /* There are no more references in this line to worry about.
1333 Copy the remaining uninteresting text to the output. */
1337 /* Finally, expand the line. */
1338 lines
[i
] = allocated_variable_expand_for_file (cmds
->command_lines
[i
],
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
));
1347 c
->command_lines
= lines
;
1348 c
->command_line
= 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. */
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)
1381 /* If we don't already have a job started, use our "free" token. */
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)
1393 printf (_("Obtained token for child 0x%08lx (%s).\n"),
1394 (unsigned long int) c
, c
->file
->name
);
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. */
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);
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
);
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);
1425 /* Move CHILD's pointers to the next command for it to execute.
1426 Returns nonzero if there is another command. */
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;
1442 /* Get the next line to run. */
1443 child
->command_ptr
= child
->command_lines
[child
->command_line
++];
1451 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1456 if (max_load_average
< 0)
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
)
1467 /* An errno value of zero means getloadavg is just unsupported. */
1468 error (NILF
, _("cannot enforce load limits on this operating system"));
1470 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1477 return load
>= max_load_average
;
1481 /* Start jobs that are waiting for the load to be lower. */
1484 start_waiting_jobs ()
1488 if (waiting_jobs
== 0)
1493 /* Check for recently deceased descendants. */
1494 reap_children (0, 0);
1496 /* Take a job off the waiting list. */
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);
1510 #include <descrip.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
)
1519 register struct child
*lastc
, *c
;
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. */
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
);
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
);
1550 /* The commands failed, but we don't care. */
1551 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 1);
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. */
1559 switch (c
->file
->command_state
)
1562 /* Successfully started. */
1566 if (c
->file
->update_status
!= 0) {
1567 /* We failed to start the commands. */
1568 delete_child_targets (c
);
1573 error (NILF
, _("internal error: `%s' command_state"), c
->file
->name
);
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. */
1589 lastc
->next
= c
->next
;
1591 #endif /* RECURSIVEJOBS */
1593 /* There is now another slot open. */
1594 if (job_slots_used
> 0)
1597 /* If the job failed, and the -k flag was not given, die. */
1598 if (child_failed
&& !keep_going_flag
)
1601 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask
));
1607 Spawn a process executing the command in ARGV and return its pid. */
1609 #define MAXCMDLEN 200
1612 child_execute_job (argv
, child
)
1614 struct child
*child
;
1617 static struct dsc$descriptor_s cmddsc
;
1618 #ifndef DONTWAITFORCHILD
1621 int spflags
= CLI$M_NOWAIT
;
1624 char cmd
[4096],*p
,*c
;
1627 /* Remove backslashes */
1628 for (p
= argv
, c
= cmd
; *p
; p
++,c
++)
1630 if (*p
== '\\') 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. */
1640 if (strlen (cmd
) > MAXCMDLEN
|| strchr (cmd
, '\n'))
1645 strcpy (comname
, "sys$scratch:CMDXXXXXX.COM");
1646 (void) mktemp (comname
);
1648 outfile
= fopen (comname
, "w");
1650 pfatal_with_name (comname
);
1652 fprintf (outfile
, "$ ");
1657 p
= strchr (c
, ',');
1658 if ((p
== NULL
) || (p
-c
> MAXCMDLEN
))
1659 p
= strchr (c
, ' ');
1668 fprintf (outfile
, "%s%s\n", c
, (tmp
== '\0')?"":" -");
1676 sprintf (cmd
, "$ @%s", comname
);
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
;
1688 while (child
->efn
< 32 || child
->efn
> 63)
1690 status
= lib$
get_ef(&child
->efn
);
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
,
1702 vmsHandleChildTerm(child
);
1704 status
= lib$
spawn(&cmddsc
,0,0,&spflags
,0,&child
->pid
,&child
->cstatus
,
1705 &child
->efn
,vmsHandleChildTerm
,child
);
1710 printf(_("Error spawning, %d\n"),status
);
1716 return (status
& 1);
1721 #if !defined (_AMIGA) && !defined (__MSDOS__)
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. */
1728 child_execute_job (stdin_fd
, stdout_fd
, argv
, envp
)
1729 int stdin_fd
, stdout_fd
;
1730 char **argv
, **envp
;
1733 (void) dup2 (stdin_fd
, 0);
1735 (void) dup2 (stdout_fd
, 1);
1737 (void) close (stdin_fd
);
1739 (void) close (stdout_fd
);
1741 /* Run the command. */
1742 exec_command (argv
, envp
);
1744 #endif /* !AMIGA && !__MSDOS__ */
1746 #endif /* !WINDOWS32 */
1749 /* Replace the current process with one running the command in ARGV,
1750 with environment ENVP. This function does not return. */
1753 exec_command (argv
, envp
)
1754 char **argv
, **envp
;
1757 /* Run the program. */
1758 execve (argv
[0], argv
, envp
);
1759 perror_with_name ("execve: ", argv
[0]);
1760 _exit (EXIT_FAILURE
);
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
)
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
);
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
);
1794 exit_code
= process_exit_code(hWaitPID
);
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
)
1808 _("make reaped child pid %d, still waiting for pid %d\n"),
1812 /* return child's exit code as our exit code */
1815 #else /* !WINDOWS32 */
1817 /* Be the user, permanently. */
1820 /* Run the program. */
1822 execvp (argv
[0], argv
);
1827 error (NILF
, _("%s: Command not found"), argv
[0]);
1831 /* The file is not executable. Try it as a shell script. */
1832 extern char *getenv ();
1837 shell
= getenv ("SHELL");
1839 shell
= default_shell
;
1842 while (argv
[argc
] != 0)
1845 new_argv
= (char **) alloca ((1 + argc
+ 1) * sizeof (char *));
1846 new_argv
[0] = shell
;
1847 new_argv
[1] = argv
[0];
1850 new_argv
[1 + argc
] = argv
[argc
];
1854 execvp (shell
, new_argv
);
1855 if (errno
== ENOENT
)
1856 error (NILF
, _("%s: Shell program not found"), shell
);
1858 perror_with_name ("execvp: ", shell
);
1863 perror_with_name ("execvp: ", argv
[0]);
1868 #endif /* !WINDOWS32 */
1871 #else /* On Amiga */
1872 void exec_command (argv
)
1878 void clean_tmp (void)
1880 DeleteFile (amiga_bname
);
1883 #endif /* On Amiga */
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). */
1900 construct_command_argv_internal (line
, restp
, shell
, ifs
, batch_filename_ptr
)
1901 char *line
, **restp
;
1903 char **batch_filename_ptr
;
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",
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",
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",
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
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 */
1985 #endif /* __MSDOS__ */
1990 int instring
, word_has_equals
, seen_nonequals
, last_argument_was_empty
;
1991 char **new_argv
= 0;
1995 if (no_default_sh_exe
) {
1996 sh_cmds
= sh_cmds_dos
;
1997 sh_chars
= sh_chars_dos
;
1999 sh_cmds
= sh_cmds_sh
;
2000 sh_chars
= sh_chars_sh
;
2002 #endif /* WINDOWS32 */
2007 /* Make sure not to bother processing an empty line. */
2008 while (isblank (*line
))
2013 /* See if it is safe to parse commands internally. */
2015 shell
= default_shell
;
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
: ""));
2031 #else /* not WINDOWS32 */
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
;
2043 sh_chars
= sh_chars_sh
;
2044 sh_cmds
= sh_cmds_sh
;
2048 sh_chars
= sh_chars_dos
;
2049 sh_cmds
= sh_cmds_dos
;
2051 #else /* not __MSDOS__ */
2052 else if (strcmp (shell
, default_shell
))
2054 #endif /* not __MSDOS__ */
2055 #endif /* not WINDOWS32 */
2058 for (ap
= ifs
; *ap
!= '\0'; ++ap
)
2059 if (*ap
!= ' ' && *ap
!= '\t' && *ap
!= '\n')
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
);
2071 /* I is how many complete arguments have been found. */
2073 instring
= word_has_equals
= seen_nonequals
= last_argument_was_empty
= 0;
2074 for (p
= line
; *p
!= '\0'; ++p
)
2082 /* Inside a string, just copy any char except a closing quote
2083 or a backslash-newline combination. */
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. */
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
)
2107 else if (index (sh_chars
, *p
) != 0)
2108 /* Not inside a string, but it's a special char. */
2111 else if (*p
== '.' && p
[1] == '.' && p
[2] == '.' && p
[3] != '.')
2112 /* `...' is a wildcard in DJGPP. */
2116 /* Not a special char. */
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
2124 if (! seen_nonequals
&& unixy_shell
)
2126 word_has_equals
= 1;
2131 /* Backslash-newline combinations are eaten. */
2134 swallow_escaped_newline
:
2136 /* Eat the backslash, the newline, and following whitespace,
2137 replacing it all with a single space. */
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. */
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
));
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. */
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. */
2174 /* A dot is only special as part of the "..."
2176 if (strneq (p
+ 1, ".\\.\\.", 5))
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 */
2189 #endif /* __MSDOS__ || WINDOWS32 */
2190 /* Copy and skip the following char. */
2203 /* End of the command line. */
2208 /* Newlines are not special. */
2215 /* We have the end of an argument.
2216 Terminate the text of the argument. */
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. */
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. */
2236 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2237 if (streq (sh_cmds
[j
], new_argv
[0]))
2241 /* Ignore multiple whitespace chars. */
2243 /* Next iteration should examine the first nonwhite char. */
2255 /* Let the shell deal with an unterminated quote. */
2258 /* Terminate the last argument and the argument list. */
2261 if (new_argv
[i
][0] != '\0' || last_argument_was_empty
)
2268 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2269 if (streq (sh_cmds
[j
], new_argv
[0]))
2273 if (new_argv
[0] == 0)
2274 /* Line was empty. */
2280 /* We must use the shell. */
2284 /* Free the old argument list we were working on. */
2286 free ((void *)new_argv
);
2290 execute_by_shell
= 1; /* actually, call `system' if shell isn't unixy */
2299 buffer
= (char *)xmalloc (strlen (line
)+1);
2302 for (dptr
=buffer
; *ptr
; )
2304 if (*ptr
== '\\' && ptr
[1] == '\n')
2306 else if (*ptr
== '@') /* Kludge: multiline commands */
2316 new_argv
= (char **) xmalloc (2 * sizeof (char *));
2317 new_argv
[0] = buffer
;
2320 #else /* Not Amiga */
2323 * Not eating this whitespace caused things like
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
))
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
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 */
2353 bcopy (shell
, ap
, shell_len
);
2355 bcopy (minus_c
, ap
, sizeof (minus_c
) - 1);
2356 ap
+= sizeof (minus_c
) - 1;
2358 for (p
= line
; *p
!= '\0'; ++p
)
2360 if (restp
!= NULL
&& *p
== '\n')
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
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. */
2377 bcopy (p
+ 1, p
, strlen (p
));
2381 if (unixy_shell
&& !batch_mode_shell
)
2387 /* DOS shells don't know about backslash-escaping. */
2388 if (unixy_shell
&& !batch_mode_shell
&&
2389 (*p
== '\\' || *p
== '\'' || *p
== '"'
2391 || index (sh_chars
, *p
) != 0))
2394 else if (unixy_shell
&& strneq (p
, "...", 3))
2396 /* The case of `...' wildcard again. */
2397 strcpy (ap
, "\\.\\.\\");
2404 if (ap
== new_line
+ shell_len
+ sizeof (minus_c
) - 1)
2405 /* Line was empty. */
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
) {
2415 int id
= GetCurrentProcessId();
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 */
2429 fname
= *batch_filename_ptr
;
2430 for (i
= 0; fname
[i
] != '\0'; ++i
)
2431 if (fname
[i
] == '/')
2433 strcat(*batch_filename_ptr
, ".bat");
2435 strcat(*batch_filename_ptr
, ".sh");
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");
2444 fputs ("@echo off\n", batch
);
2445 fputs (command_ptr
, batch
);
2446 fputc ('\n', batch
);
2450 new_argv
= (char **) xmalloc(3 * sizeof(char *));
2452 new_argv
[0] = xstrdup (shell
);
2453 new_argv
[1] = *batch_filename_ptr
; /* only argv[0] gets freed later */
2455 new_argv
[0] = xstrdup (*batch_filename_ptr
);
2460 #endif /* WINDOWS32 */
2462 new_argv
= construct_command_argv_internal (new_line
, (char **) NULL
,
2463 (char *) 0, (char *) 0,
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';
2480 fatal (NILF
, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2481 __FILE__
, __LINE__
);
2484 #endif /* ! AMIGA */
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). */
2503 construct_command_argv (line
, restp
, file
, batch_filename_ptr
)
2504 char *line
, **restp
;
2506 char** batch_filename_ptr
;
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
);
2519 * Convert to forward slashes so that construct_command_argv_internal()
2523 char *p
= w32ify(shell
, 0);
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
);
2541 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2559 #endif /* !HAPE_DUP2 && !_AMIGA */