Add a Finnish translation.
[make.git] / job.c
blob28d1e6b8c387866cd49f60cbf6fe9631ddea112d
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)
8 any later version.
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. */
20 #include "make.h"
22 #include <assert.h>
24 #include "job.h"
25 #include "debug.h"
26 #include "filedef.h"
27 #include "commands.h"
28 #include "variable.h"
29 #include "debug.h"
31 #include <string.h>
33 /* Default shell to use. */
34 #ifdef WINDOWS32
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;
60 #elif defined (VMS)
62 # include <descrip.h>
63 char default_shell[] = "";
64 int batch_mode_shell = 0;
66 #elif defined (__riscos__)
68 char default_shell[] = "";
69 int batch_mode_shell = 0;
71 #else
73 char default_shell[] = "/bin/sh";
74 int batch_mode_shell = 0;
76 #endif
78 #ifdef __MSDOS__
79 # include <process.h>
80 static int execute_by_shell;
81 static int dos_pid = 123;
82 int dos_status;
83 int dos_command_running;
84 #endif /* __MSDOS__ */
86 #ifdef _AMIGA
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;
92 #endif /* Amiga. */
94 #ifdef VMS
95 # ifndef __GNUC__
96 # include <processes.h>
97 # endif
98 # include <starlet.h>
99 # include <lib$routines.h>
100 #endif
102 #ifdef WINDOWS32
103 # include <windows.h>
104 # include <io.h>
105 # include <process.h>
106 # include "sub_proc.h"
107 # include "w32err.h"
108 # include "pathstuff.h"
109 #endif /* WINDOWS32 */
111 #ifdef __EMX__
112 # include <process.h>
113 #endif
115 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
116 # include <sys/wait.h>
117 #endif
119 #ifdef HAVE_WAITPID
120 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
121 #else /* Don't have waitpid. */
122 # ifdef HAVE_WAIT3
123 # ifndef wait3
124 extern int wait3 ();
125 # endif
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)
131 extern int wait ();
132 #endif
134 #ifndef HAVE_UNION_WAIT
136 # define WAIT_T int
138 # ifndef WTERMSIG
139 # define WTERMSIG(x) ((x) & 0x7f)
140 # endif
141 # ifndef WCOREDUMP
142 # define WCOREDUMP(x) ((x) & 0x80)
143 # endif
144 # ifndef WEXITSTATUS
145 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
146 # endif
147 # ifndef WIFSIGNALED
148 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
149 # endif
150 # ifndef WIFEXITED
151 # define WIFEXITED(x) (WTERMSIG (x) == 0)
152 # endif
154 #else /* Have `union wait'. */
156 # define WAIT_T union wait
157 # ifndef WTERMSIG
158 # define WTERMSIG(x) ((x).w_termsig)
159 # endif
160 # ifndef WCOREDUMP
161 # define WCOREDUMP(x) ((x).w_coredump)
162 # endif
163 # ifndef WEXITSTATUS
164 # define WEXITSTATUS(x) ((x).w_retcode)
165 # endif
166 # ifndef WIFSIGNALED
167 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
168 # endif
169 # ifndef WIFEXITED
170 # define WIFEXITED(x) (WTERMSIG(x) == 0)
171 # endif
173 #endif /* Don't have `union wait'. */
175 #ifdef VMS
176 static int vms_jobsefnmask = 0;
177 #endif /* !VMS */
179 #ifndef HAVE_UNISTD_H
180 extern int dup2 ();
181 extern int execve ();
182 extern void _exit ();
183 # ifndef VMS
184 extern int geteuid ();
185 extern int getegid ();
186 extern int setgid ();
187 extern int getgid ();
188 # endif
189 #endif
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 *));
206 #ifdef VMS
207 static void vmsWaitForChildren PARAMS ((int *));
208 #endif
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). */
228 int unixy_shell = 1;
230 /* Number of jobs started in the current second. */
232 unsigned long job_counter = 0;
235 #ifdef WINDOWS32
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. */
248 static char *
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);
255 int path_is_dot = 0;
256 unsigned uniq = 1;
257 const unsigned sizemax = strlen (base) + strlen (ext) + 10;
259 if (path_size == 0)
261 path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
262 path_is_dot = 1;
265 while (path_size > 0 &&
266 path_size + sizemax < sizeof temp_path &&
267 uniq < 0x10000)
269 unsigned size = sprintf (temp_path + path_size,
270 "%s%s-%x.%s",
271 temp_path[path_size - 1] == '\\' ? "" : "\\",
272 base, uniq, ext);
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)
287 ++uniq;
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);
293 path_is_dot = 1;
296 else
298 error = map_windows32_error_to_string (er);
299 break;
302 else
304 const unsigned final_size = path_size + size + 1;
305 char *const path = (char *) xmalloc (final_size);
306 memcpy (path, temp_path, final_size);
307 CloseHandle (h);
308 if (unixy)
310 char *p;
311 int ch;
312 for (p = path; (ch = *p) != 0; ++p)
313 if (ch == '\\')
314 *p = '/';
316 return path; /* good return */
320 if (error == NULL)
321 error = _("Cannot create a temporary file\n");
322 fatal (NILF, error);
324 /* not reached */
325 return NULL;
327 #endif /* WINDOWS32 */
329 #ifdef __EMX__
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[] = {
336 "cmd.exe",
337 "cmd",
338 "4os2.exe",
339 "4os2",
340 "4dos.exe",
341 "4dos",
342 "command.com",
343 "command",
344 NULL
347 /* find the rightmost '/' or '\\' */
348 const char *name = strrchr (path, '/');
349 const char *p = strrchr (path, '\\');
350 unsigned i;
352 if (name && p) /* take the max */
353 name = (name > p) ? name : p;
354 else if (p) /* name must be 0 */
355 name = p;
356 else if (!name) /* name and p must be 0 */
357 name = path;
359 if (*name == '/' || *name == '\\') name++;
361 i = 0;
362 while (known_os2shells[i] != NULL) {
363 if (stricmp (name, known_os2shells[i]) == 0) /* strcasecmp() */
364 return 0; /* not a unix shell */
365 i++;
368 /* in doubt assume a unix like shell */
369 return 1;
371 #endif /* __EMX__ */
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. */
378 static void
379 child_error (char *target_name, int exit_code, int exit_sig, int coredump,
380 int ignored)
382 if (ignored && silent_flag)
383 return;
385 #ifdef VMS
386 if (!(exit_code & 1))
387 error (NILF,
388 (ignored ? _("*** [%s] Error 0x%x (ignored)")
389 : _("*** [%s] Error 0x%x")),
390 target_name, exit_code);
391 #else
392 if (exit_sig == 0)
393 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
394 _("*** [%s] Error %d"),
395 target_name, exit_code);
396 else
397 error (NILF, "*** [%s] %s%s",
398 target_name, strsignal (exit_sig),
399 coredump ? _(" (core dumped)") : "");
400 #endif /* VMS */
403 #ifdef VMS
404 /* Wait for nchildren children to terminate */
405 static void
406 vmsWaitForChildren(int *status)
408 while (1)
410 if (!vms_jobsefnmask)
412 *status = 0;
413 return;
416 *status = sys$wflor (32, vms_jobsefnmask);
418 return;
421 /* Set up IO redirection. */
423 char *
424 vms_redirect (struct dsc$descriptor_s *desc, char *fname, char *ibuf)
426 char *fptr;
427 extern char *vmsify ();
429 ibuf++;
430 while (isspace ((unsigned char)*ibuf))
431 ibuf++;
432 fptr = ibuf;
433 while (*ibuf && !isspace ((unsigned char)*ibuf))
434 ibuf++;
435 *ibuf = 0;
436 if (strcmp (fptr, "/dev/null") != 0)
438 strcpy (fname, vmsify (fptr, 0));
439 if (strchr (fname, '.') == 0)
440 strcat (fname, ".");
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;
447 if (*fname == 0)
448 printf (_("Warning: Empty redirection\n"));
449 return ibuf;
453 /* found apostrophe at (p-1)
454 inc p until after closing apostrophe.
457 static char *
458 vms_handle_apos (char *p)
460 int alast;
462 #define SEPCHARS ",/()= "
464 alast = 0;
466 while (*p != 0)
468 if (*p == '"')
470 if (alast)
472 alast = 0;
473 p++;
475 else
477 p++;
478 if (strchr (SEPCHARS, *p))
479 break;
480 alast = 1;
483 else
484 p++;
487 return p;
490 #endif
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;
505 RETSIGTYPE
506 child_handler (int sig UNUSED)
508 ++dead_children;
510 if (job_rfd >= 0)
512 close (job_rfd);
513 job_rfd = -1;
516 #ifdef __EMX__
517 /* The signal handler must called only once! */
518 signal (SIGCHLD, SIG_DFL);
519 #endif
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. */
535 void
536 reap_children (int block, int err)
538 WAIT_T status;
539 /* Initially, assume we have some. */
540 int reap_more = 1;
542 #ifdef WAIT_NOHANG
543 # define REAP_MORE reap_more
544 #else
545 # define REAP_MORE dead_children
546 #endif
548 /* As long as:
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))
559 int remote = 0;
560 pid_t pid;
561 int exit_code, exit_sig, coredump;
562 register struct child *lastc, *c;
563 int child_failed;
564 int any_remote, any_local;
566 if (err && block)
568 /* We might block for a while, so let the user know why. */
569 fflush (stdout);
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)
591 --dead_children;
593 any_remote = 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)") : ""));
602 #ifdef VMS
603 break;
604 #endif
607 /* First, check for remote children. */
608 if (any_remote)
609 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
610 else
611 pid = 0;
613 if (pid > 0)
614 /* We got a remote child. */
615 remote = 1;
616 else if (pid < 0)
618 /* A remote status command failed miserably. Punt. */
619 remote_status_lose:
620 pfatal_with_name ("remote_status");
622 else
624 /* No remote children. Check for local children. */
625 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
626 if (any_local)
628 #ifdef VMS
629 vmsWaitForChildren (&status);
630 pid = c->pid;
631 #else
632 #ifdef WAIT_NOHANG
633 if (!block)
634 pid = WAIT_NOHANG (&status);
635 else
636 #endif
637 pid = wait (&status);
638 #endif /* !VMS */
640 else
641 pid = 0;
643 if (pid < 0)
645 /* The wait*() failed miserably. Punt. */
646 pfatal_with_name ("wait");
648 else if (pid > 0)
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. */
656 if (job_counter)
657 --job_counter;
659 else
661 /* No local children are dead. */
662 reap_more = 0;
664 if (!block || !any_remote)
665 break;
667 /* Now try a blocking wait for a remote child. */
668 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
669 if (pid < 0)
670 goto remote_status_lose;
671 else if (pid == 0)
672 /* No remote children either. Finally give up. */
673 break;
675 /* We got a remote child. */
676 remote = 1;
678 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
680 #ifdef __MSDOS__
681 /* Life is very different on MSDOS. */
682 pid = dos_pid - 1;
683 status = dos_status;
684 exit_code = WEXITSTATUS (status);
685 if (exit_code == 0xff)
686 exit_code = -1;
687 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
688 coredump = 0;
689 #endif /* __MSDOS__ */
690 #ifdef _AMIGA
691 /* Same on Amiga */
692 pid = amiga_pid - 1;
693 status = amiga_status;
694 exit_code = amiga_status;
695 exit_sig = 0;
696 coredump = 0;
697 #endif /* _AMIGA */
698 #ifdef WINDOWS32
700 HANDLE hPID;
701 int err;
702 exit_code = 0;
703 exit_sig = 0;
704 coredump = 0;
706 /* wait for anything to finish */
707 hPID = process_wait_for_any();
708 if (hPID)
711 /* was an error found on this process? */
712 err = process_last_err(hPID);
714 /* get exit data */
715 exit_code = process_exit_code(hPID);
717 if (err)
718 fprintf(stderr, "make (e=%d): %s",
719 exit_code, map_windows32_error_to_string(exit_code));
721 /* signal */
722 exit_sig = process_signal(hPID);
724 /* cleanup process */
725 process_cleanup(hPID);
727 coredump = 0;
729 pid = (pid_t) 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;
740 else
741 shell_function_completed = 1;
742 break;
745 child_failed = exit_sig != 0 || exit_code != 0;
747 /* Search for a child matching the deceased one. */
748 lastc = 0;
749 for (c = children; c != 0; lastc = c, c = c->next)
750 if (c->remote == remote && c->pid == pid)
751 break;
753 if (c == 0)
754 /* An unknown child died.
755 Ignore it; it was inherited from our invoker. */
756 continue;
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"),
766 c->sh_batch_file));
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. */
777 if (c->good_stdin)
778 good_stdin_used = 0;
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);
795 else
797 if (child_failed)
799 /* The commands failed, but we don't care. */
800 child_error (c->file->name,
801 exit_code, exit_sig, coredump, 1);
802 child_failed = 0;
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;
816 else
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. */
828 unblock_sigs ();
829 if (c->file->command_state == cs_running)
830 /* We successfully started the new command.
831 Loop to reap more children. */
832 continue;
835 if (c->file->update_status != 0)
836 /* We failed to start the commands. */
837 delete_child_targets (c);
839 else
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. */
867 block_sigs ();
869 /* There is now another slot open. */
870 if (job_slots_used > 0)
871 --job_slots_used;
873 /* Remove the child from the chain and free it. */
874 if (lastc == 0)
875 children = c->next;
876 else
877 lastc->next = c->next;
879 free_child (c);
881 unblock_sigs ();
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)
888 die (2);
890 /* Only block for one child. */
891 block = 0;
894 return;
897 /* Free the storage allocated for CHILD. */
899 static void
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)
908 char token = '+';
909 int r;
911 /* Write a job token back to the pipe. */
913 EINTRLOOP (r, write (job_fds[1], &token, 1));
914 if (r != 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. */
922 return;
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;
935 while (*ep != 0)
936 free (*ep++);
937 free ((char *) child->environment);
940 free ((char *) child);
943 #ifdef POSIX
944 extern sigset_t fatal_signal_set;
945 #endif
947 void
948 block_sigs (void)
950 #ifdef POSIX
951 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
952 #else
953 # ifdef HAVE_SIGSETMASK
954 (void) sigblock (fatal_signal_mask);
955 # endif
956 #endif
959 #ifdef POSIX
960 void
961 unblock_sigs (void)
963 sigset_t empty;
964 sigemptyset (&empty);
965 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
967 #endif
969 #ifdef MAKE_JOBSERVER
970 /* Set the child handler action flags to FLAGS. */
971 static void
972 set_child_handler_action_flags (int flags)
974 struct sigaction sa;
975 bzero ((char *) &sa, sizeof sa);
976 sa.sa_handler = child_handler;
977 sa.sa_flags = flags;
978 #if defined SIGCHLD
979 sigaction (SIGCHLD, &sa, NULL);
980 #endif
981 #if defined SIGCLD && SIGCLD != SIGCHLD
982 sigaction (SIGCLD, &sa, NULL);
983 #endif
985 #endif
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. */
995 static void
996 start_job_command (struct child *child)
998 #ifndef _AMIGA
999 static int bad_stdin = -1;
1000 #endif
1001 register char *p;
1002 int flags;
1003 #ifdef VMS
1004 char *argv;
1005 #else
1006 char **argv;
1007 #endif
1009 /* If we have a completely empty commandset, stop now. */
1010 if (!child->command_ptr)
1011 goto next_command;
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;
1021 while (*p != '\0')
1023 if (*p == '@')
1024 flags |= COMMANDS_SILENT;
1025 else if (*p == '+')
1026 flags |= COMMANDS_RECURSE;
1027 else if (*p == '-')
1028 child->noerror = 1;
1029 else if (!isblank ((unsigned char)*p))
1030 break;
1031 ++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. */
1046 char *end = 0;
1047 #ifdef VMS
1048 argv = p;
1049 #else
1050 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
1051 #endif
1052 if (end == NULL)
1053 child->command_ptr = NULL;
1054 else
1056 *end++ = '\0';
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
1064 error is 2. */
1065 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
1067 #ifndef VMS
1068 free (argv[0]);
1069 free ((char *) argv);
1070 #endif
1071 child->file->update_status = 1;
1072 notice_finished_file (child->file);
1073 return;
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. */
1080 #ifndef VMS
1081 if (argv)
1083 free (argv[0]);
1084 free ((char *) argv);
1086 #endif
1087 argv = 0;
1090 if (argv == 0)
1092 next_command:
1093 #ifdef __MSDOS__
1094 execute_by_shell = 0; /* in case construct_command_argv sets it */
1095 #endif
1096 /* This line has no commands. Go to the next. */
1097 if (job_next_command (child))
1098 start_job_command (child);
1099 else
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);
1107 return;
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
1112 appear. */
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. */
1124 ++commands_started;
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
1130 printed, etc. */
1132 #if !defined(VMS) && !defined(_AMIGA)
1133 if (
1134 #if defined __MSDOS__ || defined (__EMX__)
1135 unixy_shell /* the test is complicated and we already did it */
1136 #else
1137 (argv[0] && !strcmp (argv[0], "/bin/sh"))
1138 #endif
1139 && (argv[1]
1140 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
1141 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1142 && argv[3] == NULL)
1144 free (argv[0]);
1145 free ((char *) argv);
1146 goto next_command;
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))
1154 #ifndef VMS
1155 free (argv[0]);
1156 free ((char *) argv);
1157 #endif
1158 goto next_command;
1161 /* Flush the output streams so they won't have things written twice. */
1163 fflush (stdout);
1164 fflush (stderr);
1166 #ifndef VMS
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. */
1175 int pd[2];
1176 if (pipe (pd) == 0)
1178 /* Close the write side. */
1179 (void) close (pd[1]);
1180 /* Save the read side. */
1181 bad_stdin = pd[0];
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;
1200 #endif /* !VMS */
1202 child->deleted = 0;
1204 #ifndef _AMIGA
1205 /* Set up the environment for the child. */
1206 if (child->environment == 0)
1207 child->environment = target_environment (child->file);
1208 #endif
1210 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1212 #ifndef VMS
1213 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1214 if (child->remote)
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. */
1222 goto run_local;
1223 else
1225 if (child->good_stdin && !used_stdin)
1227 child->good_stdin = 0;
1228 good_stdin_used = 0;
1230 child->remote = is_remote;
1231 child->pid = id;
1234 else
1235 #endif /* !VMS */
1237 /* Fork the child process. */
1239 char **parent_environ;
1241 run_local:
1242 block_sigs ();
1244 child->remote = 0;
1246 #ifdef VMS
1248 if (!child_execute_job (argv, child)) {
1249 /* Fork failed! */
1250 perror_with_name ("vfork", "");
1251 goto error;
1254 #else
1256 parent_environ = environ;
1258 # ifdef __EMX__
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]);
1266 if (job_rfd >= 0)
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);
1272 if (child->pid < 0)
1274 /* spawn failed! */
1275 unblock_sigs ();
1276 perror_with_name ("spawn", "");
1277 goto error;
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);
1286 if (job_rfd >= 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. */
1296 unblock_sigs ();
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)
1302 close (job_fds[0]);
1303 close (job_fds[1]);
1305 if (job_rfd >= 0)
1306 close (job_rfd);
1308 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1309 argv, child->environment);
1311 else if (child->pid < 0)
1313 /* Fork failed! */
1314 unblock_sigs ();
1315 perror_with_name ("vfork", "");
1316 goto error;
1318 # endif /* !__EMX__ */
1319 #endif /* !VMS */
1322 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1323 #ifdef __MSDOS__
1325 int proc_return;
1327 block_sigs ();
1328 dos_status = 0;
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. */
1345 if (unixy_shell)
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 */
1357 else
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). */
1366 unblock_sigs ();
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)
1372 dos_status |= 0xff;
1373 else
1374 dos_status |= (proc_return & 0xff);
1375 ++dead_children;
1376 child->pid = dos_pid++;
1378 #endif /* __MSDOS__ */
1379 #ifdef _AMIGA
1380 amiga_status = MyExecute (argv);
1382 ++dead_children;
1383 child->pid = amiga_pid++;
1384 if (amiga_batch_file)
1386 amiga_batch_file = 0;
1387 DeleteFile (amiga_bname); /* Ignore errors. */
1389 #endif /* Amiga */
1390 #ifdef WINDOWS32
1392 HANDLE hPID;
1393 char* arg0;
1395 /* make UNC paths safe for CreateProcess -- backslash format */
1396 arg0 = argv[0];
1397 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1398 for ( ; arg0 && *arg0; arg0++)
1399 if (*arg0 == '/')
1400 *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;
1409 else {
1410 int i;
1411 unblock_sigs();
1412 fprintf(stderr,
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. */
1424 ++job_counter;
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. */
1432 #ifndef VMS
1433 free (argv[0]);
1434 free ((char *) argv);
1435 #endif
1437 return;
1439 error:
1440 child->file->update_status = 2;
1441 notice_finished_file (child->file);
1442 return;
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. */
1449 static int
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
1465 to go down. */
1466 set_command_state (f, cs_running);
1467 c->next = waiting_jobs;
1468 waiting_jobs = c;
1469 return 0;
1472 /* Start the first command; reap_children will run later command lines. */
1473 start_job_command (c);
1475 switch (f->command_state)
1477 case cs_running:
1478 c->next = children;
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)") : ""));
1482 children = c;
1483 /* One more job slot is in use. */
1484 ++job_slots_used;
1485 unblock_sigs ();
1486 break;
1488 case cs_not_started:
1489 /* All the command lines turned out to be empty. */
1490 f->update_status = 0;
1491 /* FALLTHROUGH */
1493 case cs_finished:
1494 notice_finished_file (f);
1495 free_child (c);
1496 break;
1498 default:
1499 assert (f->command_state == cs_finished);
1500 break;
1503 return 1;
1506 /* Create a `struct child' for FILE and start its commands running. */
1508 void
1509 new_job (struct file *file)
1511 register struct commands *cmds = file->cmds;
1512 register struct child *c;
1513 char **lines;
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 $. */
1549 if (out != in)
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. */
1556 out += ref - in;
1557 in = ref;
1559 if (*ref == '(' || *ref == '{')
1561 char openparen = *ref;
1562 char closeparen = openparen == '(' ? ')' : '}';
1563 int count;
1564 char *p;
1566 *out++ = *in++; /* Copy OPENPAREN. */
1567 /* IN now points past the opening paren or brace.
1568 Count parens or braces until it is matched. */
1569 count = 0;
1570 while (*in != '\0')
1572 if (*in == closeparen && --count < 0)
1573 break;
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. */
1580 int quoted = 0;
1581 for (p = in - 1; p > ref && *p == '\\'; --p)
1582 quoted = !quoted;
1584 if (quoted)
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. */
1590 *out++ = *in++;
1591 else
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. */
1599 while (out > ref
1600 && isblank ((unsigned char)out[-1]))
1601 --out;
1603 /* Replace it all with a single space. */
1604 *out++ = ' ';
1607 else
1609 if (*in == openparen)
1610 ++count;
1612 *out++ = *in++;
1618 /* There are no more references in this line to worry about.
1619 Copy the remaining uninteresting text to the output. */
1620 if (out != in)
1621 strcpy (out, in);
1623 /* Finally, expand the line. */
1624 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1625 file);
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));
1633 c->file = file;
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. */
1643 if (job_slots != 0)
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)
1661 while (1)
1663 char token;
1664 int got_token;
1665 int saved_errno;
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. */
1671 if (!children)
1672 break;
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. */
1697 if (job_rfd < 0)
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. */
1707 if (!children)
1708 break;
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;
1714 #ifdef __EMX__
1715 /* The child handler must be turned off here. */
1716 signal (SIGCHLD, SIG_DFL);
1717 #endif
1718 set_child_handler_action_flags (SA_RESTART);
1720 /* If we got one, we're done here. */
1721 if (got_token == 1)
1723 DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1724 (unsigned long int) c, c->file->name));
1725 break;
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"));
1733 if (errno == EBADF)
1734 DB (DB_JOBS, ("Read returned EBADF.\n"));
1736 #endif
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);
1748 return;
1751 /* Move CHILD's pointers to the next command for it to execute.
1752 Returns nonzero if there is another command. */
1754 static int
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;
1764 return 0;
1766 else
1767 /* Get the next line to run. */
1768 child->command_ptr = child->command_lines[child->command_line++];
1770 return 1;
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>,
1784 who writes:
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
1813 static int
1814 load_too_high (void)
1816 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
1817 return 1;
1818 #else
1819 static double last_sec;
1820 static time_t last_now;
1821 double load, guess;
1822 time_t now;
1824 if (max_load_average < 0)
1825 return 0;
1827 /* Find the real system load average. */
1828 make_access ();
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)
1835 if (errno == 0)
1836 /* An errno value of zero means getloadavg is just unsupported. */
1837 error (NILF,
1838 _("cannot enforce load limits on this operating system"));
1839 else
1840 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1842 lossage = errno;
1843 load = 0;
1845 user_access ();
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. */
1849 now = time (NULL);
1850 if (last_now < now)
1852 if (last_now == now - 1)
1853 last_sec = LOAD_WEIGHT_B * job_counter;
1854 else
1855 last_sec = 0.0;
1857 job_counter = 0;
1858 last_now = now;
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;
1868 #endif
1871 /* Start jobs that are waiting for the load to be lower. */
1873 void
1874 start_waiting_jobs (void)
1876 struct child *job;
1878 if (waiting_jobs == 0)
1879 return;
1883 /* Check for recently deceased descendants. */
1884 reap_children (0, 0);
1886 /* Take a job off the waiting list. */
1887 job = waiting_jobs;
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);
1895 return;
1898 #ifndef WINDOWS32
1899 #ifdef VMS
1900 #include <descrip.h>
1901 #include <clidef.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)
1908 int status;
1909 register struct child *lastc, *c;
1910 int child_failed;
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. */
1921 lastc = 0;
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);
1924 #else
1925 c = child;
1926 #endif
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);
1936 else
1938 if (child_failed)
1940 /* The commands failed, but we don't care. */
1941 child_error (c->file->name, c->cstatus, 0, 0, 1);
1942 child_failed = 0;
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. */
1947 start_job (c);
1949 switch (c->file->command_state)
1951 case cs_running:
1952 /* Successfully started. */
1953 break;
1955 case cs_finished:
1956 if (c->file->update_status != 0) {
1957 /* We failed to start the commands. */
1958 delete_child_targets (c);
1960 break;
1962 default:
1963 error (NILF, _("internal error: `%s' command_state"),
1964 c->file->name);
1965 abort ();
1966 break;
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. */
1977 if (lastc == 0)
1978 children = c->next;
1979 else
1980 lastc->next = c->next;
1981 free_child (c);
1982 #endif /* RECURSIVEJOBS */
1984 /* There is now another slot open. */
1985 if (job_slots_used > 0)
1986 --job_slots_used;
1988 /* If the job failed, and the -k flag was not given, die. */
1989 if (child_failed && !keep_going_flag)
1990 die (EXIT_FAILURE);
1992 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1994 return 1;
1997 /* VMS:
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 */
2003 #include <iodef.h>
2004 #include <libclidef.h>
2005 #include <ssdef.h>
2007 static int ctrlMask= LIB$M_CLI_CTRLY;
2008 static int oldCtrlMask;
2009 static int setupYAstTried= 0;
2010 static int pidToAbort= 0;
2011 static int chan= 0;
2013 static void reEnableAst(void) {
2014 lib$enable_ctrl (&oldCtrlMask,0);
2017 static astHandler (void) {
2018 if (pidToAbort) {
2019 sys$forcex (&pidToAbort, 0, SS$_ABORT);
2020 pidToAbort= 0;
2022 kill (getpid(),SIGQUIT);
2025 static void tryToSetupYAst(void) {
2026 $DESCRIPTOR(inputDsc,"SYS$COMMAND");
2027 int status;
2028 struct {
2029 short int status, count;
2030 int dvi;
2031 } iosb;
2033 setupYAstTried++;
2035 if (!chan) {
2036 status= sys$assign(&inputDsc,&chan,0,0);
2037 if (!(status&SS$_NORMAL)) {
2038 lib$signal(status);
2039 return;
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) {
2047 sys$dassgn(chan);
2048 #ifdef CTRLY_ENABLED_ANYWAY
2049 fprintf (stderr,
2050 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
2051 #else
2052 return;
2053 #endif
2055 else if (!(status&SS$_NORMAL)) {
2056 sys$dassgn(chan);
2057 lib$signal(status);
2058 return;
2061 /* called from AST handler ? */
2062 if (setupYAstTried>1)
2063 return;
2064 if (atexit(reEnableAst))
2065 fprintf (stderr,
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)) {
2069 lib$signal(status);
2070 return;
2074 child_execute_job (char *argv, struct child *child)
2076 int i;
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;
2086 int status;
2087 char *cmd = alloca (strlen (argv) + 512), *p, *q;
2088 char ifile[256], ofile[256], efile[256];
2089 char *comname = 0;
2090 char procname[100];
2091 int in_string;
2093 /* Parse IO redirection. */
2095 ifile[0] = 0;
2096 ofile[0] = 0;
2097 efile[0] = 0;
2099 DB (DB_JOBS, ("child_execute_job (%s)\n", argv));
2101 while (isspace ((unsigned char)*argv))
2102 argv++;
2104 if (*argv == 0)
2105 return 0;
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;
2113 in_string = 0;
2114 /* Handle comments and redirection. */
2115 for (p = argv, q = cmd; *p; p++, q++)
2117 if (*p == '"')
2118 in_string = !in_string;
2119 if (in_string)
2121 *q = *p;
2122 continue;
2124 switch (*p)
2126 case '#':
2127 *p-- = 0;
2128 *q-- = 0;
2129 break;
2130 case '\\':
2131 p++;
2132 if (*p == '\n')
2133 p++;
2134 if (isspace ((unsigned char)*p))
2136 do { p++; } while (isspace ((unsigned char)*p));
2137 p--;
2139 *q = *p;
2140 break;
2141 case '<':
2142 p = vms_redirect (&ifiledsc, ifile, p);
2143 *q = ' ';
2144 have_redirection = 1;
2145 break;
2146 case '>':
2147 have_redirection = 1;
2148 if (*(p-1) == '2')
2150 q--;
2151 if (strncmp (p, ">&1", 3) == 0)
2153 p += 3;
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;
2160 else
2162 p = vms_redirect (&efiledsc, efile, p);
2165 else
2167 p = vms_redirect (&ofiledsc, ofile, p);
2169 *q = ' ';
2170 break;
2171 case '\n':
2172 have_newline = 1;
2173 default:
2174 *q = *p;
2175 break;
2178 *q = *p;
2179 while (isspace ((unsigned char)*--q))
2180 *q = '\0';
2182 if (strncmp (cmd, "builtin_", 8) == 0)
2184 child->pid = 270163;
2185 child->efn = 0;
2186 child->cstatus = 1;
2188 DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));
2190 p = cmd + 8;
2192 if ((*(p) == 'c')
2193 && (*(p+1) == 'd')
2194 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
2196 p += 3;
2197 while ((*p == ' ') || (*p == '\t'))
2198 p++;
2199 DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
2200 if (chdir (p))
2201 return 0;
2202 else
2203 return 1;
2205 else if ((*(p) == 'r')
2206 && (*(p+1) == 'm')
2207 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
2209 int in_arg;
2211 /* rm */
2212 p += 3;
2213 while ((*p == ' ') || (*p == '\t'))
2214 p++;
2215 in_arg = 1;
2217 DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
2218 while (*p)
2220 switch (*p)
2222 case ' ':
2223 case '\t':
2224 if (in_arg)
2226 *p++ = ';';
2227 in_arg = 0;
2229 break;
2230 default:
2231 break;
2233 p++;
2236 else
2238 printf(_("Unknown builtin command '%s'\n"), cmd);
2239 fflush(stdout);
2240 return 0;
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))
2253 FILE *outfile;
2254 char c;
2255 char *sep;
2256 int alevel = 0; /* apostrophe level */
2258 if (strlen (cmd) == 0)
2260 printf (_("Error, empty command\n"));
2261 fflush (stdout);
2262 return 0;
2265 outfile = open_tmpfile (&comname, "sys$scratch:CMDXXXXXX.COM");
2266 if (outfile == 0)
2267 pfatal_with_name (_("fopen (temporary file)"));
2269 if (ifile[0])
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;
2276 if (efile[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;
2283 if (ofile[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;
2290 p = sep = q = cmd;
2291 for (c = '\n'; c; c = *q++)
2293 switch (c)
2295 case '\n':
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))
2299 p++;
2300 if (*p == '$')
2301 p++;
2302 while (isspace ((unsigned char)*p))
2303 p++;
2304 fwrite (p, 1, q - p, outfile);
2305 fputc ('$', outfile);
2306 fputc (' ', outfile);
2307 /* Reset variables. */
2308 p = sep = q;
2309 break;
2311 /* Nice places for line breaks are after strings, after
2312 comma or space and before slash. */
2313 case '"':
2314 q = vms_handle_apos (q);
2315 sep = q;
2316 break;
2317 case ',':
2318 case ' ':
2319 sep = q;
2320 break;
2321 case '/':
2322 case '\0':
2323 sep = q - 1;
2324 break;
2325 default:
2326 break;
2328 if (sep - p > 78)
2330 /* Enough stuff for a line. */
2331 fwrite (p, 1, sep - p, outfile);
2332 p = sep;
2333 if (*sep)
2335 /* The command continues. */
2336 fputc ('-', outfile);
2338 fputc ('\n', outfile);
2342 fwrite (p, 1, q - p, outfile);
2343 fputc ('\n', outfile);
2345 fclose (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;
2357 child->efn = 0;
2358 while (child->efn < 32 || child->efn > 63)
2360 status = lib$get_ef ((unsigned long *)&child->efn);
2361 if (!(status & 1))
2362 return 0;
2365 sys$clref (child->efn);
2367 vms_jobsefnmask |= (1 << (child->efn - 32));
2370 LIB$SPAWN [command-string]
2371 [,input-file]
2372 [,output-file]
2373 [,flags]
2374 [,process-name]
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)
2420 tryToSetupYAst();
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,
2427 0, 0,
2428 0, 0, 0);
2429 if (status & 1)
2431 pidToAbort= child->pid;
2432 status= sys$waitfr (child->efn);
2433 pidToAbort= 0;
2434 vmsHandleChildTerm(child);
2436 #else
2437 status = lib$spawn (&cmddsc,
2438 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
2439 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
2440 &spflags,
2441 &pnamedsc,
2442 &child->pid, &child->cstatus, &child->efn,
2443 vmsHandleChildTerm, child,
2444 0, 0, 0);
2445 #endif
2447 if (!(status & 1))
2449 printf (_("Error spawning, %d\n") ,status);
2450 fflush (stdout);
2451 switch (status)
2453 case 0x1c:
2454 errno = EPROCLIM;
2455 break;
2456 default:
2457 errno = EFAIL;
2461 if (comname && !ISDB (DB_JOBS))
2462 unlink (comname);
2464 return (status & 1);
2467 #else /* !VMS */
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)
2474 int pid;
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 */
2481 if (save_stdin < 0)
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. */
2493 if (stdin_fd != 0)
2494 (void) dup2 (stdin_fd, 0);
2495 if (stdout_fd != 1)
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 */
2500 if (stdin_fd != 0)
2501 CLOSE_ON_EXEC (stdin_fd);
2502 if (stdout_fd != 1)
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. */
2509 if (stdin_fd != 0)
2511 if (dup2 (save_stdin, 0) != 0)
2512 fatal (NILF, _("Could not restore stdin\n"));
2513 else
2514 close (save_stdin);
2517 if (stdout_fd != 1)
2519 if (dup2 (save_stdout, 1) != 1)
2520 fatal (NILF, _("Could not restore stdout\n"));
2521 else
2522 close (save_stdout);
2525 return pid;
2528 #elif !defined (_AMIGA) && !defined (__MSDOS__)
2530 /* UNIX:
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. */
2534 void
2535 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2537 if (stdin_fd != 0)
2538 (void) dup2 (stdin_fd, 0);
2539 if (stdout_fd != 1)
2540 (void) dup2 (stdout_fd, 1);
2541 if (stdin_fd != 0)
2542 (void) close (stdin_fd);
2543 if (stdout_fd != 1)
2544 (void) close (stdout_fd);
2546 /* Run the command. */
2547 exec_command (argv, envp);
2549 #endif /* !AMIGA && !__MSDOS__ */
2550 #endif /* !VMS */
2551 #endif /* !WINDOWS32 */
2553 #ifndef _AMIGA
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. */
2558 # ifdef __EMX__
2560 # else
2561 void
2562 # endif
2563 exec_command (char **argv, char **envp)
2565 #ifdef VMS
2566 /* to work around a problem with signals and execve: ignore them */
2567 #ifdef SIGCHLD
2568 signal (SIGCHLD,SIG_IGN);
2569 #endif
2570 /* Run the program. */
2571 execve (argv[0], argv, envp);
2572 perror_with_name ("execve: ", argv[0]);
2573 _exit (EXIT_FAILURE);
2574 #else
2575 #ifdef WINDOWS32
2576 HANDLE hPID;
2577 HANDLE hWaitPID;
2578 int err = 0;
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)
2590 int i;
2591 fprintf(stderr,
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);
2597 exit(EXIT_FAILURE);
2600 /* wait and reap last child */
2601 hWaitPID = process_wait_for_any();
2602 while (hWaitPID)
2604 /* was an error found on this process? */
2605 err = process_last_err(hWaitPID);
2607 /* get exit data */
2608 exit_code = process_exit_code(hWaitPID);
2610 if (err)
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)
2619 break;
2620 else
2621 fprintf(stderr,
2622 _("make reaped child pid %d, still waiting for pid %d\n"),
2623 hWaitPID, hPID);
2626 /* return child's exit code as our exit code */
2627 exit(exit_code);
2629 #else /* !WINDOWS32 */
2631 # ifdef __EMX__
2632 int pid;
2633 # endif
2635 /* Be the user, permanently. */
2636 child_access ();
2638 # ifdef __EMX__
2640 /* Run the program. */
2641 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2643 if (pid >= 0)
2644 return pid;
2646 /* the file might have a strange shell extension */
2647 if (errno == ENOENT)
2648 errno = ENOEXEC;
2650 # else
2652 /* Run the program. */
2653 environ = envp;
2654 execvp (argv[0], argv);
2656 # endif /* !__EMX__ */
2658 switch (errno)
2660 case ENOENT:
2661 error (NILF, _("%s: Command not found"), argv[0]);
2662 break;
2663 case ENOEXEC:
2665 /* The file is not executable. Try it as a shell script. */
2666 extern char *getenv ();
2667 char *shell;
2668 char **new_argv;
2669 int argc;
2670 int i=1;
2672 # ifdef __EMX__
2673 /* Do not use $SHELL from the environment */
2674 struct variable *p = lookup_variable ("SHELL", 5);
2675 if (p)
2676 shell = p->value;
2677 else
2678 shell = 0;
2679 # else
2680 shell = getenv ("SHELL");
2681 # endif
2682 if (shell == 0)
2683 shell = default_shell;
2685 argc = 1;
2686 while (argv[argc] != 0)
2687 ++argc;
2689 # ifdef __EMX__
2690 if (!unixy_shell)
2691 ++argc;
2692 # endif
2694 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
2695 new_argv[0] = shell;
2697 # ifdef __EMX__
2698 if (!unixy_shell)
2700 new_argv[1] = "/c";
2701 ++i;
2702 --argc;
2704 # endif
2706 new_argv[i] = argv[0];
2707 while (argc > 0)
2709 new_argv[i + argc] = argv[argc];
2710 --argc;
2713 # ifdef __EMX__
2714 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2715 if (pid >= 0)
2716 break;
2717 # else
2718 execvp (shell, new_argv);
2719 # endif
2720 if (errno == ENOENT)
2721 error (NILF, _("%s: Shell program not found"), shell);
2722 else
2723 perror_with_name ("execvp: ", shell);
2724 break;
2727 # ifdef __EMX__
2728 case EINVAL:
2729 /* this nasty error was driving me nuts :-( */
2730 error (NILF, _("spawnvpe: environment space might be exhausted"));
2731 /* FALLTHROUGH */
2732 # endif
2734 default:
2735 perror_with_name ("execvp: ", argv[0]);
2736 break;
2739 # ifdef __EMX__
2740 return pid;
2741 # else
2742 _exit (127);
2743 # endif
2744 #endif /* !WINDOWS32 */
2745 #endif /* !VMS */
2747 #else /* On Amiga */
2748 void exec_command (char **argv)
2750 MyExecute (argv);
2753 void clean_tmp (void)
2755 DeleteFile (amiga_bname);
2758 #endif /* On Amiga */
2760 #ifndef VMS
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). */
2774 static char **
2775 construct_command_argv_internal (char *line, char **restp, char *shell,
2776 char *ifs, char **batch_filename_ptr)
2778 #ifdef __MSDOS__
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",
2808 "vol", ":", 0 };
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",
2816 0 };
2818 char *sh_chars;
2819 char **sh_cmds;
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",
2828 "vol", ":", 0 };
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",
2845 0 };
2846 char *sh_chars;
2847 char **sh_cmds;
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",
2855 0 };
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
2871 "echo",
2872 #endif
2873 0 };
2874 char* sh_chars;
2875 char** sh_cmds;
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 };
2886 #endif
2887 register int i;
2888 register char *p;
2889 register char *ap;
2890 char *end;
2891 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2892 char **new_argv = 0;
2893 #ifdef WINDOWS32
2894 int slow_flag = 0;
2896 if (no_default_sh_exe) {
2897 sh_cmds = sh_cmds_dos;
2898 sh_chars = sh_chars_dos;
2899 } else {
2900 sh_cmds = sh_cmds_sh;
2901 sh_chars = sh_chars_sh;
2903 #endif /* WINDOWS32 */
2905 if (restp != NULL)
2906 *restp = NULL;
2908 /* Make sure not to bother processing an empty line. */
2909 while (isblank ((unsigned char)*line))
2910 ++line;
2911 if (*line == '\0')
2912 return 0;
2914 /* See if it is safe to parse commands internally. */
2915 if (shell == 0)
2916 shell = default_shell;
2917 #ifdef WINDOWS32
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 : ""));
2925 if (s1)
2926 free (s1);
2927 if (s2)
2928 free (s2);
2930 if (slow_flag)
2931 goto slow;
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);
2945 if (unixy_shell)
2947 sh_chars = sh_chars_sh;
2948 sh_cmds = sh_cmds_sh;
2950 else
2952 sh_chars = sh_chars_dos;
2953 sh_cmds = sh_cmds_dos;
2954 # ifdef __EMX__
2955 if (_osmode == OS2_MODE)
2957 sh_chars = sh_chars_os2;
2958 sh_cmds = sh_cmds_os2;
2960 # endif
2962 #else /* !__MSDOS__ */
2963 else if (strcmp (shell, default_shell))
2964 goto slow;
2965 #endif /* !__MSDOS__ && !__EMX__ */
2966 #endif /* not WINDOWS32 */
2968 if (ifs != 0)
2969 for (ap = ifs; *ap != '\0'; ++ap)
2970 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2971 goto slow;
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);
2980 end = ap + i;
2982 /* I is how many complete arguments have been found. */
2983 i = 0;
2984 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2985 for (p = line; *p != '\0'; ++p)
2987 if (ap > end)
2988 abort ();
2990 if (instring)
2992 string_char:
2993 /* Inside a string, just copy any char except a closing quote
2994 or a backslash-newline combination. */
2995 if (*p == instring)
2997 instring = 0;
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. */
3006 *restp = p;
3007 goto end_of_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)
3014 goto slow;
3015 else
3016 *ap++ = *p;
3018 else if (strchr (sh_chars, *p) != 0)
3019 /* Not inside a string, but it's a special char. */
3020 goto slow;
3021 #ifdef __MSDOS__
3022 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
3023 /* `...' is a wildcard in DJGPP. */
3024 goto slow;
3025 #endif
3026 else
3027 /* Not a special char. */
3028 switch (*p)
3030 case '=':
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
3034 shell flags. */
3035 if (! seen_nonequals && unixy_shell)
3036 goto slow;
3037 word_has_equals = 1;
3038 *ap++ = '=';
3039 break;
3041 case '\\':
3042 /* Backslash-newline combinations are eaten. */
3043 if (p[1] == '\n')
3045 swallow_escaped_newline:
3047 /* Eat the backslash, the newline, and following whitespace,
3048 replacing it all with a single space. */
3049 p += 2;
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. */
3055 if (*p == '\t')
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));
3061 if (instring)
3062 goto string_char;
3063 else
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. */
3069 goto end_of_arg;
3070 else
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. */
3084 #ifdef __MSDOS__
3085 /* A dot is only special as part of the "..."
3086 wildcard. */
3087 if (strneq (p + 1, ".\\.\\.", 5))
3089 *ap++ = '.';
3090 *ap++ = '.';
3091 p += 4;
3093 else
3094 #endif
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 */
3099 --p;
3100 #endif /* HAVE_DOS_PATHS */
3102 /* Copy and skip the following char. */
3103 *ap++ = *++p;
3105 break;
3107 case '\'':
3108 case '"':
3109 instring = *p;
3110 break;
3112 case '\n':
3113 if (restp != NULL)
3115 /* End of the command line. */
3116 *restp = p;
3117 goto end_of_line;
3119 else
3120 /* Newlines are not special. */
3121 *ap++ = '\n';
3122 break;
3124 case ' ':
3125 case '\t':
3126 end_of_arg:
3127 /* We have the end of an argument.
3128 Terminate the text of the argument. */
3129 *ap++ = '\0';
3130 new_argv[++i] = ap;
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. */
3139 goto slow;
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. */
3145 if (i == 1)
3147 register int j;
3148 for (j = 0; sh_cmds[j] != 0; ++j)
3150 if (streq (sh_cmds[j], new_argv[0]))
3151 goto slow;
3152 # ifdef __EMX__
3153 /* Non-Unix shells are case insensitive. */
3154 if (!unixy_shell
3155 && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
3156 goto slow;
3157 # endif
3161 /* Ignore multiple whitespace chars. */
3162 p = next_token (p);
3163 /* Next iteration should examine the first nonwhite char. */
3164 --p;
3165 break;
3167 default:
3168 *ap++ = *p;
3169 break;
3172 end_of_line:
3174 if (instring)
3175 /* Let the shell deal with an unterminated quote. */
3176 goto slow;
3178 /* Terminate the last argument and the argument list. */
3180 *ap = '\0';
3181 if (new_argv[i][0] != '\0' || last_argument_was_empty)
3182 ++i;
3183 new_argv[i] = 0;
3185 if (i == 1)
3187 register int j;
3188 for (j = 0; sh_cmds[j] != 0; ++j)
3189 if (streq (sh_cmds[j], new_argv[0]))
3190 goto slow;
3193 if (new_argv[0] == 0)
3194 /* Line was empty. */
3195 return 0;
3197 return new_argv;
3199 slow:;
3200 /* We must use the shell. */
3202 if (new_argv != 0)
3204 /* Free the old argument list we were working on. */
3205 free (new_argv[0]);
3206 free ((void *)new_argv);
3209 #ifdef __MSDOS__
3210 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
3211 #endif
3213 #ifdef _AMIGA
3215 char *ptr;
3216 char *buffer;
3217 char *dptr;
3219 buffer = (char *)xmalloc (strlen (line)+1);
3221 ptr = line;
3222 for (dptr=buffer; *ptr; )
3224 if (*ptr == '\\' && ptr[1] == '\n')
3225 ptr += 2;
3226 else if (*ptr == '@') /* Kludge: multiline commands */
3228 ptr += 2;
3229 *dptr++ = '\n';
3231 else
3232 *dptr++ = *ptr++;
3234 *dptr = 0;
3236 new_argv = (char **) xmalloc (2 * sizeof (char *));
3237 new_argv[0] = buffer;
3238 new_argv[1] = 0;
3240 #else /* Not Amiga */
3241 #ifdef WINDOWS32
3243 * Not eating this whitespace caused things like
3245 * sh -c "\n"
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))
3254 ++line;
3255 if (*line == '\0')
3256 return 0;
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
3262 argument list. */
3264 unsigned int shell_len = strlen (shell);
3265 #ifndef VMS
3266 static char minus_c[] = " -c ";
3267 #else
3268 static char minus_c[] = "";
3269 #endif
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? */
3277 if (!unixy_shell)
3278 minus_c[1] = '/'; /* " /c " */
3279 # endif
3281 ap = new_line;
3282 bcopy (shell, ap, shell_len);
3283 ap += shell_len;
3284 bcopy (minus_c, ap, sizeof (minus_c) - 1);
3285 ap += sizeof (minus_c) - 1;
3286 command_ptr = ap;
3287 for (p = line; *p != '\0'; ++p)
3289 if (restp != NULL && *p == '\n')
3291 *restp = p;
3292 break;
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
3298 from the shell). */
3299 p += 2;
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. */
3305 if (*p == '\t')
3306 bcopy (p + 1, p, strlen (p));
3308 p = next_token (p);
3309 --p;
3310 if (unixy_shell && !batch_mode_shell)
3311 *ap++ = '\\';
3312 *ap++ = ' ';
3313 continue;
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))
3321 *ap++ = '\\';
3322 #ifdef __MSDOS__
3323 else if (unixy_shell && strneq (p, "...", 3))
3325 /* The case of `...' wildcard again. */
3326 strcpy (ap, "\\.\\.\\");
3327 ap += 5;
3328 p += 2;
3330 #endif
3331 *ap++ = *p;
3333 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
3334 /* Line was empty. */
3335 return 0;
3336 *ap = '\0';
3338 #ifdef WINDOWS32
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) {
3343 FILE* batch = NULL;
3344 int id = GetCurrentProcessId();
3345 PATH_VAR(fbuf);
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");
3356 if (!unixy_shell)
3357 fputs ("@echo off\n", batch);
3358 fputs (command_ptr, batch);
3359 fputc ('\n', batch);
3360 fclose (batch);
3362 /* create argv */
3363 new_argv = (char **) xmalloc(3 * sizeof (char *));
3364 if (unixy_shell) {
3365 new_argv[0] = xstrdup (shell);
3366 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
3367 } else {
3368 new_argv[0] = xstrdup (*batch_filename_ptr);
3369 new_argv[1] = NULL;
3371 new_argv[2] = NULL;
3372 } else
3373 #endif /* WINDOWS32 */
3374 if (unixy_shell)
3375 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
3376 (char *) 0, (char *) 0,
3377 (char **) 0);
3378 #ifdef __EMX__
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
3383 manually. */
3384 size_t line_len = strlen (line);
3385 char *p = new_line;
3386 char *q = new_line;
3387 memcpy (new_line, line, line_len + 1);
3388 /* replace all backslash-newline combination and also following tabs */
3389 while (*q != '\0')
3391 if (q[0] == '\\' && q[1] == '\n')
3393 q += 2; /* remove '\\' and '\n' */
3394 if (q[0] == '\t')
3395 q++; /* remove 1st tab in the next line */
3397 else
3398 *p++ = *q++;
3400 *p = '\0';
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';
3427 # endif
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);
3444 new_argv[3] = NULL;
3447 #elif defined(__MSDOS__)
3448 else
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';
3460 #else
3461 else
3462 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3463 __FILE__, __LINE__);
3464 #endif
3466 #endif /* ! AMIGA */
3468 return new_argv;
3470 #endif /* !VMS */
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). */
3485 char **
3486 construct_command_argv (char *line, char **restp, struct file *file,
3487 char **batch_filename_ptr)
3489 char *shell, *ifs;
3490 char **argv;
3492 #ifdef VMS
3493 char *cptr;
3494 int argc;
3496 argc = 0;
3497 cptr = line;
3498 for (;;)
3500 while ((*cptr != 0)
3501 && (isspace ((unsigned char)*cptr)))
3502 cptr++;
3503 if (*cptr == 0)
3504 break;
3505 while ((*cptr != 0)
3506 && (!isspace((unsigned char)*cptr)))
3507 cptr++;
3508 argc++;
3511 argv = (char **)malloc (argc * sizeof (char *));
3512 if (argv == 0)
3513 abort ();
3515 cptr = line;
3516 argc = 0;
3517 for (;;)
3519 while ((*cptr != 0)
3520 && (isspace ((unsigned char)*cptr)))
3521 cptr++;
3522 if (*cptr == 0)
3523 break;
3524 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3525 argv[argc++] = cptr;
3526 while ((*cptr != 0)
3527 && (!isspace((unsigned char)*cptr)))
3528 cptr++;
3529 if (*cptr != 0)
3530 *cptr++ = 0;
3532 #else
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);
3539 #ifdef WINDOWS32
3541 * Convert to forward slashes so that construct_command_argv_internal()
3542 * is not confused.
3544 if (shell) {
3545 char *p = w32ify (shell, 0);
3546 strcpy (shell, p);
3548 #endif
3549 #ifdef __EMX__
3551 static const char *unixroot = NULL;
3552 static const char *last_shell = "";
3553 static int init = 0;
3554 if (init == 0)
3556 unixroot = getenv ("UNIXROOT");
3557 /* unixroot must be NULL or not empty */
3558 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3559 init = 1;
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! */
3583 /* free(shell); */
3584 shell = buf;
3585 else
3586 free (buf);
3588 else
3589 free (buf);
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);
3601 free (shell);
3602 free (ifs);
3603 #endif /* !VMS */
3604 return argv;
3607 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3609 dup2 (int old, int new)
3611 int fd;
3613 (void) close (new);
3614 fd = dup (old);
3615 if (fd != new)
3617 (void) close (fd);
3618 errno = EMFILE;
3619 return -1;
3622 return fd;
3624 #endif /* !HAPE_DUP2 && !_AMIGA */