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 <process.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). */
225 /* Number of jobs started in the current second. */
227 unsigned long job_counter
= 0;
232 * The macro which references this function is defined in make.h.
235 w32_kill(int pid
, int sig
)
237 return ((process_kill(pid
, sig
) == TRUE
) ? 0 : -1);
239 #endif /* WINDOWS32 */
242 /* returns whether path is assumed to be a unix like shell. */
244 _is_unixy_shell (const char *path
)
246 /* list of non unix shells */
247 const char *known_os2shells
[] = {
259 /* find the rightmost '/' or '\\' */
260 const char *name
= strrchr (path
, '/');
261 const char *p
= strrchr (path
, '\\');
264 if (name
&& p
) /* take the max */
265 name
= (name
> p
) ? name
: p
;
266 else if (p
) /* name must be 0 */
268 else if (!name
) /* name and p must be 0 */
271 if (*name
== '/' || *name
== '\\') name
++;
274 while (known_os2shells
[i
] != NULL
) {
275 if (stricmp (name
, known_os2shells
[i
]) == 0) /* strcasecmp() */
276 return 0; /* not a unix shell */
280 /* in doubt assume a unix like shell */
286 /* Write an error message describing the exit status given in
287 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
288 Append "(ignored)" if IGNORED is nonzero. */
291 child_error (char *target_name
, int exit_code
, int exit_sig
, int coredump
,
294 if (ignored
&& silent_flag
)
298 if (!(exit_code
& 1))
300 (ignored
? _("*** [%s] Error 0x%x (ignored)")
301 : _("*** [%s] Error 0x%x")),
302 target_name
, exit_code
);
305 error (NILF
, ignored
? _("[%s] Error %d (ignored)") :
306 _("*** [%s] Error %d"),
307 target_name
, exit_code
);
309 error (NILF
, "*** [%s] %s%s",
310 target_name
, strsignal (exit_sig
),
311 coredump
? _(" (core dumped)") : "");
316 /* Wait for nchildren children to terminate */
318 vmsWaitForChildren(int *status
)
322 if (!vms_jobsefnmask
)
328 *status
= sys$
wflor (32, vms_jobsefnmask
);
333 /* Set up IO redirection. */
336 vms_redirect (struct dsc$descriptor_s
*desc
, char *fname
, char *ibuf
)
339 extern char *vmsify ();
342 while (isspace ((unsigned char)*ibuf
))
345 while (*ibuf
&& !isspace ((unsigned char)*ibuf
))
348 if (strcmp (fptr
, "/dev/null") != 0)
350 strcpy (fname
, vmsify (fptr
, 0));
351 if (strchr (fname
, '.') == 0)
354 desc
->dsc$w_length
= strlen(fname
);
355 desc
->dsc$a_pointer
= fname
;
356 desc
->dsc$b_dtype
= DSC$K_DTYPE_T
;
357 desc
->dsc$b_class
= DSC$K_CLASS_S
;
360 printf (_("Warning: Empty redirection\n"));
365 /* found apostrophe at (p-1)
366 inc p until after closing apostrophe.
370 vms_handle_apos (char *p
)
375 #define SEPCHARS ",/()= "
395 fprintf (stderr
, _("Syntax error, still inside '\"'\n"));
402 if (strchr (SEPCHARS
, *p
))
423 /* Handle a dead child. This handler may or may not ever be installed.
425 If we're using the jobserver feature, we need it. First, installing it
426 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
427 read FD to ensure we don't enter another blocking read without reaping all
428 the dead children. In this case we don't need the dead_children count.
430 If we don't have either waitpid or wait3, then make is unreliable, but we
431 use the dead_children count to reap children as best we can. */
433 static unsigned int dead_children
= 0;
435 #ifndef __EMX__ /* Don't use SIGCHLD handler on OS/2. */
437 child_handler (int sig
)
447 DB (DB_JOBS
, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children
));
449 #endif /* !__EMX__ */
451 extern int shell_function_pid
, shell_function_completed
;
453 /* Reap all dead children, storing the returned status and the new command
454 state (`cs_finished') in the `file' member of the `struct child' for the
455 dead child, and removing the child from the chain. In addition, if BLOCK
456 nonzero, we block in this function until we've reaped at least one
457 complete child, waiting for it to die if necessary. If ERR is nonzero,
458 print an error message first. */
461 reap_children (int block
, int err
)
464 /* Initially, assume we have some. */
468 # define REAP_MORE reap_more
470 # define REAP_MORE dead_children
475 We have at least one child outstanding OR a shell function in progress,
477 We're blocking for a complete child OR there are more children to reap
479 we'll keep reaping children. */
481 while ((children
!= 0 || shell_function_pid
!= 0)
482 && (block
|| REAP_MORE
))
486 int exit_code
, exit_sig
, coredump
;
487 register struct child
*lastc
, *c
;
489 int any_remote
, any_local
;
493 /* We might block for a while, so let the user know why. */
495 error (NILF
, _("*** Waiting for unfinished jobs...."));
498 /* We have one less dead child to reap. As noted in
499 child_handler() above, this count is completely unimportant for
500 all modern, POSIX-y systems that support wait3() or waitpid().
501 The rest of this comment below applies only to early, broken
502 pre-POSIX systems. We keep the count only because... it's there...
504 The test and decrement are not atomic; if it is compiled into:
505 register = dead_children - 1;
506 dead_children = register;
507 a SIGCHLD could come between the two instructions.
508 child_handler increments dead_children.
509 The second instruction here would lose that increment. But the
510 only effect of dead_children being wrong is that we might wait
511 longer than necessary to reap a child, and lose some parallelism;
512 and we might print the "Waiting for unfinished jobs" message above
513 when not necessary. */
515 if (dead_children
> 0)
519 any_local
= shell_function_pid
!= 0;
520 for (c
= children
; c
!= 0; c
= c
->next
)
522 any_remote
|= c
->remote
;
523 any_local
|= ! c
->remote
;
524 DB (DB_JOBS
, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
525 (unsigned long int) c
, c
->file
->name
,
526 (long) c
->pid
, c
->remote
? _(" (remote)") : ""));
532 /* First, check for remote children. */
534 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 0);
539 /* We got a remote child. */
543 /* A remote status command failed miserably. Punt. */
545 pfatal_with_name ("remote_status");
549 /* No remote children. Check for local children. */
550 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
554 vmsWaitForChildren (&status
);
559 pid
= WAIT_NOHANG (&status
);
562 pid
= wait (&status
);
570 /* The wait*() failed miserably. Punt. */
571 pfatal_with_name ("wait");
575 /* We got a child exit; chop the status word up. */
576 exit_code
= WEXITSTATUS (status
);
577 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
578 coredump
= WCOREDUMP (status
);
580 /* If we have started jobs in this second, remove one. */
585 /* the SIGCHLD handler must not be used on OS/2 because, unlike
586 on UNIX systems, it had to call wait() itself. Therefore
587 job_rfd has to be closed here. */
598 /* No local children are dead. */
601 if (!block
|| !any_remote
)
604 /* Now try a blocking wait for a remote child. */
605 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 1);
607 goto remote_status_lose
;
609 /* No remote children either. Finally give up. */
612 /* We got a remote child. */
615 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
618 /* Life is very different on MSDOS. */
621 exit_code
= WEXITSTATUS (status
);
622 if (exit_code
== 0xff)
624 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
626 #endif /* __MSDOS__ */
630 status
= amiga_status
;
631 exit_code
= amiga_status
;
640 /* wait for anything to finish */
641 if (hPID
= process_wait_for_any()) {
643 /* was an error found on this process? */
644 err
= process_last_err(hPID
);
647 exit_code
= process_exit_code(hPID
);
650 fprintf(stderr
, "make (e=%d): %s",
651 exit_code
, map_windows32_error_to_string(exit_code
));
654 exit_sig
= process_signal(hPID
);
656 /* cleanup process */
657 process_cleanup(hPID
);
663 #endif /* WINDOWS32 */
666 /* Check if this is the child of the `shell' function. */
667 if (!remote
&& pid
== shell_function_pid
)
669 /* It is. Leave an indicator for the `shell' function. */
670 if (exit_sig
== 0 && exit_code
== 127)
671 shell_function_completed
= -1;
673 shell_function_completed
= 1;
677 child_failed
= exit_sig
!= 0 || exit_code
!= 0;
679 /* Search for a child matching the deceased one. */
681 for (c
= children
; c
!= 0; lastc
= c
, c
= c
->next
)
682 if (c
->remote
== remote
&& c
->pid
== pid
)
686 /* An unknown child died.
687 Ignore it; it was inherited from our invoker. */
690 DB (DB_JOBS
, (child_failed
691 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
692 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
693 (unsigned long int) c
, (long) c
->pid
,
694 c
->remote
? _(" (remote)") : ""));
696 if (c
->sh_batch_file
) {
697 DB (DB_JOBS
, (_("Cleaning up temp batch file %s\n"),
700 /* just try and remove, don't care if this fails */
701 remove (c
->sh_batch_file
);
703 /* all done with memory */
704 free (c
->sh_batch_file
);
705 c
->sh_batch_file
= NULL
;
708 /* If this child had the good stdin, say it is now free. */
712 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
714 /* The commands failed. Write an error message,
715 delete non-precious targets, and abort. */
716 static int delete_on_error
= -1;
717 child_error (c
->file
->name
, exit_code
, exit_sig
, coredump
, 0);
718 c
->file
->update_status
= 2;
719 if (delete_on_error
== -1)
721 struct file
*f
= lookup_file (".DELETE_ON_ERROR");
722 delete_on_error
= f
!= 0 && f
->is_target
;
724 if (exit_sig
!= 0 || delete_on_error
)
725 delete_child_targets (c
);
731 /* The commands failed, but we don't care. */
732 child_error (c
->file
->name
,
733 exit_code
, exit_sig
, coredump
, 1);
737 /* If there are more commands to run, try to start them. */
738 if (job_next_command (c
))
740 if (handling_fatal_signal
)
742 /* Never start new commands while we are dying.
743 Since there are more commands that wanted to be run,
744 the target was not completely remade. So we treat
745 this as if a command had failed. */
746 c
->file
->update_status
= 2;
750 /* Check again whether to start remotely.
751 Whether or not we want to changes over time.
752 Also, start_remote_job may need state set up
753 by start_remote_job_p. */
754 c
->remote
= start_remote_job_p (0);
755 start_job_command (c
);
756 /* Fatal signals are left blocked in case we were
757 about to put that child on the chain. But it is
758 already there, so it is safe for a fatal signal to
759 arrive now; it will clean up this child's targets. */
761 if (c
->file
->command_state
== cs_running
)
762 /* We successfully started the new command.
763 Loop to reap more children. */
767 if (c
->file
->update_status
!= 0)
768 /* We failed to start the commands. */
769 delete_child_targets (c
);
772 /* There are no more commands. We got through them all
773 without an unignored error. Now the target has been
774 successfully updated. */
775 c
->file
->update_status
= 0;
778 /* When we get here, all the commands for C->file are finished
779 (or aborted) and C->file->update_status contains 0 or 2. But
780 C->file->command_state is still cs_running if all the commands
781 ran; notice_finish_file looks for cs_running to tell it that
782 it's interesting to check the file's modtime again now. */
784 if (! handling_fatal_signal
)
785 /* Notice if the target of the commands has been changed.
786 This also propagates its values for command_state and
787 update_status to its also_make files. */
788 notice_finished_file (c
->file
);
790 DB (DB_JOBS
, (_("Removing child 0x%08lx PID %ld%s from chain.\n"),
791 (unsigned long int) c
, (long) c
->pid
,
792 c
->remote
? _(" (remote)") : ""));
794 /* Block fatal signals while frobnicating the list, so that
795 children and job_slots_used are always consistent. Otherwise
796 a fatal signal arriving after the child is off the chain and
797 before job_slots_used is decremented would believe a child was
798 live and call reap_children again. */
801 /* There is now another slot open. */
802 if (job_slots_used
> 0)
805 /* Remove the child from the chain and free it. */
809 lastc
->next
= c
->next
;
815 /* If the job failed, and the -k flag was not given, die,
816 unless we are already in the process of dying. */
817 if (!err
&& child_failed
&& !keep_going_flag
&&
818 /* fatal_error_signal will die with the right signal. */
819 !handling_fatal_signal
)
822 /* Only block for one child. */
829 /* Free the storage allocated for CHILD. */
832 free_child (struct child
*child
)
834 /* If this child is the only one it was our "free" job, so don't put a
835 token back for it. This child has already been removed from the list,
836 so if there any left this wasn't the last one. */
838 if (job_fds
[1] >= 0 && children
)
843 /* Write a job token back to the pipe. */
845 EINTRLOOP (r
, write (job_fds
[1], &token
, 1));
847 pfatal_with_name (_("write jobserver"));
849 DB (DB_JOBS
, (_("Released token for child 0x%08lx (%s).\n"),
850 (unsigned long int) child
, child
->file
->name
));
853 if (handling_fatal_signal
) /* Don't bother free'ing if about to die. */
856 if (child
->command_lines
!= 0)
858 register unsigned int i
;
859 for (i
= 0; i
< child
->file
->cmds
->ncommand_lines
; ++i
)
860 free (child
->command_lines
[i
]);
861 free ((char *) child
->command_lines
);
864 if (child
->environment
!= 0)
866 register char **ep
= child
->environment
;
869 free ((char *) child
->environment
);
872 free ((char *) child
);
876 extern sigset_t fatal_signal_set
;
883 (void) sigprocmask (SIG_BLOCK
, &fatal_signal_set
, (sigset_t
*) 0);
885 # ifdef HAVE_SIGSETMASK
886 (void) sigblock (fatal_signal_mask
);
896 sigemptyset (&empty
);
897 sigprocmask (SIG_SETMASK
, &empty
, (sigset_t
*) 0);
901 #ifdef MAKE_JOBSERVER
903 /* Never install the SIGCHLD handler for EMX!!! */
904 # define set_child_handler_action_flags(x)
906 /* Set the child handler action flags to FLAGS. */
908 set_child_handler_action_flags (int flags
)
911 bzero ((char *) &sa
, sizeof sa
);
912 sa
.sa_handler
= child_handler
;
915 sigaction (SIGCHLD
, &sa
, NULL
);
917 #if defined SIGCLD && SIGCLD != SIGCHLD
918 sigaction (SIGCLD
, &sa
, NULL
);
921 #endif /* !__EMX__ */
925 /* Start a job to run the commands specified in CHILD.
926 CHILD is updated to reflect the commands and ID of the child process.
928 NOTE: On return fatal signals are blocked! The caller is responsible
929 for calling `unblock_sigs', once the new child is safely on the chain so
930 it can be cleaned up in the event of a fatal signal. */
933 start_job_command (struct child
*child
)
936 static int bad_stdin
= -1;
946 /* If we have a completely empty commandset, stop now. */
947 if (!child
->command_ptr
)
950 /* Combine the flags parsed for the line itself with
951 the flags specified globally for this target. */
952 flags
= (child
->file
->command_flags
953 | child
->file
->cmds
->lines_flags
[child
->command_line
- 1]);
955 p
= child
->command_ptr
;
956 child
->noerror
= flags
& COMMANDS_NOERROR
;
961 flags
|= COMMANDS_SILENT
;
963 flags
|= COMMANDS_RECURSE
;
966 else if (!isblank ((unsigned char)*p
))
971 /* Update the file's command flags with any new ones we found. We only
972 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
973 now marking more commands recursive than should be in the case of
974 multiline define/endef scripts where only one line is marked "+". In
975 order to really fix this, we'll have to keep a lines_flags for every
976 actual line, after expansion. */
977 child
->file
->cmds
->lines_flags
[child
->command_line
- 1]
978 |= flags
& COMMANDS_RECURSE
;
980 /* Figure out an argument list from this command line. */
987 argv
= construct_command_argv (p
, &end
, child
->file
, &child
->sh_batch_file
);
990 child
->command_ptr
= NULL
;
994 child
->command_ptr
= end
;
998 /* If -q was given, say that updating `failed' if there was any text on the
999 command line, or `succeeded' otherwise. The exit status of 1 tells the
1000 user that -q is saying `something to do'; the exit status for a random
1002 if (argv
!= 0 && question_flag
&& !(flags
& COMMANDS_RECURSE
))
1006 free ((char *) argv
);
1008 child
->file
->update_status
= 1;
1009 notice_finished_file (child
->file
);
1013 if (touch_flag
&& !(flags
& COMMANDS_RECURSE
))
1015 /* Go on to the next command. It might be the recursive one.
1016 We construct ARGV only to find the end of the command line. */
1021 free ((char *) argv
);
1031 execute_by_shell
= 0; /* in case construct_command_argv sets it */
1033 /* This line has no commands. Go to the next. */
1034 if (job_next_command (child
))
1035 start_job_command (child
);
1038 /* No more commands. Make sure we're "running"; we might not be if
1039 (e.g.) all commands were skipped due to -n. */
1040 set_command_state (child
->file
, cs_running
);
1041 child
->file
->update_status
= 0;
1042 notice_finished_file (child
->file
);
1047 /* Print out the command. If silent, we call `message' with null so it
1048 can log the working directory before the command's own error messages
1051 message (0, (just_print_flag
|| (!(flags
& COMMANDS_SILENT
) && !silent_flag
))
1052 ? "%s" : (char *) 0, p
);
1054 /* Tell update_goal_chain that a command has been started on behalf of
1055 this target. It is important that this happens here and not in
1056 reap_children (where we used to do it), because reap_children might be
1057 reaping children from a different target. We want this increment to
1058 guaranteedly indicate that a command was started for the dependency
1059 chain (i.e., update_file recursion chain) we are processing. */
1063 /* Optimize an empty command. People use this for timestamp rules,
1064 so avoid forking a useless shell. Do this after we increment
1065 commands_started so make still treats this special case as if it
1066 performed some action (makes a difference as to what messages are
1069 #if !defined(VMS) && !defined(_AMIGA)
1071 #if defined __MSDOS__ || defined (__EMX__)
1072 unixy_shell
/* the test is complicated and we already did it */
1074 (argv
[0] && !strcmp (argv
[0], "/bin/sh"))
1077 && argv
[1][0] == '-' && argv
[1][1] == 'c' && argv
[1][2] == '\0')
1078 && (argv
[2] && argv
[2][0] == ':' && argv
[2][1] == '\0')
1082 free ((char *) argv
);
1085 #endif /* !VMS && !_AMIGA */
1087 /* If -n was given, recurse to get the next line in the sequence. */
1089 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
))
1093 free ((char *) argv
);
1098 /* Flush the output streams so they won't have things written twice. */
1104 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1106 /* Set up a bad standard input that reads from a broken pipe. */
1108 if (bad_stdin
== -1)
1110 /* Make a file descriptor that is the read end of a broken pipe.
1111 This will be used for some children's standard inputs. */
1115 /* Close the write side. */
1116 (void) close (pd
[1]);
1117 /* Save the read side. */
1120 /* Set the descriptor to close on exec, so it does not litter any
1121 child's descriptor table. When it is dup2'd onto descriptor 0,
1122 that descriptor will not close on exec. */
1123 CLOSE_ON_EXEC (bad_stdin
);
1127 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1129 /* Decide whether to give this child the `good' standard input
1130 (one that points to the terminal or whatever), or the `bad' one
1131 that points to the read side of a broken pipe. */
1133 child
->good_stdin
= !good_stdin_used
;
1134 if (child
->good_stdin
)
1135 good_stdin_used
= 1;
1142 /* Set up the environment for the child. */
1143 if (child
->environment
== 0)
1144 child
->environment
= target_environment (child
->file
);
1147 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1150 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1153 int is_remote
, id
, used_stdin
;
1154 if (start_remote_job (argv
, child
->environment
,
1155 child
->good_stdin
? 0 : bad_stdin
,
1156 &is_remote
, &id
, &used_stdin
))
1157 /* Don't give up; remote execution may fail for various reasons. If
1158 so, simply run the job locally. */
1162 if (child
->good_stdin
&& !used_stdin
)
1164 child
->good_stdin
= 0;
1165 good_stdin_used
= 0;
1167 child
->remote
= is_remote
;
1174 /* Fork the child process. */
1176 char **parent_environ
;
1185 if (!child_execute_job (argv
, child
)) {
1187 perror_with_name ("vfork", "");
1193 parent_environ
= environ
;
1196 /* If we aren't running a recursive command and we have a jobserver
1197 pipe, close it before exec'ing. */
1198 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1200 CLOSE_ON_EXEC (job_fds
[0]);
1201 CLOSE_ON_EXEC (job_fds
[1]);
1204 CLOSE_ON_EXEC (job_rfd
);
1206 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1207 child
->pid
= child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1208 argv
, child
->environment
);
1213 perror_with_name ("spawn", "");
1217 /* undo CLOSE_ON_EXEC() after the child process has been started */
1218 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1220 fcntl (job_fds
[0], F_SETFD
, 0);
1221 fcntl (job_fds
[1], F_SETFD
, 0);
1224 fcntl (job_rfd
, F_SETFD
, 0);
1226 #else /* !__EMX__ */
1228 child
->pid
= vfork ();
1229 environ
= parent_environ
; /* Restore value child may have clobbered. */
1230 if (child
->pid
== 0)
1232 /* We are the child side. */
1235 /* If we aren't running a recursive command and we have a jobserver
1236 pipe, close it before exec'ing. */
1237 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1245 child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1246 argv
, child
->environment
);
1248 else if (child
->pid
< 0)
1252 perror_with_name ("vfork", "");
1255 # endif /* !__EMX__ */
1259 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1267 /* We call `system' to do the job of the SHELL, since stock DOS
1268 shell is too dumb. Our `system' knows how to handle long
1269 command lines even if pipes/redirection is needed; it will only
1270 call COMMAND.COM when its internal commands are used. */
1271 if (execute_by_shell
)
1273 char *cmdline
= argv
[0];
1274 /* We don't have a way to pass environment to `system',
1275 so we need to save and restore ours, sigh... */
1276 char **parent_environ
= environ
;
1278 environ
= child
->environment
;
1280 /* If we have a *real* shell, tell `system' to call
1281 it to do everything for us. */
1284 /* A *real* shell on MSDOS may not support long
1285 command lines the DJGPP way, so we must use `system'. */
1286 cmdline
= argv
[2]; /* get past "shell -c" */
1289 dos_command_running
= 1;
1290 proc_return
= system (cmdline
);
1291 environ
= parent_environ
;
1292 execute_by_shell
= 0; /* for the next time */
1296 dos_command_running
= 1;
1297 proc_return
= spawnvpe (P_WAIT
, argv
[0], argv
, child
->environment
);
1300 /* Need to unblock signals before turning off
1301 dos_command_running, so that child's signals
1302 will be treated as such (see fatal_error_signal). */
1304 dos_command_running
= 0;
1306 /* If the child got a signal, dos_status has its
1307 high 8 bits set, so be careful not to alter them. */
1308 if (proc_return
== -1)
1311 dos_status
|= (proc_return
& 0xff);
1313 child
->pid
= dos_pid
++;
1315 #endif /* __MSDOS__ */
1317 amiga_status
= MyExecute (argv
);
1320 child
->pid
= amiga_pid
++;
1321 if (amiga_batch_file
)
1323 amiga_batch_file
= 0;
1324 DeleteFile (amiga_bname
); /* Ignore errors. */
1332 /* make UNC paths safe for CreateProcess -- backslash format */
1334 if (arg0
&& arg0
[0] == '/' && arg0
[1] == '/')
1335 for ( ; arg0
&& *arg0
; arg0
++)
1339 /* make sure CreateProcess() has Path it needs */
1340 sync_Path_environment();
1342 hPID
= process_easy(argv
, child
->environment
);
1344 if (hPID
!= INVALID_HANDLE_VALUE
)
1345 child
->pid
= (int) hPID
;
1350 _("process_easy() failed failed to launch process (e=%d)\n"),
1351 process_last_err(hPID
));
1352 for (i
= 0; argv
[i
]; i
++)
1353 fprintf(stderr
, "%s ", argv
[i
]);
1354 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
1357 #endif /* WINDOWS32 */
1358 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1360 /* Bump the number of jobs started in this second. */
1363 /* We are the parent side. Set the state to
1364 say the commands are running and return. */
1366 set_command_state (child
->file
, cs_running
);
1368 /* Free the storage used by the child's argument list. */
1371 free ((char *) argv
);
1377 child
->file
->update_status
= 2;
1378 notice_finished_file (child
->file
);
1382 /* Try to start a child running.
1383 Returns nonzero if the child was started (and maybe finished), or zero if
1384 the load was too high and the child was put on the `waiting_jobs' chain. */
1387 start_waiting_job (struct child
*c
)
1389 struct file
*f
= c
->file
;
1391 /* If we can start a job remotely, we always want to, and don't care about
1392 the local load average. We record that the job should be started
1393 remotely in C->remote for start_job_command to test. */
1395 c
->remote
= start_remote_job_p (1);
1397 /* If we are running at least one job already and the load average
1398 is too high, make this one wait. */
1399 if (!c
->remote
&& job_slots_used
> 0 && load_too_high ())
1401 /* Put this child on the chain of children waiting for the load average
1403 set_command_state (f
, cs_running
);
1404 c
->next
= waiting_jobs
;
1409 /* Start the first command; reap_children will run later command lines. */
1410 start_job_command (c
);
1412 switch (f
->command_state
)
1416 DB (DB_JOBS
, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1417 (unsigned long int) c
, c
->file
->name
,
1418 (long) c
->pid
, c
->remote
? _(" (remote)") : ""));
1420 /* One more job slot is in use. */
1425 case cs_not_started
:
1426 /* All the command lines turned out to be empty. */
1427 f
->update_status
= 0;
1431 notice_finished_file (f
);
1436 assert (f
->command_state
== cs_finished
);
1443 /* Create a `struct child' for FILE and start its commands running. */
1446 new_job (struct file
*file
)
1448 register struct commands
*cmds
= file
->cmds
;
1449 register struct child
*c
;
1451 register unsigned int i
;
1453 /* Let any previously decided-upon jobs that are waiting
1454 for the load to go down start before this new one. */
1455 start_waiting_jobs ();
1457 /* Reap any children that might have finished recently. */
1458 reap_children (0, 0);
1460 /* Chop the commands up into lines if they aren't already. */
1461 chop_commands (cmds
);
1463 /* Expand the command lines and store the results in LINES. */
1464 lines
= (char **) xmalloc (cmds
->ncommand_lines
* sizeof (char *));
1465 for (i
= 0; i
< cmds
->ncommand_lines
; ++i
)
1467 /* Collapse backslash-newline combinations that are inside variable
1468 or function references. These are left alone by the parser so
1469 that they will appear in the echoing of commands (where they look
1470 nice); and collapsed by construct_command_argv when it tokenizes.
1471 But letting them survive inside function invocations loses because
1472 we don't want the functions to see them as part of the text. */
1474 char *in
, *out
, *ref
;
1476 /* IN points to where in the line we are scanning.
1477 OUT points to where in the line we are writing.
1478 When we collapse a backslash-newline combination,
1479 IN gets ahead of OUT. */
1481 in
= out
= cmds
->command_lines
[i
];
1482 while ((ref
= strchr (in
, '$')) != 0)
1484 ++ref
; /* Move past the $. */
1487 /* Copy the text between the end of the last chunk
1488 we processed (where IN points) and the new chunk
1489 we are about to process (where REF points). */
1490 bcopy (in
, out
, ref
- in
);
1492 /* Move both pointers past the boring stuff. */
1496 if (*ref
== '(' || *ref
== '{')
1498 char openparen
= *ref
;
1499 char closeparen
= openparen
== '(' ? ')' : '}';
1503 *out
++ = *in
++; /* Copy OPENPAREN. */
1504 /* IN now points past the opening paren or brace.
1505 Count parens or braces until it is matched. */
1509 if (*in
== closeparen
&& --count
< 0)
1511 else if (*in
== '\\' && in
[1] == '\n')
1513 /* We have found a backslash-newline inside a
1514 variable or function reference. Eat it and
1515 any following whitespace. */
1518 for (p
= in
- 1; p
> ref
&& *p
== '\\'; --p
)
1522 /* There were two or more backslashes, so this is
1523 not really a continuation line. We don't collapse
1524 the quoting backslashes here as is done in
1525 collapse_continuations, because the line will
1526 be collapsed again after expansion. */
1530 /* Skip the backslash, newline and
1531 any following whitespace. */
1532 in
= next_token (in
+ 2);
1534 /* Discard any preceding whitespace that has
1535 already been written to the output. */
1537 && isblank ((unsigned char)out
[-1]))
1540 /* Replace it all with a single space. */
1546 if (*in
== openparen
)
1555 /* There are no more references in this line to worry about.
1556 Copy the remaining uninteresting text to the output. */
1560 /* Finally, expand the line. */
1561 lines
[i
] = allocated_variable_expand_for_file (cmds
->command_lines
[i
],
1565 /* Start the command sequence, record it in a new
1566 `struct child', and add that to the chain. */
1568 c
= (struct child
*) xmalloc (sizeof (struct child
));
1569 bzero ((char *)c
, sizeof (struct child
));
1571 c
->command_lines
= lines
;
1572 c
->sh_batch_file
= NULL
;
1574 /* Fetch the first command line to be run. */
1575 job_next_command (c
);
1577 /* Wait for a job slot to be freed up. If we allow an infinite number
1578 don't bother; also job_slots will == 0 if we're using the jobserver. */
1581 while (job_slots_used
== job_slots
)
1582 reap_children (1, 0);
1584 #ifdef MAKE_JOBSERVER
1585 /* If we are controlling multiple jobs make sure we have a token before
1586 starting the child. */
1588 /* This can be inefficient. There's a decent chance that this job won't
1589 actually have to run any subprocesses: the command script may be empty
1590 or otherwise optimized away. It would be nice if we could defer
1591 obtaining a token until just before we need it, in start_job_command.
1592 To do that we'd need to keep track of whether we'd already obtained a
1593 token (since start_job_command is called for each line of the job, not
1594 just once). Also more thought needs to go into the entire algorithm;
1595 this is where the old parallel job code waits, so... */
1597 else if (job_fds
[0] >= 0)
1604 DB (DB_JOBS
, ("Need a job token; we %shave children\n",
1605 children
? "" : "don't "));
1607 /* If we don't already have a job started, use our "free" token. */
1611 /* Read a token. As long as there's no token available we'll block.
1612 We enable interruptible system calls before the read(2) so that if
1613 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1614 we can process the death(s) and return tokens to the free pool.
1616 Once we return from the read, we immediately reinstate restartable
1617 system calls. This allows us to not worry about checking for
1618 EINTR on all the other system calls in the program.
1620 There is one other twist: there is a span between the time
1621 reap_children() does its last check for dead children and the time
1622 the read(2) call is entered, below, where if a child dies we won't
1623 notice. This is extremely serious as it could cause us to
1624 deadlock, given the right set of events.
1626 To avoid this, we do the following: before we reap_children(), we
1627 dup(2) the read FD on the jobserver pipe. The read(2) call below
1628 uses that new FD. In the signal handler, we close that FD. That
1629 way, if a child dies during the section mentioned above, the
1630 read(2) will be invoked with an invalid FD and will return
1631 immediately with EBADF. */
1633 /* Make sure we have a dup'd FD. */
1636 DB (DB_JOBS
, ("Duplicate the job FD\n"));
1637 job_rfd
= dup (job_fds
[0]);
1640 /* Reap anything that's currently waiting. */
1641 reap_children (0, 0);
1643 /* If our "free" token has become available, use it. */
1647 /* Set interruptible system calls, and read() for a job token. */
1648 set_child_handler_action_flags (0);
1649 got_token
= read (job_rfd
, &token
, 1);
1650 saved_errno
= errno
;
1651 set_child_handler_action_flags (SA_RESTART
);
1653 /* If we got one, we're done here. */
1656 DB (DB_JOBS
, (_("Obtained token for child 0x%08lx (%s).\n"),
1657 (unsigned long int) c
, c
->file
->name
));
1661 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1662 go back and reap_children(), and try again. */
1663 errno
= saved_errno
;
1664 if (errno
!= EINTR
&& errno
!= EBADF
)
1665 pfatal_with_name (_("read jobs pipe"));
1667 DB (DB_JOBS
, ("Read returned EBADF.\n"));
1671 /* The job is now primed. Start it running.
1672 (This will notice if there are in fact no commands.) */
1673 (void) start_waiting_job (c
);
1675 if (job_slots
== 1 || not_parallel
)
1676 /* Since there is only one job slot, make things run linearly.
1677 Wait for the child to die, setting the state to `cs_finished'. */
1678 while (file
->command_state
== cs_running
)
1679 reap_children (1, 0);
1684 /* Move CHILD's pointers to the next command for it to execute.
1685 Returns nonzero if there is another command. */
1688 job_next_command (struct child
*child
)
1690 while (child
->command_ptr
== 0 || *child
->command_ptr
== '\0')
1692 /* There are no more lines in the expansion of this line. */
1693 if (child
->command_line
== child
->file
->cmds
->ncommand_lines
)
1695 /* There are no more lines to be expanded. */
1696 child
->command_ptr
= 0;
1700 /* Get the next line to run. */
1701 child
->command_ptr
= child
->command_lines
[child
->command_line
++];
1706 /* Determine if the load average on the system is too high to start a new job.
1707 The real system load average is only recomputed once a second. However, a
1708 very parallel make can easily start tens or even hundreds of jobs in a
1709 second, which brings the system to its knees for a while until that first
1710 batch of jobs clears out.
1712 To avoid this we use a weighted algorithm to try to account for jobs which
1713 have been started since the last second, and guess what the load average
1714 would be now if it were computed.
1716 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1719 ! calculate something load-oid and add to the observed sys.load,
1720 ! so that latter can catch up:
1721 ! - every job started increases jobctr;
1722 ! - every dying job decreases a positive jobctr;
1723 ! - the jobctr value gets zeroed every change of seconds,
1724 ! after its value*weight_b is stored into the 'backlog' value last_sec
1725 ! - weight_a times the sum of jobctr and last_sec gets
1726 ! added to the observed sys.load.
1728 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1729 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1730 ! sub-shelled commands (rm, echo, sed...) for tests.
1731 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1732 ! resulted in significant excession of the load limit, raising it
1733 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1734 ! reach the limit in most test cases.
1736 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1737 ! exceeding the limit for longer-running stuff (compile jobs in
1738 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1739 ! small jobs' effects.
1743 #define LOAD_WEIGHT_A 0.25
1744 #define LOAD_WEIGHT_B 0.25
1747 load_too_high (void)
1749 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1752 static double last_sec
;
1753 static time_t last_now
;
1757 if (max_load_average
< 0)
1760 /* Find the real system load average. */
1762 if (getloadavg (&load
, 1) != 1)
1764 static int lossage
= -1;
1765 /* Complain only once for the same error. */
1766 if (lossage
== -1 || errno
!= lossage
)
1769 /* An errno value of zero means getloadavg is just unsupported. */
1771 _("cannot enforce load limits on this operating system"));
1773 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1780 /* If we're in a new second zero the counter and correct the backlog
1781 value. Only keep the backlog for one extra second; after that it's 0. */
1785 if (last_now
== now
- 1)
1786 last_sec
= LOAD_WEIGHT_B
* job_counter
;
1794 /* Try to guess what the load would be right now. */
1795 guess
= load
+ (LOAD_WEIGHT_A
* (job_counter
+ last_sec
));
1797 DB (DB_JOBS
, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1798 guess
, load
, max_load_average
));
1800 return guess
>= max_load_average
;
1804 /* Start jobs that are waiting for the load to be lower. */
1807 start_waiting_jobs (void)
1811 if (waiting_jobs
== 0)
1816 /* Check for recently deceased descendants. */
1817 reap_children (0, 0);
1819 /* Take a job off the waiting list. */
1821 waiting_jobs
= job
->next
;
1823 /* Try to start that job. We break out of the loop as soon
1824 as start_waiting_job puts one back on the waiting list. */
1826 while (start_waiting_job (job
) && waiting_jobs
!= 0);
1833 #include <descrip.h>
1836 /* This is called as an AST when a child process dies (it won't get
1837 interrupted by anything except a higher level AST).
1839 int vmsHandleChildTerm(struct child
*child
)
1842 register struct child
*lastc
, *c
;
1845 vms_jobsefnmask
&= ~(1 << (child
->efn
- 32));
1847 lib$
free_ef(&child
->efn
);
1849 (void) sigblock (fatal_signal_mask
);
1851 child_failed
= !(child
->cstatus
& 1 || ((child
->cstatus
& 7) == 0));
1853 /* Search for a child matching the deceased one. */
1855 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1856 for (c
= children
; c
!= 0 && c
!= child
; lastc
= c
, c
= c
->next
);
1861 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
1863 /* The commands failed. Write an error message,
1864 delete non-precious targets, and abort. */
1865 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 0);
1866 c
->file
->update_status
= 1;
1867 delete_child_targets (c
);
1873 /* The commands failed, but we don't care. */
1874 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 1);
1878 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1879 /* If there are more commands to run, try to start them. */
1882 switch (c
->file
->command_state
)
1885 /* Successfully started. */
1889 if (c
->file
->update_status
!= 0) {
1890 /* We failed to start the commands. */
1891 delete_child_targets (c
);
1896 error (NILF
, _("internal error: `%s' command_state"),
1901 #endif /* RECURSIVEJOBS */
1904 /* Set the state flag to say the commands have finished. */
1905 c
->file
->command_state
= cs_finished
;
1906 notice_finished_file (c
->file
);
1908 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1909 /* Remove the child from the chain and free it. */
1913 lastc
->next
= c
->next
;
1915 #endif /* RECURSIVEJOBS */
1917 /* There is now another slot open. */
1918 if (job_slots_used
> 0)
1921 /* If the job failed, and the -k flag was not given, die. */
1922 if (child_failed
&& !keep_going_flag
)
1925 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask
));
1931 Spawn a process executing the command in ARGV and return its pid. */
1933 #define MAXCMDLEN 200
1935 /* local helpers to make ctrl+c and ctrl+y working, see below */
1937 #include <libclidef.h>
1940 static int ctrlMask
= LIB$M_CLI_CTRLY
;
1941 static int oldCtrlMask
;
1942 static int setupYAstTried
= 0;
1943 static int pidToAbort
= 0;
1946 static void reEnableAst(void) {
1947 lib$
enable_ctrl (&oldCtrlMask
,0);
1950 static astHandler (void) {
1952 sys$
forcex (&pidToAbort
, 0, SS$_ABORT
);
1955 kill (getpid(),SIGQUIT
);
1958 static void tryToSetupYAst(void) {
1959 $
DESCRIPTOR(inputDsc
,"SYS$COMMAND");
1962 short int status
, count
;
1969 status
= sys$
assign(&inputDsc
,&chan
,0,0);
1970 if (!(status
&SS$_NORMAL
)) {
1975 status
= sys$
qiow (0, chan
, IO$_SETMODE
|IO$M_CTRLYAST
,&iosb
,0,0,
1976 astHandler
,0,0,0,0,0);
1977 if (status
==SS$_ILLIOFUNC
) {
1979 #ifdef CTRLY_ENABLED_ANYWAY
1981 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
1986 if (status
==SS$_NORMAL
)
1987 status
= iosb
.status
;
1988 if (!(status
&SS$_NORMAL
)) {
1993 /* called from AST handler ? */
1994 if (setupYAstTried
>1)
1996 if (atexit(reEnableAst
))
1998 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
1999 status
= lib$
disable_ctrl (&ctrlMask
, &oldCtrlMask
);
2000 if (!(status
&SS$_NORMAL
)) {
2006 child_execute_job (char *argv
, struct child
*child
)
2009 static struct dsc$descriptor_s cmddsc
;
2010 static struct dsc$descriptor_s pnamedsc
;
2011 static struct dsc$descriptor_s ifiledsc
;
2012 static struct dsc$descriptor_s ofiledsc
;
2013 static struct dsc$descriptor_s efiledsc
;
2014 int have_redirection
= 0;
2015 int have_newline
= 0;
2017 int spflags
= CLI$M_NOWAIT
;
2019 char *cmd
= alloca (strlen (argv
) + 512), *p
, *q
;
2020 char ifile
[256], ofile
[256], efile
[256];
2024 /* Parse IO redirection. */
2030 DB (DB_JOBS
, ("child_execute_job (%s)\n", argv
));
2032 while (isspace ((unsigned char)*argv
))
2038 sprintf (procname
, "GMAKE_%05x", getpid () & 0xfffff);
2039 pnamedsc
.dsc$w_length
= strlen(procname
);
2040 pnamedsc
.dsc$a_pointer
= procname
;
2041 pnamedsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
2042 pnamedsc
.dsc$b_class
= DSC$K_CLASS_S
;
2044 /* Handle comments and redirection. */
2045 for (p
= argv
, q
= cmd
; *p
; p
++, q
++)
2057 if (isspace ((unsigned char)*p
))
2059 do { p
++; } while (isspace ((unsigned char)*p
));
2065 p
= vms_redirect (&ifiledsc
, ifile
, p
);
2067 have_redirection
= 1;
2070 have_redirection
= 1;
2074 if (strncmp (p
, ">&1", 3) == 0)
2077 strcpy (efile
, "sys$output");
2078 efiledsc
.dsc$w_length
= strlen(efile
);
2079 efiledsc
.dsc$a_pointer
= efile
;
2080 efiledsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
2081 efiledsc
.dsc$b_class
= DSC$K_CLASS_S
;
2085 p
= vms_redirect (&efiledsc
, efile
, p
);
2090 p
= vms_redirect (&ofiledsc
, ofile
, p
);
2103 if (strncmp (cmd
, "builtin_", 8) == 0)
2105 child
->pid
= 270163;
2109 DB (DB_JOBS
, (_("BUILTIN [%s][%s]\n"), cmd
, cmd
+8));
2115 && ((*(p
+2) == ' ') || (*(p
+2) == '\t')))
2118 while ((*p
== ' ') || (*p
== '\t'))
2120 DB (DB_JOBS
, (_("BUILTIN CD %s\n"), p
));
2126 else if ((*(p
) == 'r')
2128 && ((*(p
+2) == ' ') || (*(p
+2) == '\t')))
2134 while ((*p
== ' ') || (*p
== '\t'))
2138 DB (DB_JOBS
, (_("BUILTIN RM %s\n"), p
));
2159 printf(_("Unknown builtin command '%s'\n"), cmd
);
2165 /* Create a *.com file if either the command is too long for
2166 lib$spawn, or the command contains a newline, or if redirection
2167 is desired. Forcing commands with newlines into DCLs allows to
2168 store search lists on user mode logicals. */
2170 if (strlen (cmd
) > MAXCMDLEN
2171 || (have_redirection
!= 0)
2172 || (have_newline
!= 0))
2177 int alevel
= 0; /* apostrophe level */
2179 if (strlen (cmd
) == 0)
2181 printf (_("Error, empty command\n"));
2186 outfile
= open_tmpfile (&comname
, "sys$scratch:CMDXXXXXX.COM");
2188 pfatal_with_name (_("fopen (temporary file)"));
2192 fprintf (outfile
, "$ assign/user %s sys$input\n", ifile
);
2193 DB (DB_JOBS
, (_("Redirected input from %s\n"), ifile
));
2194 ifiledsc
.dsc$w_length
= 0;
2199 fprintf (outfile
, "$ define sys$error %s\n", efile
);
2200 DB (DB_JOBS
, (_("Redirected error to %s\n"), efile
));
2201 efiledsc
.dsc$w_length
= 0;
2206 fprintf (outfile
, "$ define sys$output %s\n", ofile
);
2207 DB (DB_JOBS
, (_("Redirected output to %s\n"), ofile
));
2208 ofiledsc
.dsc$w_length
= 0;
2212 for (c
= '\n'; c
; c
= *q
++)
2217 /* At a newline, skip any whitespace around a leading $
2218 from the command and issue exactly one $ into the DCL. */
2219 while (isspace ((unsigned char)*p
))
2223 while (isspace ((unsigned char)*p
))
2225 fwrite (p
, 1, q
- p
, outfile
);
2226 fputc ('$', outfile
);
2227 fputc (' ', outfile
);
2228 /* Reset variables. */
2232 /* Nice places for line breaks are after strings, after
2233 comma or space and before slash. */
2235 q
= vms_handle_apos (q
+ 1);
2251 /* Enough stuff for a line. */
2252 fwrite (p
, 1, sep
- p
, outfile
);
2256 /* The command continues. */
2257 fputc ('-', outfile
);
2259 fputc ('\n', outfile
);
2263 fwrite (p
, 1, q
- p
, outfile
);
2264 fputc ('\n', outfile
);
2268 sprintf (cmd
, "$ @%s", comname
);
2270 DB (DB_JOBS
, (_("Executing %s instead\n"), cmd
));
2273 cmddsc
.dsc$w_length
= strlen(cmd
);
2274 cmddsc
.dsc$a_pointer
= cmd
;
2275 cmddsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
2276 cmddsc
.dsc$b_class
= DSC$K_CLASS_S
;
2279 while (child
->efn
< 32 || child
->efn
> 63)
2281 status
= lib$
get_ef ((unsigned long *)&child
->efn
);
2286 sys$
clref (child
->efn
);
2288 vms_jobsefnmask
|= (1 << (child
->efn
- 32));
2291 LIB$SPAWN [command-string]
2296 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2297 [,AST-address] [,varying-AST-argument]
2298 [,prompt-string] [,cli] [,table]
2301 #ifndef DONTWAITFORCHILD
2303 * Code to make ctrl+c and ctrl+y working.
2304 * The problem starts with the synchronous case where after lib$spawn is
2305 * called any input will go to the child. But with input re-directed,
2306 * both control characters won't make it to any of the programs, neither
2307 * the spawning nor to the spawned one. Hence the caller needs to spawn
2308 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2309 * has to follow to simulate the wanted synchronous behaviour.
2310 * The next problem is ctrl+y which isn't caught by the crtl and
2311 * therefore isn't converted to SIGQUIT (for a signal handler which is
2312 * already established). The only way to catch ctrl+y, is an AST
2313 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2314 * disabled, otherwise it will handle it. Not to mention the previous
2315 * ctrl+y handling of DCL needs to be re-established before make exits.
2316 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2317 * make it to the signal handler after the child "normally" terminates.
2318 * This isn't enough. It seems reasonable for simple command lines like
2319 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2320 * spawning make. Therefore we need to abort the process in the AST.
2322 * Prior to the spawn it is checked if an AST is already set up for
2323 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2324 * this will work except if make is run in a batch environment, but there
2325 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2326 * is disabled and an exit handler is established to re-enable it.
2327 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2328 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2329 * the already established handler and will bring us back to common code.
2330 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2331 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2332 * which the crtl converts to SIGINT and which is caught by the common
2333 * signal handler. Because signals were blocked before entering this code
2334 * sys$waitfr will always complete and the SIGQUIT will be processed after
2335 * it (after termination of the current block, somewhere in common code).
2336 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2337 * current command completes. Anyway it's better than nothing :-)
2340 if (!setupYAstTried
)
2342 status
= lib$
spawn (&cmddsc
, /* cmd-string */
2343 (ifiledsc
.dsc$w_length
== 0)?0:&ifiledsc
, /* input-file */
2344 (ofiledsc
.dsc$w_length
== 0)?0:&ofiledsc
, /* output-file */
2345 &spflags
, /* flags */
2346 &pnamedsc
, /* proc name */
2347 &child
->pid
, &child
->cstatus
, &child
->efn
,
2352 pidToAbort
= child
->pid
;
2353 status
= sys$
waitfr (child
->efn
);
2355 vmsHandleChildTerm(child
);
2358 status
= lib$
spawn (&cmddsc
,
2359 (ifiledsc
.dsc$w_length
== 0)?0:&ifiledsc
,
2360 (ofiledsc
.dsc$w_length
== 0)?0:&ofiledsc
,
2363 &child
->pid
, &child
->cstatus
, &child
->efn
,
2364 vmsHandleChildTerm
, child
,
2370 printf (_("Error spawning, %d\n") ,status
);
2382 if (comname
&& !ISDB (DB_JOBS
))
2385 return (status
& 1);
2390 /* EMX: Start a child process. This function returns the new pid. */
2391 # if defined __MSDOS__ || defined __EMX__
2393 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2396 /* stdin_fd == 0 means: nothing to do for stdin;
2397 stdout_fd == 1 means: nothing to do for stdout */
2398 int save_stdin
= (stdin_fd
!= 0) ? dup (0) : 0;
2399 int save_stdout
= (stdout_fd
!= 1) ? dup (1): 1;
2401 /* < 0 only if dup() failed */
2403 fatal (NILF
, _("no more file handles: could not duplicate stdin\n"));
2404 if (save_stdout
< 0)
2405 fatal (NILF
, _("no more file handles: could not duplicate stdout\n"));
2407 /* Close unnecessary file handles for the child. */
2408 if (save_stdin
!= 0)
2409 CLOSE_ON_EXEC (save_stdin
);
2410 if (save_stdout
!= 1)
2411 CLOSE_ON_EXEC (save_stdout
);
2413 /* Connect the pipes to the child process. */
2415 (void) dup2 (stdin_fd
, 0);
2417 (void) dup2 (stdout_fd
, 1);
2419 /* stdin_fd and stdout_fd must be closed on exit because we are
2420 still in the parent process */
2422 CLOSE_ON_EXEC (stdin_fd
);
2424 CLOSE_ON_EXEC (stdout_fd
);
2426 /* Run the command. */
2427 pid
= exec_command (argv
, envp
);
2429 /* Restore stdout/stdin of the parent process. */
2430 if (stdin_fd
!= 0 && dup2 (save_stdin
, 0) != 0)
2431 fatal (NILF
, _("restoring of stdin failed\n"));
2432 if (stdout_fd
!= 1 && dup2 (save_stdout
, 1) != 1)
2433 fatal (NILF
, _("restoring of stdout failed\n"));
2438 #elif !defined (_AMIGA) && !defined (__MSDOS__)
2441 Replace the current process with one executing the command in ARGV.
2442 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2443 the environment of the new program. This function does not return. */
2445 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2448 (void) dup2 (stdin_fd
, 0);
2450 (void) dup2 (stdout_fd
, 1);
2452 (void) close (stdin_fd
);
2454 (void) close (stdout_fd
);
2456 /* Run the command. */
2457 exec_command (argv
, envp
);
2459 #endif /* !AMIGA && !__MSDOS__ */
2461 #endif /* !WINDOWS32 */
2464 /* Replace the current process with one running the command in ARGV,
2465 with environment ENVP. This function does not return. */
2467 /* EMX: This function returns the pid of the child process. */
2473 exec_command (char **argv
, char **envp
)
2476 /* to work around a problem with signals and execve: ignore them */
2478 signal (SIGCHLD
,SIG_IGN
);
2480 /* Run the program. */
2481 execve (argv
[0], argv
, envp
);
2482 perror_with_name ("execve: ", argv
[0]);
2483 _exit (EXIT_FAILURE
);
2489 int exit_code
= EXIT_FAILURE
;
2491 /* make sure CreateProcess() has Path it needs */
2492 sync_Path_environment();
2494 /* launch command */
2495 hPID
= process_easy(argv
, envp
);
2497 /* make sure launch ok */
2498 if (hPID
== INVALID_HANDLE_VALUE
)
2502 _("process_easy() failed failed to launch process (e=%d)\n"),
2503 process_last_err(hPID
));
2504 for (i
= 0; argv
[i
]; i
++)
2505 fprintf(stderr
, "%s ", argv
[i
]);
2506 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
2510 /* wait and reap last child */
2511 while (hWaitPID
= process_wait_for_any())
2513 /* was an error found on this process? */
2514 err
= process_last_err(hWaitPID
);
2517 exit_code
= process_exit_code(hWaitPID
);
2520 fprintf(stderr
, "make (e=%d, rc=%d): %s",
2521 err
, exit_code
, map_windows32_error_to_string(err
));
2523 /* cleanup process */
2524 process_cleanup(hWaitPID
);
2526 /* expect to find only last pid, warn about other pids reaped */
2527 if (hWaitPID
== hPID
)
2531 _("make reaped child pid %d, still waiting for pid %d\n"),
2535 /* return child's exit code as our exit code */
2538 #else /* !WINDOWS32 */
2544 /* Be the user, permanently. */
2549 /* Run the program. */
2550 pid
= spawnvpe (P_NOWAIT
, argv
[0], argv
, envp
);
2555 /* the file might have a strange shell extension */
2556 if (errno
== ENOENT
)
2561 /* Run the program. */
2563 execvp (argv
[0], argv
);
2565 # endif /* !__EMX__ */
2570 error (NILF
, _("%s: Command not found"), argv
[0]);
2574 /* The file is not executable. Try it as a shell script. */
2575 extern char *getenv ();
2581 /* Do not use $SHELL from the environment */
2582 struct variable
*p
= lookup_variable ("SHELL", 5);
2588 shell
= getenv ("SHELL");
2591 shell
= default_shell
;
2594 while (argv
[argc
] != 0)
2597 new_argv
= (char **) alloca ((1 + argc
+ 1) * sizeof (char *));
2598 new_argv
[0] = shell
;
2599 new_argv
[1] = argv
[0];
2602 new_argv
[1 + argc
] = argv
[argc
];
2607 pid
= spawnvpe (P_NOWAIT
, shell
, new_argv
, envp
);
2611 execvp (shell
, new_argv
);
2613 if (errno
== ENOENT
)
2614 error (NILF
, _("%s: Shell program not found"), shell
);
2616 perror_with_name ("execvp: ", shell
);
2622 /* this nasty error was driving me nuts :-( */
2623 error (NILF
, _("spawnvpe: environment space might be exhausted"));
2628 perror_with_name ("execvp: ", argv
[0]);
2637 #endif /* !WINDOWS32 */
2640 #else /* On Amiga */
2641 void exec_command (char **argv
)
2646 void clean_tmp (void)
2648 DeleteFile (amiga_bname
);
2651 #endif /* On Amiga */
2654 /* Figure out the argument list necessary to run LINE as a command. Try to
2655 avoid using a shell. This routine handles only ' quoting, and " quoting
2656 when no backslash, $ or ` characters are seen in the quotes. Starting
2657 quotes may be escaped with a backslash. If any of the characters in
2658 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2659 is the first word of a line, the shell is used.
2661 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2662 If *RESTP is NULL, newlines will be ignored.
2664 SHELL is the shell to use, or nil to use the default shell.
2665 IFS is the value of $IFS, or nil (meaning the default). */
2668 construct_command_argv_internal (char *line
, char **restp
, char *shell
,
2669 char *ifs
, char **batch_filename_ptr
)
2672 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2673 We call `system' for anything that requires ``slow'' processing,
2674 because DOS shells are too dumb. When $SHELL points to a real
2675 (unix-style) shell, `system' just calls it to do everything. When
2676 $SHELL points to a DOS shell, `system' does most of the work
2677 internally, calling the shell only for its internal commands.
2678 However, it looks on the $PATH first, so you can e.g. have an
2679 external command named `mkdir'.
2681 Since we call `system', certain characters and commands below are
2682 actually not specific to COMMAND.COM, but to the DJGPP implementation
2683 of `system'. In particular:
2685 The shell wildcard characters are in DOS_CHARS because they will
2686 not be expanded if we call the child via `spawnXX'.
2688 The `;' is in DOS_CHARS, because our `system' knows how to run
2689 multiple commands on a single line.
2691 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2692 won't have to tell one from another and have one more set of
2693 commands and special characters. */
2694 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2695 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2696 "copy", "ctty", "date", "del", "dir", "echo",
2697 "erase", "exit", "for", "goto", "if", "md",
2698 "mkdir", "path", "pause", "prompt", "rd",
2699 "rmdir", "rem", "ren", "rename", "set",
2700 "shift", "time", "type", "ver", "verify",
2703 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2704 static char *sh_cmds_sh
[] = { "cd", "echo", "eval", "exec", "exit", "login",
2705 "logout", "set", "umask", "wait", "while",
2706 "for", "case", "if", ":", ".", "break",
2707 "continue", "export", "read", "readonly",
2708 "shift", "times", "trap", "switch", "unset",
2713 #elif defined (__EMX__)
2714 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2715 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2716 "copy", "ctty", "date", "del", "dir", "echo",
2717 "erase", "exit", "for", "goto", "if", "md",
2718 "mkdir", "path", "pause", "prompt", "rd",
2719 "rmdir", "rem", "ren", "rename", "set",
2720 "shift", "time", "type", "ver", "verify",
2723 static char sh_chars_os2
[] = "*?[];|<>%^()\"'&";
2724 static char *sh_cmds_os2
[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2725 "date", "del", "detach", "dir", "echo",
2726 "endlocal", "erase", "exit", "for", "goto", "if",
2727 "keys", "md", "mkdir", "move", "path", "pause",
2728 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2729 "set", "setlocal", "shift", "start", "time",
2730 "type", "ver", "verify", "vol", ":", 0 };
2732 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^~'";
2733 static char *sh_cmds_sh
[] = { "echo", "cd", "eval", "exec", "exit", "login",
2734 "logout", "set", "umask", "wait", "while",
2735 "for", "case", "if", ":", ".", "break",
2736 "continue", "export", "read", "readonly",
2737 "shift", "times", "trap", "switch", "unset",
2742 #elif defined (_AMIGA)
2743 static char sh_chars
[] = "#;\"|<>()?*$`";
2744 static char *sh_cmds
[] = { "cd", "eval", "if", "delete", "echo", "copy",
2745 "rename", "set", "setenv", "date", "makedir",
2746 "skip", "else", "endif", "path", "prompt",
2747 "unset", "unsetenv", "version",
2749 #elif defined (WINDOWS32)
2750 static char sh_chars_dos
[] = "\"|&<>";
2751 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2752 "copy", "ctty", "date", "del", "dir", "echo",
2753 "erase", "exit", "for", "goto", "if", "if", "md",
2754 "mkdir", "path", "pause", "prompt", "rd", "rem",
2755 "ren", "rename", "rmdir", "set", "shift", "time",
2756 "type", "ver", "verify", "vol", ":", 0 };
2757 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2758 static char *sh_cmds_sh
[] = { "cd", "eval", "exec", "exit", "login",
2759 "logout", "set", "umask", "wait", "while", "for",
2760 "case", "if", ":", ".", "break", "continue",
2761 "export", "read", "readonly", "shift", "times",
2762 "trap", "switch", "test",
2763 #ifdef BATCH_MODE_ONLY_SHELL
2769 #else /* must be UNIX-ish */
2770 static char sh_chars
[] = "#;\"*?[]&|<>(){}$`^~!";
2771 static char *sh_cmds
[] = { "cd", "eval", "exec", "exit", "login",
2772 "logout", "set", "umask", "wait", "while", "for",
2773 "case", "if", ":", ".", "break", "continue",
2774 "export", "read", "readonly", "shift", "times",
2775 "trap", "switch", 0 };
2776 #endif /* __MSDOS__ */
2781 int instring
, word_has_equals
, seen_nonequals
, last_argument_was_empty
;
2782 char **new_argv
= 0;
2786 if (no_default_sh_exe
) {
2787 sh_cmds
= sh_cmds_dos
;
2788 sh_chars
= sh_chars_dos
;
2790 sh_cmds
= sh_cmds_sh
;
2791 sh_chars
= sh_chars_sh
;
2793 #endif /* WINDOWS32 */
2798 /* Make sure not to bother processing an empty line. */
2799 while (isblank ((unsigned char)*line
))
2804 /* See if it is safe to parse commands internally. */
2806 shell
= default_shell
;
2808 else if (strcmp (shell
, default_shell
))
2810 char *s1
= _fullpath(NULL
, shell
, 0);
2811 char *s2
= _fullpath(NULL
, default_shell
, 0);
2813 slow_flag
= strcmp((s1
? s1
: ""), (s2
? s2
: ""));
2822 #else /* not WINDOWS32 */
2823 #if defined (__MSDOS__) || defined (__EMX__)
2824 else if (stricmp (shell
, default_shell
))
2826 extern int _is_unixy_shell (const char *_path
);
2828 DB (DB_BASIC
, (_("$SHELL changed (was `%s', now `%s')\n"),
2829 default_shell
, shell
));
2830 unixy_shell
= _is_unixy_shell (shell
);
2831 /* we must allocate a copy of shell: construct_command_argv() will free
2832 * shell after this function returns. */
2833 default_shell
= xstrdup (shell
);
2837 sh_chars
= sh_chars_sh
;
2838 sh_cmds
= sh_cmds_sh
;
2842 sh_chars
= sh_chars_dos
;
2843 sh_cmds
= sh_cmds_dos
;
2845 if (_osmode
== OS2_MODE
)
2847 sh_chars
= sh_chars_os2
;
2848 sh_cmds
= sh_cmds_os2
;
2852 #else /* !__MSDOS__ */
2853 else if (strcmp (shell
, default_shell
))
2855 #endif /* !__MSDOS__ && !__EMX__ */
2856 #endif /* not WINDOWS32 */
2859 for (ap
= ifs
; *ap
!= '\0'; ++ap
)
2860 if (*ap
!= ' ' && *ap
!= '\t' && *ap
!= '\n')
2863 i
= strlen (line
) + 1;
2865 /* More than 1 arg per character is impossible. */
2866 new_argv
= (char **) xmalloc (i
* sizeof (char *));
2868 /* All the args can fit in a buffer as big as LINE is. */
2869 ap
= new_argv
[0] = (char *) xmalloc (i
);
2872 /* I is how many complete arguments have been found. */
2874 instring
= word_has_equals
= seen_nonequals
= last_argument_was_empty
= 0;
2875 for (p
= line
; *p
!= '\0'; ++p
)
2883 /* Inside a string, just copy any char except a closing quote
2884 or a backslash-newline combination. */
2888 if (ap
== new_argv
[0] || *(ap
-1) == '\0')
2889 last_argument_was_empty
= 1;
2891 else if (*p
== '\\' && p
[1] == '\n')
2892 goto swallow_escaped_newline
;
2893 else if (*p
== '\n' && restp
!= NULL
)
2895 /* End of the command line. */
2899 /* Backslash, $, and ` are special inside double quotes.
2900 If we see any of those, punt.
2901 But on MSDOS, if we use COMMAND.COM, double and single
2902 quotes have the same effect. */
2903 else if (instring
== '"' && strchr ("\\$`", *p
) != 0 && unixy_shell
)
2908 else if (strchr (sh_chars
, *p
) != 0)
2909 /* Not inside a string, but it's a special char. */
2912 else if (*p
== '.' && p
[1] == '.' && p
[2] == '.' && p
[3] != '.')
2913 /* `...' is a wildcard in DJGPP. */
2917 /* Not a special char. */
2921 /* Equals is a special character in leading words before the
2922 first word with no equals sign in it. This is not the case
2923 with sh -k, but we never get here when using nonstandard
2925 if (! seen_nonequals
&& unixy_shell
)
2927 word_has_equals
= 1;
2932 /* Backslash-newline combinations are eaten. */
2935 swallow_escaped_newline
:
2937 /* Eat the backslash, the newline, and following whitespace,
2938 replacing it all with a single space. */
2941 /* If there is a tab after a backslash-newline,
2942 remove it from the source line which will be echoed,
2943 since it was most likely used to line
2944 up the continued line with the previous one. */
2946 /* Note these overlap and strcpy() is undefined for
2947 overlapping objects in ANSI C. The strlen() _IS_ right,
2948 since we need to copy the nul byte too. */
2949 bcopy (p
+ 1, p
, strlen (p
));
2955 if (ap
!= new_argv
[i
])
2956 /* Treat this as a space, ending the arg.
2957 But if it's at the beginning of the arg, it should
2958 just get eaten, rather than becoming an empty arg. */
2961 p
= next_token (p
) - 1;
2964 else if (p
[1] != '\0')
2966 #ifdef HAVE_DOS_PATHS
2967 /* Only remove backslashes before characters special
2968 to Unixy shells. All other backslashes are copied
2969 verbatim, since they are probably DOS-style
2970 directory separators. This still leaves a small
2971 window for problems, but at least it should work
2972 for the vast majority of naive users. */
2975 /* A dot is only special as part of the "..."
2977 if (strneq (p
+ 1, ".\\.\\.", 5))
2985 if (p
[1] != '\\' && p
[1] != '\''
2986 && !isspace ((unsigned char)p
[1])
2987 && (strchr (sh_chars_sh
, p
[1]) == 0))
2988 /* back up one notch, to copy the backslash */
2990 #endif /* HAVE_DOS_PATHS */
2992 /* Copy and skip the following char. */
3005 /* End of the command line. */
3010 /* Newlines are not special. */
3017 /* We have the end of an argument.
3018 Terminate the text of the argument. */
3021 last_argument_was_empty
= 0;
3023 /* Update SEEN_NONEQUALS, which tells us if every word
3024 heretofore has contained an `='. */
3025 seen_nonequals
|= ! word_has_equals
;
3026 if (word_has_equals
&& ! seen_nonequals
)
3027 /* An `=' in a word before the first
3028 word without one is magical. */
3030 word_has_equals
= 0; /* Prepare for the next word. */
3032 /* If this argument is the command name,
3033 see if it is a built-in shell command.
3034 If so, have the shell handle it. */
3038 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
3039 if (streq (sh_cmds
[j
], new_argv
[0]))
3043 /* Ignore multiple whitespace chars. */
3045 /* Next iteration should examine the first nonwhite char. */
3057 /* Let the shell deal with an unterminated quote. */
3060 /* Terminate the last argument and the argument list. */
3063 if (new_argv
[i
][0] != '\0' || last_argument_was_empty
)
3070 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
3071 if (streq (sh_cmds
[j
], new_argv
[0]))
3075 if (new_argv
[0] == 0)
3076 /* Line was empty. */
3082 /* We must use the shell. */
3086 /* Free the old argument list we were working on. */
3088 free ((void *)new_argv
);
3092 execute_by_shell
= 1; /* actually, call `system' if shell isn't unixy */
3101 buffer
= (char *)xmalloc (strlen (line
)+1);
3104 for (dptr
=buffer
; *ptr
; )
3106 if (*ptr
== '\\' && ptr
[1] == '\n')
3108 else if (*ptr
== '@') /* Kludge: multiline commands */
3118 new_argv
= (char **) xmalloc (2 * sizeof (char *));
3119 new_argv
[0] = buffer
;
3122 #else /* Not Amiga */
3125 * Not eating this whitespace caused things like
3129 * which gave the shell fits. I think we have to eat
3130 * whitespace here, but this code should be considered
3131 * suspicious if things start failing....
3134 /* Make sure not to bother processing an empty line. */
3135 while (isspace ((unsigned char)*line
))
3139 #endif /* WINDOWS32 */
3141 /* SHELL may be a multi-word command. Construct a command line
3142 "SHELL -c LINE", with all special chars in LINE escaped.
3143 Then recurse, expanding this command line to get the final
3146 unsigned int shell_len
= strlen (shell
);
3148 static char minus_c
[] = " -c ";
3150 static char minus_c
[] = "";
3152 unsigned int line_len
= strlen (line
);
3154 char *new_line
= (char *) alloca (shell_len
+ (sizeof (minus_c
) - 1)
3155 + (line_len
* 2) + 1);
3156 char *command_ptr
= NULL
; /* used for batch_mode_shell mode */
3158 # ifdef __EMX__ /* is this necessary? */
3160 minus_c
[1] = '/'; /* " /c " */
3164 bcopy (shell
, ap
, shell_len
);
3166 bcopy (minus_c
, ap
, sizeof (minus_c
) - 1);
3167 ap
+= sizeof (minus_c
) - 1;
3169 for (p
= line
; *p
!= '\0'; ++p
)
3171 if (restp
!= NULL
&& *p
== '\n')
3176 else if (*p
== '\\' && p
[1] == '\n')
3178 /* Eat the backslash, the newline, and following whitespace,
3179 replacing it all with a single space (which is escaped
3183 /* If there is a tab after a backslash-newline,
3184 remove it from the source line which will be echoed,
3185 since it was most likely used to line
3186 up the continued line with the previous one. */
3188 bcopy (p
+ 1, p
, strlen (p
));
3192 if (unixy_shell
&& !batch_mode_shell
)
3198 /* DOS shells don't know about backslash-escaping. */
3199 if (unixy_shell
&& !batch_mode_shell
&&
3200 (*p
== '\\' || *p
== '\'' || *p
== '"'
3201 || isspace ((unsigned char)*p
)
3202 || strchr (sh_chars
, *p
) != 0))
3205 else if (unixy_shell
&& strneq (p
, "...", 3))
3207 /* The case of `...' wildcard again. */
3208 strcpy (ap
, "\\.\\.\\");
3215 if (ap
== new_line
+ shell_len
+ sizeof (minus_c
) - 1)
3216 /* Line was empty. */
3221 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3222 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3223 cases, run commands via a script file. */
3224 if ((no_default_sh_exe
|| batch_mode_shell
) && batch_filename_ptr
) {
3226 int id
= GetCurrentProcessId();
3230 /* create a file name */
3231 sprintf(fbuf
, "make%d", id
);
3232 fname
= tempnam(".", fbuf
);
3234 /* create batch file name */
3235 *batch_filename_ptr
= xmalloc(strlen(fname
) + 5);
3236 strcpy(*batch_filename_ptr
, fname
);
3238 /* make sure path name is in DOS backslash format */
3240 fname
= *batch_filename_ptr
;
3241 for (i
= 0; fname
[i
] != '\0'; ++i
)
3242 if (fname
[i
] == '/')
3244 strcat(*batch_filename_ptr
, ".bat");
3246 strcat(*batch_filename_ptr
, ".sh");
3249 DB (DB_JOBS
, (_("Creating temporary batch file %s\n"),
3250 *batch_filename_ptr
));
3252 /* create batch file to execute command */
3253 batch
= fopen (*batch_filename_ptr
, "w");
3255 fputs ("@echo off\n", batch
);
3256 fputs (command_ptr
, batch
);
3257 fputc ('\n', batch
);
3261 new_argv
= (char **) xmalloc(3 * sizeof (char *));
3263 new_argv
[0] = xstrdup (shell
);
3264 new_argv
[1] = *batch_filename_ptr
; /* only argv[0] gets freed later */
3266 new_argv
[0] = xstrdup (*batch_filename_ptr
);
3271 #endif /* WINDOWS32 */
3273 new_argv
= construct_command_argv_internal (new_line
, (char **) NULL
,
3274 (char *) 0, (char *) 0,
3277 else if (!unixy_shell
)
3279 /* new_line is local, must not be freed therefore */
3286 We have to remove all double quotes and to split the line
3287 into distinct arguments because of the strange handling
3288 of builtin commands by cmd: 'echo "bla"' prints "bla"
3289 (with quotes) while 'c:\bin\echo.exe "bla"' prints bla
3290 (without quotes). Some programs like autoconf rely
3291 on the second behaviour. */
3293 len
= strlen (new_line
) + 1;
3295 /* More than 1 arg per character is impossible. */
3296 new_argv
= (char **) xmalloc (len
* sizeof (char *));
3298 /* All the args can fit in a buffer as big as new_line is. */
3299 new_argv
[0] = (char *) xmalloc (len
);
3304 p
= new_argv
[index
];
3307 /* searching for closing quote */
3312 /* remove the quote */
3316 else /* normal character: copy it */
3320 /* searching for opening quote */
3322 # ifndef NO_CMD_DEFAULT
3327 /* remove opening quote */
3332 /* spaces outside of a quoted string: remove them
3333 and start a new argument */
3334 else if (*q
== ' ' || *q
== '\t')
3336 *p
++ = '\0'; /* trailing '\0' for last argument */
3338 /* remove all successive spaces */
3343 while(*q
== ' ' || *q
== '\t');
3345 /* start new argument */
3347 new_argv
[index
] = p
;
3350 /* normal character (no space) outside a quoted string*/
3355 *p
= '\0'; /* trailing '\0' for the last argument */
3356 new_argv
[index
+ 1] = NULL
;
3358 # ifndef NO_CMD_DEFAULT
3359 /* special case: echo x="y"
3360 (e.g. autoconf uses this to determine whether make works)
3361 this is pure idioty but cmd works this way:
3362 if 'echo' and 'x="y"' are two different arguments cmd
3363 will print '"x="y""' but if they are only one argument
3364 cmd will print 'bla="blurb"' as it should be
3365 note: if we do not allow cmd to be the default shell
3366 we do not need this kind of voodoo */
3367 if (index
== 3 && strcasecmp(new_argv
[2], "echo") == 0)
3369 new_argv
[2][4] = ' ';
3374 #elif defined(__MSDOS__)
3377 /* With MSDOS shells, we must construct the command line here
3378 instead of recursively calling ourselves, because we
3379 cannot backslash-escape the special characters (see above). */
3380 new_argv
= (char **) xmalloc (sizeof (char *));
3381 line_len
= strlen (new_line
) - shell_len
- sizeof (minus_c
) + 1;
3382 new_argv
[0] = xmalloc (line_len
+ 1);
3383 strncpy (new_argv
[0],
3384 new_line
+ shell_len
+ sizeof (minus_c
) - 1, line_len
);
3385 new_argv
[0][line_len
] = '\0';
3389 fatal (NILF
, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3390 __FILE__
, __LINE__
);
3393 #endif /* ! AMIGA */
3399 /* Figure out the argument list necessary to run LINE as a command. Try to
3400 avoid using a shell. This routine handles only ' quoting, and " quoting
3401 when no backslash, $ or ` characters are seen in the quotes. Starting
3402 quotes may be escaped with a backslash. If any of the characters in
3403 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3404 is the first word of a line, the shell is used.
3406 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3407 If *RESTP is NULL, newlines will be ignored.
3409 FILE is the target whose commands these are. It is used for
3410 variable expansion for $(SHELL) and $(IFS). */
3413 construct_command_argv (char *line
, char **restp
, struct file
*file
,
3414 char **batch_filename_ptr
)
3428 && (isspace ((unsigned char)*cptr
)))
3433 && (!isspace((unsigned char)*cptr
)))
3438 argv
= (char **)malloc (argc
* sizeof (char *));
3447 && (isspace ((unsigned char)*cptr
)))
3451 DB (DB_JOBS
, ("argv[%d] = [%s]\n", argc
, cptr
));
3452 argv
[argc
++] = cptr
;
3454 && (!isspace((unsigned char)*cptr
)))
3461 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3462 int save
= warn_undefined_variables_flag
;
3463 warn_undefined_variables_flag
= 0;
3465 shell
= allocated_variable_expand_for_file ("$(SHELL)", file
);
3468 * Convert to forward slashes so that construct_command_argv_internal()
3472 char *p
= w32ify (shell
, 0);
3478 static const char *unixroot
= NULL
;
3479 static const char *last_shell
= "";
3480 static int init
= 0;
3483 unixroot
= getenv ("UNIXROOT");
3484 /* unixroot must be NULL or not empty */
3485 if (unixroot
&& unixroot
[0] == '\0') unixroot
= NULL
;
3489 /* if we have an unixroot drive and if shell is not default_shell
3490 (which means it's either cmd.exe or the test has already been
3491 performed) and if shell is an absolute path without drive letter,
3492 try whether it exists e.g.: if "/bin/sh" does not exist use
3493 "$UNIXROOT/bin/sh" instead. */
3494 if (unixroot
&& shell
&& strcmp (shell
, last_shell
) != 0
3495 && (shell
[0] == '/' || shell
[0] == '\\'))
3497 /* trying a new shell, check whether it exists */
3498 size_t size
= strlen (shell
);
3499 char *buf
= xmalloc (size
+ 7);
3500 memcpy (buf
, shell
, size
);
3501 memcpy (buf
+ size
, ".exe", 5); /* including the trailing '\0' */
3502 if (access (shell
, F_OK
) != 0 && access (buf
, F_OK
) != 0)
3504 /* try the same for the unixroot drive */
3505 memmove (buf
+ 2, buf
, size
+ 5);
3506 buf
[0] = unixroot
[0];
3507 buf
[1] = unixroot
[1];
3508 if (access (buf
, F_OK
) == 0)
3509 /* we have found a shell! */
3519 #endif /* __EMX__ */
3521 ifs
= allocated_variable_expand_for_file ("$(IFS)", file
);
3523 warn_undefined_variables_flag
= save
;
3526 argv
= construct_command_argv_internal (line
, restp
, shell
, ifs
, batch_filename_ptr
);
3534 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3536 dup2 (int old
, int new)
3551 #endif /* !HAPE_DUP2 && !_AMIGA */