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. */
36 /* Default shell to use. */
39 char *default_shell
= "sh.exe";
40 int no_default_sh_exe
= 1;
41 int batch_mode_shell
= 1;
43 #elif defined (_AMIGA)
44 char default_shell
[] = "";
45 int batch_mode_shell
= 0;
47 #elif defined (__MSDOS__)
49 /* The default shell is a pointer so we can change it if Makefile
50 says so. It is without an explicit path so we get a chance
51 to search the $PATH for it (since MSDOS doesn't have standard
52 directories we could trust). */
53 char *default_shell
= "command.com";
54 int batch_mode_shell
= 0;
56 #elif defined (__EMX__)
58 char *default_shell
= "/bin/sh";
59 int batch_mode_shell
= 0;
64 char default_shell
[] = "";
65 int batch_mode_shell
= 0;
67 #elif defined (__riscos__)
69 char default_shell
[] = "";
70 int batch_mode_shell
= 0;
74 char default_shell
[] = "/bin/sh";
75 int batch_mode_shell
= 0;
81 static int execute_by_shell
;
82 static int dos_pid
= 123;
84 int dos_command_running
;
85 #endif /* __MSDOS__ */
88 # include <proto/dos.h>
89 static int amiga_pid
= 123;
90 static int amiga_status
;
91 static char amiga_bname
[32];
92 static int amiga_batch_file
;
97 # include <processes.h>
100 # include <lib$routines.h>
104 # include <windows.h>
106 # include <process.h>
107 # include "sub_proc.h"
109 # include "pathstuff.h"
110 #endif /* WINDOWS32 */
113 # include <process.h>
116 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
117 # include <sys/wait.h>
121 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
122 #else /* Don't have waitpid. */
127 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
128 # endif /* Have wait3. */
129 #endif /* Have waitpid. */
131 #if !defined (wait) && !defined (POSIX)
135 #ifndef HAVE_UNION_WAIT
140 # define WTERMSIG(x) ((x) & 0x7f)
143 # define WCOREDUMP(x) ((x) & 0x80)
146 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
149 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
152 # define WIFEXITED(x) (WTERMSIG (x) == 0)
155 #else /* Have `union wait'. */
157 # define WAIT_T union wait
159 # define WTERMSIG(x) ((x).w_termsig)
162 # define WCOREDUMP(x) ((x).w_coredump)
165 # define WEXITSTATUS(x) ((x).w_retcode)
168 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
171 # define WIFEXITED(x) (WTERMSIG(x) == 0)
174 #endif /* Don't have `union wait'. */
177 static int vms_jobsefnmask
= 0;
180 #ifndef HAVE_UNISTD_H
182 extern int execve ();
183 extern void _exit ();
185 extern int geteuid ();
186 extern int getegid ();
187 extern int setgid ();
188 extern int getgid ();
192 extern char *allocated_variable_expand_for_file
PARAMS ((char *line
, struct file
*file
));
194 extern int getloadavg
PARAMS ((double loadavg
[], int nelem
));
195 extern int start_remote_job
PARAMS ((char **argv
, char **envp
, int stdin_fd
,
196 int *is_remote
, int *id_ptr
, int *used_stdin
));
197 extern int start_remote_job_p
PARAMS ((int));
198 extern int remote_status
PARAMS ((int *exit_code_ptr
, int *signal_ptr
,
199 int *coredump_ptr
, int block
));
201 RETSIGTYPE child_handler
PARAMS ((int));
202 static void free_child
PARAMS ((struct child
*));
203 static void start_job_command
PARAMS ((struct child
*child
));
204 static int load_too_high
PARAMS ((void));
205 static int job_next_command
PARAMS ((struct child
*));
206 static int start_waiting_job
PARAMS ((struct child
*));
208 static void vmsWaitForChildren
PARAMS ((int *));
211 /* Chain of all live (or recently deceased) children. */
213 struct child
*children
= 0;
215 /* Number of children currently running. */
217 unsigned int job_slots_used
= 0;
219 /* Nonzero if the `good' standard input is in use. */
221 static int good_stdin_used
= 0;
223 /* Chain of children waiting to run until the load average goes down. */
225 static struct child
*waiting_jobs
= 0;
227 /* Non-zero if we use a *real* shell (always so on Unix). */
231 /* Number of jobs started in the current second. */
233 unsigned long job_counter
= 0;
238 * The macro which references this function is defined in make.h.
241 w32_kill(int pid
, int sig
)
243 return ((process_kill(pid
, sig
) == TRUE
) ? 0 : -1);
245 #endif /* WINDOWS32 */
248 /* returns whether path is assumed to be a unix like shell. */
250 _is_unixy_shell (const char *path
)
252 /* list of non unix shells */
253 const char *known_os2shells
[] = {
265 /* find the rightmost '/' or '\\' */
266 const char *name
= strrchr (path
, '/');
267 const char *p
= strrchr (path
, '\\');
270 if (name
&& p
) /* take the max */
271 name
= (name
> p
) ? name
: p
;
272 else if (p
) /* name must be 0 */
274 else if (!name
) /* name and p must be 0 */
277 if (*name
== '/' || *name
== '\\') name
++;
280 while (known_os2shells
[i
] != NULL
) {
281 if (stricmp (name
, known_os2shells
[i
]) == 0) /* strcasecmp() */
282 return 0; /* not a unix shell */
286 /* in doubt assume a unix like shell */
292 /* Write an error message describing the exit status given in
293 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
294 Append "(ignored)" if IGNORED is nonzero. */
297 child_error (char *target_name
, int exit_code
, int exit_sig
, int coredump
,
300 if (ignored
&& silent_flag
)
304 if (!(exit_code
& 1))
306 (ignored
? _("*** [%s] Error 0x%x (ignored)")
307 : _("*** [%s] Error 0x%x")),
308 target_name
, exit_code
);
311 error (NILF
, ignored
? _("[%s] Error %d (ignored)") :
312 _("*** [%s] Error %d"),
313 target_name
, exit_code
);
315 error (NILF
, "*** [%s] %s%s",
316 target_name
, strsignal (exit_sig
),
317 coredump
? _(" (core dumped)") : "");
322 /* Wait for nchildren children to terminate */
324 vmsWaitForChildren(int *status
)
328 if (!vms_jobsefnmask
)
334 *status
= sys$
wflor (32, vms_jobsefnmask
);
339 /* Set up IO redirection. */
342 vms_redirect (struct dsc$descriptor_s
*desc
, char *fname
, char *ibuf
)
345 extern char *vmsify ();
348 while (isspace ((unsigned char)*ibuf
))
351 while (*ibuf
&& !isspace ((unsigned char)*ibuf
))
354 if (strcmp (fptr
, "/dev/null") != 0)
356 strcpy (fname
, vmsify (fptr
, 0));
357 if (strchr (fname
, '.') == 0)
360 desc
->dsc$w_length
= strlen(fname
);
361 desc
->dsc$a_pointer
= fname
;
362 desc
->dsc$b_dtype
= DSC$K_DTYPE_T
;
363 desc
->dsc$b_class
= DSC$K_CLASS_S
;
366 printf (_("Warning: Empty redirection\n"));
371 /* found apostrophe at (p-1)
372 inc p until after closing apostrophe.
376 vms_handle_apos (char *p
)
380 #define SEPCHARS ",/()= "
396 if (strchr (SEPCHARS
, *p
))
411 /* Handle a dead child. This handler may or may not ever be installed.
413 If we're using the jobserver feature, we need it. First, installing it
414 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
415 read FD to ensure we don't enter another blocking read without reaping all
416 the dead children. In this case we don't need the dead_children count.
418 If we don't have either waitpid or wait3, then make is unreliable, but we
419 use the dead_children count to reap children as best we can. */
421 static unsigned int dead_children
= 0;
424 child_handler (int sig UNUSED
)
435 /* The signal handler must called only once! */
436 signal (SIGCHLD
, SIG_DFL
);
439 /* This causes problems if the SIGCHLD interrupts a printf().
440 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
444 extern int shell_function_pid
, shell_function_completed
;
446 /* Reap all dead children, storing the returned status and the new command
447 state (`cs_finished') in the `file' member of the `struct child' for the
448 dead child, and removing the child from the chain. In addition, if BLOCK
449 nonzero, we block in this function until we've reaped at least one
450 complete child, waiting for it to die if necessary. If ERR is nonzero,
451 print an error message first. */
454 reap_children (int block
, int err
)
457 /* Initially, assume we have some. */
461 # define REAP_MORE reap_more
463 # define REAP_MORE dead_children
468 We have at least one child outstanding OR a shell function in progress,
470 We're blocking for a complete child OR there are more children to reap
472 we'll keep reaping children. */
474 while ((children
!= 0 || shell_function_pid
!= 0)
475 && (block
|| REAP_MORE
))
479 int exit_code
, exit_sig
, coredump
;
480 register struct child
*lastc
, *c
;
482 int any_remote
, any_local
;
486 /* We might block for a while, so let the user know why. */
488 error (NILF
, _("*** Waiting for unfinished jobs...."));
491 /* We have one less dead child to reap. As noted in
492 child_handler() above, this count is completely unimportant for
493 all modern, POSIX-y systems that support wait3() or waitpid().
494 The rest of this comment below applies only to early, broken
495 pre-POSIX systems. We keep the count only because... it's there...
497 The test and decrement are not atomic; if it is compiled into:
498 register = dead_children - 1;
499 dead_children = register;
500 a SIGCHLD could come between the two instructions.
501 child_handler increments dead_children.
502 The second instruction here would lose that increment. But the
503 only effect of dead_children being wrong is that we might wait
504 longer than necessary to reap a child, and lose some parallelism;
505 and we might print the "Waiting for unfinished jobs" message above
506 when not necessary. */
508 if (dead_children
> 0)
512 any_local
= shell_function_pid
!= 0;
513 for (c
= children
; c
!= 0; c
= c
->next
)
515 any_remote
|= c
->remote
;
516 any_local
|= ! c
->remote
;
517 DB (DB_JOBS
, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
518 (unsigned long int) c
, c
->file
->name
,
519 (long) c
->pid
, c
->remote
? _(" (remote)") : ""));
525 /* First, check for remote children. */
527 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 0);
532 /* We got a remote child. */
536 /* A remote status command failed miserably. Punt. */
538 pfatal_with_name ("remote_status");
542 /* No remote children. Check for local children. */
543 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
547 vmsWaitForChildren (&status
);
552 pid
= WAIT_NOHANG (&status
);
555 pid
= wait (&status
);
563 /* The wait*() failed miserably. Punt. */
564 pfatal_with_name ("wait");
568 /* We got a child exit; chop the status word up. */
569 exit_code
= WEXITSTATUS (status
);
570 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
571 coredump
= WCOREDUMP (status
);
573 /* If we have started jobs in this second, remove one. */
579 /* No local children are dead. */
582 if (!block
|| !any_remote
)
585 /* Now try a blocking wait for a remote child. */
586 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 1);
588 goto remote_status_lose
;
590 /* No remote children either. Finally give up. */
593 /* We got a remote child. */
596 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
599 /* Life is very different on MSDOS. */
602 exit_code
= WEXITSTATUS (status
);
603 if (exit_code
== 0xff)
605 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
607 #endif /* __MSDOS__ */
611 status
= amiga_status
;
612 exit_code
= amiga_status
;
624 /* wait for anything to finish */
625 hPID
= process_wait_for_any();
629 /* was an error found on this process? */
630 err
= process_last_err(hPID
);
633 exit_code
= process_exit_code(hPID
);
636 fprintf(stderr
, "make (e=%d): %s",
637 exit_code
, map_windows32_error_to_string(exit_code
));
640 exit_sig
= process_signal(hPID
);
642 /* cleanup process */
643 process_cleanup(hPID
);
649 #endif /* WINDOWS32 */
652 /* Check if this is the child of the `shell' function. */
653 if (!remote
&& pid
== shell_function_pid
)
655 /* It is. Leave an indicator for the `shell' function. */
656 if (exit_sig
== 0 && exit_code
== 127)
657 shell_function_completed
= -1;
659 shell_function_completed
= 1;
663 child_failed
= exit_sig
!= 0 || exit_code
!= 0;
665 /* Search for a child matching the deceased one. */
667 for (c
= children
; c
!= 0; lastc
= c
, c
= c
->next
)
668 if (c
->remote
== remote
&& c
->pid
== pid
)
672 /* An unknown child died.
673 Ignore it; it was inherited from our invoker. */
676 DB (DB_JOBS
, (child_failed
677 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
678 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
679 (unsigned long int) c
, (long) c
->pid
,
680 c
->remote
? _(" (remote)") : ""));
682 if (c
->sh_batch_file
) {
683 DB (DB_JOBS
, (_("Cleaning up temp batch file %s\n"),
686 /* just try and remove, don't care if this fails */
687 remove (c
->sh_batch_file
);
689 /* all done with memory */
690 free (c
->sh_batch_file
);
691 c
->sh_batch_file
= NULL
;
694 /* If this child had the good stdin, say it is now free. */
698 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
700 /* The commands failed. Write an error message,
701 delete non-precious targets, and abort. */
702 static int delete_on_error
= -1;
703 child_error (c
->file
->name
, exit_code
, exit_sig
, coredump
, 0);
704 c
->file
->update_status
= 2;
705 if (delete_on_error
== -1)
707 struct file
*f
= lookup_file (".DELETE_ON_ERROR");
708 delete_on_error
= f
!= 0 && f
->is_target
;
710 if (exit_sig
!= 0 || delete_on_error
)
711 delete_child_targets (c
);
717 /* The commands failed, but we don't care. */
718 child_error (c
->file
->name
,
719 exit_code
, exit_sig
, coredump
, 1);
723 /* If there are more commands to run, try to start them. */
724 if (job_next_command (c
))
726 if (handling_fatal_signal
)
728 /* Never start new commands while we are dying.
729 Since there are more commands that wanted to be run,
730 the target was not completely remade. So we treat
731 this as if a command had failed. */
732 c
->file
->update_status
= 2;
736 /* Check again whether to start remotely.
737 Whether or not we want to changes over time.
738 Also, start_remote_job may need state set up
739 by start_remote_job_p. */
740 c
->remote
= start_remote_job_p (0);
741 start_job_command (c
);
742 /* Fatal signals are left blocked in case we were
743 about to put that child on the chain. But it is
744 already there, so it is safe for a fatal signal to
745 arrive now; it will clean up this child's targets. */
747 if (c
->file
->command_state
== cs_running
)
748 /* We successfully started the new command.
749 Loop to reap more children. */
753 if (c
->file
->update_status
!= 0)
754 /* We failed to start the commands. */
755 delete_child_targets (c
);
758 /* There are no more commands. We got through them all
759 without an unignored error. Now the target has been
760 successfully updated. */
761 c
->file
->update_status
= 0;
764 /* When we get here, all the commands for C->file are finished
765 (or aborted) and C->file->update_status contains 0 or 2. But
766 C->file->command_state is still cs_running if all the commands
767 ran; notice_finish_file looks for cs_running to tell it that
768 it's interesting to check the file's modtime again now. */
770 if (! handling_fatal_signal
)
771 /* Notice if the target of the commands has been changed.
772 This also propagates its values for command_state and
773 update_status to its also_make files. */
774 notice_finished_file (c
->file
);
776 DB (DB_JOBS
, (_("Removing child 0x%08lx PID %ld%s from chain.\n"),
777 (unsigned long int) c
, (long) c
->pid
,
778 c
->remote
? _(" (remote)") : ""));
780 /* Block fatal signals while frobnicating the list, so that
781 children and job_slots_used are always consistent. Otherwise
782 a fatal signal arriving after the child is off the chain and
783 before job_slots_used is decremented would believe a child was
784 live and call reap_children again. */
787 /* There is now another slot open. */
788 if (job_slots_used
> 0)
791 /* Remove the child from the chain and free it. */
795 lastc
->next
= c
->next
;
801 /* If the job failed, and the -k flag was not given, die,
802 unless we are already in the process of dying. */
803 if (!err
&& child_failed
&& !keep_going_flag
&&
804 /* fatal_error_signal will die with the right signal. */
805 !handling_fatal_signal
)
808 /* Only block for one child. */
815 /* Free the storage allocated for CHILD. */
818 free_child (struct child
*child
)
820 /* If this child is the only one it was our "free" job, so don't put a
821 token back for it. This child has already been removed from the list,
822 so if there any left this wasn't the last one. */
824 if (job_fds
[1] >= 0 && children
)
829 /* Write a job token back to the pipe. */
831 EINTRLOOP (r
, write (job_fds
[1], &token
, 1));
833 pfatal_with_name (_("write jobserver"));
835 DB (DB_JOBS
, (_("Released token for child 0x%08lx (%s).\n"),
836 (unsigned long int) child
, child
->file
->name
));
839 if (handling_fatal_signal
) /* Don't bother free'ing if about to die. */
842 if (child
->command_lines
!= 0)
844 register unsigned int i
;
845 for (i
= 0; i
< child
->file
->cmds
->ncommand_lines
; ++i
)
846 free (child
->command_lines
[i
]);
847 free ((char *) child
->command_lines
);
850 if (child
->environment
!= 0)
852 register char **ep
= child
->environment
;
855 free ((char *) child
->environment
);
858 free ((char *) child
);
862 extern sigset_t fatal_signal_set
;
872 (void) sigprocmask (SIG_BLOCK
, &fatal_signal_set
, (sigset_t
*) 0);
874 #ifdef HAVE_SIGSETMASK
875 (void) sigblock (fatal_signal_mask
);
887 sigemptyset (&empty
);
888 sigprocmask (SIG_SETMASK
, &empty
, (sigset_t
*) 0);
894 #ifdef MAKE_JOBSERVER
895 /* Set the child handler action flags to FLAGS. */
897 set_child_handler_action_flags (int flags
)
900 bzero ((char *) &sa
, sizeof sa
);
901 sa
.sa_handler
= child_handler
;
904 sigaction (SIGCHLD
, &sa
, NULL
);
906 #if defined SIGCLD && SIGCLD != SIGCHLD
907 sigaction (SIGCLD
, &sa
, NULL
);
913 /* Start a job to run the commands specified in CHILD.
914 CHILD is updated to reflect the commands and ID of the child process.
916 NOTE: On return fatal signals are blocked! The caller is responsible
917 for calling `unblock_sigs', once the new child is safely on the chain so
918 it can be cleaned up in the event of a fatal signal. */
921 start_job_command (struct child
*child
)
924 static int bad_stdin
= -1;
934 /* If we have a completely empty commandset, stop now. */
935 if (!child
->command_ptr
)
938 /* Combine the flags parsed for the line itself with
939 the flags specified globally for this target. */
940 flags
= (child
->file
->command_flags
941 | child
->file
->cmds
->lines_flags
[child
->command_line
- 1]);
943 p
= child
->command_ptr
;
944 child
->noerror
= flags
& COMMANDS_NOERROR
;
949 flags
|= COMMANDS_SILENT
;
951 flags
|= COMMANDS_RECURSE
;
954 else if (!isblank ((unsigned char)*p
))
959 /* Update the file's command flags with any new ones we found. We only
960 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
961 now marking more commands recursive than should be in the case of
962 multiline define/endef scripts where only one line is marked "+". In
963 order to really fix this, we'll have to keep a lines_flags for every
964 actual line, after expansion. */
965 child
->file
->cmds
->lines_flags
[child
->command_line
- 1]
966 |= flags
& COMMANDS_RECURSE
;
968 /* Figure out an argument list from this command line. */
975 argv
= construct_command_argv (p
, &end
, child
->file
, &child
->sh_batch_file
);
978 child
->command_ptr
= NULL
;
982 child
->command_ptr
= end
;
986 /* If -q was given, say that updating `failed' if there was any text on the
987 command line, or `succeeded' otherwise. The exit status of 1 tells the
988 user that -q is saying `something to do'; the exit status for a random
990 if (argv
!= 0 && question_flag
&& !(flags
& COMMANDS_RECURSE
))
994 free ((char *) argv
);
996 child
->file
->update_status
= 1;
997 notice_finished_file (child
->file
);
1001 if (touch_flag
&& !(flags
& COMMANDS_RECURSE
))
1003 /* Go on to the next command. It might be the recursive one.
1004 We construct ARGV only to find the end of the command line. */
1009 free ((char *) argv
);
1019 execute_by_shell
= 0; /* in case construct_command_argv sets it */
1021 /* This line has no commands. Go to the next. */
1022 if (job_next_command (child
))
1023 start_job_command (child
);
1026 /* No more commands. Make sure we're "running"; we might not be if
1027 (e.g.) all commands were skipped due to -n. */
1028 set_command_state (child
->file
, cs_running
);
1029 child
->file
->update_status
= 0;
1030 notice_finished_file (child
->file
);
1035 /* Print out the command. If silent, we call `message' with null so it
1036 can log the working directory before the command's own error messages
1039 message (0, (just_print_flag
|| (!(flags
& COMMANDS_SILENT
) && !silent_flag
))
1040 ? "%s" : (char *) 0, p
);
1042 /* Tell update_goal_chain that a command has been started on behalf of
1043 this target. It is important that this happens here and not in
1044 reap_children (where we used to do it), because reap_children might be
1045 reaping children from a different target. We want this increment to
1046 guaranteedly indicate that a command was started for the dependency
1047 chain (i.e., update_file recursion chain) we are processing. */
1051 /* Optimize an empty command. People use this for timestamp rules,
1052 so avoid forking a useless shell. Do this after we increment
1053 commands_started so make still treats this special case as if it
1054 performed some action (makes a difference as to what messages are
1057 #if !defined(VMS) && !defined(_AMIGA)
1059 #if defined __MSDOS__ || defined (__EMX__)
1060 unixy_shell
/* the test is complicated and we already did it */
1062 (argv
[0] && !strcmp (argv
[0], "/bin/sh"))
1065 && argv
[1][0] == '-' && argv
[1][1] == 'c' && argv
[1][2] == '\0')
1066 && (argv
[2] && argv
[2][0] == ':' && argv
[2][1] == '\0')
1070 free ((char *) argv
);
1073 #endif /* !VMS && !_AMIGA */
1075 /* If -n was given, recurse to get the next line in the sequence. */
1077 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
))
1081 free ((char *) argv
);
1086 /* Flush the output streams so they won't have things written twice. */
1092 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1094 /* Set up a bad standard input that reads from a broken pipe. */
1096 if (bad_stdin
== -1)
1098 /* Make a file descriptor that is the read end of a broken pipe.
1099 This will be used for some children's standard inputs. */
1103 /* Close the write side. */
1104 (void) close (pd
[1]);
1105 /* Save the read side. */
1108 /* Set the descriptor to close on exec, so it does not litter any
1109 child's descriptor table. When it is dup2'd onto descriptor 0,
1110 that descriptor will not close on exec. */
1111 CLOSE_ON_EXEC (bad_stdin
);
1115 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1117 /* Decide whether to give this child the `good' standard input
1118 (one that points to the terminal or whatever), or the `bad' one
1119 that points to the read side of a broken pipe. */
1121 child
->good_stdin
= !good_stdin_used
;
1122 if (child
->good_stdin
)
1123 good_stdin_used
= 1;
1130 /* Set up the environment for the child. */
1131 if (child
->environment
== 0)
1132 child
->environment
= target_environment (child
->file
);
1135 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1138 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1141 int is_remote
, id
, used_stdin
;
1142 if (start_remote_job (argv
, child
->environment
,
1143 child
->good_stdin
? 0 : bad_stdin
,
1144 &is_remote
, &id
, &used_stdin
))
1145 /* Don't give up; remote execution may fail for various reasons. If
1146 so, simply run the job locally. */
1150 if (child
->good_stdin
&& !used_stdin
)
1152 child
->good_stdin
= 0;
1153 good_stdin_used
= 0;
1155 child
->remote
= is_remote
;
1162 /* Fork the child process. */
1164 char **parent_environ
;
1173 if (!child_execute_job (argv
, child
)) {
1175 perror_with_name ("vfork", "");
1181 parent_environ
= environ
;
1184 /* If we aren't running a recursive command and we have a jobserver
1185 pipe, close it before exec'ing. */
1186 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1188 CLOSE_ON_EXEC (job_fds
[0]);
1189 CLOSE_ON_EXEC (job_fds
[1]);
1192 CLOSE_ON_EXEC (job_rfd
);
1194 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1195 child
->pid
= child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1196 argv
, child
->environment
);
1201 perror_with_name ("spawn", "");
1205 /* undo CLOSE_ON_EXEC() after the child process has been started */
1206 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1208 fcntl (job_fds
[0], F_SETFD
, 0);
1209 fcntl (job_fds
[1], F_SETFD
, 0);
1212 fcntl (job_rfd
, F_SETFD
, 0);
1214 #else /* !__EMX__ */
1216 child
->pid
= vfork ();
1217 environ
= parent_environ
; /* Restore value child may have clobbered. */
1218 if (child
->pid
== 0)
1220 /* We are the child side. */
1223 /* If we aren't running a recursive command and we have a jobserver
1224 pipe, close it before exec'ing. */
1225 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1233 child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1234 argv
, child
->environment
);
1236 else if (child
->pid
< 0)
1240 perror_with_name ("vfork", "");
1243 # endif /* !__EMX__ */
1247 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1255 /* We call `system' to do the job of the SHELL, since stock DOS
1256 shell is too dumb. Our `system' knows how to handle long
1257 command lines even if pipes/redirection is needed; it will only
1258 call COMMAND.COM when its internal commands are used. */
1259 if (execute_by_shell
)
1261 char *cmdline
= argv
[0];
1262 /* We don't have a way to pass environment to `system',
1263 so we need to save and restore ours, sigh... */
1264 char **parent_environ
= environ
;
1266 environ
= child
->environment
;
1268 /* If we have a *real* shell, tell `system' to call
1269 it to do everything for us. */
1272 /* A *real* shell on MSDOS may not support long
1273 command lines the DJGPP way, so we must use `system'. */
1274 cmdline
= argv
[2]; /* get past "shell -c" */
1277 dos_command_running
= 1;
1278 proc_return
= system (cmdline
);
1279 environ
= parent_environ
;
1280 execute_by_shell
= 0; /* for the next time */
1284 dos_command_running
= 1;
1285 proc_return
= spawnvpe (P_WAIT
, argv
[0], argv
, child
->environment
);
1288 /* Need to unblock signals before turning off
1289 dos_command_running, so that child's signals
1290 will be treated as such (see fatal_error_signal). */
1292 dos_command_running
= 0;
1294 /* If the child got a signal, dos_status has its
1295 high 8 bits set, so be careful not to alter them. */
1296 if (proc_return
== -1)
1299 dos_status
|= (proc_return
& 0xff);
1301 child
->pid
= dos_pid
++;
1303 #endif /* __MSDOS__ */
1305 amiga_status
= MyExecute (argv
, child
->environment
, NULL
);
1308 child
->pid
= amiga_pid
++;
1309 if (amiga_batch_file
)
1311 amiga_batch_file
= 0;
1312 DeleteFile (amiga_bname
); /* Ignore errors. */
1320 /* make UNC paths safe for CreateProcess -- backslash format */
1322 if (arg0
&& arg0
[0] == '/' && arg0
[1] == '/')
1323 for ( ; arg0
&& *arg0
; arg0
++)
1327 /* make sure CreateProcess() has Path it needs */
1328 sync_Path_environment();
1330 hPID
= process_easy(argv
, child
->environment
);
1332 if (hPID
!= INVALID_HANDLE_VALUE
)
1333 child
->pid
= (int) hPID
;
1338 _("process_easy() failed failed to launch process (e=%d)\n"),
1339 process_last_err(hPID
));
1340 for (i
= 0; argv
[i
]; i
++)
1341 fprintf(stderr
, "%s ", argv
[i
]);
1342 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
1345 #endif /* WINDOWS32 */
1346 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1348 /* Bump the number of jobs started in this second. */
1351 /* We are the parent side. Set the state to
1352 say the commands are running and return. */
1354 set_command_state (child
->file
, cs_running
);
1356 /* Free the storage used by the child's argument list. */
1359 free ((char *) argv
);
1365 child
->file
->update_status
= 2;
1366 notice_finished_file (child
->file
);
1370 /* Try to start a child running.
1371 Returns nonzero if the child was started (and maybe finished), or zero if
1372 the load was too high and the child was put on the `waiting_jobs' chain. */
1375 start_waiting_job (struct child
*c
)
1377 struct file
*f
= c
->file
;
1379 /* If we can start a job remotely, we always want to, and don't care about
1380 the local load average. We record that the job should be started
1381 remotely in C->remote for start_job_command to test. */
1383 c
->remote
= start_remote_job_p (1);
1385 /* If we are running at least one job already and the load average
1386 is too high, make this one wait. */
1387 if (!c
->remote
&& job_slots_used
> 0 && load_too_high ())
1389 /* Put this child on the chain of children waiting for the load average
1391 set_command_state (f
, cs_running
);
1392 c
->next
= waiting_jobs
;
1397 /* Start the first command; reap_children will run later command lines. */
1398 start_job_command (c
);
1400 switch (f
->command_state
)
1404 DB (DB_JOBS
, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1405 (unsigned long int) c
, c
->file
->name
,
1406 (long) c
->pid
, c
->remote
? _(" (remote)") : ""));
1408 /* One more job slot is in use. */
1413 case cs_not_started
:
1414 /* All the command lines turned out to be empty. */
1415 f
->update_status
= 0;
1419 notice_finished_file (f
);
1424 assert (f
->command_state
== cs_finished
);
1431 /* Create a `struct child' for FILE and start its commands running. */
1434 new_job (struct file
*file
)
1436 register struct commands
*cmds
= file
->cmds
;
1437 register struct child
*c
;
1439 register unsigned int i
;
1441 /* Let any previously decided-upon jobs that are waiting
1442 for the load to go down start before this new one. */
1443 start_waiting_jobs ();
1445 /* Reap any children that might have finished recently. */
1446 reap_children (0, 0);
1448 /* Chop the commands up into lines if they aren't already. */
1449 chop_commands (cmds
);
1451 /* Expand the command lines and store the results in LINES. */
1452 lines
= (char **) xmalloc (cmds
->ncommand_lines
* sizeof (char *));
1453 for (i
= 0; i
< cmds
->ncommand_lines
; ++i
)
1455 /* Collapse backslash-newline combinations that are inside variable
1456 or function references. These are left alone by the parser so
1457 that they will appear in the echoing of commands (where they look
1458 nice); and collapsed by construct_command_argv when it tokenizes.
1459 But letting them survive inside function invocations loses because
1460 we don't want the functions to see them as part of the text. */
1462 char *in
, *out
, *ref
;
1464 /* IN points to where in the line we are scanning.
1465 OUT points to where in the line we are writing.
1466 When we collapse a backslash-newline combination,
1467 IN gets ahead of OUT. */
1469 in
= out
= cmds
->command_lines
[i
];
1470 while ((ref
= strchr (in
, '$')) != 0)
1472 ++ref
; /* Move past the $. */
1475 /* Copy the text between the end of the last chunk
1476 we processed (where IN points) and the new chunk
1477 we are about to process (where REF points). */
1478 bcopy (in
, out
, ref
- in
);
1480 /* Move both pointers past the boring stuff. */
1484 if (*ref
== '(' || *ref
== '{')
1486 char openparen
= *ref
;
1487 char closeparen
= openparen
== '(' ? ')' : '}';
1491 *out
++ = *in
++; /* Copy OPENPAREN. */
1492 /* IN now points past the opening paren or brace.
1493 Count parens or braces until it is matched. */
1497 if (*in
== closeparen
&& --count
< 0)
1499 else if (*in
== '\\' && in
[1] == '\n')
1501 /* We have found a backslash-newline inside a
1502 variable or function reference. Eat it and
1503 any following whitespace. */
1506 for (p
= in
- 1; p
> ref
&& *p
== '\\'; --p
)
1510 /* There were two or more backslashes, so this is
1511 not really a continuation line. We don't collapse
1512 the quoting backslashes here as is done in
1513 collapse_continuations, because the line will
1514 be collapsed again after expansion. */
1518 /* Skip the backslash, newline and
1519 any following whitespace. */
1520 in
= next_token (in
+ 2);
1522 /* Discard any preceding whitespace that has
1523 already been written to the output. */
1525 && isblank ((unsigned char)out
[-1]))
1528 /* Replace it all with a single space. */
1534 if (*in
== openparen
)
1543 /* There are no more references in this line to worry about.
1544 Copy the remaining uninteresting text to the output. */
1548 /* Finally, expand the line. */
1549 lines
[i
] = allocated_variable_expand_for_file (cmds
->command_lines
[i
],
1553 /* Start the command sequence, record it in a new
1554 `struct child', and add that to the chain. */
1556 c
= (struct child
*) xmalloc (sizeof (struct child
));
1557 bzero ((char *)c
, sizeof (struct child
));
1559 c
->command_lines
= lines
;
1560 c
->sh_batch_file
= NULL
;
1562 /* Fetch the first command line to be run. */
1563 job_next_command (c
);
1565 /* Wait for a job slot to be freed up. If we allow an infinite number
1566 don't bother; also job_slots will == 0 if we're using the jobserver. */
1569 while (job_slots_used
== job_slots
)
1570 reap_children (1, 0);
1572 #ifdef MAKE_JOBSERVER
1573 /* If we are controlling multiple jobs make sure we have a token before
1574 starting the child. */
1576 /* This can be inefficient. There's a decent chance that this job won't
1577 actually have to run any subprocesses: the command script may be empty
1578 or otherwise optimized away. It would be nice if we could defer
1579 obtaining a token until just before we need it, in start_job_command.
1580 To do that we'd need to keep track of whether we'd already obtained a
1581 token (since start_job_command is called for each line of the job, not
1582 just once). Also more thought needs to go into the entire algorithm;
1583 this is where the old parallel job code waits, so... */
1585 else if (job_fds
[0] >= 0)
1592 DB (DB_JOBS
, ("Need a job token; we %shave children\n",
1593 children
? "" : "don't "));
1595 /* If we don't already have a job started, use our "free" token. */
1599 /* Read a token. As long as there's no token available we'll block.
1600 We enable interruptible system calls before the read(2) so that if
1601 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1602 we can process the death(s) and return tokens to the free pool.
1604 Once we return from the read, we immediately reinstate restartable
1605 system calls. This allows us to not worry about checking for
1606 EINTR on all the other system calls in the program.
1608 There is one other twist: there is a span between the time
1609 reap_children() does its last check for dead children and the time
1610 the read(2) call is entered, below, where if a child dies we won't
1611 notice. This is extremely serious as it could cause us to
1612 deadlock, given the right set of events.
1614 To avoid this, we do the following: before we reap_children(), we
1615 dup(2) the read FD on the jobserver pipe. The read(2) call below
1616 uses that new FD. In the signal handler, we close that FD. That
1617 way, if a child dies during the section mentioned above, the
1618 read(2) will be invoked with an invalid FD and will return
1619 immediately with EBADF. */
1621 /* Make sure we have a dup'd FD. */
1624 DB (DB_JOBS
, ("Duplicate the job FD\n"));
1625 job_rfd
= dup (job_fds
[0]);
1628 /* Reap anything that's currently waiting. */
1629 reap_children (0, 0);
1631 /* If our "free" token has become available, use it. */
1635 /* Set interruptible system calls, and read() for a job token. */
1636 set_child_handler_action_flags (0);
1637 got_token
= read (job_rfd
, &token
, 1);
1638 saved_errno
= errno
;
1640 /* The child handler must be turned off here. */
1641 signal (SIGCHLD
, SIG_DFL
);
1643 set_child_handler_action_flags (SA_RESTART
);
1645 /* If we got one, we're done here. */
1648 DB (DB_JOBS
, (_("Obtained token for child 0x%08lx (%s).\n"),
1649 (unsigned long int) c
, c
->file
->name
));
1653 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1654 go back and reap_children(), and try again. */
1655 errno
= saved_errno
;
1656 if (errno
!= EINTR
&& errno
!= EBADF
)
1657 pfatal_with_name (_("read jobs pipe"));
1659 DB (DB_JOBS
, ("Read returned EBADF.\n"));
1663 /* The job is now primed. Start it running.
1664 (This will notice if there are in fact no commands.) */
1665 (void) start_waiting_job (c
);
1667 if (job_slots
== 1 || not_parallel
)
1668 /* Since there is only one job slot, make things run linearly.
1669 Wait for the child to die, setting the state to `cs_finished'. */
1670 while (file
->command_state
== cs_running
)
1671 reap_children (1, 0);
1676 /* Move CHILD's pointers to the next command for it to execute.
1677 Returns nonzero if there is another command. */
1680 job_next_command (struct child
*child
)
1682 while (child
->command_ptr
== 0 || *child
->command_ptr
== '\0')
1684 /* There are no more lines in the expansion of this line. */
1685 if (child
->command_line
== child
->file
->cmds
->ncommand_lines
)
1687 /* There are no more lines to be expanded. */
1688 child
->command_ptr
= 0;
1692 /* Get the next line to run. */
1693 child
->command_ptr
= child
->command_lines
[child
->command_line
++];
1698 /* Determine if the load average on the system is too high to start a new job.
1699 The real system load average is only recomputed once a second. However, a
1700 very parallel make can easily start tens or even hundreds of jobs in a
1701 second, which brings the system to its knees for a while until that first
1702 batch of jobs clears out.
1704 To avoid this we use a weighted algorithm to try to account for jobs which
1705 have been started since the last second, and guess what the load average
1706 would be now if it were computed.
1708 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1711 ! calculate something load-oid and add to the observed sys.load,
1712 ! so that latter can catch up:
1713 ! - every job started increases jobctr;
1714 ! - every dying job decreases a positive jobctr;
1715 ! - the jobctr value gets zeroed every change of seconds,
1716 ! after its value*weight_b is stored into the 'backlog' value last_sec
1717 ! - weight_a times the sum of jobctr and last_sec gets
1718 ! added to the observed sys.load.
1720 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1721 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1722 ! sub-shelled commands (rm, echo, sed...) for tests.
1723 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1724 ! resulted in significant excession of the load limit, raising it
1725 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1726 ! reach the limit in most test cases.
1728 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1729 ! exceeding the limit for longer-running stuff (compile jobs in
1730 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1731 ! small jobs' effects.
1735 #define LOAD_WEIGHT_A 0.25
1736 #define LOAD_WEIGHT_B 0.25
1739 load_too_high (void)
1741 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
1744 static double last_sec
;
1745 static time_t last_now
;
1749 if (max_load_average
< 0)
1752 /* Find the real system load average. */
1754 if (getloadavg (&load
, 1) != 1)
1756 static int lossage
= -1;
1757 /* Complain only once for the same error. */
1758 if (lossage
== -1 || errno
!= lossage
)
1761 /* An errno value of zero means getloadavg is just unsupported. */
1763 _("cannot enforce load limits on this operating system"));
1765 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1772 /* If we're in a new second zero the counter and correct the backlog
1773 value. Only keep the backlog for one extra second; after that it's 0. */
1777 if (last_now
== now
- 1)
1778 last_sec
= LOAD_WEIGHT_B
* job_counter
;
1786 /* Try to guess what the load would be right now. */
1787 guess
= load
+ (LOAD_WEIGHT_A
* (job_counter
+ last_sec
));
1789 DB (DB_JOBS
, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1790 guess
, load
, max_load_average
));
1792 return guess
>= max_load_average
;
1796 /* Start jobs that are waiting for the load to be lower. */
1799 start_waiting_jobs (void)
1803 if (waiting_jobs
== 0)
1808 /* Check for recently deceased descendants. */
1809 reap_children (0, 0);
1811 /* Take a job off the waiting list. */
1813 waiting_jobs
= job
->next
;
1815 /* Try to start that job. We break out of the loop as soon
1816 as start_waiting_job puts one back on the waiting list. */
1818 while (start_waiting_job (job
) && waiting_jobs
!= 0);
1825 #include <descrip.h>
1828 /* This is called as an AST when a child process dies (it won't get
1829 interrupted by anything except a higher level AST).
1831 int vmsHandleChildTerm(struct child
*child
)
1834 register struct child
*lastc
, *c
;
1837 vms_jobsefnmask
&= ~(1 << (child
->efn
- 32));
1839 lib$
free_ef(&child
->efn
);
1841 (void) sigblock (fatal_signal_mask
);
1843 child_failed
= !(child
->cstatus
& 1 || ((child
->cstatus
& 7) == 0));
1845 /* Search for a child matching the deceased one. */
1847 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1848 for (c
= children
; c
!= 0 && c
!= child
; lastc
= c
, c
= c
->next
);
1853 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
1855 /* The commands failed. Write an error message,
1856 delete non-precious targets, and abort. */
1857 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 0);
1858 c
->file
->update_status
= 1;
1859 delete_child_targets (c
);
1865 /* The commands failed, but we don't care. */
1866 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 1);
1870 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1871 /* If there are more commands to run, try to start them. */
1874 switch (c
->file
->command_state
)
1877 /* Successfully started. */
1881 if (c
->file
->update_status
!= 0) {
1882 /* We failed to start the commands. */
1883 delete_child_targets (c
);
1888 error (NILF
, _("internal error: `%s' command_state"),
1893 #endif /* RECURSIVEJOBS */
1896 /* Set the state flag to say the commands have finished. */
1897 c
->file
->command_state
= cs_finished
;
1898 notice_finished_file (c
->file
);
1900 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1901 /* Remove the child from the chain and free it. */
1905 lastc
->next
= c
->next
;
1907 #endif /* RECURSIVEJOBS */
1909 /* There is now another slot open. */
1910 if (job_slots_used
> 0)
1913 /* If the job failed, and the -k flag was not given, die. */
1914 if (child_failed
&& !keep_going_flag
)
1917 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask
));
1923 Spawn a process executing the command in ARGV and return its pid. */
1925 #define MAXCMDLEN 200
1927 /* local helpers to make ctrl+c and ctrl+y working, see below */
1929 #include <libclidef.h>
1932 static int ctrlMask
= LIB$M_CLI_CTRLY
;
1933 static int oldCtrlMask
;
1934 static int setupYAstTried
= 0;
1935 static int pidToAbort
= 0;
1938 static void reEnableAst(void) {
1939 lib$
enable_ctrl (&oldCtrlMask
,0);
1942 static astHandler (void) {
1944 sys$
forcex (&pidToAbort
, 0, SS$_ABORT
);
1947 kill (getpid(),SIGQUIT
);
1950 static void tryToSetupYAst(void) {
1951 $
DESCRIPTOR(inputDsc
,"SYS$COMMAND");
1954 short int status
, count
;
1961 status
= sys$
assign(&inputDsc
,&chan
,0,0);
1962 if (!(status
&SS$_NORMAL
)) {
1967 status
= sys$
qiow (0, chan
, IO$_SETMODE
|IO$M_CTRLYAST
,&iosb
,0,0,
1968 astHandler
,0,0,0,0,0);
1969 if (status
==SS$_NORMAL
)
1970 status
= iosb
.status
;
1971 if (status
==SS$_ILLIOFUNC
|| status
==SS$_NOPRIV
) {
1973 #ifdef CTRLY_ENABLED_ANYWAY
1975 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
1980 else if (!(status
&SS$_NORMAL
)) {
1986 /* called from AST handler ? */
1987 if (setupYAstTried
>1)
1989 if (atexit(reEnableAst
))
1991 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
1992 status
= lib$
disable_ctrl (&ctrlMask
, &oldCtrlMask
);
1993 if (!(status
&SS$_NORMAL
)) {
1999 child_execute_job (char *argv
, struct child
*child
)
2002 static struct dsc$descriptor_s cmddsc
;
2003 static struct dsc$descriptor_s pnamedsc
;
2004 static struct dsc$descriptor_s ifiledsc
;
2005 static struct dsc$descriptor_s ofiledsc
;
2006 static struct dsc$descriptor_s efiledsc
;
2007 int have_redirection
= 0;
2008 int have_newline
= 0;
2010 int spflags
= CLI$M_NOWAIT
;
2012 char *cmd
= alloca (strlen (argv
) + 512), *p
, *q
;
2013 char ifile
[256], ofile
[256], efile
[256];
2017 /* Parse IO redirection. */
2023 DB (DB_JOBS
, ("child_execute_job (%s)\n", argv
));
2025 while (isspace ((unsigned char)*argv
))
2031 sprintf (procname
, "GMAKE_%05x", getpid () & 0xfffff);
2032 pnamedsc
.dsc$w_length
= strlen(procname
);
2033 pnamedsc
.dsc$a_pointer
= procname
;
2034 pnamedsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
2035 pnamedsc
.dsc$b_class
= DSC$K_CLASS_S
;
2037 /* Handle comments and redirection. */
2038 for (p
= argv
, q
= cmd
; *p
; p
++, q
++)
2050 if (isspace ((unsigned char)*p
))
2052 do { p
++; } while (isspace ((unsigned char)*p
));
2058 p
= vms_redirect (&ifiledsc
, ifile
, p
);
2060 have_redirection
= 1;
2063 have_redirection
= 1;
2067 if (strncmp (p
, ">&1", 3) == 0)
2070 strcpy (efile
, "sys$output");
2071 efiledsc
.dsc$w_length
= strlen(efile
);
2072 efiledsc
.dsc$a_pointer
= efile
;
2073 efiledsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
2074 efiledsc
.dsc$b_class
= DSC$K_CLASS_S
;
2078 p
= vms_redirect (&efiledsc
, efile
, p
);
2083 p
= vms_redirect (&ofiledsc
, ofile
, p
);
2096 if (strncmp (cmd
, "builtin_", 8) == 0)
2098 child
->pid
= 270163;
2102 DB (DB_JOBS
, (_("BUILTIN [%s][%s]\n"), cmd
, cmd
+8));
2108 && ((*(p
+2) == ' ') || (*(p
+2) == '\t')))
2111 while ((*p
== ' ') || (*p
== '\t'))
2113 DB (DB_JOBS
, (_("BUILTIN CD %s\n"), p
));
2119 else if ((*(p
) == 'r')
2121 && ((*(p
+2) == ' ') || (*(p
+2) == '\t')))
2127 while ((*p
== ' ') || (*p
== '\t'))
2131 DB (DB_JOBS
, (_("BUILTIN RM %s\n"), p
));
2152 printf(_("Unknown builtin command '%s'\n"), cmd
);
2158 /* Create a *.com file if either the command is too long for
2159 lib$spawn, or the command contains a newline, or if redirection
2160 is desired. Forcing commands with newlines into DCLs allows to
2161 store search lists on user mode logicals. */
2163 if (strlen (cmd
) > MAXCMDLEN
2164 || (have_redirection
!= 0)
2165 || (have_newline
!= 0))
2170 int alevel
= 0; /* apostrophe level */
2172 if (strlen (cmd
) == 0)
2174 printf (_("Error, empty command\n"));
2179 outfile
= open_tmpfile (&comname
, "sys$scratch:CMDXXXXXX.COM");
2181 pfatal_with_name (_("fopen (temporary file)"));
2185 fprintf (outfile
, "$ assign/user %s sys$input\n", ifile
);
2186 DB (DB_JOBS
, (_("Redirected input from %s\n"), ifile
));
2187 ifiledsc
.dsc$w_length
= 0;
2192 fprintf (outfile
, "$ define sys$error %s\n", efile
);
2193 DB (DB_JOBS
, (_("Redirected error to %s\n"), efile
));
2194 efiledsc
.dsc$w_length
= 0;
2199 fprintf (outfile
, "$ define sys$output %s\n", ofile
);
2200 DB (DB_JOBS
, (_("Redirected output to %s\n"), ofile
));
2201 ofiledsc
.dsc$w_length
= 0;
2205 for (c
= '\n'; c
; c
= *q
++)
2210 /* At a newline, skip any whitespace around a leading $
2211 from the command and issue exactly one $ into the DCL. */
2212 while (isspace ((unsigned char)*p
))
2216 while (isspace ((unsigned char)*p
))
2218 fwrite (p
, 1, q
- p
, outfile
);
2219 fputc ('$', outfile
);
2220 fputc (' ', outfile
);
2221 /* Reset variables. */
2225 /* Nice places for line breaks are after strings, after
2226 comma or space and before slash. */
2228 q
= vms_handle_apos (q
);
2244 /* Enough stuff for a line. */
2245 fwrite (p
, 1, sep
- p
, outfile
);
2249 /* The command continues. */
2250 fputc ('-', outfile
);
2252 fputc ('\n', outfile
);
2256 fwrite (p
, 1, q
- p
, outfile
);
2257 fputc ('\n', outfile
);
2261 sprintf (cmd
, "$ @%s", comname
);
2263 DB (DB_JOBS
, (_("Executing %s instead\n"), cmd
));
2266 cmddsc
.dsc$w_length
= strlen(cmd
);
2267 cmddsc
.dsc$a_pointer
= cmd
;
2268 cmddsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
2269 cmddsc
.dsc$b_class
= DSC$K_CLASS_S
;
2272 while (child
->efn
< 32 || child
->efn
> 63)
2274 status
= lib$
get_ef ((unsigned long *)&child
->efn
);
2279 sys$
clref (child
->efn
);
2281 vms_jobsefnmask
|= (1 << (child
->efn
- 32));
2284 LIB$SPAWN [command-string]
2289 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2290 [,AST-address] [,varying-AST-argument]
2291 [,prompt-string] [,cli] [,table]
2294 #ifndef DONTWAITFORCHILD
2296 * Code to make ctrl+c and ctrl+y working.
2297 * The problem starts with the synchronous case where after lib$spawn is
2298 * called any input will go to the child. But with input re-directed,
2299 * both control characters won't make it to any of the programs, neither
2300 * the spawning nor to the spawned one. Hence the caller needs to spawn
2301 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2302 * has to follow to simulate the wanted synchronous behaviour.
2303 * The next problem is ctrl+y which isn't caught by the crtl and
2304 * therefore isn't converted to SIGQUIT (for a signal handler which is
2305 * already established). The only way to catch ctrl+y, is an AST
2306 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2307 * disabled, otherwise it will handle it. Not to mention the previous
2308 * ctrl+y handling of DCL needs to be re-established before make exits.
2309 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2310 * make it to the signal handler after the child "normally" terminates.
2311 * This isn't enough. It seems reasonable for simple command lines like
2312 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2313 * spawning make. Therefore we need to abort the process in the AST.
2315 * Prior to the spawn it is checked if an AST is already set up for
2316 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2317 * this will work except if make is run in a batch environment, but there
2318 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2319 * is disabled and an exit handler is established to re-enable it.
2320 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2321 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2322 * the already established handler and will bring us back to common code.
2323 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2324 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2325 * which the crtl converts to SIGINT and which is caught by the common
2326 * signal handler. Because signals were blocked before entering this code
2327 * sys$waitfr will always complete and the SIGQUIT will be processed after
2328 * it (after termination of the current block, somewhere in common code).
2329 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2330 * current command completes. Anyway it's better than nothing :-)
2333 if (!setupYAstTried
)
2335 status
= lib$
spawn (&cmddsc
, /* cmd-string */
2336 (ifiledsc
.dsc$w_length
== 0)?0:&ifiledsc
, /* input-file */
2337 (ofiledsc
.dsc$w_length
== 0)?0:&ofiledsc
, /* output-file */
2338 &spflags
, /* flags */
2339 &pnamedsc
, /* proc name */
2340 &child
->pid
, &child
->cstatus
, &child
->efn
,
2345 pidToAbort
= child
->pid
;
2346 status
= sys$
waitfr (child
->efn
);
2348 vmsHandleChildTerm(child
);
2351 status
= lib$
spawn (&cmddsc
,
2352 (ifiledsc
.dsc$w_length
== 0)?0:&ifiledsc
,
2353 (ofiledsc
.dsc$w_length
== 0)?0:&ofiledsc
,
2356 &child
->pid
, &child
->cstatus
, &child
->efn
,
2357 vmsHandleChildTerm
, child
,
2363 printf (_("Error spawning, %d\n") ,status
);
2375 if (comname
&& !ISDB (DB_JOBS
))
2378 return (status
& 1);
2383 /* EMX: Start a child process. This function returns the new pid. */
2384 # if defined __MSDOS__ || defined __EMX__
2386 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2389 /* stdin_fd == 0 means: nothing to do for stdin;
2390 stdout_fd == 1 means: nothing to do for stdout */
2391 int save_stdin
= (stdin_fd
!= 0) ? dup (0) : 0;
2392 int save_stdout
= (stdout_fd
!= 1) ? dup (1): 1;
2394 /* < 0 only if dup() failed */
2396 fatal (NILF
, _("no more file handles: could not duplicate stdin\n"));
2397 if (save_stdout
< 0)
2398 fatal (NILF
, _("no more file handles: could not duplicate stdout\n"));
2400 /* Close unnecessary file handles for the child. */
2401 if (save_stdin
!= 0)
2402 CLOSE_ON_EXEC (save_stdin
);
2403 if (save_stdout
!= 1)
2404 CLOSE_ON_EXEC (save_stdout
);
2406 /* Connect the pipes to the child process. */
2408 (void) dup2 (stdin_fd
, 0);
2410 (void) dup2 (stdout_fd
, 1);
2412 /* stdin_fd and stdout_fd must be closed on exit because we are
2413 still in the parent process */
2415 CLOSE_ON_EXEC (stdin_fd
);
2417 CLOSE_ON_EXEC (stdout_fd
);
2419 /* Run the command. */
2420 pid
= exec_command (argv
, envp
);
2422 /* Restore stdout/stdin of the parent and close temporary FDs. */
2425 if (dup2 (save_stdin
, 0) != 0)
2426 fatal (NILF
, _("Could not restore stdin\n"));
2433 if (dup2 (save_stdout
, 1) != 1)
2434 fatal (NILF
, _("Could not restore stdout\n"));
2436 close (save_stdout
);
2442 #elif !defined (_AMIGA) && !defined (__MSDOS__)
2445 Replace the current process with one executing the command in ARGV.
2446 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2447 the environment of the new program. This function does not return. */
2449 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2452 (void) dup2 (stdin_fd
, 0);
2454 (void) dup2 (stdout_fd
, 1);
2456 (void) close (stdin_fd
);
2458 (void) close (stdout_fd
);
2460 /* Run the command. */
2461 exec_command (argv
, envp
);
2463 #endif /* !AMIGA && !__MSDOS__ */
2465 #endif /* !WINDOWS32 */
2468 /* Replace the current process with one running the command in ARGV,
2469 with environment ENVP. This function does not return. */
2471 /* EMX: This function returns the pid of the child process. */
2477 exec_command (char **argv
, char **envp
)
2480 /* to work around a problem with signals and execve: ignore them */
2482 signal (SIGCHLD
,SIG_IGN
);
2484 /* Run the program. */
2485 execve (argv
[0], argv
, envp
);
2486 perror_with_name ("execve: ", argv
[0]);
2487 _exit (EXIT_FAILURE
);
2493 int exit_code
= EXIT_FAILURE
;
2495 /* make sure CreateProcess() has Path it needs */
2496 sync_Path_environment();
2498 /* launch command */
2499 hPID
= process_easy(argv
, envp
);
2501 /* make sure launch ok */
2502 if (hPID
== INVALID_HANDLE_VALUE
)
2506 _("process_easy() failed failed to launch process (e=%d)\n"),
2507 process_last_err(hPID
));
2508 for (i
= 0; argv
[i
]; i
++)
2509 fprintf(stderr
, "%s ", argv
[i
]);
2510 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
2514 /* wait and reap last child */
2515 hWaitPID
= process_wait_for_any();
2518 /* was an error found on this process? */
2519 err
= process_last_err(hWaitPID
);
2522 exit_code
= process_exit_code(hWaitPID
);
2525 fprintf(stderr
, "make (e=%d, rc=%d): %s",
2526 err
, exit_code
, map_windows32_error_to_string(err
));
2528 /* cleanup process */
2529 process_cleanup(hWaitPID
);
2531 /* expect to find only last pid, warn about other pids reaped */
2532 if (hWaitPID
== hPID
)
2536 _("make reaped child pid %d, still waiting for pid %d\n"),
2540 /* return child's exit code as our exit code */
2543 #else /* !WINDOWS32 */
2549 /* Be the user, permanently. */
2554 /* Run the program. */
2555 pid
= spawnvpe (P_NOWAIT
, argv
[0], argv
, envp
);
2560 /* the file might have a strange shell extension */
2561 if (errno
== ENOENT
)
2566 /* Run the program. */
2568 execvp (argv
[0], argv
);
2570 # endif /* !__EMX__ */
2575 error (NILF
, _("%s: Command not found"), argv
[0]);
2579 /* The file is not executable. Try it as a shell script. */
2580 extern char *getenv ();
2587 /* Do not use $SHELL from the environment */
2588 struct variable
*p
= lookup_variable ("SHELL", 5);
2594 shell
= getenv ("SHELL");
2597 shell
= default_shell
;
2600 while (argv
[argc
] != 0)
2608 new_argv
= (char **) alloca ((1 + argc
+ 1) * sizeof (char *));
2609 new_argv
[0] = shell
;
2620 new_argv
[i
] = argv
[0];
2623 new_argv
[i
+ argc
] = argv
[argc
];
2628 pid
= spawnvpe (P_NOWAIT
, shell
, new_argv
, envp
);
2632 execvp (shell
, new_argv
);
2634 if (errno
== ENOENT
)
2635 error (NILF
, _("%s: Shell program not found"), shell
);
2637 perror_with_name ("execvp: ", shell
);
2643 /* this nasty error was driving me nuts :-( */
2644 error (NILF
, _("spawnvpe: environment space might be exhausted"));
2649 perror_with_name ("execvp: ", argv
[0]);
2658 #endif /* !WINDOWS32 */
2661 #else /* On Amiga */
2662 void exec_command (char **argv
,char **envp
)
2664 MyExecute (argv
,envp
,NULL
);
2667 void clean_tmp (void)
2669 DeleteFile (amiga_bname
);
2672 #endif /* On Amiga */
2675 /* Figure out the argument list necessary to run LINE as a command. Try to
2676 avoid using a shell. This routine handles only ' quoting, and " quoting
2677 when no backslash, $ or ` characters are seen in the quotes. Starting
2678 quotes may be escaped with a backslash. If any of the characters in
2679 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2680 is the first word of a line, the shell is used.
2682 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2683 If *RESTP is NULL, newlines will be ignored.
2685 SHELL is the shell to use, or nil to use the default shell.
2686 IFS is the value of $IFS, or nil (meaning the default). */
2689 construct_command_argv_internal (char *line
, char **restp
, char *shell
,
2690 char *ifs
, char **batch_filename_ptr
)
2693 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2694 We call `system' for anything that requires ``slow'' processing,
2695 because DOS shells are too dumb. When $SHELL points to a real
2696 (unix-style) shell, `system' just calls it to do everything. When
2697 $SHELL points to a DOS shell, `system' does most of the work
2698 internally, calling the shell only for its internal commands.
2699 However, it looks on the $PATH first, so you can e.g. have an
2700 external command named `mkdir'.
2702 Since we call `system', certain characters and commands below are
2703 actually not specific to COMMAND.COM, but to the DJGPP implementation
2704 of `system'. In particular:
2706 The shell wildcard characters are in DOS_CHARS because they will
2707 not be expanded if we call the child via `spawnXX'.
2709 The `;' is in DOS_CHARS, because our `system' knows how to run
2710 multiple commands on a single line.
2712 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2713 won't have to tell one from another and have one more set of
2714 commands and special characters. */
2715 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2716 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2717 "copy", "ctty", "date", "del", "dir", "echo",
2718 "erase", "exit", "for", "goto", "if", "md",
2719 "mkdir", "path", "pause", "prompt", "rd",
2720 "rmdir", "rem", "ren", "rename", "set",
2721 "shift", "time", "type", "ver", "verify",
2724 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2725 static char *sh_cmds_sh
[] = { "cd", "echo", "eval", "exec", "exit", "login",
2726 "logout", "set", "umask", "wait", "while",
2727 "for", "case", "if", ":", ".", "break",
2728 "continue", "export", "read", "readonly",
2729 "shift", "times", "trap", "switch", "unset",
2734 #elif defined (__EMX__)
2735 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2736 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2737 "copy", "ctty", "date", "del", "dir", "echo",
2738 "erase", "exit", "for", "goto", "if", "md",
2739 "mkdir", "path", "pause", "prompt", "rd",
2740 "rmdir", "rem", "ren", "rename", "set",
2741 "shift", "time", "type", "ver", "verify",
2744 static char sh_chars_os2
[] = "*?[];|<>%^()\"'&";
2745 static char *sh_cmds_os2
[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2746 "date", "del", "detach", "dir", "echo",
2747 "endlocal", "erase", "exit", "for", "goto", "if",
2748 "keys", "md", "mkdir", "move", "path", "pause",
2749 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2750 "set", "setlocal", "shift", "start", "time",
2751 "type", "ver", "verify", "vol", ":", 0 };
2753 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^~'";
2754 static char *sh_cmds_sh
[] = { "echo", "cd", "eval", "exec", "exit", "login",
2755 "logout", "set", "umask", "wait", "while",
2756 "for", "case", "if", ":", ".", "break",
2757 "continue", "export", "read", "readonly",
2758 "shift", "times", "trap", "switch", "unset",
2763 #elif defined (_AMIGA)
2764 static char sh_chars
[] = "#;\"|<>()?*$`";
2765 static char *sh_cmds
[] = { "cd", "eval", "if", "delete", "echo", "copy",
2766 "rename", "set", "setenv", "date", "makedir",
2767 "skip", "else", "endif", "path", "prompt",
2768 "unset", "unsetenv", "version",
2770 #elif defined (WINDOWS32)
2771 static char sh_chars_dos
[] = "\"|&<>";
2772 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2773 "copy", "ctty", "date", "del", "dir", "echo",
2774 "erase", "exit", "for", "goto", "if", "if", "md",
2775 "mkdir", "path", "pause", "prompt", "rd", "rem",
2776 "ren", "rename", "rmdir", "set", "shift", "time",
2777 "type", "ver", "verify", "vol", ":", 0 };
2778 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2779 static char *sh_cmds_sh
[] = { "cd", "eval", "exec", "exit", "login",
2780 "logout", "set", "umask", "wait", "while", "for",
2781 "case", "if", ":", ".", "break", "continue",
2782 "export", "read", "readonly", "shift", "times",
2783 "trap", "switch", "test",
2784 #ifdef BATCH_MODE_ONLY_SHELL
2790 #elif defined(__riscos__)
2791 static char sh_chars
[] = "";
2792 static char *sh_cmds
[] = { 0 };
2793 #else /* must be UNIX-ish */
2794 static char sh_chars
[] = "#;\"*?[]&|<>(){}$`^~!";
2795 static char *sh_cmds
[] = { ".", ":", "break", "case", "cd", "continue",
2796 "eval", "exec", "exit", "export", "for", "if",
2797 "login", "logout", "read", "readonly", "set",
2798 "shift", "switch", "test", "times", "trap",
2799 "umask", "wait", "while", 0 };
2805 int instring
, word_has_equals
, seen_nonequals
, last_argument_was_empty
;
2806 char **new_argv
= 0;
2810 if (no_default_sh_exe
) {
2811 sh_cmds
= sh_cmds_dos
;
2812 sh_chars
= sh_chars_dos
;
2814 sh_cmds
= sh_cmds_sh
;
2815 sh_chars
= sh_chars_sh
;
2817 #endif /* WINDOWS32 */
2822 /* Make sure not to bother processing an empty line. */
2823 while (isblank ((unsigned char)*line
))
2828 /* See if it is safe to parse commands internally. */
2830 shell
= default_shell
;
2832 else if (strcmp (shell
, default_shell
))
2834 char *s1
= _fullpath(NULL
, shell
, 0);
2835 char *s2
= _fullpath(NULL
, default_shell
, 0);
2837 slow_flag
= strcmp((s1
? s1
: ""), (s2
? s2
: ""));
2846 #else /* not WINDOWS32 */
2847 #if defined (__MSDOS__) || defined (__EMX__)
2848 else if (stricmp (shell
, default_shell
))
2850 extern int _is_unixy_shell (const char *_path
);
2852 DB (DB_BASIC
, (_("$SHELL changed (was `%s', now `%s')\n"),
2853 default_shell
, shell
));
2854 unixy_shell
= _is_unixy_shell (shell
);
2855 /* we must allocate a copy of shell: construct_command_argv() will free
2856 * shell after this function returns. */
2857 default_shell
= xstrdup (shell
);
2861 sh_chars
= sh_chars_sh
;
2862 sh_cmds
= sh_cmds_sh
;
2866 sh_chars
= sh_chars_dos
;
2867 sh_cmds
= sh_cmds_dos
;
2869 if (_osmode
== OS2_MODE
)
2871 sh_chars
= sh_chars_os2
;
2872 sh_cmds
= sh_cmds_os2
;
2876 #else /* !__MSDOS__ */
2877 else if (strcmp (shell
, default_shell
))
2879 #endif /* !__MSDOS__ && !__EMX__ */
2880 #endif /* not WINDOWS32 */
2883 for (ap
= ifs
; *ap
!= '\0'; ++ap
)
2884 if (*ap
!= ' ' && *ap
!= '\t' && *ap
!= '\n')
2887 i
= strlen (line
) + 1;
2889 /* More than 1 arg per character is impossible. */
2890 new_argv
= (char **) xmalloc (i
* sizeof (char *));
2892 /* All the args can fit in a buffer as big as LINE is. */
2893 ap
= new_argv
[0] = (char *) xmalloc (i
);
2896 /* I is how many complete arguments have been found. */
2898 instring
= word_has_equals
= seen_nonequals
= last_argument_was_empty
= 0;
2899 for (p
= line
; *p
!= '\0'; ++p
)
2907 /* Inside a string, just copy any char except a closing quote
2908 or a backslash-newline combination. */
2912 if (ap
== new_argv
[0] || *(ap
-1) == '\0')
2913 last_argument_was_empty
= 1;
2915 else if (*p
== '\\' && p
[1] == '\n')
2916 goto swallow_escaped_newline
;
2917 else if (*p
== '\n' && restp
!= NULL
)
2919 /* End of the command line. */
2923 /* Backslash, $, and ` are special inside double quotes.
2924 If we see any of those, punt.
2925 But on MSDOS, if we use COMMAND.COM, double and single
2926 quotes have the same effect. */
2927 else if (instring
== '"' && strchr ("\\$`", *p
) != 0 && unixy_shell
)
2932 else if (strchr (sh_chars
, *p
) != 0)
2933 /* Not inside a string, but it's a special char. */
2936 else if (*p
== '.' && p
[1] == '.' && p
[2] == '.' && p
[3] != '.')
2937 /* `...' is a wildcard in DJGPP. */
2941 /* Not a special char. */
2945 /* Equals is a special character in leading words before the
2946 first word with no equals sign in it. This is not the case
2947 with sh -k, but we never get here when using nonstandard
2949 if (! seen_nonequals
&& unixy_shell
)
2951 word_has_equals
= 1;
2956 /* Backslash-newline combinations are eaten. */
2959 swallow_escaped_newline
:
2961 /* Eat the backslash, the newline, and following whitespace,
2962 replacing it all with a single space. */
2965 /* If there is a tab after a backslash-newline,
2966 remove it from the source line which will be echoed,
2967 since it was most likely used to line
2968 up the continued line with the previous one. */
2970 /* Note these overlap and strcpy() is undefined for
2971 overlapping objects in ANSI C. The strlen() _IS_ right,
2972 since we need to copy the nul byte too. */
2973 bcopy (p
+ 1, p
, strlen (p
));
2979 if (ap
!= new_argv
[i
])
2980 /* Treat this as a space, ending the arg.
2981 But if it's at the beginning of the arg, it should
2982 just get eaten, rather than becoming an empty arg. */
2985 p
= next_token (p
) - 1;
2988 else if (p
[1] != '\0')
2990 #ifdef HAVE_DOS_PATHS
2991 /* Only remove backslashes before characters special
2992 to Unixy shells. All other backslashes are copied
2993 verbatim, since they are probably DOS-style
2994 directory separators. This still leaves a small
2995 window for problems, but at least it should work
2996 for the vast majority of naive users. */
2999 /* A dot is only special as part of the "..."
3001 if (strneq (p
+ 1, ".\\.\\.", 5))
3009 if (p
[1] != '\\' && p
[1] != '\''
3010 && !isspace ((unsigned char)p
[1])
3011 && (strchr (sh_chars_sh
, p
[1]) == 0))
3012 /* back up one notch, to copy the backslash */
3014 #endif /* HAVE_DOS_PATHS */
3016 /* Copy and skip the following char. */
3029 /* End of the command line. */
3034 /* Newlines are not special. */
3041 /* We have the end of an argument.
3042 Terminate the text of the argument. */
3045 last_argument_was_empty
= 0;
3047 /* Update SEEN_NONEQUALS, which tells us if every word
3048 heretofore has contained an `='. */
3049 seen_nonequals
|= ! word_has_equals
;
3050 if (word_has_equals
&& ! seen_nonequals
)
3051 /* An `=' in a word before the first
3052 word without one is magical. */
3054 word_has_equals
= 0; /* Prepare for the next word. */
3056 /* If this argument is the command name,
3057 see if it is a built-in shell command.
3058 If so, have the shell handle it. */
3062 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
3064 if (streq (sh_cmds
[j
], new_argv
[0]))
3067 /* Non-Unix shells are case insensitive. */
3069 && strcasecmp (sh_cmds
[j
], new_argv
[0]) == 0)
3075 /* Ignore multiple whitespace chars. */
3077 /* Next iteration should examine the first nonwhite char. */
3089 /* Let the shell deal with an unterminated quote. */
3092 /* Terminate the last argument and the argument list. */
3095 if (new_argv
[i
][0] != '\0' || last_argument_was_empty
)
3102 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
3103 if (streq (sh_cmds
[j
], new_argv
[0]))
3107 if (new_argv
[0] == 0)
3108 /* Line was empty. */
3114 /* We must use the shell. */
3118 /* Free the old argument list we were working on. */
3120 free ((void *)new_argv
);
3124 execute_by_shell
= 1; /* actually, call `system' if shell isn't unixy */
3133 buffer
= (char *)xmalloc (strlen (line
)+1);
3136 for (dptr
=buffer
; *ptr
; )
3138 if (*ptr
== '\\' && ptr
[1] == '\n')
3140 else if (*ptr
== '@') /* Kludge: multiline commands */
3150 new_argv
= (char **) xmalloc (2 * sizeof (char *));
3151 new_argv
[0] = buffer
;
3154 #else /* Not Amiga */
3157 * Not eating this whitespace caused things like
3161 * which gave the shell fits. I think we have to eat
3162 * whitespace here, but this code should be considered
3163 * suspicious if things start failing....
3166 /* Make sure not to bother processing an empty line. */
3167 while (isspace ((unsigned char)*line
))
3171 #endif /* WINDOWS32 */
3173 /* SHELL may be a multi-word command. Construct a command line
3174 "SHELL -c LINE", with all special chars in LINE escaped.
3175 Then recurse, expanding this command line to get the final
3178 unsigned int shell_len
= strlen (shell
);
3180 static char minus_c
[] = " -c ";
3182 static char minus_c
[] = "";
3184 unsigned int line_len
= strlen (line
);
3186 char *new_line
= (char *) alloca (shell_len
+ (sizeof (minus_c
) - 1)
3187 + (line_len
* 2) + 1);
3188 char *command_ptr
= NULL
; /* used for batch_mode_shell mode */
3190 # ifdef __EMX__ /* is this necessary? */
3192 minus_c
[1] = '/'; /* " /c " */
3196 bcopy (shell
, ap
, shell_len
);
3198 bcopy (minus_c
, ap
, sizeof (minus_c
) - 1);
3199 ap
+= sizeof (minus_c
) - 1;
3201 for (p
= line
; *p
!= '\0'; ++p
)
3203 if (restp
!= NULL
&& *p
== '\n')
3208 else if (*p
== '\\' && p
[1] == '\n')
3210 /* Eat the backslash, the newline, and following whitespace,
3211 replacing it all with a single space (which is escaped
3215 /* If there is a tab after a backslash-newline,
3216 remove it from the source line which will be echoed,
3217 since it was most likely used to line
3218 up the continued line with the previous one. */
3220 bcopy (p
+ 1, p
, strlen (p
));
3224 if (unixy_shell
&& !batch_mode_shell
)
3230 /* DOS shells don't know about backslash-escaping. */
3231 if (unixy_shell
&& !batch_mode_shell
&&
3232 (*p
== '\\' || *p
== '\'' || *p
== '"'
3233 || isspace ((unsigned char)*p
)
3234 || strchr (sh_chars
, *p
) != 0))
3237 else if (unixy_shell
&& strneq (p
, "...", 3))
3239 /* The case of `...' wildcard again. */
3240 strcpy (ap
, "\\.\\.\\");
3247 if (ap
== new_line
+ shell_len
+ sizeof (minus_c
) - 1)
3248 /* Line was empty. */
3253 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3254 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3255 cases, run commands via a script file. */
3256 if ((no_default_sh_exe
|| batch_mode_shell
) && batch_filename_ptr
) {
3258 int id
= GetCurrentProcessId();
3262 /* create a file name */
3263 sprintf(fbuf
, "make%d", id
);
3264 fname
= tempnam(".", fbuf
);
3266 /* create batch file name */
3267 *batch_filename_ptr
= xmalloc(strlen(fname
) + 5);
3268 strcpy(*batch_filename_ptr
, fname
);
3270 /* make sure path name is in DOS backslash format */
3272 fname
= *batch_filename_ptr
;
3273 for (i
= 0; fname
[i
] != '\0'; ++i
)
3274 if (fname
[i
] == '/')
3276 strcat(*batch_filename_ptr
, ".bat");
3278 strcat(*batch_filename_ptr
, ".sh");
3281 DB (DB_JOBS
, (_("Creating temporary batch file %s\n"),
3282 *batch_filename_ptr
));
3284 /* create batch file to execute command */
3285 batch
= fopen (*batch_filename_ptr
, "w");
3287 fputs ("@echo off\n", batch
);
3288 fputs (command_ptr
, batch
);
3289 fputc ('\n', batch
);
3293 new_argv
= (char **) xmalloc(3 * sizeof (char *));
3295 new_argv
[0] = xstrdup (shell
);
3296 new_argv
[1] = *batch_filename_ptr
; /* only argv[0] gets freed later */
3298 new_argv
[0] = xstrdup (*batch_filename_ptr
);
3303 #endif /* WINDOWS32 */
3305 new_argv
= construct_command_argv_internal (new_line
, (char **) NULL
,
3306 (char *) 0, (char *) 0,
3309 else if (!unixy_shell
)
3311 /* new_line is local, must not be freed therefore
3312 We use line here instead of new_line because we run the shell
3314 size_t line_len
= strlen (line
);
3317 memcpy (new_line
, line
, line_len
+ 1);
3318 /* replace all backslash-newline combination and also following tabs */
3321 if (q
[0] == '\\' && q
[1] == '\n')
3323 q
+= 2; /* remove '\\' and '\n' */
3325 q
++; /* remove 1st tab in the next line */
3332 # ifndef NO_CMD_DEFAULT
3333 if (strnicmp (new_line
, "echo", 4) == 0
3334 && (new_line
[4] == ' ' || new_line
[4] == '\t'))
3336 /* the builtin echo command: handle it separately */
3337 size_t echo_len
= line_len
- 5;
3338 char *echo_line
= new_line
+ 5;
3340 /* special case: echo 'x="y"'
3341 cmd works this way: a string is printed as is, i.e., no quotes
3342 are removed. But autoconf uses a command like echo 'x="y"' to
3343 determine whether make works. autoconf expects the output x="y"
3344 so we will do exactly that.
3345 Note: if we do not allow cmd to be the default shell
3346 we do not need this kind of voodoo */
3347 if (echo_line
[0] == '\''
3348 && echo_line
[echo_len
- 1] == '\''
3349 && strncmp (echo_line
+ 1, "ac_maketemp=",
3350 strlen ("ac_maketemp=")) == 0)
3352 /* remove the enclosing quotes */
3353 memmove (echo_line
, echo_line
+ 1, echo_len
- 2);
3354 echo_line
[echo_len
- 2] = '\0';
3360 /* Let the shell decide what to do. Put the command line into the
3361 2nd command line argument and hope for the best ;-) */
3362 size_t sh_len
= strlen (shell
);
3364 /* exactly 3 arguments + NULL */
3365 new_argv
= (char **) xmalloc (4 * sizeof (char *));
3366 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3367 the trailing '\0' */
3368 new_argv
[0] = (char *) malloc (sh_len
+ line_len
+ 5);
3369 memcpy (new_argv
[0], shell
, sh_len
+ 1);
3370 new_argv
[1] = new_argv
[0] + sh_len
+ 1;
3371 memcpy (new_argv
[1], "/c", 3);
3372 new_argv
[2] = new_argv
[1] + 3;
3373 memcpy (new_argv
[2], new_line
, line_len
+ 1);
3377 #elif defined(__MSDOS__)
3380 /* With MSDOS shells, we must construct the command line here
3381 instead of recursively calling ourselves, because we
3382 cannot backslash-escape the special characters (see above). */
3383 new_argv
= (char **) xmalloc (sizeof (char *));
3384 line_len
= strlen (new_line
) - shell_len
- sizeof (minus_c
) + 1;
3385 new_argv
[0] = xmalloc (line_len
+ 1);
3386 strncpy (new_argv
[0],
3387 new_line
+ shell_len
+ sizeof (minus_c
) - 1, line_len
);
3388 new_argv
[0][line_len
] = '\0';
3392 fatal (NILF
, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3393 __FILE__
, __LINE__
);
3396 #endif /* ! AMIGA */
3402 /* Figure out the argument list necessary to run LINE as a command. Try to
3403 avoid using a shell. This routine handles only ' quoting, and " quoting
3404 when no backslash, $ or ` characters are seen in the quotes. Starting
3405 quotes may be escaped with a backslash. If any of the characters in
3406 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3407 is the first word of a line, the shell is used.
3409 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3410 If *RESTP is NULL, newlines will be ignored.
3412 FILE is the target whose commands these are. It is used for
3413 variable expansion for $(SHELL) and $(IFS). */
3416 construct_command_argv (char *line
, char **restp
, struct file
*file
,
3417 char **batch_filename_ptr
)
3431 && (isspace ((unsigned char)*cptr
)))
3436 && (!isspace((unsigned char)*cptr
)))
3441 argv
= (char **)malloc (argc
* sizeof (char *));
3450 && (isspace ((unsigned char)*cptr
)))
3454 DB (DB_JOBS
, ("argv[%d] = [%s]\n", argc
, cptr
));
3455 argv
[argc
++] = cptr
;
3457 && (!isspace((unsigned char)*cptr
)))
3464 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3465 int save
= warn_undefined_variables_flag
;
3466 warn_undefined_variables_flag
= 0;
3468 shell
= allocated_variable_expand_for_file ("$(SHELL)", file
);
3471 * Convert to forward slashes so that construct_command_argv_internal()
3475 char *p
= w32ify (shell
, 0);
3481 static const char *unixroot
= NULL
;
3482 static const char *last_shell
= "";
3483 static int init
= 0;
3486 unixroot
= getenv ("UNIXROOT");
3487 /* unixroot must be NULL or not empty */
3488 if (unixroot
&& unixroot
[0] == '\0') unixroot
= NULL
;
3492 /* if we have an unixroot drive and if shell is not default_shell
3493 (which means it's either cmd.exe or the test has already been
3494 performed) and if shell is an absolute path without drive letter,
3495 try whether it exists e.g.: if "/bin/sh" does not exist use
3496 "$UNIXROOT/bin/sh" instead. */
3497 if (unixroot
&& shell
&& strcmp (shell
, last_shell
) != 0
3498 && (shell
[0] == '/' || shell
[0] == '\\'))
3500 /* trying a new shell, check whether it exists */
3501 size_t size
= strlen (shell
);
3502 char *buf
= xmalloc (size
+ 7);
3503 memcpy (buf
, shell
, size
);
3504 memcpy (buf
+ size
, ".exe", 5); /* including the trailing '\0' */
3505 if (access (shell
, F_OK
) != 0 && access (buf
, F_OK
) != 0)
3507 /* try the same for the unixroot drive */
3508 memmove (buf
+ 2, buf
, size
+ 5);
3509 buf
[0] = unixroot
[0];
3510 buf
[1] = unixroot
[1];
3511 if (access (buf
, F_OK
) == 0)
3512 /* we have found a shell! */
3522 #endif /* __EMX__ */
3524 ifs
= allocated_variable_expand_for_file ("$(IFS)", file
);
3526 warn_undefined_variables_flag
= save
;
3529 argv
= construct_command_argv_internal (line
, restp
, shell
, ifs
, batch_filename_ptr
);
3537 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3539 dup2 (int old
, int new)
3554 #endif /* !HAPE_DUP2 && !_AMIGA */