In very obscure situations we may write the free token back to the pipe.
[make.git] / job.c
blobc2ce84dbbaf4af454a533d5eff6fb161545ce676
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
4 2010 Free Software Foundation, Inc.
5 This file is part of GNU Make.
7 GNU Make is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 3 of the License, or (at your option) any later
10 version.
12 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along with
17 this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include "make.h"
21 #include <assert.h>
23 #include "job.h"
24 #include "debug.h"
25 #include "filedef.h"
26 #include "commands.h"
27 #include "variable.h"
28 #include "debug.h"
30 #include <string.h>
32 /* Default shell to use. */
33 #ifdef WINDOWS32
34 #include <windows.h>
36 char *default_shell = "sh.exe";
37 int no_default_sh_exe = 1;
38 int batch_mode_shell = 1;
39 HANDLE main_thread;
41 #elif defined (_AMIGA)
43 char default_shell[] = "";
44 extern int MyExecute (char **);
45 int batch_mode_shell = 0;
47 #elif defined (__MSDOS__)
49 /* The default shell is a pointer so we can change it if Makefile
50 says so. It is without an explicit path so we get a chance
51 to search the $PATH for it (since MSDOS doesn't have standard
52 directories we could trust). */
53 char *default_shell = "command.com";
54 int batch_mode_shell = 0;
56 #elif defined (__EMX__)
58 char *default_shell = "/bin/sh";
59 int batch_mode_shell = 0;
61 #elif defined (VMS)
63 # include <descrip.h>
64 char default_shell[] = "";
65 int batch_mode_shell = 0;
67 #elif defined (__riscos__)
69 char default_shell[] = "";
70 int batch_mode_shell = 0;
72 #else
74 char default_shell[] = "/bin/sh";
75 int batch_mode_shell = 0;
77 #endif
79 #ifdef __MSDOS__
80 # include <process.h>
81 static int execute_by_shell;
82 static int dos_pid = 123;
83 int dos_status;
84 int dos_command_running;
85 #endif /* __MSDOS__ */
87 #ifdef _AMIGA
88 # include <proto/dos.h>
89 static int amiga_pid = 123;
90 static int amiga_status;
91 static char amiga_bname[32];
92 static int amiga_batch_file;
93 #endif /* Amiga. */
95 #ifdef VMS
96 # ifndef __GNUC__
97 # include <processes.h>
98 # endif
99 # include <starlet.h>
100 # include <lib$routines.h>
101 static void vmsWaitForChildren (int *);
102 #endif
104 #ifdef WINDOWS32
105 # include <windows.h>
106 # include <io.h>
107 # include <process.h>
108 # include "sub_proc.h"
109 # include "w32err.h"
110 # include "pathstuff.h"
111 #endif /* WINDOWS32 */
113 #ifdef __EMX__
114 # include <process.h>
115 #endif
117 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
118 # include <sys/wait.h>
119 #endif
121 #ifdef HAVE_WAITPID
122 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
123 #else /* Don't have waitpid. */
124 # ifdef HAVE_WAIT3
125 # ifndef wait3
126 extern int wait3 ();
127 # endif
128 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
129 # endif /* Have wait3. */
130 #endif /* Have waitpid. */
132 #if !defined (wait) && !defined (POSIX)
133 int wait ();
134 #endif
136 #ifndef HAVE_UNION_WAIT
138 # define WAIT_T int
140 # ifndef WTERMSIG
141 # define WTERMSIG(x) ((x) & 0x7f)
142 # endif
143 # ifndef WCOREDUMP
144 # define WCOREDUMP(x) ((x) & 0x80)
145 # endif
146 # ifndef WEXITSTATUS
147 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
148 # endif
149 # ifndef WIFSIGNALED
150 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
151 # endif
152 # ifndef WIFEXITED
153 # define WIFEXITED(x) (WTERMSIG (x) == 0)
154 # endif
156 #else /* Have `union wait'. */
158 # define WAIT_T union wait
159 # ifndef WTERMSIG
160 # define WTERMSIG(x) ((x).w_termsig)
161 # endif
162 # ifndef WCOREDUMP
163 # define WCOREDUMP(x) ((x).w_coredump)
164 # endif
165 # ifndef WEXITSTATUS
166 # define WEXITSTATUS(x) ((x).w_retcode)
167 # endif
168 # ifndef WIFSIGNALED
169 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
170 # endif
171 # ifndef WIFEXITED
172 # define WIFEXITED(x) (WTERMSIG(x) == 0)
173 # endif
175 #endif /* Don't have `union wait'. */
177 #if !defined(HAVE_UNISTD_H) && !defined(WINDOWS32)
178 int dup2 ();
179 int execve ();
180 void _exit ();
181 # ifndef VMS
182 int geteuid ();
183 int getegid ();
184 int setgid ();
185 int getgid ();
186 # endif
187 #endif
189 /* Different systems have different requirements for pid_t.
190 Plus we have to support gettext string translation... Argh. */
191 static const char *
192 pid2str (pid_t pid)
194 static char pidstring[100];
195 #if defined(WINDOWS32) && (__GNUC__ > 3 || _MSC_VER > 1300)
196 /* %Id is only needed for 64-builds, which were not supported by
197 older versions of Windows compilers. */
198 sprintf (pidstring, "%Id", pid);
199 #else
200 sprintf (pidstring, "%lu", (unsigned long) pid);
201 #endif
202 return pidstring;
205 int getloadavg (double loadavg[], int nelem);
206 int start_remote_job (char **argv, char **envp, int stdin_fd, int *is_remote,
207 int *id_ptr, int *used_stdin);
208 int start_remote_job_p (int);
209 int remote_status (int *exit_code_ptr, int *signal_ptr, int *coredump_ptr,
210 int block);
212 RETSIGTYPE child_handler (int);
213 static void free_child (struct child *);
214 static void start_job_command (struct child *child);
215 static int load_too_high (void);
216 static int job_next_command (struct child *);
217 static int start_waiting_job (struct child *);
219 /* Chain of all live (or recently deceased) children. */
221 struct child *children = 0;
223 /* Number of children currently running. */
225 unsigned int job_slots_used = 0;
227 /* Nonzero if the `good' standard input is in use. */
229 static int good_stdin_used = 0;
231 /* Chain of children waiting to run until the load average goes down. */
233 static struct child *waiting_jobs = 0;
235 /* Non-zero if we use a *real* shell (always so on Unix). */
237 int unixy_shell = 1;
239 /* Number of jobs started in the current second. */
241 unsigned long job_counter = 0;
243 /* Number of jobserver tokens this instance is currently using. */
245 unsigned int jobserver_tokens = 0;
247 #ifdef WINDOWS32
249 * The macro which references this function is defined in make.h.
252 w32_kill(pid_t pid, int sig)
254 return ((process_kill((HANDLE)pid, sig) == TRUE) ? 0 : -1);
257 /* This function creates a temporary file name with an extension specified
258 * by the unixy arg.
259 * Return an xmalloc'ed string of a newly created temp file and its
260 * file descriptor, or die. */
261 static char *
262 create_batch_file (char const *base, int unixy, int *fd)
264 const char *const ext = unixy ? "sh" : "bat";
265 const char *error_string = NULL;
266 char temp_path[MAXPATHLEN]; /* need to know its length */
267 unsigned path_size = GetTempPath(sizeof temp_path, temp_path);
268 int path_is_dot = 0;
269 unsigned uniq = 1;
270 const unsigned sizemax = strlen (base) + strlen (ext) + 10;
272 if (path_size == 0)
274 path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
275 path_is_dot = 1;
278 while (path_size > 0 &&
279 path_size + sizemax < sizeof temp_path &&
280 uniq < 0x10000)
282 unsigned size = sprintf (temp_path + path_size,
283 "%s%s-%x.%s",
284 temp_path[path_size - 1] == '\\' ? "" : "\\",
285 base, uniq, ext);
286 HANDLE h = CreateFile (temp_path, /* file name */
287 GENERIC_READ | GENERIC_WRITE, /* desired access */
288 0, /* no share mode */
289 NULL, /* default security attributes */
290 CREATE_NEW, /* creation disposition */
291 FILE_ATTRIBUTE_NORMAL | /* flags and attributes */
292 FILE_ATTRIBUTE_TEMPORARY, /* we'll delete it */
293 NULL); /* no template file */
295 if (h == INVALID_HANDLE_VALUE)
297 const DWORD er = GetLastError();
299 if (er == ERROR_FILE_EXISTS || er == ERROR_ALREADY_EXISTS)
300 ++uniq;
302 /* the temporary path is not guaranteed to exist */
303 else if (path_is_dot == 0)
305 path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
306 path_is_dot = 1;
309 else
311 error_string = map_windows32_error_to_string (er);
312 break;
315 else
317 const unsigned final_size = path_size + size + 1;
318 char *const path = xmalloc (final_size);
319 memcpy (path, temp_path, final_size);
320 *fd = _open_osfhandle ((intptr_t)h, 0);
321 if (unixy)
323 char *p;
324 int ch;
325 for (p = path; (ch = *p) != 0; ++p)
326 if (ch == '\\')
327 *p = '/';
329 return path; /* good return */
333 *fd = -1;
334 if (error_string == NULL)
335 error_string = _("Cannot create a temporary file\n");
336 fatal (NILF, error_string);
338 /* not reached */
339 return NULL;
341 #endif /* WINDOWS32 */
343 #ifdef __EMX__
344 /* returns whether path is assumed to be a unix like shell. */
346 _is_unixy_shell (const char *path)
348 /* list of non unix shells */
349 const char *known_os2shells[] = {
350 "cmd.exe",
351 "cmd",
352 "4os2.exe",
353 "4os2",
354 "4dos.exe",
355 "4dos",
356 "command.com",
357 "command",
358 NULL
361 /* find the rightmost '/' or '\\' */
362 const char *name = strrchr (path, '/');
363 const char *p = strrchr (path, '\\');
364 unsigned i;
366 if (name && p) /* take the max */
367 name = (name > p) ? name : p;
368 else if (p) /* name must be 0 */
369 name = p;
370 else if (!name) /* name and p must be 0 */
371 name = path;
373 if (*name == '/' || *name == '\\') name++;
375 i = 0;
376 while (known_os2shells[i] != NULL) {
377 if (strcasecmp (name, known_os2shells[i]) == 0)
378 return 0; /* not a unix shell */
379 i++;
382 /* in doubt assume a unix like shell */
383 return 1;
385 #endif /* __EMX__ */
387 /* determines whether path looks to be a Bourne-like shell. */
389 is_bourne_compatible_shell (const char *path)
391 /* list of known unix (Bourne-like) shells */
392 const char *unix_shells[] = {
393 "sh",
394 "bash",
395 "ksh",
396 "rksh",
397 "zsh",
398 "ash",
399 "dash",
400 NULL
402 unsigned i, len;
404 /* find the rightmost '/' or '\\' */
405 const char *name = strrchr (path, '/');
406 char *p = strrchr (path, '\\');
408 if (name && p) /* take the max */
409 name = (name > p) ? name : p;
410 else if (p) /* name must be 0 */
411 name = p;
412 else if (!name) /* name and p must be 0 */
413 name = path;
415 if (*name == '/' || *name == '\\') name++;
417 /* this should be able to deal with extensions on Windows-like systems */
418 for (i = 0; unix_shells[i] != NULL; i++) {
419 len = strlen(unix_shells[i]);
420 #if defined(WINDOWS32) || defined(__MSDOS__)
421 if ((strncasecmp (name, unix_shells[i], len) == 0) &&
422 (strlen(name) >= len && (name[len] == '\0' || name[len] == '.')))
423 #else
424 if ((strncmp (name, unix_shells[i], len) == 0) &&
425 (strlen(name) >= len && name[len] == '\0'))
426 #endif
427 return 1; /* a known unix-style shell */
430 /* if not on the list, assume it's not a Bourne-like shell */
431 return 0;
435 /* Write an error message describing the exit status given in
436 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
437 Append "(ignored)" if IGNORED is nonzero. */
439 static void
440 child_error (const struct file *file,
441 int exit_code, int exit_sig, int coredump, int ignored)
443 const char *nm;
444 const char *pre = "*** ";
445 const char *post = "";
446 const char *dump = "";
447 struct floc *flocp = &file->cmds->fileinfo;
449 if (ignored && silent_flag)
450 return;
452 if (exit_sig && coredump)
453 dump = _(" (core dumped)");
455 if (ignored)
457 pre = "";
458 post = _(" (ignored)");
461 if (! flocp->filenm)
462 nm = _("<builtin>");
463 else
465 char *a = alloca (strlen (flocp->filenm) + 1 + 11 + 1);
466 sprintf (a, "%s:%lu", flocp->filenm, flocp->lineno);
467 nm = a;
469 message (0, _("%s: recipe for target `%s' failed"), nm, file->name);
471 #ifdef VMS
472 if (!(exit_code & 1))
473 error (NILF, _("%s[%s] Error 0x%x%s"), pre, file->name, exit_code, post);
474 #else
475 if (exit_sig == 0)
476 error (NILF, _("%s[%s] Error %d%s"), pre, file->name, exit_code, post);
477 else
478 error (NILF, _("%s[%s] %s%s%s"),
479 pre, file->name, strsignal (exit_sig), dump, post);
480 #endif /* VMS */
484 /* Handle a dead child. This handler may or may not ever be installed.
486 If we're using the jobserver feature, we need it. First, installing it
487 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
488 read FD to ensure we don't enter another blocking read without reaping all
489 the dead children. In this case we don't need the dead_children count.
491 If we don't have either waitpid or wait3, then make is unreliable, but we
492 use the dead_children count to reap children as best we can. */
494 static unsigned int dead_children = 0;
496 RETSIGTYPE
497 child_handler (int sig UNUSED)
499 ++dead_children;
501 if (job_rfd >= 0)
503 close (job_rfd);
504 job_rfd = -1;
507 #ifdef __EMX__
508 /* The signal handler must called only once! */
509 signal (SIGCHLD, SIG_DFL);
510 #endif
512 /* This causes problems if the SIGCHLD interrupts a printf().
513 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
517 extern int shell_function_pid, shell_function_completed;
519 /* Reap all dead children, storing the returned status and the new command
520 state (`cs_finished') in the `file' member of the `struct child' for the
521 dead child, and removing the child from the chain. In addition, if BLOCK
522 nonzero, we block in this function until we've reaped at least one
523 complete child, waiting for it to die if necessary. If ERR is nonzero,
524 print an error message first. */
526 void
527 reap_children (int block, int err)
529 #ifndef WINDOWS32
530 WAIT_T status;
531 /* Initially, assume we have some. */
532 int reap_more = 1;
533 #endif
535 #ifdef WAIT_NOHANG
536 # define REAP_MORE reap_more
537 #else
538 # define REAP_MORE dead_children
539 #endif
541 /* As long as:
543 We have at least one child outstanding OR a shell function in progress,
545 We're blocking for a complete child OR there are more children to reap
547 we'll keep reaping children. */
549 while ((children != 0 || shell_function_pid != 0)
550 && (block || REAP_MORE))
552 int remote = 0;
553 pid_t pid;
554 int exit_code, exit_sig, coredump;
555 struct child *lastc, *c;
556 int child_failed;
557 int any_remote, any_local;
558 int dontcare;
560 if (err && block)
562 static int printed = 0;
564 /* We might block for a while, so let the user know why.
565 Only print this message once no matter how many jobs are left. */
566 fflush (stdout);
567 if (!printed)
568 error (NILF, _("*** Waiting for unfinished jobs...."));
569 printed = 1;
572 /* We have one less dead child to reap. As noted in
573 child_handler() above, this count is completely unimportant for
574 all modern, POSIX-y systems that support wait3() or waitpid().
575 The rest of this comment below applies only to early, broken
576 pre-POSIX systems. We keep the count only because... it's there...
578 The test and decrement are not atomic; if it is compiled into:
579 register = dead_children - 1;
580 dead_children = register;
581 a SIGCHLD could come between the two instructions.
582 child_handler increments dead_children.
583 The second instruction here would lose that increment. But the
584 only effect of dead_children being wrong is that we might wait
585 longer than necessary to reap a child, and lose some parallelism;
586 and we might print the "Waiting for unfinished jobs" message above
587 when not necessary. */
589 if (dead_children > 0)
590 --dead_children;
592 any_remote = 0;
593 any_local = shell_function_pid != 0;
594 for (c = children; c != 0; c = c->next)
596 any_remote |= c->remote;
597 any_local |= ! c->remote;
598 DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
599 c, c->file->name, pid2str (c->pid),
600 c->remote ? _(" (remote)") : ""));
601 #ifdef VMS
602 break;
603 #endif
606 /* First, check for remote children. */
607 if (any_remote)
608 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
609 else
610 pid = 0;
612 if (pid > 0)
613 /* We got a remote child. */
614 remote = 1;
615 else if (pid < 0)
617 /* A remote status command failed miserably. Punt. */
618 remote_status_lose:
619 pfatal_with_name ("remote_status");
621 else
623 /* No remote children. Check for local children. */
624 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
625 if (any_local)
627 #ifdef VMS
628 vmsWaitForChildren (&status);
629 pid = c->pid;
630 #else
631 #ifdef WAIT_NOHANG
632 if (!block)
633 pid = WAIT_NOHANG (&status);
634 else
635 #endif
636 EINTRLOOP(pid, wait (&status));
637 #endif /* !VMS */
639 else
640 pid = 0;
642 if (pid < 0)
644 /* The wait*() failed miserably. Punt. */
645 pfatal_with_name ("wait");
647 else if (pid > 0)
649 /* We got a child exit; chop the status word up. */
650 exit_code = WEXITSTATUS (status);
651 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
652 coredump = WCOREDUMP (status);
654 /* If we have started jobs in this second, remove one. */
655 if (job_counter)
656 --job_counter;
658 else
660 /* No local children are dead. */
661 reap_more = 0;
663 if (!block || !any_remote)
664 break;
666 /* Now try a blocking wait for a remote child. */
667 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
668 if (pid < 0)
669 goto remote_status_lose;
670 else if (pid == 0)
671 /* No remote children either. Finally give up. */
672 break;
674 /* We got a remote child. */
675 remote = 1;
677 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
679 #ifdef __MSDOS__
680 /* Life is very different on MSDOS. */
681 pid = dos_pid - 1;
682 status = dos_status;
683 exit_code = WEXITSTATUS (status);
684 if (exit_code == 0xff)
685 exit_code = -1;
686 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
687 coredump = 0;
688 #endif /* __MSDOS__ */
689 #ifdef _AMIGA
690 /* Same on Amiga */
691 pid = amiga_pid - 1;
692 status = amiga_status;
693 exit_code = amiga_status;
694 exit_sig = 0;
695 coredump = 0;
696 #endif /* _AMIGA */
697 #ifdef WINDOWS32
699 HANDLE hPID;
700 int werr;
701 HANDLE hcTID, hcPID;
702 exit_code = 0;
703 exit_sig = 0;
704 coredump = 0;
706 /* Record the thread ID of the main process, so that we
707 could suspend it in the signal handler. */
708 if (!main_thread)
710 hcTID = GetCurrentThread ();
711 hcPID = GetCurrentProcess ();
712 if (!DuplicateHandle (hcPID, hcTID, hcPID, &main_thread, 0,
713 FALSE, DUPLICATE_SAME_ACCESS))
715 DWORD e = GetLastError ();
716 fprintf (stderr,
717 "Determine main thread ID (Error %ld: %s)\n",
718 e, map_windows32_error_to_string(e));
720 else
721 DB (DB_VERBOSE, ("Main thread handle = %p\n", main_thread));
724 /* wait for anything to finish */
725 hPID = process_wait_for_any();
726 if (hPID)
729 /* was an error found on this process? */
730 werr = process_last_err(hPID);
732 /* get exit data */
733 exit_code = process_exit_code(hPID);
735 if (werr)
736 fprintf(stderr, "make (e=%d): %s",
737 exit_code, map_windows32_error_to_string(exit_code));
739 /* signal */
740 exit_sig = process_signal(hPID);
742 /* cleanup process */
743 process_cleanup(hPID);
745 coredump = 0;
747 pid = (pid_t) hPID;
749 #endif /* WINDOWS32 */
752 /* Check if this is the child of the `shell' function. */
753 if (!remote && pid == shell_function_pid)
755 /* It is. Leave an indicator for the `shell' function. */
756 if (exit_sig == 0 && exit_code == 127)
757 shell_function_completed = -1;
758 else
759 shell_function_completed = 1;
760 break;
763 child_failed = exit_sig != 0 || exit_code != 0;
765 /* Search for a child matching the deceased one. */
766 lastc = 0;
767 for (c = children; c != 0; lastc = c, c = c->next)
768 if (c->remote == remote && c->pid == pid)
769 break;
771 if (c == 0)
772 /* An unknown child died.
773 Ignore it; it was inherited from our invoker. */
774 continue;
776 DB (DB_JOBS, (child_failed
777 ? _("Reaping losing child %p PID %s %s\n")
778 : _("Reaping winning child %p PID %s %s\n"),
779 c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
781 if (c->sh_batch_file) {
782 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
783 c->sh_batch_file));
785 /* just try and remove, don't care if this fails */
786 remove (c->sh_batch_file);
788 /* all done with memory */
789 free (c->sh_batch_file);
790 c->sh_batch_file = NULL;
793 /* If this child had the good stdin, say it is now free. */
794 if (c->good_stdin)
795 good_stdin_used = 0;
797 dontcare = c->dontcare;
799 if (child_failed && !c->noerror && !ignore_errors_flag)
801 /* The commands failed. Write an error message,
802 delete non-precious targets, and abort. */
803 static int delete_on_error = -1;
805 if (!dontcare)
806 child_error (c->file, exit_code, exit_sig, coredump, 0);
808 c->file->update_status = 2;
809 if (delete_on_error == -1)
811 struct file *f = lookup_file (".DELETE_ON_ERROR");
812 delete_on_error = f != 0 && f->is_target;
814 if (exit_sig != 0 || delete_on_error)
815 delete_child_targets (c);
817 else
819 if (child_failed)
821 /* The commands failed, but we don't care. */
822 child_error (c->file, exit_code, exit_sig, coredump, 1);
823 child_failed = 0;
826 /* If there are more commands to run, try to start them. */
827 if (job_next_command (c))
829 if (handling_fatal_signal)
831 /* Never start new commands while we are dying.
832 Since there are more commands that wanted to be run,
833 the target was not completely remade. So we treat
834 this as if a command had failed. */
835 c->file->update_status = 2;
837 else
839 /* Check again whether to start remotely.
840 Whether or not we want to changes over time.
841 Also, start_remote_job may need state set up
842 by start_remote_job_p. */
843 c->remote = start_remote_job_p (0);
844 start_job_command (c);
845 /* Fatal signals are left blocked in case we were
846 about to put that child on the chain. But it is
847 already there, so it is safe for a fatal signal to
848 arrive now; it will clean up this child's targets. */
849 unblock_sigs ();
850 if (c->file->command_state == cs_running)
851 /* We successfully started the new command.
852 Loop to reap more children. */
853 continue;
856 if (c->file->update_status != 0)
857 /* We failed to start the commands. */
858 delete_child_targets (c);
860 else
861 /* There are no more commands. We got through them all
862 without an unignored error. Now the target has been
863 successfully updated. */
864 c->file->update_status = 0;
867 /* When we get here, all the commands for C->file are finished
868 (or aborted) and C->file->update_status contains 0 or 2. But
869 C->file->command_state is still cs_running if all the commands
870 ran; notice_finish_file looks for cs_running to tell it that
871 it's interesting to check the file's modtime again now. */
873 if (! handling_fatal_signal)
874 /* Notice if the target of the commands has been changed.
875 This also propagates its values for command_state and
876 update_status to its also_make files. */
877 notice_finished_file (c->file);
879 DB (DB_JOBS, (_("Removing child %p PID %s%s from chain.\n"),
880 c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
882 /* Block fatal signals while frobnicating the list, so that
883 children and job_slots_used are always consistent. Otherwise
884 a fatal signal arriving after the child is off the chain and
885 before job_slots_used is decremented would believe a child was
886 live and call reap_children again. */
887 block_sigs ();
889 /* There is now another slot open. */
890 if (job_slots_used > 0)
891 --job_slots_used;
893 /* Remove the child from the chain and free it. */
894 if (lastc == 0)
895 children = c->next;
896 else
897 lastc->next = c->next;
899 free_child (c);
901 unblock_sigs ();
903 /* If the job failed, and the -k flag was not given, die,
904 unless we are already in the process of dying. */
905 if (!err && child_failed && !dontcare && !keep_going_flag &&
906 /* fatal_error_signal will die with the right signal. */
907 !handling_fatal_signal)
908 die (2);
910 /* Only block for one child. */
911 block = 0;
914 return;
917 /* Free the storage allocated for CHILD. */
919 static void
920 free_child (struct child *child)
922 if (!jobserver_tokens)
923 fatal (NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
924 child, child->file->name);
926 /* If we're using the jobserver and this child is not the only outstanding
927 job, put a token back into the pipe for it. */
929 if (job_fds[1] >= 0 && jobserver_tokens > 1)
931 char token = '+';
932 int r;
934 /* Write a job token back to the pipe. */
936 EINTRLOOP (r, write (job_fds[1], &token, 1));
937 if (r != 1)
938 pfatal_with_name (_("write jobserver"));
940 DB (DB_JOBS, (_("Released token for child %p (%s).\n"),
941 child, child->file->name));
944 --jobserver_tokens;
946 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
947 return;
949 if (child->command_lines != 0)
951 register unsigned int i;
952 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
953 free (child->command_lines[i]);
954 free (child->command_lines);
957 if (child->environment != 0)
959 register char **ep = child->environment;
960 while (*ep != 0)
961 free (*ep++);
962 free (child->environment);
965 free (child);
968 #ifdef POSIX
969 extern sigset_t fatal_signal_set;
970 #endif
972 void
973 block_sigs (void)
975 #ifdef POSIX
976 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
977 #else
978 # ifdef HAVE_SIGSETMASK
979 (void) sigblock (fatal_signal_mask);
980 # endif
981 #endif
984 #ifdef POSIX
985 void
986 unblock_sigs (void)
988 sigset_t empty;
989 sigemptyset (&empty);
990 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
992 #endif
994 #ifdef MAKE_JOBSERVER
995 RETSIGTYPE
996 job_noop (int sig UNUSED)
999 /* Set the child handler action flags to FLAGS. */
1000 static void
1001 set_child_handler_action_flags (int set_handler, int set_alarm)
1003 struct sigaction sa;
1005 #ifdef __EMX__
1006 /* The child handler must be turned off here. */
1007 signal (SIGCHLD, SIG_DFL);
1008 #endif
1010 memset (&sa, '\0', sizeof sa);
1011 sa.sa_handler = child_handler;
1012 sa.sa_flags = set_handler ? 0 : SA_RESTART;
1013 #if defined SIGCHLD
1014 sigaction (SIGCHLD, &sa, NULL);
1015 #endif
1016 #if defined SIGCLD && SIGCLD != SIGCHLD
1017 sigaction (SIGCLD, &sa, NULL);
1018 #endif
1019 #if defined SIGALRM
1020 if (set_alarm)
1022 /* If we're about to enter the read(), set an alarm to wake up in a
1023 second so we can check if the load has dropped and we can start more
1024 work. On the way out, turn off the alarm and set SIG_DFL. */
1025 alarm (set_handler ? 1 : 0);
1026 sa.sa_handler = set_handler ? job_noop : SIG_DFL;
1027 sa.sa_flags = 0;
1028 sigaction (SIGALRM, &sa, NULL);
1030 #endif
1032 #endif
1035 /* Start a job to run the commands specified in CHILD.
1036 CHILD is updated to reflect the commands and ID of the child process.
1038 NOTE: On return fatal signals are blocked! The caller is responsible
1039 for calling `unblock_sigs', once the new child is safely on the chain so
1040 it can be cleaned up in the event of a fatal signal. */
1042 static void
1043 start_job_command (struct child *child)
1045 #if !defined(_AMIGA) && !defined(WINDOWS32)
1046 static int bad_stdin = -1;
1047 #endif
1048 char *p;
1049 /* Must be volatile to silence bogus GCC warning about longjmp/vfork. */
1050 volatile int flags;
1051 #ifdef VMS
1052 char *argv;
1053 #else
1054 char **argv;
1055 #endif
1057 /* If we have a completely empty commandset, stop now. */
1058 if (!child->command_ptr)
1059 goto next_command;
1061 /* Combine the flags parsed for the line itself with
1062 the flags specified globally for this target. */
1063 flags = (child->file->command_flags
1064 | child->file->cmds->lines_flags[child->command_line - 1]);
1066 p = child->command_ptr;
1067 child->noerror = ((flags & COMMANDS_NOERROR) != 0);
1069 while (*p != '\0')
1071 if (*p == '@')
1072 flags |= COMMANDS_SILENT;
1073 else if (*p == '+')
1074 flags |= COMMANDS_RECURSE;
1075 else if (*p == '-')
1076 child->noerror = 1;
1077 else if (!isblank ((unsigned char)*p))
1078 break;
1079 ++p;
1082 /* Update the file's command flags with any new ones we found. We only
1083 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
1084 now marking more commands recursive than should be in the case of
1085 multiline define/endef scripts where only one line is marked "+". In
1086 order to really fix this, we'll have to keep a lines_flags for every
1087 actual line, after expansion. */
1088 child->file->cmds->lines_flags[child->command_line - 1]
1089 |= flags & COMMANDS_RECURSE;
1091 /* POSIX requires that a recipe prefix after a backslash-newline should
1092 be ignored. Remove it now so the output is correct. */
1094 char prefix = child->file->cmds->recipe_prefix;
1095 char *p1, *p2;
1096 p1 = p2 = p;
1097 while (*p1 != '\0')
1099 *(p2++) = *p1;
1100 if (p1[0] == '\n' && p1[1] == prefix)
1101 ++p1;
1102 ++p1;
1104 *p2 = *p1;
1107 /* Figure out an argument list from this command line. */
1109 char *end = 0;
1110 #ifdef VMS
1111 argv = p;
1112 #else
1113 argv = construct_command_argv (p, &end, child->file,
1114 child->file->cmds->lines_flags[child->command_line - 1],
1115 &child->sh_batch_file);
1116 #endif
1117 if (end == NULL)
1118 child->command_ptr = NULL;
1119 else
1121 *end++ = '\0';
1122 child->command_ptr = end;
1126 /* If -q was given, say that updating `failed' if there was any text on the
1127 command line, or `succeeded' otherwise. The exit status of 1 tells the
1128 user that -q is saying `something to do'; the exit status for a random
1129 error is 2. */
1130 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
1132 #ifndef VMS
1133 free (argv[0]);
1134 free (argv);
1135 #endif
1136 child->file->update_status = 1;
1137 notice_finished_file (child->file);
1138 return;
1141 if (touch_flag && !(flags & COMMANDS_RECURSE))
1143 /* Go on to the next command. It might be the recursive one.
1144 We construct ARGV only to find the end of the command line. */
1145 #ifndef VMS
1146 if (argv)
1148 free (argv[0]);
1149 free (argv);
1151 #endif
1152 argv = 0;
1155 if (argv == 0)
1157 next_command:
1158 #ifdef __MSDOS__
1159 execute_by_shell = 0; /* in case construct_command_argv sets it */
1160 #endif
1161 /* This line has no commands. Go to the next. */
1162 if (job_next_command (child))
1163 start_job_command (child);
1164 else
1166 /* No more commands. Make sure we're "running"; we might not be if
1167 (e.g.) all commands were skipped due to -n. */
1168 set_command_state (child->file, cs_running);
1169 child->file->update_status = 0;
1170 notice_finished_file (child->file);
1172 return;
1175 /* Print out the command. If silent, we call `message' with null so it
1176 can log the working directory before the command's own error messages
1177 appear. */
1179 message (0, (just_print_flag || trace_flag
1180 || (!(flags & COMMANDS_SILENT) && !silent_flag))
1181 ? "%s" : (char *) 0, p);
1183 /* Tell update_goal_chain that a command has been started on behalf of
1184 this target. It is important that this happens here and not in
1185 reap_children (where we used to do it), because reap_children might be
1186 reaping children from a different target. We want this increment to
1187 guaranteedly indicate that a command was started for the dependency
1188 chain (i.e., update_file recursion chain) we are processing. */
1190 ++commands_started;
1192 /* Optimize an empty command. People use this for timestamp rules,
1193 so avoid forking a useless shell. Do this after we increment
1194 commands_started so make still treats this special case as if it
1195 performed some action (makes a difference as to what messages are
1196 printed, etc. */
1198 #if !defined(VMS) && !defined(_AMIGA)
1199 if (
1200 #if defined __MSDOS__ || defined (__EMX__)
1201 unixy_shell /* the test is complicated and we already did it */
1202 #else
1203 (argv[0] && is_bourne_compatible_shell(argv[0]))
1204 #endif
1205 && (argv[1] && argv[1][0] == '-'
1207 ((argv[1][1] == 'c' && argv[1][2] == '\0')
1209 (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
1210 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1211 && argv[3] == NULL)
1213 free (argv[0]);
1214 free (argv);
1215 goto next_command;
1217 #endif /* !VMS && !_AMIGA */
1219 /* If -n was given, recurse to get the next line in the sequence. */
1221 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1223 #ifndef VMS
1224 free (argv[0]);
1225 free (argv);
1226 #endif
1227 goto next_command;
1230 /* Flush the output streams so they won't have things written twice. */
1232 fflush (stdout);
1233 fflush (stderr);
1235 #ifndef VMS
1236 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1238 /* Set up a bad standard input that reads from a broken pipe. */
1240 if (bad_stdin == -1)
1242 /* Make a file descriptor that is the read end of a broken pipe.
1243 This will be used for some children's standard inputs. */
1244 int pd[2];
1245 if (pipe (pd) == 0)
1247 /* Close the write side. */
1248 (void) close (pd[1]);
1249 /* Save the read side. */
1250 bad_stdin = pd[0];
1252 /* Set the descriptor to close on exec, so it does not litter any
1253 child's descriptor table. When it is dup2'd onto descriptor 0,
1254 that descriptor will not close on exec. */
1255 CLOSE_ON_EXEC (bad_stdin);
1259 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1261 /* Decide whether to give this child the `good' standard input
1262 (one that points to the terminal or whatever), or the `bad' one
1263 that points to the read side of a broken pipe. */
1265 child->good_stdin = !good_stdin_used;
1266 if (child->good_stdin)
1267 good_stdin_used = 1;
1269 #endif /* !VMS */
1271 child->deleted = 0;
1273 #ifndef _AMIGA
1274 /* Set up the environment for the child. */
1275 if (child->environment == 0)
1276 child->environment = target_environment (child->file);
1277 #endif
1279 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1281 #ifndef VMS
1282 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1283 if (child->remote)
1285 int is_remote, id, used_stdin;
1286 if (start_remote_job (argv, child->environment,
1287 child->good_stdin ? 0 : bad_stdin,
1288 &is_remote, &id, &used_stdin))
1289 /* Don't give up; remote execution may fail for various reasons. If
1290 so, simply run the job locally. */
1291 goto run_local;
1292 else
1294 if (child->good_stdin && !used_stdin)
1296 child->good_stdin = 0;
1297 good_stdin_used = 0;
1299 child->remote = is_remote;
1300 child->pid = id;
1303 else
1304 #endif /* !VMS */
1306 /* Fork the child process. */
1308 char **parent_environ;
1310 run_local:
1311 block_sigs ();
1313 child->remote = 0;
1315 #ifdef VMS
1316 if (!child_execute_job (argv, child)) {
1317 /* Fork failed! */
1318 perror_with_name ("vfork", "");
1319 goto error;
1322 #else
1324 parent_environ = environ;
1326 # ifdef __EMX__
1327 /* If we aren't running a recursive command and we have a jobserver
1328 pipe, close it before exec'ing. */
1329 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1331 CLOSE_ON_EXEC (job_fds[0]);
1332 CLOSE_ON_EXEC (job_fds[1]);
1334 if (job_rfd >= 0)
1335 CLOSE_ON_EXEC (job_rfd);
1337 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1338 child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1339 argv, child->environment);
1340 if (child->pid < 0)
1342 /* spawn failed! */
1343 unblock_sigs ();
1344 perror_with_name ("spawn", "");
1345 goto error;
1348 /* undo CLOSE_ON_EXEC() after the child process has been started */
1349 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1351 fcntl (job_fds[0], F_SETFD, 0);
1352 fcntl (job_fds[1], F_SETFD, 0);
1354 if (job_rfd >= 0)
1355 fcntl (job_rfd, F_SETFD, 0);
1357 #else /* !__EMX__ */
1359 child->pid = vfork ();
1360 environ = parent_environ; /* Restore value child may have clobbered. */
1361 if (child->pid == 0)
1363 /* We are the child side. */
1364 unblock_sigs ();
1366 /* If we aren't running a recursive command and we have a jobserver
1367 pipe, close it before exec'ing. */
1368 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1370 close (job_fds[0]);
1371 close (job_fds[1]);
1373 if (job_rfd >= 0)
1374 close (job_rfd);
1376 #ifdef SET_STACK_SIZE
1377 /* Reset limits, if necessary. */
1378 if (stack_limit.rlim_cur)
1379 setrlimit (RLIMIT_STACK, &stack_limit);
1380 #endif
1382 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1383 argv, child->environment);
1385 else if (child->pid < 0)
1387 /* Fork failed! */
1388 unblock_sigs ();
1389 perror_with_name ("vfork", "");
1390 goto error;
1392 # endif /* !__EMX__ */
1393 #endif /* !VMS */
1396 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1397 #ifdef __MSDOS__
1399 int proc_return;
1401 block_sigs ();
1402 dos_status = 0;
1404 /* We call `system' to do the job of the SHELL, since stock DOS
1405 shell is too dumb. Our `system' knows how to handle long
1406 command lines even if pipes/redirection is needed; it will only
1407 call COMMAND.COM when its internal commands are used. */
1408 if (execute_by_shell)
1410 char *cmdline = argv[0];
1411 /* We don't have a way to pass environment to `system',
1412 so we need to save and restore ours, sigh... */
1413 char **parent_environ = environ;
1415 environ = child->environment;
1417 /* If we have a *real* shell, tell `system' to call
1418 it to do everything for us. */
1419 if (unixy_shell)
1421 /* A *real* shell on MSDOS may not support long
1422 command lines the DJGPP way, so we must use `system'. */
1423 cmdline = argv[2]; /* get past "shell -c" */
1426 dos_command_running = 1;
1427 proc_return = system (cmdline);
1428 environ = parent_environ;
1429 execute_by_shell = 0; /* for the next time */
1431 else
1433 dos_command_running = 1;
1434 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1437 /* Need to unblock signals before turning off
1438 dos_command_running, so that child's signals
1439 will be treated as such (see fatal_error_signal). */
1440 unblock_sigs ();
1441 dos_command_running = 0;
1443 /* If the child got a signal, dos_status has its
1444 high 8 bits set, so be careful not to alter them. */
1445 if (proc_return == -1)
1446 dos_status |= 0xff;
1447 else
1448 dos_status |= (proc_return & 0xff);
1449 ++dead_children;
1450 child->pid = dos_pid++;
1452 #endif /* __MSDOS__ */
1453 #ifdef _AMIGA
1454 amiga_status = MyExecute (argv);
1456 ++dead_children;
1457 child->pid = amiga_pid++;
1458 if (amiga_batch_file)
1460 amiga_batch_file = 0;
1461 DeleteFile (amiga_bname); /* Ignore errors. */
1463 #endif /* Amiga */
1464 #ifdef WINDOWS32
1466 HANDLE hPID;
1467 char* arg0;
1469 /* make UNC paths safe for CreateProcess -- backslash format */
1470 arg0 = argv[0];
1471 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1472 for ( ; arg0 && *arg0; arg0++)
1473 if (*arg0 == '/')
1474 *arg0 = '\\';
1476 /* make sure CreateProcess() has Path it needs */
1477 sync_Path_environment();
1479 hPID = process_easy(argv, child->environment);
1481 if (hPID != INVALID_HANDLE_VALUE)
1482 child->pid = (pid_t) hPID;
1483 else {
1484 int i;
1485 unblock_sigs();
1486 fprintf(stderr,
1487 _("process_easy() failed to launch process (e=%ld)\n"),
1488 process_last_err(hPID));
1489 for (i = 0; argv[i]; i++)
1490 fprintf(stderr, "%s ", argv[i]);
1491 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1492 goto error;
1495 #endif /* WINDOWS32 */
1496 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1498 /* Bump the number of jobs started in this second. */
1499 ++job_counter;
1501 /* We are the parent side. Set the state to
1502 say the commands are running and return. */
1504 set_command_state (child->file, cs_running);
1506 /* Free the storage used by the child's argument list. */
1507 #ifndef VMS
1508 free (argv[0]);
1509 free (argv);
1510 #endif
1512 return;
1514 error:
1515 child->file->update_status = 2;
1516 notice_finished_file (child->file);
1517 return;
1520 /* Try to start a child running.
1521 Returns nonzero if the child was started (and maybe finished), or zero if
1522 the load was too high and the child was put on the `waiting_jobs' chain. */
1524 static int
1525 start_waiting_job (struct child *c)
1527 struct file *f = c->file;
1529 /* If we can start a job remotely, we always want to, and don't care about
1530 the local load average. We record that the job should be started
1531 remotely in C->remote for start_job_command to test. */
1533 c->remote = start_remote_job_p (1);
1535 /* If we are running at least one job already and the load average
1536 is too high, make this one wait. */
1537 if (!c->remote
1538 && ((job_slots_used > 0 && load_too_high ())
1539 #ifdef WINDOWS32
1540 || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
1541 #endif
1544 /* Put this child on the chain of children waiting for the load average
1545 to go down. */
1546 set_command_state (f, cs_running);
1547 c->next = waiting_jobs;
1548 waiting_jobs = c;
1549 return 0;
1552 /* Start the first command; reap_children will run later command lines. */
1553 start_job_command (c);
1555 switch (f->command_state)
1557 case cs_running:
1558 c->next = children;
1559 DB (DB_JOBS, (_("Putting child %p (%s) PID %s%s on the chain.\n"),
1560 c, c->file->name, pid2str (c->pid),
1561 c->remote ? _(" (remote)") : ""));
1562 children = c;
1563 /* One more job slot is in use. */
1564 ++job_slots_used;
1565 unblock_sigs ();
1566 break;
1568 case cs_not_started:
1569 /* All the command lines turned out to be empty. */
1570 f->update_status = 0;
1571 /* FALLTHROUGH */
1573 case cs_finished:
1574 notice_finished_file (f);
1575 free_child (c);
1576 break;
1578 default:
1579 assert (f->command_state == cs_finished);
1580 break;
1583 return 1;
1586 /* Create a `struct child' for FILE and start its commands running. */
1588 void
1589 new_job (struct file *file)
1591 struct commands *cmds = file->cmds;
1592 struct child *c;
1593 char **lines;
1594 unsigned int i;
1596 /* Let any previously decided-upon jobs that are waiting
1597 for the load to go down start before this new one. */
1598 start_waiting_jobs ();
1600 /* Reap any children that might have finished recently. */
1601 reap_children (0, 0);
1603 /* Chop the commands up into lines if they aren't already. */
1604 chop_commands (cmds);
1606 /* Expand the command lines and store the results in LINES. */
1607 lines = xmalloc (cmds->ncommand_lines * sizeof (char *));
1608 for (i = 0; i < cmds->ncommand_lines; ++i)
1610 /* Collapse backslash-newline combinations that are inside variable
1611 or function references. These are left alone by the parser so
1612 that they will appear in the echoing of commands (where they look
1613 nice); and collapsed by construct_command_argv when it tokenizes.
1614 But letting them survive inside function invocations loses because
1615 we don't want the functions to see them as part of the text. */
1617 char *in, *out, *ref;
1619 /* IN points to where in the line we are scanning.
1620 OUT points to where in the line we are writing.
1621 When we collapse a backslash-newline combination,
1622 IN gets ahead of OUT. */
1624 in = out = cmds->command_lines[i];
1625 while ((ref = strchr (in, '$')) != 0)
1627 ++ref; /* Move past the $. */
1629 if (out != in)
1630 /* Copy the text between the end of the last chunk
1631 we processed (where IN points) and the new chunk
1632 we are about to process (where REF points). */
1633 memmove (out, in, ref - in);
1635 /* Move both pointers past the boring stuff. */
1636 out += ref - in;
1637 in = ref;
1639 if (*ref == '(' || *ref == '{')
1641 char openparen = *ref;
1642 char closeparen = openparen == '(' ? ')' : '}';
1643 int count;
1644 char *p;
1646 *out++ = *in++; /* Copy OPENPAREN. */
1647 /* IN now points past the opening paren or brace.
1648 Count parens or braces until it is matched. */
1649 count = 0;
1650 while (*in != '\0')
1652 if (*in == closeparen && --count < 0)
1653 break;
1654 else if (*in == '\\' && in[1] == '\n')
1656 /* We have found a backslash-newline inside a
1657 variable or function reference. Eat it and
1658 any following whitespace. */
1660 int quoted = 0;
1661 for (p = in - 1; p > ref && *p == '\\'; --p)
1662 quoted = !quoted;
1664 if (quoted)
1665 /* There were two or more backslashes, so this is
1666 not really a continuation line. We don't collapse
1667 the quoting backslashes here as is done in
1668 collapse_continuations, because the line will
1669 be collapsed again after expansion. */
1670 *out++ = *in++;
1671 else
1673 /* Skip the backslash, newline and
1674 any following whitespace. */
1675 in = next_token (in + 2);
1677 /* Discard any preceding whitespace that has
1678 already been written to the output. */
1679 while (out > ref
1680 && isblank ((unsigned char)out[-1]))
1681 --out;
1683 /* Replace it all with a single space. */
1684 *out++ = ' ';
1687 else
1689 if (*in == openparen)
1690 ++count;
1692 *out++ = *in++;
1698 /* There are no more references in this line to worry about.
1699 Copy the remaining uninteresting text to the output. */
1700 if (out != in)
1701 memmove (out, in, strlen (in) + 1);
1703 /* Finally, expand the line. */
1704 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1705 file);
1708 /* Start the command sequence, record it in a new
1709 `struct child', and add that to the chain. */
1711 c = xcalloc (sizeof (struct child));
1712 c->file = file;
1713 c->command_lines = lines;
1714 c->sh_batch_file = NULL;
1716 /* Cache dontcare flag because file->dontcare can be changed once we
1717 return. Check dontcare inheritance mechanism for details. */
1718 c->dontcare = file->dontcare;
1720 /* Fetch the first command line to be run. */
1721 job_next_command (c);
1723 /* Wait for a job slot to be freed up. If we allow an infinite number
1724 don't bother; also job_slots will == 0 if we're using the jobserver. */
1726 if (job_slots != 0)
1727 while (job_slots_used == job_slots)
1728 reap_children (1, 0);
1730 #ifdef MAKE_JOBSERVER
1731 /* If we are controlling multiple jobs make sure we have a token before
1732 starting the child. */
1734 /* This can be inefficient. There's a decent chance that this job won't
1735 actually have to run any subprocesses: the command script may be empty
1736 or otherwise optimized away. It would be nice if we could defer
1737 obtaining a token until just before we need it, in start_job_command.
1738 To do that we'd need to keep track of whether we'd already obtained a
1739 token (since start_job_command is called for each line of the job, not
1740 just once). Also more thought needs to go into the entire algorithm;
1741 this is where the old parallel job code waits, so... */
1743 else if (job_fds[0] >= 0)
1744 while (1)
1746 char token;
1747 int got_token;
1748 int saved_errno;
1750 DB (DB_JOBS, ("Need a job token; we %shave children\n",
1751 children ? "" : "don't "));
1753 /* If we don't already have a job started, use our "free" token. */
1754 if (!jobserver_tokens)
1755 break;
1757 /* Read a token. As long as there's no token available we'll block.
1758 We enable interruptible system calls before the read(2) so that if
1759 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1760 we can process the death(s) and return tokens to the free pool.
1762 Once we return from the read, we immediately reinstate restartable
1763 system calls. This allows us to not worry about checking for
1764 EINTR on all the other system calls in the program.
1766 There is one other twist: there is a span between the time
1767 reap_children() does its last check for dead children and the time
1768 the read(2) call is entered, below, where if a child dies we won't
1769 notice. This is extremely serious as it could cause us to
1770 deadlock, given the right set of events.
1772 To avoid this, we do the following: before we reap_children(), we
1773 dup(2) the read FD on the jobserver pipe. The read(2) call below
1774 uses that new FD. In the signal handler, we close that FD. That
1775 way, if a child dies during the section mentioned above, the
1776 read(2) will be invoked with an invalid FD and will return
1777 immediately with EBADF. */
1779 /* Make sure we have a dup'd FD. */
1780 if (job_rfd < 0)
1782 DB (DB_JOBS, ("Duplicate the job FD\n"));
1783 job_rfd = dup (job_fds[0]);
1786 /* Reap anything that's currently waiting. */
1787 reap_children (0, 0);
1789 /* Kick off any jobs we have waiting for an opportunity that
1790 can run now (ie waiting for load). */
1791 start_waiting_jobs ();
1793 /* If our "free" slot has become available, use it; we don't need an
1794 actual token. */
1795 if (!jobserver_tokens)
1796 break;
1798 /* There must be at least one child already, or we have no business
1799 waiting for a token. */
1800 if (!children)
1801 fatal (NILF, "INTERNAL: no children as we go to sleep on read\n");
1803 /* Set interruptible system calls, and read() for a job token. */
1804 set_child_handler_action_flags (1, waiting_jobs != NULL);
1805 got_token = read (job_rfd, &token, 1);
1806 saved_errno = errno;
1807 set_child_handler_action_flags (0, waiting_jobs != NULL);
1809 /* If we got one, we're done here. */
1810 if (got_token == 1)
1812 DB (DB_JOBS, (_("Obtained token for child %p (%s).\n"),
1813 c, c->file->name));
1814 break;
1817 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1818 go back and reap_children(), and try again. */
1819 errno = saved_errno;
1820 if (errno != EINTR && errno != EBADF)
1821 pfatal_with_name (_("read jobs pipe"));
1822 if (errno == EBADF)
1823 DB (DB_JOBS, ("Read returned EBADF.\n"));
1825 #endif
1827 ++jobserver_tokens;
1829 /* Trace the build.
1830 Use message here so that changes to working directories are logged. */
1831 if (trace_flag)
1833 char *newer = allocated_variable_expand_for_file ("$?", c->file);
1834 char *nm;
1836 if (! cmds->fileinfo.filenm)
1837 nm = _("<builtin>");
1838 else
1840 nm = alloca (strlen (cmds->fileinfo.filenm) + 1 + 11 + 1);
1841 sprintf (nm, "%s:%lu", cmds->fileinfo.filenm, cmds->fileinfo.lineno);
1844 if (newer[0] == '\0')
1845 message (0, _("%s: target `%s' does not exist"), nm, c->file->name);
1846 else
1847 message (0, _("%s: update target `%s' due to: %s"), nm,
1848 c->file->name, newer);
1850 free (newer);
1854 /* The job is now primed. Start it running.
1855 (This will notice if there is in fact no recipe.) */
1856 start_waiting_job (c);
1858 if (job_slots == 1 || not_parallel)
1859 /* Since there is only one job slot, make things run linearly.
1860 Wait for the child to die, setting the state to `cs_finished'. */
1861 while (file->command_state == cs_running)
1862 reap_children (1, 0);
1864 return;
1867 /* Move CHILD's pointers to the next command for it to execute.
1868 Returns nonzero if there is another command. */
1870 static int
1871 job_next_command (struct child *child)
1873 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1875 /* There are no more lines in the expansion of this line. */
1876 if (child->command_line == child->file->cmds->ncommand_lines)
1878 /* There are no more lines to be expanded. */
1879 child->command_ptr = 0;
1880 return 0;
1882 else
1883 /* Get the next line to run. */
1884 child->command_ptr = child->command_lines[child->command_line++];
1886 return 1;
1889 /* Determine if the load average on the system is too high to start a new job.
1890 The real system load average is only recomputed once a second. However, a
1891 very parallel make can easily start tens or even hundreds of jobs in a
1892 second, which brings the system to its knees for a while until that first
1893 batch of jobs clears out.
1895 To avoid this we use a weighted algorithm to try to account for jobs which
1896 have been started since the last second, and guess what the load average
1897 would be now if it were computed.
1899 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1900 who writes:
1902 ! calculate something load-oid and add to the observed sys.load,
1903 ! so that latter can catch up:
1904 ! - every job started increases jobctr;
1905 ! - every dying job decreases a positive jobctr;
1906 ! - the jobctr value gets zeroed every change of seconds,
1907 ! after its value*weight_b is stored into the 'backlog' value last_sec
1908 ! - weight_a times the sum of jobctr and last_sec gets
1909 ! added to the observed sys.load.
1911 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1912 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1913 ! sub-shelled commands (rm, echo, sed...) for tests.
1914 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1915 ! resulted in significant excession of the load limit, raising it
1916 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1917 ! reach the limit in most test cases.
1919 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1920 ! exceeding the limit for longer-running stuff (compile jobs in
1921 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1922 ! small jobs' effects.
1926 #define LOAD_WEIGHT_A 0.25
1927 #define LOAD_WEIGHT_B 0.25
1929 static int
1930 load_too_high (void)
1932 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
1933 return 1;
1934 #else
1935 static double last_sec;
1936 static time_t last_now;
1937 double load, guess;
1938 time_t now;
1940 #ifdef WINDOWS32
1941 /* sub_proc.c cannot wait for more than MAXIMUM_WAIT_OBJECTS children */
1942 if (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
1943 return 1;
1944 #endif
1946 if (max_load_average < 0)
1947 return 0;
1949 /* Find the real system load average. */
1950 make_access ();
1951 if (getloadavg (&load, 1) != 1)
1953 static int lossage = -1;
1954 /* Complain only once for the same error. */
1955 if (lossage == -1 || errno != lossage)
1957 if (errno == 0)
1958 /* An errno value of zero means getloadavg is just unsupported. */
1959 error (NILF,
1960 _("cannot enforce load limits on this operating system"));
1961 else
1962 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1964 lossage = errno;
1965 load = 0;
1967 user_access ();
1969 /* If we're in a new second zero the counter and correct the backlog
1970 value. Only keep the backlog for one extra second; after that it's 0. */
1971 now = time (NULL);
1972 if (last_now < now)
1974 if (last_now == now - 1)
1975 last_sec = LOAD_WEIGHT_B * job_counter;
1976 else
1977 last_sec = 0.0;
1979 job_counter = 0;
1980 last_now = now;
1983 /* Try to guess what the load would be right now. */
1984 guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
1986 DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1987 guess, load, max_load_average));
1989 return guess >= max_load_average;
1990 #endif
1993 /* Start jobs that are waiting for the load to be lower. */
1995 void
1996 start_waiting_jobs (void)
1998 struct child *job;
2000 if (waiting_jobs == 0)
2001 return;
2005 /* Check for recently deceased descendants. */
2006 reap_children (0, 0);
2008 /* Take a job off the waiting list. */
2009 job = waiting_jobs;
2010 waiting_jobs = job->next;
2012 /* Try to start that job. We break out of the loop as soon
2013 as start_waiting_job puts one back on the waiting list. */
2015 while (start_waiting_job (job) && waiting_jobs != 0);
2017 return;
2020 #ifndef WINDOWS32
2022 /* EMX: Start a child process. This function returns the new pid. */
2023 # if defined __EMX__
2025 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2027 int pid;
2028 /* stdin_fd == 0 means: nothing to do for stdin;
2029 stdout_fd == 1 means: nothing to do for stdout */
2030 int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
2031 int save_stdout = (stdout_fd != 1) ? dup (1): 1;
2033 /* < 0 only if dup() failed */
2034 if (save_stdin < 0)
2035 fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
2036 if (save_stdout < 0)
2037 fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
2039 /* Close unnecessary file handles for the child. */
2040 if (save_stdin != 0)
2041 CLOSE_ON_EXEC (save_stdin);
2042 if (save_stdout != 1)
2043 CLOSE_ON_EXEC (save_stdout);
2045 /* Connect the pipes to the child process. */
2046 if (stdin_fd != 0)
2047 (void) dup2 (stdin_fd, 0);
2048 if (stdout_fd != 1)
2049 (void) dup2 (stdout_fd, 1);
2051 /* stdin_fd and stdout_fd must be closed on exit because we are
2052 still in the parent process */
2053 if (stdin_fd != 0)
2054 CLOSE_ON_EXEC (stdin_fd);
2055 if (stdout_fd != 1)
2056 CLOSE_ON_EXEC (stdout_fd);
2058 /* Run the command. */
2059 pid = exec_command (argv, envp);
2061 /* Restore stdout/stdin of the parent and close temporary FDs. */
2062 if (stdin_fd != 0)
2064 if (dup2 (save_stdin, 0) != 0)
2065 fatal (NILF, _("Could not restore stdin\n"));
2066 else
2067 close (save_stdin);
2070 if (stdout_fd != 1)
2072 if (dup2 (save_stdout, 1) != 1)
2073 fatal (NILF, _("Could not restore stdout\n"));
2074 else
2075 close (save_stdout);
2078 return pid;
2081 #elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
2083 /* UNIX:
2084 Replace the current process with one executing the command in ARGV.
2085 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2086 the environment of the new program. This function does not return. */
2087 void
2088 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2090 if (stdin_fd != 0)
2091 (void) dup2 (stdin_fd, 0);
2092 if (stdout_fd != 1)
2093 (void) dup2 (stdout_fd, 1);
2094 if (stdin_fd != 0)
2095 (void) close (stdin_fd);
2096 if (stdout_fd != 1)
2097 (void) close (stdout_fd);
2099 /* Run the command. */
2100 exec_command (argv, envp);
2102 #endif /* !AMIGA && !__MSDOS__ && !VMS */
2103 #endif /* !WINDOWS32 */
2105 #ifndef _AMIGA
2106 /* Replace the current process with one running the command in ARGV,
2107 with environment ENVP. This function does not return. */
2109 /* EMX: This function returns the pid of the child process. */
2110 # ifdef __EMX__
2112 # else
2113 void
2114 # endif
2115 exec_command (char **argv, char **envp)
2117 #ifdef VMS
2118 /* to work around a problem with signals and execve: ignore them */
2119 #ifdef SIGCHLD
2120 signal (SIGCHLD,SIG_IGN);
2121 #endif
2122 /* Run the program. */
2123 execve (argv[0], argv, envp);
2124 perror_with_name ("execve: ", argv[0]);
2125 _exit (EXIT_FAILURE);
2126 #else
2127 #ifdef WINDOWS32
2128 HANDLE hPID;
2129 HANDLE hWaitPID;
2130 int err = 0;
2131 int exit_code = EXIT_FAILURE;
2133 /* make sure CreateProcess() has Path it needs */
2134 sync_Path_environment();
2136 /* launch command */
2137 hPID = process_easy(argv, envp);
2139 /* make sure launch ok */
2140 if (hPID == INVALID_HANDLE_VALUE)
2142 int i;
2143 fprintf(stderr,
2144 _("process_easy() failed to launch process (e=%ld)\n"),
2145 process_last_err(hPID));
2146 for (i = 0; argv[i]; i++)
2147 fprintf(stderr, "%s ", argv[i]);
2148 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2149 exit(EXIT_FAILURE);
2152 /* wait and reap last child */
2153 hWaitPID = process_wait_for_any();
2154 while (hWaitPID)
2156 /* was an error found on this process? */
2157 err = process_last_err(hWaitPID);
2159 /* get exit data */
2160 exit_code = process_exit_code(hWaitPID);
2162 if (err)
2163 fprintf(stderr, "make (e=%d, rc=%d): %s",
2164 err, exit_code, map_windows32_error_to_string(err));
2166 /* cleanup process */
2167 process_cleanup(hWaitPID);
2169 /* expect to find only last pid, warn about other pids reaped */
2170 if (hWaitPID == hPID)
2171 break;
2172 else
2174 char *pidstr = xstrdup (pid2str ((pid_t)hWaitPID));
2176 fprintf(stderr,
2177 _("make reaped child pid %s, still waiting for pid %s\n"),
2178 pidstr, pid2str ((pid_t)hPID));
2179 free (pidstr);
2183 /* return child's exit code as our exit code */
2184 exit(exit_code);
2186 #else /* !WINDOWS32 */
2188 # ifdef __EMX__
2189 int pid;
2190 # endif
2192 /* Be the user, permanently. */
2193 child_access ();
2195 # ifdef __EMX__
2197 /* Run the program. */
2198 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2200 if (pid >= 0)
2201 return pid;
2203 /* the file might have a strange shell extension */
2204 if (errno == ENOENT)
2205 errno = ENOEXEC;
2207 # else
2209 /* Run the program. */
2210 environ = envp;
2211 execvp (argv[0], argv);
2213 # endif /* !__EMX__ */
2215 switch (errno)
2217 case ENOENT:
2218 error (NILF, _("%s: Command not found"), argv[0]);
2219 break;
2220 case ENOEXEC:
2222 /* The file is not executable. Try it as a shell script. */
2223 extern char *getenv ();
2224 char *shell;
2225 char **new_argv;
2226 int argc;
2227 int i=1;
2229 # ifdef __EMX__
2230 /* Do not use $SHELL from the environment */
2231 struct variable *p = lookup_variable ("SHELL", 5);
2232 if (p)
2233 shell = p->value;
2234 else
2235 shell = 0;
2236 # else
2237 shell = getenv ("SHELL");
2238 # endif
2239 if (shell == 0)
2240 shell = default_shell;
2242 argc = 1;
2243 while (argv[argc] != 0)
2244 ++argc;
2246 # ifdef __EMX__
2247 if (!unixy_shell)
2248 ++argc;
2249 # endif
2251 new_argv = alloca ((1 + argc + 1) * sizeof (char *));
2252 new_argv[0] = shell;
2254 # ifdef __EMX__
2255 if (!unixy_shell)
2257 new_argv[1] = "/c";
2258 ++i;
2259 --argc;
2261 # endif
2263 new_argv[i] = argv[0];
2264 while (argc > 0)
2266 new_argv[i + argc] = argv[argc];
2267 --argc;
2270 # ifdef __EMX__
2271 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2272 if (pid >= 0)
2273 break;
2274 # else
2275 execvp (shell, new_argv);
2276 # endif
2277 if (errno == ENOENT)
2278 error (NILF, _("%s: Shell program not found"), shell);
2279 else
2280 perror_with_name ("execvp: ", shell);
2281 break;
2284 # ifdef __EMX__
2285 case EINVAL:
2286 /* this nasty error was driving me nuts :-( */
2287 error (NILF, _("spawnvpe: environment space might be exhausted"));
2288 /* FALLTHROUGH */
2289 # endif
2291 default:
2292 perror_with_name ("execvp: ", argv[0]);
2293 break;
2296 # ifdef __EMX__
2297 return pid;
2298 # else
2299 _exit (127);
2300 # endif
2301 #endif /* !WINDOWS32 */
2302 #endif /* !VMS */
2304 #else /* On Amiga */
2305 void exec_command (char **argv)
2307 MyExecute (argv);
2310 void clean_tmp (void)
2312 DeleteFile (amiga_bname);
2315 #endif /* On Amiga */
2317 #ifndef VMS
2318 /* Figure out the argument list necessary to run LINE as a command. Try to
2319 avoid using a shell. This routine handles only ' quoting, and " quoting
2320 when no backslash, $ or ` characters are seen in the quotes. Starting
2321 quotes may be escaped with a backslash. If any of the characters in
2322 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2323 is the first word of a line, the shell is used.
2325 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2326 If *RESTP is NULL, newlines will be ignored.
2328 SHELL is the shell to use, or nil to use the default shell.
2329 IFS is the value of $IFS, or nil (meaning the default).
2331 FLAGS is the value of lines_flags for this command line. It is
2332 used in the WINDOWS32 port to check whether + or $(MAKE) were found
2333 in this command line, in which case the effect of just_print_flag
2334 is overridden. */
2336 static char **
2337 construct_command_argv_internal (char *line, char **restp, char *shell,
2338 char *shellflags, char *ifs, int flags,
2339 char **batch_filename_p)
2341 #ifdef __MSDOS__
2342 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2343 We call `system' for anything that requires ``slow'' processing,
2344 because DOS shells are too dumb. When $SHELL points to a real
2345 (unix-style) shell, `system' just calls it to do everything. When
2346 $SHELL points to a DOS shell, `system' does most of the work
2347 internally, calling the shell only for its internal commands.
2348 However, it looks on the $PATH first, so you can e.g. have an
2349 external command named `mkdir'.
2351 Since we call `system', certain characters and commands below are
2352 actually not specific to COMMAND.COM, but to the DJGPP implementation
2353 of `system'. In particular:
2355 The shell wildcard characters are in DOS_CHARS because they will
2356 not be expanded if we call the child via `spawnXX'.
2358 The `;' is in DOS_CHARS, because our `system' knows how to run
2359 multiple commands on a single line.
2361 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2362 won't have to tell one from another and have one more set of
2363 commands and special characters. */
2364 static char sh_chars_dos[] = "*?[];|<>%^&()";
2365 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2366 "copy", "ctty", "date", "del", "dir", "echo",
2367 "erase", "exit", "for", "goto", "if", "md",
2368 "mkdir", "path", "pause", "prompt", "rd",
2369 "rmdir", "rem", "ren", "rename", "set",
2370 "shift", "time", "type", "ver", "verify",
2371 "vol", ":", 0 };
2373 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2374 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2375 "logout", "set", "umask", "wait", "while",
2376 "for", "case", "if", ":", ".", "break",
2377 "continue", "export", "read", "readonly",
2378 "shift", "times", "trap", "switch", "unset",
2379 "ulimit", 0 };
2381 char *sh_chars;
2382 char **sh_cmds;
2383 #elif defined (__EMX__)
2384 static char sh_chars_dos[] = "*?[];|<>%^&()";
2385 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2386 "copy", "ctty", "date", "del", "dir", "echo",
2387 "erase", "exit", "for", "goto", "if", "md",
2388 "mkdir", "path", "pause", "prompt", "rd",
2389 "rmdir", "rem", "ren", "rename", "set",
2390 "shift", "time", "type", "ver", "verify",
2391 "vol", ":", 0 };
2393 static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
2394 static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2395 "date", "del", "detach", "dir", "echo",
2396 "endlocal", "erase", "exit", "for", "goto", "if",
2397 "keys", "md", "mkdir", "move", "path", "pause",
2398 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2399 "set", "setlocal", "shift", "start", "time",
2400 "type", "ver", "verify", "vol", ":", 0 };
2402 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~'";
2403 static char *sh_cmds_sh[] = { "echo", "cd", "eval", "exec", "exit", "login",
2404 "logout", "set", "umask", "wait", "while",
2405 "for", "case", "if", ":", ".", "break",
2406 "continue", "export", "read", "readonly",
2407 "shift", "times", "trap", "switch", "unset",
2408 0 };
2409 char *sh_chars;
2410 char **sh_cmds;
2412 #elif defined (_AMIGA)
2413 static char sh_chars[] = "#;\"|<>()?*$`";
2414 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2415 "rename", "set", "setenv", "date", "makedir",
2416 "skip", "else", "endif", "path", "prompt",
2417 "unset", "unsetenv", "version",
2418 0 };
2419 #elif defined (WINDOWS32)
2420 static char sh_chars_dos[] = "\"|&<>";
2421 static char *sh_cmds_dos[] = { "assoc", "break", "call", "cd", "chcp",
2422 "chdir", "cls", "color", "copy", "ctty",
2423 "date", "del", "dir", "echo", "echo.",
2424 "endlocal", "erase", "exit", "for", "ftype",
2425 "goto", "if", "if", "md", "mkdir", "path",
2426 "pause", "prompt", "rd", "rem", "ren",
2427 "rename", "rmdir", "set", "setlocal",
2428 "shift", "time", "title", "type", "ver",
2429 "verify", "vol", ":", 0 };
2430 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2431 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2432 "logout", "set", "umask", "wait", "while", "for",
2433 "case", "if", ":", ".", "break", "continue",
2434 "export", "read", "readonly", "shift", "times",
2435 "trap", "switch", "test",
2436 #ifdef BATCH_MODE_ONLY_SHELL
2437 "echo",
2438 #endif
2439 0 };
2440 char* sh_chars;
2441 char** sh_cmds;
2442 #elif defined(__riscos__)
2443 static char sh_chars[] = "";
2444 static char *sh_cmds[] = { 0 };
2445 #else /* must be UNIX-ish */
2446 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~!";
2447 static char *sh_cmds[] = { ".", ":", "break", "case", "cd", "continue",
2448 "eval", "exec", "exit", "export", "for", "if",
2449 "login", "logout", "read", "readonly", "set",
2450 "shift", "switch", "test", "times", "trap",
2451 "ulimit", "umask", "unset", "wait", "while", 0 };
2452 # ifdef HAVE_DOS_PATHS
2453 /* This is required if the MSYS/Cygwin ports (which do not define
2454 WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
2455 sh_chars_sh[] directly (see below). */
2456 static char *sh_chars_sh = sh_chars;
2457 # endif /* HAVE_DOS_PATHS */
2458 #endif
2459 int i;
2460 char *p;
2461 char *ap;
2462 char *end;
2463 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2464 char **new_argv = 0;
2465 char *argstr = 0;
2466 #ifdef WINDOWS32
2467 int slow_flag = 0;
2469 if (!unixy_shell) {
2470 sh_cmds = sh_cmds_dos;
2471 sh_chars = sh_chars_dos;
2472 } else {
2473 sh_cmds = sh_cmds_sh;
2474 sh_chars = sh_chars_sh;
2476 #endif /* WINDOWS32 */
2478 if (restp != NULL)
2479 *restp = NULL;
2481 /* Make sure not to bother processing an empty line. */
2482 while (isblank ((unsigned char)*line))
2483 ++line;
2484 if (*line == '\0')
2485 return 0;
2487 if (shellflags == 0)
2488 shellflags = posix_pedantic ? "-ec" : "-c";
2490 /* See if it is safe to parse commands internally. */
2491 if (shell == 0)
2492 shell = default_shell;
2493 #ifdef WINDOWS32
2494 else if (strcmp (shell, default_shell))
2496 char *s1 = _fullpath (NULL, shell, 0);
2497 char *s2 = _fullpath (NULL, default_shell, 0);
2499 slow_flag = strcmp ((s1 ? s1 : ""), (s2 ? s2 : ""));
2501 if (s1)
2502 free (s1);
2503 if (s2)
2504 free (s2);
2506 if (slow_flag)
2507 goto slow;
2508 #else /* not WINDOWS32 */
2509 #if defined (__MSDOS__) || defined (__EMX__)
2510 else if (strcasecmp (shell, default_shell))
2512 extern int _is_unixy_shell (const char *_path);
2514 DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
2515 default_shell, shell));
2516 unixy_shell = _is_unixy_shell (shell);
2517 /* we must allocate a copy of shell: construct_command_argv() will free
2518 * shell after this function returns. */
2519 default_shell = xstrdup (shell);
2521 if (unixy_shell)
2523 sh_chars = sh_chars_sh;
2524 sh_cmds = sh_cmds_sh;
2526 else
2528 sh_chars = sh_chars_dos;
2529 sh_cmds = sh_cmds_dos;
2530 # ifdef __EMX__
2531 if (_osmode == OS2_MODE)
2533 sh_chars = sh_chars_os2;
2534 sh_cmds = sh_cmds_os2;
2536 # endif
2538 #else /* !__MSDOS__ */
2539 else if (strcmp (shell, default_shell))
2540 goto slow;
2541 #endif /* !__MSDOS__ && !__EMX__ */
2542 #endif /* not WINDOWS32 */
2544 if (ifs != 0)
2545 for (ap = ifs; *ap != '\0'; ++ap)
2546 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2547 goto slow;
2549 if (shellflags != 0)
2550 if (shellflags[0] != '-'
2551 || ((shellflags[1] != 'c' || shellflags[2] != '\0')
2552 && (shellflags[1] != 'e' || shellflags[2] != 'c' || shellflags[3] != '\0')))
2553 goto slow;
2555 i = strlen (line) + 1;
2557 /* More than 1 arg per character is impossible. */
2558 new_argv = xmalloc (i * sizeof (char *));
2560 /* All the args can fit in a buffer as big as LINE is. */
2561 ap = new_argv[0] = argstr = xmalloc (i);
2562 end = ap + i;
2564 /* I is how many complete arguments have been found. */
2565 i = 0;
2566 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2567 for (p = line; *p != '\0'; ++p)
2569 assert (ap <= end);
2571 if (instring)
2573 /* Inside a string, just copy any char except a closing quote
2574 or a backslash-newline combination. */
2575 if (*p == instring)
2577 instring = 0;
2578 if (ap == new_argv[0] || *(ap-1) == '\0')
2579 last_argument_was_empty = 1;
2581 else if (*p == '\\' && p[1] == '\n')
2583 /* Backslash-newline is handled differently depending on what
2584 kind of string we're in: inside single-quoted strings you
2585 keep them; in double-quoted strings they disappear. For
2586 DOS/Windows/OS2, if we don't have a POSIX shell, we keep the
2587 pre-POSIX behavior of removing the backslash-newline. */
2588 if (instring == '"'
2589 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2590 || !unixy_shell
2591 #endif
2593 ++p;
2594 else
2596 *(ap++) = *(p++);
2597 *(ap++) = *p;
2600 else if (*p == '\n' && restp != NULL)
2602 /* End of the command line. */
2603 *restp = p;
2604 goto end_of_line;
2606 /* Backslash, $, and ` are special inside double quotes.
2607 If we see any of those, punt.
2608 But on MSDOS, if we use COMMAND.COM, double and single
2609 quotes have the same effect. */
2610 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2611 goto slow;
2612 else
2613 *ap++ = *p;
2615 else if (strchr (sh_chars, *p) != 0)
2616 /* Not inside a string, but it's a special char. */
2617 goto slow;
2618 else if (one_shell && *p == '\n')
2619 /* In .ONESHELL mode \n is a separator like ; or && */
2620 goto slow;
2621 #ifdef __MSDOS__
2622 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2623 /* `...' is a wildcard in DJGPP. */
2624 goto slow;
2625 #endif
2626 else
2627 /* Not a special char. */
2628 switch (*p)
2630 case '=':
2631 /* Equals is a special character in leading words before the
2632 first word with no equals sign in it. This is not the case
2633 with sh -k, but we never get here when using nonstandard
2634 shell flags. */
2635 if (! seen_nonequals && unixy_shell)
2636 goto slow;
2637 word_has_equals = 1;
2638 *ap++ = '=';
2639 break;
2641 case '\\':
2642 /* Backslash-newline has special case handling, ref POSIX.
2643 We're in the fastpath, so emulate what the shell would do. */
2644 if (p[1] == '\n')
2646 /* Throw out the backslash and newline. */
2647 ++p;
2649 /* If there's nothing in this argument yet, skip any
2650 whitespace before the start of the next word. */
2651 if (ap == new_argv[i])
2652 p = next_token (p + 1) - 1;
2654 else if (p[1] != '\0')
2656 #ifdef HAVE_DOS_PATHS
2657 /* Only remove backslashes before characters special to Unixy
2658 shells. All other backslashes are copied verbatim, since
2659 they are probably DOS-style directory separators. This
2660 still leaves a small window for problems, but at least it
2661 should work for the vast majority of naive users. */
2663 #ifdef __MSDOS__
2664 /* A dot is only special as part of the "..."
2665 wildcard. */
2666 if (strneq (p + 1, ".\\.\\.", 5))
2668 *ap++ = '.';
2669 *ap++ = '.';
2670 p += 4;
2672 else
2673 #endif
2674 if (p[1] != '\\' && p[1] != '\''
2675 && !isspace ((unsigned char)p[1])
2676 && strchr (sh_chars_sh, p[1]) == 0)
2677 /* back up one notch, to copy the backslash */
2678 --p;
2679 #endif /* HAVE_DOS_PATHS */
2681 /* Copy and skip the following char. */
2682 *ap++ = *++p;
2684 break;
2686 case '\'':
2687 case '"':
2688 instring = *p;
2689 break;
2691 case '\n':
2692 if (restp != NULL)
2694 /* End of the command line. */
2695 *restp = p;
2696 goto end_of_line;
2698 else
2699 /* Newlines are not special. */
2700 *ap++ = '\n';
2701 break;
2703 case ' ':
2704 case '\t':
2705 /* We have the end of an argument.
2706 Terminate the text of the argument. */
2707 *ap++ = '\0';
2708 new_argv[++i] = ap;
2709 last_argument_was_empty = 0;
2711 /* Update SEEN_NONEQUALS, which tells us if every word
2712 heretofore has contained an `='. */
2713 seen_nonequals |= ! word_has_equals;
2714 if (word_has_equals && ! seen_nonequals)
2715 /* An `=' in a word before the first
2716 word without one is magical. */
2717 goto slow;
2718 word_has_equals = 0; /* Prepare for the next word. */
2720 /* If this argument is the command name,
2721 see if it is a built-in shell command.
2722 If so, have the shell handle it. */
2723 if (i == 1)
2725 register int j;
2726 for (j = 0; sh_cmds[j] != 0; ++j)
2728 if (streq (sh_cmds[j], new_argv[0]))
2729 goto slow;
2730 # ifdef __EMX__
2731 /* Non-Unix shells are case insensitive. */
2732 if (!unixy_shell
2733 && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
2734 goto slow;
2735 # endif
2739 /* Ignore multiple whitespace chars. */
2740 p = next_token (p) - 1;
2741 break;
2743 default:
2744 *ap++ = *p;
2745 break;
2748 end_of_line:
2750 if (instring)
2751 /* Let the shell deal with an unterminated quote. */
2752 goto slow;
2754 /* Terminate the last argument and the argument list. */
2756 *ap = '\0';
2757 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2758 ++i;
2759 new_argv[i] = 0;
2761 if (i == 1)
2763 register int j;
2764 for (j = 0; sh_cmds[j] != 0; ++j)
2765 if (streq (sh_cmds[j], new_argv[0]))
2766 goto slow;
2769 if (new_argv[0] == 0)
2771 /* Line was empty. */
2772 free (argstr);
2773 free (new_argv);
2774 return 0;
2777 return new_argv;
2779 slow:;
2780 /* We must use the shell. */
2782 if (new_argv != 0)
2784 /* Free the old argument list we were working on. */
2785 free (argstr);
2786 free (new_argv);
2789 #ifdef __MSDOS__
2790 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2791 #endif
2793 #ifdef _AMIGA
2795 char *ptr;
2796 char *buffer;
2797 char *dptr;
2799 buffer = xmalloc (strlen (line)+1);
2801 ptr = line;
2802 for (dptr=buffer; *ptr; )
2804 if (*ptr == '\\' && ptr[1] == '\n')
2805 ptr += 2;
2806 else if (*ptr == '@') /* Kludge: multiline commands */
2808 ptr += 2;
2809 *dptr++ = '\n';
2811 else
2812 *dptr++ = *ptr++;
2814 *dptr = 0;
2816 new_argv = xmalloc (2 * sizeof (char *));
2817 new_argv[0] = buffer;
2818 new_argv[1] = 0;
2820 #else /* Not Amiga */
2821 #ifdef WINDOWS32
2823 * Not eating this whitespace caused things like
2825 * sh -c "\n"
2827 * which gave the shell fits. I think we have to eat
2828 * whitespace here, but this code should be considered
2829 * suspicious if things start failing....
2832 /* Make sure not to bother processing an empty line. */
2833 while (isspace ((unsigned char)*line))
2834 ++line;
2835 if (*line == '\0')
2836 return 0;
2837 #endif /* WINDOWS32 */
2840 /* SHELL may be a multi-word command. Construct a command line
2841 "$(SHELL) $(.SHELLFLAGS) LINE", with all special chars in LINE escaped.
2842 Then recurse, expanding this command line to get the final
2843 argument list. */
2845 unsigned int shell_len = strlen (shell);
2846 unsigned int line_len = strlen (line);
2847 unsigned int sflags_len = shellflags ? strlen (shellflags) : 0;
2848 char *command_ptr = NULL; /* used for batch_mode_shell mode */
2849 char *new_line;
2851 # ifdef __EMX__ /* is this necessary? */
2852 if (!unixy_shell && shellflags)
2853 shellflags[0] = '/'; /* "/c" */
2854 # endif
2856 /* In .ONESHELL mode we are allowed to throw the entire current
2857 recipe string at a single shell and trust that the user
2858 has configured the shell and shell flags, and formatted
2859 the string, appropriately. */
2860 if (one_shell)
2862 /* If the shell is Bourne compatible, we must remove and ignore
2863 interior special chars [@+-] because they're meaningless to
2864 the shell itself. If, however, we're in .ONESHELL mode and
2865 have changed SHELL to something non-standard, we should
2866 leave those alone because they could be part of the
2867 script. In this case we must also leave in place
2868 any leading [@+-] for the same reason. */
2870 /* Remove and ignore interior prefix chars [@+-] because they're
2871 meaningless given a single shell. */
2872 #if defined __MSDOS__ || defined (__EMX__)
2873 if (unixy_shell) /* the test is complicated and we already did it */
2874 #else
2875 if (is_bourne_compatible_shell(shell))
2876 #endif
2878 const char *f = line;
2879 char *t = line;
2881 /* Copy the recipe, removing and ignoring interior prefix chars
2882 [@+-]: they're meaningless in .ONESHELL mode. */
2883 while (f[0] != '\0')
2885 int esc = 0;
2887 /* This is the start of a new recipe line.
2888 Skip whitespace and prefix characters. */
2889 while (isblank (*f) || *f == '-' || *f == '@' || *f == '+')
2890 ++f;
2892 /* Copy until we get to the next logical recipe line. */
2893 while (*f != '\0')
2895 *(t++) = *(f++);
2896 if (f[-1] == '\\')
2897 esc = !esc;
2898 else
2900 /* On unescaped newline, we're done with this line. */
2901 if (f[-1] == '\n' && ! esc)
2902 break;
2904 /* Something else: reset the escape sequence. */
2905 esc = 0;
2909 *t = '\0';
2912 new_argv = xmalloc (4 * sizeof (char *));
2913 new_argv[0] = xstrdup(shell);
2914 new_argv[1] = xstrdup(shellflags ? shellflags : "");
2915 new_argv[2] = line;
2916 new_argv[3] = NULL;
2917 return new_argv;
2920 new_line = alloca ((shell_len*2) + 1 + sflags_len + 1
2921 + (line_len*2) + 1);
2922 ap = new_line;
2923 /* Copy SHELL, escaping any characters special to the shell. If
2924 we don't escape them, construct_command_argv_internal will
2925 recursively call itself ad nauseam, or until stack overflow,
2926 whichever happens first. */
2927 for (p = shell; *p != '\0'; ++p)
2929 if (strchr (sh_chars, *p) != 0)
2930 *(ap++) = '\\';
2931 *(ap++) = *p;
2933 *(ap++) = ' ';
2934 if (shellflags)
2935 memcpy (ap, shellflags, sflags_len);
2936 ap += sflags_len;
2937 *(ap++) = ' ';
2938 command_ptr = ap;
2939 for (p = line; *p != '\0'; ++p)
2941 if (restp != NULL && *p == '\n')
2943 *restp = p;
2944 break;
2946 else if (*p == '\\' && p[1] == '\n')
2948 /* POSIX says we keep the backslash-newline. If we don't have a
2949 POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
2950 and remove the backslash/newline. */
2951 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2952 # define PRESERVE_BSNL unixy_shell
2953 #else
2954 # define PRESERVE_BSNL 1
2955 #endif
2956 if (PRESERVE_BSNL)
2958 *(ap++) = '\\';
2959 /* Only non-batch execution needs another backslash,
2960 because it will be passed through a recursive
2961 invocation of this function. */
2962 if (!batch_mode_shell)
2963 *(ap++) = '\\';
2964 *(ap++) = '\n';
2966 ++p;
2967 continue;
2970 /* DOS shells don't know about backslash-escaping. */
2971 if (unixy_shell && !batch_mode_shell &&
2972 (*p == '\\' || *p == '\'' || *p == '"'
2973 || isspace ((unsigned char)*p)
2974 || strchr (sh_chars, *p) != 0))
2975 *ap++ = '\\';
2976 #ifdef __MSDOS__
2977 else if (unixy_shell && strneq (p, "...", 3))
2979 /* The case of `...' wildcard again. */
2980 strcpy (ap, "\\.\\.\\");
2981 ap += 5;
2982 p += 2;
2984 #endif
2985 *ap++ = *p;
2987 if (ap == new_line + shell_len + sflags_len + 2)
2988 /* Line was empty. */
2989 return 0;
2990 *ap = '\0';
2992 #ifdef WINDOWS32
2993 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2994 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2995 cases, run commands via a script file. */
2996 if (just_print_flag && !(flags & COMMANDS_RECURSE)) {
2997 /* Need to allocate new_argv, although it's unused, because
2998 start_job_command will want to free it and its 0'th element. */
2999 new_argv = xmalloc(2 * sizeof (char *));
3000 new_argv[0] = xstrdup ("");
3001 new_argv[1] = NULL;
3002 } else if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
3003 int temp_fd;
3004 FILE* batch = NULL;
3005 int id = GetCurrentProcessId();
3006 PATH_VAR(fbuf);
3008 /* create a file name */
3009 sprintf(fbuf, "make%d", id);
3010 *batch_filename_ptr = create_batch_file (fbuf, unixy_shell, &temp_fd);
3012 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3013 *batch_filename_ptr));
3015 /* Create a FILE object for the batch file, and write to it the
3016 commands to be executed. Put the batch file in TEXT mode. */
3017 _setmode (temp_fd, _O_TEXT);
3018 batch = _fdopen (temp_fd, "wt");
3019 if (!unixy_shell)
3020 fputs ("@echo off\n", batch);
3021 fputs (command_ptr, batch);
3022 fputc ('\n', batch);
3023 fclose (batch);
3024 DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
3025 !unixy_shell ? "\n\t@echo off" : "", command_ptr));
3027 /* create argv */
3028 new_argv = xmalloc(3 * sizeof (char *));
3029 if (unixy_shell) {
3030 new_argv[0] = xstrdup (shell);
3031 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
3032 } else {
3033 new_argv[0] = xstrdup (*batch_filename_ptr);
3034 new_argv[1] = NULL;
3036 new_argv[2] = NULL;
3037 } else
3038 #endif /* WINDOWS32 */
3040 if (unixy_shell)
3041 new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0,
3042 flags, 0);
3044 #ifdef __EMX__
3045 else if (!unixy_shell)
3047 /* new_line is local, must not be freed therefore
3048 We use line here instead of new_line because we run the shell
3049 manually. */
3050 size_t line_len = strlen (line);
3051 char *p = new_line;
3052 char *q = new_line;
3053 memcpy (new_line, line, line_len + 1);
3054 /* Replace all backslash-newline combination and also following tabs.
3055 Important: stop at the first '\n' because that's what the loop above
3056 did. The next line starting at restp[0] will be executed during the
3057 next call of this function. */
3058 while (*q != '\0' && *q != '\n')
3060 if (q[0] == '\\' && q[1] == '\n')
3061 q += 2; /* remove '\\' and '\n' */
3062 else
3063 *p++ = *q++;
3065 *p = '\0';
3067 # ifndef NO_CMD_DEFAULT
3068 if (strnicmp (new_line, "echo", 4) == 0
3069 && (new_line[4] == ' ' || new_line[4] == '\t'))
3071 /* the builtin echo command: handle it separately */
3072 size_t echo_len = line_len - 5;
3073 char *echo_line = new_line + 5;
3075 /* special case: echo 'x="y"'
3076 cmd works this way: a string is printed as is, i.e., no quotes
3077 are removed. But autoconf uses a command like echo 'x="y"' to
3078 determine whether make works. autoconf expects the output x="y"
3079 so we will do exactly that.
3080 Note: if we do not allow cmd to be the default shell
3081 we do not need this kind of voodoo */
3082 if (echo_line[0] == '\''
3083 && echo_line[echo_len - 1] == '\''
3084 && strncmp (echo_line + 1, "ac_maketemp=",
3085 strlen ("ac_maketemp=")) == 0)
3087 /* remove the enclosing quotes */
3088 memmove (echo_line, echo_line + 1, echo_len - 2);
3089 echo_line[echo_len - 2] = '\0';
3092 # endif
3095 /* Let the shell decide what to do. Put the command line into the
3096 2nd command line argument and hope for the best ;-) */
3097 size_t sh_len = strlen (shell);
3099 /* exactly 3 arguments + NULL */
3100 new_argv = xmalloc (4 * sizeof (char *));
3101 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3102 the trailing '\0' */
3103 new_argv[0] = xmalloc (sh_len + line_len + 5);
3104 memcpy (new_argv[0], shell, sh_len + 1);
3105 new_argv[1] = new_argv[0] + sh_len + 1;
3106 memcpy (new_argv[1], "/c", 3);
3107 new_argv[2] = new_argv[1] + 3;
3108 memcpy (new_argv[2], new_line, line_len + 1);
3109 new_argv[3] = NULL;
3112 #elif defined(__MSDOS__)
3113 else
3115 /* With MSDOS shells, we must construct the command line here
3116 instead of recursively calling ourselves, because we
3117 cannot backslash-escape the special characters (see above). */
3118 new_argv = xmalloc (sizeof (char *));
3119 line_len = strlen (new_line) - shell_len - sflags_len - 2;
3120 new_argv[0] = xmalloc (line_len + 1);
3121 strncpy (new_argv[0],
3122 new_line + shell_len + sflags_len + 2, line_len);
3123 new_argv[0][line_len] = '\0';
3125 #else
3126 else
3127 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3128 __FILE__, __LINE__);
3129 #endif
3131 #endif /* ! AMIGA */
3133 return new_argv;
3135 #endif /* !VMS */
3137 /* Figure out the argument list necessary to run LINE as a command. Try to
3138 avoid using a shell. This routine handles only ' quoting, and " quoting
3139 when no backslash, $ or ` characters are seen in the quotes. Starting
3140 quotes may be escaped with a backslash. If any of the characters in
3141 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3142 is the first word of a line, the shell is used.
3144 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3145 If *RESTP is NULL, newlines will be ignored.
3147 FILE is the target whose commands these are. It is used for
3148 variable expansion for $(SHELL) and $(IFS). */
3150 char **
3151 construct_command_argv (char *line, char **restp, struct file *file,
3152 int cmd_flags, char **batch_filename_p)
3154 char *shell, *ifs, *shellflags;
3155 char **argv;
3157 #ifdef VMS
3158 char *cptr;
3159 int argc;
3161 argc = 0;
3162 cptr = line;
3163 for (;;)
3165 while ((*cptr != 0)
3166 && (isspace ((unsigned char)*cptr)))
3167 cptr++;
3168 if (*cptr == 0)
3169 break;
3170 while ((*cptr != 0)
3171 && (!isspace((unsigned char)*cptr)))
3172 cptr++;
3173 argc++;
3176 argv = xmalloc (argc * sizeof (char *));
3177 if (argv == 0)
3178 abort ();
3180 cptr = line;
3181 argc = 0;
3182 for (;;)
3184 while ((*cptr != 0)
3185 && (isspace ((unsigned char)*cptr)))
3186 cptr++;
3187 if (*cptr == 0)
3188 break;
3189 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3190 argv[argc++] = cptr;
3191 while ((*cptr != 0)
3192 && (!isspace((unsigned char)*cptr)))
3193 cptr++;
3194 if (*cptr != 0)
3195 *cptr++ = 0;
3197 #else
3199 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3200 int save = warn_undefined_variables_flag;
3201 warn_undefined_variables_flag = 0;
3203 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3204 #ifdef WINDOWS32
3206 * Convert to forward slashes so that construct_command_argv_internal()
3207 * is not confused.
3209 if (shell) {
3210 char *p = w32ify (shell, 0);
3211 strcpy (shell, p);
3213 #endif
3214 #ifdef __EMX__
3216 static const char *unixroot = NULL;
3217 static const char *last_shell = "";
3218 static int init = 0;
3219 if (init == 0)
3221 unixroot = getenv ("UNIXROOT");
3222 /* unixroot must be NULL or not empty */
3223 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3224 init = 1;
3227 /* if we have an unixroot drive and if shell is not default_shell
3228 (which means it's either cmd.exe or the test has already been
3229 performed) and if shell is an absolute path without drive letter,
3230 try whether it exists e.g.: if "/bin/sh" does not exist use
3231 "$UNIXROOT/bin/sh" instead. */
3232 if (unixroot && shell && strcmp (shell, last_shell) != 0
3233 && (shell[0] == '/' || shell[0] == '\\'))
3235 /* trying a new shell, check whether it exists */
3236 size_t size = strlen (shell);
3237 char *buf = xmalloc (size + 7);
3238 memcpy (buf, shell, size);
3239 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3240 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3242 /* try the same for the unixroot drive */
3243 memmove (buf + 2, buf, size + 5);
3244 buf[0] = unixroot[0];
3245 buf[1] = unixroot[1];
3246 if (access (buf, F_OK) == 0)
3247 /* we have found a shell! */
3248 /* free(shell); */
3249 shell = buf;
3250 else
3251 free (buf);
3253 else
3254 free (buf);
3257 #endif /* __EMX__ */
3259 shellflags = allocated_variable_expand_for_file ("$(.SHELLFLAGS)", file);
3260 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3262 warn_undefined_variables_flag = save;
3265 argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
3266 cmd_flags, batch_filename_p);
3268 free (shell);
3269 free (shellflags);
3270 free (ifs);
3271 #endif /* !VMS */
3272 return argv;
3275 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3277 dup2 (int old, int new)
3279 int fd;
3281 (void) close (new);
3282 fd = dup (old);
3283 if (fd != new)
3285 (void) close (fd);
3286 errno = EMFILE;
3287 return -1;
3290 return fd;
3292 #endif /* !HAVE_DUP2 && !_AMIGA */
3294 /* On VMS systems, include special VMS functions. */
3296 #ifdef VMS
3297 #include "vmsjobs.c"
3298 #endif