Define _GNU_SOURCE before testing for bsd_signal.
[make.git] / job.c
blobf7b7d5199fdc981e8bd1140b21184a62f1bfe943
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988-2012 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 it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
8 version.
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along with
15 this program. If not, see <http://www.gnu.org/licenses/>. */
17 #include "make.h"
19 #include <assert.h>
21 #include "job.h"
22 #include "debug.h"
23 #include "filedef.h"
24 #include "commands.h"
25 #include "variable.h"
26 #include "debug.h"
28 #include <string.h>
30 /* Default shell to use. */
31 #ifdef WINDOWS32
32 #include <windows.h>
34 char *default_shell = "sh.exe";
35 int no_default_sh_exe = 1;
36 int batch_mode_shell = 1;
37 HANDLE main_thread;
39 #elif defined (_AMIGA)
41 char default_shell[] = "";
42 extern int MyExecute (char **);
43 int batch_mode_shell = 0;
45 #elif defined (__MSDOS__)
47 /* The default shell is a pointer so we can change it if Makefile
48 says so. It is without an explicit path so we get a chance
49 to search the $PATH for it (since MSDOS doesn't have standard
50 directories we could trust). */
51 char *default_shell = "command.com";
52 int batch_mode_shell = 0;
54 #elif defined (__EMX__)
56 char *default_shell = "/bin/sh";
57 int batch_mode_shell = 0;
59 #elif defined (VMS)
61 # include <descrip.h>
62 char default_shell[] = "";
63 int batch_mode_shell = 0;
65 #elif defined (__riscos__)
67 char default_shell[] = "";
68 int batch_mode_shell = 0;
70 #else
72 char default_shell[] = "/bin/sh";
73 int batch_mode_shell = 0;
75 #endif
77 #ifdef __MSDOS__
78 # include <process.h>
79 static int execute_by_shell;
80 static int dos_pid = 123;
81 int dos_status;
82 int dos_command_running;
83 #endif /* __MSDOS__ */
85 #ifdef _AMIGA
86 # include <proto/dos.h>
87 static int amiga_pid = 123;
88 static int amiga_status;
89 static char amiga_bname[32];
90 static int amiga_batch_file;
91 #endif /* Amiga. */
93 #ifdef VMS
94 # ifndef __GNUC__
95 # include <processes.h>
96 # endif
97 # include <starlet.h>
98 # include <lib$routines.h>
99 static void vmsWaitForChildren (int *);
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 # define WAIT_NOHANG 1
110 #endif /* WINDOWS32 */
112 #ifdef __EMX__
113 # include <process.h>
114 #endif
116 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
117 # include <sys/wait.h>
118 #endif
120 #ifdef HAVE_WAITPID
121 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
122 #else /* Don't have waitpid. */
123 # ifdef HAVE_WAIT3
124 # ifndef wait3
125 extern int wait3 ();
126 # endif
127 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
128 # endif /* Have wait3. */
129 #endif /* Have waitpid. */
131 #if !defined (wait) && !defined (POSIX)
132 int wait ();
133 #endif
135 #ifndef HAVE_UNION_WAIT
137 # define WAIT_T int
139 # ifndef WTERMSIG
140 # define WTERMSIG(x) ((x) & 0x7f)
141 # endif
142 # ifndef WCOREDUMP
143 # define WCOREDUMP(x) ((x) & 0x80)
144 # endif
145 # ifndef WEXITSTATUS
146 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
147 # endif
148 # ifndef WIFSIGNALED
149 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
150 # endif
151 # ifndef WIFEXITED
152 # define WIFEXITED(x) (WTERMSIG (x) == 0)
153 # endif
155 #else /* Have 'union wait'. */
157 # define WAIT_T union wait
158 # ifndef WTERMSIG
159 # define WTERMSIG(x) ((x).w_termsig)
160 # endif
161 # ifndef WCOREDUMP
162 # define WCOREDUMP(x) ((x).w_coredump)
163 # endif
164 # ifndef WEXITSTATUS
165 # define WEXITSTATUS(x) ((x).w_retcode)
166 # endif
167 # ifndef WIFSIGNALED
168 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
169 # endif
170 # ifndef WIFEXITED
171 # define WIFEXITED(x) (WTERMSIG(x) == 0)
172 # endif
174 #endif /* Don't have 'union wait'. */
176 #if !defined(HAVE_UNISTD_H) && !defined(WINDOWS32)
177 int dup2 ();
178 int execve ();
179 void _exit ();
180 # ifndef VMS
181 int geteuid ();
182 int getegid ();
183 int setgid ();
184 int getgid ();
185 # endif
186 #endif
188 /* Different systems have different requirements for pid_t.
189 Plus we have to support gettext string translation... Argh. */
190 static const char *
191 pid2str (pid_t pid)
193 static char pidstring[100];
194 #if defined(WINDOWS32) && (__GNUC__ > 3 || _MSC_VER > 1300)
195 /* %Id is only needed for 64-builds, which were not supported by
196 older versions of Windows compilers. */
197 sprintf (pidstring, "%Id", pid);
198 #else
199 sprintf (pidstring, "%lu", (unsigned long) pid);
200 #endif
201 return pidstring;
204 int getloadavg (double loadavg[], int nelem);
205 int start_remote_job (char **argv, char **envp, int stdin_fd, int *is_remote,
206 int *id_ptr, int *used_stdin);
207 int start_remote_job_p (int);
208 int remote_status (int *exit_code_ptr, int *signal_ptr, int *coredump_ptr,
209 int block);
211 RETSIGTYPE child_handler (int);
212 static void free_child (struct child *);
213 static void start_job_command (struct child *child);
214 static int load_too_high (void);
215 static int job_next_command (struct child *);
216 static int start_waiting_job (struct child *);
218 /* Chain of all live (or recently deceased) children. */
220 struct child *children = 0;
222 /* Number of children currently running. */
224 unsigned int job_slots_used = 0;
226 /* Nonzero if the 'good' standard input is in use. */
228 static int good_stdin_used = 0;
230 /* Chain of children waiting to run until the load average goes down. */
232 static struct child *waiting_jobs = 0;
234 /* Non-zero if we use a *real* shell (always so on Unix). */
236 int unixy_shell = 1;
238 /* Number of jobs started in the current second. */
240 unsigned long job_counter = 0;
242 /* Number of jobserver tokens this instance is currently using. */
244 unsigned int jobserver_tokens = 0;
246 #ifdef WINDOWS32
248 * The macro which references this function is defined in make.h.
251 w32_kill(pid_t pid, int sig)
253 return ((process_kill((HANDLE)pid, sig) == TRUE) ? 0 : -1);
256 /* This function creates a temporary file name with an extension specified
257 * by the unixy arg.
258 * Return an xmalloc'ed string of a newly created temp file and its
259 * file descriptor, or die. */
260 static char *
261 create_batch_file (char const *base, int unixy, int *fd)
263 const char *const ext = unixy ? "sh" : "bat";
264 const char *error_string = NULL;
265 char temp_path[MAXPATHLEN]; /* need to know its length */
266 unsigned path_size = GetTempPath(sizeof temp_path, temp_path);
267 int path_is_dot = 0;
268 unsigned uniq = 1;
269 const unsigned sizemax = strlen (base) + strlen (ext) + 10;
271 if (path_size == 0)
273 path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
274 path_is_dot = 1;
277 while (path_size > 0 &&
278 path_size + sizemax < sizeof temp_path &&
279 uniq < 0x10000)
281 unsigned size = sprintf (temp_path + path_size,
282 "%s%s-%x.%s",
283 temp_path[path_size - 1] == '\\' ? "" : "\\",
284 base, uniq, ext);
285 HANDLE h = CreateFile (temp_path, /* file name */
286 GENERIC_READ | GENERIC_WRITE, /* desired access */
287 0, /* no share mode */
288 NULL, /* default security attributes */
289 CREATE_NEW, /* creation disposition */
290 FILE_ATTRIBUTE_NORMAL | /* flags and attributes */
291 FILE_ATTRIBUTE_TEMPORARY, /* we'll delete it */
292 NULL); /* no template file */
294 if (h == INVALID_HANDLE_VALUE)
296 const DWORD er = GetLastError();
298 if (er == ERROR_FILE_EXISTS || er == ERROR_ALREADY_EXISTS)
299 ++uniq;
301 /* the temporary path is not guaranteed to exist */
302 else if (path_is_dot == 0)
304 path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
305 path_is_dot = 1;
308 else
310 error_string = map_windows32_error_to_string (er);
311 break;
314 else
316 const unsigned final_size = path_size + size + 1;
317 char *const path = xmalloc (final_size);
318 memcpy (path, temp_path, final_size);
319 *fd = _open_osfhandle ((intptr_t)h, 0);
320 if (unixy)
322 char *p;
323 int ch;
324 for (p = path; (ch = *p) != 0; ++p)
325 if (ch == '\\')
326 *p = '/';
328 return path; /* good return */
332 *fd = -1;
333 if (error_string == NULL)
334 error_string = _("Cannot create a temporary file\n");
335 fatal (NILF, error_string);
337 /* not reached */
338 return NULL;
340 #endif /* WINDOWS32 */
342 #ifdef __EMX__
343 /* returns whether path is assumed to be a unix like shell. */
345 _is_unixy_shell (const char *path)
347 /* list of non unix shells */
348 const char *known_os2shells[] = {
349 "cmd.exe",
350 "cmd",
351 "4os2.exe",
352 "4os2",
353 "4dos.exe",
354 "4dos",
355 "command.com",
356 "command",
357 NULL
360 /* find the rightmost '/' or '\\' */
361 const char *name = strrchr (path, '/');
362 const char *p = strrchr (path, '\\');
363 unsigned i;
365 if (name && p) /* take the max */
366 name = (name > p) ? name : p;
367 else if (p) /* name must be 0 */
368 name = p;
369 else if (!name) /* name and p must be 0 */
370 name = path;
372 if (*name == '/' || *name == '\\') name++;
374 i = 0;
375 while (known_os2shells[i] != NULL) {
376 if (strcasecmp (name, known_os2shells[i]) == 0)
377 return 0; /* not a unix shell */
378 i++;
381 /* in doubt assume a unix like shell */
382 return 1;
384 #endif /* __EMX__ */
386 /* determines whether path looks to be a Bourne-like shell. */
388 is_bourne_compatible_shell (const char *path)
390 /* list of known unix (Bourne-like) shells */
391 const char *unix_shells[] = {
392 "sh",
393 "bash",
394 "ksh",
395 "rksh",
396 "zsh",
397 "ash",
398 "dash",
399 NULL
401 unsigned i, len;
403 /* find the rightmost '/' or '\\' */
404 const char *name = strrchr (path, '/');
405 char *p = strrchr (path, '\\');
407 if (name && p) /* take the max */
408 name = (name > p) ? name : p;
409 else if (p) /* name must be 0 */
410 name = p;
411 else if (!name) /* name and p must be 0 */
412 name = path;
414 if (*name == '/' || *name == '\\') name++;
416 /* this should be able to deal with extensions on Windows-like systems */
417 for (i = 0; unix_shells[i] != NULL; i++) {
418 len = strlen(unix_shells[i]);
419 #if defined(WINDOWS32) || defined(__MSDOS__)
420 if ((strncasecmp (name, unix_shells[i], len) == 0) &&
421 (strlen(name) >= len && (name[len] == '\0' || name[len] == '.')))
422 #else
423 if ((strncmp (name, unix_shells[i], len) == 0) &&
424 (strlen(name) >= len && name[len] == '\0'))
425 #endif
426 return 1; /* a known unix-style shell */
429 /* if not on the list, assume it's not a Bourne-like shell */
430 return 0;
434 /* Write an error message describing the exit status given in
435 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
436 Append "(ignored)" if IGNORED is nonzero. */
438 static void
439 child_error (const struct file *file,
440 int exit_code, int exit_sig, int coredump, int ignored)
442 const char *nm;
443 const char *pre = "*** ";
444 const char *post = "";
445 const char *dump = "";
446 struct floc *flocp = &file->cmds->fileinfo;
448 if (ignored && silent_flag)
449 return;
451 if (exit_sig && coredump)
452 dump = _(" (core dumped)");
454 if (ignored)
456 pre = "";
457 post = _(" (ignored)");
460 if (! flocp->filenm)
461 nm = _("<builtin>");
462 else
464 char *a = alloca (strlen (flocp->filenm) + 1 + 11 + 1);
465 sprintf (a, "%s:%lu", flocp->filenm, flocp->lineno);
466 nm = a;
468 message (0, _("%s: recipe for target '%s' failed"), nm, file->name);
470 #ifdef VMS
471 if (!(exit_code & 1))
472 error (NILF, _("%s[%s] Error 0x%x%s"), pre, file->name, exit_code, post);
473 #else
474 if (exit_sig == 0)
475 error (NILF, _("%s[%s] Error %d%s"), pre, file->name, exit_code, post);
476 else
477 error (NILF, _("%s[%s] %s%s%s"),
478 pre, file->name, strsignal (exit_sig), dump, post);
479 #endif /* VMS */
483 /* Handle a dead child. This handler may or may not ever be installed.
485 If we're using the jobserver feature, we need it. First, installing it
486 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
487 read FD to ensure we don't enter another blocking read without reaping all
488 the dead children. In this case we don't need the dead_children count.
490 If we don't have either waitpid or wait3, then make is unreliable, but we
491 use the dead_children count to reap children as best we can. */
493 static unsigned int dead_children = 0;
495 RETSIGTYPE
496 child_handler (int sig UNUSED)
498 ++dead_children;
500 if (job_rfd >= 0)
502 close (job_rfd);
503 job_rfd = -1;
506 #ifdef __EMX__
507 /* The signal handler must called only once! */
508 signal (SIGCHLD, SIG_DFL);
509 #endif
511 /* This causes problems if the SIGCHLD interrupts a printf().
512 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
516 extern int shell_function_pid, shell_function_completed;
518 /* Reap all dead children, storing the returned status and the new command
519 state ('cs_finished') in the 'file' member of the 'struct child' for the
520 dead child, and removing the child from the chain. In addition, if BLOCK
521 nonzero, we block in this function until we've reaped at least one
522 complete child, waiting for it to die if necessary. If ERR is nonzero,
523 print an error message first. */
525 void
526 reap_children (int block, int err)
528 #ifndef WINDOWS32
529 WAIT_T status;
530 #endif
531 /* Initially, assume we have some. */
532 int reap_more = 1;
534 #ifdef WAIT_NOHANG
535 # define REAP_MORE reap_more
536 #else
537 # define REAP_MORE dead_children
538 #endif
540 /* As long as:
542 We have at least one child outstanding OR a shell function in progress,
544 We're blocking for a complete child OR there are more children to reap
546 we'll keep reaping children. */
548 while ((children != 0 || shell_function_pid != 0)
549 && (block || REAP_MORE))
551 int remote = 0;
552 pid_t pid;
553 int exit_code, exit_sig, coredump;
554 struct child *lastc, *c;
555 int child_failed;
556 int any_remote, any_local;
557 int dontcare;
559 if (err && block)
561 static int printed = 0;
563 /* We might block for a while, so let the user know why.
564 Only print this message once no matter how many jobs are left. */
565 fflush (stdout);
566 if (!printed)
567 error (NILF, _("*** Waiting for unfinished jobs...."));
568 printed = 1;
571 /* We have one less dead child to reap. As noted in
572 child_handler() above, this count is completely unimportant for
573 all modern, POSIX-y systems that support wait3() or waitpid().
574 The rest of this comment below applies only to early, broken
575 pre-POSIX systems. We keep the count only because... it's there...
577 The test and decrement are not atomic; if it is compiled into:
578 register = dead_children - 1;
579 dead_children = register;
580 a SIGCHLD could come between the two instructions.
581 child_handler increments dead_children.
582 The second instruction here would lose that increment. But the
583 only effect of dead_children being wrong is that we might wait
584 longer than necessary to reap a child, and lose some parallelism;
585 and we might print the "Waiting for unfinished jobs" message above
586 when not necessary. */
588 if (dead_children > 0)
589 --dead_children;
591 any_remote = 0;
592 any_local = shell_function_pid != 0;
593 for (c = children; c != 0; c = c->next)
595 any_remote |= c->remote;
596 any_local |= ! c->remote;
597 DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
598 c, c->file->name, pid2str (c->pid),
599 c->remote ? _(" (remote)") : ""));
600 #ifdef VMS
601 break;
602 #endif
605 /* First, check for remote children. */
606 if (any_remote)
607 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
608 else
609 pid = 0;
611 if (pid > 0)
612 /* We got a remote child. */
613 remote = 1;
614 else if (pid < 0)
616 /* A remote status command failed miserably. Punt. */
617 remote_status_lose:
618 pfatal_with_name ("remote_status");
620 else
622 /* No remote children. Check for local children. */
623 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
624 if (any_local)
626 #ifdef VMS
627 vmsWaitForChildren (&status);
628 pid = c->pid;
629 #else
630 #ifdef WAIT_NOHANG
631 if (!block)
632 pid = WAIT_NOHANG (&status);
633 else
634 #endif
635 EINTRLOOP(pid, wait (&status));
636 #endif /* !VMS */
638 else
639 pid = 0;
641 if (pid < 0)
643 /* The wait*() failed miserably. Punt. */
644 pfatal_with_name ("wait");
646 else if (pid > 0)
648 /* We got a child exit; chop the status word up. */
649 exit_code = WEXITSTATUS (status);
650 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
651 coredump = WCOREDUMP (status);
653 /* If we have started jobs in this second, remove one. */
654 if (job_counter)
655 --job_counter;
657 else
659 /* No local children are dead. */
660 reap_more = 0;
662 if (!block || !any_remote)
663 break;
665 /* Now try a blocking wait for a remote child. */
666 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
667 if (pid < 0)
668 goto remote_status_lose;
669 else if (pid == 0)
670 /* No remote children either. Finally give up. */
671 break;
673 /* We got a remote child. */
674 remote = 1;
676 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
678 #ifdef __MSDOS__
679 /* Life is very different on MSDOS. */
680 pid = dos_pid - 1;
681 status = dos_status;
682 exit_code = WEXITSTATUS (status);
683 if (exit_code == 0xff)
684 exit_code = -1;
685 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
686 coredump = 0;
687 #endif /* __MSDOS__ */
688 #ifdef _AMIGA
689 /* Same on Amiga */
690 pid = amiga_pid - 1;
691 status = amiga_status;
692 exit_code = amiga_status;
693 exit_sig = 0;
694 coredump = 0;
695 #endif /* _AMIGA */
696 #ifdef WINDOWS32
698 HANDLE hPID;
699 int werr;
700 HANDLE hcTID, hcPID;
701 DWORD dwWaitStatus = 0;
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(block, &dwWaitStatus);
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 else if (dwWaitStatus == WAIT_FAILED)
749 /* The WaitForMultipleObjects() failed miserably. Punt. */
750 pfatal_with_name ("WaitForMultipleObjects");
752 else if (dwWaitStatus == WAIT_TIMEOUT)
754 /* No child processes are finished. Give up waiting. */
755 reap_more = 0;
756 break;
759 pid = (pid_t) hPID;
761 #endif /* WINDOWS32 */
764 /* Check if this is the child of the 'shell' function. */
765 if (!remote && pid == shell_function_pid)
767 /* It is. Leave an indicator for the 'shell' function. */
768 if (exit_sig == 0 && exit_code == 127)
769 shell_function_completed = -1;
770 else
771 shell_function_completed = 1;
772 break;
775 child_failed = exit_sig != 0 || exit_code != 0;
777 /* Search for a child matching the deceased one. */
778 lastc = 0;
779 for (c = children; c != 0; lastc = c, c = c->next)
780 if (c->remote == remote && c->pid == pid)
781 break;
783 if (c == 0)
784 /* An unknown child died.
785 Ignore it; it was inherited from our invoker. */
786 continue;
788 DB (DB_JOBS, (child_failed
789 ? _("Reaping losing child %p PID %s %s\n")
790 : _("Reaping winning child %p PID %s %s\n"),
791 c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
793 if (c->sh_batch_file) {
794 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
795 c->sh_batch_file));
797 /* just try and remove, don't care if this fails */
798 remove (c->sh_batch_file);
800 /* all done with memory */
801 free (c->sh_batch_file);
802 c->sh_batch_file = NULL;
805 /* If this child had the good stdin, say it is now free. */
806 if (c->good_stdin)
807 good_stdin_used = 0;
809 dontcare = c->dontcare;
811 if (child_failed && !c->noerror && !ignore_errors_flag)
813 /* The commands failed. Write an error message,
814 delete non-precious targets, and abort. */
815 static int delete_on_error = -1;
817 if (!dontcare)
818 child_error (c->file, exit_code, exit_sig, coredump, 0);
820 c->file->update_status = 2;
821 if (delete_on_error == -1)
823 struct file *f = lookup_file (".DELETE_ON_ERROR");
824 delete_on_error = f != 0 && f->is_target;
826 if (exit_sig != 0 || delete_on_error)
827 delete_child_targets (c);
829 else
831 if (child_failed)
833 /* The commands failed, but we don't care. */
834 child_error (c->file, exit_code, exit_sig, coredump, 1);
835 child_failed = 0;
838 /* If there are more commands to run, try to start them. */
839 if (job_next_command (c))
841 if (handling_fatal_signal)
843 /* Never start new commands while we are dying.
844 Since there are more commands that wanted to be run,
845 the target was not completely remade. So we treat
846 this as if a command had failed. */
847 c->file->update_status = 2;
849 else
851 /* Check again whether to start remotely.
852 Whether or not we want to changes over time.
853 Also, start_remote_job may need state set up
854 by start_remote_job_p. */
855 c->remote = start_remote_job_p (0);
856 start_job_command (c);
857 /* Fatal signals are left blocked in case we were
858 about to put that child on the chain. But it is
859 already there, so it is safe for a fatal signal to
860 arrive now; it will clean up this child's targets. */
861 unblock_sigs ();
862 if (c->file->command_state == cs_running)
863 /* We successfully started the new command.
864 Loop to reap more children. */
865 continue;
868 if (c->file->update_status != 0)
869 /* We failed to start the commands. */
870 delete_child_targets (c);
872 else
873 /* There are no more commands. We got through them all
874 without an unignored error. Now the target has been
875 successfully updated. */
876 c->file->update_status = 0;
879 /* When we get here, all the commands for C->file are finished
880 (or aborted) and C->file->update_status contains 0 or 2. But
881 C->file->command_state is still cs_running if all the commands
882 ran; notice_finish_file looks for cs_running to tell it that
883 it's interesting to check the file's modtime again now. */
885 if (! handling_fatal_signal)
886 /* Notice if the target of the commands has been changed.
887 This also propagates its values for command_state and
888 update_status to its also_make files. */
889 notice_finished_file (c->file);
891 DB (DB_JOBS, (_("Removing child %p PID %s%s from chain.\n"),
892 c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
894 /* Block fatal signals while frobnicating the list, so that
895 children and job_slots_used are always consistent. Otherwise
896 a fatal signal arriving after the child is off the chain and
897 before job_slots_used is decremented would believe a child was
898 live and call reap_children again. */
899 block_sigs ();
901 /* There is now another slot open. */
902 if (job_slots_used > 0)
903 --job_slots_used;
905 /* Remove the child from the chain and free it. */
906 if (lastc == 0)
907 children = c->next;
908 else
909 lastc->next = c->next;
911 free_child (c);
913 unblock_sigs ();
915 /* If the job failed, and the -k flag was not given, die,
916 unless we are already in the process of dying. */
917 if (!err && child_failed && !dontcare && !keep_going_flag &&
918 /* fatal_error_signal will die with the right signal. */
919 !handling_fatal_signal)
920 die (2);
922 /* Only block for one child. */
923 block = 0;
926 return;
929 /* Free the storage allocated for CHILD. */
931 static void
932 free_child (struct child *child)
934 if (!jobserver_tokens)
935 fatal (NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
936 child, child->file->name);
938 /* If we're using the jobserver and this child is not the only outstanding
939 job, put a token back into the pipe for it. */
941 #ifdef WINDOWS32
942 if (has_jobserver_semaphore() && jobserver_tokens > 1)
944 if (! release_jobserver_semaphore())
946 DWORD err = GetLastError();
947 fatal (NILF, _("release jobserver semaphore: (Error %ld: %s)"),
948 err, map_windows32_error_to_string(err));
951 DB (DB_JOBS, (_("Released token for child %p (%s).\n"), child, child->file->name));
953 #else
954 if (job_fds[1] >= 0 && jobserver_tokens > 1)
956 char token = '+';
957 int r;
959 /* Write a job token back to the pipe. */
961 EINTRLOOP (r, write (job_fds[1], &token, 1));
962 if (r != 1)
963 pfatal_with_name (_("write jobserver"));
965 DB (DB_JOBS, (_("Released token for child %p (%s).\n"),
966 child, child->file->name));
968 #endif
970 --jobserver_tokens;
972 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
973 return;
975 if (child->command_lines != 0)
977 register unsigned int i;
978 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
979 free (child->command_lines[i]);
980 free (child->command_lines);
983 if (child->environment != 0)
985 register char **ep = child->environment;
986 while (*ep != 0)
987 free (*ep++);
988 free (child->environment);
991 free (child);
994 #ifdef POSIX
995 extern sigset_t fatal_signal_set;
996 #endif
998 void
999 block_sigs (void)
1001 #ifdef POSIX
1002 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
1003 #else
1004 # ifdef HAVE_SIGSETMASK
1005 (void) sigblock (fatal_signal_mask);
1006 # endif
1007 #endif
1010 #ifdef POSIX
1011 void
1012 unblock_sigs (void)
1014 sigset_t empty;
1015 sigemptyset (&empty);
1016 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
1018 #endif
1020 #if defined(MAKE_JOBSERVER) && !defined(WINDOWS32)
1021 RETSIGTYPE
1022 job_noop (int sig UNUSED)
1025 /* Set the child handler action flags to FLAGS. */
1026 static void
1027 set_child_handler_action_flags (int set_handler, int set_alarm)
1029 struct sigaction sa;
1031 #ifdef __EMX__
1032 /* The child handler must be turned off here. */
1033 signal (SIGCHLD, SIG_DFL);
1034 #endif
1036 memset (&sa, '\0', sizeof sa);
1037 sa.sa_handler = child_handler;
1038 sa.sa_flags = set_handler ? 0 : SA_RESTART;
1039 #if defined SIGCHLD
1040 sigaction (SIGCHLD, &sa, NULL);
1041 #endif
1042 #if defined SIGCLD && SIGCLD != SIGCHLD
1043 sigaction (SIGCLD, &sa, NULL);
1044 #endif
1045 #if defined SIGALRM
1046 if (set_alarm)
1048 /* If we're about to enter the read(), set an alarm to wake up in a
1049 second so we can check if the load has dropped and we can start more
1050 work. On the way out, turn off the alarm and set SIG_DFL. */
1051 alarm (set_handler ? 1 : 0);
1052 sa.sa_handler = set_handler ? job_noop : SIG_DFL;
1053 sa.sa_flags = 0;
1054 sigaction (SIGALRM, &sa, NULL);
1056 #endif
1058 #endif
1061 /* Start a job to run the commands specified in CHILD.
1062 CHILD is updated to reflect the commands and ID of the child process.
1064 NOTE: On return fatal signals are blocked! The caller is responsible
1065 for calling 'unblock_sigs', once the new child is safely on the chain so
1066 it can be cleaned up in the event of a fatal signal. */
1068 static void
1069 start_job_command (struct child *child)
1071 #if !defined(_AMIGA) && !defined(WINDOWS32)
1072 static int bad_stdin = -1;
1073 #endif
1074 char *p;
1075 /* Must be volatile to silence bogus GCC warning about longjmp/vfork. */
1076 volatile int flags;
1077 #ifdef VMS
1078 char *argv;
1079 #else
1080 char **argv;
1081 #endif
1083 /* If we have a completely empty commandset, stop now. */
1084 if (!child->command_ptr)
1085 goto next_command;
1087 /* Combine the flags parsed for the line itself with
1088 the flags specified globally for this target. */
1089 flags = (child->file->command_flags
1090 | child->file->cmds->lines_flags[child->command_line - 1]);
1092 p = child->command_ptr;
1093 child->noerror = ((flags & COMMANDS_NOERROR) != 0);
1095 while (*p != '\0')
1097 if (*p == '@')
1098 flags |= COMMANDS_SILENT;
1099 else if (*p == '+')
1100 flags |= COMMANDS_RECURSE;
1101 else if (*p == '-')
1102 child->noerror = 1;
1103 else if (!isblank ((unsigned char)*p))
1104 break;
1105 ++p;
1108 /* Update the file's command flags with any new ones we found. We only
1109 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
1110 now marking more commands recursive than should be in the case of
1111 multiline define/endef scripts where only one line is marked "+". In
1112 order to really fix this, we'll have to keep a lines_flags for every
1113 actual line, after expansion. */
1114 child->file->cmds->lines_flags[child->command_line - 1]
1115 |= flags & COMMANDS_RECURSE;
1117 /* POSIX requires that a recipe prefix after a backslash-newline should
1118 be ignored. Remove it now so the output is correct. */
1120 char prefix = child->file->cmds->recipe_prefix;
1121 char *p1, *p2;
1122 p1 = p2 = p;
1123 while (*p1 != '\0')
1125 *(p2++) = *p1;
1126 if (p1[0] == '\n' && p1[1] == prefix)
1127 ++p1;
1128 ++p1;
1130 *p2 = *p1;
1133 /* Figure out an argument list from this command line. */
1135 char *end = 0;
1136 #ifdef VMS
1137 argv = p;
1138 #else
1139 argv = construct_command_argv (p, &end, child->file,
1140 child->file->cmds->lines_flags[child->command_line - 1],
1141 &child->sh_batch_file);
1142 #endif
1143 if (end == NULL)
1144 child->command_ptr = NULL;
1145 else
1147 *end++ = '\0';
1148 child->command_ptr = end;
1152 /* If -q was given, say that updating 'failed' if there was any text on the
1153 command line, or 'succeeded' otherwise. The exit status of 1 tells the
1154 user that -q is saying 'something to do'; the exit status for a random
1155 error is 2. */
1156 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
1158 #ifndef VMS
1159 free (argv[0]);
1160 free (argv);
1161 #endif
1162 child->file->update_status = 1;
1163 notice_finished_file (child->file);
1164 return;
1167 if (touch_flag && !(flags & COMMANDS_RECURSE))
1169 /* Go on to the next command. It might be the recursive one.
1170 We construct ARGV only to find the end of the command line. */
1171 #ifndef VMS
1172 if (argv)
1174 free (argv[0]);
1175 free (argv);
1177 #endif
1178 argv = 0;
1181 if (argv == 0)
1183 next_command:
1184 #ifdef __MSDOS__
1185 execute_by_shell = 0; /* in case construct_command_argv sets it */
1186 #endif
1187 /* This line has no commands. Go to the next. */
1188 if (job_next_command (child))
1189 start_job_command (child);
1190 else
1192 /* No more commands. Make sure we're "running"; we might not be if
1193 (e.g.) all commands were skipped due to -n. */
1194 set_command_state (child->file, cs_running);
1195 child->file->update_status = 0;
1196 notice_finished_file (child->file);
1198 return;
1201 /* Print out the command. If silent, we call 'message' with null so it
1202 can log the working directory before the command's own error messages
1203 appear. */
1205 message (0, (just_print_flag || trace_flag
1206 || (!(flags & COMMANDS_SILENT) && !silent_flag))
1207 ? "%s" : (char *) 0, p);
1209 /* Tell update_goal_chain that a command has been started on behalf of
1210 this target. It is important that this happens here and not in
1211 reap_children (where we used to do it), because reap_children might be
1212 reaping children from a different target. We want this increment to
1213 guaranteedly indicate that a command was started for the dependency
1214 chain (i.e., update_file recursion chain) we are processing. */
1216 ++commands_started;
1218 /* Optimize an empty command. People use this for timestamp rules,
1219 so avoid forking a useless shell. Do this after we increment
1220 commands_started so make still treats this special case as if it
1221 performed some action (makes a difference as to what messages are
1222 printed, etc. */
1224 #if !defined(VMS) && !defined(_AMIGA)
1225 if (
1226 #if defined __MSDOS__ || defined (__EMX__)
1227 unixy_shell /* the test is complicated and we already did it */
1228 #else
1229 (argv[0] && is_bourne_compatible_shell(argv[0]))
1230 #endif
1231 && (argv[1] && argv[1][0] == '-'
1233 ((argv[1][1] == 'c' && argv[1][2] == '\0')
1235 (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
1236 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1237 && argv[3] == NULL)
1239 free (argv[0]);
1240 free (argv);
1241 goto next_command;
1243 #endif /* !VMS && !_AMIGA */
1245 /* If -n was given, recurse to get the next line in the sequence. */
1247 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1249 #ifndef VMS
1250 free (argv[0]);
1251 free (argv);
1252 #endif
1253 goto next_command;
1256 /* Flush the output streams so they won't have things written twice. */
1258 fflush (stdout);
1259 fflush (stderr);
1261 #ifndef VMS
1262 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1264 /* Set up a bad standard input that reads from a broken pipe. */
1266 if (bad_stdin == -1)
1268 /* Make a file descriptor that is the read end of a broken pipe.
1269 This will be used for some children's standard inputs. */
1270 int pd[2];
1271 if (pipe (pd) == 0)
1273 /* Close the write side. */
1274 (void) close (pd[1]);
1275 /* Save the read side. */
1276 bad_stdin = pd[0];
1278 /* Set the descriptor to close on exec, so it does not litter any
1279 child's descriptor table. When it is dup2'd onto descriptor 0,
1280 that descriptor will not close on exec. */
1281 CLOSE_ON_EXEC (bad_stdin);
1285 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1287 /* Decide whether to give this child the 'good' standard input
1288 (one that points to the terminal or whatever), or the 'bad' one
1289 that points to the read side of a broken pipe. */
1291 child->good_stdin = !good_stdin_used;
1292 if (child->good_stdin)
1293 good_stdin_used = 1;
1295 #endif /* !VMS */
1297 child->deleted = 0;
1299 #ifndef _AMIGA
1300 /* Set up the environment for the child. */
1301 if (child->environment == 0)
1302 child->environment = target_environment (child->file);
1303 #endif
1305 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1307 #ifndef VMS
1308 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1309 if (child->remote)
1311 int is_remote, id, used_stdin;
1312 if (start_remote_job (argv, child->environment,
1313 child->good_stdin ? 0 : bad_stdin,
1314 &is_remote, &id, &used_stdin))
1315 /* Don't give up; remote execution may fail for various reasons. If
1316 so, simply run the job locally. */
1317 goto run_local;
1318 else
1320 if (child->good_stdin && !used_stdin)
1322 child->good_stdin = 0;
1323 good_stdin_used = 0;
1325 child->remote = is_remote;
1326 child->pid = id;
1329 else
1330 #endif /* !VMS */
1332 /* Fork the child process. */
1334 char **parent_environ;
1336 run_local:
1337 block_sigs ();
1339 child->remote = 0;
1341 #ifdef VMS
1342 if (!child_execute_job (argv, child)) {
1343 /* Fork failed! */
1344 perror_with_name ("vfork", "");
1345 goto error;
1348 #else
1350 parent_environ = environ;
1352 # ifdef __EMX__
1353 /* If we aren't running a recursive command and we have a jobserver
1354 pipe, close it before exec'ing. */
1355 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1357 CLOSE_ON_EXEC (job_fds[0]);
1358 CLOSE_ON_EXEC (job_fds[1]);
1360 if (job_rfd >= 0)
1361 CLOSE_ON_EXEC (job_rfd);
1363 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1364 child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1365 argv, child->environment);
1366 if (child->pid < 0)
1368 /* spawn failed! */
1369 unblock_sigs ();
1370 perror_with_name ("spawn", "");
1371 goto error;
1374 /* undo CLOSE_ON_EXEC() after the child process has been started */
1375 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1377 fcntl (job_fds[0], F_SETFD, 0);
1378 fcntl (job_fds[1], F_SETFD, 0);
1380 if (job_rfd >= 0)
1381 fcntl (job_rfd, F_SETFD, 0);
1383 #else /* !__EMX__ */
1385 child->pid = vfork ();
1386 environ = parent_environ; /* Restore value child may have clobbered. */
1387 if (child->pid == 0)
1389 /* We are the child side. */
1390 unblock_sigs ();
1392 /* If we aren't running a recursive command and we have a jobserver
1393 pipe, close it before exec'ing. */
1394 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1396 close (job_fds[0]);
1397 close (job_fds[1]);
1399 if (job_rfd >= 0)
1400 close (job_rfd);
1402 #ifdef SET_STACK_SIZE
1403 /* Reset limits, if necessary. */
1404 if (stack_limit.rlim_cur)
1405 setrlimit (RLIMIT_STACK, &stack_limit);
1406 #endif
1408 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1409 argv, child->environment);
1411 else if (child->pid < 0)
1413 /* Fork failed! */
1414 unblock_sigs ();
1415 perror_with_name ("vfork", "");
1416 goto error;
1418 # endif /* !__EMX__ */
1419 #endif /* !VMS */
1422 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1423 #ifdef __MSDOS__
1425 int proc_return;
1427 block_sigs ();
1428 dos_status = 0;
1430 /* We call 'system' to do the job of the SHELL, since stock DOS
1431 shell is too dumb. Our 'system' knows how to handle long
1432 command lines even if pipes/redirection is needed; it will only
1433 call COMMAND.COM when its internal commands are used. */
1434 if (execute_by_shell)
1436 char *cmdline = argv[0];
1437 /* We don't have a way to pass environment to 'system',
1438 so we need to save and restore ours, sigh... */
1439 char **parent_environ = environ;
1441 environ = child->environment;
1443 /* If we have a *real* shell, tell 'system' to call
1444 it to do everything for us. */
1445 if (unixy_shell)
1447 /* A *real* shell on MSDOS may not support long
1448 command lines the DJGPP way, so we must use 'system'. */
1449 cmdline = argv[2]; /* get past "shell -c" */
1452 dos_command_running = 1;
1453 proc_return = system (cmdline);
1454 environ = parent_environ;
1455 execute_by_shell = 0; /* for the next time */
1457 else
1459 dos_command_running = 1;
1460 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1463 /* Need to unblock signals before turning off
1464 dos_command_running, so that child's signals
1465 will be treated as such (see fatal_error_signal). */
1466 unblock_sigs ();
1467 dos_command_running = 0;
1469 /* If the child got a signal, dos_status has its
1470 high 8 bits set, so be careful not to alter them. */
1471 if (proc_return == -1)
1472 dos_status |= 0xff;
1473 else
1474 dos_status |= (proc_return & 0xff);
1475 ++dead_children;
1476 child->pid = dos_pid++;
1478 #endif /* __MSDOS__ */
1479 #ifdef _AMIGA
1480 amiga_status = MyExecute (argv);
1482 ++dead_children;
1483 child->pid = amiga_pid++;
1484 if (amiga_batch_file)
1486 amiga_batch_file = 0;
1487 DeleteFile (amiga_bname); /* Ignore errors. */
1489 #endif /* Amiga */
1490 #ifdef WINDOWS32
1492 HANDLE hPID;
1493 char* arg0;
1495 /* make UNC paths safe for CreateProcess -- backslash format */
1496 arg0 = argv[0];
1497 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1498 for ( ; arg0 && *arg0; arg0++)
1499 if (*arg0 == '/')
1500 *arg0 = '\\';
1502 /* make sure CreateProcess() has Path it needs */
1503 sync_Path_environment();
1505 hPID = process_easy(argv, child->environment);
1507 if (hPID != INVALID_HANDLE_VALUE)
1508 child->pid = (pid_t) hPID;
1509 else {
1510 int i;
1511 unblock_sigs();
1512 fprintf(stderr,
1513 _("process_easy() failed to launch process (e=%ld)\n"),
1514 process_last_err(hPID));
1515 for (i = 0; argv[i]; i++)
1516 fprintf(stderr, "%s ", argv[i]);
1517 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1518 goto error;
1521 #endif /* WINDOWS32 */
1522 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1524 /* Bump the number of jobs started in this second. */
1525 ++job_counter;
1527 /* We are the parent side. Set the state to
1528 say the commands are running and return. */
1530 set_command_state (child->file, cs_running);
1532 /* Free the storage used by the child's argument list. */
1533 #ifndef VMS
1534 free (argv[0]);
1535 free (argv);
1536 #endif
1538 return;
1540 error:
1541 child->file->update_status = 2;
1542 notice_finished_file (child->file);
1543 return;
1546 /* Try to start a child running.
1547 Returns nonzero if the child was started (and maybe finished), or zero if
1548 the load was too high and the child was put on the 'waiting_jobs' chain. */
1550 static int
1551 start_waiting_job (struct child *c)
1553 struct file *f = c->file;
1555 /* If we can start a job remotely, we always want to, and don't care about
1556 the local load average. We record that the job should be started
1557 remotely in C->remote for start_job_command to test. */
1559 c->remote = start_remote_job_p (1);
1561 /* If we are running at least one job already and the load average
1562 is too high, make this one wait. */
1563 if (!c->remote
1564 && ((job_slots_used > 0 && load_too_high ())
1565 #ifdef WINDOWS32
1566 || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
1567 #endif
1570 /* Put this child on the chain of children waiting for the load average
1571 to go down. */
1572 set_command_state (f, cs_running);
1573 c->next = waiting_jobs;
1574 waiting_jobs = c;
1575 return 0;
1578 /* Start the first command; reap_children will run later command lines. */
1579 start_job_command (c);
1581 switch (f->command_state)
1583 case cs_running:
1584 c->next = children;
1585 DB (DB_JOBS, (_("Putting child %p (%s) PID %s%s on the chain.\n"),
1586 c, c->file->name, pid2str (c->pid),
1587 c->remote ? _(" (remote)") : ""));
1588 children = c;
1589 /* One more job slot is in use. */
1590 ++job_slots_used;
1591 unblock_sigs ();
1592 break;
1594 case cs_not_started:
1595 /* All the command lines turned out to be empty. */
1596 f->update_status = 0;
1597 /* FALLTHROUGH */
1599 case cs_finished:
1600 notice_finished_file (f);
1601 free_child (c);
1602 break;
1604 default:
1605 assert (f->command_state == cs_finished);
1606 break;
1609 return 1;
1612 /* Create a 'struct child' for FILE and start its commands running. */
1614 void
1615 new_job (struct file *file)
1617 struct commands *cmds = file->cmds;
1618 struct child *c;
1619 char **lines;
1620 unsigned int i;
1622 /* Let any previously decided-upon jobs that are waiting
1623 for the load to go down start before this new one. */
1624 start_waiting_jobs ();
1626 /* Reap any children that might have finished recently. */
1627 reap_children (0, 0);
1629 /* Chop the commands up into lines if they aren't already. */
1630 chop_commands (cmds);
1632 /* Expand the command lines and store the results in LINES. */
1633 lines = xmalloc (cmds->ncommand_lines * sizeof (char *));
1634 for (i = 0; i < cmds->ncommand_lines; ++i)
1636 /* Collapse backslash-newline combinations that are inside variable
1637 or function references. These are left alone by the parser so
1638 that they will appear in the echoing of commands (where they look
1639 nice); and collapsed by construct_command_argv when it tokenizes.
1640 But letting them survive inside function invocations loses because
1641 we don't want the functions to see them as part of the text. */
1643 char *in, *out, *ref;
1645 /* IN points to where in the line we are scanning.
1646 OUT points to where in the line we are writing.
1647 When we collapse a backslash-newline combination,
1648 IN gets ahead of OUT. */
1650 in = out = cmds->command_lines[i];
1651 while ((ref = strchr (in, '$')) != 0)
1653 ++ref; /* Move past the $. */
1655 if (out != in)
1656 /* Copy the text between the end of the last chunk
1657 we processed (where IN points) and the new chunk
1658 we are about to process (where REF points). */
1659 memmove (out, in, ref - in);
1661 /* Move both pointers past the boring stuff. */
1662 out += ref - in;
1663 in = ref;
1665 if (*ref == '(' || *ref == '{')
1667 char openparen = *ref;
1668 char closeparen = openparen == '(' ? ')' : '}';
1669 int count;
1670 char *p;
1672 *out++ = *in++; /* Copy OPENPAREN. */
1673 /* IN now points past the opening paren or brace.
1674 Count parens or braces until it is matched. */
1675 count = 0;
1676 while (*in != '\0')
1678 if (*in == closeparen && --count < 0)
1679 break;
1680 else if (*in == '\\' && in[1] == '\n')
1682 /* We have found a backslash-newline inside a
1683 variable or function reference. Eat it and
1684 any following whitespace. */
1686 int quoted = 0;
1687 for (p = in - 1; p > ref && *p == '\\'; --p)
1688 quoted = !quoted;
1690 if (quoted)
1691 /* There were two or more backslashes, so this is
1692 not really a continuation line. We don't collapse
1693 the quoting backslashes here as is done in
1694 collapse_continuations, because the line will
1695 be collapsed again after expansion. */
1696 *out++ = *in++;
1697 else
1699 /* Skip the backslash, newline and
1700 any following whitespace. */
1701 in = next_token (in + 2);
1703 /* Discard any preceding whitespace that has
1704 already been written to the output. */
1705 while (out > ref
1706 && isblank ((unsigned char)out[-1]))
1707 --out;
1709 /* Replace it all with a single space. */
1710 *out++ = ' ';
1713 else
1715 if (*in == openparen)
1716 ++count;
1718 *out++ = *in++;
1724 /* There are no more references in this line to worry about.
1725 Copy the remaining uninteresting text to the output. */
1726 if (out != in)
1727 memmove (out, in, strlen (in) + 1);
1729 /* Finally, expand the line. */
1730 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1731 file);
1734 /* Start the command sequence, record it in a new
1735 'struct child', and add that to the chain. */
1737 c = xcalloc (sizeof (struct child));
1738 c->file = file;
1739 c->command_lines = lines;
1740 c->sh_batch_file = NULL;
1742 /* Cache dontcare flag because file->dontcare can be changed once we
1743 return. Check dontcare inheritance mechanism for details. */
1744 c->dontcare = file->dontcare;
1746 /* Fetch the first command line to be run. */
1747 job_next_command (c);
1749 /* Wait for a job slot to be freed up. If we allow an infinite number
1750 don't bother; also job_slots will == 0 if we're using the jobserver. */
1752 if (job_slots != 0)
1753 while (job_slots_used == job_slots)
1754 reap_children (1, 0);
1756 #ifdef MAKE_JOBSERVER
1757 /* If we are controlling multiple jobs make sure we have a token before
1758 starting the child. */
1760 /* This can be inefficient. There's a decent chance that this job won't
1761 actually have to run any subprocesses: the command script may be empty
1762 or otherwise optimized away. It would be nice if we could defer
1763 obtaining a token until just before we need it, in start_job_command.
1764 To do that we'd need to keep track of whether we'd already obtained a
1765 token (since start_job_command is called for each line of the job, not
1766 just once). Also more thought needs to go into the entire algorithm;
1767 this is where the old parallel job code waits, so... */
1769 #ifdef WINDOWS32
1770 else if (has_jobserver_semaphore())
1771 #else
1772 else if (job_fds[0] >= 0)
1773 #endif
1774 while (1)
1776 int got_token;
1777 #ifndef WINDOWS32
1778 char token;
1779 int saved_errno;
1780 #endif
1782 DB (DB_JOBS, ("Need a job token; we %shave children\n",
1783 children ? "" : "don't "));
1785 /* If we don't already have a job started, use our "free" token. */
1786 if (!jobserver_tokens)
1787 break;
1789 #ifndef WINDOWS32
1790 /* Read a token. As long as there's no token available we'll block.
1791 We enable interruptible system calls before the read(2) so that if
1792 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1793 we can process the death(s) and return tokens to the free pool.
1795 Once we return from the read, we immediately reinstate restartable
1796 system calls. This allows us to not worry about checking for
1797 EINTR on all the other system calls in the program.
1799 There is one other twist: there is a span between the time
1800 reap_children() does its last check for dead children and the time
1801 the read(2) call is entered, below, where if a child dies we won't
1802 notice. This is extremely serious as it could cause us to
1803 deadlock, given the right set of events.
1805 To avoid this, we do the following: before we reap_children(), we
1806 dup(2) the read FD on the jobserver pipe. The read(2) call below
1807 uses that new FD. In the signal handler, we close that FD. That
1808 way, if a child dies during the section mentioned above, the
1809 read(2) will be invoked with an invalid FD and will return
1810 immediately with EBADF. */
1812 /* Make sure we have a dup'd FD. */
1813 if (job_rfd < 0)
1815 DB (DB_JOBS, ("Duplicate the job FD\n"));
1816 job_rfd = dup (job_fds[0]);
1818 #endif
1820 /* Reap anything that's currently waiting. */
1821 reap_children (0, 0);
1823 /* Kick off any jobs we have waiting for an opportunity that
1824 can run now (ie waiting for load). */
1825 start_waiting_jobs ();
1827 /* If our "free" slot has become available, use it; we don't need an
1828 actual token. */
1829 if (!jobserver_tokens)
1830 break;
1832 /* There must be at least one child already, or we have no business
1833 waiting for a token. */
1834 if (!children)
1835 fatal (NILF, "INTERNAL: no children as we go to sleep on read\n");
1837 #ifdef WINDOWS32
1838 /* On Windows we simply wait for the jobserver semaphore to become
1839 * signalled or one of our child processes to terminate.
1841 got_token = wait_for_semaphore_or_child_process();
1842 if (got_token < 0)
1844 DWORD err = GetLastError();
1845 fatal (NILF, _("semaphore or child process wait: (Error %ld: %s)"),
1846 err, map_windows32_error_to_string(err));
1848 #else
1849 /* Set interruptible system calls, and read() for a job token. */
1850 set_child_handler_action_flags (1, waiting_jobs != NULL);
1851 got_token = read (job_rfd, &token, 1);
1852 saved_errno = errno;
1853 set_child_handler_action_flags (0, waiting_jobs != NULL);
1854 #endif
1856 /* If we got one, we're done here. */
1857 if (got_token == 1)
1859 DB (DB_JOBS, (_("Obtained token for child %p (%s).\n"),
1860 c, c->file->name));
1861 break;
1864 #ifndef WINDOWS32
1865 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1866 go back and reap_children(), and try again. */
1867 errno = saved_errno;
1868 if (errno != EINTR && errno != EBADF)
1869 pfatal_with_name (_("read jobs pipe"));
1870 if (errno == EBADF)
1871 DB (DB_JOBS, ("Read returned EBADF.\n"));
1872 #endif
1874 #endif
1876 ++jobserver_tokens;
1878 /* Trace the build.
1879 Use message here so that changes to working directories are logged. */
1880 if (trace_flag)
1882 char *newer = allocated_variable_expand_for_file ("$?", c->file);
1883 char *nm;
1885 if (! cmds->fileinfo.filenm)
1886 nm = _("<builtin>");
1887 else
1889 nm = alloca (strlen (cmds->fileinfo.filenm) + 1 + 11 + 1);
1890 sprintf (nm, "%s:%lu", cmds->fileinfo.filenm, cmds->fileinfo.lineno);
1893 if (newer[0] == '\0')
1894 message (0, _("%s: target '%s' does not exist"), nm, c->file->name);
1895 else
1896 message (0, _("%s: update target '%s' due to: %s"), nm,
1897 c->file->name, newer);
1899 free (newer);
1903 /* The job is now primed. Start it running.
1904 (This will notice if there is in fact no recipe.) */
1905 start_waiting_job (c);
1907 if (job_slots == 1 || not_parallel)
1908 /* Since there is only one job slot, make things run linearly.
1909 Wait for the child to die, setting the state to 'cs_finished'. */
1910 while (file->command_state == cs_running)
1911 reap_children (1, 0);
1913 return;
1916 /* Move CHILD's pointers to the next command for it to execute.
1917 Returns nonzero if there is another command. */
1919 static int
1920 job_next_command (struct child *child)
1922 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1924 /* There are no more lines in the expansion of this line. */
1925 if (child->command_line == child->file->cmds->ncommand_lines)
1927 /* There are no more lines to be expanded. */
1928 child->command_ptr = 0;
1929 return 0;
1931 else
1932 /* Get the next line to run. */
1933 child->command_ptr = child->command_lines[child->command_line++];
1935 return 1;
1938 /* Determine if the load average on the system is too high to start a new job.
1939 The real system load average is only recomputed once a second. However, a
1940 very parallel make can easily start tens or even hundreds of jobs in a
1941 second, which brings the system to its knees for a while until that first
1942 batch of jobs clears out.
1944 To avoid this we use a weighted algorithm to try to account for jobs which
1945 have been started since the last second, and guess what the load average
1946 would be now if it were computed.
1948 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1949 who writes:
1951 ! calculate something load-oid and add to the observed sys.load,
1952 ! so that latter can catch up:
1953 ! - every job started increases jobctr;
1954 ! - every dying job decreases a positive jobctr;
1955 ! - the jobctr value gets zeroed every change of seconds,
1956 ! after its value*weight_b is stored into the 'backlog' value last_sec
1957 ! - weight_a times the sum of jobctr and last_sec gets
1958 ! added to the observed sys.load.
1960 ! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1961 ! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1962 ! sub-shelled commands (rm, echo, sed...) for tests.
1963 ! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1964 ! resulted in significant excession of the load limit, raising it
1965 ! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1966 ! reach the limit in most test cases.
1968 ! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1969 ! exceeding the limit for longer-running stuff (compile jobs in
1970 ! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1971 ! small jobs' effects.
1975 #define LOAD_WEIGHT_A 0.25
1976 #define LOAD_WEIGHT_B 0.25
1978 static int
1979 load_too_high (void)
1981 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
1982 return 1;
1983 #else
1984 static double last_sec;
1985 static time_t last_now;
1986 double load, guess;
1987 time_t now;
1989 #ifdef WINDOWS32
1990 /* sub_proc.c cannot wait for more than MAXIMUM_WAIT_OBJECTS children */
1991 if (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
1992 return 1;
1993 #endif
1995 if (max_load_average < 0)
1996 return 0;
1998 /* Find the real system load average. */
1999 make_access ();
2000 if (getloadavg (&load, 1) != 1)
2002 static int lossage = -1;
2003 /* Complain only once for the same error. */
2004 if (lossage == -1 || errno != lossage)
2006 if (errno == 0)
2007 /* An errno value of zero means getloadavg is just unsupported. */
2008 error (NILF,
2009 _("cannot enforce load limits on this operating system"));
2010 else
2011 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
2013 lossage = errno;
2014 load = 0;
2016 user_access ();
2018 /* If we're in a new second zero the counter and correct the backlog
2019 value. Only keep the backlog for one extra second; after that it's 0. */
2020 now = time (NULL);
2021 if (last_now < now)
2023 if (last_now == now - 1)
2024 last_sec = LOAD_WEIGHT_B * job_counter;
2025 else
2026 last_sec = 0.0;
2028 job_counter = 0;
2029 last_now = now;
2032 /* Try to guess what the load would be right now. */
2033 guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
2035 DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
2036 guess, load, max_load_average));
2038 return guess >= max_load_average;
2039 #endif
2042 /* Start jobs that are waiting for the load to be lower. */
2044 void
2045 start_waiting_jobs (void)
2047 struct child *job;
2049 if (waiting_jobs == 0)
2050 return;
2054 /* Check for recently deceased descendants. */
2055 reap_children (0, 0);
2057 /* Take a job off the waiting list. */
2058 job = waiting_jobs;
2059 waiting_jobs = job->next;
2061 /* Try to start that job. We break out of the loop as soon
2062 as start_waiting_job puts one back on the waiting list. */
2064 while (start_waiting_job (job) && waiting_jobs != 0);
2066 return;
2069 #ifndef WINDOWS32
2071 /* EMX: Start a child process. This function returns the new pid. */
2072 # if defined __EMX__
2074 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2076 int pid;
2077 /* stdin_fd == 0 means: nothing to do for stdin;
2078 stdout_fd == 1 means: nothing to do for stdout */
2079 int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
2080 int save_stdout = (stdout_fd != 1) ? dup (1): 1;
2082 /* < 0 only if dup() failed */
2083 if (save_stdin < 0)
2084 fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
2085 if (save_stdout < 0)
2086 fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
2088 /* Close unnecessary file handles for the child. */
2089 if (save_stdin != 0)
2090 CLOSE_ON_EXEC (save_stdin);
2091 if (save_stdout != 1)
2092 CLOSE_ON_EXEC (save_stdout);
2094 /* Connect the pipes to the child process. */
2095 if (stdin_fd != 0)
2096 (void) dup2 (stdin_fd, 0);
2097 if (stdout_fd != 1)
2098 (void) dup2 (stdout_fd, 1);
2100 /* stdin_fd and stdout_fd must be closed on exit because we are
2101 still in the parent process */
2102 if (stdin_fd != 0)
2103 CLOSE_ON_EXEC (stdin_fd);
2104 if (stdout_fd != 1)
2105 CLOSE_ON_EXEC (stdout_fd);
2107 /* Run the command. */
2108 pid = exec_command (argv, envp);
2110 /* Restore stdout/stdin of the parent and close temporary FDs. */
2111 if (stdin_fd != 0)
2113 if (dup2 (save_stdin, 0) != 0)
2114 fatal (NILF, _("Could not restore stdin\n"));
2115 else
2116 close (save_stdin);
2119 if (stdout_fd != 1)
2121 if (dup2 (save_stdout, 1) != 1)
2122 fatal (NILF, _("Could not restore stdout\n"));
2123 else
2124 close (save_stdout);
2127 return pid;
2130 #elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
2132 /* UNIX:
2133 Replace the current process with one executing the command in ARGV.
2134 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2135 the environment of the new program. This function does not return. */
2136 void
2137 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2139 if (stdin_fd != 0)
2140 (void) dup2 (stdin_fd, 0);
2141 if (stdout_fd != 1)
2142 (void) dup2 (stdout_fd, 1);
2143 if (stdin_fd != 0)
2144 (void) close (stdin_fd);
2145 if (stdout_fd != 1)
2146 (void) close (stdout_fd);
2148 /* Run the command. */
2149 exec_command (argv, envp);
2151 #endif /* !AMIGA && !__MSDOS__ && !VMS */
2152 #endif /* !WINDOWS32 */
2154 #ifndef _AMIGA
2155 /* Replace the current process with one running the command in ARGV,
2156 with environment ENVP. This function does not return. */
2158 /* EMX: This function returns the pid of the child process. */
2159 # ifdef __EMX__
2161 # else
2162 void
2163 # endif
2164 exec_command (char **argv, char **envp)
2166 #ifdef VMS
2167 /* to work around a problem with signals and execve: ignore them */
2168 #ifdef SIGCHLD
2169 signal (SIGCHLD,SIG_IGN);
2170 #endif
2171 /* Run the program. */
2172 execve (argv[0], argv, envp);
2173 perror_with_name ("execve: ", argv[0]);
2174 _exit (EXIT_FAILURE);
2175 #else
2176 #ifdef WINDOWS32
2177 HANDLE hPID;
2178 HANDLE hWaitPID;
2179 int err = 0;
2180 int exit_code = EXIT_FAILURE;
2182 /* make sure CreateProcess() has Path it needs */
2183 sync_Path_environment();
2185 /* launch command */
2186 hPID = process_easy(argv, envp);
2188 /* make sure launch ok */
2189 if (hPID == INVALID_HANDLE_VALUE)
2191 int i;
2192 fprintf(stderr,
2193 _("process_easy() failed to launch process (e=%ld)\n"),
2194 process_last_err(hPID));
2195 for (i = 0; argv[i]; i++)
2196 fprintf(stderr, "%s ", argv[i]);
2197 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2198 exit(EXIT_FAILURE);
2201 /* wait and reap last child */
2202 hWaitPID = process_wait_for_any(1, 0);
2203 while (hWaitPID)
2205 /* was an error found on this process? */
2206 err = process_last_err(hWaitPID);
2208 /* get exit data */
2209 exit_code = process_exit_code(hWaitPID);
2211 if (err)
2212 fprintf(stderr, "make (e=%d, rc=%d): %s",
2213 err, exit_code, map_windows32_error_to_string(err));
2215 /* cleanup process */
2216 process_cleanup(hWaitPID);
2218 /* expect to find only last pid, warn about other pids reaped */
2219 if (hWaitPID == hPID)
2220 break;
2221 else
2223 char *pidstr = xstrdup (pid2str ((pid_t)hWaitPID));
2225 fprintf(stderr,
2226 _("make reaped child pid %s, still waiting for pid %s\n"),
2227 pidstr, pid2str ((pid_t)hPID));
2228 free (pidstr);
2232 /* return child's exit code as our exit code */
2233 exit(exit_code);
2235 #else /* !WINDOWS32 */
2237 # ifdef __EMX__
2238 int pid;
2239 # endif
2241 /* Be the user, permanently. */
2242 child_access ();
2244 # ifdef __EMX__
2246 /* Run the program. */
2247 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2249 if (pid >= 0)
2250 return pid;
2252 /* the file might have a strange shell extension */
2253 if (errno == ENOENT)
2254 errno = ENOEXEC;
2256 # else
2258 /* Run the program. */
2259 environ = envp;
2260 execvp (argv[0], argv);
2262 # endif /* !__EMX__ */
2264 switch (errno)
2266 case ENOENT:
2267 error (NILF, _("%s: Command not found"), argv[0]);
2268 break;
2269 case ENOEXEC:
2271 /* The file is not executable. Try it as a shell script. */
2272 extern char *getenv ();
2273 char *shell;
2274 char **new_argv;
2275 int argc;
2276 int i=1;
2278 # ifdef __EMX__
2279 /* Do not use $SHELL from the environment */
2280 struct variable *p = lookup_variable ("SHELL", 5);
2281 if (p)
2282 shell = p->value;
2283 else
2284 shell = 0;
2285 # else
2286 shell = getenv ("SHELL");
2287 # endif
2288 if (shell == 0)
2289 shell = default_shell;
2291 argc = 1;
2292 while (argv[argc] != 0)
2293 ++argc;
2295 # ifdef __EMX__
2296 if (!unixy_shell)
2297 ++argc;
2298 # endif
2300 new_argv = alloca ((1 + argc + 1) * sizeof (char *));
2301 new_argv[0] = shell;
2303 # ifdef __EMX__
2304 if (!unixy_shell)
2306 new_argv[1] = "/c";
2307 ++i;
2308 --argc;
2310 # endif
2312 new_argv[i] = argv[0];
2313 while (argc > 0)
2315 new_argv[i + argc] = argv[argc];
2316 --argc;
2319 # ifdef __EMX__
2320 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2321 if (pid >= 0)
2322 break;
2323 # else
2324 execvp (shell, new_argv);
2325 # endif
2326 if (errno == ENOENT)
2327 error (NILF, _("%s: Shell program not found"), shell);
2328 else
2329 perror_with_name ("execvp: ", shell);
2330 break;
2333 # ifdef __EMX__
2334 case EINVAL:
2335 /* this nasty error was driving me nuts :-( */
2336 error (NILF, _("spawnvpe: environment space might be exhausted"));
2337 /* FALLTHROUGH */
2338 # endif
2340 default:
2341 perror_with_name ("execvp: ", argv[0]);
2342 break;
2345 # ifdef __EMX__
2346 return pid;
2347 # else
2348 _exit (127);
2349 # endif
2350 #endif /* !WINDOWS32 */
2351 #endif /* !VMS */
2353 #else /* On Amiga */
2354 void exec_command (char **argv)
2356 MyExecute (argv);
2359 void clean_tmp (void)
2361 DeleteFile (amiga_bname);
2364 #endif /* On Amiga */
2366 #ifndef VMS
2367 /* Figure out the argument list necessary to run LINE as a command. Try to
2368 avoid using a shell. This routine handles only ' quoting, and " quoting
2369 when no backslash, $ or ' characters are seen in the quotes. Starting
2370 quotes may be escaped with a backslash. If any of the characters in
2371 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2372 is the first word of a line, the shell is used.
2374 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2375 If *RESTP is NULL, newlines will be ignored.
2377 SHELL is the shell to use, or nil to use the default shell.
2378 IFS is the value of $IFS, or nil (meaning the default).
2380 FLAGS is the value of lines_flags for this command line. It is
2381 used in the WINDOWS32 port to check whether + or $(MAKE) were found
2382 in this command line, in which case the effect of just_print_flag
2383 is overridden. */
2385 static char **
2386 construct_command_argv_internal (char *line, char **restp, char *shell,
2387 char *shellflags, char *ifs, int flags,
2388 char **batch_filename UNUSED)
2390 #ifdef __MSDOS__
2391 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2392 We call 'system' for anything that requires ''slow'' processing,
2393 because DOS shells are too dumb. When $SHELL points to a real
2394 (unix-style) shell, 'system' just calls it to do everything. When
2395 $SHELL points to a DOS shell, 'system' does most of the work
2396 internally, calling the shell only for its internal commands.
2397 However, it looks on the $PATH first, so you can e.g. have an
2398 external command named 'mkdir'.
2400 Since we call 'system', certain characters and commands below are
2401 actually not specific to COMMAND.COM, but to the DJGPP implementation
2402 of 'system'. In particular:
2404 The shell wildcard characters are in DOS_CHARS because they will
2405 not be expanded if we call the child via 'spawnXX'.
2407 The ';' is in DOS_CHARS, because our 'system' knows how to run
2408 multiple commands on a single line.
2410 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2411 won't have to tell one from another and have one more set of
2412 commands and special characters. */
2413 static char sh_chars_dos[] = "*?[];|<>%^&()";
2414 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2415 "copy", "ctty", "date", "del", "dir", "echo",
2416 "erase", "exit", "for", "goto", "if", "md",
2417 "mkdir", "path", "pause", "prompt", "rd",
2418 "rmdir", "rem", "ren", "rename", "set",
2419 "shift", "time", "type", "ver", "verify",
2420 "vol", ":", 0 };
2422 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2423 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2424 "logout", "set", "umask", "wait", "while",
2425 "for", "case", "if", ":", ".", "break",
2426 "continue", "export", "read", "readonly",
2427 "shift", "times", "trap", "switch", "unset",
2428 "ulimit", 0 };
2430 char *sh_chars;
2431 char **sh_cmds;
2432 #elif defined (__EMX__)
2433 static char sh_chars_dos[] = "*?[];|<>%^&()";
2434 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2435 "copy", "ctty", "date", "del", "dir", "echo",
2436 "erase", "exit", "for", "goto", "if", "md",
2437 "mkdir", "path", "pause", "prompt", "rd",
2438 "rmdir", "rem", "ren", "rename", "set",
2439 "shift", "time", "type", "ver", "verify",
2440 "vol", ":", 0 };
2442 static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
2443 static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2444 "date", "del", "detach", "dir", "echo",
2445 "endlocal", "erase", "exit", "for", "goto", "if",
2446 "keys", "md", "mkdir", "move", "path", "pause",
2447 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2448 "set", "setlocal", "shift", "start", "time",
2449 "type", "ver", "verify", "vol", ":", 0 };
2451 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~'";
2452 static char *sh_cmds_sh[] = { "echo", "cd", "eval", "exec", "exit", "login",
2453 "logout", "set", "umask", "wait", "while",
2454 "for", "case", "if", ":", ".", "break",
2455 "continue", "export", "read", "readonly",
2456 "shift", "times", "trap", "switch", "unset",
2457 0 };
2458 char *sh_chars;
2459 char **sh_cmds;
2461 #elif defined (_AMIGA)
2462 static char sh_chars[] = "#;\"|<>()?*$`";
2463 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2464 "rename", "set", "setenv", "date", "makedir",
2465 "skip", "else", "endif", "path", "prompt",
2466 "unset", "unsetenv", "version",
2467 0 };
2468 #elif defined (WINDOWS32)
2469 static char sh_chars_dos[] = "\"|&<>";
2470 static char *sh_cmds_dos[] = { "assoc", "break", "call", "cd", "chcp",
2471 "chdir", "cls", "color", "copy", "ctty",
2472 "date", "del", "dir", "echo", "echo.",
2473 "endlocal", "erase", "exit", "for", "ftype",
2474 "goto", "if", "if", "md", "mkdir", "path",
2475 "pause", "prompt", "rd", "rem", "ren",
2476 "rename", "rmdir", "set", "setlocal",
2477 "shift", "time", "title", "type", "ver",
2478 "verify", "vol", ":", 0 };
2479 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2480 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2481 "logout", "set", "umask", "wait", "while", "for",
2482 "case", "if", ":", ".", "break", "continue",
2483 "export", "read", "readonly", "shift", "times",
2484 "trap", "switch", "test",
2485 #ifdef BATCH_MODE_ONLY_SHELL
2486 "echo",
2487 #endif
2488 0 };
2489 char* sh_chars;
2490 char** sh_cmds;
2491 #elif defined(__riscos__)
2492 static char sh_chars[] = "";
2493 static char *sh_cmds[] = { 0 };
2494 #else /* must be UNIX-ish */
2495 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~!";
2496 static char *sh_cmds[] = { ".", ":", "break", "case", "cd", "continue",
2497 "eval", "exec", "exit", "export", "for", "if",
2498 "login", "logout", "read", "readonly", "set",
2499 "shift", "switch", "test", "times", "trap",
2500 "ulimit", "umask", "unset", "wait", "while", 0 };
2501 # ifdef HAVE_DOS_PATHS
2502 /* This is required if the MSYS/Cygwin ports (which do not define
2503 WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
2504 sh_chars_sh[] directly (see below). */
2505 static char *sh_chars_sh = sh_chars;
2506 # endif /* HAVE_DOS_PATHS */
2507 #endif
2508 int i;
2509 char *p;
2510 char *ap;
2511 char *end;
2512 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2513 char **new_argv = 0;
2514 char *argstr = 0;
2515 #ifdef WINDOWS32
2516 int slow_flag = 0;
2518 if (!unixy_shell) {
2519 sh_cmds = sh_cmds_dos;
2520 sh_chars = sh_chars_dos;
2521 } else {
2522 sh_cmds = sh_cmds_sh;
2523 sh_chars = sh_chars_sh;
2525 #endif /* WINDOWS32 */
2527 if (restp != NULL)
2528 *restp = NULL;
2530 /* Make sure not to bother processing an empty line. */
2531 while (isblank ((unsigned char)*line))
2532 ++line;
2533 if (*line == '\0')
2534 return 0;
2536 if (shellflags == 0)
2537 shellflags = posix_pedantic ? "-ec" : "-c";
2539 /* See if it is safe to parse commands internally. */
2540 if (shell == 0)
2541 shell = default_shell;
2542 #ifdef WINDOWS32
2543 else if (strcmp (shell, default_shell))
2545 char *s1 = _fullpath (NULL, shell, 0);
2546 char *s2 = _fullpath (NULL, default_shell, 0);
2548 slow_flag = strcmp ((s1 ? s1 : ""), (s2 ? s2 : ""));
2550 if (s1)
2551 free (s1);
2552 if (s2)
2553 free (s2);
2555 if (slow_flag)
2556 goto slow;
2557 #else /* not WINDOWS32 */
2558 #if defined (__MSDOS__) || defined (__EMX__)
2559 else if (strcasecmp (shell, default_shell))
2561 extern int _is_unixy_shell (const char *_path);
2563 DB (DB_BASIC, (_("$SHELL changed (was '%s', now '%s')\n"),
2564 default_shell, shell));
2565 unixy_shell = _is_unixy_shell (shell);
2566 /* we must allocate a copy of shell: construct_command_argv() will free
2567 * shell after this function returns. */
2568 default_shell = xstrdup (shell);
2570 if (unixy_shell)
2572 sh_chars = sh_chars_sh;
2573 sh_cmds = sh_cmds_sh;
2575 else
2577 sh_chars = sh_chars_dos;
2578 sh_cmds = sh_cmds_dos;
2579 # ifdef __EMX__
2580 if (_osmode == OS2_MODE)
2582 sh_chars = sh_chars_os2;
2583 sh_cmds = sh_cmds_os2;
2585 # endif
2587 #else /* !__MSDOS__ */
2588 else if (strcmp (shell, default_shell))
2589 goto slow;
2590 #endif /* !__MSDOS__ && !__EMX__ */
2591 #endif /* not WINDOWS32 */
2593 if (ifs != 0)
2594 for (ap = ifs; *ap != '\0'; ++ap)
2595 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2596 goto slow;
2598 if (shellflags != 0)
2599 if (shellflags[0] != '-'
2600 || ((shellflags[1] != 'c' || shellflags[2] != '\0')
2601 && (shellflags[1] != 'e' || shellflags[2] != 'c' || shellflags[3] != '\0')))
2602 goto slow;
2604 i = strlen (line) + 1;
2606 /* More than 1 arg per character is impossible. */
2607 new_argv = xmalloc (i * sizeof (char *));
2609 /* All the args can fit in a buffer as big as LINE is. */
2610 ap = new_argv[0] = argstr = xmalloc (i);
2611 end = ap + i;
2613 /* I is how many complete arguments have been found. */
2614 i = 0;
2615 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2616 for (p = line; *p != '\0'; ++p)
2618 assert (ap <= end);
2620 if (instring)
2622 /* Inside a string, just copy any char except a closing quote
2623 or a backslash-newline combination. */
2624 if (*p == instring)
2626 instring = 0;
2627 if (ap == new_argv[0] || *(ap-1) == '\0')
2628 last_argument_was_empty = 1;
2630 else if (*p == '\\' && p[1] == '\n')
2632 /* Backslash-newline is handled differently depending on what
2633 kind of string we're in: inside single-quoted strings you
2634 keep them; in double-quoted strings they disappear. For
2635 DOS/Windows/OS2, if we don't have a POSIX shell, we keep the
2636 pre-POSIX behavior of removing the backslash-newline. */
2637 if (instring == '"'
2638 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2639 || !unixy_shell
2640 #endif
2642 ++p;
2643 else
2645 *(ap++) = *(p++);
2646 *(ap++) = *p;
2649 else if (*p == '\n' && restp != NULL)
2651 /* End of the command line. */
2652 *restp = p;
2653 goto end_of_line;
2655 /* Backslash, $, and ` are special inside double quotes.
2656 If we see any of those, punt.
2657 But on MSDOS, if we use COMMAND.COM, double and single
2658 quotes have the same effect. */
2659 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2660 goto slow;
2661 else
2662 *ap++ = *p;
2664 else if (strchr (sh_chars, *p) != 0)
2665 /* Not inside a string, but it's a special char. */
2666 goto slow;
2667 else if (one_shell && *p == '\n')
2668 /* In .ONESHELL mode \n is a separator like ; or && */
2669 goto slow;
2670 #ifdef __MSDOS__
2671 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2672 /* '...' is a wildcard in DJGPP. */
2673 goto slow;
2674 #endif
2675 else
2676 /* Not a special char. */
2677 switch (*p)
2679 case '=':
2680 /* Equals is a special character in leading words before the
2681 first word with no equals sign in it. This is not the case
2682 with sh -k, but we never get here when using nonstandard
2683 shell flags. */
2684 if (! seen_nonequals && unixy_shell)
2685 goto slow;
2686 word_has_equals = 1;
2687 *ap++ = '=';
2688 break;
2690 case '\\':
2691 /* Backslash-newline has special case handling, ref POSIX.
2692 We're in the fastpath, so emulate what the shell would do. */
2693 if (p[1] == '\n')
2695 /* Throw out the backslash and newline. */
2696 ++p;
2698 /* If there's nothing in this argument yet, skip any
2699 whitespace before the start of the next word. */
2700 if (ap == new_argv[i])
2701 p = next_token (p + 1) - 1;
2703 else if (p[1] != '\0')
2705 #ifdef HAVE_DOS_PATHS
2706 /* Only remove backslashes before characters special to Unixy
2707 shells. All other backslashes are copied verbatim, since
2708 they are probably DOS-style directory separators. This
2709 still leaves a small window for problems, but at least it
2710 should work for the vast majority of naive users. */
2712 #ifdef __MSDOS__
2713 /* A dot is only special as part of the "..."
2714 wildcard. */
2715 if (strneq (p + 1, ".\\.\\.", 5))
2717 *ap++ = '.';
2718 *ap++ = '.';
2719 p += 4;
2721 else
2722 #endif
2723 if (p[1] != '\\' && p[1] != '\''
2724 && !isspace ((unsigned char)p[1])
2725 && strchr (sh_chars_sh, p[1]) == 0)
2726 /* back up one notch, to copy the backslash */
2727 --p;
2728 #endif /* HAVE_DOS_PATHS */
2730 /* Copy and skip the following char. */
2731 *ap++ = *++p;
2733 break;
2735 case '\'':
2736 case '"':
2737 instring = *p;
2738 break;
2740 case '\n':
2741 if (restp != NULL)
2743 /* End of the command line. */
2744 *restp = p;
2745 goto end_of_line;
2747 else
2748 /* Newlines are not special. */
2749 *ap++ = '\n';
2750 break;
2752 case ' ':
2753 case '\t':
2754 /* We have the end of an argument.
2755 Terminate the text of the argument. */
2756 *ap++ = '\0';
2757 new_argv[++i] = ap;
2758 last_argument_was_empty = 0;
2760 /* Update SEEN_NONEQUALS, which tells us if every word
2761 heretofore has contained an '='. */
2762 seen_nonequals |= ! word_has_equals;
2763 if (word_has_equals && ! seen_nonequals)
2764 /* An '=' in a word before the first
2765 word without one is magical. */
2766 goto slow;
2767 word_has_equals = 0; /* Prepare for the next word. */
2769 /* If this argument is the command name,
2770 see if it is a built-in shell command.
2771 If so, have the shell handle it. */
2772 if (i == 1)
2774 register int j;
2775 for (j = 0; sh_cmds[j] != 0; ++j)
2777 if (streq (sh_cmds[j], new_argv[0]))
2778 goto slow;
2779 # ifdef __EMX__
2780 /* Non-Unix shells are case insensitive. */
2781 if (!unixy_shell
2782 && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
2783 goto slow;
2784 # endif
2788 /* Ignore multiple whitespace chars. */
2789 p = next_token (p) - 1;
2790 break;
2792 default:
2793 *ap++ = *p;
2794 break;
2797 end_of_line:
2799 if (instring)
2800 /* Let the shell deal with an unterminated quote. */
2801 goto slow;
2803 /* Terminate the last argument and the argument list. */
2805 *ap = '\0';
2806 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2807 ++i;
2808 new_argv[i] = 0;
2810 if (i == 1)
2812 register int j;
2813 for (j = 0; sh_cmds[j] != 0; ++j)
2814 if (streq (sh_cmds[j], new_argv[0]))
2815 goto slow;
2818 if (new_argv[0] == 0)
2820 /* Line was empty. */
2821 free (argstr);
2822 free (new_argv);
2823 return 0;
2826 return new_argv;
2828 slow:;
2829 /* We must use the shell. */
2831 if (new_argv != 0)
2833 /* Free the old argument list we were working on. */
2834 free (argstr);
2835 free (new_argv);
2838 #ifdef __MSDOS__
2839 execute_by_shell = 1; /* actually, call 'system' if shell isn't unixy */
2840 #endif
2842 #ifdef _AMIGA
2844 char *ptr;
2845 char *buffer;
2846 char *dptr;
2848 buffer = xmalloc (strlen (line)+1);
2850 ptr = line;
2851 for (dptr=buffer; *ptr; )
2853 if (*ptr == '\\' && ptr[1] == '\n')
2854 ptr += 2;
2855 else if (*ptr == '@') /* Kludge: multiline commands */
2857 ptr += 2;
2858 *dptr++ = '\n';
2860 else
2861 *dptr++ = *ptr++;
2863 *dptr = 0;
2865 new_argv = xmalloc (2 * sizeof (char *));
2866 new_argv[0] = buffer;
2867 new_argv[1] = 0;
2869 #else /* Not Amiga */
2870 #ifdef WINDOWS32
2872 * Not eating this whitespace caused things like
2874 * sh -c "\n"
2876 * which gave the shell fits. I think we have to eat
2877 * whitespace here, but this code should be considered
2878 * suspicious if things start failing....
2881 /* Make sure not to bother processing an empty line. */
2882 while (isspace ((unsigned char)*line))
2883 ++line;
2884 if (*line == '\0')
2885 return 0;
2886 #endif /* WINDOWS32 */
2889 /* SHELL may be a multi-word command. Construct a command line
2890 "$(SHELL) $(.SHELLFLAGS) LINE", with all special chars in LINE escaped.
2891 Then recurse, expanding this command line to get the final
2892 argument list. */
2894 unsigned int shell_len = strlen (shell);
2895 unsigned int line_len = strlen (line);
2896 unsigned int sflags_len = shellflags ? strlen (shellflags) : 0;
2897 char *command_ptr = NULL; /* used for batch_mode_shell mode */
2898 char *new_line;
2900 # ifdef __EMX__ /* is this necessary? */
2901 if (!unixy_shell && shellflags)
2902 shellflags[0] = '/'; /* "/c" */
2903 # endif
2905 /* In .ONESHELL mode we are allowed to throw the entire current
2906 recipe string at a single shell and trust that the user
2907 has configured the shell and shell flags, and formatted
2908 the string, appropriately. */
2909 if (one_shell)
2911 /* If the shell is Bourne compatible, we must remove and ignore
2912 interior special chars [@+-] because they're meaningless to
2913 the shell itself. If, however, we're in .ONESHELL mode and
2914 have changed SHELL to something non-standard, we should
2915 leave those alone because they could be part of the
2916 script. In this case we must also leave in place
2917 any leading [@+-] for the same reason. */
2919 /* Remove and ignore interior prefix chars [@+-] because they're
2920 meaningless given a single shell. */
2921 #if defined __MSDOS__ || defined (__EMX__)
2922 if (unixy_shell) /* the test is complicated and we already did it */
2923 #else
2924 if (is_bourne_compatible_shell(shell))
2925 #endif
2927 const char *f = line;
2928 char *t = line;
2930 /* Copy the recipe, removing and ignoring interior prefix chars
2931 [@+-]: they're meaningless in .ONESHELL mode. */
2932 while (f[0] != '\0')
2934 int esc = 0;
2936 /* This is the start of a new recipe line.
2937 Skip whitespace and prefix characters. */
2938 while (isblank (*f) || *f == '-' || *f == '@' || *f == '+')
2939 ++f;
2941 /* Copy until we get to the next logical recipe line. */
2942 while (*f != '\0')
2944 *(t++) = *(f++);
2945 if (f[-1] == '\\')
2946 esc = !esc;
2947 else
2949 /* On unescaped newline, we're done with this line. */
2950 if (f[-1] == '\n' && ! esc)
2951 break;
2953 /* Something else: reset the escape sequence. */
2954 esc = 0;
2958 *t = '\0';
2961 /* Create an argv list for the shell command line. */
2963 int n = 0;
2965 new_argv = xmalloc ((4 + sflags_len/2) * sizeof (char *));
2966 new_argv[n++] = xstrdup (shell);
2968 /* Chop up the shellflags (if any) and assign them. */
2969 if (! shellflags)
2970 new_argv[n++] = xstrdup ("");
2971 else
2973 const char *s = shellflags;
2974 char *t;
2975 unsigned int len;
2976 while ((t = find_next_token (&s, &len)) != 0)
2977 new_argv[n++] = xstrndup (t, len);
2980 /* Set the command to invoke. */
2981 new_argv[n++] = line;
2982 new_argv[n++] = NULL;
2984 return new_argv;
2987 new_line = xmalloc ((shell_len*2) + 1 + sflags_len + 1
2988 + (line_len*2) + 1);
2989 ap = new_line;
2990 /* Copy SHELL, escaping any characters special to the shell. If
2991 we don't escape them, construct_command_argv_internal will
2992 recursively call itself ad nauseam, or until stack overflow,
2993 whichever happens first. */
2994 for (p = shell; *p != '\0'; ++p)
2996 if (strchr (sh_chars, *p) != 0)
2997 *(ap++) = '\\';
2998 *(ap++) = *p;
3000 *(ap++) = ' ';
3001 if (shellflags)
3002 memcpy (ap, shellflags, sflags_len);
3003 ap += sflags_len;
3004 *(ap++) = ' ';
3005 command_ptr = ap;
3006 for (p = line; *p != '\0'; ++p)
3008 if (restp != NULL && *p == '\n')
3010 *restp = p;
3011 break;
3013 else if (*p == '\\' && p[1] == '\n')
3015 /* POSIX says we keep the backslash-newline. If we don't have a
3016 POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
3017 and remove the backslash/newline. */
3018 #if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
3019 # define PRESERVE_BSNL unixy_shell
3020 #else
3021 # define PRESERVE_BSNL 1
3022 #endif
3023 if (PRESERVE_BSNL)
3025 *(ap++) = '\\';
3026 /* Only non-batch execution needs another backslash,
3027 because it will be passed through a recursive
3028 invocation of this function. */
3029 if (!batch_mode_shell)
3030 *(ap++) = '\\';
3031 *(ap++) = '\n';
3033 ++p;
3034 continue;
3037 /* DOS shells don't know about backslash-escaping. */
3038 if (unixy_shell && !batch_mode_shell &&
3039 (*p == '\\' || *p == '\'' || *p == '"'
3040 || isspace ((unsigned char)*p)
3041 || strchr (sh_chars, *p) != 0))
3042 *ap++ = '\\';
3043 #ifdef __MSDOS__
3044 else if (unixy_shell && strneq (p, "...", 3))
3046 /* The case of '...' wildcard again. */
3047 strcpy (ap, "\\.\\.\\");
3048 ap += 5;
3049 p += 2;
3051 #endif
3052 *ap++ = *p;
3054 if (ap == new_line + shell_len + sflags_len + 2)
3056 /* Line was empty. */
3057 free (new_line);
3058 return 0;
3060 *ap = '\0';
3062 #ifdef WINDOWS32
3063 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3064 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3065 cases, run commands via a script file. */
3066 if (just_print_flag && !(flags & COMMANDS_RECURSE)) {
3067 /* Need to allocate new_argv, although it's unused, because
3068 start_job_command will want to free it and its 0'th element. */
3069 new_argv = xmalloc(2 * sizeof (char *));
3070 new_argv[0] = xstrdup ("");
3071 new_argv[1] = NULL;
3072 } else if ((no_default_sh_exe || batch_mode_shell) && batch_filename) {
3073 int temp_fd;
3074 FILE* batch = NULL;
3075 int id = GetCurrentProcessId();
3076 PATH_VAR(fbuf);
3078 /* create a file name */
3079 sprintf(fbuf, "make%d", id);
3080 *batch_filename = create_batch_file (fbuf, unixy_shell, &temp_fd);
3082 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3083 *batch_filename));
3085 /* Create a FILE object for the batch file, and write to it the
3086 commands to be executed. Put the batch file in TEXT mode. */
3087 _setmode (temp_fd, _O_TEXT);
3088 batch = _fdopen (temp_fd, "wt");
3089 if (!unixy_shell)
3090 fputs ("@echo off\n", batch);
3091 fputs (command_ptr, batch);
3092 fputc ('\n', batch);
3093 fclose (batch);
3094 DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
3095 !unixy_shell ? "\n\t@echo off" : "", command_ptr));
3097 /* create argv */
3098 new_argv = xmalloc(3 * sizeof (char *));
3099 if (unixy_shell) {
3100 new_argv[0] = xstrdup (shell);
3101 new_argv[1] = *batch_filename; /* only argv[0] gets freed later */
3102 } else {
3103 new_argv[0] = xstrdup (*batch_filename);
3104 new_argv[1] = NULL;
3106 new_argv[2] = NULL;
3107 } else
3108 #endif /* WINDOWS32 */
3110 if (unixy_shell)
3111 new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0,
3112 flags, 0);
3114 #ifdef __EMX__
3115 else if (!unixy_shell)
3117 /* new_line is local, must not be freed therefore
3118 We use line here instead of new_line because we run the shell
3119 manually. */
3120 size_t line_len = strlen (line);
3121 char *p = new_line;
3122 char *q = new_line;
3123 memcpy (new_line, line, line_len + 1);
3124 /* Replace all backslash-newline combination and also following tabs.
3125 Important: stop at the first '\n' because that's what the loop above
3126 did. The next line starting at restp[0] will be executed during the
3127 next call of this function. */
3128 while (*q != '\0' && *q != '\n')
3130 if (q[0] == '\\' && q[1] == '\n')
3131 q += 2; /* remove '\\' and '\n' */
3132 else
3133 *p++ = *q++;
3135 *p = '\0';
3137 # ifndef NO_CMD_DEFAULT
3138 if (strnicmp (new_line, "echo", 4) == 0
3139 && (new_line[4] == ' ' || new_line[4] == '\t'))
3141 /* the builtin echo command: handle it separately */
3142 size_t echo_len = line_len - 5;
3143 char *echo_line = new_line + 5;
3145 /* special case: echo 'x="y"'
3146 cmd works this way: a string is printed as is, i.e., no quotes
3147 are removed. But autoconf uses a command like echo 'x="y"' to
3148 determine whether make works. autoconf expects the output x="y"
3149 so we will do exactly that.
3150 Note: if we do not allow cmd to be the default shell
3151 we do not need this kind of voodoo */
3152 if (echo_line[0] == '\''
3153 && echo_line[echo_len - 1] == '\''
3154 && strncmp (echo_line + 1, "ac_maketemp=",
3155 strlen ("ac_maketemp=")) == 0)
3157 /* remove the enclosing quotes */
3158 memmove (echo_line, echo_line + 1, echo_len - 2);
3159 echo_line[echo_len - 2] = '\0';
3162 # endif
3165 /* Let the shell decide what to do. Put the command line into the
3166 2nd command line argument and hope for the best ;-) */
3167 size_t sh_len = strlen (shell);
3169 /* exactly 3 arguments + NULL */
3170 new_argv = xmalloc (4 * sizeof (char *));
3171 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3172 the trailing '\0' */
3173 new_argv[0] = xmalloc (sh_len + line_len + 5);
3174 memcpy (new_argv[0], shell, sh_len + 1);
3175 new_argv[1] = new_argv[0] + sh_len + 1;
3176 memcpy (new_argv[1], "/c", 3);
3177 new_argv[2] = new_argv[1] + 3;
3178 memcpy (new_argv[2], new_line, line_len + 1);
3179 new_argv[3] = NULL;
3182 #elif defined(__MSDOS__)
3183 else
3185 /* With MSDOS shells, we must construct the command line here
3186 instead of recursively calling ourselves, because we
3187 cannot backslash-escape the special characters (see above). */
3188 new_argv = xmalloc (sizeof (char *));
3189 line_len = strlen (new_line) - shell_len - sflags_len - 2;
3190 new_argv[0] = xmalloc (line_len + 1);
3191 strncpy (new_argv[0],
3192 new_line + shell_len + sflags_len + 2, line_len);
3193 new_argv[0][line_len] = '\0';
3195 #else
3196 else
3197 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3198 __FILE__, __LINE__);
3199 #endif
3201 free (new_line);
3203 #endif /* ! AMIGA */
3205 return new_argv;
3207 #endif /* !VMS */
3209 /* Figure out the argument list necessary to run LINE as a command. Try to
3210 avoid using a shell. This routine handles only ' quoting, and " quoting
3211 when no backslash, $ or ' characters are seen in the quotes. Starting
3212 quotes may be escaped with a backslash. If any of the characters in
3213 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3214 is the first word of a line, the shell is used.
3216 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3217 If *RESTP is NULL, newlines will be ignored.
3219 FILE is the target whose commands these are. It is used for
3220 variable expansion for $(SHELL) and $(IFS). */
3222 char **
3223 construct_command_argv (char *line, char **restp, struct file *file,
3224 int cmd_flags, char **batch_filename)
3226 char *shell, *ifs, *shellflags;
3227 char **argv;
3229 #ifdef VMS
3230 char *cptr;
3231 int argc;
3233 argc = 0;
3234 cptr = line;
3235 for (;;)
3237 while ((*cptr != 0)
3238 && (isspace ((unsigned char)*cptr)))
3239 cptr++;
3240 if (*cptr == 0)
3241 break;
3242 while ((*cptr != 0)
3243 && (!isspace((unsigned char)*cptr)))
3244 cptr++;
3245 argc++;
3248 argv = xmalloc (argc * sizeof (char *));
3249 if (argv == 0)
3250 abort ();
3252 cptr = line;
3253 argc = 0;
3254 for (;;)
3256 while ((*cptr != 0)
3257 && (isspace ((unsigned char)*cptr)))
3258 cptr++;
3259 if (*cptr == 0)
3260 break;
3261 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3262 argv[argc++] = cptr;
3263 while ((*cptr != 0)
3264 && (!isspace((unsigned char)*cptr)))
3265 cptr++;
3266 if (*cptr != 0)
3267 *cptr++ = 0;
3269 #else
3271 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3272 int save = warn_undefined_variables_flag;
3273 warn_undefined_variables_flag = 0;
3275 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3276 #ifdef WINDOWS32
3278 * Convert to forward slashes so that construct_command_argv_internal()
3279 * is not confused.
3281 if (shell) {
3282 char *p = w32ify (shell, 0);
3283 strcpy (shell, p);
3285 #endif
3286 #ifdef __EMX__
3288 static const char *unixroot = NULL;
3289 static const char *last_shell = "";
3290 static int init = 0;
3291 if (init == 0)
3293 unixroot = getenv ("UNIXROOT");
3294 /* unixroot must be NULL or not empty */
3295 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3296 init = 1;
3299 /* if we have an unixroot drive and if shell is not default_shell
3300 (which means it's either cmd.exe or the test has already been
3301 performed) and if shell is an absolute path without drive letter,
3302 try whether it exists e.g.: if "/bin/sh" does not exist use
3303 "$UNIXROOT/bin/sh" instead. */
3304 if (unixroot && shell && strcmp (shell, last_shell) != 0
3305 && (shell[0] == '/' || shell[0] == '\\'))
3307 /* trying a new shell, check whether it exists */
3308 size_t size = strlen (shell);
3309 char *buf = xmalloc (size + 7);
3310 memcpy (buf, shell, size);
3311 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3312 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3314 /* try the same for the unixroot drive */
3315 memmove (buf + 2, buf, size + 5);
3316 buf[0] = unixroot[0];
3317 buf[1] = unixroot[1];
3318 if (access (buf, F_OK) == 0)
3319 /* we have found a shell! */
3320 /* free(shell); */
3321 shell = buf;
3322 else
3323 free (buf);
3325 else
3326 free (buf);
3329 #endif /* __EMX__ */
3331 shellflags = allocated_variable_expand_for_file ("$(.SHELLFLAGS)", file);
3332 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3334 warn_undefined_variables_flag = save;
3337 argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
3338 cmd_flags, batch_filename);
3340 free (shell);
3341 free (shellflags);
3342 free (ifs);
3343 #endif /* !VMS */
3344 return argv;
3347 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3349 dup2 (int old, int new)
3351 int fd;
3353 (void) close (new);
3354 fd = dup (old);
3355 if (fd != new)
3357 (void) close (fd);
3358 errno = EMFILE;
3359 return -1;
3362 return fd;
3364 #endif /* !HAVE_DUP2 && !_AMIGA */
3366 /* On VMS systems, include special VMS functions. */
3368 #ifdef VMS
3369 #include "vmsjobs.c"
3370 #endif