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 /* If -q was given, just say that updating `failed'. The exit status of
798 1 tells the user that -q is saying `something to do'; the exit status
799 for a random error is 2. */
800 if (question_flag
&& !(flags
& COMMANDS_RECURSE
))
802 child
->file
->update_status
= 1;
803 notice_finished_file (child
->file
);
807 /* There may be some preceding whitespace left if there
808 was nothing but a backslash on the first line. */
811 /* Figure out an argument list from this command line. */
818 argv
= construct_command_argv (p
, &end
, child
->file
, &child
->sh_batch_file
);
821 child
->command_ptr
= NULL
;
825 child
->command_ptr
= end
;
829 if (touch_flag
&& !(flags
& COMMANDS_RECURSE
))
831 /* Go on to the next command. It might be the recursive one.
832 We construct ARGV only to find the end of the command line. */
835 free ((char *) argv
);
844 execute_by_shell
= 0; /* in case construct_command_argv sets it */
846 /* This line has no commands. Go to the next. */
847 if (job_next_command (child
))
848 start_job_command (child
);
851 /* No more commands. Make sure we're "running"; we might not be if
852 (e.g.) all commands were skipped due to -n. */
853 set_command_state (child
->file
, cs_running
);
854 child
->file
->update_status
= 0;
855 notice_finished_file (child
->file
);
860 /* Print out the command. If silent, we call `message' with null so it
861 can log the working directory before the command's own error messages
864 message (0, (just_print_flag
|| (!(flags
& COMMANDS_SILENT
) && !silent_flag
))
865 ? "%s" : (char *) 0, p
);
867 /* Optimize an empty command. People use this for timestamp rules,
868 so avoid forking a useless shell. */
870 #if !defined(VMS) && !defined(_AMIGA)
873 unixy_shell
/* the test is complicated and we already did it */
875 (argv
[0] && !strcmp (argv
[0], "/bin/sh"))
878 && argv
[1][0] == '-' && argv
[1][1] == 'c' && argv
[1][2] == '\0')
879 && (argv
[2] && argv
[2][0] == ':' && argv
[2][1] == '\0')
883 free ((char *) argv
);
886 #endif /* !VMS && !_AMIGA */
888 /* Tell update_goal_chain that a command has been started on behalf of
889 this target. It is important that this happens here and not in
890 reap_children (where we used to do it), because reap_children might be
891 reaping children from a different target. We want this increment to
892 guaranteedly indicate that a command was started for the dependency
893 chain (i.e., update_file recursion chain) we are processing. */
897 /* If -n was given, recurse to get the next line in the sequence. */
899 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
))
903 free ((char *) argv
);
908 /* Flush the output streams so they won't have things written twice. */
914 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
916 /* Set up a bad standard input that reads from a broken pipe. */
920 /* Make a file descriptor that is the read end of a broken pipe.
921 This will be used for some children's standard inputs. */
925 /* Close the write side. */
926 (void) close (pd
[1]);
927 /* Save the read side. */
930 /* Set the descriptor to close on exec, so it does not litter any
931 child's descriptor table. When it is dup2'd onto descriptor 0,
932 that descriptor will not close on exec. */
933 CLOSE_ON_EXEC (bad_stdin
);
937 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
939 /* Decide whether to give this child the `good' standard input
940 (one that points to the terminal or whatever), or the `bad' one
941 that points to the read side of a broken pipe. */
943 child
->good_stdin
= !good_stdin_used
;
944 if (child
->good_stdin
)
952 /* Set up the environment for the child. */
953 if (child
->environment
== 0)
954 child
->environment
= target_environment (child
->file
);
957 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
960 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
963 int is_remote
, id
, used_stdin
;
964 if (start_remote_job (argv
, child
->environment
,
965 child
->good_stdin
? 0 : bad_stdin
,
966 &is_remote
, &id
, &used_stdin
))
967 /* Don't give up; remote execution may fail for various reasons. If
968 so, simply run the job locally. */
972 if (child
->good_stdin
&& !used_stdin
)
974 child
->good_stdin
= 0;
977 child
->remote
= is_remote
;
984 /* Fork the child process. */
986 char **parent_environ
;
995 if (!child_execute_job (argv
, child
)) {
997 perror_with_name ("vfork", "");
1003 parent_environ
= environ
;
1004 child
->pid
= vfork ();
1005 environ
= parent_environ
; /* Restore value child may have clobbered. */
1006 if (child
->pid
== 0)
1008 /* We are the child side. */
1011 /* If we aren't running a recursive command and we have a jobserver
1012 pipe, close it before exec'ing. */
1013 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1021 child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1022 argv
, child
->environment
);
1024 else if (child
->pid
< 0)
1028 perror_with_name ("vfork", "");
1034 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1042 /* We call `system' to do the job of the SHELL, since stock DOS
1043 shell is too dumb. Our `system' knows how to handle long
1044 command lines even if pipes/redirection is needed; it will only
1045 call COMMAND.COM when its internal commands are used. */
1046 if (execute_by_shell
)
1048 char *cmdline
= argv
[0];
1049 /* We don't have a way to pass environment to `system',
1050 so we need to save and restore ours, sigh... */
1051 char **parent_environ
= environ
;
1053 environ
= child
->environment
;
1055 /* If we have a *real* shell, tell `system' to call
1056 it to do everything for us. */
1059 /* A *real* shell on MSDOS may not support long
1060 command lines the DJGPP way, so we must use `system'. */
1061 cmdline
= argv
[2]; /* get past "shell -c" */
1064 dos_command_running
= 1;
1065 proc_return
= system (cmdline
);
1066 environ
= parent_environ
;
1067 execute_by_shell
= 0; /* for the next time */
1071 dos_command_running
= 1;
1072 proc_return
= spawnvpe (P_WAIT
, argv
[0], argv
, child
->environment
);
1075 /* Need to unblock signals before turning off
1076 dos_command_running, so that child's signals
1077 will be treated as such (see fatal_error_signal). */
1079 dos_command_running
= 0;
1081 /* If the child got a signal, dos_status has its
1082 high 8 bits set, so be careful not to alter them. */
1083 if (proc_return
== -1)
1086 dos_status
|= (proc_return
& 0xff);
1088 child
->pid
= dos_pid
++;
1090 #endif /* __MSDOS__ */
1092 amiga_status
= MyExecute (argv
);
1095 child
->pid
= amiga_pid
++;
1096 if (amiga_batch_file
)
1098 amiga_batch_file
= 0;
1099 DeleteFile (amiga_bname
); /* Ignore errors. */
1107 /* make UNC paths safe for CreateProcess -- backslash format */
1109 if (arg0
&& arg0
[0] == '/' && arg0
[1] == '/')
1110 for ( ; arg0
&& *arg0
; arg0
++)
1114 /* make sure CreateProcess() has Path it needs */
1115 sync_Path_environment();
1117 hPID
= process_easy(argv
, child
->environment
);
1119 if (hPID
!= INVALID_HANDLE_VALUE
)
1120 child
->pid
= (int) hPID
;
1125 _("process_easy() failed failed to launch process (e=%d)\n"),
1126 process_last_err(hPID
));
1127 for (i
= 0; argv
[i
]; i
++)
1128 fprintf(stderr
, "%s ", argv
[i
]);
1129 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
1132 #endif /* WINDOWS32 */
1133 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1135 /* We are the parent side. Set the state to
1136 say the commands are running and return. */
1138 set_command_state (child
->file
, cs_running
);
1140 /* Free the storage used by the child's argument list. */
1143 free ((char *) argv
);
1149 child
->file
->update_status
= 2;
1150 notice_finished_file (child
->file
);
1154 /* Try to start a child running.
1155 Returns nonzero if the child was started (and maybe finished), or zero if
1156 the load was too high and the child was put on the `waiting_jobs' chain. */
1159 start_waiting_job (c
)
1162 struct file
*f
= c
->file
;
1164 /* If we can start a job remotely, we always want to, and don't care about
1165 the local load average. We record that the job should be started
1166 remotely in C->remote for start_job_command to test. */
1168 c
->remote
= start_remote_job_p (1);
1170 /* If we are running at least one job already and the load average
1171 is too high, make this one wait. */
1172 if (!c
->remote
&& job_slots_used
> 0 && load_too_high ())
1174 /* Put this child on the chain of children waiting for the load average
1176 set_command_state (f
, cs_running
);
1177 c
->next
= waiting_jobs
;
1182 /* Start the first command; reap_children will run later command lines. */
1183 start_job_command (c
);
1185 switch (f
->command_state
)
1190 printf (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1191 (unsigned long int) c
, c
->file
->name
,
1192 (long) c
->pid
, c
->remote
? _(" (remote)") : "");
1194 /* One more job slot is in use. */
1199 case cs_not_started
:
1200 /* All the command lines turned out to be empty. */
1201 f
->update_status
= 0;
1205 notice_finished_file (f
);
1210 assert (f
->command_state
== cs_finished
);
1217 /* Create a `struct child' for FILE and start its commands running. */
1221 register struct file
*file
;
1223 register struct commands
*cmds
= file
->cmds
;
1224 register struct child
*c
;
1226 register unsigned int i
;
1228 /* Let any previously decided-upon jobs that are waiting
1229 for the load to go down start before this new one. */
1230 start_waiting_jobs ();
1232 /* Reap any children that might have finished recently. */
1233 reap_children (0, 0);
1235 /* Chop the commands up into lines if they aren't already. */
1236 chop_commands (cmds
);
1238 /* Expand the command lines and store the results in LINES. */
1239 lines
= (char **) xmalloc (cmds
->ncommand_lines
* sizeof (char *));
1240 for (i
= 0; i
< cmds
->ncommand_lines
; ++i
)
1242 /* Collapse backslash-newline combinations that are inside variable
1243 or function references. These are left alone by the parser so
1244 that they will appear in the echoing of commands (where they look
1245 nice); and collapsed by construct_command_argv when it tokenizes.
1246 But letting them survive inside function invocations loses because
1247 we don't want the functions to see them as part of the text. */
1249 char *in
, *out
, *ref
;
1251 /* IN points to where in the line we are scanning.
1252 OUT points to where in the line we are writing.
1253 When we collapse a backslash-newline combination,
1254 IN gets ahead of OUT. */
1256 in
= out
= cmds
->command_lines
[i
];
1257 while ((ref
= index (in
, '$')) != 0)
1259 ++ref
; /* Move past the $. */
1262 /* Copy the text between the end of the last chunk
1263 we processed (where IN points) and the new chunk
1264 we are about to process (where REF points). */
1265 bcopy (in
, out
, ref
- in
);
1267 /* Move both pointers past the boring stuff. */
1271 if (*ref
== '(' || *ref
== '{')
1273 char openparen
= *ref
;
1274 char closeparen
= openparen
== '(' ? ')' : '}';
1278 *out
++ = *in
++; /* Copy OPENPAREN. */
1279 /* IN now points past the opening paren or brace.
1280 Count parens or braces until it is matched. */
1284 if (*in
== closeparen
&& --count
< 0)
1286 else if (*in
== '\\' && in
[1] == '\n')
1288 /* We have found a backslash-newline inside a
1289 variable or function reference. Eat it and
1290 any following whitespace. */
1293 for (p
= in
- 1; p
> ref
&& *p
== '\\'; --p
)
1297 /* There were two or more backslashes, so this is
1298 not really a continuation line. We don't collapse
1299 the quoting backslashes here as is done in
1300 collapse_continuations, because the line will
1301 be collapsed again after expansion. */
1305 /* Skip the backslash, newline and
1306 any following whitespace. */
1307 in
= next_token (in
+ 2);
1309 /* Discard any preceding whitespace that has
1310 already been written to the output. */
1311 while (out
> ref
&& isblank (out
[-1]))
1314 /* Replace it all with a single space. */
1320 if (*in
== openparen
)
1329 /* There are no more references in this line to worry about.
1330 Copy the remaining uninteresting text to the output. */
1334 /* Finally, expand the line. */
1335 lines
[i
] = allocated_variable_expand_for_file (cmds
->command_lines
[i
],
1339 /* Start the command sequence, record it in a new
1340 `struct child', and add that to the chain. */
1342 c
= (struct child
*) xmalloc (sizeof (struct child
));
1344 c
->command_lines
= lines
;
1345 c
->command_line
= 0;
1348 c
->sh_batch_file
= NULL
;
1350 /* Fetch the first command line to be run. */
1351 job_next_command (c
);
1353 /* Wait for a job slot to be freed up. If we allow an infinite number
1354 don't bother; also job_slots will == 0 if we're using the jobserver. */
1357 while (job_slots_used
== job_slots
)
1358 reap_children (1, 0);
1360 #ifdef MAKE_JOBSERVER
1361 /* If we are controlling multiple jobs make sure we have a token before
1362 starting the child. */
1364 /* This can be inefficient. There's a decent chance that this job won't
1365 actually have to run any subprocesses: the command script may be empty
1366 or otherwise optimized away. It would be nice if we could defer
1367 obtaining a token until just before we need it, in start_job_command.
1368 To do that we'd need to keep track of whether we'd already obtained a
1369 token (since start_job_command is called for each line of the job, not
1370 just once). Also more thought needs to go into the entire algorithm;
1371 this is where the old parallel job code waits, so... */
1373 else if (job_fds
[0] >= 0)
1378 /* If we don't already have a job started, use our "free" token. */
1382 /* Read a token. As long as there's no token available we'll block.
1383 If we get a SIGCHLD we'll return with EINTR. If one happened
1384 before we got here we'll return immediately with EBADF because
1385 the signal handler closes the dup'd file descriptor. */
1387 if (read (job_rfd
, &token
, 1) == 1)
1390 printf (_("Obtained token for child 0x%08lx (%s).\n"),
1391 (unsigned long int) c
, c
->file
->name
);
1395 if (errno
!= EINTR
&& errno
!= EBADF
)
1396 pfatal_with_name (_("read jobs pipe"));
1398 /* Re-dup the read side of the pipe, so the signal handler can
1399 notify us if we miss a child. */
1401 job_rfd
= dup (job_fds
[0]);
1403 /* Something's done. We don't want to block for a whole child,
1404 just reap whatever's there. */
1405 reap_children (0, 0);
1409 /* The job is now primed. Start it running.
1410 (This will notice if there are in fact no commands.) */
1411 (void) start_waiting_job (c
);
1414 /* Since there is only one job slot, make things run linearly.
1415 Wait for the child to die, setting the state to `cs_finished'. */
1416 while (file
->command_state
== cs_running
)
1417 reap_children (1, 0);
1422 /* Move CHILD's pointers to the next command for it to execute.
1423 Returns nonzero if there is another command. */
1426 job_next_command (child
)
1427 struct child
*child
;
1429 while (child
->command_ptr
== 0 || *child
->command_ptr
== '\0')
1431 /* There are no more lines in the expansion of this line. */
1432 if (child
->command_line
== child
->file
->cmds
->ncommand_lines
)
1434 /* There are no more lines to be expanded. */
1435 child
->command_ptr
= 0;
1439 /* Get the next line to run. */
1440 child
->command_ptr
= child
->command_lines
[child
->command_line
++];
1448 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1453 if (max_load_average
< 0)
1457 if (getloadavg (&load
, 1) != 1)
1459 static int lossage
= -1;
1460 /* Complain only once for the same error. */
1461 if (lossage
== -1 || errno
!= lossage
)
1464 /* An errno value of zero means getloadavg is just unsupported. */
1465 error (NILF
, _("cannot enforce load limits on this operating system"));
1467 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1474 return load
>= max_load_average
;
1478 /* Start jobs that are waiting for the load to be lower. */
1481 start_waiting_jobs ()
1485 if (waiting_jobs
== 0)
1490 /* Check for recently deceased descendants. */
1491 reap_children (0, 0);
1493 /* Take a job off the waiting list. */
1495 waiting_jobs
= job
->next
;
1497 /* Try to start that job. We break out of the loop as soon
1498 as start_waiting_job puts one back on the waiting list. */
1500 while (start_waiting_job (job
) && waiting_jobs
!= 0);
1507 #include <descrip.h>
1510 /* This is called as an AST when a child process dies (it won't get
1511 interrupted by anything except a higher level AST).
1513 int vmsHandleChildTerm(struct child
*child
)
1516 register struct child
*lastc
, *c
;
1519 vms_jobsefnmask
&= ~(1 << (child
->efn
- 32));
1521 lib$
free_ef(&child
->efn
);
1523 (void) sigblock (fatal_signal_mask
);
1525 child_failed
= !(child
->cstatus
& 1 || ((child
->cstatus
& 7) == 0));
1527 /* Search for a child matching the deceased one. */
1529 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1530 for (c
= children
; c
!= 0 && c
!= child
; lastc
= c
, c
= c
->next
);
1535 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
1537 /* The commands failed. Write an error message,
1538 delete non-precious targets, and abort. */
1539 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 0);
1540 c
->file
->update_status
= 1;
1541 delete_child_targets (c
);
1547 /* The commands failed, but we don't care. */
1548 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 1);
1552 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1553 /* If there are more commands to run, try to start them. */
1556 switch (c
->file
->command_state
)
1559 /* Successfully started. */
1563 if (c
->file
->update_status
!= 0) {
1564 /* We failed to start the commands. */
1565 delete_child_targets (c
);
1570 error (NILF
, _("internal error: `%s' command_state"), c
->file
->name
);
1574 #endif /* RECURSIVEJOBS */
1577 /* Set the state flag to say the commands have finished. */
1578 c
->file
->command_state
= cs_finished
;
1579 notice_finished_file (c
->file
);
1581 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1582 /* Remove the child from the chain and free it. */
1586 lastc
->next
= c
->next
;
1588 #endif /* RECURSIVEJOBS */
1590 /* There is now another slot open. */
1591 if (job_slots_used
> 0)
1594 /* If the job failed, and the -k flag was not given, die. */
1595 if (child_failed
&& !keep_going_flag
)
1598 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask
));
1604 Spawn a process executing the command in ARGV and return its pid. */
1606 #define MAXCMDLEN 200
1609 child_execute_job (argv
, child
)
1611 struct child
*child
;
1614 static struct dsc$descriptor_s cmddsc
;
1615 #ifndef DONTWAITFORCHILD
1618 int spflags
= CLI$M_NOWAIT
;
1621 char cmd
[4096],*p
,*c
;
1624 /* Remove backslashes */
1625 for (p
= argv
, c
= cmd
; *p
; p
++,c
++)
1627 if (*p
== '\\') p
++;
1632 /* Check for maximum DCL length and create *.com file if neccesary.
1633 Also create a .com file if the command is more than one line long. */
1637 if (strlen (cmd
) > MAXCMDLEN
|| strchr (cmd
, '\n'))
1642 strcpy (comname
, "sys$scratch:CMDXXXXXX.COM");
1643 (void) mktemp (comname
);
1645 outfile
= fopen (comname
, "w");
1647 pfatal_with_name (comname
);
1649 fprintf (outfile
, "$ ");
1654 p
= strchr (c
, ',');
1655 if ((p
== NULL
) || (p
-c
> MAXCMDLEN
))
1656 p
= strchr (c
, ' ');
1665 fprintf (outfile
, "%s%s\n", c
, (tmp
== '\0')?"":" -");
1673 sprintf (cmd
, "$ @%s", comname
);
1676 printf (_("Executing %s instead\n"), cmd
);
1679 cmddsc
.dsc$w_length
= strlen(cmd
);
1680 cmddsc
.dsc$a_pointer
= cmd
;
1681 cmddsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
1682 cmddsc
.dsc$b_class
= DSC$K_CLASS_S
;
1685 while (child
->efn
< 32 || child
->efn
> 63)
1687 status
= lib$
get_ef(&child
->efn
);
1692 sys$
clref(child
->efn
);
1694 vms_jobsefnmask
|= (1 << (child
->efn
- 32));
1696 #ifndef DONTWAITFORCHILD
1697 status
= lib$
spawn(&cmddsc
,0,0,&spflags
,0,&child
->pid
,&child
->cstatus
,
1699 vmsHandleChildTerm(child
);
1701 status
= lib$
spawn(&cmddsc
,0,0,&spflags
,0,&child
->pid
,&child
->cstatus
,
1702 &child
->efn
,vmsHandleChildTerm
,child
);
1707 printf(_("Error spawning, %d\n"),status
);
1713 return (status
& 1);
1718 #if !defined (_AMIGA) && !defined (__MSDOS__)
1720 Replace the current process with one executing the command in ARGV.
1721 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1722 the environment of the new program. This function does not return. */
1725 child_execute_job (stdin_fd
, stdout_fd
, argv
, envp
)
1726 int stdin_fd
, stdout_fd
;
1727 char **argv
, **envp
;
1730 (void) dup2 (stdin_fd
, 0);
1732 (void) dup2 (stdout_fd
, 1);
1734 (void) close (stdin_fd
);
1736 (void) close (stdout_fd
);
1738 /* Run the command. */
1739 exec_command (argv
, envp
);
1741 #endif /* !AMIGA && !__MSDOS__ */
1743 #endif /* !WINDOWS32 */
1746 /* Replace the current process with one running the command in ARGV,
1747 with environment ENVP. This function does not return. */
1750 exec_command (argv
, envp
)
1751 char **argv
, **envp
;
1754 /* Run the program. */
1755 execve (argv
[0], argv
, envp
);
1756 perror_with_name ("execve: ", argv
[0]);
1757 _exit (EXIT_FAILURE
);
1763 int exit_code
= EXIT_FAILURE
;
1765 /* make sure CreateProcess() has Path it needs */
1766 sync_Path_environment();
1768 /* launch command */
1769 hPID
= process_easy(argv
, envp
);
1771 /* make sure launch ok */
1772 if (hPID
== INVALID_HANDLE_VALUE
)
1776 _("process_easy() failed failed to launch process (e=%d)\n"),
1777 process_last_err(hPID
));
1778 for (i
= 0; argv
[i
]; i
++)
1779 fprintf(stderr
, "%s ", argv
[i
]);
1780 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
1784 /* wait and reap last child */
1785 while (hWaitPID
= process_wait_for_any())
1787 /* was an error found on this process? */
1788 err
= process_last_err(hWaitPID
);
1791 exit_code
= process_exit_code(hWaitPID
);
1794 fprintf(stderr
, "make (e=%d, rc=%d): %s",
1795 err
, exit_code
, map_windows32_error_to_string(err
));
1797 /* cleanup process */
1798 process_cleanup(hWaitPID
);
1800 /* expect to find only last pid, warn about other pids reaped */
1801 if (hWaitPID
== hPID
)
1805 _("make reaped child pid %d, still waiting for pid %d\n"),
1809 /* return child's exit code as our exit code */
1812 #else /* !WINDOWS32 */
1814 /* Be the user, permanently. */
1817 /* Run the program. */
1819 execvp (argv
[0], argv
);
1824 error (NILF
, _("%s: Command not found"), argv
[0]);
1828 /* The file is not executable. Try it as a shell script. */
1829 extern char *getenv ();
1834 shell
= getenv ("SHELL");
1836 shell
= default_shell
;
1839 while (argv
[argc
] != 0)
1842 new_argv
= (char **) alloca ((1 + argc
+ 1) * sizeof (char *));
1843 new_argv
[0] = shell
;
1844 new_argv
[1] = argv
[0];
1847 new_argv
[1 + argc
] = argv
[argc
];
1851 execvp (shell
, new_argv
);
1852 if (errno
== ENOENT
)
1853 error (NILF
, _("%s: Shell program not found"), shell
);
1855 perror_with_name ("execvp: ", shell
);
1860 perror_with_name ("execvp: ", argv
[0]);
1865 #endif /* !WINDOWS32 */
1868 #else /* On Amiga */
1869 void exec_command (argv
)
1875 void clean_tmp (void)
1877 DeleteFile (amiga_bname
);
1880 #endif /* On Amiga */
1883 /* Figure out the argument list necessary to run LINE as a command. Try to
1884 avoid using a shell. This routine handles only ' quoting, and " quoting
1885 when no backslash, $ or ` characters are seen in the quotes. Starting
1886 quotes may be escaped with a backslash. If any of the characters in
1887 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1888 is the first word of a line, the shell is used.
1890 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1891 If *RESTP is NULL, newlines will be ignored.
1893 SHELL is the shell to use, or nil to use the default shell.
1894 IFS is the value of $IFS, or nil (meaning the default). */
1897 construct_command_argv_internal (line
, restp
, shell
, ifs
, batch_filename_ptr
)
1898 char *line
, **restp
;
1900 char **batch_filename_ptr
;
1903 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
1904 We call `system' for anything that requires ``slow'' processing,
1905 because DOS shells are too dumb. When $SHELL points to a real
1906 (unix-style) shell, `system' just calls it to do everything. When
1907 $SHELL points to a DOS shell, `system' does most of the work
1908 internally, calling the shell only for its internal commands.
1909 However, it looks on the $PATH first, so you can e.g. have an
1910 external command named `mkdir'.
1912 Since we call `system', certain characters and commands below are
1913 actually not specific to COMMAND.COM, but to the DJGPP implementation
1914 of `system'. In particular:
1916 The shell wildcard characters are in DOS_CHARS because they will
1917 not be expanded if we call the child via `spawnXX'.
1919 The `;' is in DOS_CHARS, because our `system' knows how to run
1920 multiple commands on a single line.
1922 DOS_CHARS also include characters special to 4DOS/NDOS, so we
1923 won't have to tell one from another and have one more set of
1924 commands and special characters. */
1925 static char sh_chars_dos
[] = "*?[];|<>%^&()";
1926 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1927 "copy", "ctty", "date", "del", "dir", "echo",
1928 "erase", "exit", "for", "goto", "if", "md",
1929 "mkdir", "path", "pause", "prompt", "rd",
1930 "rmdir", "rem", "ren", "rename", "set",
1931 "shift", "time", "type", "ver", "verify",
1934 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
1935 static char *sh_cmds_sh
[] = { "cd", "echo", "eval", "exec", "exit", "login",
1936 "logout", "set", "umask", "wait", "while",
1937 "for", "case", "if", ":", ".", "break",
1938 "continue", "export", "read", "readonly",
1939 "shift", "times", "trap", "switch", "unset",
1946 static char sh_chars
[] = "#;\"|<>()?*$`";
1947 static char *sh_cmds
[] = { "cd", "eval", "if", "delete", "echo", "copy",
1948 "rename", "set", "setenv", "date", "makedir",
1949 "skip", "else", "endif", "path", "prompt",
1950 "unset", "unsetenv", "version",
1954 static char sh_chars_dos
[] = "\"|<>";
1955 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1956 "copy", "ctty", "date", "del", "dir", "echo",
1957 "erase", "exit", "for", "goto", "if", "if", "md",
1958 "mkdir", "path", "pause", "prompt", "rem", "ren",
1959 "rename", "set", "shift", "time", "type",
1960 "ver", "verify", "vol", ":", 0 };
1961 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
1962 static char *sh_cmds_sh
[] = { "cd", "eval", "exec", "exit", "login",
1963 "logout", "set", "umask", "wait", "while", "for",
1964 "case", "if", ":", ".", "break", "continue",
1965 "export", "read", "readonly", "shift", "times",
1966 "trap", "switch", "test",
1967 #ifdef BATCH_MODE_ONLY_SHELL
1973 #else /* WINDOWS32 */
1974 static char sh_chars
[] = "#;\"*?[]&|<>(){}$`^";
1975 static char *sh_cmds
[] = { "cd", "eval", "exec", "exit", "login",
1976 "logout", "set", "umask", "wait", "while", "for",
1977 "case", "if", ":", ".", "break", "continue",
1978 "export", "read", "readonly", "shift", "times",
1979 "trap", "switch", 0 };
1980 #endif /* WINDOWS32 */
1982 #endif /* __MSDOS__ */
1987 int instring
, word_has_equals
, seen_nonequals
, last_argument_was_empty
;
1988 char **new_argv
= 0;
1992 if (no_default_sh_exe
) {
1993 sh_cmds
= sh_cmds_dos
;
1994 sh_chars
= sh_chars_dos
;
1996 sh_cmds
= sh_cmds_sh
;
1997 sh_chars
= sh_chars_sh
;
1999 #endif /* WINDOWS32 */
2004 /* Make sure not to bother processing an empty line. */
2005 while (isblank (*line
))
2010 /* See if it is safe to parse commands internally. */
2012 shell
= default_shell
;
2014 else if (strcmp (shell
, default_shell
))
2016 char *s1
= _fullpath(NULL
, shell
, 0);
2017 char *s2
= _fullpath(NULL
, default_shell
, 0);
2019 slow_flag
= strcmp((s1
? s1
: ""), (s2
? s2
: ""));
2028 #else /* not WINDOWS32 */
2030 else if (stricmp (shell
, default_shell
))
2032 extern int _is_unixy_shell (const char *_path
);
2034 message (1, _("$SHELL changed (was `%s', now `%s')"), default_shell
, shell
);
2035 unixy_shell
= _is_unixy_shell (shell
);
2036 default_shell
= shell
;
2040 sh_chars
= sh_chars_sh
;
2041 sh_cmds
= sh_cmds_sh
;
2045 sh_chars
= sh_chars_dos
;
2046 sh_cmds
= sh_cmds_dos
;
2048 #else /* not __MSDOS__ */
2049 else if (strcmp (shell
, default_shell
))
2051 #endif /* not __MSDOS__ */
2052 #endif /* not WINDOWS32 */
2055 for (ap
= ifs
; *ap
!= '\0'; ++ap
)
2056 if (*ap
!= ' ' && *ap
!= '\t' && *ap
!= '\n')
2059 i
= strlen (line
) + 1;
2061 /* More than 1 arg per character is impossible. */
2062 new_argv
= (char **) xmalloc (i
* sizeof (char *));
2064 /* All the args can fit in a buffer as big as LINE is. */
2065 ap
= new_argv
[0] = (char *) xmalloc (i
);
2068 /* I is how many complete arguments have been found. */
2070 instring
= word_has_equals
= seen_nonequals
= last_argument_was_empty
= 0;
2071 for (p
= line
; *p
!= '\0'; ++p
)
2079 /* Inside a string, just copy any char except a closing quote
2080 or a backslash-newline combination. */
2084 if (ap
== new_argv
[0] || *(ap
-1) == '\0')
2085 last_argument_was_empty
= 1;
2087 else if (*p
== '\\' && p
[1] == '\n')
2088 goto swallow_escaped_newline
;
2089 else if (*p
== '\n' && restp
!= NULL
)
2091 /* End of the command line. */
2095 /* Backslash, $, and ` are special inside double quotes.
2096 If we see any of those, punt.
2097 But on MSDOS, if we use COMMAND.COM, double and single
2098 quotes have the same effect. */
2099 else if (instring
== '"' && index ("\\$`", *p
) != 0 && unixy_shell
)
2104 else if (index (sh_chars
, *p
) != 0)
2105 /* Not inside a string, but it's a special char. */
2108 else if (*p
== '.' && p
[1] == '.' && p
[2] == '.' && p
[3] != '.')
2109 /* `...' is a wildcard in DJGPP. */
2113 /* Not a special char. */
2117 /* Equals is a special character in leading words before the
2118 first word with no equals sign in it. This is not the case
2119 with sh -k, but we never get here when using nonstandard
2121 if (! seen_nonequals
&& unixy_shell
)
2123 word_has_equals
= 1;
2128 /* Backslash-newline combinations are eaten. */
2131 swallow_escaped_newline
:
2133 /* Eat the backslash, the newline, and following whitespace,
2134 replacing it all with a single space. */
2137 /* If there is a tab after a backslash-newline,
2138 remove it from the source line which will be echoed,
2139 since it was most likely used to line
2140 up the continued line with the previous one. */
2142 /* Note these overlap and strcpy() is undefined for
2143 overlapping objects in ANSI C. The strlen() _IS_ right,
2144 since we need to copy the nul byte too. */
2145 bcopy (p
+ 1, p
, strlen (p
));
2151 if (ap
!= new_argv
[i
])
2152 /* Treat this as a space, ending the arg.
2153 But if it's at the beginning of the arg, it should
2154 just get eaten, rather than becoming an empty arg. */
2157 p
= next_token (p
) - 1;
2160 else if (p
[1] != '\0')
2162 #if defined(__MSDOS__) || defined(WINDOWS32)
2163 /* Only remove backslashes before characters special
2164 to Unixy shells. All other backslashes are copied
2165 verbatim, since they are probably DOS-style
2166 directory separators. This still leaves a small
2167 window for problems, but at least it should work
2168 for the vast majority of naive users. */
2171 /* A dot is only special as part of the "..."
2173 if (strneq (p
+ 1, ".\\.\\.", 5))
2181 if (p
[1] != '\\' && p
[1] != '\'' && !isspace (p
[1])
2182 && (index (sh_chars_sh
, p
[1]) == 0))
2183 /* back up one notch, to copy the backslash */
2186 #endif /* __MSDOS__ || WINDOWS32 */
2187 /* Copy and skip the following char. */
2200 /* End of the command line. */
2205 /* Newlines are not special. */
2212 /* We have the end of an argument.
2213 Terminate the text of the argument. */
2216 last_argument_was_empty
= 0;
2218 /* Update SEEN_NONEQUALS, which tells us if every word
2219 heretofore has contained an `='. */
2220 seen_nonequals
|= ! word_has_equals
;
2221 if (word_has_equals
&& ! seen_nonequals
)
2222 /* An `=' in a word before the first
2223 word without one is magical. */
2225 word_has_equals
= 0; /* Prepare for the next word. */
2227 /* If this argument is the command name,
2228 see if it is a built-in shell command.
2229 If so, have the shell handle it. */
2233 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2234 if (streq (sh_cmds
[j
], new_argv
[0]))
2238 /* Ignore multiple whitespace chars. */
2240 /* Next iteration should examine the first nonwhite char. */
2252 /* Let the shell deal with an unterminated quote. */
2255 /* Terminate the last argument and the argument list. */
2258 if (new_argv
[i
][0] != '\0' || last_argument_was_empty
)
2265 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2266 if (streq (sh_cmds
[j
], new_argv
[0]))
2270 if (new_argv
[0] == 0)
2271 /* Line was empty. */
2277 /* We must use the shell. */
2281 /* Free the old argument list we were working on. */
2283 free ((void *)new_argv
);
2287 execute_by_shell
= 1; /* actually, call `system' if shell isn't unixy */
2296 buffer
= (char *)xmalloc (strlen (line
)+1);
2299 for (dptr
=buffer
; *ptr
; )
2301 if (*ptr
== '\\' && ptr
[1] == '\n')
2303 else if (*ptr
== '@') /* Kludge: multiline commands */
2313 new_argv
= (char **) xmalloc (2 * sizeof (char *));
2314 new_argv
[0] = buffer
;
2317 #else /* Not Amiga */
2320 * Not eating this whitespace caused things like
2324 * which gave the shell fits. I think we have to eat
2325 * whitespace here, but this code should be considered
2326 * suspicious if things start failing....
2329 /* Make sure not to bother processing an empty line. */
2330 while (isspace (*line
))
2334 #endif /* WINDOWS32 */
2336 /* SHELL may be a multi-word command. Construct a command line
2337 "SHELL -c LINE", with all special chars in LINE escaped.
2338 Then recurse, expanding this command line to get the final
2341 unsigned int shell_len
= strlen (shell
);
2342 static char minus_c
[] = " -c ";
2343 unsigned int line_len
= strlen (line
);
2345 char *new_line
= (char *) alloca (shell_len
+ (sizeof (minus_c
) - 1)
2346 + (line_len
* 2) + 1);
2347 char* command_ptr
= NULL
; /* used for batch_mode_shell mode */
2350 bcopy (shell
, ap
, shell_len
);
2352 bcopy (minus_c
, ap
, sizeof (minus_c
) - 1);
2353 ap
+= sizeof (minus_c
) - 1;
2355 for (p
= line
; *p
!= '\0'; ++p
)
2357 if (restp
!= NULL
&& *p
== '\n')
2362 else if (*p
== '\\' && p
[1] == '\n')
2364 /* Eat the backslash, the newline, and following whitespace,
2365 replacing it all with a single space (which is escaped
2369 /* If there is a tab after a backslash-newline,
2370 remove it from the source line which will be echoed,
2371 since it was most likely used to line
2372 up the continued line with the previous one. */
2374 bcopy (p
+ 1, p
, strlen (p
));
2378 if (unixy_shell
&& !batch_mode_shell
)
2384 /* DOS shells don't know about backslash-escaping. */
2385 if (unixy_shell
&& !batch_mode_shell
&&
2386 (*p
== '\\' || *p
== '\'' || *p
== '"'
2388 || index (sh_chars
, *p
) != 0))
2391 else if (unixy_shell
&& strneq (p
, "...", 3))
2393 /* The case of `...' wildcard again. */
2394 strcpy (ap
, "\\.\\.\\");
2401 if (ap
== new_line
+ shell_len
+ sizeof (minus_c
) - 1)
2402 /* Line was empty. */
2407 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2408 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2409 cases, run commands via a script file. */
2410 if ((no_default_sh_exe
|| batch_mode_shell
) && batch_filename_ptr
) {
2412 int id
= GetCurrentProcessId();
2416 /* create a file name */
2417 sprintf(fbuf
, "make%d", id
);
2418 fname
= tempnam(".", fbuf
);
2420 /* create batch file name */
2421 *batch_filename_ptr
= xmalloc(strlen(fname
) + 5);
2422 strcpy(*batch_filename_ptr
, fname
);
2424 /* make sure path name is in DOS backslash format */
2426 fname
= *batch_filename_ptr
;
2427 for (i
= 0; fname
[i
] != '\0'; ++i
)
2428 if (fname
[i
] == '/')
2430 strcat(*batch_filename_ptr
, ".bat");
2432 strcat(*batch_filename_ptr
, ".sh");
2436 printf(_("Creating temporary batch file %s\n"), *batch_filename_ptr
);
2438 /* create batch file to execute command */
2439 batch
= fopen (*batch_filename_ptr
, "w");
2441 fputs ("@echo off\n", batch
);
2442 fputs (command_ptr
, batch
);
2443 fputc ('\n', batch
);
2447 new_argv
= (char **) xmalloc(3 * sizeof(char *));
2449 new_argv
[0] = xstrdup (shell
);
2450 new_argv
[1] = *batch_filename_ptr
; /* only argv[0] gets freed later */
2452 new_argv
[0] = xstrdup (*batch_filename_ptr
);
2457 #endif /* WINDOWS32 */
2459 new_argv
= construct_command_argv_internal (new_line
, (char **) NULL
,
2460 (char *) 0, (char *) 0,
2465 /* With MSDOS shells, we must construct the command line here
2466 instead of recursively calling ourselves, because we
2467 cannot backslash-escape the special characters (see above). */
2468 new_argv
= (char **) xmalloc (sizeof (char *));
2469 line_len
= strlen (new_line
) - shell_len
- sizeof (minus_c
) + 1;
2470 new_argv
[0] = xmalloc (line_len
+ 1);
2471 strncpy (new_argv
[0],
2472 new_line
+ shell_len
+ sizeof (minus_c
) - 1, line_len
);
2473 new_argv
[0][line_len
] = '\0';
2477 fatal (NILF
, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2478 __FILE__
, __LINE__
);
2481 #endif /* ! AMIGA */
2486 /* Figure out the argument list necessary to run LINE as a command. Try to
2487 avoid using a shell. This routine handles only ' quoting, and " quoting
2488 when no backslash, $ or ` characters are seen in the quotes. Starting
2489 quotes may be escaped with a backslash. If any of the characters in
2490 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2491 is the first word of a line, the shell is used.
2493 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2494 If *RESTP is NULL, newlines will be ignored.
2496 FILE is the target whose commands these are. It is used for
2497 variable expansion for $(SHELL) and $(IFS). */
2500 construct_command_argv (line
, restp
, file
, batch_filename_ptr
)
2501 char *line
, **restp
;
2503 char** batch_filename_ptr
;
2509 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2510 int save
= warn_undefined_variables_flag
;
2511 warn_undefined_variables_flag
= 0;
2513 shell
= allocated_variable_expand_for_file ("$(SHELL)", file
);
2516 * Convert to forward slashes so that construct_command_argv_internal()
2520 char *p
= w32ify(shell
, 0);
2524 ifs
= allocated_variable_expand_for_file ("$(IFS)", file
);
2526 warn_undefined_variables_flag
= save
;
2529 argv
= construct_command_argv_internal (line
, restp
, shell
, ifs
, batch_filename_ptr
);
2538 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2556 #endif /* !HAPE_DUP2 && !_AMIGA */