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. */
33 /* Default shell to use. */
36 char *default_shell
= "sh.exe";
37 int no_default_sh_exe
= 1;
38 int batch_mode_shell
= 1;
40 #elif defined (_AMIGA)
42 char default_shell
[] = "";
43 extern int MyExecute (char **);
44 int batch_mode_shell
= 0;
46 #elif defined (__MSDOS__)
48 /* The default shell is a pointer so we can change it if Makefile
49 says so. It is without an explicit path so we get a chance
50 to search the $PATH for it (since MSDOS doesn't have standard
51 directories we could trust). */
52 char *default_shell
= "command.com";
53 int batch_mode_shell
= 0;
55 #elif defined (__EMX__)
57 const char *default_shell
= "/bin/sh";
58 int batch_mode_shell
= 0;
63 char default_shell
[] = "";
64 int batch_mode_shell
= 0;
68 char default_shell
[] = "/bin/sh";
69 int batch_mode_shell
= 0;
75 static int execute_by_shell
;
76 static int dos_pid
= 123;
78 int dos_command_running
;
79 #endif /* __MSDOS__ */
82 # include <proto/dos.h>
83 static int amiga_pid
= 123;
84 static int amiga_status
;
85 static char amiga_bname
[32];
86 static int amiga_batch_file
;
91 # include <processes.h>
94 # include <lib$routines.h>
100 # include <process.h>
101 # include "sub_proc.h"
103 # include "pathstuff.h"
104 #endif /* WINDOWS32 */
107 # include <sys/file.h>
110 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
111 # include <sys/wait.h>
115 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
116 #else /* Don't have waitpid. */
121 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
122 # endif /* Have wait3. */
123 #endif /* Have waitpid. */
125 #if !defined (wait) && !defined (POSIX)
129 #ifndef HAVE_UNION_WAIT
134 # define WTERMSIG(x) ((x) & 0x7f)
137 # define WCOREDUMP(x) ((x) & 0x80)
140 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
143 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
146 # define WIFEXITED(x) (WTERMSIG (x) == 0)
149 #else /* Have `union wait'. */
151 # define WAIT_T union wait
153 # define WTERMSIG(x) ((x).w_termsig)
156 # define WCOREDUMP(x) ((x).w_coredump)
159 # define WEXITSTATUS(x) ((x).w_retcode)
162 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
165 # define WIFEXITED(x) (WTERMSIG(x) == 0)
168 #endif /* Don't have `union wait'. */
171 static int vms_jobsefnmask
= 0;
174 #ifndef HAVE_UNISTD_H
176 extern int execve ();
177 extern void _exit ();
179 extern int geteuid ();
180 extern int getegid ();
181 extern int setgid ();
182 extern int getgid ();
186 extern char *allocated_variable_expand_for_file
PARAMS ((char *line
, struct file
*file
));
188 extern int getloadavg
PARAMS ((double loadavg
[], int nelem
));
189 extern int start_remote_job
PARAMS ((char **argv
, char **envp
, int stdin_fd
,
190 int *is_remote
, int *id_ptr
, int *used_stdin
));
191 extern int start_remote_job_p
PARAMS ((int));
192 extern int remote_status
PARAMS ((int *exit_code_ptr
, int *signal_ptr
,
193 int *coredump_ptr
, int block
));
195 RETSIGTYPE child_handler
PARAMS ((int));
196 static void free_child
PARAMS ((struct child
*));
197 static void start_job_command
PARAMS ((struct child
*child
));
198 static int load_too_high
PARAMS ((void));
199 static int job_next_command
PARAMS ((struct child
*));
200 static int start_waiting_job
PARAMS ((struct child
*));
202 static void vmsWaitForChildren
PARAMS ((int *));
205 /* Chain of all live (or recently deceased) children. */
207 struct child
*children
= 0;
209 /* Number of children currently running. */
211 unsigned int job_slots_used
= 0;
213 /* Nonzero if the `good' standard input is in use. */
215 static int good_stdin_used
= 0;
217 /* Chain of children waiting to run until the load average goes down. */
219 static struct child
*waiting_jobs
= 0;
221 /* Non-zero if we use a *real* shell (always so on Unix). */
228 * The macro which references this function is defined in make.h.
231 w32_kill(int pid
, int sig
)
233 return ((process_kill(pid
, sig
) == TRUE
) ? 0 : -1);
235 #endif /* WINDOWS32 */
238 /* returns whether path is assumed to be a unix like shell. */
240 _is_unixy_shell (const char *path
)
242 /* list of non unix shells */
243 const char *known_os2shells
[] = {
255 /* find the rightmost '/' or '\\' */
256 const char *name
= strrchr (path
, '/');
257 const char *p
= strrchr (path
, '\\');
260 if (name
&& p
) /* take the max */
261 name
= (name
> p
) ? name
: p
;
262 else if (p
) /* name must be 0 */
264 else if (!name
) /* name and p must be 0 */
267 if (*name
== '/' || *name
== '\\') name
++;
270 while (known_os2shells
[i
] != NULL
) {
271 if (stricmp (name
, known_os2shells
[i
]) == 0) /* strcasecmp() */
272 return 0; /* not a unix shell */
276 /* in doubt assume a unix like shell */
282 /* Write an error message describing the exit status given in
283 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
284 Append "(ignored)" if IGNORED is nonzero. */
287 child_error (char *target_name
, int exit_code
, int exit_sig
, int coredump
,
290 if (ignored
&& silent_flag
)
294 if (!(exit_code
& 1))
296 (ignored
? _("*** [%s] Error 0x%x (ignored)")
297 : _("*** [%s] Error 0x%x")),
298 target_name
, exit_code
);
301 error (NILF
, ignored
? _("[%s] Error %d (ignored)") :
302 _("*** [%s] Error %d"),
303 target_name
, exit_code
);
305 error (NILF
, "*** [%s] %s%s",
306 target_name
, strsignal (exit_sig
),
307 coredump
? _(" (core dumped)") : "");
312 /* Wait for nchildren children to terminate */
314 vmsWaitForChildren(int *status
)
318 if (!vms_jobsefnmask
)
324 *status
= sys$
wflor (32, vms_jobsefnmask
);
329 /* Set up IO redirection. */
332 vms_redirect (struct dsc$descriptor_s
*desc
, char *fname
, char *ibuf
)
335 extern char *vmsify ();
338 while (isspace ((unsigned char)*ibuf
))
341 while (*ibuf
&& !isspace ((unsigned char)*ibuf
))
344 if (strcmp (fptr
, "/dev/null") != 0)
346 strcpy (fname
, vmsify (fptr
, 0));
347 if (strchr (fname
, '.') == 0)
350 desc
->dsc$w_length
= strlen(fname
);
351 desc
->dsc$a_pointer
= fname
;
352 desc
->dsc$b_dtype
= DSC$K_DTYPE_T
;
353 desc
->dsc$b_class
= DSC$K_CLASS_S
;
356 printf (_("Warning: Empty redirection\n"));
362 found apostrophe at (p-1)
364 inc p until after closing apostrophe. */
367 handle_apos (char *p
)
372 #define SEPCHARS ",/()= "
392 fprintf (stderr
, _("Syntax error, still inside '\"'\n"));
399 if (strchr (SEPCHARS
, *p
))
420 /* Handle a dead child. This handler may or may not ever be installed.
422 If we're using the jobserver feature, we need it. First, installing it
423 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
424 read FD to ensure we don't enter another blocking read without reaping all
425 the dead children. In this case we don't need the dead_children count.
427 If we don't have either waitpid or wait3, then make is unreliable, but we
428 use the dead_children count to reap children as best we can. */
430 static unsigned int dead_children
= 0;
432 #ifndef __EMX__ /* Don't use SIGCHLD handler on OS/2. */
434 child_handler (int sig
)
444 DB (DB_JOBS
, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children
));
446 #endif /* !__EMX__ */
448 extern int shell_function_pid
, shell_function_completed
;
450 /* Reap all dead children, storing the returned status and the new command
451 state (`cs_finished') in the `file' member of the `struct child' for the
452 dead child, and removing the child from the chain. In addition, if BLOCK
453 nonzero, we block in this function until we've reaped at least one
454 complete child, waiting for it to die if necessary. If ERR is nonzero,
455 print an error message first. */
458 reap_children (int block
, int err
)
461 /* Initially, assume we have some. */
465 # define REAP_MORE reap_more
467 # define REAP_MORE dead_children
472 We have at least one child outstanding OR a shell function in progress,
474 We're blocking for a complete child OR there are more children to reap
476 we'll keep reaping children. */
478 while ((children
!= 0 || shell_function_pid
!= 0)
479 && (block
|| REAP_MORE
))
483 int exit_code
, exit_sig
, coredump
;
484 register struct child
*lastc
, *c
;
486 int any_remote
, any_local
;
490 /* We might block for a while, so let the user know why. */
492 error (NILF
, _("*** Waiting for unfinished jobs...."));
495 /* We have one less dead child to reap. As noted in
496 child_handler() above, this count is completely unimportant for
497 all modern, POSIX-y systems that support wait3() or waitpid().
498 The rest of this comment below applies only to early, broken
499 pre-POSIX systems. We keep the count only because... it's there...
501 The test and decrement are not atomic; if it is compiled into:
502 register = dead_children - 1;
503 dead_children = register;
504 a SIGCHLD could come between the two instructions.
505 child_handler increments dead_children.
506 The second instruction here would lose that increment. But the
507 only effect of dead_children being wrong is that we might wait
508 longer than necessary to reap a child, and lose some parallelism;
509 and we might print the "Waiting for unfinished jobs" message above
510 when not necessary. */
512 if (dead_children
> 0)
516 any_local
= shell_function_pid
!= 0;
517 for (c
= children
; c
!= 0; c
= c
->next
)
519 any_remote
|= c
->remote
;
520 any_local
|= ! c
->remote
;
521 DB (DB_JOBS
, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
522 (unsigned long int) c
, c
->file
->name
,
523 (long) c
->pid
, c
->remote
? _(" (remote)") : ""));
529 /* First, check for remote children. */
531 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 0);
536 /* We got a remote child. */
540 /* A remote status command failed miserably. Punt. */
542 pfatal_with_name ("remote_status");
546 /* No remote children. Check for local children. */
547 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
551 vmsWaitForChildren (&status
);
556 pid
= WAIT_NOHANG (&status
);
559 pid
= wait (&status
);
567 /* The wait*() failed miserably. Punt. */
568 pfatal_with_name ("wait");
572 /* We got a child exit; chop the status word up. */
573 exit_code
= WEXITSTATUS (status
);
574 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
575 coredump
= WCOREDUMP (status
);
578 /* the SIGCHLD handler must not be used on OS/2 because, unlike
579 on UNIX systems, it had to call wait() itself. Therefore
580 job_rfd has to be closed here. */
591 /* No local children are dead. */
594 if (!block
|| !any_remote
)
597 /* Now try a blocking wait for a remote child. */
598 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 1);
600 goto remote_status_lose
;
602 /* No remote children either. Finally give up. */
605 /* We got a remote child. */
608 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
611 /* Life is very different on MSDOS. */
614 exit_code
= WEXITSTATUS (status
);
615 if (exit_code
== 0xff)
617 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
619 #endif /* __MSDOS__ */
623 status
= amiga_status
;
624 exit_code
= amiga_status
;
633 /* wait for anything to finish */
634 if (hPID
= process_wait_for_any()) {
636 /* was an error found on this process? */
637 err
= process_last_err(hPID
);
640 exit_code
= process_exit_code(hPID
);
643 fprintf(stderr
, "make (e=%d): %s",
644 exit_code
, map_windows32_error_to_string(exit_code
));
647 exit_sig
= process_signal(hPID
);
649 /* cleanup process */
650 process_cleanup(hPID
);
656 #endif /* WINDOWS32 */
659 /* Check if this is the child of the `shell' function. */
660 if (!remote
&& pid
== shell_function_pid
)
662 /* It is. Leave an indicator for the `shell' function. */
663 if (exit_sig
== 0 && exit_code
== 127)
664 shell_function_completed
= -1;
666 shell_function_completed
= 1;
670 child_failed
= exit_sig
!= 0 || exit_code
!= 0;
672 /* Search for a child matching the deceased one. */
674 for (c
= children
; c
!= 0; lastc
= c
, c
= c
->next
)
675 if (c
->remote
== remote
&& c
->pid
== pid
)
679 /* An unknown child died.
680 Ignore it; it was inherited from our invoker. */
683 DB (DB_JOBS
, (child_failed
684 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
685 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
686 (unsigned long int) c
, (long) c
->pid
,
687 c
->remote
? _(" (remote)") : ""));
689 if (c
->sh_batch_file
) {
690 DB (DB_JOBS
, (_("Cleaning up temp batch file %s\n"),
693 /* just try and remove, don't care if this fails */
694 remove (c
->sh_batch_file
);
696 /* all done with memory */
697 free (c
->sh_batch_file
);
698 c
->sh_batch_file
= NULL
;
701 /* If this child had the good stdin, say it is now free. */
705 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
707 /* The commands failed. Write an error message,
708 delete non-precious targets, and abort. */
709 static int delete_on_error
= -1;
710 child_error (c
->file
->name
, exit_code
, exit_sig
, coredump
, 0);
711 c
->file
->update_status
= 2;
712 if (delete_on_error
== -1)
714 struct file
*f
= lookup_file (".DELETE_ON_ERROR");
715 delete_on_error
= f
!= 0 && f
->is_target
;
717 if (exit_sig
!= 0 || delete_on_error
)
718 delete_child_targets (c
);
724 /* The commands failed, but we don't care. */
725 child_error (c
->file
->name
,
726 exit_code
, exit_sig
, coredump
, 1);
730 /* If there are more commands to run, try to start them. */
731 if (job_next_command (c
))
733 if (handling_fatal_signal
)
735 /* Never start new commands while we are dying.
736 Since there are more commands that wanted to be run,
737 the target was not completely remade. So we treat
738 this as if a command had failed. */
739 c
->file
->update_status
= 2;
743 /* Check again whether to start remotely.
744 Whether or not we want to changes over time.
745 Also, start_remote_job may need state set up
746 by start_remote_job_p. */
747 c
->remote
= start_remote_job_p (0);
748 start_job_command (c
);
749 /* Fatal signals are left blocked in case we were
750 about to put that child on the chain. But it is
751 already there, so it is safe for a fatal signal to
752 arrive now; it will clean up this child's targets. */
754 if (c
->file
->command_state
== cs_running
)
755 /* We successfully started the new command.
756 Loop to reap more children. */
760 if (c
->file
->update_status
!= 0)
761 /* We failed to start the commands. */
762 delete_child_targets (c
);
765 /* There are no more commands. We got through them all
766 without an unignored error. Now the target has been
767 successfully updated. */
768 c
->file
->update_status
= 0;
771 /* When we get here, all the commands for C->file are finished
772 (or aborted) and C->file->update_status contains 0 or 2. But
773 C->file->command_state is still cs_running if all the commands
774 ran; notice_finish_file looks for cs_running to tell it that
775 it's interesting to check the file's modtime again now. */
777 if (! handling_fatal_signal
)
778 /* Notice if the target of the commands has been changed.
779 This also propagates its values for command_state and
780 update_status to its also_make files. */
781 notice_finished_file (c
->file
);
783 DB (DB_JOBS
, (_("Removing child 0x%08lx PID %ld%s from chain.\n"),
784 (unsigned long int) c
, (long) c
->pid
,
785 c
->remote
? _(" (remote)") : ""));
787 /* Block fatal signals while frobnicating the list, so that
788 children and job_slots_used are always consistent. Otherwise
789 a fatal signal arriving after the child is off the chain and
790 before job_slots_used is decremented would believe a child was
791 live and call reap_children again. */
794 /* There is now another slot open. */
795 if (job_slots_used
> 0)
798 /* Remove the child from the chain and free it. */
802 lastc
->next
= c
->next
;
808 /* If the job failed, and the -k flag was not given, die,
809 unless we are already in the process of dying. */
810 if (!err
&& child_failed
&& !keep_going_flag
&&
811 /* fatal_error_signal will die with the right signal. */
812 !handling_fatal_signal
)
815 /* Only block for one child. */
822 /* Free the storage allocated for CHILD. */
825 free_child (struct child
*child
)
827 /* If this child is the only one it was our "free" job, so don't put a
828 token back for it. This child has already been removed from the list,
829 so if there any left this wasn't the last one. */
831 if (job_fds
[1] >= 0 && children
)
836 /* Write a job token back to the pipe. */
838 EINTRLOOP (r
, write (job_fds
[1], &token
, 1));
840 pfatal_with_name (_("write jobserver"));
842 DB (DB_JOBS
, (_("Released token for child 0x%08lx (%s).\n"),
843 (unsigned long int) child
, child
->file
->name
));
846 if (handling_fatal_signal
) /* Don't bother free'ing if about to die. */
849 if (child
->command_lines
!= 0)
851 register unsigned int i
;
852 for (i
= 0; i
< child
->file
->cmds
->ncommand_lines
; ++i
)
853 free (child
->command_lines
[i
]);
854 free ((char *) child
->command_lines
);
857 if (child
->environment
!= 0)
859 register char **ep
= child
->environment
;
862 free ((char *) child
->environment
);
865 free ((char *) child
);
869 extern sigset_t fatal_signal_set
;
876 (void) sigprocmask (SIG_BLOCK
, &fatal_signal_set
, (sigset_t
*) 0);
878 # ifdef HAVE_SIGSETMASK
879 (void) sigblock (fatal_signal_mask
);
889 sigemptyset (&empty
);
890 sigprocmask (SIG_SETMASK
, &empty
, (sigset_t
*) 0);
894 #ifdef MAKE_JOBSERVER
896 /* Never install the SIGCHLD handler for EMX!!! */
897 # define set_child_handler_action_flags(x)
899 /* Set the child handler action flags to FLAGS. */
901 set_child_handler_action_flags (int flags
)
904 bzero ((char *) &sa
, sizeof sa
);
905 sa
.sa_handler
= child_handler
;
908 sigaction (SIGCHLD
, &sa
, NULL
);
910 #if defined SIGCLD && SIGCLD != SIGCHLD
911 sigaction (SIGCLD
, &sa
, NULL
);
914 #endif /* !__EMX__ */
918 /* Start a job to run the commands specified in CHILD.
919 CHILD is updated to reflect the commands and ID of the child process.
921 NOTE: On return fatal signals are blocked! The caller is responsible
922 for calling `unblock_sigs', once the new child is safely on the chain so
923 it can be cleaned up in the event of a fatal signal. */
926 start_job_command (struct child
*child
)
929 static int bad_stdin
= -1;
939 /* If we have a completely empty commandset, stop now. */
940 if (!child
->command_ptr
)
943 /* Combine the flags parsed for the line itself with
944 the flags specified globally for this target. */
945 flags
= (child
->file
->command_flags
946 | child
->file
->cmds
->lines_flags
[child
->command_line
- 1]);
948 p
= child
->command_ptr
;
949 child
->noerror
= flags
& COMMANDS_NOERROR
;
954 flags
|= COMMANDS_SILENT
;
956 flags
|= COMMANDS_RECURSE
;
959 else if (!isblank ((unsigned char)*p
))
964 /* Update the file's command flags with any new ones we found. We only
965 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
966 now marking more commands recursive than should be in the case of
967 multiline define/endef scripts where only one line is marked "+". In
968 order to really fix this, we'll have to keep a lines_flags for every
969 actual line, after expansion. */
970 child
->file
->cmds
->lines_flags
[child
->command_line
- 1]
971 |= flags
& COMMANDS_RECURSE
;
973 /* Figure out an argument list from this command line. */
980 argv
= construct_command_argv (p
, &end
, child
->file
, &child
->sh_batch_file
);
983 child
->command_ptr
= NULL
;
987 child
->command_ptr
= end
;
991 /* If -q was given, say that updating `failed' if there was any text on the
992 command line, or `succeeded' otherwise. The exit status of 1 tells the
993 user that -q is saying `something to do'; the exit status for a random
995 if (argv
!= 0 && question_flag
&& !(flags
& COMMANDS_RECURSE
))
999 free ((char *) argv
);
1001 child
->file
->update_status
= 1;
1002 notice_finished_file (child
->file
);
1006 if (touch_flag
&& !(flags
& COMMANDS_RECURSE
))
1008 /* Go on to the next command. It might be the recursive one.
1009 We construct ARGV only to find the end of the command line. */
1014 free ((char *) argv
);
1024 execute_by_shell
= 0; /* in case construct_command_argv sets it */
1026 /* This line has no commands. Go to the next. */
1027 if (job_next_command (child
))
1028 start_job_command (child
);
1031 /* No more commands. Make sure we're "running"; we might not be if
1032 (e.g.) all commands were skipped due to -n. */
1033 set_command_state (child
->file
, cs_running
);
1034 child
->file
->update_status
= 0;
1035 notice_finished_file (child
->file
);
1040 /* Print out the command. If silent, we call `message' with null so it
1041 can log the working directory before the command's own error messages
1044 message (0, (just_print_flag
|| (!(flags
& COMMANDS_SILENT
) && !silent_flag
))
1045 ? "%s" : (char *) 0, p
);
1047 /* Tell update_goal_chain that a command has been started on behalf of
1048 this target. It is important that this happens here and not in
1049 reap_children (where we used to do it), because reap_children might be
1050 reaping children from a different target. We want this increment to
1051 guaranteedly indicate that a command was started for the dependency
1052 chain (i.e., update_file recursion chain) we are processing. */
1056 /* Optimize an empty command. People use this for timestamp rules,
1057 so avoid forking a useless shell. Do this after we increment
1058 commands_started so make still treats this special case as if it
1059 performed some action (makes a difference as to what messages are
1062 #if !defined(VMS) && !defined(_AMIGA)
1064 #if defined __MSDOS__ || defined (__EMX__)
1065 unixy_shell
/* the test is complicated and we already did it */
1067 (argv
[0] && !strcmp (argv
[0], "/bin/sh"))
1070 && argv
[1][0] == '-' && argv
[1][1] == 'c' && argv
[1][2] == '\0')
1071 && (argv
[2] && argv
[2][0] == ':' && argv
[2][1] == '\0')
1075 free ((char *) argv
);
1078 #endif /* !VMS && !_AMIGA */
1080 /* If -n was given, recurse to get the next line in the sequence. */
1082 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
))
1086 free ((char *) argv
);
1091 /* Flush the output streams so they won't have things written twice. */
1097 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1099 /* Set up a bad standard input that reads from a broken pipe. */
1101 if (bad_stdin
== -1)
1103 /* Make a file descriptor that is the read end of a broken pipe.
1104 This will be used for some children's standard inputs. */
1108 /* Close the write side. */
1109 (void) close (pd
[1]);
1110 /* Save the read side. */
1113 /* Set the descriptor to close on exec, so it does not litter any
1114 child's descriptor table. When it is dup2'd onto descriptor 0,
1115 that descriptor will not close on exec. */
1116 CLOSE_ON_EXEC (bad_stdin
);
1120 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1122 /* Decide whether to give this child the `good' standard input
1123 (one that points to the terminal or whatever), or the `bad' one
1124 that points to the read side of a broken pipe. */
1126 child
->good_stdin
= !good_stdin_used
;
1127 if (child
->good_stdin
)
1128 good_stdin_used
= 1;
1135 /* Set up the environment for the child. */
1136 if (child
->environment
== 0)
1137 child
->environment
= target_environment (child
->file
);
1140 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1143 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1146 int is_remote
, id
, used_stdin
;
1147 if (start_remote_job (argv
, child
->environment
,
1148 child
->good_stdin
? 0 : bad_stdin
,
1149 &is_remote
, &id
, &used_stdin
))
1150 /* Don't give up; remote execution may fail for various reasons. If
1151 so, simply run the job locally. */
1155 if (child
->good_stdin
&& !used_stdin
)
1157 child
->good_stdin
= 0;
1158 good_stdin_used
= 0;
1160 child
->remote
= is_remote
;
1167 /* Fork the child process. */
1169 char **parent_environ
;
1178 if (!child_execute_job (argv
, child
)) {
1180 perror_with_name ("vfork", "");
1186 parent_environ
= environ
;
1189 /* If we aren't running a recursive command and we have a jobserver
1190 pipe, close it before exec'ing. */
1191 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1193 CLOSE_ON_EXEC (job_fds
[0]);
1194 CLOSE_ON_EXEC (job_fds
[1]);
1197 CLOSE_ON_EXEC (job_rfd
);
1199 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1200 child
->pid
= child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1201 argv
, child
->environment
);
1206 perror_with_name ("spawn", "");
1210 /* undo CLOSE_ON_EXEC() after the child process has been started */
1211 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1213 fcntl (job_fds
[0], F_SETFD
, 0);
1214 fcntl (job_fds
[1], F_SETFD
, 0);
1217 fcntl (job_rfd
, F_SETFD
, 0);
1219 #else /* !__EMX__ */
1221 child
->pid
= vfork ();
1222 environ
= parent_environ
; /* Restore value child may have clobbered. */
1223 if (child
->pid
== 0)
1225 /* We are the child side. */
1228 /* If we aren't running a recursive command and we have a jobserver
1229 pipe, close it before exec'ing. */
1230 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1238 child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1239 argv
, child
->environment
);
1241 else if (child
->pid
< 0)
1245 perror_with_name ("vfork", "");
1248 # endif /* !__EMX__ */
1252 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1260 /* We call `system' to do the job of the SHELL, since stock DOS
1261 shell is too dumb. Our `system' knows how to handle long
1262 command lines even if pipes/redirection is needed; it will only
1263 call COMMAND.COM when its internal commands are used. */
1264 if (execute_by_shell
)
1266 char *cmdline
= argv
[0];
1267 /* We don't have a way to pass environment to `system',
1268 so we need to save and restore ours, sigh... */
1269 char **parent_environ
= environ
;
1271 environ
= child
->environment
;
1273 /* If we have a *real* shell, tell `system' to call
1274 it to do everything for us. */
1277 /* A *real* shell on MSDOS may not support long
1278 command lines the DJGPP way, so we must use `system'. */
1279 cmdline
= argv
[2]; /* get past "shell -c" */
1282 dos_command_running
= 1;
1283 proc_return
= system (cmdline
);
1284 environ
= parent_environ
;
1285 execute_by_shell
= 0; /* for the next time */
1289 dos_command_running
= 1;
1290 proc_return
= spawnvpe (P_WAIT
, argv
[0], argv
, child
->environment
);
1293 /* Need to unblock signals before turning off
1294 dos_command_running, so that child's signals
1295 will be treated as such (see fatal_error_signal). */
1297 dos_command_running
= 0;
1299 /* If the child got a signal, dos_status has its
1300 high 8 bits set, so be careful not to alter them. */
1301 if (proc_return
== -1)
1304 dos_status
|= (proc_return
& 0xff);
1306 child
->pid
= dos_pid
++;
1308 #endif /* __MSDOS__ */
1310 amiga_status
= MyExecute (argv
);
1313 child
->pid
= amiga_pid
++;
1314 if (amiga_batch_file
)
1316 amiga_batch_file
= 0;
1317 DeleteFile (amiga_bname
); /* Ignore errors. */
1325 /* make UNC paths safe for CreateProcess -- backslash format */
1327 if (arg0
&& arg0
[0] == '/' && arg0
[1] == '/')
1328 for ( ; arg0
&& *arg0
; arg0
++)
1332 /* make sure CreateProcess() has Path it needs */
1333 sync_Path_environment();
1335 hPID
= process_easy(argv
, child
->environment
);
1337 if (hPID
!= INVALID_HANDLE_VALUE
)
1338 child
->pid
= (int) hPID
;
1343 _("process_easy() failed failed to launch process (e=%d)\n"),
1344 process_last_err(hPID
));
1345 for (i
= 0; argv
[i
]; i
++)
1346 fprintf(stderr
, "%s ", argv
[i
]);
1347 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
1350 #endif /* WINDOWS32 */
1351 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1353 /* We are the parent side. Set the state to
1354 say the commands are running and return. */
1356 set_command_state (child
->file
, cs_running
);
1358 /* Free the storage used by the child's argument list. */
1361 free ((char *) argv
);
1367 child
->file
->update_status
= 2;
1368 notice_finished_file (child
->file
);
1372 /* Try to start a child running.
1373 Returns nonzero if the child was started (and maybe finished), or zero if
1374 the load was too high and the child was put on the `waiting_jobs' chain. */
1377 start_waiting_job (struct child
*c
)
1379 struct file
*f
= c
->file
;
1381 /* If we can start a job remotely, we always want to, and don't care about
1382 the local load average. We record that the job should be started
1383 remotely in C->remote for start_job_command to test. */
1385 c
->remote
= start_remote_job_p (1);
1387 /* If we are running at least one job already and the load average
1388 is too high, make this one wait. */
1389 if (!c
->remote
&& job_slots_used
> 0 && load_too_high ())
1391 /* Put this child on the chain of children waiting for the load average
1393 set_command_state (f
, cs_running
);
1394 c
->next
= waiting_jobs
;
1399 /* Start the first command; reap_children will run later command lines. */
1400 start_job_command (c
);
1402 switch (f
->command_state
)
1406 DB (DB_JOBS
, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1407 (unsigned long int) c
, c
->file
->name
,
1408 (long) c
->pid
, c
->remote
? _(" (remote)") : ""));
1410 /* One more job slot is in use. */
1415 case cs_not_started
:
1416 /* All the command lines turned out to be empty. */
1417 f
->update_status
= 0;
1421 notice_finished_file (f
);
1426 assert (f
->command_state
== cs_finished
);
1433 /* Create a `struct child' for FILE and start its commands running. */
1436 new_job (struct file
*file
)
1438 register struct commands
*cmds
= file
->cmds
;
1439 register struct child
*c
;
1441 register unsigned int i
;
1443 /* Let any previously decided-upon jobs that are waiting
1444 for the load to go down start before this new one. */
1445 start_waiting_jobs ();
1447 /* Reap any children that might have finished recently. */
1448 reap_children (0, 0);
1450 /* Chop the commands up into lines if they aren't already. */
1451 chop_commands (cmds
);
1453 /* Expand the command lines and store the results in LINES. */
1454 lines
= (char **) xmalloc (cmds
->ncommand_lines
* sizeof (char *));
1455 for (i
= 0; i
< cmds
->ncommand_lines
; ++i
)
1457 /* Collapse backslash-newline combinations that are inside variable
1458 or function references. These are left alone by the parser so
1459 that they will appear in the echoing of commands (where they look
1460 nice); and collapsed by construct_command_argv when it tokenizes.
1461 But letting them survive inside function invocations loses because
1462 we don't want the functions to see them as part of the text. */
1464 char *in
, *out
, *ref
;
1466 /* IN points to where in the line we are scanning.
1467 OUT points to where in the line we are writing.
1468 When we collapse a backslash-newline combination,
1469 IN gets ahead of OUT. */
1471 in
= out
= cmds
->command_lines
[i
];
1472 while ((ref
= strchr (in
, '$')) != 0)
1474 ++ref
; /* Move past the $. */
1477 /* Copy the text between the end of the last chunk
1478 we processed (where IN points) and the new chunk
1479 we are about to process (where REF points). */
1480 bcopy (in
, out
, ref
- in
);
1482 /* Move both pointers past the boring stuff. */
1486 if (*ref
== '(' || *ref
== '{')
1488 char openparen
= *ref
;
1489 char closeparen
= openparen
== '(' ? ')' : '}';
1493 *out
++ = *in
++; /* Copy OPENPAREN. */
1494 /* IN now points past the opening paren or brace.
1495 Count parens or braces until it is matched. */
1499 if (*in
== closeparen
&& --count
< 0)
1501 else if (*in
== '\\' && in
[1] == '\n')
1503 /* We have found a backslash-newline inside a
1504 variable or function reference. Eat it and
1505 any following whitespace. */
1508 for (p
= in
- 1; p
> ref
&& *p
== '\\'; --p
)
1512 /* There were two or more backslashes, so this is
1513 not really a continuation line. We don't collapse
1514 the quoting backslashes here as is done in
1515 collapse_continuations, because the line will
1516 be collapsed again after expansion. */
1520 /* Skip the backslash, newline and
1521 any following whitespace. */
1522 in
= next_token (in
+ 2);
1524 /* Discard any preceding whitespace that has
1525 already been written to the output. */
1527 && isblank ((unsigned char)out
[-1]))
1530 /* Replace it all with a single space. */
1536 if (*in
== openparen
)
1545 /* There are no more references in this line to worry about.
1546 Copy the remaining uninteresting text to the output. */
1550 /* Finally, expand the line. */
1551 lines
[i
] = allocated_variable_expand_for_file (cmds
->command_lines
[i
],
1555 /* Start the command sequence, record it in a new
1556 `struct child', and add that to the chain. */
1558 c
= (struct child
*) xmalloc (sizeof (struct child
));
1559 bzero ((char *)c
, sizeof (struct child
));
1561 c
->command_lines
= lines
;
1562 c
->sh_batch_file
= NULL
;
1564 /* Fetch the first command line to be run. */
1565 job_next_command (c
);
1567 /* Wait for a job slot to be freed up. If we allow an infinite number
1568 don't bother; also job_slots will == 0 if we're using the jobserver. */
1571 while (job_slots_used
== job_slots
)
1572 reap_children (1, 0);
1574 #ifdef MAKE_JOBSERVER
1575 /* If we are controlling multiple jobs make sure we have a token before
1576 starting the child. */
1578 /* This can be inefficient. There's a decent chance that this job won't
1579 actually have to run any subprocesses: the command script may be empty
1580 or otherwise optimized away. It would be nice if we could defer
1581 obtaining a token until just before we need it, in start_job_command.
1582 To do that we'd need to keep track of whether we'd already obtained a
1583 token (since start_job_command is called for each line of the job, not
1584 just once). Also more thought needs to go into the entire algorithm;
1585 this is where the old parallel job code waits, so... */
1587 else if (job_fds
[0] >= 0)
1594 DB (DB_JOBS
, ("Need a job token; we %shave children\n",
1595 children
? "" : "don't "));
1597 /* If we don't already have a job started, use our "free" token. */
1601 /* Read a token. As long as there's no token available we'll block.
1602 We enable interruptible system calls before the read(2) so that if
1603 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1604 we can process the death(s) and return tokens to the free pool.
1606 Once we return from the read, we immediately reinstate restartable
1607 system calls. This allows us to not worry about checking for
1608 EINTR on all the other system calls in the program.
1610 There is one other twist: there is a span between the time
1611 reap_children() does its last check for dead children and the time
1612 the read(2) call is entered, below, where if a child dies we won't
1613 notice. This is extremely serious as it could cause us to
1614 deadlock, given the right set of events.
1616 To avoid this, we do the following: before we reap_children(), we
1617 dup(2) the read FD on the jobserver pipe. The read(2) call below
1618 uses that new FD. In the signal handler, we close that FD. That
1619 way, if a child dies during the section mentioned above, the
1620 read(2) will be invoked with an invalid FD and will return
1621 immediately with EBADF. */
1623 /* Make sure we have a dup'd FD. */
1626 DB (DB_JOBS
, ("Duplicate the job FD\n"));
1627 job_rfd
= dup (job_fds
[0]);
1630 /* Reap anything that's currently waiting. */
1631 reap_children (0, 0);
1633 /* If our "free" token has become available, use it. */
1637 /* Set interruptible system calls, and read() for a job token. */
1638 set_child_handler_action_flags (0);
1639 got_token
= read (job_rfd
, &token
, 1);
1640 saved_errno
= errno
;
1641 set_child_handler_action_flags (SA_RESTART
);
1643 /* If we got one, we're done here. */
1646 DB (DB_JOBS
, (_("Obtained token for child 0x%08lx (%s).\n"),
1647 (unsigned long int) c
, c
->file
->name
));
1651 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1652 go back and reap_children(), and try again. */
1653 errno
= saved_errno
;
1654 if (errno
!= EINTR
&& errno
!= EBADF
)
1655 pfatal_with_name (_("read jobs pipe"));
1657 DB (DB_JOBS
, ("Read returned EBADF.\n"));
1661 /* The job is now primed. Start it running.
1662 (This will notice if there are in fact no commands.) */
1663 (void) start_waiting_job (c
);
1665 if (job_slots
== 1 || not_parallel
)
1666 /* Since there is only one job slot, make things run linearly.
1667 Wait for the child to die, setting the state to `cs_finished'. */
1668 while (file
->command_state
== cs_running
)
1669 reap_children (1, 0);
1674 /* Move CHILD's pointers to the next command for it to execute.
1675 Returns nonzero if there is another command. */
1678 job_next_command (struct child
*child
)
1680 while (child
->command_ptr
== 0 || *child
->command_ptr
== '\0')
1682 /* There are no more lines in the expansion of this line. */
1683 if (child
->command_line
== child
->file
->cmds
->ncommand_lines
)
1685 /* There are no more lines to be expanded. */
1686 child
->command_ptr
= 0;
1690 /* Get the next line to run. */
1691 child
->command_ptr
= child
->command_lines
[child
->command_line
++];
1697 load_too_high (void)
1699 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1704 if (max_load_average
< 0)
1708 if (getloadavg (&load
, 1) != 1)
1710 static int lossage
= -1;
1711 /* Complain only once for the same error. */
1712 if (lossage
== -1 || errno
!= lossage
)
1715 /* An errno value of zero means getloadavg is just unsupported. */
1717 _("cannot enforce load limits on this operating system"));
1719 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1726 DB (DB_JOBS
, ("Current system load = %f (max requested = %f)\n",
1727 load
, max_load_average
));
1728 return load
>= max_load_average
;
1732 /* Start jobs that are waiting for the load to be lower. */
1735 start_waiting_jobs (void)
1739 if (waiting_jobs
== 0)
1744 /* Check for recently deceased descendants. */
1745 reap_children (0, 0);
1747 /* Take a job off the waiting list. */
1749 waiting_jobs
= job
->next
;
1751 /* Try to start that job. We break out of the loop as soon
1752 as start_waiting_job puts one back on the waiting list. */
1754 while (start_waiting_job (job
) && waiting_jobs
!= 0);
1761 #include <descrip.h>
1764 /* This is called as an AST when a child process dies (it won't get
1765 interrupted by anything except a higher level AST).
1767 int vmsHandleChildTerm(struct child
*child
)
1770 register struct child
*lastc
, *c
;
1773 vms_jobsefnmask
&= ~(1 << (child
->efn
- 32));
1775 lib$
free_ef(&child
->efn
);
1777 (void) sigblock (fatal_signal_mask
);
1779 child_failed
= !(child
->cstatus
& 1 || ((child
->cstatus
& 7) == 0));
1781 /* Search for a child matching the deceased one. */
1783 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1784 for (c
= children
; c
!= 0 && c
!= child
; lastc
= c
, c
= c
->next
);
1789 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
1791 /* The commands failed. Write an error message,
1792 delete non-precious targets, and abort. */
1793 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 0);
1794 c
->file
->update_status
= 1;
1795 delete_child_targets (c
);
1801 /* The commands failed, but we don't care. */
1802 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 1);
1806 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1807 /* If there are more commands to run, try to start them. */
1810 switch (c
->file
->command_state
)
1813 /* Successfully started. */
1817 if (c
->file
->update_status
!= 0) {
1818 /* We failed to start the commands. */
1819 delete_child_targets (c
);
1824 error (NILF
, _("internal error: `%s' command_state"),
1829 #endif /* RECURSIVEJOBS */
1832 /* Set the state flag to say the commands have finished. */
1833 c
->file
->command_state
= cs_finished
;
1834 notice_finished_file (c
->file
);
1836 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1837 /* Remove the child from the chain and free it. */
1841 lastc
->next
= c
->next
;
1843 #endif /* RECURSIVEJOBS */
1845 /* There is now another slot open. */
1846 if (job_slots_used
> 0)
1849 /* If the job failed, and the -k flag was not given, die. */
1850 if (child_failed
&& !keep_going_flag
)
1853 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask
));
1859 Spawn a process executing the command in ARGV and return its pid. */
1861 #define MAXCMDLEN 200
1863 /* local helpers to make ctrl+c and ctrl+y working, see below */
1865 #include <libclidef.h>
1868 static int ctrlMask
= LIB$M_CLI_CTRLY
;
1869 static int oldCtrlMask
;
1870 static int setupYAstTried
= 0;
1871 static int pidToAbort
= 0;
1874 static void reEnableAst(void) {
1875 lib$
enable_ctrl (&oldCtrlMask
,0);
1878 static astHandler (void) {
1880 sys$
forcex (&pidToAbort
, 0, SS$_ABORT
);
1883 kill (getpid(),SIGQUIT
);
1886 static void tryToSetupYAst(void) {
1887 $
DESCRIPTOR(inputDsc
,"SYS$COMMAND");
1890 short int status
, count
;
1897 status
= sys$
assign(&inputDsc
,&chan
,0,0);
1898 if (!(status
&SS$_NORMAL
)) {
1903 status
= sys$
qiow (0, chan
, IO$_SETMODE
|IO$M_CTRLYAST
,&iosb
,0,0,
1904 astHandler
,0,0,0,0,0);
1905 if (status
==SS$_ILLIOFUNC
) {
1907 #ifdef CTRLY_ENABLED_ANYWAY
1909 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
1914 if (status
==SS$_NORMAL
)
1915 status
= iosb
.status
;
1916 if (!(status
&SS$_NORMAL
)) {
1921 /* called from AST handler ? */
1922 if (setupYAstTried
>1)
1924 if (atexit(reEnableAst
))
1926 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
1927 status
= lib$
disable_ctrl (&ctrlMask
, &oldCtrlMask
);
1928 if (!(status
&SS$_NORMAL
)) {
1934 child_execute_job (char *argv
, struct child
*child
)
1937 static struct dsc$descriptor_s cmddsc
;
1938 static struct dsc$descriptor_s pnamedsc
;
1939 static struct dsc$descriptor_s ifiledsc
;
1940 static struct dsc$descriptor_s ofiledsc
;
1941 static struct dsc$descriptor_s efiledsc
;
1942 int have_redirection
= 0;
1943 int have_newline
= 0;
1945 int spflags
= CLI$M_NOWAIT
;
1947 char *cmd
= alloca (strlen (argv
) + 512), *p
, *q
;
1948 char ifile
[256], ofile
[256], efile
[256];
1952 /* Parse IO redirection. */
1958 DB (DB_JOBS
, ("child_execute_job (%s)\n", argv
));
1960 while (isspace ((unsigned char)*argv
))
1966 sprintf (procname
, "GMAKE_%05x", getpid () & 0xfffff);
1967 pnamedsc
.dsc$w_length
= strlen(procname
);
1968 pnamedsc
.dsc$a_pointer
= procname
;
1969 pnamedsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
1970 pnamedsc
.dsc$b_class
= DSC$K_CLASS_S
;
1972 /* Handle comments and redirection. */
1973 for (p
= argv
, q
= cmd
; *p
; p
++, q
++)
1985 if (isspace ((unsigned char)*p
))
1987 do { p
++; } while (isspace ((unsigned char)*p
));
1993 p
= vms_redirect (&ifiledsc
, ifile
, p
);
1995 have_redirection
= 1;
1998 have_redirection
= 1;
2002 if (strncmp (p
, ">&1", 3) == 0)
2005 strcpy (efile
, "sys$output");
2006 efiledsc
.dsc$w_length
= strlen(efile
);
2007 efiledsc
.dsc$a_pointer
= efile
;
2008 efiledsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
2009 efiledsc
.dsc$b_class
= DSC$K_CLASS_S
;
2013 p
= vms_redirect (&efiledsc
, efile
, p
);
2018 p
= vms_redirect (&ofiledsc
, ofile
, p
);
2031 if (strncmp (cmd
, "builtin_", 8) == 0)
2033 child
->pid
= 270163;
2037 DB (DB_JOBS
, (_("BUILTIN [%s][%s]\n"), cmd
, cmd
+8));
2043 && ((*(p
+2) == ' ') || (*(p
+2) == '\t')))
2046 while ((*p
== ' ') || (*p
== '\t'))
2048 DB (DB_JOBS
, (_("BUILTIN CD %s\n"), p
));
2054 else if ((*(p
) == 'r')
2056 && ((*(p
+2) == ' ') || (*(p
+2) == '\t')))
2062 while ((*p
== ' ') || (*p
== '\t'))
2066 DB (DB_JOBS
, (_("BUILTIN RM %s\n"), p
));
2087 printf(_("Unknown builtin command '%s'\n"), cmd
);
2093 /* Create a *.com file if either the command is too long for
2094 lib$spawn, or the command contains a newline, or if redirection
2095 is desired. Forcing commands with newlines into DCLs allows to
2096 store search lists on user mode logicals. */
2098 if (strlen (cmd
) > MAXCMDLEN
2099 || (have_redirection
!= 0)
2100 || (have_newline
!= 0))
2105 int alevel
= 0; /* apostrophe level */
2107 if (strlen (cmd
) == 0)
2109 printf (_("Error, empty command\n"));
2114 outfile
= open_tmpfile (&comname
, "sys$scratch:CMDXXXXXX.COM");
2116 pfatal_with_name (_("fopen (temporary file)"));
2120 fprintf (outfile
, "$ assign/user %s sys$input\n", ifile
);
2121 DB (DB_JOBS
, (_("Redirected input from %s\n"), ifile
));
2122 ifiledsc
.dsc$w_length
= 0;
2127 fprintf (outfile
, "$ define sys$error %s\n", efile
);
2128 DB (DB_JOBS
, (_("Redirected error to %s\n"), efile
));
2129 efiledsc
.dsc$w_length
= 0;
2134 fprintf (outfile
, "$ define sys$output %s\n", ofile
);
2135 DB (DB_JOBS
, (_("Redirected output to %s\n"), ofile
));
2136 ofiledsc
.dsc$w_length
= 0;
2140 for (c
= '\n'; c
; c
= *q
++)
2145 /* At a newline, skip any whitespace around a leading $
2146 from the command and issue exactly one $ into the DCL. */
2147 while (isspace ((unsigned char)*p
))
2151 while (isspace ((unsigned char)*p
))
2153 fwrite (p
, 1, q
- p
, outfile
);
2154 fputc ('$', outfile
);
2155 fputc (' ', outfile
);
2156 /* Reset variables. */
2160 /* Nice places for line breaks are after strings, after
2161 comma or space and before slash. */
2163 q
= handle_apos (q
+ 1);
2179 /* Enough stuff for a line. */
2180 fwrite (p
, 1, sep
- p
, outfile
);
2184 /* The command continues. */
2185 fputc ('-', outfile
);
2187 fputc ('\n', outfile
);
2191 fwrite (p
, 1, q
- p
, outfile
);
2192 fputc ('\n', outfile
);
2196 sprintf (cmd
, "$ @%s", comname
);
2198 DB (DB_JOBS
, (_("Executing %s instead\n"), cmd
));
2201 cmddsc
.dsc$w_length
= strlen(cmd
);
2202 cmddsc
.dsc$a_pointer
= cmd
;
2203 cmddsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
2204 cmddsc
.dsc$b_class
= DSC$K_CLASS_S
;
2207 while (child
->efn
< 32 || child
->efn
> 63)
2209 status
= lib$
get_ef ((unsigned long *)&child
->efn
);
2214 sys$
clref (child
->efn
);
2216 vms_jobsefnmask
|= (1 << (child
->efn
- 32));
2219 LIB$SPAWN [command-string]
2224 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2225 [,AST-address] [,varying-AST-argument]
2226 [,prompt-string] [,cli] [,table]
2229 #ifndef DONTWAITFORCHILD
2231 * Code to make ctrl+c and ctrl+y working.
2232 * The problem starts with the synchronous case where after lib$spawn is
2233 * called any input will go to the child. But with input re-directed,
2234 * both control characters won't make it to any of the programs, neither
2235 * the spawning nor to the spawned one. Hence the caller needs to spawn
2236 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2237 * has to follow to simulate the wanted synchronous behaviour.
2238 * The next problem is ctrl+y which isn't caught by the crtl and
2239 * therefore isn't converted to SIGQUIT (for a signal handler which is
2240 * already established). The only way to catch ctrl+y, is an AST
2241 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2242 * disabled, otherwise it will handle it. Not to mention the previous
2243 * ctrl+y handling of DCL needs to be re-established before make exits.
2244 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2245 * make it to the signal handler after the child "normally" terminates.
2246 * This isn't enough. It seems reasonable for simple command lines like
2247 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2248 * spawning make. Therefore we need to abort the process in the AST.
2250 * Prior to the spawn it is checked if an AST is already set up for
2251 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2252 * this will work except if make is run in a batch environment, but there
2253 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2254 * is disabled and an exit handler is established to re-enable it.
2255 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2256 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2257 * the already established handler and will bring us back to common code.
2258 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2259 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2260 * which the crtl converts to SIGINT and which is caught by the common
2261 * signal handler. Because signals were blocked before entering this code
2262 * sys$waitfr will always complete and the SIGQUIT will be processed after
2263 * it (after termination of the current block, somewhere in common code).
2264 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2265 * current command completes. Anyway it's better than nothing :-)
2268 if (!setupYAstTried
)
2270 status
= lib$
spawn (&cmddsc
, /* cmd-string */
2271 (ifiledsc
.dsc$w_length
== 0)?0:&ifiledsc
, /* input-file */
2272 (ofiledsc
.dsc$w_length
== 0)?0:&ofiledsc
, /* output-file */
2273 &spflags
, /* flags */
2274 &pnamedsc
, /* proc name */
2275 &child
->pid
, &child
->cstatus
, &child
->efn
,
2280 pidToAbort
= child
->pid
;
2281 status
= sys$
waitfr (child
->efn
);
2283 vmsHandleChildTerm(child
);
2286 status
= lib$
spawn (&cmddsc
,
2287 (ifiledsc
.dsc$w_length
== 0)?0:&ifiledsc
,
2288 (ofiledsc
.dsc$w_length
== 0)?0:&ofiledsc
,
2291 &child
->pid
, &child
->cstatus
, &child
->efn
,
2292 vmsHandleChildTerm
, child
,
2298 printf (_("Error spawning, %d\n") ,status
);
2310 if (comname
&& !ISDB (DB_JOBS
))
2313 return (status
& 1);
2318 /* EMX: Start a child process. This function returns the new pid. */
2319 # if defined __MSDOS__ || defined __EMX__
2321 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2324 /* stdin_fd == 0 means: nothing to do for stdin;
2325 stdout_fd == 1 means: nothing to do for stdout */
2326 int save_stdin
= (stdin_fd
!= 0) ? dup (0) : 0;
2327 int save_stdout
= (stdout_fd
!= 1) ? dup (1): 1;
2329 /* < 0 only if dup() failed */
2331 fatal (NILF
, _("no more file handles: could not duplicate stdin\n"));
2332 if (save_stdout
< 0)
2333 fatal (NILF
, _("no more file handles: could not duplicate stdout\n"));
2335 /* Close unnecessary file handles for the child. */
2336 if (save_stdin
!= 0)
2337 CLOSE_ON_EXEC (save_stdin
);
2338 if (save_stdout
!= 1)
2339 CLOSE_ON_EXEC (save_stdout
);
2341 /* Connect the pipes to the child process. */
2343 (void) dup2 (stdin_fd
, 0);
2345 (void) dup2 (stdout_fd
, 1);
2347 /* stdin_fd and stdout_fd must be closed on exit because we are
2348 still in the parent process */
2350 CLOSE_ON_EXEC (stdin_fd
);
2352 CLOSE_ON_EXEC (stdout_fd
);
2354 /* Run the command. */
2355 pid
= exec_command (argv
, envp
);
2357 /* Restore stdout/stdin of the parent process. */
2358 if (stdin_fd
!= 0 && dup2 (save_stdin
, 0) != 0)
2359 fatal (NILF
, _("restoring of stdin failed\n"));
2360 if (stdout_fd
!= 1 && dup2 (save_stdout
, 1) != 1)
2361 fatal (NILF
, _("restoring of stdout failed\n"));
2366 #elif !defined (_AMIGA) && !defined (__MSDOS__)
2369 Replace the current process with one executing the command in ARGV.
2370 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2371 the environment of the new program. This function does not return. */
2373 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2376 (void) dup2 (stdin_fd
, 0);
2378 (void) dup2 (stdout_fd
, 1);
2380 (void) close (stdin_fd
);
2382 (void) close (stdout_fd
);
2384 /* Run the command. */
2385 exec_command (argv
, envp
);
2387 #endif /* !AMIGA && !__MSDOS__ */
2389 #endif /* !WINDOWS32 */
2392 /* Replace the current process with one running the command in ARGV,
2393 with environment ENVP. This function does not return. */
2395 /* EMX: This function returns the pid of the child process. */
2401 exec_command (char **argv
, char **envp
)
2404 /* to work around a problem with signals and execve: ignore them */
2406 signal (SIGCHLD
,SIG_IGN
);
2408 /* Run the program. */
2409 execve (argv
[0], argv
, envp
);
2410 perror_with_name ("execve: ", argv
[0]);
2411 _exit (EXIT_FAILURE
);
2417 int exit_code
= EXIT_FAILURE
;
2419 /* make sure CreateProcess() has Path it needs */
2420 sync_Path_environment();
2422 /* launch command */
2423 hPID
= process_easy(argv
, envp
);
2425 /* make sure launch ok */
2426 if (hPID
== INVALID_HANDLE_VALUE
)
2430 _("process_easy() failed failed to launch process (e=%d)\n"),
2431 process_last_err(hPID
));
2432 for (i
= 0; argv
[i
]; i
++)
2433 fprintf(stderr
, "%s ", argv
[i
]);
2434 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
2438 /* wait and reap last child */
2439 while (hWaitPID
= process_wait_for_any())
2441 /* was an error found on this process? */
2442 err
= process_last_err(hWaitPID
);
2445 exit_code
= process_exit_code(hWaitPID
);
2448 fprintf(stderr
, "make (e=%d, rc=%d): %s",
2449 err
, exit_code
, map_windows32_error_to_string(err
));
2451 /* cleanup process */
2452 process_cleanup(hWaitPID
);
2454 /* expect to find only last pid, warn about other pids reaped */
2455 if (hWaitPID
== hPID
)
2459 _("make reaped child pid %d, still waiting for pid %d\n"),
2463 /* return child's exit code as our exit code */
2466 #else /* !WINDOWS32 */
2472 /* Be the user, permanently. */
2477 /* Run the program. */
2478 pid
= spawnvpe (P_NOWAIT
, argv
[0], argv
, envp
);
2483 /* the file might have a strange shell extension */
2484 if (errno
== ENOENT
)
2489 /* Run the program. */
2491 execvp (argv
[0], argv
);
2493 # endif /* !__EMX__ */
2498 error (NILF
, _("%s: Command not found"), argv
[0]);
2502 /* The file is not executable. Try it as a shell script. */
2503 extern char *getenv ();
2509 /* Do not use $SHELL from the environment */
2510 shell
= lookup_variable ("SHELL", 5);
2512 shell
= shell
->value
;
2516 shell
= getenv ("SHELL");
2519 shell
= default_shell
;
2522 while (argv
[argc
] != 0)
2525 new_argv
= (char **) alloca ((1 + argc
+ 1) * sizeof (char *));
2526 new_argv
[0] = shell
;
2527 new_argv
[1] = argv
[0];
2530 new_argv
[1 + argc
] = argv
[argc
];
2535 pid
= spawnvpe (P_NOWAIT
, shell
, new_argv
, envp
);
2539 execvp (shell
, new_argv
);
2541 if (errno
== ENOENT
)
2542 error (NILF
, _("%s: Shell program not found"), shell
);
2544 perror_with_name ("execvp: ", shell
);
2550 /* this nasty error was driving me nuts :-( */
2551 error (NILF
, _("spawnvpe: environment space might be exhausted"));
2556 perror_with_name ("execvp: ", argv
[0]);
2565 #endif /* !WINDOWS32 */
2568 #else /* On Amiga */
2569 void exec_command (char **argv
)
2574 void clean_tmp (void)
2576 DeleteFile (amiga_bname
);
2579 #endif /* On Amiga */
2582 /* Figure out the argument list necessary to run LINE as a command. Try to
2583 avoid using a shell. This routine handles only ' quoting, and " quoting
2584 when no backslash, $ or ` characters are seen in the quotes. Starting
2585 quotes may be escaped with a backslash. If any of the characters in
2586 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2587 is the first word of a line, the shell is used.
2589 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2590 If *RESTP is NULL, newlines will be ignored.
2592 SHELL is the shell to use, or nil to use the default shell.
2593 IFS is the value of $IFS, or nil (meaning the default). */
2596 construct_command_argv_internal (char *line
, char **restp
, char *shell
,
2597 char *ifs
, char **batch_filename_ptr
)
2600 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2601 We call `system' for anything that requires ``slow'' processing,
2602 because DOS shells are too dumb. When $SHELL points to a real
2603 (unix-style) shell, `system' just calls it to do everything. When
2604 $SHELL points to a DOS shell, `system' does most of the work
2605 internally, calling the shell only for its internal commands.
2606 However, it looks on the $PATH first, so you can e.g. have an
2607 external command named `mkdir'.
2609 Since we call `system', certain characters and commands below are
2610 actually not specific to COMMAND.COM, but to the DJGPP implementation
2611 of `system'. In particular:
2613 The shell wildcard characters are in DOS_CHARS because they will
2614 not be expanded if we call the child via `spawnXX'.
2616 The `;' is in DOS_CHARS, because our `system' knows how to run
2617 multiple commands on a single line.
2619 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2620 won't have to tell one from another and have one more set of
2621 commands and special characters. */
2622 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2623 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2624 "copy", "ctty", "date", "del", "dir", "echo",
2625 "erase", "exit", "for", "goto", "if", "md",
2626 "mkdir", "path", "pause", "prompt", "rd",
2627 "rmdir", "rem", "ren", "rename", "set",
2628 "shift", "time", "type", "ver", "verify",
2631 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2632 static char *sh_cmds_sh
[] = { "cd", "echo", "eval", "exec", "exit", "login",
2633 "logout", "set", "umask", "wait", "while",
2634 "for", "case", "if", ":", ".", "break",
2635 "continue", "export", "read", "readonly",
2636 "shift", "times", "trap", "switch", "unset",
2641 #elif defined (__EMX__)
2642 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2643 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2644 "copy", "ctty", "date", "del", "dir", "echo",
2645 "erase", "exit", "for", "goto", "if", "md",
2646 "mkdir", "path", "pause", "prompt", "rd",
2647 "rmdir", "rem", "ren", "rename", "set",
2648 "shift", "time", "type", "ver", "verify",
2651 static char sh_chars_os2
[] = "*?[];|<>%^()\"'&";
2652 static char *sh_cmds_os2
[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2653 "date", "del", "detach", "dir", "echo",
2654 "endlocal", "erase", "exit", "for", "goto", "if",
2655 "keys", "md", "mkdir", "move", "path", "pause",
2656 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2657 "set", "setlocal", "shift", "start", "time",
2658 "type", "ver", "verify", "vol", ":", 0 };
2660 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^~'";
2661 static char *sh_cmds_sh
[] = { "echo", "cd", "eval", "exec", "exit", "login",
2662 "logout", "set", "umask", "wait", "while",
2663 "for", "case", "if", ":", ".", "break",
2664 "continue", "export", "read", "readonly",
2665 "shift", "times", "trap", "switch", "unset",
2670 #elif defined (_AMIGA)
2671 static char sh_chars
[] = "#;\"|<>()?*$`";
2672 static char *sh_cmds
[] = { "cd", "eval", "if", "delete", "echo", "copy",
2673 "rename", "set", "setenv", "date", "makedir",
2674 "skip", "else", "endif", "path", "prompt",
2675 "unset", "unsetenv", "version",
2677 #elif defined (WINDOWS32)
2678 static char sh_chars_dos
[] = "\"|&<>";
2679 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2680 "copy", "ctty", "date", "del", "dir", "echo",
2681 "erase", "exit", "for", "goto", "if", "if", "md",
2682 "mkdir", "path", "pause", "prompt", "rd", "rem",
2683 "ren", "rename", "rmdir", "set", "shift", "time",
2684 "type", "ver", "verify", "vol", ":", 0 };
2685 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2686 static char *sh_cmds_sh
[] = { "cd", "eval", "exec", "exit", "login",
2687 "logout", "set", "umask", "wait", "while", "for",
2688 "case", "if", ":", ".", "break", "continue",
2689 "export", "read", "readonly", "shift", "times",
2690 "trap", "switch", "test",
2691 #ifdef BATCH_MODE_ONLY_SHELL
2697 #else /* must be UNIX-ish */
2698 static char sh_chars
[] = "#;\"*?[]&|<>(){}$`^~";
2699 static char *sh_cmds
[] = { "cd", "eval", "exec", "exit", "login",
2700 "logout", "set", "umask", "wait", "while", "for",
2701 "case", "if", ":", ".", "break", "continue",
2702 "export", "read", "readonly", "shift", "times",
2703 "trap", "switch", 0 };
2704 #endif /* __MSDOS__ */
2709 int instring
, word_has_equals
, seen_nonequals
, last_argument_was_empty
;
2710 char **new_argv
= 0;
2714 if (no_default_sh_exe
) {
2715 sh_cmds
= sh_cmds_dos
;
2716 sh_chars
= sh_chars_dos
;
2718 sh_cmds
= sh_cmds_sh
;
2719 sh_chars
= sh_chars_sh
;
2721 #endif /* WINDOWS32 */
2726 /* Make sure not to bother processing an empty line. */
2727 while (isblank ((unsigned char)*line
))
2732 /* See if it is safe to parse commands internally. */
2734 shell
= default_shell
;
2736 else if (strcmp (shell
, default_shell
))
2738 char *s1
= _fullpath(NULL
, shell
, 0);
2739 char *s2
= _fullpath(NULL
, default_shell
, 0);
2741 slow_flag
= strcmp((s1
? s1
: ""), (s2
? s2
: ""));
2750 #else /* not WINDOWS32 */
2751 #if defined (__MSDOS__) || defined (__EMX__)
2752 else if (stricmp (shell
, default_shell
))
2754 extern int _is_unixy_shell (const char *_path
);
2756 DB (DB_BASIC
, (_("$SHELL changed (was `%s', now `%s')\n"),
2757 default_shell
, shell
));
2758 unixy_shell
= _is_unixy_shell (shell
);
2759 default_shell
= shell
;
2760 /* we must allocate a copy of shell: construct_command_argv() will free
2761 * shell after this function returns. */
2762 default_shell
= xmalloc (strlen (shell
) + 1);
2763 strcpy (default_shell
, shell
);
2767 sh_chars
= sh_chars_sh
;
2768 sh_cmds
= sh_cmds_sh
;
2772 sh_chars
= sh_chars_dos
;
2773 sh_cmds
= sh_cmds_dos
;
2775 if (_osmode
== OS2_MODE
)
2777 sh_chars
= sh_chars_os2
;
2778 sh_cmds
= sh_cmds_os2
;
2781 #else /* !__MSDOS__ */
2782 else if (strcmp (shell
, default_shell
))
2784 #endif /* !__MSDOS__ && !__EMX__ */
2785 #endif /* not WINDOWS32 */
2788 for (ap
= ifs
; *ap
!= '\0'; ++ap
)
2789 if (*ap
!= ' ' && *ap
!= '\t' && *ap
!= '\n')
2792 i
= strlen (line
) + 1;
2794 /* More than 1 arg per character is impossible. */
2795 new_argv
= (char **) xmalloc (i
* sizeof (char *));
2797 /* All the args can fit in a buffer as big as LINE is. */
2798 ap
= new_argv
[0] = (char *) xmalloc (i
);
2801 /* I is how many complete arguments have been found. */
2803 instring
= word_has_equals
= seen_nonequals
= last_argument_was_empty
= 0;
2804 for (p
= line
; *p
!= '\0'; ++p
)
2812 /* Inside a string, just copy any char except a closing quote
2813 or a backslash-newline combination. */
2817 if (ap
== new_argv
[0] || *(ap
-1) == '\0')
2818 last_argument_was_empty
= 1;
2820 else if (*p
== '\\' && p
[1] == '\n')
2821 goto swallow_escaped_newline
;
2822 else if (*p
== '\n' && restp
!= NULL
)
2824 /* End of the command line. */
2828 /* Backslash, $, and ` are special inside double quotes.
2829 If we see any of those, punt.
2830 But on MSDOS, if we use COMMAND.COM, double and single
2831 quotes have the same effect. */
2832 else if (instring
== '"' && strchr ("\\$`", *p
) != 0 && unixy_shell
)
2837 else if (strchr (sh_chars
, *p
) != 0)
2838 /* Not inside a string, but it's a special char. */
2841 else if (*p
== '.' && p
[1] == '.' && p
[2] == '.' && p
[3] != '.')
2842 /* `...' is a wildcard in DJGPP. */
2846 /* Not a special char. */
2850 /* Equals is a special character in leading words before the
2851 first word with no equals sign in it. This is not the case
2852 with sh -k, but we never get here when using nonstandard
2854 if (! seen_nonequals
&& unixy_shell
)
2856 word_has_equals
= 1;
2861 /* Backslash-newline combinations are eaten. */
2864 swallow_escaped_newline
:
2866 /* Eat the backslash, the newline, and following whitespace,
2867 replacing it all with a single space. */
2870 /* If there is a tab after a backslash-newline,
2871 remove it from the source line which will be echoed,
2872 since it was most likely used to line
2873 up the continued line with the previous one. */
2875 /* Note these overlap and strcpy() is undefined for
2876 overlapping objects in ANSI C. The strlen() _IS_ right,
2877 since we need to copy the nul byte too. */
2878 bcopy (p
+ 1, p
, strlen (p
));
2884 if (ap
!= new_argv
[i
])
2885 /* Treat this as a space, ending the arg.
2886 But if it's at the beginning of the arg, it should
2887 just get eaten, rather than becoming an empty arg. */
2890 p
= next_token (p
) - 1;
2893 else if (p
[1] != '\0')
2895 #ifdef HAVE_DOS_PATHS
2896 /* Only remove backslashes before characters special
2897 to Unixy shells. All other backslashes are copied
2898 verbatim, since they are probably DOS-style
2899 directory separators. This still leaves a small
2900 window for problems, but at least it should work
2901 for the vast majority of naive users. */
2904 /* A dot is only special as part of the "..."
2906 if (strneq (p
+ 1, ".\\.\\.", 5))
2914 if (p
[1] != '\\' && p
[1] != '\''
2915 && !isspace ((unsigned char)p
[1])
2916 && (strchr (sh_chars_sh
, p
[1]) == 0))
2917 /* back up one notch, to copy the backslash */
2919 #endif /* HAVE_DOS_PATHS */
2921 /* Copy and skip the following char. */
2934 /* End of the command line. */
2939 /* Newlines are not special. */
2946 /* We have the end of an argument.
2947 Terminate the text of the argument. */
2950 last_argument_was_empty
= 0;
2952 /* Update SEEN_NONEQUALS, which tells us if every word
2953 heretofore has contained an `='. */
2954 seen_nonequals
|= ! word_has_equals
;
2955 if (word_has_equals
&& ! seen_nonequals
)
2956 /* An `=' in a word before the first
2957 word without one is magical. */
2959 word_has_equals
= 0; /* Prepare for the next word. */
2961 /* If this argument is the command name,
2962 see if it is a built-in shell command.
2963 If so, have the shell handle it. */
2967 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
2968 if (streq (sh_cmds
[j
], new_argv
[0]))
2972 /* Ignore multiple whitespace chars. */
2974 /* Next iteration should examine the first nonwhite char. */
2986 /* Let the shell deal with an unterminated quote. */
2989 /* Terminate the last argument and the argument list. */
2992 if (new_argv
[i
][0] != '\0' || last_argument_was_empty
)
2999 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
3000 if (streq (sh_cmds
[j
], new_argv
[0]))
3004 if (new_argv
[0] == 0)
3005 /* Line was empty. */
3011 /* We must use the shell. */
3015 /* Free the old argument list we were working on. */
3017 free ((void *)new_argv
);
3021 execute_by_shell
= 1; /* actually, call `system' if shell isn't unixy */
3030 buffer
= (char *)xmalloc (strlen (line
)+1);
3033 for (dptr
=buffer
; *ptr
; )
3035 if (*ptr
== '\\' && ptr
[1] == '\n')
3037 else if (*ptr
== '@') /* Kludge: multiline commands */
3047 new_argv
= (char **) xmalloc (2 * sizeof (char *));
3048 new_argv
[0] = buffer
;
3051 #else /* Not Amiga */
3054 * Not eating this whitespace caused things like
3058 * which gave the shell fits. I think we have to eat
3059 * whitespace here, but this code should be considered
3060 * suspicious if things start failing....
3063 /* Make sure not to bother processing an empty line. */
3064 while (isspace ((unsigned char)*line
))
3068 #endif /* WINDOWS32 */
3070 /* SHELL may be a multi-word command. Construct a command line
3071 "SHELL -c LINE", with all special chars in LINE escaped.
3072 Then recurse, expanding this command line to get the final
3075 unsigned int shell_len
= strlen (shell
);
3077 static char minus_c
[] = " -c ";
3079 static char minus_c
[] = "";
3081 unsigned int line_len
= strlen (line
);
3083 char *new_line
= (char *) alloca (shell_len
+ (sizeof (minus_c
) - 1)
3084 + (line_len
* 2) + 1);
3085 char *command_ptr
= NULL
; /* used for batch_mode_shell mode */
3087 # ifdef __EMX__ /* is this necessary? */
3089 minus_c
[1] = '/'; /* " /c " */
3093 bcopy (shell
, ap
, shell_len
);
3095 bcopy (minus_c
, ap
, sizeof (minus_c
) - 1);
3096 ap
+= sizeof (minus_c
) - 1;
3098 for (p
= line
; *p
!= '\0'; ++p
)
3100 if (restp
!= NULL
&& *p
== '\n')
3105 else if (*p
== '\\' && p
[1] == '\n')
3107 /* Eat the backslash, the newline, and following whitespace,
3108 replacing it all with a single space (which is escaped
3112 /* If there is a tab after a backslash-newline,
3113 remove it from the source line which will be echoed,
3114 since it was most likely used to line
3115 up the continued line with the previous one. */
3117 bcopy (p
+ 1, p
, strlen (p
));
3121 if (unixy_shell
&& !batch_mode_shell
)
3127 /* DOS shells don't know about backslash-escaping. */
3128 if (unixy_shell
&& !batch_mode_shell
&&
3129 (*p
== '\\' || *p
== '\'' || *p
== '"'
3130 || isspace ((unsigned char)*p
)
3131 || strchr (sh_chars
, *p
) != 0))
3134 else if (unixy_shell
&& strneq (p
, "...", 3))
3136 /* The case of `...' wildcard again. */
3137 strcpy (ap
, "\\.\\.\\");
3144 if (ap
== new_line
+ shell_len
+ sizeof (minus_c
) - 1)
3145 /* Line was empty. */
3150 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3151 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3152 cases, run commands via a script file. */
3153 if ((no_default_sh_exe
|| batch_mode_shell
) && batch_filename_ptr
) {
3155 int id
= GetCurrentProcessId();
3159 /* create a file name */
3160 sprintf(fbuf
, "make%d", id
);
3161 fname
= tempnam(".", fbuf
);
3163 /* create batch file name */
3164 *batch_filename_ptr
= xmalloc(strlen(fname
) + 5);
3165 strcpy(*batch_filename_ptr
, fname
);
3167 /* make sure path name is in DOS backslash format */
3169 fname
= *batch_filename_ptr
;
3170 for (i
= 0; fname
[i
] != '\0'; ++i
)
3171 if (fname
[i
] == '/')
3173 strcat(*batch_filename_ptr
, ".bat");
3175 strcat(*batch_filename_ptr
, ".sh");
3178 DB (DB_JOBS
, (_("Creating temporary batch file %s\n"),
3179 *batch_filename_ptr
));
3181 /* create batch file to execute command */
3182 batch
= fopen (*batch_filename_ptr
, "w");
3184 fputs ("@echo off\n", batch
);
3185 fputs (command_ptr
, batch
);
3186 fputc ('\n', batch
);
3190 new_argv
= (char **) xmalloc(3 * sizeof (char *));
3192 new_argv
[0] = xstrdup (shell
);
3193 new_argv
[1] = *batch_filename_ptr
; /* only argv[0] gets freed later */
3195 new_argv
[0] = xstrdup (*batch_filename_ptr
);
3200 #endif /* WINDOWS32 */
3202 new_argv
= construct_command_argv_internal (new_line
, (char **) NULL
,
3203 (char *) 0, (char *) 0,
3206 else if (!unixy_shell
)
3208 /* new_line is local, must not be freed therefore */
3215 We have to remove all double quotes and to split the line
3216 into distinct arguments because of the strange handling
3217 of builtin commands by cmd: 'echo "bla"' prints "bla"
3218 (with quotes) while 'c:\bin\echo.exe "bla"' prints bla
3219 (without quotes). Some programs like autoconf rely
3220 on the second behaviour. */
3222 len
= strlen (new_line
) + 1;
3224 /* More than 1 arg per character is impossible. */
3225 new_argv
= (char **) xmalloc (len
* sizeof (char *));
3227 /* All the args can fit in a buffer as big as new_line is. */
3228 new_argv
[0] = (char *) xmalloc (len
);
3233 p
= new_argv
[index
];
3236 /* searching for closing quote */
3241 /* remove the quote */
3245 else /* normal character: copy it */
3249 /* searching for opening quote */
3251 # ifndef NO_CMD_DEFAULT
3256 /* remove opening quote */
3261 /* spaces outside of a quoted string: remove them
3262 and start a new argument */
3263 else if (*q
== ' ' || *q
== '\t')
3265 *p
++ = '\0'; /* trailing '\0' for last argument */
3267 /* remove all successive spaces */
3272 while(*q
== ' ' || *q
== '\t');
3274 /* start new argument */
3276 new_argv
[index
] = p
;
3279 /* normal character (no space) outside a quoted string*/
3284 *p
= '\0'; /* trailing '\0' for the last argument */
3285 new_argv
[index
+ 1] = NULL
;
3287 # ifndef NO_CMD_DEFAULT
3288 /* special case: echo x="y"
3289 (e.g. autoconf uses this to determine whether make works)
3290 this is pure idioty but cmd works this way:
3291 if 'echo' and 'x="y"' are two different arguments cmd
3292 will print '"x="y""' but if they are only one argument
3293 cmd will print 'bla="blurb"' as it should be
3294 note: if we do not allow cmd to be the default shell
3295 we do not need this kind of voodoo */
3296 if (index
== 3 && strcasecmp(new_argv
[2], "echo") == 0)
3298 new_argv
[2][4] = ' ';
3303 #elif defined(__MSDOS__)
3306 /* With MSDOS shells, we must construct the command line here
3307 instead of recursively calling ourselves, because we
3308 cannot backslash-escape the special characters (see above). */
3309 new_argv
= (char **) xmalloc (sizeof (char *));
3310 line_len
= strlen (new_line
) - shell_len
- sizeof (minus_c
) + 1;
3311 new_argv
[0] = xmalloc (line_len
+ 1);
3312 strncpy (new_argv
[0],
3313 new_line
+ shell_len
+ sizeof (minus_c
) - 1, line_len
);
3314 new_argv
[0][line_len
] = '\0';
3318 fatal (NILF
, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3319 __FILE__
, __LINE__
);
3322 #endif /* ! AMIGA */
3328 /* Figure out the argument list necessary to run LINE as a command. Try to
3329 avoid using a shell. This routine handles only ' quoting, and " quoting
3330 when no backslash, $ or ` characters are seen in the quotes. Starting
3331 quotes may be escaped with a backslash. If any of the characters in
3332 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3333 is the first word of a line, the shell is used.
3335 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3336 If *RESTP is NULL, newlines will be ignored.
3338 FILE is the target whose commands these are. It is used for
3339 variable expansion for $(SHELL) and $(IFS). */
3342 construct_command_argv (char *line
, char **restp
, struct file
*file
,
3343 char **batch_filename_ptr
)
3357 && (isspace ((unsigned char)*cptr
)))
3362 && (!isspace((unsigned char)*cptr
)))
3367 argv
= (char **)malloc (argc
* sizeof (char *));
3376 && (isspace ((unsigned char)*cptr
)))
3380 DB (DB_JOBS
, ("argv[%d] = [%s]\n", argc
, cptr
));
3381 argv
[argc
++] = cptr
;
3383 && (!isspace((unsigned char)*cptr
)))
3390 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3391 int save
= warn_undefined_variables_flag
;
3392 warn_undefined_variables_flag
= 0;
3394 shell
= allocated_variable_expand_for_file ("$(SHELL)", file
);
3397 * Convert to forward slashes so that construct_command_argv_internal()
3401 char *p
= w32ify (shell
, 0);
3407 static const char *unixroot
= NULL
;
3408 static const char *last_shell
= "";
3409 static int init
= 0;
3412 unixroot
= getenv ("UNIXROOT");
3413 /* unixroot must be NULL or not empty */
3414 if (unixroot
&& unixroot
[0] == '\0') unixroot
= NULL
;
3418 /* if we have an unixroot drive and if shell is not default_shell
3419 (which means it's either cmd.exe or the test has already been
3420 performed) and if shell is an absolute path without drive letter,
3421 try whether it exists e.g.: if "/bin/sh" does not exist use
3422 "$UNIXROOT/bin/sh" instead. */
3423 if (unixroot
&& shell
&& strcmp (shell
, last_shell
) != 0
3424 && (shell
[0] == '/' || shell
[0] == '\\'))
3426 /* trying a new shell, check whether it exists */
3427 size_t size
= strlen (shell
);
3428 char *buf
= xmalloc (size
+ 7);
3429 memcpy (buf
, shell
, size
);
3430 memcpy (buf
+ size
, ".exe", 5); /* including the trailing '\0' */
3431 if (access (shell
, F_OK
) != 0 && access (buf
, F_OK
) != 0)
3433 /* try the same for the unixroot drive */
3434 memmove (buf
+ 2, buf
, size
+ 5);
3435 buf
[0] = unixroot
[0];
3436 buf
[1] = unixroot
[1];
3437 if (access (buf
, F_OK
) == 0)
3438 /* we have found a shell! */
3450 ifs
= allocated_variable_expand_for_file ("$(IFS)", file
);
3452 warn_undefined_variables_flag
= save
;
3455 argv
= construct_command_argv_internal (line
, restp
, shell
, ifs
, batch_filename_ptr
);
3463 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3465 dup2 (int old
, int new)
3480 #endif /* !HAPE_DUP2 && !_AMIGA */