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 char *default_shell
= "/bin/sh";
58 int batch_mode_shell
= 0;
63 char default_shell
[] = "";
64 int batch_mode_shell
= 0;
66 #elif defined (__riscos__)
68 char default_shell
[] = "";
69 int batch_mode_shell
= 0;
73 char default_shell
[] = "/bin/sh";
74 int batch_mode_shell
= 0;
80 static int execute_by_shell
;
81 static int dos_pid
= 123;
83 int dos_command_running
;
84 #endif /* __MSDOS__ */
87 # include <proto/dos.h>
88 static int amiga_pid
= 123;
89 static int amiga_status
;
90 static char amiga_bname
[32];
91 static int amiga_batch_file
;
96 # include <processes.h>
99 # include <lib$routines.h>
103 # include <windows.h>
105 # include <process.h>
106 # include "sub_proc.h"
108 # include "pathstuff.h"
109 #endif /* WINDOWS32 */
112 # include <process.h>
115 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
116 # include <sys/wait.h>
120 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
121 #else /* Don't have waitpid. */
126 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
127 # endif /* Have wait3. */
128 #endif /* Have waitpid. */
130 #if !defined (wait) && !defined (POSIX)
134 #ifndef HAVE_UNION_WAIT
139 # define WTERMSIG(x) ((x) & 0x7f)
142 # define WCOREDUMP(x) ((x) & 0x80)
145 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
148 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
151 # define WIFEXITED(x) (WTERMSIG (x) == 0)
154 #else /* Have `union wait'. */
156 # define WAIT_T union wait
158 # define WTERMSIG(x) ((x).w_termsig)
161 # define WCOREDUMP(x) ((x).w_coredump)
164 # define WEXITSTATUS(x) ((x).w_retcode)
167 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
170 # define WIFEXITED(x) (WTERMSIG(x) == 0)
173 #endif /* Don't have `union wait'. */
176 static int vms_jobsefnmask
= 0;
179 #ifndef HAVE_UNISTD_H
181 extern int execve ();
182 extern void _exit ();
184 extern int geteuid ();
185 extern int getegid ();
186 extern int setgid ();
187 extern int getgid ();
191 extern char *allocated_variable_expand_for_file
PARAMS ((char *line
, struct file
*file
));
193 extern int getloadavg
PARAMS ((double loadavg
[], int nelem
));
194 extern int start_remote_job
PARAMS ((char **argv
, char **envp
, int stdin_fd
,
195 int *is_remote
, int *id_ptr
, int *used_stdin
));
196 extern int start_remote_job_p
PARAMS ((int));
197 extern int remote_status
PARAMS ((int *exit_code_ptr
, int *signal_ptr
,
198 int *coredump_ptr
, int block
));
200 RETSIGTYPE child_handler
PARAMS ((int));
201 static void free_child
PARAMS ((struct child
*));
202 static void start_job_command
PARAMS ((struct child
*child
));
203 static int load_too_high
PARAMS ((void));
204 static int job_next_command
PARAMS ((struct child
*));
205 static int start_waiting_job
PARAMS ((struct child
*));
207 static void vmsWaitForChildren
PARAMS ((int *));
210 /* Chain of all live (or recently deceased) children. */
212 struct child
*children
= 0;
214 /* Number of children currently running. */
216 unsigned int job_slots_used
= 0;
218 /* Nonzero if the `good' standard input is in use. */
220 static int good_stdin_used
= 0;
222 /* Chain of children waiting to run until the load average goes down. */
224 static struct child
*waiting_jobs
= 0;
226 /* Non-zero if we use a *real* shell (always so on Unix). */
230 /* Number of jobs started in the current second. */
232 unsigned long job_counter
= 0;
237 * The macro which references this function is defined in make.h.
240 w32_kill(int pid
, int sig
)
242 return ((process_kill((HANDLE
)pid
, sig
) == TRUE
) ? 0 : -1);
245 /* This function creates a temporary file name with the given extension
246 * the unixy param controls both the extension and the path separator
247 * return an xmalloc'ed string of a newly created temp file or die. */
249 create_batch_filename(char const *base
, int unixy
)
251 const char *const ext
= unixy
? "sh" : "bat";
252 const char *error
= NULL
;
253 char temp_path
[MAXPATHLEN
]; /* need to know its length */
254 unsigned path_size
= GetTempPath(sizeof temp_path
, temp_path
);
257 const unsigned sizemax
= strlen (base
) + strlen (ext
) + 10;
261 path_size
= GetCurrentDirectory (sizeof temp_path
, temp_path
);
265 while (path_size
> 0 &&
266 path_size
+ sizemax
< sizeof temp_path
&&
269 unsigned size
= sprintf (temp_path
+ path_size
,
271 temp_path
[path_size
- 1] == '\\' ? "" : "\\",
273 HANDLE h
= CreateFile (temp_path
, /* file name */
274 GENERIC_READ
| GENERIC_WRITE
, /* desired access */
275 0, /* no share mode */
276 NULL
, /* default security attributes */
277 CREATE_NEW
, /* creation disposition */
278 FILE_ATTRIBUTE_NORMAL
| /* flags and attributes */
279 FILE_ATTRIBUTE_TEMPORARY
, /* we'll delete it */
280 NULL
); /* no template file */
282 if (h
== INVALID_HANDLE_VALUE
)
284 const DWORD er
= GetLastError();
286 if (er
== ERROR_FILE_EXISTS
|| er
== ERROR_ALREADY_EXISTS
)
289 /* the temporary path is not guaranteed to exist */
290 else if (path_is_dot
== 0)
292 path_size
= GetCurrentDirectory (sizeof temp_path
, temp_path
);
298 error
= map_windows32_error_to_string (er
);
304 const unsigned final_size
= path_size
+ size
+ 1;
305 char *const path
= (char *) xmalloc (final_size
);
306 memcpy (path
, temp_path
, final_size
);
312 for (p
= path
; (ch
= *p
) != 0; ++p
)
316 return path
; /* good return */
321 error
= _("Cannot create a temporary file\n");
327 #endif /* WINDOWS32 */
330 /* returns whether path is assumed to be a unix like shell. */
332 _is_unixy_shell (const char *path
)
334 /* list of non unix shells */
335 const char *known_os2shells
[] = {
347 /* find the rightmost '/' or '\\' */
348 const char *name
= strrchr (path
, '/');
349 const char *p
= strrchr (path
, '\\');
352 if (name
&& p
) /* take the max */
353 name
= (name
> p
) ? name
: p
;
354 else if (p
) /* name must be 0 */
356 else if (!name
) /* name and p must be 0 */
359 if (*name
== '/' || *name
== '\\') name
++;
362 while (known_os2shells
[i
] != NULL
) {
363 if (stricmp (name
, known_os2shells
[i
]) == 0) /* strcasecmp() */
364 return 0; /* not a unix shell */
368 /* in doubt assume a unix like shell */
374 /* Write an error message describing the exit status given in
375 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
376 Append "(ignored)" if IGNORED is nonzero. */
379 child_error (char *target_name
, int exit_code
, int exit_sig
, int coredump
,
382 if (ignored
&& silent_flag
)
386 if (!(exit_code
& 1))
388 (ignored
? _("*** [%s] Error 0x%x (ignored)")
389 : _("*** [%s] Error 0x%x")),
390 target_name
, exit_code
);
393 error (NILF
, ignored
? _("[%s] Error %d (ignored)") :
394 _("*** [%s] Error %d"),
395 target_name
, exit_code
);
397 error (NILF
, "*** [%s] %s%s",
398 target_name
, strsignal (exit_sig
),
399 coredump
? _(" (core dumped)") : "");
404 /* Wait for nchildren children to terminate */
406 vmsWaitForChildren(int *status
)
410 if (!vms_jobsefnmask
)
416 *status
= sys$
wflor (32, vms_jobsefnmask
);
421 /* Set up IO redirection. */
424 vms_redirect (struct dsc$descriptor_s
*desc
, char *fname
, char *ibuf
)
427 extern char *vmsify ();
430 while (isspace ((unsigned char)*ibuf
))
433 while (*ibuf
&& !isspace ((unsigned char)*ibuf
))
436 if (strcmp (fptr
, "/dev/null") != 0)
438 strcpy (fname
, vmsify (fptr
, 0));
439 if (strchr (fname
, '.') == 0)
442 desc
->dsc$w_length
= strlen(fname
);
443 desc
->dsc$a_pointer
= fname
;
444 desc
->dsc$b_dtype
= DSC$K_DTYPE_T
;
445 desc
->dsc$b_class
= DSC$K_CLASS_S
;
448 printf (_("Warning: Empty redirection\n"));
453 /* found apostrophe at (p-1)
454 inc p until after closing apostrophe.
458 vms_handle_apos (char *p
)
462 #define SEPCHARS ",/()= "
478 if (strchr (SEPCHARS
, *p
))
493 /* Handle a dead child. This handler may or may not ever be installed.
495 If we're using the jobserver feature, we need it. First, installing it
496 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
497 read FD to ensure we don't enter another blocking read without reaping all
498 the dead children. In this case we don't need the dead_children count.
500 If we don't have either waitpid or wait3, then make is unreliable, but we
501 use the dead_children count to reap children as best we can. */
503 static unsigned int dead_children
= 0;
506 child_handler (int sig UNUSED
)
517 /* The signal handler must called only once! */
518 signal (SIGCHLD
, SIG_DFL
);
521 /* This causes problems if the SIGCHLD interrupts a printf().
522 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
526 extern int shell_function_pid
, shell_function_completed
;
528 /* Reap all dead children, storing the returned status and the new command
529 state (`cs_finished') in the `file' member of the `struct child' for the
530 dead child, and removing the child from the chain. In addition, if BLOCK
531 nonzero, we block in this function until we've reaped at least one
532 complete child, waiting for it to die if necessary. If ERR is nonzero,
533 print an error message first. */
536 reap_children (int block
, int err
)
539 /* Initially, assume we have some. */
543 # define REAP_MORE reap_more
545 # define REAP_MORE dead_children
550 We have at least one child outstanding OR a shell function in progress,
552 We're blocking for a complete child OR there are more children to reap
554 we'll keep reaping children. */
556 while ((children
!= 0 || shell_function_pid
!= 0)
557 && (block
|| REAP_MORE
))
561 int exit_code
, exit_sig
, coredump
;
562 register struct child
*lastc
, *c
;
564 int any_remote
, any_local
;
568 /* We might block for a while, so let the user know why. */
570 error (NILF
, _("*** Waiting for unfinished jobs...."));
573 /* We have one less dead child to reap. As noted in
574 child_handler() above, this count is completely unimportant for
575 all modern, POSIX-y systems that support wait3() or waitpid().
576 The rest of this comment below applies only to early, broken
577 pre-POSIX systems. We keep the count only because... it's there...
579 The test and decrement are not atomic; if it is compiled into:
580 register = dead_children - 1;
581 dead_children = register;
582 a SIGCHLD could come between the two instructions.
583 child_handler increments dead_children.
584 The second instruction here would lose that increment. But the
585 only effect of dead_children being wrong is that we might wait
586 longer than necessary to reap a child, and lose some parallelism;
587 and we might print the "Waiting for unfinished jobs" message above
588 when not necessary. */
590 if (dead_children
> 0)
594 any_local
= shell_function_pid
!= 0;
595 for (c
= children
; c
!= 0; c
= c
->next
)
597 any_remote
|= c
->remote
;
598 any_local
|= ! c
->remote
;
599 DB (DB_JOBS
, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
600 (unsigned long int) c
, c
->file
->name
,
601 (long) c
->pid
, c
->remote
? _(" (remote)") : ""));
607 /* First, check for remote children. */
609 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 0);
614 /* We got a remote child. */
618 /* A remote status command failed miserably. Punt. */
620 pfatal_with_name ("remote_status");
624 /* No remote children. Check for local children. */
625 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
629 vmsWaitForChildren (&status
);
634 pid
= WAIT_NOHANG (&status
);
637 pid
= wait (&status
);
645 /* The wait*() failed miserably. Punt. */
646 pfatal_with_name ("wait");
650 /* We got a child exit; chop the status word up. */
651 exit_code
= WEXITSTATUS (status
);
652 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
653 coredump
= WCOREDUMP (status
);
655 /* If we have started jobs in this second, remove one. */
661 /* No local children are dead. */
664 if (!block
|| !any_remote
)
667 /* Now try a blocking wait for a remote child. */
668 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 1);
670 goto remote_status_lose
;
672 /* No remote children either. Finally give up. */
675 /* We got a remote child. */
678 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
681 /* Life is very different on MSDOS. */
684 exit_code
= WEXITSTATUS (status
);
685 if (exit_code
== 0xff)
687 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
689 #endif /* __MSDOS__ */
693 status
= amiga_status
;
694 exit_code
= amiga_status
;
706 /* wait for anything to finish */
707 hPID
= process_wait_for_any();
711 /* was an error found on this process? */
712 err
= process_last_err(hPID
);
715 exit_code
= process_exit_code(hPID
);
718 fprintf(stderr
, "make (e=%d): %s",
719 exit_code
, map_windows32_error_to_string(exit_code
));
722 exit_sig
= process_signal(hPID
);
724 /* cleanup process */
725 process_cleanup(hPID
);
731 #endif /* WINDOWS32 */
734 /* Check if this is the child of the `shell' function. */
735 if (!remote
&& pid
== shell_function_pid
)
737 /* It is. Leave an indicator for the `shell' function. */
738 if (exit_sig
== 0 && exit_code
== 127)
739 shell_function_completed
= -1;
741 shell_function_completed
= 1;
745 child_failed
= exit_sig
!= 0 || exit_code
!= 0;
747 /* Search for a child matching the deceased one. */
749 for (c
= children
; c
!= 0; lastc
= c
, c
= c
->next
)
750 if (c
->remote
== remote
&& c
->pid
== pid
)
754 /* An unknown child died.
755 Ignore it; it was inherited from our invoker. */
758 DB (DB_JOBS
, (child_failed
759 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
760 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
761 (unsigned long int) c
, (long) c
->pid
,
762 c
->remote
? _(" (remote)") : ""));
764 if (c
->sh_batch_file
) {
765 DB (DB_JOBS
, (_("Cleaning up temp batch file %s\n"),
768 /* just try and remove, don't care if this fails */
769 remove (c
->sh_batch_file
);
771 /* all done with memory */
772 free (c
->sh_batch_file
);
773 c
->sh_batch_file
= NULL
;
776 /* If this child had the good stdin, say it is now free. */
780 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
782 /* The commands failed. Write an error message,
783 delete non-precious targets, and abort. */
784 static int delete_on_error
= -1;
785 child_error (c
->file
->name
, exit_code
, exit_sig
, coredump
, 0);
786 c
->file
->update_status
= 2;
787 if (delete_on_error
== -1)
789 struct file
*f
= lookup_file (".DELETE_ON_ERROR");
790 delete_on_error
= f
!= 0 && f
->is_target
;
792 if (exit_sig
!= 0 || delete_on_error
)
793 delete_child_targets (c
);
799 /* The commands failed, but we don't care. */
800 child_error (c
->file
->name
,
801 exit_code
, exit_sig
, coredump
, 1);
805 /* If there are more commands to run, try to start them. */
806 if (job_next_command (c
))
808 if (handling_fatal_signal
)
810 /* Never start new commands while we are dying.
811 Since there are more commands that wanted to be run,
812 the target was not completely remade. So we treat
813 this as if a command had failed. */
814 c
->file
->update_status
= 2;
818 /* Check again whether to start remotely.
819 Whether or not we want to changes over time.
820 Also, start_remote_job may need state set up
821 by start_remote_job_p. */
822 c
->remote
= start_remote_job_p (0);
823 start_job_command (c
);
824 /* Fatal signals are left blocked in case we were
825 about to put that child on the chain. But it is
826 already there, so it is safe for a fatal signal to
827 arrive now; it will clean up this child's targets. */
829 if (c
->file
->command_state
== cs_running
)
830 /* We successfully started the new command.
831 Loop to reap more children. */
835 if (c
->file
->update_status
!= 0)
836 /* We failed to start the commands. */
837 delete_child_targets (c
);
840 /* There are no more commands. We got through them all
841 without an unignored error. Now the target has been
842 successfully updated. */
843 c
->file
->update_status
= 0;
846 /* When we get here, all the commands for C->file are finished
847 (or aborted) and C->file->update_status contains 0 or 2. But
848 C->file->command_state is still cs_running if all the commands
849 ran; notice_finish_file looks for cs_running to tell it that
850 it's interesting to check the file's modtime again now. */
852 if (! handling_fatal_signal
)
853 /* Notice if the target of the commands has been changed.
854 This also propagates its values for command_state and
855 update_status to its also_make files. */
856 notice_finished_file (c
->file
);
858 DB (DB_JOBS
, (_("Removing child 0x%08lx PID %ld%s from chain.\n"),
859 (unsigned long int) c
, (long) c
->pid
,
860 c
->remote
? _(" (remote)") : ""));
862 /* Block fatal signals while frobnicating the list, so that
863 children and job_slots_used are always consistent. Otherwise
864 a fatal signal arriving after the child is off the chain and
865 before job_slots_used is decremented would believe a child was
866 live and call reap_children again. */
869 /* There is now another slot open. */
870 if (job_slots_used
> 0)
873 /* Remove the child from the chain and free it. */
877 lastc
->next
= c
->next
;
883 /* If the job failed, and the -k flag was not given, die,
884 unless we are already in the process of dying. */
885 if (!err
&& child_failed
&& !keep_going_flag
&&
886 /* fatal_error_signal will die with the right signal. */
887 !handling_fatal_signal
)
890 /* Only block for one child. */
897 /* Free the storage allocated for CHILD. */
900 free_child (struct child
*child
)
902 /* If this child is the only one it was our "free" job, so don't put a
903 token back for it. This child has already been removed from the list,
904 so if there any left this wasn't the last one. */
906 if (job_fds
[1] >= 0 && children
)
911 /* Write a job token back to the pipe. */
913 EINTRLOOP (r
, write (job_fds
[1], &token
, 1));
915 pfatal_with_name (_("write jobserver"));
917 DB (DB_JOBS
, (_("Released token for child 0x%08lx (%s).\n"),
918 (unsigned long int) child
, child
->file
->name
));
921 if (handling_fatal_signal
) /* Don't bother free'ing if about to die. */
924 if (child
->command_lines
!= 0)
926 register unsigned int i
;
927 for (i
= 0; i
< child
->file
->cmds
->ncommand_lines
; ++i
)
928 free (child
->command_lines
[i
]);
929 free ((char *) child
->command_lines
);
932 if (child
->environment
!= 0)
934 register char **ep
= child
->environment
;
937 free ((char *) child
->environment
);
940 free ((char *) child
);
944 extern sigset_t fatal_signal_set
;
951 (void) sigprocmask (SIG_BLOCK
, &fatal_signal_set
, (sigset_t
*) 0);
953 # ifdef HAVE_SIGSETMASK
954 (void) sigblock (fatal_signal_mask
);
964 sigemptyset (&empty
);
965 sigprocmask (SIG_SETMASK
, &empty
, (sigset_t
*) 0);
969 #ifdef MAKE_JOBSERVER
970 /* Set the child handler action flags to FLAGS. */
972 set_child_handler_action_flags (int flags
)
975 bzero ((char *) &sa
, sizeof sa
);
976 sa
.sa_handler
= child_handler
;
979 sigaction (SIGCHLD
, &sa
, NULL
);
981 #if defined SIGCLD && SIGCLD != SIGCHLD
982 sigaction (SIGCLD
, &sa
, NULL
);
988 /* Start a job to run the commands specified in CHILD.
989 CHILD is updated to reflect the commands and ID of the child process.
991 NOTE: On return fatal signals are blocked! The caller is responsible
992 for calling `unblock_sigs', once the new child is safely on the chain so
993 it can be cleaned up in the event of a fatal signal. */
996 start_job_command (struct child
*child
)
999 static int bad_stdin
= -1;
1009 /* If we have a completely empty commandset, stop now. */
1010 if (!child
->command_ptr
)
1013 /* Combine the flags parsed for the line itself with
1014 the flags specified globally for this target. */
1015 flags
= (child
->file
->command_flags
1016 | child
->file
->cmds
->lines_flags
[child
->command_line
- 1]);
1018 p
= child
->command_ptr
;
1019 child
->noerror
= flags
& COMMANDS_NOERROR
;
1024 flags
|= COMMANDS_SILENT
;
1026 flags
|= COMMANDS_RECURSE
;
1029 else if (!isblank ((unsigned char)*p
))
1034 /* Update the file's command flags with any new ones we found. We only
1035 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
1036 now marking more commands recursive than should be in the case of
1037 multiline define/endef scripts where only one line is marked "+". In
1038 order to really fix this, we'll have to keep a lines_flags for every
1039 actual line, after expansion. */
1040 child
->file
->cmds
->lines_flags
[child
->command_line
- 1]
1041 |= flags
& COMMANDS_RECURSE
;
1043 /* Figure out an argument list from this command line. */
1050 argv
= construct_command_argv (p
, &end
, child
->file
, &child
->sh_batch_file
);
1053 child
->command_ptr
= NULL
;
1057 child
->command_ptr
= end
;
1061 /* If -q was given, say that updating `failed' if there was any text on the
1062 command line, or `succeeded' otherwise. The exit status of 1 tells the
1063 user that -q is saying `something to do'; the exit status for a random
1065 if (argv
!= 0 && question_flag
&& !(flags
& COMMANDS_RECURSE
))
1069 free ((char *) argv
);
1071 child
->file
->update_status
= 1;
1072 notice_finished_file (child
->file
);
1076 if (touch_flag
&& !(flags
& COMMANDS_RECURSE
))
1078 /* Go on to the next command. It might be the recursive one.
1079 We construct ARGV only to find the end of the command line. */
1084 free ((char *) argv
);
1094 execute_by_shell
= 0; /* in case construct_command_argv sets it */
1096 /* This line has no commands. Go to the next. */
1097 if (job_next_command (child
))
1098 start_job_command (child
);
1101 /* No more commands. Make sure we're "running"; we might not be if
1102 (e.g.) all commands were skipped due to -n. */
1103 set_command_state (child
->file
, cs_running
);
1104 child
->file
->update_status
= 0;
1105 notice_finished_file (child
->file
);
1110 /* Print out the command. If silent, we call `message' with null so it
1111 can log the working directory before the command's own error messages
1114 message (0, (just_print_flag
|| (!(flags
& COMMANDS_SILENT
) && !silent_flag
))
1115 ? "%s" : (char *) 0, p
);
1117 /* Tell update_goal_chain that a command has been started on behalf of
1118 this target. It is important that this happens here and not in
1119 reap_children (where we used to do it), because reap_children might be
1120 reaping children from a different target. We want this increment to
1121 guaranteedly indicate that a command was started for the dependency
1122 chain (i.e., update_file recursion chain) we are processing. */
1126 /* Optimize an empty command. People use this for timestamp rules,
1127 so avoid forking a useless shell. Do this after we increment
1128 commands_started so make still treats this special case as if it
1129 performed some action (makes a difference as to what messages are
1132 #if !defined(VMS) && !defined(_AMIGA)
1134 #if defined __MSDOS__ || defined (__EMX__)
1135 unixy_shell
/* the test is complicated and we already did it */
1137 (argv
[0] && !strcmp (argv
[0], "/bin/sh"))
1140 && argv
[1][0] == '-' && argv
[1][1] == 'c' && argv
[1][2] == '\0')
1141 && (argv
[2] && argv
[2][0] == ':' && argv
[2][1] == '\0')
1145 free ((char *) argv
);
1148 #endif /* !VMS && !_AMIGA */
1150 /* If -n was given, recurse to get the next line in the sequence. */
1152 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
))
1156 free ((char *) argv
);
1161 /* Flush the output streams so they won't have things written twice. */
1167 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1169 /* Set up a bad standard input that reads from a broken pipe. */
1171 if (bad_stdin
== -1)
1173 /* Make a file descriptor that is the read end of a broken pipe.
1174 This will be used for some children's standard inputs. */
1178 /* Close the write side. */
1179 (void) close (pd
[1]);
1180 /* Save the read side. */
1183 /* Set the descriptor to close on exec, so it does not litter any
1184 child's descriptor table. When it is dup2'd onto descriptor 0,
1185 that descriptor will not close on exec. */
1186 CLOSE_ON_EXEC (bad_stdin
);
1190 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1192 /* Decide whether to give this child the `good' standard input
1193 (one that points to the terminal or whatever), or the `bad' one
1194 that points to the read side of a broken pipe. */
1196 child
->good_stdin
= !good_stdin_used
;
1197 if (child
->good_stdin
)
1198 good_stdin_used
= 1;
1205 /* Set up the environment for the child. */
1206 if (child
->environment
== 0)
1207 child
->environment
= target_environment (child
->file
);
1210 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1213 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1216 int is_remote
, id
, used_stdin
;
1217 if (start_remote_job (argv
, child
->environment
,
1218 child
->good_stdin
? 0 : bad_stdin
,
1219 &is_remote
, &id
, &used_stdin
))
1220 /* Don't give up; remote execution may fail for various reasons. If
1221 so, simply run the job locally. */
1225 if (child
->good_stdin
&& !used_stdin
)
1227 child
->good_stdin
= 0;
1228 good_stdin_used
= 0;
1230 child
->remote
= is_remote
;
1237 /* Fork the child process. */
1239 char **parent_environ
;
1248 if (!child_execute_job (argv
, child
)) {
1250 perror_with_name ("vfork", "");
1256 parent_environ
= environ
;
1259 /* If we aren't running a recursive command and we have a jobserver
1260 pipe, close it before exec'ing. */
1261 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1263 CLOSE_ON_EXEC (job_fds
[0]);
1264 CLOSE_ON_EXEC (job_fds
[1]);
1267 CLOSE_ON_EXEC (job_rfd
);
1269 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1270 child
->pid
= child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1271 argv
, child
->environment
);
1276 perror_with_name ("spawn", "");
1280 /* undo CLOSE_ON_EXEC() after the child process has been started */
1281 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1283 fcntl (job_fds
[0], F_SETFD
, 0);
1284 fcntl (job_fds
[1], F_SETFD
, 0);
1287 fcntl (job_rfd
, F_SETFD
, 0);
1289 #else /* !__EMX__ */
1291 child
->pid
= vfork ();
1292 environ
= parent_environ
; /* Restore value child may have clobbered. */
1293 if (child
->pid
== 0)
1295 /* We are the child side. */
1298 /* If we aren't running a recursive command and we have a jobserver
1299 pipe, close it before exec'ing. */
1300 if (!(flags
& COMMANDS_RECURSE
) && job_fds
[0] >= 0)
1308 child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
1309 argv
, child
->environment
);
1311 else if (child
->pid
< 0)
1315 perror_with_name ("vfork", "");
1318 # endif /* !__EMX__ */
1322 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1330 /* We call `system' to do the job of the SHELL, since stock DOS
1331 shell is too dumb. Our `system' knows how to handle long
1332 command lines even if pipes/redirection is needed; it will only
1333 call COMMAND.COM when its internal commands are used. */
1334 if (execute_by_shell
)
1336 char *cmdline
= argv
[0];
1337 /* We don't have a way to pass environment to `system',
1338 so we need to save and restore ours, sigh... */
1339 char **parent_environ
= environ
;
1341 environ
= child
->environment
;
1343 /* If we have a *real* shell, tell `system' to call
1344 it to do everything for us. */
1347 /* A *real* shell on MSDOS may not support long
1348 command lines the DJGPP way, so we must use `system'. */
1349 cmdline
= argv
[2]; /* get past "shell -c" */
1352 dos_command_running
= 1;
1353 proc_return
= system (cmdline
);
1354 environ
= parent_environ
;
1355 execute_by_shell
= 0; /* for the next time */
1359 dos_command_running
= 1;
1360 proc_return
= spawnvpe (P_WAIT
, argv
[0], argv
, child
->environment
);
1363 /* Need to unblock signals before turning off
1364 dos_command_running, so that child's signals
1365 will be treated as such (see fatal_error_signal). */
1367 dos_command_running
= 0;
1369 /* If the child got a signal, dos_status has its
1370 high 8 bits set, so be careful not to alter them. */
1371 if (proc_return
== -1)
1374 dos_status
|= (proc_return
& 0xff);
1376 child
->pid
= dos_pid
++;
1378 #endif /* __MSDOS__ */
1380 amiga_status
= MyExecute (argv
);
1383 child
->pid
= amiga_pid
++;
1384 if (amiga_batch_file
)
1386 amiga_batch_file
= 0;
1387 DeleteFile (amiga_bname
); /* Ignore errors. */
1395 /* make UNC paths safe for CreateProcess -- backslash format */
1397 if (arg0
&& arg0
[0] == '/' && arg0
[1] == '/')
1398 for ( ; arg0
&& *arg0
; arg0
++)
1402 /* make sure CreateProcess() has Path it needs */
1403 sync_Path_environment();
1405 hPID
= process_easy(argv
, child
->environment
);
1407 if (hPID
!= INVALID_HANDLE_VALUE
)
1408 child
->pid
= (int) hPID
;
1413 _("process_easy() failed failed to launch process (e=%d)\n"),
1414 process_last_err(hPID
));
1415 for (i
= 0; argv
[i
]; i
++)
1416 fprintf(stderr
, "%s ", argv
[i
]);
1417 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
1420 #endif /* WINDOWS32 */
1421 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1423 /* Bump the number of jobs started in this second. */
1426 /* We are the parent side. Set the state to
1427 say the commands are running and return. */
1429 set_command_state (child
->file
, cs_running
);
1431 /* Free the storage used by the child's argument list. */
1434 free ((char *) argv
);
1440 child
->file
->update_status
= 2;
1441 notice_finished_file (child
->file
);
1445 /* Try to start a child running.
1446 Returns nonzero if the child was started (and maybe finished), or zero if
1447 the load was too high and the child was put on the `waiting_jobs' chain. */
1450 start_waiting_job (struct child
*c
)
1452 struct file
*f
= c
->file
;
1454 /* If we can start a job remotely, we always want to, and don't care about
1455 the local load average. We record that the job should be started
1456 remotely in C->remote for start_job_command to test. */
1458 c
->remote
= start_remote_job_p (1);
1460 /* If we are running at least one job already and the load average
1461 is too high, make this one wait. */
1462 if (!c
->remote
&& job_slots_used
> 0 && load_too_high ())
1464 /* Put this child on the chain of children waiting for the load average
1466 set_command_state (f
, cs_running
);
1467 c
->next
= waiting_jobs
;
1472 /* Start the first command; reap_children will run later command lines. */
1473 start_job_command (c
);
1475 switch (f
->command_state
)
1479 DB (DB_JOBS
, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1480 (unsigned long int) c
, c
->file
->name
,
1481 (long) c
->pid
, c
->remote
? _(" (remote)") : ""));
1483 /* One more job slot is in use. */
1488 case cs_not_started
:
1489 /* All the command lines turned out to be empty. */
1490 f
->update_status
= 0;
1494 notice_finished_file (f
);
1499 assert (f
->command_state
== cs_finished
);
1506 /* Create a `struct child' for FILE and start its commands running. */
1509 new_job (struct file
*file
)
1511 register struct commands
*cmds
= file
->cmds
;
1512 register struct child
*c
;
1514 register unsigned int i
;
1516 /* Let any previously decided-upon jobs that are waiting
1517 for the load to go down start before this new one. */
1518 start_waiting_jobs ();
1520 /* Reap any children that might have finished recently. */
1521 reap_children (0, 0);
1523 /* Chop the commands up into lines if they aren't already. */
1524 chop_commands (cmds
);
1526 /* Expand the command lines and store the results in LINES. */
1527 lines
= (char **) xmalloc (cmds
->ncommand_lines
* sizeof (char *));
1528 for (i
= 0; i
< cmds
->ncommand_lines
; ++i
)
1530 /* Collapse backslash-newline combinations that are inside variable
1531 or function references. These are left alone by the parser so
1532 that they will appear in the echoing of commands (where they look
1533 nice); and collapsed by construct_command_argv when it tokenizes.
1534 But letting them survive inside function invocations loses because
1535 we don't want the functions to see them as part of the text. */
1537 char *in
, *out
, *ref
;
1539 /* IN points to where in the line we are scanning.
1540 OUT points to where in the line we are writing.
1541 When we collapse a backslash-newline combination,
1542 IN gets ahead of OUT. */
1544 in
= out
= cmds
->command_lines
[i
];
1545 while ((ref
= strchr (in
, '$')) != 0)
1547 ++ref
; /* Move past the $. */
1550 /* Copy the text between the end of the last chunk
1551 we processed (where IN points) and the new chunk
1552 we are about to process (where REF points). */
1553 bcopy (in
, out
, ref
- in
);
1555 /* Move both pointers past the boring stuff. */
1559 if (*ref
== '(' || *ref
== '{')
1561 char openparen
= *ref
;
1562 char closeparen
= openparen
== '(' ? ')' : '}';
1566 *out
++ = *in
++; /* Copy OPENPAREN. */
1567 /* IN now points past the opening paren or brace.
1568 Count parens or braces until it is matched. */
1572 if (*in
== closeparen
&& --count
< 0)
1574 else if (*in
== '\\' && in
[1] == '\n')
1576 /* We have found a backslash-newline inside a
1577 variable or function reference. Eat it and
1578 any following whitespace. */
1581 for (p
= in
- 1; p
> ref
&& *p
== '\\'; --p
)
1585 /* There were two or more backslashes, so this is
1586 not really a continuation line. We don't collapse
1587 the quoting backslashes here as is done in
1588 collapse_continuations, because the line will
1589 be collapsed again after expansion. */
1593 /* Skip the backslash, newline and
1594 any following whitespace. */
1595 in
= next_token (in
+ 2);
1597 /* Discard any preceding whitespace that has
1598 already been written to the output. */
1600 && isblank ((unsigned char)out
[-1]))
1603 /* Replace it all with a single space. */
1609 if (*in
== openparen
)
1618 /* There are no more references in this line to worry about.
1619 Copy the remaining uninteresting text to the output. */
1623 /* Finally, expand the line. */
1624 lines
[i
] = allocated_variable_expand_for_file (cmds
->command_lines
[i
],
1628 /* Start the command sequence, record it in a new
1629 `struct child', and add that to the chain. */
1631 c
= (struct child
*) xmalloc (sizeof (struct child
));
1632 bzero ((char *)c
, sizeof (struct child
));
1634 c
->command_lines
= lines
;
1635 c
->sh_batch_file
= NULL
;
1637 /* Fetch the first command line to be run. */
1638 job_next_command (c
);
1640 /* Wait for a job slot to be freed up. If we allow an infinite number
1641 don't bother; also job_slots will == 0 if we're using the jobserver. */
1644 while (job_slots_used
== job_slots
)
1645 reap_children (1, 0);
1647 #ifdef MAKE_JOBSERVER
1648 /* If we are controlling multiple jobs make sure we have a token before
1649 starting the child. */
1651 /* This can be inefficient. There's a decent chance that this job won't
1652 actually have to run any subprocesses: the command script may be empty
1653 or otherwise optimized away. It would be nice if we could defer
1654 obtaining a token until just before we need it, in start_job_command.
1655 To do that we'd need to keep track of whether we'd already obtained a
1656 token (since start_job_command is called for each line of the job, not
1657 just once). Also more thought needs to go into the entire algorithm;
1658 this is where the old parallel job code waits, so... */
1660 else if (job_fds
[0] >= 0)
1667 DB (DB_JOBS
, ("Need a job token; we %shave children\n",
1668 children
? "" : "don't "));
1670 /* If we don't already have a job started, use our "free" token. */
1674 /* Read a token. As long as there's no token available we'll block.
1675 We enable interruptible system calls before the read(2) so that if
1676 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1677 we can process the death(s) and return tokens to the free pool.
1679 Once we return from the read, we immediately reinstate restartable
1680 system calls. This allows us to not worry about checking for
1681 EINTR on all the other system calls in the program.
1683 There is one other twist: there is a span between the time
1684 reap_children() does its last check for dead children and the time
1685 the read(2) call is entered, below, where if a child dies we won't
1686 notice. This is extremely serious as it could cause us to
1687 deadlock, given the right set of events.
1689 To avoid this, we do the following: before we reap_children(), we
1690 dup(2) the read FD on the jobserver pipe. The read(2) call below
1691 uses that new FD. In the signal handler, we close that FD. That
1692 way, if a child dies during the section mentioned above, the
1693 read(2) will be invoked with an invalid FD and will return
1694 immediately with EBADF. */
1696 /* Make sure we have a dup'd FD. */
1699 DB (DB_JOBS
, ("Duplicate the job FD\n"));
1700 job_rfd
= dup (job_fds
[0]);
1703 /* Reap anything that's currently waiting. */
1704 reap_children (0, 0);
1706 /* If our "free" token has become available, use it. */
1710 /* Set interruptible system calls, and read() for a job token. */
1711 set_child_handler_action_flags (0);
1712 got_token
= read (job_rfd
, &token
, 1);
1713 saved_errno
= errno
;
1715 /* The child handler must be turned off here. */
1716 signal (SIGCHLD
, SIG_DFL
);
1718 set_child_handler_action_flags (SA_RESTART
);
1720 /* If we got one, we're done here. */
1723 DB (DB_JOBS
, (_("Obtained token for child 0x%08lx (%s).\n"),
1724 (unsigned long int) c
, c
->file
->name
));
1728 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1729 go back and reap_children(), and try again. */
1730 errno
= saved_errno
;
1731 if (errno
!= EINTR
&& errno
!= EBADF
)
1732 pfatal_with_name (_("read jobs pipe"));
1734 DB (DB_JOBS
, ("Read returned EBADF.\n"));
1738 /* The job is now primed. Start it running.
1739 (This will notice if there are in fact no commands.) */
1740 (void) start_waiting_job (c
);
1742 if (job_slots
== 1 || not_parallel
)
1743 /* Since there is only one job slot, make things run linearly.
1744 Wait for the child to die, setting the state to `cs_finished'. */
1745 while (file
->command_state
== cs_running
)
1746 reap_children (1, 0);
1751 /* Move CHILD's pointers to the next command for it to execute.
1752 Returns nonzero if there is another command. */
1755 job_next_command (struct child
*child
)
1757 while (child
->command_ptr
== 0 || *child
->command_ptr
== '\0')
1759 /* There are no more lines in the expansion of this line. */
1760 if (child
->command_line
== child
->file
->cmds
->ncommand_lines
)
1762 /* There are no more lines to be expanded. */
1763 child
->command_ptr
= 0;
1767 /* Get the next line to run. */
1768 child
->command_ptr
= child
->command_lines
[child
->command_line
++];
1773 /* Determine if the load average on the system is too high to start a new job.
1774 The real system load average is only recomputed once a second. However, a
1775 very parallel make can easily start tens or even hundreds of jobs in a
1776 second, which brings the system to its knees for a while until that first
1777 batch of jobs clears out.
1779 To avoid this we use a weighted algorithm to try to account for jobs which
1780 have been started since the last second, and guess what the load average
1781 would be now if it were computed.
1783 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1786 ! calculate something load-oid and add to the observed sys.load,
1787 ! so that latter can catch up:
1788 ! - every job started increases jobctr;
1789 ! - every dying job decreases a positive jobctr;
1790 ! - the jobctr value gets zeroed every change of seconds,
1791 ! after its value*weight_b is stored into the 'backlog' value last_sec
1792 ! - weight_a times the sum of jobctr and last_sec gets
1793 ! added to the observed sys.load.
1795 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1796 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1797 ! sub-shelled commands (rm, echo, sed...) for tests.
1798 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1799 ! resulted in significant excession of the load limit, raising it
1800 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1801 ! reach the limit in most test cases.
1803 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1804 ! exceeding the limit for longer-running stuff (compile jobs in
1805 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1806 ! small jobs' effects.
1810 #define LOAD_WEIGHT_A 0.25
1811 #define LOAD_WEIGHT_B 0.25
1814 load_too_high (void)
1816 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
1819 static double last_sec
;
1820 static time_t last_now
;
1824 if (max_load_average
< 0)
1827 /* Find the real system load average. */
1829 if (getloadavg (&load
, 1) != 1)
1831 static int lossage
= -1;
1832 /* Complain only once for the same error. */
1833 if (lossage
== -1 || errno
!= lossage
)
1836 /* An errno value of zero means getloadavg is just unsupported. */
1838 _("cannot enforce load limits on this operating system"));
1840 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1847 /* If we're in a new second zero the counter and correct the backlog
1848 value. Only keep the backlog for one extra second; after that it's 0. */
1852 if (last_now
== now
- 1)
1853 last_sec
= LOAD_WEIGHT_B
* job_counter
;
1861 /* Try to guess what the load would be right now. */
1862 guess
= load
+ (LOAD_WEIGHT_A
* (job_counter
+ last_sec
));
1864 DB (DB_JOBS
, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1865 guess
, load
, max_load_average
));
1867 return guess
>= max_load_average
;
1871 /* Start jobs that are waiting for the load to be lower. */
1874 start_waiting_jobs (void)
1878 if (waiting_jobs
== 0)
1883 /* Check for recently deceased descendants. */
1884 reap_children (0, 0);
1886 /* Take a job off the waiting list. */
1888 waiting_jobs
= job
->next
;
1890 /* Try to start that job. We break out of the loop as soon
1891 as start_waiting_job puts one back on the waiting list. */
1893 while (start_waiting_job (job
) && waiting_jobs
!= 0);
1900 #include <descrip.h>
1903 /* This is called as an AST when a child process dies (it won't get
1904 interrupted by anything except a higher level AST).
1906 int vmsHandleChildTerm(struct child
*child
)
1909 register struct child
*lastc
, *c
;
1912 vms_jobsefnmask
&= ~(1 << (child
->efn
- 32));
1914 lib$
free_ef(&child
->efn
);
1916 (void) sigblock (fatal_signal_mask
);
1918 child_failed
= !(child
->cstatus
& 1 || ((child
->cstatus
& 7) == 0));
1920 /* Search for a child matching the deceased one. */
1922 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1923 for (c
= children
; c
!= 0 && c
!= child
; lastc
= c
, c
= c
->next
);
1928 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
1930 /* The commands failed. Write an error message,
1931 delete non-precious targets, and abort. */
1932 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 0);
1933 c
->file
->update_status
= 1;
1934 delete_child_targets (c
);
1940 /* The commands failed, but we don't care. */
1941 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 1);
1945 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1946 /* If there are more commands to run, try to start them. */
1949 switch (c
->file
->command_state
)
1952 /* Successfully started. */
1956 if (c
->file
->update_status
!= 0) {
1957 /* We failed to start the commands. */
1958 delete_child_targets (c
);
1963 error (NILF
, _("internal error: `%s' command_state"),
1968 #endif /* RECURSIVEJOBS */
1971 /* Set the state flag to say the commands have finished. */
1972 c
->file
->command_state
= cs_finished
;
1973 notice_finished_file (c
->file
);
1975 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1976 /* Remove the child from the chain and free it. */
1980 lastc
->next
= c
->next
;
1982 #endif /* RECURSIVEJOBS */
1984 /* There is now another slot open. */
1985 if (job_slots_used
> 0)
1988 /* If the job failed, and the -k flag was not given, die. */
1989 if (child_failed
&& !keep_going_flag
)
1992 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask
));
1998 Spawn a process executing the command in ARGV and return its pid. */
2000 #define MAXCMDLEN 200
2002 /* local helpers to make ctrl+c and ctrl+y working, see below */
2004 #include <libclidef.h>
2007 static int ctrlMask
= LIB$M_CLI_CTRLY
;
2008 static int oldCtrlMask
;
2009 static int setupYAstTried
= 0;
2010 static int pidToAbort
= 0;
2013 static void reEnableAst(void) {
2014 lib$
enable_ctrl (&oldCtrlMask
,0);
2017 static astHandler (void) {
2019 sys$
forcex (&pidToAbort
, 0, SS$_ABORT
);
2022 kill (getpid(),SIGQUIT
);
2025 static void tryToSetupYAst(void) {
2026 $
DESCRIPTOR(inputDsc
,"SYS$COMMAND");
2029 short int status
, count
;
2036 status
= sys$
assign(&inputDsc
,&chan
,0,0);
2037 if (!(status
&SS$_NORMAL
)) {
2042 status
= sys$
qiow (0, chan
, IO$_SETMODE
|IO$M_CTRLYAST
,&iosb
,0,0,
2043 astHandler
,0,0,0,0,0);
2044 if (status
==SS$_NORMAL
)
2045 status
= iosb
.status
;
2046 if (status
==SS$_ILLIOFUNC
|| status
==SS$_NOPRIV
) {
2048 #ifdef CTRLY_ENABLED_ANYWAY
2050 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
2055 else if (!(status
&SS$_NORMAL
)) {
2061 /* called from AST handler ? */
2062 if (setupYAstTried
>1)
2064 if (atexit(reEnableAst
))
2066 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
2067 status
= lib$
disable_ctrl (&ctrlMask
, &oldCtrlMask
);
2068 if (!(status
&SS$_NORMAL
)) {
2074 child_execute_job (char *argv
, struct child
*child
)
2077 static struct dsc$descriptor_s cmddsc
;
2078 static struct dsc$descriptor_s pnamedsc
;
2079 static struct dsc$descriptor_s ifiledsc
;
2080 static struct dsc$descriptor_s ofiledsc
;
2081 static struct dsc$descriptor_s efiledsc
;
2082 int have_redirection
= 0;
2083 int have_newline
= 0;
2085 int spflags
= CLI$M_NOWAIT
;
2087 char *cmd
= alloca (strlen (argv
) + 512), *p
, *q
;
2088 char ifile
[256], ofile
[256], efile
[256];
2093 /* Parse IO redirection. */
2099 DB (DB_JOBS
, ("child_execute_job (%s)\n", argv
));
2101 while (isspace ((unsigned char)*argv
))
2107 sprintf (procname
, "GMAKE_%05x", getpid () & 0xfffff);
2108 pnamedsc
.dsc$w_length
= strlen(procname
);
2109 pnamedsc
.dsc$a_pointer
= procname
;
2110 pnamedsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
2111 pnamedsc
.dsc$b_class
= DSC$K_CLASS_S
;
2114 /* Handle comments and redirection. */
2115 for (p
= argv
, q
= cmd
; *p
; p
++, q
++)
2118 in_string
= !in_string
;
2134 if (isspace ((unsigned char)*p
))
2136 do { p
++; } while (isspace ((unsigned char)*p
));
2142 p
= vms_redirect (&ifiledsc
, ifile
, p
);
2144 have_redirection
= 1;
2147 have_redirection
= 1;
2151 if (strncmp (p
, ">&1", 3) == 0)
2154 strcpy (efile
, "sys$output");
2155 efiledsc
.dsc$w_length
= strlen(efile
);
2156 efiledsc
.dsc$a_pointer
= efile
;
2157 efiledsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
2158 efiledsc
.dsc$b_class
= DSC$K_CLASS_S
;
2162 p
= vms_redirect (&efiledsc
, efile
, p
);
2167 p
= vms_redirect (&ofiledsc
, ofile
, p
);
2179 while (isspace ((unsigned char)*--q
))
2182 if (strncmp (cmd
, "builtin_", 8) == 0)
2184 child
->pid
= 270163;
2188 DB (DB_JOBS
, (_("BUILTIN [%s][%s]\n"), cmd
, cmd
+8));
2194 && ((*(p
+2) == ' ') || (*(p
+2) == '\t')))
2197 while ((*p
== ' ') || (*p
== '\t'))
2199 DB (DB_JOBS
, (_("BUILTIN CD %s\n"), p
));
2205 else if ((*(p
) == 'r')
2207 && ((*(p
+2) == ' ') || (*(p
+2) == '\t')))
2213 while ((*p
== ' ') || (*p
== '\t'))
2217 DB (DB_JOBS
, (_("BUILTIN RM %s\n"), p
));
2238 printf(_("Unknown builtin command '%s'\n"), cmd
);
2244 /* Create a *.com file if either the command is too long for
2245 lib$spawn, or the command contains a newline, or if redirection
2246 is desired. Forcing commands with newlines into DCLs allows to
2247 store search lists on user mode logicals. */
2249 if (strlen (cmd
) > MAXCMDLEN
2250 || (have_redirection
!= 0)
2251 || (have_newline
!= 0))
2256 int alevel
= 0; /* apostrophe level */
2258 if (strlen (cmd
) == 0)
2260 printf (_("Error, empty command\n"));
2265 outfile
= open_tmpfile (&comname
, "sys$scratch:CMDXXXXXX.COM");
2267 pfatal_with_name (_("fopen (temporary file)"));
2271 fprintf (outfile
, "$ assign/user %s sys$input\n", ifile
);
2272 DB (DB_JOBS
, (_("Redirected input from %s\n"), ifile
));
2273 ifiledsc
.dsc$w_length
= 0;
2278 fprintf (outfile
, "$ define sys$error %s\n", efile
);
2279 DB (DB_JOBS
, (_("Redirected error to %s\n"), efile
));
2280 efiledsc
.dsc$w_length
= 0;
2285 fprintf (outfile
, "$ define sys$output %s\n", ofile
);
2286 DB (DB_JOBS
, (_("Redirected output to %s\n"), ofile
));
2287 ofiledsc
.dsc$w_length
= 0;
2291 for (c
= '\n'; c
; c
= *q
++)
2296 /* At a newline, skip any whitespace around a leading $
2297 from the command and issue exactly one $ into the DCL. */
2298 while (isspace ((unsigned char)*p
))
2302 while (isspace ((unsigned char)*p
))
2304 fwrite (p
, 1, q
- p
, outfile
);
2305 fputc ('$', outfile
);
2306 fputc (' ', outfile
);
2307 /* Reset variables. */
2311 /* Nice places for line breaks are after strings, after
2312 comma or space and before slash. */
2314 q
= vms_handle_apos (q
);
2330 /* Enough stuff for a line. */
2331 fwrite (p
, 1, sep
- p
, outfile
);
2335 /* The command continues. */
2336 fputc ('-', outfile
);
2338 fputc ('\n', outfile
);
2342 fwrite (p
, 1, q
- p
, outfile
);
2343 fputc ('\n', outfile
);
2347 sprintf (cmd
, "$ @%s", comname
);
2349 DB (DB_JOBS
, (_("Executing %s instead\n"), cmd
));
2352 cmddsc
.dsc$w_length
= strlen(cmd
);
2353 cmddsc
.dsc$a_pointer
= cmd
;
2354 cmddsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
2355 cmddsc
.dsc$b_class
= DSC$K_CLASS_S
;
2358 while (child
->efn
< 32 || child
->efn
> 63)
2360 status
= lib$
get_ef ((unsigned long *)&child
->efn
);
2365 sys$
clref (child
->efn
);
2367 vms_jobsefnmask
|= (1 << (child
->efn
- 32));
2370 LIB$SPAWN [command-string]
2375 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2376 [,AST-address] [,varying-AST-argument]
2377 [,prompt-string] [,cli] [,table]
2380 #ifndef DONTWAITFORCHILD
2382 * Code to make ctrl+c and ctrl+y working.
2383 * The problem starts with the synchronous case where after lib$spawn is
2384 * called any input will go to the child. But with input re-directed,
2385 * both control characters won't make it to any of the programs, neither
2386 * the spawning nor to the spawned one. Hence the caller needs to spawn
2387 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2388 * has to follow to simulate the wanted synchronous behaviour.
2389 * The next problem is ctrl+y which isn't caught by the crtl and
2390 * therefore isn't converted to SIGQUIT (for a signal handler which is
2391 * already established). The only way to catch ctrl+y, is an AST
2392 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2393 * disabled, otherwise it will handle it. Not to mention the previous
2394 * ctrl+y handling of DCL needs to be re-established before make exits.
2395 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2396 * make it to the signal handler after the child "normally" terminates.
2397 * This isn't enough. It seems reasonable for simple command lines like
2398 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2399 * spawning make. Therefore we need to abort the process in the AST.
2401 * Prior to the spawn it is checked if an AST is already set up for
2402 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2403 * this will work except if make is run in a batch environment, but there
2404 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2405 * is disabled and an exit handler is established to re-enable it.
2406 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2407 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2408 * the already established handler and will bring us back to common code.
2409 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2410 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2411 * which the crtl converts to SIGINT and which is caught by the common
2412 * signal handler. Because signals were blocked before entering this code
2413 * sys$waitfr will always complete and the SIGQUIT will be processed after
2414 * it (after termination of the current block, somewhere in common code).
2415 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2416 * current command completes. Anyway it's better than nothing :-)
2419 if (!setupYAstTried
)
2421 status
= lib$
spawn (&cmddsc
, /* cmd-string */
2422 (ifiledsc
.dsc$w_length
== 0)?0:&ifiledsc
, /* input-file */
2423 (ofiledsc
.dsc$w_length
== 0)?0:&ofiledsc
, /* output-file */
2424 &spflags
, /* flags */
2425 &pnamedsc
, /* proc name */
2426 &child
->pid
, &child
->cstatus
, &child
->efn
,
2431 pidToAbort
= child
->pid
;
2432 status
= sys$
waitfr (child
->efn
);
2434 vmsHandleChildTerm(child
);
2437 status
= lib$
spawn (&cmddsc
,
2438 (ifiledsc
.dsc$w_length
== 0)?0:&ifiledsc
,
2439 (ofiledsc
.dsc$w_length
== 0)?0:&ofiledsc
,
2442 &child
->pid
, &child
->cstatus
, &child
->efn
,
2443 vmsHandleChildTerm
, child
,
2449 printf (_("Error spawning, %d\n") ,status
);
2461 if (comname
&& !ISDB (DB_JOBS
))
2464 return (status
& 1);
2469 /* EMX: Start a child process. This function returns the new pid. */
2470 # if defined __MSDOS__ || defined __EMX__
2472 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2475 /* stdin_fd == 0 means: nothing to do for stdin;
2476 stdout_fd == 1 means: nothing to do for stdout */
2477 int save_stdin
= (stdin_fd
!= 0) ? dup (0) : 0;
2478 int save_stdout
= (stdout_fd
!= 1) ? dup (1): 1;
2480 /* < 0 only if dup() failed */
2482 fatal (NILF
, _("no more file handles: could not duplicate stdin\n"));
2483 if (save_stdout
< 0)
2484 fatal (NILF
, _("no more file handles: could not duplicate stdout\n"));
2486 /* Close unnecessary file handles for the child. */
2487 if (save_stdin
!= 0)
2488 CLOSE_ON_EXEC (save_stdin
);
2489 if (save_stdout
!= 1)
2490 CLOSE_ON_EXEC (save_stdout
);
2492 /* Connect the pipes to the child process. */
2494 (void) dup2 (stdin_fd
, 0);
2496 (void) dup2 (stdout_fd
, 1);
2498 /* stdin_fd and stdout_fd must be closed on exit because we are
2499 still in the parent process */
2501 CLOSE_ON_EXEC (stdin_fd
);
2503 CLOSE_ON_EXEC (stdout_fd
);
2505 /* Run the command. */
2506 pid
= exec_command (argv
, envp
);
2508 /* Restore stdout/stdin of the parent and close temporary FDs. */
2511 if (dup2 (save_stdin
, 0) != 0)
2512 fatal (NILF
, _("Could not restore stdin\n"));
2519 if (dup2 (save_stdout
, 1) != 1)
2520 fatal (NILF
, _("Could not restore stdout\n"));
2522 close (save_stdout
);
2528 #elif !defined (_AMIGA) && !defined (__MSDOS__)
2531 Replace the current process with one executing the command in ARGV.
2532 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2533 the environment of the new program. This function does not return. */
2535 child_execute_job (int stdin_fd
, int stdout_fd
, char **argv
, char **envp
)
2538 (void) dup2 (stdin_fd
, 0);
2540 (void) dup2 (stdout_fd
, 1);
2542 (void) close (stdin_fd
);
2544 (void) close (stdout_fd
);
2546 /* Run the command. */
2547 exec_command (argv
, envp
);
2549 #endif /* !AMIGA && !__MSDOS__ */
2551 #endif /* !WINDOWS32 */
2554 /* Replace the current process with one running the command in ARGV,
2555 with environment ENVP. This function does not return. */
2557 /* EMX: This function returns the pid of the child process. */
2563 exec_command (char **argv
, char **envp
)
2566 /* to work around a problem with signals and execve: ignore them */
2568 signal (SIGCHLD
,SIG_IGN
);
2570 /* Run the program. */
2571 execve (argv
[0], argv
, envp
);
2572 perror_with_name ("execve: ", argv
[0]);
2573 _exit (EXIT_FAILURE
);
2579 int exit_code
= EXIT_FAILURE
;
2581 /* make sure CreateProcess() has Path it needs */
2582 sync_Path_environment();
2584 /* launch command */
2585 hPID
= process_easy(argv
, envp
);
2587 /* make sure launch ok */
2588 if (hPID
== INVALID_HANDLE_VALUE
)
2592 _("process_easy() failed failed to launch process (e=%d)\n"),
2593 process_last_err(hPID
));
2594 for (i
= 0; argv
[i
]; i
++)
2595 fprintf(stderr
, "%s ", argv
[i
]);
2596 fprintf(stderr
, _("\nCounted %d args in failed launch\n"), i
);
2600 /* wait and reap last child */
2601 hWaitPID
= process_wait_for_any();
2604 /* was an error found on this process? */
2605 err
= process_last_err(hWaitPID
);
2608 exit_code
= process_exit_code(hWaitPID
);
2611 fprintf(stderr
, "make (e=%d, rc=%d): %s",
2612 err
, exit_code
, map_windows32_error_to_string(err
));
2614 /* cleanup process */
2615 process_cleanup(hWaitPID
);
2617 /* expect to find only last pid, warn about other pids reaped */
2618 if (hWaitPID
== hPID
)
2622 _("make reaped child pid %d, still waiting for pid %d\n"),
2626 /* return child's exit code as our exit code */
2629 #else /* !WINDOWS32 */
2635 /* Be the user, permanently. */
2640 /* Run the program. */
2641 pid
= spawnvpe (P_NOWAIT
, argv
[0], argv
, envp
);
2646 /* the file might have a strange shell extension */
2647 if (errno
== ENOENT
)
2652 /* Run the program. */
2654 execvp (argv
[0], argv
);
2656 # endif /* !__EMX__ */
2661 error (NILF
, _("%s: Command not found"), argv
[0]);
2665 /* The file is not executable. Try it as a shell script. */
2666 extern char *getenv ();
2673 /* Do not use $SHELL from the environment */
2674 struct variable
*p
= lookup_variable ("SHELL", 5);
2680 shell
= getenv ("SHELL");
2683 shell
= default_shell
;
2686 while (argv
[argc
] != 0)
2694 new_argv
= (char **) alloca ((1 + argc
+ 1) * sizeof (char *));
2695 new_argv
[0] = shell
;
2706 new_argv
[i
] = argv
[0];
2709 new_argv
[i
+ argc
] = argv
[argc
];
2714 pid
= spawnvpe (P_NOWAIT
, shell
, new_argv
, envp
);
2718 execvp (shell
, new_argv
);
2720 if (errno
== ENOENT
)
2721 error (NILF
, _("%s: Shell program not found"), shell
);
2723 perror_with_name ("execvp: ", shell
);
2729 /* this nasty error was driving me nuts :-( */
2730 error (NILF
, _("spawnvpe: environment space might be exhausted"));
2735 perror_with_name ("execvp: ", argv
[0]);
2744 #endif /* !WINDOWS32 */
2747 #else /* On Amiga */
2748 void exec_command (char **argv
)
2753 void clean_tmp (void)
2755 DeleteFile (amiga_bname
);
2758 #endif /* On Amiga */
2761 /* Figure out the argument list necessary to run LINE as a command. Try to
2762 avoid using a shell. This routine handles only ' quoting, and " quoting
2763 when no backslash, $ or ` characters are seen in the quotes. Starting
2764 quotes may be escaped with a backslash. If any of the characters in
2765 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2766 is the first word of a line, the shell is used.
2768 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2769 If *RESTP is NULL, newlines will be ignored.
2771 SHELL is the shell to use, or nil to use the default shell.
2772 IFS is the value of $IFS, or nil (meaning the default). */
2775 construct_command_argv_internal (char *line
, char **restp
, char *shell
,
2776 char *ifs
, char **batch_filename_ptr
)
2779 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2780 We call `system' for anything that requires ``slow'' processing,
2781 because DOS shells are too dumb. When $SHELL points to a real
2782 (unix-style) shell, `system' just calls it to do everything. When
2783 $SHELL points to a DOS shell, `system' does most of the work
2784 internally, calling the shell only for its internal commands.
2785 However, it looks on the $PATH first, so you can e.g. have an
2786 external command named `mkdir'.
2788 Since we call `system', certain characters and commands below are
2789 actually not specific to COMMAND.COM, but to the DJGPP implementation
2790 of `system'. In particular:
2792 The shell wildcard characters are in DOS_CHARS because they will
2793 not be expanded if we call the child via `spawnXX'.
2795 The `;' is in DOS_CHARS, because our `system' knows how to run
2796 multiple commands on a single line.
2798 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2799 won't have to tell one from another and have one more set of
2800 commands and special characters. */
2801 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2802 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2803 "copy", "ctty", "date", "del", "dir", "echo",
2804 "erase", "exit", "for", "goto", "if", "md",
2805 "mkdir", "path", "pause", "prompt", "rd",
2806 "rmdir", "rem", "ren", "rename", "set",
2807 "shift", "time", "type", "ver", "verify",
2810 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2811 static char *sh_cmds_sh
[] = { "cd", "echo", "eval", "exec", "exit", "login",
2812 "logout", "set", "umask", "wait", "while",
2813 "for", "case", "if", ":", ".", "break",
2814 "continue", "export", "read", "readonly",
2815 "shift", "times", "trap", "switch", "unset",
2820 #elif defined (__EMX__)
2821 static char sh_chars_dos
[] = "*?[];|<>%^&()";
2822 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2823 "copy", "ctty", "date", "del", "dir", "echo",
2824 "erase", "exit", "for", "goto", "if", "md",
2825 "mkdir", "path", "pause", "prompt", "rd",
2826 "rmdir", "rem", "ren", "rename", "set",
2827 "shift", "time", "type", "ver", "verify",
2830 static char sh_chars_os2
[] = "*?[];|<>%^()\"'&";
2831 static char *sh_cmds_os2
[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2832 "date", "del", "detach", "dir", "echo",
2833 "endlocal", "erase", "exit", "for", "goto", "if",
2834 "keys", "md", "mkdir", "move", "path", "pause",
2835 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2836 "set", "setlocal", "shift", "start", "time",
2837 "type", "ver", "verify", "vol", ":", 0 };
2839 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^~'";
2840 static char *sh_cmds_sh
[] = { "echo", "cd", "eval", "exec", "exit", "login",
2841 "logout", "set", "umask", "wait", "while",
2842 "for", "case", "if", ":", ".", "break",
2843 "continue", "export", "read", "readonly",
2844 "shift", "times", "trap", "switch", "unset",
2849 #elif defined (_AMIGA)
2850 static char sh_chars
[] = "#;\"|<>()?*$`";
2851 static char *sh_cmds
[] = { "cd", "eval", "if", "delete", "echo", "copy",
2852 "rename", "set", "setenv", "date", "makedir",
2853 "skip", "else", "endif", "path", "prompt",
2854 "unset", "unsetenv", "version",
2856 #elif defined (WINDOWS32)
2857 static char sh_chars_dos
[] = "\"|&<>";
2858 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2859 "copy", "ctty", "date", "del", "dir", "echo",
2860 "erase", "exit", "for", "goto", "if", "if", "md",
2861 "mkdir", "path", "pause", "prompt", "rd", "rem",
2862 "ren", "rename", "rmdir", "set", "shift", "time",
2863 "type", "ver", "verify", "vol", ":", 0 };
2864 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
2865 static char *sh_cmds_sh
[] = { "cd", "eval", "exec", "exit", "login",
2866 "logout", "set", "umask", "wait", "while", "for",
2867 "case", "if", ":", ".", "break", "continue",
2868 "export", "read", "readonly", "shift", "times",
2869 "trap", "switch", "test",
2870 #ifdef BATCH_MODE_ONLY_SHELL
2876 #elif defined(__riscos__)
2877 static char sh_chars
[] = "";
2878 static char *sh_cmds
[] = { 0 };
2879 #else /* must be UNIX-ish */
2880 static char sh_chars
[] = "#;\"*?[]&|<>(){}$`^~!";
2881 static char *sh_cmds
[] = { ".", ":", "break", "case", "cd", "continue",
2882 "eval", "exec", "exit", "export", "for", "if",
2883 "login", "logout", "read", "readonly", "set",
2884 "shift", "switch", "test", "times", "trap",
2885 "umask", "wait", "while", 0 };
2891 int instring
, word_has_equals
, seen_nonequals
, last_argument_was_empty
;
2892 char **new_argv
= 0;
2896 if (no_default_sh_exe
) {
2897 sh_cmds
= sh_cmds_dos
;
2898 sh_chars
= sh_chars_dos
;
2900 sh_cmds
= sh_cmds_sh
;
2901 sh_chars
= sh_chars_sh
;
2903 #endif /* WINDOWS32 */
2908 /* Make sure not to bother processing an empty line. */
2909 while (isblank ((unsigned char)*line
))
2914 /* See if it is safe to parse commands internally. */
2916 shell
= default_shell
;
2918 else if (strcmp (shell
, default_shell
))
2920 char *s1
= _fullpath(NULL
, shell
, 0);
2921 char *s2
= _fullpath(NULL
, default_shell
, 0);
2923 slow_flag
= strcmp((s1
? s1
: ""), (s2
? s2
: ""));
2932 #else /* not WINDOWS32 */
2933 #if defined (__MSDOS__) || defined (__EMX__)
2934 else if (stricmp (shell
, default_shell
))
2936 extern int _is_unixy_shell (const char *_path
);
2938 DB (DB_BASIC
, (_("$SHELL changed (was `%s', now `%s')\n"),
2939 default_shell
, shell
));
2940 unixy_shell
= _is_unixy_shell (shell
);
2941 /* we must allocate a copy of shell: construct_command_argv() will free
2942 * shell after this function returns. */
2943 default_shell
= xstrdup (shell
);
2947 sh_chars
= sh_chars_sh
;
2948 sh_cmds
= sh_cmds_sh
;
2952 sh_chars
= sh_chars_dos
;
2953 sh_cmds
= sh_cmds_dos
;
2955 if (_osmode
== OS2_MODE
)
2957 sh_chars
= sh_chars_os2
;
2958 sh_cmds
= sh_cmds_os2
;
2962 #else /* !__MSDOS__ */
2963 else if (strcmp (shell
, default_shell
))
2965 #endif /* !__MSDOS__ && !__EMX__ */
2966 #endif /* not WINDOWS32 */
2969 for (ap
= ifs
; *ap
!= '\0'; ++ap
)
2970 if (*ap
!= ' ' && *ap
!= '\t' && *ap
!= '\n')
2973 i
= strlen (line
) + 1;
2975 /* More than 1 arg per character is impossible. */
2976 new_argv
= (char **) xmalloc (i
* sizeof (char *));
2978 /* All the args can fit in a buffer as big as LINE is. */
2979 ap
= new_argv
[0] = (char *) xmalloc (i
);
2982 /* I is how many complete arguments have been found. */
2984 instring
= word_has_equals
= seen_nonequals
= last_argument_was_empty
= 0;
2985 for (p
= line
; *p
!= '\0'; ++p
)
2993 /* Inside a string, just copy any char except a closing quote
2994 or a backslash-newline combination. */
2998 if (ap
== new_argv
[0] || *(ap
-1) == '\0')
2999 last_argument_was_empty
= 1;
3001 else if (*p
== '\\' && p
[1] == '\n')
3002 goto swallow_escaped_newline
;
3003 else if (*p
== '\n' && restp
!= NULL
)
3005 /* End of the command line. */
3009 /* Backslash, $, and ` are special inside double quotes.
3010 If we see any of those, punt.
3011 But on MSDOS, if we use COMMAND.COM, double and single
3012 quotes have the same effect. */
3013 else if (instring
== '"' && strchr ("\\$`", *p
) != 0 && unixy_shell
)
3018 else if (strchr (sh_chars
, *p
) != 0)
3019 /* Not inside a string, but it's a special char. */
3022 else if (*p
== '.' && p
[1] == '.' && p
[2] == '.' && p
[3] != '.')
3023 /* `...' is a wildcard in DJGPP. */
3027 /* Not a special char. */
3031 /* Equals is a special character in leading words before the
3032 first word with no equals sign in it. This is not the case
3033 with sh -k, but we never get here when using nonstandard
3035 if (! seen_nonequals
&& unixy_shell
)
3037 word_has_equals
= 1;
3042 /* Backslash-newline combinations are eaten. */
3045 swallow_escaped_newline
:
3047 /* Eat the backslash, the newline, and following whitespace,
3048 replacing it all with a single space. */
3051 /* If there is a tab after a backslash-newline,
3052 remove it from the source line which will be echoed,
3053 since it was most likely used to line
3054 up the continued line with the previous one. */
3056 /* Note these overlap and strcpy() is undefined for
3057 overlapping objects in ANSI C. The strlen() _IS_ right,
3058 since we need to copy the nul byte too. */
3059 bcopy (p
+ 1, p
, strlen (p
));
3065 if (ap
!= new_argv
[i
])
3066 /* Treat this as a space, ending the arg.
3067 But if it's at the beginning of the arg, it should
3068 just get eaten, rather than becoming an empty arg. */
3071 p
= next_token (p
) - 1;
3074 else if (p
[1] != '\0')
3076 #ifdef HAVE_DOS_PATHS
3077 /* Only remove backslashes before characters special
3078 to Unixy shells. All other backslashes are copied
3079 verbatim, since they are probably DOS-style
3080 directory separators. This still leaves a small
3081 window for problems, but at least it should work
3082 for the vast majority of naive users. */
3085 /* A dot is only special as part of the "..."
3087 if (strneq (p
+ 1, ".\\.\\.", 5))
3095 if (p
[1] != '\\' && p
[1] != '\''
3096 && !isspace ((unsigned char)p
[1])
3097 && (strchr (sh_chars_sh
, p
[1]) == 0))
3098 /* back up one notch, to copy the backslash */
3100 #endif /* HAVE_DOS_PATHS */
3102 /* Copy and skip the following char. */
3115 /* End of the command line. */
3120 /* Newlines are not special. */
3127 /* We have the end of an argument.
3128 Terminate the text of the argument. */
3131 last_argument_was_empty
= 0;
3133 /* Update SEEN_NONEQUALS, which tells us if every word
3134 heretofore has contained an `='. */
3135 seen_nonequals
|= ! word_has_equals
;
3136 if (word_has_equals
&& ! seen_nonequals
)
3137 /* An `=' in a word before the first
3138 word without one is magical. */
3140 word_has_equals
= 0; /* Prepare for the next word. */
3142 /* If this argument is the command name,
3143 see if it is a built-in shell command.
3144 If so, have the shell handle it. */
3148 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
3150 if (streq (sh_cmds
[j
], new_argv
[0]))
3153 /* Non-Unix shells are case insensitive. */
3155 && strcasecmp (sh_cmds
[j
], new_argv
[0]) == 0)
3161 /* Ignore multiple whitespace chars. */
3163 /* Next iteration should examine the first nonwhite char. */
3175 /* Let the shell deal with an unterminated quote. */
3178 /* Terminate the last argument and the argument list. */
3181 if (new_argv
[i
][0] != '\0' || last_argument_was_empty
)
3188 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
3189 if (streq (sh_cmds
[j
], new_argv
[0]))
3193 if (new_argv
[0] == 0)
3194 /* Line was empty. */
3200 /* We must use the shell. */
3204 /* Free the old argument list we were working on. */
3206 free ((void *)new_argv
);
3210 execute_by_shell
= 1; /* actually, call `system' if shell isn't unixy */
3219 buffer
= (char *)xmalloc (strlen (line
)+1);
3222 for (dptr
=buffer
; *ptr
; )
3224 if (*ptr
== '\\' && ptr
[1] == '\n')
3226 else if (*ptr
== '@') /* Kludge: multiline commands */
3236 new_argv
= (char **) xmalloc (2 * sizeof (char *));
3237 new_argv
[0] = buffer
;
3240 #else /* Not Amiga */
3243 * Not eating this whitespace caused things like
3247 * which gave the shell fits. I think we have to eat
3248 * whitespace here, but this code should be considered
3249 * suspicious if things start failing....
3252 /* Make sure not to bother processing an empty line. */
3253 while (isspace ((unsigned char)*line
))
3257 #endif /* WINDOWS32 */
3259 /* SHELL may be a multi-word command. Construct a command line
3260 "SHELL -c LINE", with all special chars in LINE escaped.
3261 Then recurse, expanding this command line to get the final
3264 unsigned int shell_len
= strlen (shell
);
3266 static char minus_c
[] = " -c ";
3268 static char minus_c
[] = "";
3270 unsigned int line_len
= strlen (line
);
3272 char *new_line
= (char *) alloca (shell_len
+ (sizeof (minus_c
) - 1)
3273 + (line_len
* 2) + 1);
3274 char *command_ptr
= NULL
; /* used for batch_mode_shell mode */
3276 # ifdef __EMX__ /* is this necessary? */
3278 minus_c
[1] = '/'; /* " /c " */
3282 bcopy (shell
, ap
, shell_len
);
3284 bcopy (minus_c
, ap
, sizeof (minus_c
) - 1);
3285 ap
+= sizeof (minus_c
) - 1;
3287 for (p
= line
; *p
!= '\0'; ++p
)
3289 if (restp
!= NULL
&& *p
== '\n')
3294 else if (*p
== '\\' && p
[1] == '\n')
3296 /* Eat the backslash, the newline, and following whitespace,
3297 replacing it all with a single space (which is escaped
3301 /* If there is a tab after a backslash-newline,
3302 remove it from the source line which will be echoed,
3303 since it was most likely used to line
3304 up the continued line with the previous one. */
3306 bcopy (p
+ 1, p
, strlen (p
));
3310 if (unixy_shell
&& !batch_mode_shell
)
3316 /* DOS shells don't know about backslash-escaping. */
3317 if (unixy_shell
&& !batch_mode_shell
&&
3318 (*p
== '\\' || *p
== '\'' || *p
== '"'
3319 || isspace ((unsigned char)*p
)
3320 || strchr (sh_chars
, *p
) != 0))
3323 else if (unixy_shell
&& strneq (p
, "...", 3))
3325 /* The case of `...' wildcard again. */
3326 strcpy (ap
, "\\.\\.\\");
3333 if (ap
== new_line
+ shell_len
+ sizeof (minus_c
) - 1)
3334 /* Line was empty. */
3339 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3340 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3341 cases, run commands via a script file. */
3342 if ((no_default_sh_exe
|| batch_mode_shell
) && batch_filename_ptr
) {
3344 int id
= GetCurrentProcessId();
3347 /* create a file name */
3348 sprintf(fbuf
, "make%d", id
);
3349 *batch_filename_ptr
= create_batch_filename (fbuf
, unixy_shell
);
3351 DB (DB_JOBS
, (_("Creating temporary batch file %s\n"),
3352 *batch_filename_ptr
));
3354 /* create batch file to execute command */
3355 batch
= fopen (*batch_filename_ptr
, "w");
3357 fputs ("@echo off\n", batch
);
3358 fputs (command_ptr
, batch
);
3359 fputc ('\n', batch
);
3363 new_argv
= (char **) xmalloc(3 * sizeof (char *));
3365 new_argv
[0] = xstrdup (shell
);
3366 new_argv
[1] = *batch_filename_ptr
; /* only argv[0] gets freed later */
3368 new_argv
[0] = xstrdup (*batch_filename_ptr
);
3373 #endif /* WINDOWS32 */
3375 new_argv
= construct_command_argv_internal (new_line
, (char **) NULL
,
3376 (char *) 0, (char *) 0,
3379 else if (!unixy_shell
)
3381 /* new_line is local, must not be freed therefore
3382 We use line here instead of new_line because we run the shell
3384 size_t line_len
= strlen (line
);
3387 memcpy (new_line
, line
, line_len
+ 1);
3388 /* replace all backslash-newline combination and also following tabs */
3391 if (q
[0] == '\\' && q
[1] == '\n')
3393 q
+= 2; /* remove '\\' and '\n' */
3395 q
++; /* remove 1st tab in the next line */
3402 # ifndef NO_CMD_DEFAULT
3403 if (strnicmp (new_line
, "echo", 4) == 0
3404 && (new_line
[4] == ' ' || new_line
[4] == '\t'))
3406 /* the builtin echo command: handle it separately */
3407 size_t echo_len
= line_len
- 5;
3408 char *echo_line
= new_line
+ 5;
3410 /* special case: echo 'x="y"'
3411 cmd works this way: a string is printed as is, i.e., no quotes
3412 are removed. But autoconf uses a command like echo 'x="y"' to
3413 determine whether make works. autoconf expects the output x="y"
3414 so we will do exactly that.
3415 Note: if we do not allow cmd to be the default shell
3416 we do not need this kind of voodoo */
3417 if (echo_line
[0] == '\''
3418 && echo_line
[echo_len
- 1] == '\''
3419 && strncmp (echo_line
+ 1, "ac_maketemp=",
3420 strlen ("ac_maketemp=")) == 0)
3422 /* remove the enclosing quotes */
3423 memmove (echo_line
, echo_line
+ 1, echo_len
- 2);
3424 echo_line
[echo_len
- 2] = '\0';
3430 /* Let the shell decide what to do. Put the command line into the
3431 2nd command line argument and hope for the best ;-) */
3432 size_t sh_len
= strlen (shell
);
3434 /* exactly 3 arguments + NULL */
3435 new_argv
= (char **) xmalloc (4 * sizeof (char *));
3436 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3437 the trailing '\0' */
3438 new_argv
[0] = (char *) malloc (sh_len
+ line_len
+ 5);
3439 memcpy (new_argv
[0], shell
, sh_len
+ 1);
3440 new_argv
[1] = new_argv
[0] + sh_len
+ 1;
3441 memcpy (new_argv
[1], "/c", 3);
3442 new_argv
[2] = new_argv
[1] + 3;
3443 memcpy (new_argv
[2], new_line
, line_len
+ 1);
3447 #elif defined(__MSDOS__)
3450 /* With MSDOS shells, we must construct the command line here
3451 instead of recursively calling ourselves, because we
3452 cannot backslash-escape the special characters (see above). */
3453 new_argv
= (char **) xmalloc (sizeof (char *));
3454 line_len
= strlen (new_line
) - shell_len
- sizeof (minus_c
) + 1;
3455 new_argv
[0] = xmalloc (line_len
+ 1);
3456 strncpy (new_argv
[0],
3457 new_line
+ shell_len
+ sizeof (minus_c
) - 1, line_len
);
3458 new_argv
[0][line_len
] = '\0';
3462 fatal (NILF
, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3463 __FILE__
, __LINE__
);
3466 #endif /* ! AMIGA */
3472 /* Figure out the argument list necessary to run LINE as a command. Try to
3473 avoid using a shell. This routine handles only ' quoting, and " quoting
3474 when no backslash, $ or ` characters are seen in the quotes. Starting
3475 quotes may be escaped with a backslash. If any of the characters in
3476 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3477 is the first word of a line, the shell is used.
3479 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3480 If *RESTP is NULL, newlines will be ignored.
3482 FILE is the target whose commands these are. It is used for
3483 variable expansion for $(SHELL) and $(IFS). */
3486 construct_command_argv (char *line
, char **restp
, struct file
*file
,
3487 char **batch_filename_ptr
)
3501 && (isspace ((unsigned char)*cptr
)))
3506 && (!isspace((unsigned char)*cptr
)))
3511 argv
= (char **)malloc (argc
* sizeof (char *));
3520 && (isspace ((unsigned char)*cptr
)))
3524 DB (DB_JOBS
, ("argv[%d] = [%s]\n", argc
, cptr
));
3525 argv
[argc
++] = cptr
;
3527 && (!isspace((unsigned char)*cptr
)))
3534 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3535 int save
= warn_undefined_variables_flag
;
3536 warn_undefined_variables_flag
= 0;
3538 shell
= allocated_variable_expand_for_file ("$(SHELL)", file
);
3541 * Convert to forward slashes so that construct_command_argv_internal()
3545 char *p
= w32ify (shell
, 0);
3551 static const char *unixroot
= NULL
;
3552 static const char *last_shell
= "";
3553 static int init
= 0;
3556 unixroot
= getenv ("UNIXROOT");
3557 /* unixroot must be NULL or not empty */
3558 if (unixroot
&& unixroot
[0] == '\0') unixroot
= NULL
;
3562 /* if we have an unixroot drive and if shell is not default_shell
3563 (which means it's either cmd.exe or the test has already been
3564 performed) and if shell is an absolute path without drive letter,
3565 try whether it exists e.g.: if "/bin/sh" does not exist use
3566 "$UNIXROOT/bin/sh" instead. */
3567 if (unixroot
&& shell
&& strcmp (shell
, last_shell
) != 0
3568 && (shell
[0] == '/' || shell
[0] == '\\'))
3570 /* trying a new shell, check whether it exists */
3571 size_t size
= strlen (shell
);
3572 char *buf
= xmalloc (size
+ 7);
3573 memcpy (buf
, shell
, size
);
3574 memcpy (buf
+ size
, ".exe", 5); /* including the trailing '\0' */
3575 if (access (shell
, F_OK
) != 0 && access (buf
, F_OK
) != 0)
3577 /* try the same for the unixroot drive */
3578 memmove (buf
+ 2, buf
, size
+ 5);
3579 buf
[0] = unixroot
[0];
3580 buf
[1] = unixroot
[1];
3581 if (access (buf
, F_OK
) == 0)
3582 /* we have found a shell! */
3592 #endif /* __EMX__ */
3594 ifs
= allocated_variable_expand_for_file ("$(IFS)", file
);
3596 warn_undefined_variables_flag
= save
;
3599 argv
= construct_command_argv_internal (line
, restp
, shell
, ifs
, batch_filename_ptr
);
3607 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3609 dup2 (int old
, int new)
3624 #endif /* !HAPE_DUP2 && !_AMIGA */