1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988, 89, 90, 91, 92, 93, 94, 95, 96
3 Free Software Foundation, Inc.
4 This file is part of GNU Make.
6 GNU Make is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Make is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Make; see the file COPYING. If not, write to
18 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
27 /* Default shell to use. */
29 char *default_shell
= "sh.exe";
30 int no_default_sh_exe
= 1;
33 char default_shell
[] = "/bin/sh";
35 char default_shell
[] = "";
36 extern int MyExecute (char **);
42 static int dos_pid
= 123;
43 static int dos_status
;
44 static char *dos_bname
;
45 static char *dos_bename
;
46 static int dos_batch_file
;
50 #include <proto/dos.h>
51 static int amiga_pid
= 123;
52 static int amiga_status
;
53 static char amiga_bname
[32];
54 static int amiga_batch_file
;
59 #include <processes.h>
61 #include <lib$routines.h>
70 #include "pathstuff.h"
72 /* this stuff used if no sh.exe is around */
73 static char *dos_bname
;
74 static char *dos_bename
;
75 static int dos_batch_file
;
84 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
89 #define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
90 #else /* Don't have waitpid. */
95 #define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
96 #endif /* Have wait3. */
97 #endif /* Have waitpid. */
99 #if !defined (wait) && !defined (POSIX)
103 #ifndef HAVE_UNION_WAIT
108 #define WTERMSIG(x) ((x) & 0x7f)
111 #define WCOREDUMP(x) ((x) & 0x80)
114 #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
117 #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
120 #define WIFEXITED(x) (WTERMSIG (x) == 0)
123 #else /* Have `union wait'. */
125 #define WAIT_T union wait
127 #define WTERMSIG(x) ((x).w_termsig)
130 #define WCOREDUMP(x) ((x).w_coredump)
133 #define WEXITSTATUS(x) ((x).w_retcode)
136 #define WIFSIGNALED(x) (WTERMSIG(x) != 0)
139 #define WIFEXITED(x) (WTERMSIG(x) == 0)
142 #endif /* Don't have `union wait'. */
145 static int vms_jobsefnmask
=0;
148 #ifndef HAVE_UNISTD_H
150 extern int execve ();
151 extern void _exit ();
153 extern int geteuid ();
154 extern int getegid ();
155 extern int setgid ();
156 extern int getgid ();
160 extern char *allocated_variable_expand_for_file
PARAMS ((char *line
, struct file
*file
));
162 extern int getloadavg
PARAMS ((double loadavg
[], int nelem
));
163 extern int start_remote_job
PARAMS ((char **argv
, char **envp
, int stdin_fd
,
164 int *is_remote
, int *id_ptr
, int *used_stdin
));
165 extern int start_remote_job_p
PARAMS ((void));
166 extern int remote_status
PARAMS ((int *exit_code_ptr
, int *signal_ptr
,
167 int *coredump_ptr
, int block
));
169 RETSIGTYPE child_handler
PARAMS ((int));
170 static void free_child
PARAMS ((struct child
*));
171 static void start_job_command
PARAMS ((struct child
*child
));
172 static int load_too_high
PARAMS ((void));
173 static int job_next_command
PARAMS ((struct child
*));
174 static int start_waiting_job
PARAMS ((struct child
*));
176 static void vmsWaitForChildren
PARAMS ((int *));
179 /* Chain of all live (or recently deceased) children. */
181 struct child
*children
= 0;
183 /* Number of children currently running. */
185 unsigned int job_slots_used
= 0;
187 /* Nonzero if the `good' standard input is in use. */
189 static int good_stdin_used
= 0;
191 /* Chain of children waiting to run until the load average goes down. */
193 static struct child
*waiting_jobs
= 0;
197 * The macro which references this function is defined in make.h.
199 int w32_kill(int pid
, int sig
)
201 return ((process_kill(pid
, sig
) == TRUE
) ? 0 : -1);
205 /* Write an error message describing the exit status given in
206 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
207 Append "(ignored)" if IGNORED is nonzero. */
210 child_error (target_name
, exit_code
, exit_sig
, coredump
, ignored
)
212 int exit_code
, exit_sig
, coredump
;
215 if (ignored
&& silent_flag
)
219 if (!(exit_code
& 1))
220 error("*** [%s] Error 0x%x%s", target_name
, exit_code
, ((ignored
)? " (ignored)" : ""));
223 error (ignored
? "[%s] Error %d (ignored)" :
225 target_name
, exit_code
);
227 error ("*** [%s] %s%s",
228 target_name
, strsignal (exit_sig
),
229 coredump
? " (core dumped)" : "");
233 static unsigned int dead_children
= 0;
236 /* Wait for nchildren children to terminate */
238 vmsWaitForChildren(int *status
)
242 if (!vms_jobsefnmask
)
248 *status
= sys$
wflor (32, vms_jobsefnmask
);
255 /* Notice that a child died.
256 reap_children should be called when convenient. */
264 printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children
);
267 extern int shell_function_pid
, shell_function_completed
;
269 /* Reap dead children, storing the returned status and the new command
270 state (`cs_finished') in the `file' member of the `struct child' for the
271 dead child, and removing the child from the chain. If BLOCK nonzero,
272 reap at least one child, waiting for it to die if necessary. If ERR is
273 nonzero, print an error message first. */
276 reap_children (block
, err
)
281 while ((children
!= 0 || shell_function_pid
!= 0) &&
282 (block
|| dead_children
> 0))
286 int exit_code
, exit_sig
, coredump
;
287 register struct child
*lastc
, *c
;
289 int any_remote
, any_local
;
291 if (err
&& dead_children
== 0)
293 /* We might block for a while, so let the user know why. */
295 error ("*** Waiting for unfinished jobs....");
298 /* We have one less dead child to reap.
299 The test and decrement are not atomic; if it is compiled into:
300 register = dead_children - 1;
301 dead_children = register;
302 a SIGCHLD could come between the two instructions.
303 child_handler increments dead_children.
304 The second instruction here would lose that increment. But the
305 only effect of dead_children being wrong is that we might wait
306 longer than necessary to reap a child, and lose some parallelism;
307 and we might print the "Waiting for unfinished jobs" message above
308 when not necessary. */
310 if (dead_children
> 0)
314 any_local
= shell_function_pid
!= -1;
315 for (c
= children
; c
!= 0; c
= c
->next
)
317 any_remote
|= c
->remote
;
318 any_local
|= ! c
->remote
;
320 printf ("Live child 0x%08lx PID %d%s\n",
321 (unsigned long int) c
,
322 c
->pid
, c
->remote
? " (remote)" : "");
328 /* First, check for remote children. */
330 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 0);
341 pfatal_with_name ("remote_status");
345 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WIN32)
346 /* No remote children. Check for local children. */
351 vmsWaitForChildren (&status
);
356 pid
= WAIT_NOHANG (&status
);
359 pid
= wait (&status
);
371 pfatal_with_name ("wait");
375 /* No local children. */
376 if (block
&& any_remote
)
378 /* Now try a blocking wait for a remote child. */
379 pid
= remote_status (&exit_code
, &exit_sig
, &coredump
, 1);
381 goto remote_status_lose
;
383 /* No remote children either. Finally give up. */
386 /* We got a remote child. */
394 /* Chop the status word up. */
395 exit_code
= WEXITSTATUS (status
);
396 exit_sig
= WIFSIGNALED (status
) ? WTERMSIG (status
) : 0;
397 coredump
= WCOREDUMP (status
);
399 #else /* MSDOS, Amiga, WIN32. */
401 /* Life is very different on MSDOS. */
404 exit_code
= dos_status
;
407 #endif /* __MSDOS__ */
411 status
= amiga_status
;
412 exit_code
= amiga_status
;
421 /* wait for anything to finish */
422 if (hPID
= process_wait_for_any()) {
424 /* was an error found on this process? */
425 err
= process_last_err(hPID
);
428 exit_code
= process_exit_code(hPID
);
431 fprintf(stderr
, "make (e=%d): %s",
432 exit_code
, map_win32_error_to_string(exit_code
));
434 exit_sig
= process_signal(hPID
);
436 /* cleanup process */
437 process_cleanup(hPID
);
439 if (dos_batch_file
) {
450 #endif /* Not MSDOS. */
453 /* We got a remote child. */
456 /* Check if this is the child of the `shell' function. */
457 if (!remote
&& pid
== shell_function_pid
)
459 /* It is. Leave an indicator for the `shell' function. */
460 if (exit_sig
== 0 && exit_code
== 127)
461 shell_function_completed
= -1;
463 shell_function_completed
= 1;
467 child_failed
= exit_sig
!= 0 || exit_code
!= 0;
469 /* Search for a child matching the deceased one. */
471 for (c
= children
; c
!= 0; lastc
= c
, c
= c
->next
)
472 if (c
->remote
== remote
&& c
->pid
== pid
)
477 /* An unknown child died. */
479 sprintf (buf
, "Unknown%s job %d", remote
? " remote" : "", pid
);
481 child_error (buf
, exit_code
, exit_sig
, coredump
,
484 error ("%s finished.", buf
);
489 printf ("Reaping %s child 0x%08lx PID %d%s\n",
490 child_failed
? "losing" : "winning",
491 (unsigned long int) c
,
492 c
->pid
, c
->remote
? " (remote)" : "");
494 /* If this child had the good stdin, say it is now free. */
498 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
500 /* The commands failed. Write an error message,
501 delete non-precious targets, and abort. */
502 static int delete_on_error
= -1;
503 child_error (c
->file
->name
, exit_code
, exit_sig
, coredump
, 0);
504 c
->file
->update_status
= 2;
505 if (delete_on_error
== -1)
507 struct file
*f
= lookup_file (".DELETE_ON_ERROR");
508 delete_on_error
= f
!= 0 && f
->is_target
;
510 if (exit_sig
!= 0 || delete_on_error
)
511 delete_child_targets (c
);
517 /* The commands failed, but we don't care. */
518 child_error (c
->file
->name
,
519 exit_code
, exit_sig
, coredump
, 1);
523 /* If there are more commands to run, try to start them. */
524 if (job_next_command (c
))
526 if (handling_fatal_signal
)
528 /* Never start new commands while we are dying.
529 Since there are more commands that wanted to be run,
530 the target was not completely remade. So we treat
531 this as if a command had failed. */
532 c
->file
->update_status
= 2;
536 /* Check again whether to start remotely.
537 Whether or not we want to changes over time.
538 Also, start_remote_job may need state set up
539 by start_remote_job_p. */
540 c
->remote
= start_remote_job_p ();
541 start_job_command (c
);
542 /* Fatal signals are left blocked in case we were
543 about to put that child on the chain. But it is
544 already there, so it is safe for a fatal signal to
545 arrive now; it will clean up this child's targets. */
547 if (c
->file
->command_state
== cs_running
)
548 /* We successfully started the new command.
549 Loop to reap more children. */
553 if (c
->file
->update_status
!= 0)
554 /* We failed to start the commands. */
555 delete_child_targets (c
);
558 /* There are no more commands. We got through them all
559 without an unignored error. Now the target has been
560 successfully updated. */
561 c
->file
->update_status
= 0;
564 /* When we get here, all the commands for C->file are finished
565 (or aborted) and C->file->update_status contains 0 or 2. But
566 C->file->command_state is still cs_running if all the commands
567 ran; notice_finish_file looks for cs_running to tell it that
568 it's interesting to check the file's modtime again now. */
570 if (! handling_fatal_signal
)
571 /* Notice if the target of the commands has been changed.
572 This also propagates its values for command_state and
573 update_status to its also_make files. */
574 notice_finished_file (c
->file
);
577 printf ("Removing child 0x%08lx PID %d%s from chain.\n",
578 (unsigned long int) c
,
579 c
->pid
, c
->remote
? " (remote)" : "");
581 /* Remove the child from the chain and free it. */
585 lastc
->next
= c
->next
;
586 if (! handling_fatal_signal
) /* Avoid nonreentrancy. */
589 /* There is now another slot open. */
590 if (job_slots_used
> 0)
593 /* If the job failed, and the -k flag was not given, die,
594 unless we are already in the process of dying. */
595 if (!err
&& child_failed
&& !keep_going_flag
)
599 /* Only block for one child. */
605 /* Free the storage allocated for CHILD. */
609 register struct child
*child
;
611 if (child
->command_lines
!= 0)
613 register unsigned int i
;
614 for (i
= 0; i
< child
->file
->cmds
->ncommand_lines
; ++i
)
615 free (child
->command_lines
[i
]);
616 free ((char *) child
->command_lines
);
619 if (child
->environment
!= 0)
621 register char **ep
= child
->environment
;
624 free ((char *) child
->environment
);
627 free ((char *) child
);
638 extern sigset_t fatal_signal_set
;
644 sigemptyset (&empty
);
645 sigprocmask (SIG_SETMASK
, &empty
, (sigset_t
*) 0);
650 /* Start a job to run the commands specified in CHILD.
651 CHILD is updated to reflect the commands and ID of the child process.
653 NOTE: On return fatal signals are blocked! The caller is responsible
654 for calling `unblock_sigs', once the new child is safely on the chain so
655 it can be cleaned up in the event of a fatal signal. */
658 start_job_command (child
)
659 register struct child
*child
;
662 static int bad_stdin
= -1;
672 /* Combine the flags parsed for the line itself with
673 the flags specified globally for this target. */
674 flags
= (child
->file
->command_flags
675 | child
->file
->cmds
->lines_flags
[child
->command_line
- 1]);
677 p
= child
->command_ptr
;
678 child
->noerror
= flags
& COMMANDS_NOERROR
;
683 flags
|= COMMANDS_SILENT
;
685 flags
|= COMMANDS_RECURSE
;
688 else if (!isblank (*p
) && *p
!= '+')
693 /* If -q was given, just say that updating `failed'. The exit status of
694 1 tells the user that -q is saying `something to do'; the exit status
695 for a random error is 2. */
696 if (question_flag
&& !(flags
& COMMANDS_RECURSE
))
698 child
->file
->update_status
= 1;
699 notice_finished_file (child
->file
);
703 /* There may be some preceding whitespace left if there
704 was nothing but a backslash on the first line. */
707 /* Figure out an argument list from this command line. */
714 argv
= construct_command_argv (p
, &end
, child
->file
);
717 child
->command_ptr
= NULL
;
721 child
->command_ptr
= end
;
725 if (touch_flag
&& !(flags
& COMMANDS_RECURSE
))
727 /* Go on to the next command. It might be the recursive one.
728 We construct ARGV only to find the end of the command line. */
731 free ((char *) argv
);
739 /* This line has no commands. Go to the next. */
740 if (job_next_command (child
))
741 start_job_command (child
);
744 /* No more commands. All done. */
745 child
->file
->update_status
= 0;
746 notice_finished_file (child
->file
);
751 /* Print out the command. If silent, we call `message' with null so it
752 can log the working directory before the command's own error messages
755 message (0, (just_print_flag
|| (!(flags
& COMMANDS_SILENT
) && !silent_flag
))
756 ? "%s" : (char *) 0, p
);
758 /* Tell update_goal_chain that a command has been started on behalf of
759 this target. It is important that this happens here and not in
760 reap_children (where we used to do it), because reap_children might be
761 reaping children from a different target. We want this increment to
762 guaranteedly indicate that a command was started for the dependency
763 chain (i.e., update_file recursion chain) we are processing. */
767 /* If -n was given, recurse to get the next line in the sequence. */
769 if (just_print_flag
&& !(flags
& COMMANDS_RECURSE
))
773 free ((char *) argv
);
778 /* Flush the output streams so they won't have things written twice. */
787 /* Set up a bad standard input that reads from a broken pipe. */
791 /* Make a file descriptor that is the read end of a broken pipe.
792 This will be used for some children's standard inputs. */
796 /* Close the write side. */
797 (void) close (pd
[1]);
798 /* Save the read side. */
801 /* Set the descriptor to close on exec, so it does not litter any
802 child's descriptor table. When it is dup2'd onto descriptor 0,
803 that descriptor will not close on exec. */
808 (void) fcntl (bad_stdin
, F_SETFD
, FD_CLOEXEC
);
816 /* Decide whether to give this child the `good' standard input
817 (one that points to the terminal or whatever), or the `bad' one
818 that points to the read side of a broken pipe. */
820 child
->good_stdin
= !good_stdin_used
;
821 if (child
->good_stdin
)
829 /* Set up the environment for the child. */
830 if (child
->environment
== 0)
831 child
->environment
= target_environment (child
->file
);
834 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WIN32)
837 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
840 int is_remote
, id
, used_stdin
;
841 if (start_remote_job (argv
, child
->environment
,
842 child
->good_stdin
? 0 : bad_stdin
,
843 &is_remote
, &id
, &used_stdin
))
847 if (child
->good_stdin
&& !used_stdin
)
849 child
->good_stdin
= 0;
852 child
->remote
= is_remote
;
859 /* Fork the child process. */
861 char **parent_environ
;
864 (void) sigprocmask (SIG_BLOCK
, &fatal_signal_set
, (sigset_t
*) 0);
866 #ifdef HAVE_SIGSETMASK
867 (void) sigblock (fatal_signal_mask
);
875 if (!child_execute_job (argv
, child
)) {
877 perror_with_name ("vfork", "");
883 parent_environ
= environ
;
884 child
->pid
= vfork ();
885 environ
= parent_environ
; /* Restore value child may have clobbered. */
888 /* We are the child side. */
890 child_execute_job (child
->good_stdin
? 0 : bad_stdin
, 1,
891 argv
, child
->environment
);
893 else if (child
->pid
< 0)
897 perror_with_name ("vfork", "");
903 #else /* MSDOS or Amiga. */
905 dos_status
= spawnvpe (P_WAIT
, argv
[0], argv
, child
->environment
);
907 child
->pid
= dos_pid
++;
911 remove (dos_bname
); /* Ignore errors. */
912 if (access (dos_bename
, 0))
918 #endif /* __MSDOS__ */
920 amiga_status
= MyExecute (argv
);
923 child
->pid
= amiga_pid
++;
924 if (amiga_batch_file
)
926 amiga_batch_file
= 0;
927 DeleteFile (amiga_bname
); /* Ignore errors. */
929 #endif /* Not Amiga */
935 /* make UNC paths safe for CreateProcess -- backslash format */
937 if (arg0
&& arg0
[0] == '/' && arg0
[1] == '/')
938 for ( ; arg0
&& *arg0
; arg0
++)
942 /* make sure CreateProcess() has Path it needs */
943 sync_Path_environment();
945 hPID
= process_easy(argv
, child
->environment
);
947 if (hPID
!= INVALID_HANDLE_VALUE
)
948 child
->pid
= (int) hPID
;
953 "process_easy() failed failed to launch process (e=%d)\n",
954 process_last_err(hPID
));
955 for (i
= 0; argv
[i
]; i
++)
956 fprintf(stderr
, "%s ", argv
[i
]);
957 fprintf(stderr
, "\nCounted %d args in failed launch\n", i
);
961 #endif /* Not MSDOS. */
963 /* We are the parent side. Set the state to
964 say the commands are running and return. */
966 set_command_state (child
->file
, cs_running
);
968 /* Free the storage used by the child's argument list. */
971 free ((char *) argv
);
977 child
->file
->update_status
= 2;
978 notice_finished_file (child
->file
);
982 /* Try to start a child running.
983 Returns nonzero if the child was started (and maybe finished), or zero if
984 the load was too high and the child was put on the `waiting_jobs' chain. */
987 start_waiting_job (c
)
990 /* If we can start a job remotely, we always want to, and don't care about
991 the local load average. We record that the job should be started
992 remotely in C->remote for start_job_command to test. */
994 c
->remote
= start_remote_job_p ();
996 /* If this job is to be started locally, and we are already running
997 some jobs, make this one wait if the load average is too high. */
998 if (!c
->remote
&& job_slots_used
> 0 && load_too_high ())
1000 /* Put this child on the chain of children waiting
1001 for the load average to go down. */
1002 set_command_state (c
->file
, cs_running
);
1003 c
->next
= waiting_jobs
;
1008 /* Start the first command; reap_children will run later command lines. */
1009 start_job_command (c
);
1011 switch (c
->file
->command_state
)
1016 printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
1017 (unsigned long int) c
,
1018 c
->pid
, c
->remote
? " (remote)" : "");
1020 /* One more job slot is in use. */
1025 case cs_not_started
:
1026 /* All the command lines turned out to be empty. */
1027 c
->file
->update_status
= 0;
1031 notice_finished_file (c
->file
);
1036 assert (c
->file
->command_state
== cs_finished
);
1043 /* Create a `struct child' for FILE and start its commands running. */
1047 register struct file
*file
;
1049 register struct commands
*cmds
= file
->cmds
;
1050 register struct child
*c
;
1052 register unsigned int i
;
1054 /* Let any previously decided-upon jobs that are waiting
1055 for the load to go down start before this new one. */
1056 start_waiting_jobs ();
1058 /* Reap any children that might have finished recently. */
1059 reap_children (0, 0);
1061 /* Chop the commands up into lines if they aren't already. */
1062 chop_commands (cmds
);
1065 /* Wait for a job slot to be freed up. */
1066 while (job_slots_used
== job_slots
)
1067 reap_children (1, 0);
1069 /* Expand the command lines and store the results in LINES. */
1070 lines
= (char **) xmalloc (cmds
->ncommand_lines
* sizeof (char *));
1071 for (i
= 0; i
< cmds
->ncommand_lines
; ++i
)
1073 /* Collapse backslash-newline combinations that are inside variable
1074 or function references. These are left alone by the parser so
1075 that they will appear in the echoing of commands (where they look
1076 nice); and collapsed by construct_command_argv when it tokenizes.
1077 But letting them survive inside function invocations loses because
1078 we don't want the functions to see them as part of the text. */
1080 char *in
, *out
, *ref
;
1082 /* IN points to where in the line we are scanning.
1083 OUT points to where in the line we are writing.
1084 When we collapse a backslash-newline combination,
1085 IN gets ahead out OUT. */
1087 in
= out
= cmds
->command_lines
[i
];
1088 while ((ref
= index (in
, '$')) != 0)
1090 ++ref
; /* Move past the $. */
1093 /* Copy the text between the end of the last chunk
1094 we processed (where IN points) and the new chunk
1095 we are about to process (where REF points). */
1096 bcopy (in
, out
, ref
- in
);
1098 /* Move both pointers past the boring stuff. */
1102 if (*ref
== '(' || *ref
== '{')
1104 char openparen
= *ref
;
1105 char closeparen
= openparen
== '(' ? ')' : '}';
1109 *out
++ = *in
++; /* Copy OPENPAREN. */
1110 /* IN now points past the opening paren or brace.
1111 Count parens or braces until it is matched. */
1115 if (*in
== closeparen
&& --count
< 0)
1117 else if (*in
== '\\' && in
[1] == '\n')
1119 /* We have found a backslash-newline inside a
1120 variable or function reference. Eat it and
1121 any following whitespace. */
1124 for (p
= in
- 1; p
> ref
&& *p
== '\\'; --p
)
1128 /* There were two or more backslashes, so this is
1129 not really a continuation line. We don't collapse
1130 the quoting backslashes here as is done in
1131 collapse_continuations, because the line will
1132 be collapsed again after expansion. */
1136 /* Skip the backslash, newline and
1137 any following whitespace. */
1138 in
= next_token (in
+ 2);
1140 /* Discard any preceding whitespace that has
1141 already been written to the output. */
1142 while (out
> ref
&& isblank (out
[-1]))
1145 /* Replace it all with a single space. */
1151 if (*in
== openparen
)
1160 /* There are no more references in this line to worry about.
1161 Copy the remaining uninteresting text to the output. */
1165 /* Finally, expand the line. */
1166 lines
[i
] = allocated_variable_expand_for_file (cmds
->command_lines
[i
],
1170 /* Start the command sequence, record it in a new
1171 `struct child', and add that to the chain. */
1173 c
= (struct child
*) xmalloc (sizeof (struct child
));
1175 c
->command_lines
= lines
;
1176 c
->command_line
= 0;
1180 /* Fetch the first command line to be run. */
1181 job_next_command (c
);
1183 /* The job is now primed. Start it running.
1184 (This will notice if there are in fact no commands.) */
1185 (void)start_waiting_job (c
);
1188 /* Since there is only one job slot, make things run linearly.
1189 Wait for the child to die, setting the state to `cs_finished'. */
1190 while (file
->command_state
== cs_running
)
1191 reap_children (1, 0);
1196 /* Move CHILD's pointers to the next command for it to execute.
1197 Returns nonzero if there is another command. */
1200 job_next_command (child
)
1201 struct child
*child
;
1203 while (child
->command_ptr
== 0 || *child
->command_ptr
== '\0')
1205 /* There are no more lines in the expansion of this line. */
1206 if (child
->command_line
== child
->file
->cmds
->ncommand_lines
)
1208 /* There are no more lines to be expanded. */
1209 child
->command_ptr
= 0;
1213 /* Get the next line to run. */
1214 child
->command_ptr
= child
->command_lines
[child
->command_line
++];
1222 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1227 if (max_load_average
< 0)
1231 if (getloadavg (&load
, 1) != 1)
1233 static int lossage
= -1;
1234 /* Complain only once for the same error. */
1235 if (lossage
== -1 || errno
!= lossage
)
1238 /* An errno value of zero means getloadavg is just unsupported. */
1239 error ("cannot enforce load limits on this operating system");
1241 perror_with_name ("cannot enforce load limit: ", "getloadavg");
1248 return load
>= max_load_average
;
1252 /* Start jobs that are waiting for the load to be lower. */
1255 start_waiting_jobs ()
1259 if (waiting_jobs
== 0)
1264 /* Check for recently deceased descendants. */
1265 reap_children (0, 0);
1267 /* Take a job off the waiting list. */
1269 waiting_jobs
= job
->next
;
1271 /* Try to start that job. We break out of the loop as soon
1272 as start_waiting_job puts one back on the waiting list. */
1274 while (start_waiting_job (job
) && waiting_jobs
!= 0);
1281 #include <descrip.h>
1284 /* This is called as an AST when a child process dies (it won't get
1285 interrupted by anything except a higher level AST).
1287 int vmsHandleChildTerm(struct child
*child
)
1290 register struct child
*lastc
, *c
;
1293 vms_jobsefnmask
&= ~(1 << (child
->efn
- 32));
1295 lib$
free_ef(&child
->efn
);
1297 (void) sigblock (fatal_signal_mask
);
1299 child_failed
= !(child
->cstatus
& 1 || ((child
->cstatus
& 7) == 0));
1301 /* Search for a child matching the deceased one. */
1303 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1304 for (c
= children
; c
!= 0 && c
!= child
; lastc
= c
, c
= c
->next
);
1309 if (child_failed
&& !c
->noerror
&& !ignore_errors_flag
)
1311 /* The commands failed. Write an error message,
1312 delete non-precious targets, and abort. */
1313 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 0);
1314 c
->file
->update_status
= 1;
1315 delete_child_targets (c
);
1321 /* The commands failed, but we don't care. */
1322 child_error (c
->file
->name
, c
->cstatus
, 0, 0, 1);
1326 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1327 /* If there are more commands to run, try to start them. */
1330 switch (c
->file
->command_state
)
1333 /* Successfully started. */
1337 if (c
->file
->update_status
!= 0) {
1338 /* We failed to start the commands. */
1339 delete_child_targets (c
);
1344 error ("internal error: `%s' command_state \
1345 %d in child_handler", c
->file
->name
);
1349 #endif /* RECURSIVEJOBS */
1352 /* Set the state flag to say the commands have finished. */
1353 c
->file
->command_state
= cs_finished
;
1354 notice_finished_file (c
->file
);
1356 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1357 /* Remove the child from the chain and free it. */
1361 lastc
->next
= c
->next
;
1363 #endif /* RECURSIVEJOBS */
1365 /* There is now another slot open. */
1366 if (job_slots_used
> 0)
1369 /* If the job failed, and the -k flag was not given, die. */
1370 if (child_failed
&& !keep_going_flag
)
1373 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask
));
1379 Spawn a process executing the command in ARGV and return its pid. */
1381 #define MAXCMDLEN 200
1384 child_execute_job (argv
, child
)
1386 struct child
*child
;
1389 static struct dsc$descriptor_s cmddsc
;
1390 #ifndef DONTWAITFORCHILD
1393 int spflags
= CLI$M_NOWAIT
;
1396 char cmd
[4096],*p
,*c
;
1399 /* Remove backslashes */
1400 for (p
= argv
, c
= cmd
; *p
; p
++,c
++)
1402 if (*p
== '\\') p
++;
1407 /* check for maximum dcl length and create *.com file if neccesary */
1411 if (strlen (cmd
) > MAXCMDLEN
)
1416 strcpy (comname
, "sys$scratch:CMDXXXXXX.COM");
1417 (void) mktemp (comname
);
1419 outfile
= fopen (comname
, "w");
1421 pfatal_with_name (comname
);
1423 fprintf (outfile
, "$ ");
1428 p
= strchr (c
, ',');
1429 if ((p
== NULL
) || (p
-c
> MAXCMDLEN
))
1430 p
= strchr (c
, ' ');
1439 fprintf (outfile
, "%s%s\n", c
, (tmp
== '\0')?"":" -");
1447 sprintf (cmd
, "$ @%s", comname
);
1450 printf ("Executing %s instead\n", cmd
);
1453 cmddsc
.dsc$w_length
= strlen(cmd
);
1454 cmddsc
.dsc$a_pointer
= cmd
;
1455 cmddsc
.dsc$b_dtype
= DSC$K_DTYPE_T
;
1456 cmddsc
.dsc$b_class
= DSC$K_CLASS_S
;
1459 while (child
->efn
< 32 || child
->efn
> 63)
1461 status
= lib$
get_ef(&child
->efn
);
1466 sys$
clref(child
->efn
);
1468 vms_jobsefnmask
|= (1 << (child
->efn
- 32));
1470 #ifndef DONTWAITFORCHILD
1471 status
= lib$
spawn(&cmddsc
,0,0,&spflags
,0,&child
->pid
,&child
->cstatus
,
1473 vmsHandleChildTerm(child
);
1475 status
= lib$
spawn(&cmddsc
,0,0,&spflags
,0,&child
->pid
,&child
->cstatus
,
1476 &child
->efn
,vmsHandleChildTerm
,child
);
1481 printf("Error spawning, %d\n",status
);
1487 return (status
& 1);
1494 Replace the current process with one executing the command in ARGV.
1495 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1496 the environment of the new program. This function does not return. */
1499 child_execute_job (stdin_fd
, stdout_fd
, argv
, envp
)
1500 int stdin_fd
, stdout_fd
;
1501 char **argv
, **envp
;
1504 (void) dup2 (stdin_fd
, 0);
1506 (void) dup2 (stdout_fd
, 1);
1508 (void) close (stdin_fd
);
1510 (void) close (stdout_fd
);
1512 /* Run the command. */
1513 exec_command (argv
, envp
);
1520 /* Replace the current process with one running the command in ARGV,
1521 with environment ENVP. This function does not return. */
1524 exec_command (argv
, envp
)
1525 char **argv
, **envp
;
1528 /* Run the program. */
1529 execve (argv
[0], argv
, envp
);
1530 perror_with_name ("execve: ", argv
[0]);
1531 _exit (EXIT_FAILURE
);
1533 /* Be the user, permanently. */
1536 /* Run the program. */
1538 execvp (argv
[0], argv
);
1543 error ("%s: Command not found", argv
[0]);
1547 /* The file is not executable. Try it as a shell script. */
1548 extern char *getenv ();
1553 shell
= getenv ("SHELL");
1555 shell
= default_shell
;
1558 while (argv
[argc
] != 0)
1561 new_argv
= (char **) alloca ((1 + argc
+ 1) * sizeof (char *));
1562 new_argv
[0] = shell
;
1563 new_argv
[1] = argv
[0];
1566 new_argv
[1 + argc
] = argv
[argc
];
1570 execvp (shell
, new_argv
);
1571 if (errno
== ENOENT
)
1572 error ("%s: Shell program not found", shell
);
1574 perror_with_name ("execvp: ", shell
);
1579 perror_with_name ("execvp: ", argv
[0]);
1586 #else /* On Amiga */
1587 void exec_command (argv
)
1593 void clean_tmp (void)
1595 DeleteFile (amiga_bname
);
1598 #endif /* An Amiga */
1601 /* Figure out the argument list necessary to run LINE as a command. Try to
1602 avoid using a shell. This routine handles only ' quoting, and " quoting
1603 when no backslash, $ or ` characters are seen in the quotes. Starting
1604 quotes may be escaped with a backslash. If any of the characters in
1605 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
1606 is the first word of a line, the shell is used.
1608 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
1609 If *RESTP is NULL, newlines will be ignored.
1611 SHELL is the shell to use, or nil to use the default shell.
1612 IFS is the value of $IFS, or nil (meaning the default). */
1615 construct_command_argv_internal (line
, restp
, shell
, ifs
)
1616 char *line
, **restp
;
1620 static char sh_chars
[] = "\"|<>";
1621 static char *sh_cmds
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1622 "copy", "ctty", "date", "del", "dir", "echo",
1623 "erase", "exit", "for", "goto", "if", "if", "md",
1624 "mkdir", "path", "pause", "prompt", "rem", "ren",
1625 "rename", "set", "shift", "time", "type",
1626 "ver", "verify", "vol", ":", 0 };
1629 static char sh_chars
[] = "#;\"|<>()?*$`";
1630 static char *sh_cmds
[] = { "cd", "eval", "if", "delete", "echo", "copy",
1631 "rename", "set", "setenv", "date", "makedir",
1632 "skip", "else", "endif", "path", "prompt",
1633 "unset", "unsetenv", "version",
1637 static char sh_chars_dos
[] = "\"|<>";
1638 static char *sh_cmds_dos
[] = { "break", "call", "cd", "chcp", "chdir", "cls",
1639 "copy", "ctty", "date", "del", "dir", "echo",
1640 "erase", "exit", "for", "goto", "if", "if", "md",
1641 "mkdir", "path", "pause", "prompt", "rem", "ren",
1642 "rename", "set", "shift", "time", "type",
1643 "ver", "verify", "vol", ":", 0 };
1644 static char sh_chars_sh
[] = "#;\"*?[]&|<>(){}$`^";
1645 static char *sh_cmds_sh
[] = { "cd", "eval", "exec", "exit", "login",
1646 "logout", "set", "umask", "wait", "while", "for",
1647 "case", "if", ":", ".", "break", "continue",
1648 "export", "read", "readonly", "shift", "times",
1649 "trap", "switch", "test", 0 };
1653 static char sh_chars
[] = "#;\"*?[]&|<>(){}$`^";
1654 static char *sh_cmds
[] = { "cd", "eval", "exec", "exit", "login",
1655 "logout", "set", "umask", "wait", "while", "for",
1656 "case", "if", ":", ".", "break", "continue",
1657 "export", "read", "readonly", "shift", "times",
1658 "trap", "switch", 0 };
1665 int instring
, word_has_equals
, seen_nonequals
;
1666 char **new_argv
= 0;
1670 if (no_default_sh_exe
) {
1671 sh_cmds
= sh_cmds_dos
;
1672 sh_chars
= sh_chars_dos
;
1674 sh_cmds
= sh_cmds_sh
;
1675 sh_chars
= sh_chars_sh
;
1682 /* Make sure not to bother processing an empty line. */
1683 while (isblank (*line
))
1688 /* See if it is safe to parse commands internally. */
1690 shell
= default_shell
;
1691 else if (strcmp (shell
, default_shell
))
1694 char *s1
= _fullpath(NULL
, shell
, 0);
1695 char *s2
= _fullpath(NULL
, default_shell
, 0);
1697 slow_flag
= strcmp((s1
? s1
: ""), (s2
? s2
: ""));
1709 for (ap
= ifs
; *ap
!= '\0'; ++ap
)
1710 if (*ap
!= ' ' && *ap
!= '\t' && *ap
!= '\n')
1713 i
= strlen (line
) + 1;
1715 /* More than 1 arg per character is impossible. */
1716 new_argv
= (char **) xmalloc (i
* sizeof (char *));
1718 /* All the args can fit in a buffer as big as LINE is. */
1719 ap
= new_argv
[0] = (char *) xmalloc (i
);
1722 /* I is how many complete arguments have been found. */
1724 instring
= word_has_equals
= seen_nonequals
= 0;
1725 for (p
= line
; *p
!= '\0'; ++p
)
1733 /* Inside a string, just copy any char except a closing quote
1734 or a backslash-newline combination. */
1737 else if (*p
== '\\' && p
[1] == '\n')
1738 goto swallow_escaped_newline
;
1739 else if (*p
== '\n' && restp
!= NULL
)
1741 /* End of the command line. */
1745 /* Backslash, $, and ` are special inside double quotes.
1746 If we see any of those, punt. */
1747 else if (instring
== '"' && index ("\\$`", *p
) != 0)
1752 else if (index (sh_chars
, *p
) != 0)
1753 /* Not inside a string, but it's a special char. */
1756 /* Not a special char. */
1760 /* Equals is a special character in leading words before the
1761 first word with no equals sign in it. This is not the case
1762 with sh -k, but we never get here when using nonstandard
1764 if (! seen_nonequals
)
1766 word_has_equals
= 1;
1771 /* Backslash-newline combinations are eaten. */
1774 swallow_escaped_newline
:
1776 /* Eat the backslash, the newline, and following whitespace,
1777 replacing it all with a single space. */
1780 /* If there is a tab after a backslash-newline,
1781 remove it from the source line which will be echoed,
1782 since it was most likely used to line
1783 up the continued line with the previous one. */
1791 if (ap
!= new_argv
[i
])
1792 /* Treat this as a space, ending the arg.
1793 But if it's at the beginning of the arg, it should
1794 just get eaten, rather than becoming an empty arg. */
1797 p
= next_token (p
) - 1;
1800 else if (p
[1] != '\0')
1801 /* Copy and skip the following char. */
1813 /* End of the command line. */
1818 /* Newlines are not special. */
1825 /* We have the end of an argument.
1826 Terminate the text of the argument. */
1830 /* Update SEEN_NONEQUALS, which tells us if every word
1831 heretofore has contained an `='. */
1832 seen_nonequals
|= ! word_has_equals
;
1833 if (word_has_equals
&& ! seen_nonequals
)
1834 /* An `=' in a word before the first
1835 word without one is magical. */
1837 word_has_equals
= 0; /* Prepare for the next word. */
1839 /* If this argument is the command name,
1840 see if it is a built-in shell command.
1841 If so, have the shell handle it. */
1845 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
1846 if (streq (sh_cmds
[j
], new_argv
[0]))
1850 /* Ignore multiple whitespace chars. */
1852 /* Next iteration should examine the first nonwhite char. */
1864 /* Let the shell deal with an unterminated quote. */
1867 /* Terminate the last argument and the argument list. */
1870 if (new_argv
[i
][0] != '\0')
1877 for (j
= 0; sh_cmds
[j
] != 0; ++j
)
1878 if (streq (sh_cmds
[j
], new_argv
[0]))
1882 if (new_argv
[0] == 0)
1883 /* Line was empty. */
1889 /* We must use the shell. */
1893 /* Free the old argument list we were working on. */
1895 free ((void *)new_argv
);
1899 * Not eating this whitespace caused things like
1903 * which gave the shell fits. I think we have to eat
1904 * whitespace here, but this code should be considered
1905 * suspicious if things start failing....
1908 /* Make sure not to bother processing an empty line. */
1909 while (isspace (*line
))
1915 #if defined(__MSDOS__) || defined(WIN32)
1918 * only come here if no sh.exe command
1920 if (no_default_sh_exe
)
1927 dos_bname
= tempnam (".", "mk");
1928 for (i
= 0; dos_bname
[i
] != '\0'; ++i
)
1929 if (dos_bname
[i
] == '/')
1930 dos_bname
[i
] = '\\';
1931 dos_bename
= (char *) xmalloc (strlen (dos_bname
) + 5);
1932 strcpy (dos_bename
, dos_bname
);
1933 strcat (dos_bname
, ".bat");
1934 strcat (dos_bename
, ".err");
1936 batch
= fopen (dos_bename
, "w"); /* Create a file. */
1939 batch
= fopen (dos_bname
, "w");
1940 fputs ("@echo off\n", batch
);
1941 fputs (line
, batch
);
1942 fprintf (batch
, "\nif errorlevel 1 del %s\n", dos_bename
);
1944 new_argv
= (char **) xmalloc(2 * sizeof(char *));
1945 new_argv
[0] = strdup (dos_bname
);
1955 buffer
= (char *)xmalloc (strlen (line
)+1);
1958 for (dptr
=buffer
; *ptr
; )
1960 if (*ptr
== '\\' && ptr
[1] == '\n')
1962 else if (*ptr
== '@') /* Kludge: multiline commands */
1972 new_argv
= (char **) xmalloc(2 * sizeof(char *));
1973 new_argv
[0] = buffer
;
1976 #else /* Not MSDOS or Amiga */
1979 * This is technically an else to the above 'if (no_default_sh_exe)',
1980 * but (IMHO) coding if-else across ifdef is dangerous.
1982 if (!no_default_sh_exe
)
1985 /* SHELL may be a multi-word command. Construct a command line
1986 "SHELL -c LINE", with all special chars in LINE escaped.
1987 Then recurse, expanding this command line to get the final
1990 unsigned int shell_len
= strlen (shell
);
1991 static char minus_c
[] = " -c ";
1992 unsigned int line_len
= strlen (line
);
1994 char *new_line
= (char *) alloca (shell_len
+ (sizeof (minus_c
) - 1)
1995 + (line_len
* 2) + 1);
1998 bcopy (shell
, ap
, shell_len
);
2000 bcopy (minus_c
, ap
, sizeof (minus_c
) - 1);
2001 ap
+= sizeof (minus_c
) - 1;
2002 for (p
= line
; *p
!= '\0'; ++p
)
2004 if (restp
!= NULL
&& *p
== '\n')
2009 else if (*p
== '\\' && p
[1] == '\n')
2011 /* Eat the backslash, the newline, and following whitespace,
2012 replacing it all with a single space (which is escaped
2016 /* If there is a tab after a backslash-newline,
2017 remove it from the source line which will be echoed,
2018 since it was most likely used to line
2019 up the continued line with the previous one. */
2030 if (*p
== '\\' || *p
== '\'' || *p
== '"'
2032 || index (sh_chars
, *p
) != 0)
2038 new_argv
= construct_command_argv_internal (new_line
, (char **) NULL
,
2039 (char *) 0, (char *) 0);
2041 #endif /* Not MSDOS nor Amiga. */
2046 /* Figure out the argument list necessary to run LINE as a command. Try to
2047 avoid using a shell. This routine handles only ' quoting, and " quoting
2048 when no backslash, $ or ` characters are seen in the quotes. Starting
2049 quotes may be escaped with a backslash. If any of the characters in
2050 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2051 is the first word of a line, the shell is used.
2053 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2054 If *RESTP is NULL, newlines will be ignored.
2056 FILE is the target whose commands these are. It is used for
2057 variable expansion for $(SHELL) and $(IFS). */
2060 construct_command_argv (line
, restp
, file
)
2061 char *line
, **restp
;
2068 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2069 int save
= warn_undefined_variables_flag
;
2070 warn_undefined_variables_flag
= 0;
2072 shell
= allocated_variable_expand_for_file ("$(SHELL)", file
);
2075 * Convert to forward slashes so that construct_command_argv_internal()
2079 char *p
= w32ify(shell
, 0);
2083 ifs
= allocated_variable_expand_for_file ("$(IFS)", file
);
2085 warn_undefined_variables_flag
= save
;
2088 argv
= construct_command_argv_internal (line
, restp
, shell
, ifs
);
2097 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
2115 #endif /* !HAPE_DUP2 && !_AMIGA */