VirtualBox

source: kBuild/trunk/src/kmk/job.c@ 3154

Last change on this file since 3154 was 3141, checked in by bird, 7 years ago

kmk: linux merge fixes.

  • Property svn:eol-style set to native
File size: 116.8 KB
Line 
1/* Job execution and handling for GNU Make.
2Copyright (C) 1988-2016 Free Software Foundation, Inc.
3This file is part of GNU Make.
4
5GNU Make is free software; you can redistribute it and/or modify it under the
6terms of the GNU General Public License as published by the Free Software
7Foundation; either version 3 of the License, or (at your option) any later
8version.
9
10GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12A PARTICULAR PURPOSE. See the GNU General Public License for more details.
13
14You should have received a copy of the GNU General Public License along with
15this program. If not, see <http://www.gnu.org/licenses/>. */
16
17#include "makeint.h"
18
19#include <assert.h>
20
21#include "job.h"
22#include "debug.h"
23#include "filedef.h"
24#include "commands.h"
25#include "variable.h"
26#include "os.h"
27#ifdef CONFIG_WITH_KMK_BUILTIN
28# include "kmkbuiltin.h"
29#endif
30#ifdef KMK
31# include "kbuild.h"
32#endif
33
34
35#include <string.h>
36
37/* Default shell to use. */
38#ifdef WINDOWS32
39#include <windows.h>
40
41const char *default_shell = "sh.exe";
42int no_default_sh_exe = 1;
43int batch_mode_shell = 1;
44HANDLE main_thread;
45
46#elif defined (_AMIGA)
47
48const char *default_shell = "";
49extern int MyExecute (char **);
50int batch_mode_shell = 0;
51
52#elif defined (__MSDOS__)
53
54/* The default shell is a pointer so we can change it if Makefile
55 says so. It is without an explicit path so we get a chance
56 to search the $PATH for it (since MSDOS doesn't have standard
57 directories we could trust). */
58const char *default_shell = "command.com";
59int batch_mode_shell = 0;
60
61#elif defined (__EMX__)
62
63const char *default_shell = "sh.exe"; /* bird changed this from "/bin/sh" as that doesn't make sense on OS/2. */
64int batch_mode_shell = 0;
65
66#elif defined (VMS)
67
68# include <descrip.h>
69# include <stsdef.h>
70const char *default_shell = "";
71int batch_mode_shell = 0;
72
73#define strsignal vms_strsignal
74char * vms_strsignal (int status);
75
76#ifndef C_FACILITY_NO
77# define C_FACILITY_NO 0x350000
78#endif
79#ifndef VMS_POSIX_EXIT_MASK
80# define VMS_POSIX_EXIT_MASK (C_FACILITY_NO | 0xA000)
81#endif
82
83#else
84
85const char *default_shell = "/bin/sh";
86int batch_mode_shell = 0;
87
88#endif
89
90#ifdef __MSDOS__
91# include <process.h>
92static int execute_by_shell;
93static int dos_pid = 123;
94int dos_status;
95int dos_command_running;
96#endif /* __MSDOS__ */
97
98#ifdef _AMIGA
99# include <proto/dos.h>
100static int amiga_pid = 123;
101static int amiga_status;
102static char amiga_bname[32];
103static int amiga_batch_file;
104#endif /* Amiga. */
105
106#ifdef VMS
107# ifndef __GNUC__
108# include <processes.h>
109# endif
110# include <starlet.h>
111# include <lib$routines.h>
112static void vmsWaitForChildren (int *);
113#endif
114
115#ifdef WINDOWS32
116# include <windows.h>
117# include <io.h>
118# include <process.h>
119# include "sub_proc.h"
120# include "w32err.h"
121# include "pathstuff.h"
122# define WAIT_NOHANG 1
123#endif /* WINDOWS32 */
124
125#ifdef __EMX__
126# include <process.h>
127#endif
128
129#if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
130# include <sys/wait.h>
131#endif
132
133#ifdef HAVE_WAITPID
134# define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
135#else /* Don't have waitpid. */
136# ifdef HAVE_WAIT3
137# ifndef wait3
138extern int wait3 ();
139# endif
140# define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
141# endif /* Have wait3. */
142#endif /* Have waitpid. */
143
144#if !defined (wait) && !defined (POSIX)
145int wait ();
146#endif
147
148#ifndef HAVE_UNION_WAIT
149
150# define WAIT_T int
151
152# ifndef WTERMSIG
153# define WTERMSIG(x) ((x) & 0x7f)
154# endif
155# ifndef WCOREDUMP
156# define WCOREDUMP(x) ((x) & 0x80)
157# endif
158# ifndef WEXITSTATUS
159# define WEXITSTATUS(x) (((x) >> 8) & 0xff)
160# endif
161# ifndef WIFSIGNALED
162# define WIFSIGNALED(x) (WTERMSIG (x) != 0)
163# endif
164# ifndef WIFEXITED
165# define WIFEXITED(x) (WTERMSIG (x) == 0)
166# endif
167
168#else /* Have 'union wait'. */
169
170# define WAIT_T union wait
171# ifndef WTERMSIG
172# define WTERMSIG(x) ((x).w_termsig)
173# endif
174# ifndef WCOREDUMP
175# define WCOREDUMP(x) ((x).w_coredump)
176# endif
177# ifndef WEXITSTATUS
178# define WEXITSTATUS(x) ((x).w_retcode)
179# endif
180# ifndef WIFSIGNALED
181# define WIFSIGNALED(x) (WTERMSIG(x) != 0)
182# endif
183# ifndef WIFEXITED
184# define WIFEXITED(x) (WTERMSIG(x) == 0)
185# endif
186
187#endif /* Don't have 'union wait'. */
188
189#if !defined(HAVE_UNISTD_H) && !defined(WINDOWS32)
190# ifndef _MSC_VER /* bird */
191int dup2 ();
192int execve ();
193void _exit ();
194# endif /* bird */
195# ifndef VMS
196int geteuid ();
197int getegid ();
198int setgid ();
199int getgid ();
200# endif
201#endif
202
203/* Different systems have different requirements for pid_t.
204 Plus we have to support gettext string translation... Argh. */
205static const char *
206pid2str (pid_t pid)
207{
208 static char pidstring[100];
209#if defined(WINDOWS32) && (__GNUC__ > 3 || _MSC_VER > 1300)
210 /* %Id is only needed for 64-builds, which were not supported by
211 older versions of Windows compilers. */
212 sprintf (pidstring, "%Id", pid);
213#else
214 sprintf (pidstring, "%lu", (unsigned long) pid);
215#endif
216 return pidstring;
217}
218
219#ifndef HAVE_GETLOADAVG
220int getloadavg (double loadavg[], int nelem);
221#endif
222
223static void free_child (struct child *);
224static void start_job_command (struct child *child);
225static int load_too_high (void);
226static int job_next_command (struct child *);
227static int start_waiting_job (struct child *);
228#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
229static void print_job_time (struct child *);
230#endif
231
232
233/* Chain of all live (or recently deceased) children. */
234
235struct child *children = 0;
236
237/* Number of children currently running. */
238
239unsigned int job_slots_used = 0;
240
241/* Nonzero if the 'good' standard input is in use. */
242
243static int good_stdin_used = 0;
244
245/* Chain of children waiting to run until the load average goes down. */
246
247static struct child *waiting_jobs = 0;
248
249/* Non-zero if we use a *real* shell (always so on Unix). */
250
251int unixy_shell = 1;
252
253/* Number of jobs started in the current second. */
254
255unsigned long job_counter = 0;
256
257/* Number of jobserver tokens this instance is currently using. */
258
259unsigned int jobserver_tokens = 0;
260
261
262
263#ifdef WINDOWS32
264/*
265 * The macro which references this function is defined in makeint.h.
266 */
267int
268w32_kill (pid_t pid, int sig)
269{
270 return ((process_kill ((HANDLE)pid, sig) == TRUE) ? 0 : -1);
271}
272
273/* This function creates a temporary file name with an extension specified
274 * by the unixy arg.
275 * Return an xmalloc'ed string of a newly created temp file and its
276 * file descriptor, or die. */
277static char *
278create_batch_file (char const *base, int unixy, int *fd)
279{
280 const char *const ext = unixy ? "sh" : "bat";
281 const char *error_string = NULL;
282 char temp_path[MAXPATHLEN]; /* need to know its length */
283 unsigned path_size = GetTempPath (sizeof temp_path, temp_path);
284 int path_is_dot = 0;
285 /* The following variable is static so we won't try to reuse a name
286 that was generated a little while ago, because that file might
287 not be on disk yet, since we use FILE_ATTRIBUTE_TEMPORARY below,
288 which tells the OS it doesn't need to flush the cache to disk.
289 If the file is not yet on disk, we might think the name is
290 available, while it really isn't. This happens in parallel
291 builds, where Make doesn't wait for one job to finish before it
292 launches the next one. */
293 static unsigned uniq = 0;
294 static int second_loop = 0;
295 const unsigned sizemax = strlen (base) + strlen (ext) + 10;
296
297 if (path_size == 0)
298 {
299 path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
300 path_is_dot = 1;
301 }
302
303 ++uniq;
304 if (uniq >= 0x10000 && !second_loop)
305 {
306 /* If we already had 64K batch files in this
307 process, make a second loop through the numbers,
308 looking for free slots, i.e. files that were
309 deleted in the meantime. */
310 second_loop = 1;
311 uniq = 1;
312 }
313 while (path_size > 0 &&
314 path_size + sizemax < sizeof temp_path &&
315 !(uniq >= 0x10000 && second_loop))
316 {
317 unsigned size = sprintf (temp_path + path_size,
318 "%s%s-%x.%s",
319 temp_path[path_size - 1] == '\\' ? "" : "\\",
320 base, uniq, ext);
321 HANDLE h = CreateFile (temp_path, /* file name */
322 GENERIC_READ | GENERIC_WRITE, /* desired access */
323 0, /* no share mode */
324 NULL, /* default security attributes */
325 CREATE_NEW, /* creation disposition */
326 FILE_ATTRIBUTE_NORMAL | /* flags and attributes */
327 FILE_ATTRIBUTE_TEMPORARY, /* we'll delete it */
328 NULL); /* no template file */
329
330 if (h == INVALID_HANDLE_VALUE)
331 {
332 const DWORD er = GetLastError ();
333
334 if (er == ERROR_FILE_EXISTS || er == ERROR_ALREADY_EXISTS)
335 {
336 ++uniq;
337 if (uniq == 0x10000 && !second_loop)
338 {
339 second_loop = 1;
340 uniq = 1;
341 }
342 }
343
344 /* the temporary path is not guaranteed to exist */
345 else if (path_is_dot == 0)
346 {
347 path_size = GetCurrentDirectory (sizeof temp_path, temp_path);
348 path_is_dot = 1;
349 }
350
351 else
352 {
353 error_string = map_windows32_error_to_string (er);
354 break;
355 }
356 }
357 else
358 {
359 const unsigned final_size = path_size + size + 1;
360 char *const path = xmalloc (final_size);
361 memcpy (path, temp_path, final_size);
362 *fd = _open_osfhandle ((intptr_t)h, 0);
363 if (unixy)
364 {
365 char *p;
366 int ch;
367 for (p = path; (ch = *p) != 0; ++p)
368 if (ch == '\\')
369 *p = '/';
370 }
371 return path; /* good return */
372 }
373 }
374
375 *fd = -1;
376 if (error_string == NULL)
377 error_string = _("Cannot create a temporary file\n");
378 O (fatal, NILF, error_string);
379
380 /* not reached */
381 return NULL;
382}
383#endif /* WINDOWS32 */
384
385#ifdef __EMX__
386/* returns whether path is assumed to be a unix like shell. */
387int
388_is_unixy_shell (const char *path)
389{
390 /* list of non unix shells */
391 const char *known_os2shells[] = {
392 "cmd.exe",
393 "cmd",
394 "4os2.exe",
395 "4os2",
396 "4dos.exe",
397 "4dos",
398 "command.com",
399 "command",
400 NULL
401 };
402
403 /* find the rightmost '/' or '\\' */
404 const char *name = strrchr (path, '/');
405 const char *p = strrchr (path, '\\');
406 unsigned i;
407
408 if (name && p) /* take the max */
409 name = (name > p) ? name : p;
410 else if (p) /* name must be 0 */
411 name = p;
412 else if (!name) /* name and p must be 0 */
413 name = path;
414
415 if (*name == '/' || *name == '\\') name++;
416
417 i = 0;
418 while (known_os2shells[i] != NULL)
419 {
420 if (strcasecmp (name, known_os2shells[i]) == 0)
421 return 0; /* not a unix shell */
422 i++;
423 }
424
425 /* in doubt assume a unix like shell */
426 return 1;
427}
428#endif /* __EMX__ */
429
430/* determines whether path looks to be a Bourne-like shell. */
431int
432is_bourne_compatible_shell (const char *path)
433{
434 /* List of known POSIX (or POSIX-ish) shells. */
435 static const char *unix_shells[] = {
436 "sh",
437 "bash",
438 "ksh",
439 "rksh",
440 "zsh",
441 "ash",
442 "dash",
443 NULL
444 };
445 const char **s;
446
447 /* find the rightmost '/' or '\\' */
448 const char *name = strrchr (path, '/');
449 char *p = strrchr (path, '\\');
450
451 if (name && p) /* take the max */
452 name = (name > p) ? name : p;
453 else if (p) /* name must be 0 */
454 name = p;
455 else if (!name) /* name and p must be 0 */
456 name = path;
457
458 if (*name == '/' || *name == '\\')
459 ++name;
460
461 /* this should be able to deal with extensions on Windows-like systems */
462 for (s = unix_shells; *s != NULL; ++s)
463 {
464#if defined(WINDOWS32) || defined(__MSDOS__)
465 unsigned int len = strlen (*s);
466 if ((strlen (name) >= len && STOP_SET (name[len], MAP_DOT|MAP_NUL))
467 && strncasecmp (name, *s, len) == 0)
468#else
469 if (strcmp (name, *s) == 0)
470#endif
471 return 1; /* a known unix-style shell */
472 }
473
474 /* if not on the list, assume it's not a Bourne-like shell */
475 return 0;
476}
477
478
479
480/* Write an error message describing the exit status given in
481 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
482 Append "(ignored)" if IGNORED is nonzero. */
483
484static void
485child_error (struct child *child,
486 int exit_code, int exit_sig, int coredump, int ignored)
487{
488 const char *pre = "*** ";
489 const char *post = "";
490 const char *dump = "";
491 const struct file *f = child->file;
492 const floc *flocp = &f->cmds->fileinfo;
493 const char *nm;
494 size_t l;
495
496 if (ignored && silent_flag)
497 return;
498
499 if (exit_sig && coredump)
500 dump = _(" (core dumped)");
501
502 if (ignored)
503 {
504 pre = "";
505 post = _(" (ignored)");
506 }
507
508 if (! flocp->filenm)
509 nm = _("<builtin>");
510 else
511 {
512 char *a = alloca (strlen (flocp->filenm) + 1 + 11 + 1);
513 sprintf (a, "%s:%lu", flocp->filenm, flocp->lineno + flocp->offset);
514 nm = a;
515 }
516
517 l = strlen (pre) + strlen (nm) + strlen (f->name) + strlen (post);
518
519 OUTPUT_SET (&child->output);
520
521 show_goal_error ();
522
523 if (exit_sig == 0)
524# if defined(KMK) && defined(KBUILD_OS_WINDOWS)
525 {
526 const char *exit_name = NULL;
527 switch ((unsigned)exit_code)
528 {
529 case 0xc0000005U: exit_name = "STATUS_ACCESS_VIOLATION"; break;
530 case 0xc000013aU: exit_name = "STATUS_CONTROL_C_EXIT"; break;
531 case 0xc0000374U: exit_name = "STATUS_HEAP_CORRUPTION"; break;
532 case 0xc0000409U: exit_name = "STATUS_STACK_BUFFER_OVERRUN"; break;
533 case 0xc0000417U: exit_name = "STATUS_INVALID_CRUNTIME_PARAMETER"; break;
534 case 0x80000003U: exit_name = "STATUS_BREAKPOINT"; break;
535 case 0x40000015U: exit_name = "STATUS_FATAL_APP_EXIT"; break;
536 case 0x40010004U: exit_name = "DBG_TERMINATE_PROCESS"; break;
537 case 0x40010005U: exit_name = "DBG_CONTROL_C"; break;
538 case 0x40010008U: exit_name = "DBG_CONTROL_BREAK"; break;
539 }
540 if (exit_name)
541 error (NILF, l + strlen (exit_name) + INTSTR_LENGTH,
542 _("%s[%s: %s] Error %d (%s)%s"),
543 pre, nm, f->name, exit_code, exit_name, post);
544 else
545 error (NILF, l + INTSTR_LENGTH + INTSTR_LENGTH,
546 _("%s[%s: %s] Error %d (%#x)%s"),
547 pre, nm, f->name, exit_code, exit_code, post);
548 }
549# else
550 error (NILF, l + INTSTR_LENGTH,
551 _("%s[%s: %s] Error %d%s"), pre, nm, f->name, exit_code, post);
552# endif
553 else
554 {
555 const char *s = strsignal (exit_sig);
556 error (NILF, l + strlen (s) + strlen (dump),
557 "%s[%s: %s] %s%s%s", pre, nm, f->name, s, dump, post);
558 }
559
560 OUTPUT_UNSET ();
561}
562
563
564
565/* Handle a dead child. This handler may or may not ever be installed.
566
567 If we're using the jobserver feature without pselect(), we need it.
568 First, installing it ensures the read will interrupt on SIGCHLD. Second,
569 we close the dup'd read FD to ensure we don't enter another blocking read
570 without reaping all the dead children. In this case we don't need the
571 dead_children count.
572
573 If we don't have either waitpid or wait3, then make is unreliable, but we
574 use the dead_children count to reap children as best we can. */
575
576static unsigned int dead_children = 0;
577
578RETSIGTYPE
579child_handler (int sig UNUSED)
580{
581 ++dead_children;
582
583 jobserver_signal ();
584
585#if defined __EMX__ && !defined(__INNOTEK_LIBC__) /* bird */
586 /* The signal handler must called only once! */
587 signal (SIGCHLD, SIG_DFL);
588#endif
589}
590
591extern pid_t shell_function_pid;
592
593/* Reap all dead children, storing the returned status and the new command
594 state ('cs_finished') in the 'file' member of the 'struct child' for the
595 dead child, and removing the child from the chain. In addition, if BLOCK
596 nonzero, we block in this function until we've reaped at least one
597 complete child, waiting for it to die if necessary. If ERR is nonzero,
598 print an error message first. */
599
600void
601reap_children (int block, int err)
602{
603#ifndef WINDOWS32
604 WAIT_T status;
605#endif
606 /* Initially, assume we have some. */
607 int reap_more = 1;
608
609#ifdef WAIT_NOHANG
610# define REAP_MORE reap_more
611#else
612# define REAP_MORE dead_children
613#endif
614
615 /* As long as:
616
617 We have at least one child outstanding OR a shell function in progress,
618 AND
619 We're blocking for a complete child OR there are more children to reap
620
621 we'll keep reaping children. */
622
623 while ((children != 0 || shell_function_pid != 0)
624 && (block || REAP_MORE))
625 {
626 unsigned int remote = 0;
627 pid_t pid;
628 int exit_code, exit_sig, coredump;
629 struct child *lastc, *c;
630 int child_failed;
631 int any_remote, any_local;
632 int dontcare;
633#ifdef CONFIG_WITH_KMK_BUILTIN
634 struct child *completed_child = NULL;
635#endif
636
637 if (err && block)
638 {
639 static int printed = 0;
640
641 /* We might block for a while, so let the user know why.
642 Only print this message once no matter how many jobs are left. */
643 fflush (stdout);
644 if (!printed)
645 O (error, NILF, _("*** Waiting for unfinished jobs...."));
646 printed = 1;
647 }
648
649 /* We have one less dead child to reap. As noted in
650 child_handler() above, this count is completely unimportant for
651 all modern, POSIX-y systems that support wait3() or waitpid().
652 The rest of this comment below applies only to early, broken
653 pre-POSIX systems. We keep the count only because... it's there...
654
655 The test and decrement are not atomic; if it is compiled into:
656 register = dead_children - 1;
657 dead_children = register;
658 a SIGCHLD could come between the two instructions.
659 child_handler increments dead_children.
660 The second instruction here would lose that increment. But the
661 only effect of dead_children being wrong is that we might wait
662 longer than necessary to reap a child, and lose some parallelism;
663 and we might print the "Waiting for unfinished jobs" message above
664 when not necessary. */
665
666 if (dead_children > 0)
667 --dead_children;
668
669 any_remote = 0;
670 any_local = shell_function_pid != 0;
671 for (c = children; c != 0; c = c->next)
672 {
673 any_remote |= c->remote;
674 any_local |= ! c->remote;
675#ifdef CONFIG_WITH_KMK_BUILTIN
676 if (c->has_status)
677 {
678 completed_child = c;
679 DB (DB_JOBS, (_("builtin child %p (%s) PID %s %s Status %ld\n"),
680 (void *)c, c->file->name,
681 pid2str (c->pid), c->remote ? _(" (remote)") : "",
682 (long) c->status));
683 }
684 else
685#endif
686 DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
687 (void *)c, c->file->name, pid2str (c->pid),
688 c->remote ? _(" (remote)") : ""));
689#ifdef VMS
690 break;
691#endif
692 }
693
694 /* First, check for remote children. */
695 if (any_remote)
696 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
697 else
698 pid = 0;
699
700 if (pid > 0)
701 /* We got a remote child. */
702 remote = 1;
703 else if (pid < 0)
704 {
705 /* A remote status command failed miserably. Punt. */
706 remote_status_lose:
707 pfatal_with_name ("remote_status");
708 }
709 else
710 {
711 /* No remote children. Check for local children. */
712#ifdef CONFIG_WITH_KMK_BUILTIN
713 if (completed_child)
714 {
715 pid = completed_child->pid;
716# if defined(WINDOWS32)
717 exit_code = completed_child->status;
718 exit_sig = 0;
719 coredump = 0;
720# else
721 status = (WAIT_T)completed_child->status;
722# endif
723 }
724 else
725#endif /* CONFIG_WITH_KMK_BUILTIN */
726#if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
727 if (any_local)
728 {
729#ifdef VMS
730 /* Todo: This needs more untangling multi-process support */
731 /* Just do single child process support now */
732 vmsWaitForChildren (&status);
733 pid = c->pid;
734
735 /* VMS failure status can not be fully translated */
736 status = $VMS_STATUS_SUCCESS (c->cstatus) ? 0 : (1 << 8);
737
738 /* A Posix failure can be exactly translated */
739 if ((c->cstatus & VMS_POSIX_EXIT_MASK) == VMS_POSIX_EXIT_MASK)
740 status = (c->cstatus >> 3 & 255) << 8;
741#else
742#ifdef WAIT_NOHANG
743 if (!block)
744 pid = WAIT_NOHANG (&status);
745 else
746#endif
747 EINTRLOOP (pid, wait (&status));
748#endif /* !VMS */
749 }
750 else
751 pid = 0;
752
753 if (pid < 0)
754 {
755 /* The wait*() failed miserably. Punt. */
756 pfatal_with_name ("wait");
757 }
758 else if (pid > 0)
759 {
760 /* We got a child exit; chop the status word up. */
761 exit_code = WEXITSTATUS (status);
762 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
763 coredump = WCOREDUMP (status);
764
765 /* If we have started jobs in this second, remove one. */
766 if (job_counter)
767 --job_counter;
768 }
769 else
770 {
771 /* No local children are dead. */
772 reap_more = 0;
773
774 if (!block || !any_remote)
775 break;
776
777 /* Now try a blocking wait for a remote child. */
778 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
779 if (pid < 0)
780 goto remote_status_lose;
781 else if (pid == 0)
782 /* No remote children either. Finally give up. */
783 break;
784
785 /* We got a remote child. */
786 remote = 1;
787 }
788#endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
789
790#ifdef __MSDOS__
791 /* Life is very different on MSDOS. */
792 pid = dos_pid - 1;
793 status = dos_status;
794 exit_code = WEXITSTATUS (status);
795 if (exit_code == 0xff)
796 exit_code = -1;
797 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
798 coredump = 0;
799#endif /* __MSDOS__ */
800#ifdef _AMIGA
801 /* Same on Amiga */
802 pid = amiga_pid - 1;
803 status = amiga_status;
804 exit_code = amiga_status;
805 exit_sig = 0;
806 coredump = 0;
807#endif /* _AMIGA */
808#ifdef WINDOWS32
809 {
810 HANDLE hPID;
811 HANDLE hcTID, hcPID;
812 DWORD dwWaitStatus = 0;
813 exit_code = 0;
814 exit_sig = 0;
815 coredump = 0;
816
817 /* Record the thread ID of the main process, so that we
818 could suspend it in the signal handler. */
819 if (!main_thread)
820 {
821 hcTID = GetCurrentThread ();
822 hcPID = GetCurrentProcess ();
823 if (!DuplicateHandle (hcPID, hcTID, hcPID, &main_thread, 0,
824 FALSE, DUPLICATE_SAME_ACCESS))
825 {
826 DWORD e = GetLastError ();
827 fprintf (stderr,
828 "Determine main thread ID (Error %ld: %s)\n",
829 e, map_windows32_error_to_string (e));
830 }
831 else
832 DB (DB_VERBOSE, ("Main thread handle = %p\n", main_thread));
833 }
834
835 /* wait for anything to finish */
836 hPID = process_wait_for_any (block, &dwWaitStatus);
837 if (hPID)
838 {
839 /* was an error found on this process? */
840 int werr = process_last_err (hPID);
841
842 /* get exit data */
843 exit_code = process_exit_code (hPID);
844
845 if (werr)
846 fprintf (stderr, "make (e=%d): %s", exit_code,
847 map_windows32_error_to_string (exit_code));
848
849 /* signal */
850 exit_sig = process_signal (hPID);
851
852 /* cleanup process */
853 process_cleanup (hPID);
854
855 coredump = 0;
856 }
857 else if (dwWaitStatus == WAIT_FAILED)
858 {
859 /* The WaitForMultipleObjects() failed miserably. Punt. */
860 pfatal_with_name ("WaitForMultipleObjects");
861 }
862 else if (dwWaitStatus == WAIT_TIMEOUT)
863 {
864 /* No child processes are finished. Give up waiting. */
865 reap_more = 0;
866 break;
867 }
868
869 pid = (pid_t) hPID;
870 }
871#endif /* WINDOWS32 */
872 }
873
874 /* Check if this is the child of the 'shell' function. */
875 if (!remote && pid == shell_function_pid)
876 {
877 shell_completed (exit_code, exit_sig);
878 break;
879 }
880
881 /* Search for a child matching the deceased one. */
882 lastc = 0;
883 for (c = children; c != 0; lastc = c, c = c->next)
884 if (c->pid == pid && c->remote == remote)
885 break;
886
887 if (c == 0)
888 /* An unknown child died.
889 Ignore it; it was inherited from our invoker. */
890 continue;
891
892 /* Determine the failure status: 0 for success, 1 for updating target in
893 question mode, 2 for anything else. */
894 if (exit_sig == 0 && exit_code == 0)
895 child_failed = MAKE_SUCCESS;
896 else if (exit_sig == 0 && exit_code == 1 && question_flag && c->recursive)
897 child_failed = MAKE_TROUBLE;
898 else
899 child_failed = MAKE_FAILURE;
900
901 DB (DB_JOBS, (child_failed
902 ? _("Reaping losing child %p PID %s %s\n")
903 : _("Reaping winning child %p PID %s %s\n"),
904 (void *)c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
905
906 if (c->sh_batch_file)
907 {
908 int rm_status;
909
910 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
911 c->sh_batch_file));
912
913 errno = 0;
914 rm_status = remove (c->sh_batch_file);
915 if (rm_status)
916 DB (DB_JOBS, (_("Cleaning up temp batch file %s failed (%d)\n"),
917 c->sh_batch_file, errno));
918
919 /* all done with memory */
920 free (c->sh_batch_file);
921 c->sh_batch_file = NULL;
922 }
923
924 /* If this child had the good stdin, say it is now free. */
925 if (c->good_stdin)
926 good_stdin_used = 0;
927
928 dontcare = c->dontcare;
929
930 if (child_failed && !c->noerror && !ignore_errors_flag)
931 {
932 /* The commands failed. Write an error message,
933 delete non-precious targets, and abort. */
934 static int delete_on_error = -1;
935
936 if (!dontcare && child_failed == MAKE_FAILURE)
937#ifdef KMK
938 {
939 child_error (c, exit_code, exit_sig, coredump, 0);
940 if ( ( c->file->cmds->lines_flags[c->command_line - 1]
941 & (COMMANDS_SILENT | COMMANDS_RECURSE))
942 == COMMANDS_SILENT
943# ifdef KBUILD_OS_WINDOWS /* show commands for NT statuses */
944 || (exit_code & 0xc0000000)
945# endif
946 || exit_sig != 0)
947 OS (message, 0, "The failing command:\n%s", c->file->cmds->command_lines[c->command_line - 1]);
948 }
949#else /* !KMK */
950 child_error (c, exit_code, exit_sig, coredump, 0);
951#endif /* !KMK */
952
953 c->file->update_status = child_failed == MAKE_FAILURE ? us_failed : us_question;
954 if (delete_on_error == -1)
955 {
956 struct file *f = lookup_file (".DELETE_ON_ERROR");
957 delete_on_error = f != 0 && f->is_target;
958 }
959 if (exit_sig != 0 || delete_on_error)
960 delete_child_targets (c);
961 }
962 else
963 {
964 if (child_failed)
965 {
966 /* The commands failed, but we don't care. */
967 child_error (c, exit_code, exit_sig, coredump, 1);
968 child_failed = 0;
969 }
970
971 /* If there are more commands to run, try to start them. */
972 if (job_next_command (c))
973 {
974 if (handling_fatal_signal)
975 {
976 /* Never start new commands while we are dying.
977 Since there are more commands that wanted to be run,
978 the target was not completely remade. So we treat
979 this as if a command had failed. */
980 c->file->update_status = us_failed;
981 }
982 else
983 {
984#ifndef NO_OUTPUT_SYNC
985 /* If we're sync'ing per line, write the previous line's
986 output before starting the next one. */
987 if (output_sync == OUTPUT_SYNC_LINE)
988 output_dump (&c->output);
989#endif
990 /* Check again whether to start remotely.
991 Whether or not we want to changes over time.
992 Also, start_remote_job may need state set up
993 by start_remote_job_p. */
994 c->remote = start_remote_job_p (0);
995 start_job_command (c);
996 /* Fatal signals are left blocked in case we were
997 about to put that child on the chain. But it is
998 already there, so it is safe for a fatal signal to
999 arrive now; it will clean up this child's targets. */
1000 unblock_sigs ();
1001 if (c->file->command_state == cs_running)
1002 /* We successfully started the new command.
1003 Loop to reap more children. */
1004 continue;
1005 }
1006
1007 if (c->file->update_status != us_success)
1008 /* We failed to start the commands. */
1009 delete_child_targets (c);
1010 }
1011 else
1012 /* There are no more commands. We got through them all
1013 without an unignored error. Now the target has been
1014 successfully updated. */
1015 c->file->update_status = us_success;
1016 }
1017
1018 /* When we get here, all the commands for c->file are finished. */
1019
1020#ifndef NO_OUTPUT_SYNC
1021 /* Synchronize any remaining parallel output. */
1022 output_dump (&c->output);
1023#endif
1024
1025 /* At this point c->file->update_status is success or failed. But
1026 c->file->command_state is still cs_running if all the commands
1027 ran; notice_finish_file looks for cs_running to tell it that
1028 it's interesting to check the file's modtime again now. */
1029
1030 if (! handling_fatal_signal)
1031 /* Notice if the target of the commands has been changed.
1032 This also propagates its values for command_state and
1033 update_status to its also_make files. */
1034 notice_finished_file (c->file);
1035
1036 DB (DB_JOBS, (_("Removing child %p PID %s%s from chain.\n"),
1037 (void *)c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
1038
1039 /* Block fatal signals while frobnicating the list, so that
1040 children and job_slots_used are always consistent. Otherwise
1041 a fatal signal arriving after the child is off the chain and
1042 before job_slots_used is decremented would believe a child was
1043 live and call reap_children again. */
1044 block_sigs ();
1045
1046 /* There is now another slot open. */
1047 if (job_slots_used > 0)
1048 --job_slots_used;
1049
1050 /* Remove the child from the chain and free it. */
1051 if (lastc == 0)
1052 children = c->next;
1053 else
1054 lastc->next = c->next;
1055
1056 free_child (c);
1057
1058 unblock_sigs ();
1059
1060 /* If the job failed, and the -k flag was not given, die,
1061 unless we are already in the process of dying. */
1062 if (!err && child_failed && !dontcare && !keep_going_flag &&
1063 /* fatal_error_signal will die with the right signal. */
1064 !handling_fatal_signal)
1065 die (child_failed);
1066
1067 /* Only block for one child. */
1068 block = 0;
1069 }
1070
1071 return;
1072}
1073
1074
1075/* Free the storage allocated for CHILD. */
1076
1077static void
1078free_child (struct child *child)
1079{
1080#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
1081 print_job_time (child);
1082#endif
1083 output_close (&child->output);
1084
1085 if (!jobserver_tokens)
1086 ONS (fatal, NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
1087 (void *)child, child->file->name);
1088
1089 /* If we're using the jobserver and this child is not the only outstanding
1090 job, put a token back into the pipe for it. */
1091
1092 if (jobserver_enabled () && jobserver_tokens > 1)
1093 {
1094 jobserver_release (1);
1095 DB (DB_JOBS, (_("Released token for child %p (%s).\n"),
1096 (void *)child, child->file->name));
1097 }
1098
1099 --jobserver_tokens;
1100
1101 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
1102 return;
1103
1104 if (child->command_lines != 0)
1105 {
1106 register unsigned int i;
1107 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
1108 free (child->command_lines[i]);
1109 free (child->command_lines);
1110 }
1111
1112 if (child->environment != 0)
1113 {
1114 register char **ep = child->environment;
1115 while (*ep != 0)
1116 free (*ep++);
1117 free (child->environment);
1118 }
1119
1120#ifdef CONFIG_WITH_MEMORY_OPTIMIZATIONS
1121 /* Free the chopped command lines for simple targets when
1122 there are no more active references to them. */
1123
1124 child->file->cmds->refs--;
1125 if ( !child->file->intermediate
1126 && !child->file->pat_variables)
1127 free_chopped_commands(child->file->cmds);
1128#endif /* CONFIG_WITH_MEMORY_OPTIMIZATIONS */
1129
1130 free (child);
1131}
1132
1133
1134#ifdef POSIX
1135extern sigset_t fatal_signal_set;
1136#endif
1137
1138void
1139block_sigs (void)
1140{
1141#ifdef POSIX
1142 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
1143#else
1144# ifdef HAVE_SIGSETMASK
1145 (void) sigblock (fatal_signal_mask);
1146# endif
1147#endif
1148}
1149
1150#ifdef POSIX
1151void
1152unblock_sigs (void)
1153{
1154 sigset_t empty;
1155 sigemptyset (&empty);
1156 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
1157}
1158#endif
1159
1160/* Start a job to run the commands specified in CHILD.
1161 CHILD is updated to reflect the commands and ID of the child process.
1162
1163 NOTE: On return fatal signals are blocked! The caller is responsible
1164 for calling 'unblock_sigs', once the new child is safely on the chain so
1165 it can be cleaned up in the event of a fatal signal. */
1166
1167static void
1168start_job_command (struct child *child)
1169{
1170 int flags;
1171 char *p;
1172#ifdef VMS
1173 char *argv;
1174#else
1175 char **argv;
1176#endif
1177
1178 /* If we have a completely empty commandset, stop now. */
1179 if (!child->command_ptr)
1180 goto next_command;
1181
1182#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
1183 if (child->start_ts == -1)
1184 child->start_ts = nano_timestamp ();
1185#endif
1186
1187 /* Combine the flags parsed for the line itself with
1188 the flags specified globally for this target. */
1189 flags = (child->file->command_flags
1190 | child->file->cmds->lines_flags[child->command_line - 1]);
1191
1192 p = child->command_ptr;
1193 child->noerror = ((flags & COMMANDS_NOERROR) != 0);
1194
1195 while (*p != '\0')
1196 {
1197 if (*p == '@')
1198 flags |= COMMANDS_SILENT;
1199 else if (*p == '+')
1200 flags |= COMMANDS_RECURSE;
1201 else if (*p == '-')
1202 child->noerror = 1;
1203#ifdef CONFIG_WITH_COMMANDS_FUNC
1204 else if (*p == '%')
1205 flags |= COMMAND_GETTER_SKIP_IT;
1206#endif
1207 /* Don't skip newlines. */
1208 else if (!ISBLANK (*p))
1209#ifndef CONFIG_WITH_KMK_BUILTIN
1210 break;
1211#else /* CONFIG_WITH_KMK_BUILTIN */
1212
1213 {
1214 if ( !(flags & COMMANDS_KMK_BUILTIN)
1215 && !strncmp(p, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
1216 flags |= COMMANDS_KMK_BUILTIN;
1217 break;
1218 }
1219#endif /* CONFIG_WITH_KMK_BUILTIN */
1220 ++p;
1221 }
1222
1223 child->recursive = ((flags & COMMANDS_RECURSE) != 0);
1224
1225 /* Update the file's command flags with any new ones we found. We only
1226 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
1227 now marking more commands recursive than should be in the case of
1228 multiline define/endef scripts where only one line is marked "+". In
1229 order to really fix this, we'll have to keep a lines_flags for every
1230 actual line, after expansion. */
1231 child->file->cmds->lines_flags[child->command_line - 1] |= flags & COMMANDS_RECURSE;
1232
1233 /* POSIX requires that a recipe prefix after a backslash-newline should
1234 be ignored. Remove it now so the output is correct. */
1235 {
1236 char prefix = child->file->cmds->recipe_prefix;
1237 char *p1, *p2;
1238 p1 = p2 = p;
1239 while (*p1 != '\0')
1240 {
1241 *(p2++) = *p1;
1242 if (p1[0] == '\n' && p1[1] == prefix)
1243 ++p1;
1244 ++p1;
1245 }
1246 *p2 = *p1;
1247 }
1248
1249 /* Figure out an argument list from this command line. */
1250 {
1251 char *end = 0;
1252#ifdef VMS
1253 /* Skip any leading whitespace */
1254 while (*p)
1255 {
1256 if (!ISSPACE (*p))
1257 {
1258 if (*p != '\\')
1259 break;
1260 if ((p[1] != '\n') && (p[1] != 'n') && (p[1] != 't'))
1261 break;
1262 }
1263 p++;
1264 }
1265
1266 argv = p;
1267 /* Although construct_command_argv contains some code for VMS, it was/is
1268 not called/used. Please note, for VMS argv is a string (not an array
1269 of strings) which contains the complete command line, which for
1270 multi-line variables still includes the newlines. So detect newlines
1271 and set 'end' (which is used for child->command_ptr) instead of
1272 (re-)writing construct_command_argv */
1273 if (!one_shell)
1274 {
1275 char *s = p;
1276 int instring = 0;
1277 while (*s)
1278 {
1279 if (*s == '"')
1280 instring = !instring;
1281 else if (*s == '\\' && !instring && *(s+1) != 0)
1282 s++;
1283 else if (*s == '\n' && !instring)
1284 {
1285 end = s;
1286 break;
1287 }
1288 ++s;
1289 }
1290 }
1291#else
1292 argv = construct_command_argv (p, &end, child->file,
1293 child->file->cmds->lines_flags[child->command_line - 1],
1294 &child->sh_batch_file);
1295#endif
1296 if (end == NULL)
1297 child->command_ptr = NULL;
1298 else
1299 {
1300 *end++ = '\0';
1301 child->command_ptr = end;
1302 }
1303 }
1304
1305 /* If -q was given, say that updating 'failed' if there was any text on the
1306 command line, or 'succeeded' otherwise. The exit status of 1 tells the
1307 user that -q is saying 'something to do'; the exit status for a random
1308 error is 2. */
1309 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
1310 {
1311#ifndef VMS
1312 free (argv[0]);
1313 free (argv);
1314#endif
1315#ifdef VMS
1316 /* On VMS, argv[0] can be a null string here */
1317 if (argv[0] != 0)
1318 {
1319#endif
1320 child->file->update_status = us_question;
1321 notice_finished_file (child->file);
1322 return;
1323#ifdef VMS
1324 }
1325#endif
1326 }
1327
1328 if (touch_flag && !(flags & COMMANDS_RECURSE))
1329 {
1330 /* Go on to the next command. It might be the recursive one.
1331 We construct ARGV only to find the end of the command line. */
1332#ifndef VMS
1333 if (argv)
1334 {
1335 free (argv[0]);
1336 free (argv);
1337 }
1338#endif
1339 argv = 0;
1340 }
1341
1342 if (argv == 0)
1343 {
1344 next_command:
1345#ifdef __MSDOS__
1346 execute_by_shell = 0; /* in case construct_command_argv sets it */
1347#endif
1348 /* This line has no commands. Go to the next. */
1349 if (job_next_command (child))
1350 start_job_command (child);
1351 else
1352 {
1353 /* No more commands. Make sure we're "running"; we might not be if
1354 (e.g.) all commands were skipped due to -n. */
1355 set_command_state (child->file, cs_running);
1356 child->file->update_status = us_success;
1357 notice_finished_file (child->file);
1358 }
1359
1360 OUTPUT_UNSET();
1361 return;
1362 }
1363
1364 /* Are we going to synchronize this command's output? Do so if either we're
1365 in SYNC_RECURSE mode or this command is not recursive. We'll also check
1366 output_sync separately below in case it changes due to error. */
1367 child->output.syncout = output_sync && (output_sync == OUTPUT_SYNC_RECURSE
1368 || !(flags & COMMANDS_RECURSE));
1369 OUTPUT_SET (&child->output);
1370
1371#ifndef NO_OUTPUT_SYNC
1372 if (! child->output.syncout)
1373 /* We don't want to sync this command: to avoid misordered
1374 output ensure any already-synced content is written. */
1375 output_dump (&child->output);
1376#endif
1377
1378 /* Print the command if appropriate. */
1379#ifdef CONFIG_PRETTY_COMMAND_PRINTING
1380 if ( pretty_command_printing
1381 && (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
1382 && argv[0][0] != '\0')
1383 {
1384 unsigned i;
1385 for (i = 0; argv[i]; i++)
1386 OSSS ( message, 0, "%s'%s'%s", i ? "\t" : "> ", argv[i], argv[i + 1] ? " \\" : "");
1387 }
1388 else
1389#endif /* CONFIG_PRETTY_COMMAND_PRINTING */
1390 if (just_print_flag || trace_flag
1391 || (!(flags & COMMANDS_SILENT) && !silent_flag))
1392 OS (message, 0, "%s", p);
1393
1394 /* Tell update_goal_chain that a command has been started on behalf of
1395 this target. It is important that this happens here and not in
1396 reap_children (where we used to do it), because reap_children might be
1397 reaping children from a different target. We want this increment to
1398 guaranteedly indicate that a command was started for the dependency
1399 chain (i.e., update_file recursion chain) we are processing. */
1400
1401 ++commands_started;
1402
1403 /* Optimize an empty command. People use this for timestamp rules,
1404 so avoid forking a useless shell. Do this after we increment
1405 commands_started so make still treats this special case as if it
1406 performed some action (makes a difference as to what messages are
1407 printed, etc. */
1408
1409#if !defined(VMS) && !defined(_AMIGA)
1410 if (
1411#if defined __MSDOS__ || defined (__EMX__)
1412 unixy_shell /* the test is complicated and we already did it */
1413#else
1414 (argv[0] && is_bourne_compatible_shell (argv[0]))
1415#endif
1416 && (argv[1] && argv[1][0] == '-'
1417 &&
1418 ((argv[1][1] == 'c' && argv[1][2] == '\0')
1419 ||
1420 (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
1421 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1422 && argv[3] == NULL)
1423 {
1424 free (argv[0]);
1425 free (argv);
1426 goto next_command;
1427 }
1428#endif /* !VMS && !_AMIGA */
1429
1430 /* If -n was given, recurse to get the next line in the sequence. */
1431
1432 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1433 {
1434#ifndef VMS
1435 free (argv[0]);
1436 free (argv);
1437#endif
1438 goto next_command;
1439 }
1440
1441#ifdef CONFIG_WITH_KMK_BUILTIN
1442 /* If builtin command then pass it on to the builtin shell interpreter. */
1443
1444 if ((flags & COMMANDS_KMK_BUILTIN) && !just_print_flag)
1445 {
1446 int rc;
1447 char **argv_spawn = NULL;
1448 char **p2 = argv;
1449 while (*p2 && strncmp (*p2, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
1450 p2++;
1451 assert (*p2);
1452 set_command_state (child->file, cs_running);
1453 child->deleted = 0;
1454 child->pid = 0;
1455 if (p2 != argv)
1456 rc = kmk_builtin_command (*p2, child, &argv_spawn, &child->pid);
1457 else
1458 {
1459 int argc = 1;
1460 while (argv[argc])
1461 argc++;
1462 rc = kmk_builtin_command_parsed (argc, argv, child, &argv_spawn, &child->pid);
1463 }
1464
1465# ifndef VMS
1466 free (argv[0]);
1467 free ((char *) argv);
1468# endif
1469
1470 if (!rc)
1471 {
1472 /* spawned a child? */
1473 if (child->pid)
1474 {
1475 ++job_counter;
1476 return;
1477 }
1478
1479 /* synchronous command execution? */
1480 if (!argv_spawn)
1481 goto next_command;
1482 }
1483
1484 /* failure? */
1485 if (rc)
1486 {
1487 child->pid = (pid_t)42424242;
1488 child->status = rc << 8;
1489 child->has_status = 1;
1490 unblock_sigs();
1491 return;
1492 }
1493
1494 /* conditional check == true; kicking off a child (not kmk_builtin_*). */
1495 argv = argv_spawn;
1496 }
1497#endif /* CONFIG_WITH_KMK_BUILTIN */
1498
1499 /* We're sure we're going to invoke a command: set up the output. */
1500 output_start ();
1501
1502 /* Flush the output streams so they won't have things written twice. */
1503
1504 fflush (stdout);
1505 fflush (stderr);
1506
1507 /* Decide whether to give this child the 'good' standard input
1508 (one that points to the terminal or whatever), or the 'bad' one
1509 that points to the read side of a broken pipe. */
1510
1511 child->good_stdin = !good_stdin_used;
1512 if (child->good_stdin)
1513 good_stdin_used = 1;
1514
1515 child->deleted = 0;
1516
1517#ifndef _AMIGA
1518 /* Set up the environment for the child. */
1519 if (child->environment == 0)
1520 child->environment = target_environment (child->file);
1521#endif
1522
1523#if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1524
1525#ifndef VMS
1526 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1527 if (child->remote)
1528 {
1529 int is_remote, id, used_stdin;
1530 if (start_remote_job (argv, child->environment,
1531 child->good_stdin ? 0 : get_bad_stdin (),
1532 &is_remote, &id, &used_stdin))
1533 /* Don't give up; remote execution may fail for various reasons. If
1534 so, simply run the job locally. */
1535 goto run_local;
1536 else
1537 {
1538 if (child->good_stdin && !used_stdin)
1539 {
1540 child->good_stdin = 0;
1541 good_stdin_used = 0;
1542 }
1543 child->remote = is_remote;
1544 child->pid = id;
1545 }
1546 }
1547 else
1548#endif /* !VMS */
1549 {
1550 /* Fork the child process. */
1551
1552 char **parent_environ;
1553
1554 run_local:
1555 block_sigs ();
1556
1557 child->remote = 0;
1558
1559#ifdef VMS
1560 if (!child_execute_job (child, argv))
1561 {
1562 /* Fork failed! */
1563 perror_with_name ("fork", "");
1564 goto error;
1565 }
1566
1567#else
1568
1569 parent_environ = environ;
1570
1571 jobserver_pre_child (flags & COMMANDS_RECURSE);
1572
1573 child->pid = child_execute_job (&child->output, child->good_stdin, argv, child->environment);
1574
1575 environ = parent_environ; /* Restore value child may have clobbered. */
1576 jobserver_post_child (flags & COMMANDS_RECURSE);
1577
1578 if (child->pid < 0)
1579 {
1580 /* Fork failed! */
1581 unblock_sigs ();
1582 perror_with_name ("fork", "");
1583 goto error;
1584 }
1585#endif /* !VMS */
1586 }
1587
1588#else /* __MSDOS__ or Amiga or WINDOWS32 */
1589#ifdef __MSDOS__
1590 {
1591 int proc_return;
1592
1593 block_sigs ();
1594 dos_status = 0;
1595
1596 /* We call 'system' to do the job of the SHELL, since stock DOS
1597 shell is too dumb. Our 'system' knows how to handle long
1598 command lines even if pipes/redirection is needed; it will only
1599 call COMMAND.COM when its internal commands are used. */
1600 if (execute_by_shell)
1601 {
1602 char *cmdline = argv[0];
1603 /* We don't have a way to pass environment to 'system',
1604 so we need to save and restore ours, sigh... */
1605 char **parent_environ = environ;
1606
1607 environ = child->environment;
1608
1609 /* If we have a *real* shell, tell 'system' to call
1610 it to do everything for us. */
1611 if (unixy_shell)
1612 {
1613 /* A *real* shell on MSDOS may not support long
1614 command lines the DJGPP way, so we must use 'system'. */
1615 cmdline = argv[2]; /* get past "shell -c" */
1616 }
1617
1618 dos_command_running = 1;
1619 proc_return = system (cmdline);
1620 environ = parent_environ;
1621 execute_by_shell = 0; /* for the next time */
1622 }
1623 else
1624 {
1625 dos_command_running = 1;
1626 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1627 }
1628
1629 /* Need to unblock signals before turning off
1630 dos_command_running, so that child's signals
1631 will be treated as such (see fatal_error_signal). */
1632 unblock_sigs ();
1633 dos_command_running = 0;
1634
1635 /* If the child got a signal, dos_status has its
1636 high 8 bits set, so be careful not to alter them. */
1637 if (proc_return == -1)
1638 dos_status |= 0xff;
1639 else
1640 dos_status |= (proc_return & 0xff);
1641 ++dead_children;
1642 child->pid = dos_pid++;
1643 }
1644#endif /* __MSDOS__ */
1645#ifdef _AMIGA
1646 amiga_status = MyExecute (argv);
1647
1648 ++dead_children;
1649 child->pid = amiga_pid++;
1650 if (amiga_batch_file)
1651 {
1652 amiga_batch_file = 0;
1653 DeleteFile (amiga_bname); /* Ignore errors. */
1654 }
1655#endif /* Amiga */
1656#ifdef WINDOWS32
1657 {
1658 HANDLE hPID;
1659 char* arg0;
1660 int outfd = FD_STDOUT;
1661 int errfd = FD_STDERR;
1662
1663 /* make UNC paths safe for CreateProcess -- backslash format */
1664 arg0 = argv[0];
1665 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1666 for ( ; arg0 && *arg0; arg0++)
1667 if (*arg0 == '/')
1668 *arg0 = '\\';
1669
1670 /* make sure CreateProcess() has Path it needs */
1671 sync_Path_environment ();
1672
1673#ifndef NO_OUTPUT_SYNC
1674 /* Divert child output if output_sync in use. */
1675 if (child->output.syncout)
1676 {
1677 if (child->output.out >= 0)
1678 outfd = child->output.out;
1679 if (child->output.err >= 0)
1680 errfd = child->output.err;
1681 }
1682#else
1683 outfd = errfd = -1;
1684#endif
1685 hPID = process_easy (argv, child->environment, outfd, errfd);
1686
1687 if (hPID != INVALID_HANDLE_VALUE)
1688 child->pid = (pid_t) hPID;
1689 else
1690 {
1691 int i;
1692 unblock_sigs ();
1693 fprintf (stderr,
1694 _("process_easy() failed to launch process (e=%ld)\n"),
1695 process_last_err (hPID));
1696 for (i = 0; argv[i]; i++)
1697 fprintf (stderr, "%s ", argv[i]);
1698 fprintf (stderr, _("\nCounted %d args in failed launch\n"), i);
1699 goto error;
1700 }
1701 }
1702#endif /* WINDOWS32 */
1703#endif /* __MSDOS__ or Amiga or WINDOWS32 */
1704
1705 /* Bump the number of jobs started in this second. */
1706 ++job_counter;
1707
1708 /* We are the parent side. Set the state to
1709 say the commands are running and return. */
1710
1711 set_command_state (child->file, cs_running);
1712
1713 /* Free the storage used by the child's argument list. */
1714#ifdef KMK /* leak */
1715 cleanup_argv:
1716#endif
1717#ifndef VMS
1718 free (argv[0]);
1719 free (argv);
1720#endif
1721
1722 OUTPUT_UNSET();
1723 return;
1724
1725 error:
1726 child->file->update_status = us_failed;
1727 notice_finished_file (child->file);
1728#ifdef KMK /* fix leak */
1729 goto cleanup_argv;
1730#else
1731 OUTPUT_UNSET();
1732#endif
1733}
1734
1735/* Try to start a child running.
1736 Returns nonzero if the child was started (and maybe finished), or zero if
1737 the load was too high and the child was put on the 'waiting_jobs' chain. */
1738
1739static int
1740start_waiting_job (struct child *c)
1741{
1742 struct file *f = c->file;
1743#ifdef DB_KMK
1744 DB (DB_KMK, (_("start_waiting_job %p (`%s') command_flags=%#x slots=%d/%d\n"),
1745 (void *)c, c->file->name, c->file->command_flags, job_slots_used, job_slots));
1746#endif
1747
1748 /* If we can start a job remotely, we always want to, and don't care about
1749 the local load average. We record that the job should be started
1750 remotely in C->remote for start_job_command to test. */
1751
1752 c->remote = start_remote_job_p (1);
1753
1754#ifdef CONFIG_WITH_EXTENDED_NOTPARALLEL
1755 if (c->file->command_flags & COMMANDS_NOTPARALLEL)
1756 {
1757 DB (DB_KMK, (_("not_parallel %d -> %d (file=%p `%s') [start_waiting_job]\n"),
1758 not_parallel, not_parallel + 1, (void *)c->file, c->file->name));
1759 assert(not_parallel >= 0);
1760 ++not_parallel;
1761 }
1762#endif /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
1763
1764 /* If we are running at least one job already and the load average
1765 is too high, make this one wait. */
1766 if (!c->remote
1767#ifdef CONFIG_WITH_EXTENDED_NOTPARALLEL
1768 && ((job_slots_used > 0 && (not_parallel > 0 || load_too_high ()))
1769#else
1770 && ((job_slots_used > 0 && load_too_high ())
1771#endif
1772#ifdef WINDOWS32
1773 || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
1774#endif
1775 ))
1776 {
1777#ifndef CONFIG_WITH_EXTENDED_NOTPARALLEL
1778 /* Put this child on the chain of children waiting for the load average
1779 to go down. */
1780 set_command_state (f, cs_running);
1781 c->next = waiting_jobs;
1782 waiting_jobs = c;
1783
1784#else /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
1785
1786 /* Put this child on the chain of children waiting for the load average
1787 to go down. If not parallel, put it last. */
1788 set_command_state (f, cs_running);
1789 c->next = waiting_jobs;
1790 if (c->next && (c->file->command_flags & COMMANDS_NOTPARALLEL))
1791 {
1792 struct child *prev = waiting_jobs;
1793 while (prev->next)
1794 prev = prev->next;
1795 c->next = 0;
1796 prev->next = c;
1797 }
1798 else /* FIXME: insert after the last node with COMMANDS_NOTPARALLEL set */
1799 waiting_jobs = c;
1800 DB (DB_KMK, (_("queued child %p (`%s')\n"), (void *)c, c->file->name));
1801#endif /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
1802 return 0;
1803 }
1804
1805 /* Start the first command; reap_children will run later command lines. */
1806 start_job_command (c);
1807
1808 switch (f->command_state)
1809 {
1810 case cs_running:
1811 c->next = children;
1812 DB (DB_JOBS, (_("Putting child %p (%s) PID %s%s on the chain.\n"),
1813 (void *)c, c->file->name, pid2str (c->pid),
1814 c->remote ? _(" (remote)") : ""));
1815 children = c;
1816 /* One more job slot is in use. */
1817 ++job_slots_used;
1818 unblock_sigs ();
1819 break;
1820
1821 case cs_not_started:
1822 /* All the command lines turned out to be empty. */
1823 f->update_status = us_success;
1824 /* FALLTHROUGH */
1825
1826 case cs_finished:
1827 notice_finished_file (f);
1828 free_child (c);
1829 break;
1830
1831 default:
1832 assert (f->command_state == cs_finished);
1833 break;
1834 }
1835
1836 return 1;
1837}
1838
1839/* Create a 'struct child' for FILE and start its commands running. */
1840
1841void
1842new_job (struct file *file)
1843{
1844 struct commands *cmds = file->cmds;
1845 struct child *c;
1846 char **lines;
1847 unsigned int i;
1848
1849 /* Let any previously decided-upon jobs that are waiting
1850 for the load to go down start before this new one. */
1851 start_waiting_jobs ();
1852
1853 /* Reap any children that might have finished recently. */
1854 reap_children (0, 0);
1855
1856 /* Chop the commands up into lines if they aren't already. */
1857 chop_commands (cmds);
1858#ifdef CONFIG_WITH_MEMORY_OPTIMIZATIONS
1859 cmds->refs++; /* retain the chopped lines. */
1860#endif
1861
1862 /* Start the command sequence, record it in a new
1863 'struct child', and add that to the chain. */
1864
1865 c = xcalloc (sizeof (struct child));
1866 output_init (&c->output);
1867
1868 c->file = file;
1869 c->sh_batch_file = NULL;
1870
1871 /* Cache dontcare flag because file->dontcare can be changed once we
1872 return. Check dontcare inheritance mechanism for details. */
1873 c->dontcare = file->dontcare;
1874
1875 /* Start saving output in case the expansion uses $(info ...) etc. */
1876 OUTPUT_SET (&c->output);
1877
1878 /* Expand the command lines and store the results in LINES. */
1879 lines = xmalloc (cmds->ncommand_lines * sizeof (char *));
1880 for (i = 0; i < cmds->ncommand_lines; ++i)
1881 {
1882 /* Collapse backslash-newline combinations that are inside variable
1883 or function references. These are left alone by the parser so
1884 that they will appear in the echoing of commands (where they look
1885 nice); and collapsed by construct_command_argv when it tokenizes.
1886 But letting them survive inside function invocations loses because
1887 we don't want the functions to see them as part of the text. */
1888
1889 char *in, *out, *ref;
1890
1891 /* IN points to where in the line we are scanning.
1892 OUT points to where in the line we are writing.
1893 When we collapse a backslash-newline combination,
1894 IN gets ahead of OUT. */
1895
1896 in = out = cmds->command_lines[i];
1897 while ((ref = strchr (in, '$')) != 0)
1898 {
1899 ++ref; /* Move past the $. */
1900
1901 if (out != in)
1902 /* Copy the text between the end of the last chunk
1903 we processed (where IN points) and the new chunk
1904 we are about to process (where REF points). */
1905 memmove (out, in, ref - in);
1906
1907 /* Move both pointers past the boring stuff. */
1908 out += ref - in;
1909 in = ref;
1910
1911 if (*ref == '(' || *ref == '{')
1912 {
1913 char openparen = *ref;
1914 char closeparen = openparen == '(' ? ')' : '}';
1915 char *outref;
1916 int count;
1917 char *p;
1918
1919 *out++ = *in++; /* Copy OPENPAREN. */
1920 outref = out;
1921 /* IN now points past the opening paren or brace.
1922 Count parens or braces until it is matched. */
1923 count = 0;
1924 while (*in != '\0')
1925 {
1926 if (*in == closeparen && --count < 0)
1927 break;
1928 else if (*in == '\\' && in[1] == '\n')
1929 {
1930 /* We have found a backslash-newline inside a
1931 variable or function reference. Eat it and
1932 any following whitespace. */
1933
1934 int quoted = 0;
1935 for (p = in - 1; p > ref && *p == '\\'; --p)
1936 quoted = !quoted;
1937
1938 if (quoted)
1939 /* There were two or more backslashes, so this is
1940 not really a continuation line. We don't collapse
1941 the quoting backslashes here as is done in
1942 collapse_continuations, because the line will
1943 be collapsed again after expansion. */
1944 *out++ = *in++;
1945 else
1946 {
1947 /* Skip the backslash, newline, and whitespace. */
1948 in += 2;
1949 NEXT_TOKEN (in);
1950
1951 /* Discard any preceding whitespace that has
1952 already been written to the output. */
1953 while (out > outref && ISBLANK (out[-1]))
1954 --out;
1955
1956 /* Replace it all with a single space. */
1957 *out++ = ' ';
1958 }
1959 }
1960 else
1961 {
1962 if (*in == openparen)
1963 ++count;
1964
1965 *out++ = *in++;
1966 }
1967 }
1968 }
1969 }
1970
1971 /* There are no more references in this line to worry about.
1972 Copy the remaining uninteresting text to the output. */
1973 if (out != in)
1974 memmove (out, in, strlen (in) + 1);
1975
1976 /* Finally, expand the line. */
1977 cmds->fileinfo.offset = i;
1978 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1979 file);
1980 }
1981
1982 cmds->fileinfo.offset = 0;
1983 c->command_lines = lines;
1984#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
1985 c->start_ts = -1;
1986#endif
1987
1988 /* Fetch the first command line to be run. */
1989 job_next_command (c);
1990
1991 /* Wait for a job slot to be freed up. If we allow an infinite number
1992 don't bother; also job_slots will == 0 if we're using the jobserver. */
1993
1994 if (job_slots != 0)
1995 while (job_slots_used == job_slots)
1996 reap_children (1, 0);
1997
1998#ifdef MAKE_JOBSERVER
1999 /* If we are controlling multiple jobs make sure we have a token before
2000 starting the child. */
2001
2002 /* This can be inefficient. There's a decent chance that this job won't
2003 actually have to run any subprocesses: the command script may be empty
2004 or otherwise optimized away. It would be nice if we could defer
2005 obtaining a token until just before we need it, in start_job_command.
2006 To do that we'd need to keep track of whether we'd already obtained a
2007 token (since start_job_command is called for each line of the job, not
2008 just once). Also more thought needs to go into the entire algorithm;
2009 this is where the old parallel job code waits, so... */
2010
2011 else if (jobserver_enabled ())
2012 while (1)
2013 {
2014 int got_token;
2015
2016 DB (DB_JOBS, ("Need a job token; we %shave children\n",
2017 children ? "" : "don't "));
2018
2019 /* If we don't already have a job started, use our "free" token. */
2020 if (!jobserver_tokens)
2021 break;
2022
2023 /* Prepare for jobserver token acquisition. */
2024 jobserver_pre_acquire ();
2025
2026 /* Reap anything that's currently waiting. */
2027 reap_children (0, 0);
2028
2029 /* Kick off any jobs we have waiting for an opportunity that
2030 can run now (i.e., waiting for load). */
2031 start_waiting_jobs ();
2032
2033 /* If our "free" slot is available, use it; we don't need a token. */
2034 if (!jobserver_tokens)
2035 break;
2036
2037 /* There must be at least one child already, or we have no business
2038 waiting for a token. */
2039 if (!children)
2040 O (fatal, NILF, "INTERNAL: no children as we go to sleep on read\n");
2041
2042 /* Get a token. */
2043 got_token = jobserver_acquire (waiting_jobs != NULL);
2044
2045 /* If we got one, we're done here. */
2046 if (got_token == 1)
2047 {
2048 DB (DB_JOBS, (_("Obtained token for child %p (%s).\n"),
2049 (void *)c, c->file->name));
2050 break;
2051 }
2052 }
2053#endif
2054
2055 ++jobserver_tokens;
2056
2057 /* Trace the build.
2058 Use message here so that changes to working directories are logged. */
2059 if (trace_flag)
2060 {
2061 char *newer = allocated_variable_expand_for_file ("$?", c->file);
2062 const char *nm;
2063
2064 if (! cmds->fileinfo.filenm)
2065 nm = _("<builtin>");
2066 else
2067 {
2068 char *n = alloca (strlen (cmds->fileinfo.filenm) + 1 + 11 + 1);
2069 sprintf (n, "%s:%lu", cmds->fileinfo.filenm, cmds->fileinfo.lineno);
2070 nm = n;
2071 }
2072
2073 if (newer[0] == '\0')
2074 OSS (message, 0,
2075 _("%s: target '%s' does not exist"), nm, c->file->name);
2076 else
2077 OSSS (message, 0,
2078 _("%s: update target '%s' due to: %s"), nm, c->file->name, newer);
2079
2080 free (newer);
2081 }
2082
2083 /* The job is now primed. Start it running.
2084 (This will notice if there is in fact no recipe.) */
2085 start_waiting_job (c);
2086
2087#ifndef CONFIG_WITH_EXTENDED_NOTPARALLEL
2088 if (job_slots == 1 || not_parallel)
2089 /* Since there is only one job slot, make things run linearly.
2090 Wait for the child to die, setting the state to 'cs_finished'. */
2091 while (file->command_state == cs_running)
2092 reap_children (1, 0);
2093
2094#else /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
2095
2096 if (job_slots == 1 || not_parallel < 0)
2097 {
2098 /* Since there is only one job slot, make things run linearly.
2099 Wait for the child to die, setting the state to `cs_finished'. */
2100 while (file->command_state == cs_running)
2101 reap_children (1, 0);
2102 }
2103 else if (not_parallel > 0)
2104 {
2105 /* wait for all live children to finish and then continue
2106 with the not-parallel child(s). FIXME: this loop could be better? */
2107 while (file->command_state == cs_running
2108 && (children != 0 || shell_function_pid != 0) /* reap_child condition */
2109 && not_parallel > 0)
2110 reap_children (1, 0);
2111 }
2112#endif /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
2113
2114 OUTPUT_UNSET ();
2115 return;
2116}
2117
2118
2119/* Move CHILD's pointers to the next command for it to execute.
2120 Returns nonzero if there is another command. */
2121
2122static int
2123job_next_command (struct child *child)
2124{
2125 while (child->command_ptr == 0 || *child->command_ptr == '\0')
2126 {
2127 /* There are no more lines in the expansion of this line. */
2128 if (child->command_line == child->file->cmds->ncommand_lines)
2129 {
2130 /* There are no more lines to be expanded. */
2131 child->command_ptr = 0;
2132 child->file->cmds->fileinfo.offset = 0;
2133 return 0;
2134 }
2135 else
2136 /* Get the next line to run. */
2137 child->command_ptr = child->command_lines[child->command_line++];
2138 }
2139
2140 child->file->cmds->fileinfo.offset = child->command_line - 1;
2141 return 1;
2142}
2143
2144/* Determine if the load average on the system is too high to start a new job.
2145 The real system load average is only recomputed once a second. However, a
2146 very parallel make can easily start tens or even hundreds of jobs in a
2147 second, which brings the system to its knees for a while until that first
2148 batch of jobs clears out.
2149
2150 To avoid this we use a weighted algorithm to try to account for jobs which
2151 have been started since the last second, and guess what the load average
2152 would be now if it were computed.
2153
2154 This algorithm was provided by Thomas Riedl <[email protected]>,
2155 who writes:
2156
2157! calculate something load-oid and add to the observed sys.load,
2158! so that latter can catch up:
2159! - every job started increases jobctr;
2160! - every dying job decreases a positive jobctr;
2161! - the jobctr value gets zeroed every change of seconds,
2162! after its value*weight_b is stored into the 'backlog' value last_sec
2163! - weight_a times the sum of jobctr and last_sec gets
2164! added to the observed sys.load.
2165!
2166! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
2167! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
2168! sub-shelled commands (rm, echo, sed...) for tests.
2169! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
2170! resulted in significant excession of the load limit, raising it
2171! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
2172! reach the limit in most test cases.
2173!
2174! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
2175! exceeding the limit for longer-running stuff (compile jobs in
2176! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
2177! small jobs' effects.
2178
2179 */
2180
2181#define LOAD_WEIGHT_A 0.25
2182#define LOAD_WEIGHT_B 0.25
2183
2184static int
2185load_too_high (void)
2186{
2187#if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__) || defined(__HAIKU__)
2188 return 1;
2189#else
2190 static double last_sec;
2191 static time_t last_now;
2192 double load, guess;
2193 time_t now;
2194
2195#ifdef WINDOWS32
2196 /* sub_proc.c cannot wait for more than MAXIMUM_WAIT_OBJECTS children */
2197 if (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
2198 return 1;
2199#endif
2200
2201 if (max_load_average < 0)
2202 return 0;
2203
2204 /* Find the real system load average. */
2205 make_access ();
2206 if (getloadavg (&load, 1) != 1)
2207 {
2208 static int lossage = -1;
2209 /* Complain only once for the same error. */
2210 if (lossage == -1 || errno != lossage)
2211 {
2212 if (errno == 0)
2213 /* An errno value of zero means getloadavg is just unsupported. */
2214 O (error, NILF,
2215 _("cannot enforce load limits on this operating system"));
2216 else
2217 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
2218 }
2219 lossage = errno;
2220 load = 0;
2221 }
2222 user_access ();
2223
2224 /* If we're in a new second zero the counter and correct the backlog
2225 value. Only keep the backlog for one extra second; after that it's 0. */
2226 now = time (NULL);
2227 if (last_now < now)
2228 {
2229 if (last_now == now - 1)
2230 last_sec = LOAD_WEIGHT_B * job_counter;
2231 else
2232 last_sec = 0.0;
2233
2234 job_counter = 0;
2235 last_now = now;
2236 }
2237
2238 /* Try to guess what the load would be right now. */
2239 guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
2240
2241 DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
2242 guess, load, max_load_average));
2243
2244 return guess >= max_load_average;
2245#endif
2246}
2247
2248/* Start jobs that are waiting for the load to be lower. */
2249
2250void
2251start_waiting_jobs (void)
2252{
2253 struct child *job;
2254
2255 if (waiting_jobs == 0)
2256 return;
2257
2258 do
2259 {
2260 /* Check for recently deceased descendants. */
2261 reap_children (0, 0);
2262
2263 /* Take a job off the waiting list. */
2264 job = waiting_jobs;
2265 waiting_jobs = job->next;
2266
2267#ifdef CONFIG_WITH_EXTENDED_NOTPARALLEL
2268 /* If it's a not-parallel job, we've already counted it once
2269 when it was queued in start_waiting_job, so decrement
2270 before sending it to start_waiting_job again. */
2271 if (job->file->command_flags & COMMANDS_NOTPARALLEL)
2272 {
2273 DB (DB_KMK, (_("not_parallel %d -> %d (file=%p `%s') [start_waiting_jobs]\n"),
2274 not_parallel, not_parallel - 1, (void *) job->file, job->file->name));
2275 assert(not_parallel > 0);
2276 --not_parallel;
2277 }
2278#endif /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
2279
2280 /* Try to start that job. We break out of the loop as soon
2281 as start_waiting_job puts one back on the waiting list. */
2282 }
2283 while (start_waiting_job (job) && waiting_jobs != 0);
2284
2285 return;
2286}
2287
2288
2289#ifndef WINDOWS32
2290
2291/* EMX: Start a child process. This function returns the new pid. */
2292# if defined __EMX__
2293int
2294child_execute_job (struct output *out, int good_stdin, char **argv, char **envp)
2295{
2296 int pid;
2297 int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
2298 int fdout = FD_STDOUT;
2299 int fderr = FD_STDERR;
2300 int save_fdin = -1;
2301 int save_fdout = -1;
2302 int save_fderr = -1;
2303
2304 /* Divert child output if we want to capture output. */
2305 if (out && out->syncout)
2306 {
2307 if (out->out >= 0)
2308 fdout = out->out;
2309 if (out->err >= 0)
2310 fderr = out->err;
2311 }
2312
2313 /* For each FD which needs to be redirected first make a dup of the standard
2314 FD to save and mark it close on exec so our child won't see it. Then
2315 dup2() the standard FD to the redirect FD, and also mark the redirect FD
2316 as close on exec. */
2317 if (fdin != FD_STDIN)
2318 {
2319 save_fdin = dup (FD_STDIN);
2320 if (save_fdin < 0)
2321 O (fatal, NILF, _("no more file handles: could not duplicate stdin\n"));
2322 CLOSE_ON_EXEC (save_fdin);
2323
2324 dup2 (fdin, FD_STDIN);
2325 CLOSE_ON_EXEC (fdin);
2326 }
2327
2328 if (fdout != FD_STDOUT)
2329 {
2330 save_fdout = dup (FD_STDOUT);
2331 if (save_fdout < 0)
2332 O (fatal, NILF,
2333 _("no more file handles: could not duplicate stdout\n"));
2334 CLOSE_ON_EXEC (save_fdout);
2335
2336 dup2 (fdout, FD_STDOUT);
2337 CLOSE_ON_EXEC (fdout);
2338 }
2339
2340 if (fderr != FD_STDERR)
2341 {
2342 if (fderr != fdout)
2343 {
2344 save_fderr = dup (FD_STDERR);
2345 if (save_fderr < 0)
2346 O (fatal, NILF,
2347 _("no more file handles: could not duplicate stderr\n"));
2348 CLOSE_ON_EXEC (save_fderr);
2349 }
2350
2351 dup2 (fderr, FD_STDERR);
2352 CLOSE_ON_EXEC (fderr);
2353 }
2354
2355 /* Run the command. */
2356 pid = exec_command (argv, envp);
2357
2358 /* Restore stdout/stdin/stderr of the parent and close temporary FDs. */
2359 if (save_fdin >= 0)
2360 {
2361 if (dup2 (save_fdin, FD_STDIN) != FD_STDIN)
2362 O (fatal, NILF, _("Could not restore stdin\n"));
2363 else
2364 close (save_fdin);
2365 }
2366
2367 if (save_fdout >= 0)
2368 {
2369 if (dup2 (save_fdout, FD_STDOUT) != FD_STDOUT)
2370 O (fatal, NILF, _("Could not restore stdout\n"));
2371 else
2372 close (save_fdout);
2373 }
2374
2375 if (save_fderr >= 0)
2376 {
2377 if (dup2 (save_fderr, FD_STDERR) != FD_STDERR)
2378 O (fatal, NILF, _("Could not restore stderr\n"));
2379 else
2380 close (save_fderr);
2381 }
2382
2383 return pid;
2384}
2385
2386#elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
2387
2388/* POSIX:
2389 Create a child process executing the command in ARGV.
2390 ENVP is the environment of the new program. Returns the PID or -1. */
2391int
2392child_execute_job (struct output *out, int good_stdin, char **argv, char **envp)
2393{
2394 int r;
2395 int pid;
2396 int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
2397 int fdout = FD_STDOUT;
2398 int fderr = FD_STDERR;
2399
2400 /* Divert child output if we want to capture it. */
2401 if (out && out->syncout)
2402 {
2403 if (out->out >= 0)
2404 fdout = out->out;
2405 if (out->err >= 0)
2406 fderr = out->err;
2407 }
2408
2409 pid = vfork();
2410 if (pid != 0)
2411 return pid;
2412
2413 /* We are the child. */
2414 unblock_sigs ();
2415
2416#ifdef SET_STACK_SIZE
2417 /* Reset limits, if necessary. */
2418 if (stack_limit.rlim_cur)
2419 setrlimit (RLIMIT_STACK, &stack_limit);
2420#endif
2421
2422 /* For any redirected FD, dup2() it to the standard FD.
2423 They are all marked close-on-exec already. */
2424 if (fdin != FD_STDIN)
2425 EINTRLOOP (r, dup2 (fdin, FD_STDIN));
2426 if (fdout != FD_STDOUT)
2427 EINTRLOOP (r, dup2 (fdout, FD_STDOUT));
2428 if (fderr != FD_STDERR)
2429 EINTRLOOP (r, dup2 (fderr, FD_STDERR));
2430
2431 /* Run the command. */
2432 exec_command (argv, envp);
2433}
2434#endif /* !AMIGA && !__MSDOS__ && !VMS */
2435#endif /* !WINDOWS32 */
2436
2437
2438#ifndef _AMIGA
2439/* Replace the current process with one running the command in ARGV,
2440 with environment ENVP. This function does not return. */
2441
2442/* EMX: This function returns the pid of the child process. */
2443# ifdef __EMX__
2444int
2445# else
2446void
2447# endif
2448exec_command (char **argv, char **envp)
2449{
2450#ifdef VMS
2451 /* to work around a problem with signals and execve: ignore them */
2452#ifdef SIGCHLD
2453 signal (SIGCHLD,SIG_IGN);
2454#endif
2455 /* Run the program. */
2456 execve (argv[0], argv, envp);
2457 perror_with_name ("execve: ", argv[0]);
2458 _exit (EXIT_FAILURE);
2459#else
2460#ifdef WINDOWS32
2461 HANDLE hPID;
2462 HANDLE hWaitPID;
2463 int exit_code = EXIT_FAILURE;
2464
2465 /* make sure CreateProcess() has Path it needs */
2466 sync_Path_environment ();
2467
2468 /* launch command */
2469 hPID = process_easy (argv, envp, -1, -1);
2470
2471 /* make sure launch ok */
2472 if (hPID == INVALID_HANDLE_VALUE)
2473 {
2474 int i;
2475 fprintf (stderr, _("process_easy() failed to launch process (e=%ld)\n"),
2476 process_last_err (hPID));
2477 for (i = 0; argv[i]; i++)
2478 fprintf (stderr, "%s ", argv[i]);
2479 fprintf (stderr, _("\nCounted %d args in failed launch\n"), i);
2480 exit (EXIT_FAILURE);
2481 }
2482
2483 /* wait and reap last child */
2484 hWaitPID = process_wait_for_any (1, 0);
2485 while (hWaitPID)
2486 {
2487 /* was an error found on this process? */
2488 int err = process_last_err (hWaitPID);
2489
2490 /* get exit data */
2491 exit_code = process_exit_code (hWaitPID);
2492
2493 if (err)
2494 fprintf (stderr, "make (e=%d, rc=%d): %s",
2495 err, exit_code, map_windows32_error_to_string (err));
2496
2497 /* cleanup process */
2498 process_cleanup (hWaitPID);
2499
2500 /* expect to find only last pid, warn about other pids reaped */
2501 if (hWaitPID == hPID)
2502 break;
2503 else
2504 {
2505 char *pidstr = xstrdup (pid2str ((pid_t)hWaitPID));
2506
2507 fprintf (stderr,
2508 _("make reaped child pid %s, still waiting for pid %s\n"),
2509 pidstr, pid2str ((pid_t)hPID));
2510 free (pidstr);
2511 }
2512 }
2513
2514 /* return child's exit code as our exit code */
2515 exit (exit_code);
2516
2517#else /* !WINDOWS32 */
2518
2519# ifdef __EMX__
2520 int pid;
2521# endif
2522
2523 /* Be the user, permanently. */
2524 child_access ();
2525
2526# ifdef __EMX__
2527 /* Run the program. */
2528 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2529 if (pid >= 0)
2530 return pid;
2531
2532 /* the file might have a strange shell extension */
2533 if (errno == ENOENT)
2534 errno = ENOEXEC;
2535
2536# else
2537 /* Run the program. */
2538 environ = envp;
2539 execvp (argv[0], argv);
2540
2541# endif /* !__EMX__ */
2542
2543 switch (errno)
2544 {
2545 case ENOENT:
2546 /* We are in the child: don't use the output buffer.
2547 It's not right to run fprintf() here! */
2548 if (makelevel == 0)
2549 fprintf (stderr, _("%s: %s: Command not found\n"), program, argv[0]);
2550 else
2551 fprintf (stderr, _("%s[%u]: %s: Command not found\n"),
2552 program, makelevel, argv[0]);
2553 break;
2554 case ENOEXEC:
2555 {
2556 /* The file is not executable. Try it as a shell script. */
2557 const char *shell;
2558 char **new_argv;
2559 int argc;
2560 int i=1;
2561
2562# ifdef __EMX__
2563 /* Do not use $SHELL from the environment */
2564 struct variable *p = lookup_variable ("SHELL", 5);
2565 if (p)
2566 shell = p->value;
2567 else
2568 shell = 0;
2569# else
2570 shell = getenv ("SHELL");
2571# endif
2572 if (shell == 0)
2573 shell = default_shell;
2574
2575 argc = 1;
2576 while (argv[argc] != 0)
2577 ++argc;
2578
2579# ifdef __EMX__
2580 if (!unixy_shell)
2581 ++argc;
2582# endif
2583
2584 new_argv = alloca ((1 + argc + 1) * sizeof (char *));
2585 new_argv[0] = (char *)shell;
2586
2587# ifdef __EMX__
2588 if (!unixy_shell)
2589 {
2590 new_argv[1] = "/c";
2591 ++i;
2592 --argc;
2593 }
2594# endif
2595
2596 new_argv[i] = argv[0];
2597 while (argc > 0)
2598 {
2599 new_argv[i + argc] = argv[argc];
2600 --argc;
2601 }
2602
2603# ifdef __EMX__
2604 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2605 if (pid >= 0)
2606 break;
2607# else
2608 execvp (shell, new_argv);
2609# endif
2610 if (errno == ENOENT)
2611 OS (error, NILF, _("%s: Shell program not found"), shell);
2612 else
2613 perror_with_name ("execvp: ", shell);
2614 break;
2615 }
2616
2617# ifdef __EMX__
2618 case EINVAL:
2619 /* this nasty error was driving me nuts :-( */
2620 O (error, NILF, _("spawnvpe: environment space might be exhausted"));
2621 /* FALLTHROUGH */
2622# endif
2623
2624 default:
2625 perror_with_name ("execvp: ", argv[0]);
2626 break;
2627 }
2628
2629# ifdef __EMX__
2630 return pid;
2631# else
2632 _exit (127);
2633# endif
2634#endif /* !WINDOWS32 */
2635#endif /* !VMS */
2636}
2637#else /* On Amiga */
2638void
2639exec_command (char **argv)
2640{
2641 MyExecute (argv);
2642}
2643
2644void clean_tmp (void)
2645{
2646 DeleteFile (amiga_bname);
2647}
2648
2649#endif /* On Amiga */
2650
2651
2652#ifndef VMS
2653/* Figure out the argument list necessary to run LINE as a command. Try to
2654 avoid using a shell. This routine handles only ' quoting, and " quoting
2655 when no backslash, $ or ' characters are seen in the quotes. Starting
2656 quotes may be escaped with a backslash. If any of the characters in
2657 sh_chars is seen, or any of the builtin commands listed in sh_cmds
2658 is the first word of a line, the shell is used.
2659
2660 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2661 If *RESTP is NULL, newlines will be ignored.
2662
2663 SHELL is the shell to use, or nil to use the default shell.
2664 IFS is the value of $IFS, or nil (meaning the default).
2665
2666 FLAGS is the value of lines_flags for this command line. It is
2667 used in the WINDOWS32 port to check whether + or $(MAKE) were found
2668 in this command line, in which case the effect of just_print_flag
2669 is overridden. */
2670
2671static char **
2672construct_command_argv_internal (char *line, char **restp, const char *shell,
2673 const char *shellflags, const char *ifs,
2674 int flags, char **batch_filename UNUSED)
2675{
2676#ifdef __MSDOS__
2677 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2678 We call 'system' for anything that requires ''slow'' processing,
2679 because DOS shells are too dumb. When $SHELL points to a real
2680 (unix-style) shell, 'system' just calls it to do everything. When
2681 $SHELL points to a DOS shell, 'system' does most of the work
2682 internally, calling the shell only for its internal commands.
2683 However, it looks on the $PATH first, so you can e.g. have an
2684 external command named 'mkdir'.
2685
2686 Since we call 'system', certain characters and commands below are
2687 actually not specific to COMMAND.COM, but to the DJGPP implementation
2688 of 'system'. In particular:
2689
2690 The shell wildcard characters are in DOS_CHARS because they will
2691 not be expanded if we call the child via 'spawnXX'.
2692
2693 The ';' is in DOS_CHARS, because our 'system' knows how to run
2694 multiple commands on a single line.
2695
2696 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2697 won't have to tell one from another and have one more set of
2698 commands and special characters. */
2699 static const char *sh_chars_dos = "*?[];|<>%^&()";
2700 static const char *sh_cmds_dos[] =
2701 { "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty", "date",
2702 "del", "dir", "echo", "erase", "exit", "for", "goto", "if", "md",
2703 "mkdir", "path", "pause", "prompt", "rd", "rmdir", "rem", "ren",
2704 "rename", "set", "shift", "time", "type", "ver", "verify", "vol", ":",
2705 0 };
2706
2707 static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^";
2708 static const char *sh_cmds_sh[] =
2709 { "cd", "echo", "eval", "exec", "exit", "login", "logout", "set", "umask",
2710 "wait", "while", "for", "case", "if", ":", ".", "break", "continue",
2711 "export", "read", "readonly", "shift", "times", "trap", "switch",
2712 "unset", "ulimit", 0 };
2713
2714 const char *sh_chars;
2715 const char **sh_cmds;
2716
2717#elif defined (__EMX__)
2718 static const char *sh_chars_dos = "*?[];|<>%^&()";
2719 static const char *sh_cmds_dos[] =
2720 { "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty", "date",
2721 "del", "dir", "echo", "erase", "exit", "for", "goto", "if", "md",
2722 "mkdir", "path", "pause", "prompt", "rd", "rmdir", "rem", "ren",
2723 "rename", "set", "shift", "time", "type", "ver", "verify", "vol", ":",
2724 0 };
2725
2726 static const char *sh_chars_os2 = "*?[];|<>%^()\"'&";
2727 static const char *sh_cmds_os2[] =
2728 { "call", "cd", "chcp", "chdir", "cls", "copy", "date", "del", "detach",
2729 "dir", "echo", "endlocal", "erase", "exit", "for", "goto", "if", "keys",
2730 "md", "mkdir", "move", "path", "pause", "prompt", "rd", "rem", "ren",
2731 "rename", "rmdir", "set", "setlocal", "shift", "start", "time", "type",
2732 "ver", "verify", "vol", ":", 0 };
2733
2734 static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^~'";
2735 static const char *sh_cmds_sh[] =
2736 { "echo", "cd", "eval", "exec", "exit", "login", "logout", "set", "umask",
2737 "wait", "while", "for", "case", "if", ":", ".", "break", "continue",
2738 "export", "read", "readonly", "shift", "times", "trap", "switch",
2739 "unset", 0 };
2740
2741 const char *sh_chars;
2742 const char **sh_cmds;
2743
2744#elif defined (_AMIGA)
2745 static const char *sh_chars = "#;\"|<>()?*$`";
2746 static const char *sh_cmds[] =
2747 { "cd", "eval", "if", "delete", "echo", "copy", "rename", "set", "setenv",
2748 "date", "makedir", "skip", "else", "endif", "path", "prompt", "unset",
2749 "unsetenv", "version", 0 };
2750
2751#elif defined (WINDOWS32)
2752 /* We used to have a double quote (") in sh_chars_dos[] below, but
2753 that caused any command line with quoted file names be run
2754 through a temporary batch file, which introduces command-line
2755 limit of 4K charcaters imposed by cmd.exe. Since CreateProcess
2756 can handle quoted file names just fine, removing the quote lifts
2757 the limit from a very frequent use case, because using quoted
2758 file names is commonplace on MS-Windows. */
2759 static const char *sh_chars_dos = "|&<>";
2760 static const char *sh_cmds_dos[] =
2761 { "assoc", "break", "call", "cd", "chcp", "chdir", "cls", "color", "copy",
2762 "ctty", "date", "del", "dir", "echo", "echo.", "endlocal", "erase",
2763 "exit", "for", "ftype", "goto", "if", "if", "md", "mkdir", "move",
2764 "path", "pause", "prompt", "rd", "rem", "ren", "rename", "rmdir",
2765 "set", "setlocal", "shift", "time", "title", "type", "ver", "verify",
2766 "vol", ":", 0 };
2767
2768 static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^";
2769 static const char *sh_cmds_sh[] =
2770 { "cd", "eval", "exec", "exit", "login", "logout", "set", "umask", "wait",
2771 "while", "for", "case", "if", ":", ".", "break", "continue", "export",
2772 "read", "readonly", "shift", "times", "trap", "switch", "test",
2773#ifdef BATCH_MODE_ONLY_SHELL
2774 "echo",
2775#endif
2776 0 };
2777
2778 const char *sh_chars;
2779 const char **sh_cmds;
2780#elif defined(__riscos__)
2781 static const char *sh_chars = "";
2782 static const char *sh_cmds[] = { 0 };
2783#else /* must be UNIX-ish */
2784 static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^~!"; /* kmk: +_sh */
2785 static const char *sh_cmds_sh[] = /* kmk: +_sh */
2786 { ".", ":", "break", "case", "cd", "continue", "eval", "exec", "exit",
2787 "export", "for", "if", "login", "logout", "read", "readonly", "set",
2788 "shift", "switch", "test", "times", "trap", "ulimit", "umask", "unset",
2789 "wait", "while", 0 };
2790
2791# if 0 /*def HAVE_DOS_PATHS - kmk */
2792 /* This is required if the MSYS/Cygwin ports (which do not define
2793 WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
2794 sh_chars_sh directly (see below). The value must be identical
2795 to that of sh_chars immediately above. */
2796 static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^~!";
2797# endif /* HAVE_DOS_PATHS */
2798 char const * sh_chars = sh_chars_sh; /* kmk: +_sh +const */
2799 char const * const * sh_cmds = sh_cmds_sh; /* kmk: +_sh +const*2 */
2800#endif
2801#ifdef KMK
2802 static const char sh_chars_kash[] = "#;*?[]&|<>(){}$`^~!"; /* note: no \" - good idea? */
2803 static const char * const sh_cmds_kash[] = {
2804 ".", ":", "break", "case", "cd", "continue", "echo", "eval", "exec", "exit",
2805 "export", "for", "if", "login", "logout", "read", "readonly", "set",
2806 "shift", "switch", "test", "times", "trap", "umask", "wait", "while", 0 /* +echo, -ulimit, -unset */
2807 };
2808 int is_kmk_shell = 0;
2809#endif
2810 int i;
2811 char *p;
2812#ifndef NDEBUG
2813 char *end;
2814#endif
2815 char *ap;
2816 const char *cap;
2817 const char *cp;
2818 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2819 char **new_argv = 0;
2820 char *argstr = 0;
2821#ifdef WINDOWS32
2822 int slow_flag = 0;
2823
2824 if (!unixy_shell)
2825 {
2826 sh_cmds = sh_cmds_dos;
2827 sh_chars = sh_chars_dos;
2828 }
2829 else
2830 {
2831 sh_cmds = sh_cmds_sh;
2832 sh_chars = sh_chars_sh;
2833 }
2834#endif /* WINDOWS32 */
2835
2836 if (restp != NULL)
2837 *restp = NULL;
2838
2839 /* Make sure not to bother processing an empty line but stop at newline. */
2840 while (ISBLANK (*line))
2841 ++line;
2842 if (*line == '\0')
2843 return 0;
2844
2845 if (shellflags == 0)
2846 shellflags = posix_pedantic ? "-ec" : "-c";
2847
2848 /* See if it is safe to parse commands internally. */
2849#ifdef KMK /* kmk_ash and kmk_kash are both fine, kmk_ash is the default btw. */
2850 if (shell == 0)
2851 {
2852 is_kmk_shell = 1;
2853 shell = (char *)get_default_kbuild_shell ();
2854 }
2855 else if (!strcmp (shell, get_default_kbuild_shell()))
2856 is_kmk_shell = 1;
2857 else
2858 {
2859 const char *psz = strstr (shell, "/kmk_ash");
2860 if (psz)
2861 psz += sizeof ("/kmk_ash") - 1;
2862 else
2863 {
2864 psz = strstr (shell, "/kmk_kash");
2865 if (psz)
2866 psz += sizeof ("/kmk_kash") - 1;
2867 }
2868# if defined (__OS2__) || defined (_WIN32) || defined (WINDOWS32)
2869 is_kmk_shell = psz && (*psz == '\0' || !stricmp (psz, ".exe"));
2870# else
2871 is_kmk_shell = psz && *psz == '\0';
2872# endif
2873 }
2874 if (is_kmk_shell)
2875 {
2876 sh_chars = sh_chars_kash;
2877 sh_cmds = sh_cmds_kash;
2878 }
2879#else /* !KMK */
2880 if (shell == 0)
2881 shell = default_shell;
2882#endif /* !KMK */
2883#ifdef WINDOWS32
2884 else if (strcmp (shell, default_shell))
2885 {
2886 char *s1 = _fullpath (NULL, shell, 0);
2887 char *s2 = _fullpath (NULL, default_shell, 0);
2888
2889 slow_flag = strcmp ((s1 ? s1 : ""), (s2 ? s2 : ""));
2890
2891 free (s1);
2892 free (s2);
2893 }
2894 if (slow_flag)
2895 goto slow;
2896#else /* not WINDOWS32 */
2897#if defined (__MSDOS__) || defined (__EMX__)
2898 else if (strcasecmp (shell, default_shell))
2899 {
2900 extern int _is_unixy_shell (const char *_path);
2901
2902 DB (DB_BASIC, (_("$SHELL changed (was '%s', now '%s')\n"),
2903 default_shell, shell));
2904 unixy_shell = _is_unixy_shell (shell);
2905 /* we must allocate a copy of shell: construct_command_argv() will free
2906 * shell after this function returns. */
2907 default_shell = xstrdup (shell);
2908 }
2909# ifdef KMK
2910 if (is_kmk_shell)
2911 { /* done above already */ }
2912 else
2913# endif
2914 if (unixy_shell)
2915 {
2916 sh_chars = sh_chars_sh;
2917 sh_cmds = sh_cmds_sh;
2918 }
2919 else
2920 {
2921 sh_chars = sh_chars_dos;
2922 sh_cmds = sh_cmds_dos;
2923# ifdef __EMX__
2924 if (_osmode == OS2_MODE)
2925 {
2926 sh_chars = sh_chars_os2;
2927 sh_cmds = sh_cmds_os2;
2928 }
2929# endif
2930 }
2931#else /* !__MSDOS__ */
2932 else if (strcmp (shell, default_shell))
2933 goto slow;
2934#endif /* !__MSDOS__ && !__EMX__ */
2935#endif /* not WINDOWS32 */
2936
2937 if (ifs)
2938 for (cap = ifs; *cap != '\0'; ++cap)
2939 if (*cap != ' ' && *cap != '\t' && *cap != '\n')
2940 goto slow;
2941
2942 if (shellflags)
2943 if (shellflags[0] != '-'
2944 || ((shellflags[1] != 'c' || shellflags[2] != '\0')
2945 && (shellflags[1] != 'e' || shellflags[2] != 'c' || shellflags[3] != '\0')))
2946 goto slow;
2947
2948 i = strlen (line) + 1;
2949
2950 /* More than 1 arg per character is impossible. */
2951 new_argv = xmalloc (i * sizeof (char *));
2952
2953 /* All the args can fit in a buffer as big as LINE is. */
2954 ap = new_argv[0] = argstr = xmalloc (i);
2955#ifndef NDEBUG
2956 end = ap + i;
2957#endif
2958
2959 /* I is how many complete arguments have been found. */
2960 i = 0;
2961 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2962 for (p = line; *p != '\0'; ++p)
2963 {
2964 assert (ap <= end);
2965
2966 if (instring)
2967 {
2968 /* Inside a string, just copy any char except a closing quote
2969 or a backslash-newline combination. */
2970 if (*p == instring)
2971 {
2972 instring = 0;
2973 if (ap == new_argv[0] || *(ap-1) == '\0')
2974 last_argument_was_empty = 1;
2975 }
2976 else if (*p == '\\' && p[1] == '\n')
2977 {
2978 /* Backslash-newline is handled differently depending on what
2979 kind of string we're in: inside single-quoted strings you
2980 keep them; in double-quoted strings they disappear. For
2981 DOS/Windows/OS2, if we don't have a POSIX shell, we keep the
2982 pre-POSIX behavior of removing the backslash-newline. */
2983 if (instring == '"'
2984#if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2985 || !unixy_shell
2986#endif
2987 )
2988 ++p;
2989 else
2990 {
2991 *(ap++) = *(p++);
2992 *(ap++) = *p;
2993 }
2994 }
2995 else if (*p == '\n' && restp != NULL)
2996 {
2997 /* End of the command line. */
2998 *restp = p;
2999 goto end_of_line;
3000 }
3001 /* Backslash, $, and ` are special inside double quotes.
3002 If we see any of those, punt.
3003 But on MSDOS, if we use COMMAND.COM, double and single
3004 quotes have the same effect. */
3005 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
3006 goto slow;
3007#ifdef WINDOWS32
3008 /* Quoted wildcard characters must be passed quoted to the
3009 command, so give up the fast route. */
3010 else if (instring == '"' && strchr ("*?", *p) != 0 && !unixy_shell)
3011 goto slow;
3012 else if (instring == '"' && strncmp (p, "\\\"", 2) == 0)
3013 *ap++ = *++p;
3014#endif
3015 else
3016 *ap++ = *p;
3017 }
3018 else if (strchr (sh_chars, *p) != 0)
3019#ifdef KMK
3020 {
3021 /* Tilde is only special if at the start of a path spec,
3022 i.e. don't get excited when we by 8.3 files on windows. */
3023 if ( *p == '~'
3024 && p > line
3025 && !ISSPACE (p[-1])
3026 && p[-1] != '='
3027 && p[-1] != ':'
3028 && p[-1] != '"'
3029 && p[-1] != '\'')
3030 *ap++ = *p;
3031 else
3032 /* Not inside a string, but it's a special char. */
3033 goto slow;
3034 }
3035#else /* !KMK */
3036 /* Not inside a string, but it's a special char. */
3037 goto slow;
3038#endif /* !KMK */
3039 else if (one_shell && *p == '\n')
3040 /* In .ONESHELL mode \n is a separator like ; or && */
3041 goto slow;
3042#ifdef __MSDOS__
3043 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
3044 /* '...' is a wildcard in DJGPP. */
3045 goto slow;
3046#endif
3047 else
3048 /* Not a special char. */
3049 switch (*p)
3050 {
3051 case '=':
3052 /* Equals is a special character in leading words before the
3053 first word with no equals sign in it. This is not the case
3054 with sh -k, but we never get here when using nonstandard
3055 shell flags. */
3056 if (! seen_nonequals && unixy_shell)
3057 goto slow;
3058 word_has_equals = 1;
3059 *ap++ = '=';
3060 break;
3061
3062 case '\\':
3063 /* Backslash-newline has special case handling, ref POSIX.
3064 We're in the fastpath, so emulate what the shell would do. */
3065 if (p[1] == '\n')
3066 {
3067 /* Throw out the backslash and newline. */
3068 ++p;
3069
3070 /* At the beginning of the argument, skip any whitespace other
3071 than newline before the start of the next word. */
3072 if (ap == new_argv[i])
3073 while (ISBLANK (p[1]))
3074 ++p;
3075 }
3076#ifdef WINDOWS32
3077 /* Backslash before whitespace is not special if our shell
3078 is not Unixy. */
3079 else if (ISSPACE (p[1]) && !unixy_shell)
3080 {
3081 *ap++ = *p;
3082 break;
3083 }
3084#endif
3085 else if (p[1] != '\0')
3086 {
3087#ifdef HAVE_DOS_PATHS
3088 /* Only remove backslashes before characters special to Unixy
3089 shells. All other backslashes are copied verbatim, since
3090 they are probably DOS-style directory separators. This
3091 still leaves a small window for problems, but at least it
3092 should work for the vast majority of naive users. */
3093
3094#ifdef __MSDOS__
3095 /* A dot is only special as part of the "..."
3096 wildcard. */
3097 if (strneq (p + 1, ".\\.\\.", 5))
3098 {
3099 *ap++ = '.';
3100 *ap++ = '.';
3101 p += 4;
3102 }
3103 else
3104#endif
3105 if (p[1] != '\\' && p[1] != '\''
3106 && !ISSPACE (p[1])
3107# ifdef KMK
3108 && strchr (sh_chars, p[1]) == 0
3109 && (p[1] != '"' || !unixy_shell))
3110# else
3111 && strchr (sh_chars_sh, p[1]) == 0)
3112# endif
3113 /* back up one notch, to copy the backslash */
3114 --p;
3115#endif /* HAVE_DOS_PATHS */
3116
3117 /* Copy and skip the following char. */
3118 *ap++ = *++p;
3119 }
3120 break;
3121
3122 case '\'':
3123 case '"':
3124 instring = *p;
3125 break;
3126
3127 case '\n':
3128 if (restp != NULL)
3129 {
3130 /* End of the command line. */
3131 *restp = p;
3132 goto end_of_line;
3133 }
3134 else
3135 /* Newlines are not special. */
3136 *ap++ = '\n';
3137 break;
3138
3139 case ' ':
3140 case '\t':
3141 /* We have the end of an argument.
3142 Terminate the text of the argument. */
3143 *ap++ = '\0';
3144 new_argv[++i] = ap;
3145 last_argument_was_empty = 0;
3146
3147 /* Update SEEN_NONEQUALS, which tells us if every word
3148 heretofore has contained an '='. */
3149 seen_nonequals |= ! word_has_equals;
3150 if (word_has_equals && ! seen_nonequals)
3151 /* An '=' in a word before the first
3152 word without one is magical. */
3153 goto slow;
3154 word_has_equals = 0; /* Prepare for the next word. */
3155
3156 /* If this argument is the command name,
3157 see if it is a built-in shell command.
3158 If so, have the shell handle it. */
3159 if (i == 1)
3160 {
3161 register int j;
3162 for (j = 0; sh_cmds[j] != 0; ++j)
3163 {
3164 if (streq (sh_cmds[j], new_argv[0]))
3165 goto slow;
3166#if defined(__EMX__) || defined(WINDOWS32)
3167 /* Non-Unix shells are case insensitive. */
3168 if (!unixy_shell
3169 && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
3170 goto slow;
3171#endif
3172 }
3173 }
3174
3175 /* Skip whitespace chars, but not newlines. */
3176 while (ISBLANK (p[1]))
3177 ++p;
3178 break;
3179
3180 default:
3181 *ap++ = *p;
3182 break;
3183 }
3184 }
3185 end_of_line:
3186
3187 if (instring)
3188 /* Let the shell deal with an unterminated quote. */
3189 goto slow;
3190
3191 /* Terminate the last argument and the argument list. */
3192
3193 *ap = '\0';
3194 if (new_argv[i][0] != '\0' || last_argument_was_empty)
3195 ++i;
3196 new_argv[i] = 0;
3197
3198 if (i == 1)
3199 {
3200 register int j;
3201 for (j = 0; sh_cmds[j] != 0; ++j)
3202 if (streq (sh_cmds[j], new_argv[0]))
3203 goto slow;
3204 }
3205
3206 if (new_argv[0] == 0)
3207 {
3208 /* Line was empty. */
3209 free (argstr);
3210 free (new_argv);
3211 return 0;
3212 }
3213
3214 return new_argv;
3215
3216 slow:;
3217 /* We must use the shell. */
3218
3219 if (new_argv != 0)
3220 {
3221 /* Free the old argument list we were working on. */
3222 free (argstr);
3223 free (new_argv);
3224 }
3225
3226#ifdef __MSDOS__
3227 execute_by_shell = 1; /* actually, call 'system' if shell isn't unixy */
3228#endif
3229
3230#ifdef _AMIGA
3231 {
3232 char *ptr;
3233 char *buffer;
3234 char *dptr;
3235
3236 buffer = xmalloc (strlen (line)+1);
3237
3238 ptr = line;
3239 for (dptr=buffer; *ptr; )
3240 {
3241 if (*ptr == '\\' && ptr[1] == '\n')
3242 ptr += 2;
3243 else if (*ptr == '@') /* Kludge: multiline commands */
3244 {
3245 ptr += 2;
3246 *dptr++ = '\n';
3247 }
3248 else
3249 *dptr++ = *ptr++;
3250 }
3251 *dptr = 0;
3252
3253 new_argv = xmalloc (2 * sizeof (char *));
3254 new_argv[0] = buffer;
3255 new_argv[1] = 0;
3256 }
3257#else /* Not Amiga */
3258#ifdef WINDOWS32
3259 /*
3260 * Not eating this whitespace caused things like
3261 *
3262 * sh -c "\n"
3263 *
3264 * which gave the shell fits. I think we have to eat
3265 * whitespace here, but this code should be considered
3266 * suspicious if things start failing....
3267 */
3268
3269 /* Make sure not to bother processing an empty line. */
3270 NEXT_TOKEN (line);
3271 if (*line == '\0')
3272 return 0;
3273#endif /* WINDOWS32 */
3274
3275 {
3276 /* SHELL may be a multi-word command. Construct a command line
3277 "$(SHELL) $(.SHELLFLAGS) LINE", with all special chars in LINE escaped.
3278 Then recurse, expanding this command line to get the final
3279 argument list. */
3280
3281 char *new_line;
3282 unsigned int shell_len = strlen (shell);
3283 unsigned int line_len = strlen (line);
3284 unsigned int sflags_len = shellflags ? strlen (shellflags) : 0;
3285#ifdef WINDOWS32
3286 char *command_ptr = NULL; /* used for batch_mode_shell mode */
3287#endif
3288
3289# ifdef __EMX__ /* is this necessary? */
3290 if (!unixy_shell && shellflags)
3291 shellflags[0] = '/'; /* "/c" */
3292# endif
3293
3294 /* In .ONESHELL mode we are allowed to throw the entire current
3295 recipe string at a single shell and trust that the user
3296 has configured the shell and shell flags, and formatted
3297 the string, appropriately. */
3298 if (one_shell)
3299 {
3300 /* If the shell is Bourne compatible, we must remove and ignore
3301 interior special chars [@+-] because they're meaningless to
3302 the shell itself. If, however, we're in .ONESHELL mode and
3303 have changed SHELL to something non-standard, we should
3304 leave those alone because they could be part of the
3305 script. In this case we must also leave in place
3306 any leading [@+-] for the same reason. */
3307
3308 /* Remove and ignore interior prefix chars [@+-] because they're
3309 meaningless given a single shell. */
3310#if defined __MSDOS__ || defined (__EMX__)
3311 if (unixy_shell) /* the test is complicated and we already did it */
3312#else
3313 if (is_bourne_compatible_shell (shell)
3314#ifdef WINDOWS32
3315 /* If we didn't find any sh.exe, don't behave is if we did! */
3316 && !no_default_sh_exe
3317#endif
3318 )
3319#endif
3320 {
3321 const char *f = line;
3322 char *t = line;
3323
3324 /* Copy the recipe, removing and ignoring interior prefix chars
3325 [@+-]: they're meaningless in .ONESHELL mode. */
3326 while (f[0] != '\0')
3327 {
3328 int esc = 0;
3329
3330 /* This is the start of a new recipe line. Skip whitespace
3331 and prefix characters but not newlines. */
3332 while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
3333 ++f;
3334
3335 /* Copy until we get to the next logical recipe line. */
3336 while (*f != '\0')
3337 {
3338 *(t++) = *(f++);
3339 if (f[-1] == '\\')
3340 esc = !esc;
3341 else
3342 {
3343 /* On unescaped newline, we're done with this line. */
3344 if (f[-1] == '\n' && ! esc)
3345 break;
3346
3347 /* Something else: reset the escape sequence. */
3348 esc = 0;
3349 }
3350 }
3351 }
3352 *t = '\0';
3353 }
3354#ifdef WINDOWS32
3355 else /* non-Posix shell (cmd.exe etc.) */
3356 {
3357 const char *f = line;
3358 char *t = line;
3359 char *tstart = t;
3360 int temp_fd;
3361 FILE* batch = NULL;
3362 int id = GetCurrentProcessId ();
3363 PATH_VAR(fbuf);
3364
3365 /* Generate a file name for the temporary batch file. */
3366 sprintf (fbuf, "make%d", id);
3367 *batch_filename = create_batch_file (fbuf, 0, &temp_fd);
3368 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3369 *batch_filename));
3370
3371 /* Create a FILE object for the batch file, and write to it the
3372 commands to be executed. Put the batch file in TEXT mode. */
3373 _setmode (temp_fd, _O_TEXT);
3374 batch = _fdopen (temp_fd, "wt");
3375 fputs ("@echo off\n", batch);
3376 DB (DB_JOBS, (_("Batch file contents:\n\t@echo off\n")));
3377
3378 /* Copy the recipe, removing and ignoring interior prefix chars
3379 [@+-]: they're meaningless in .ONESHELL mode. */
3380 while (*f != '\0')
3381 {
3382 /* This is the start of a new recipe line. Skip whitespace
3383 and prefix characters but not newlines. */
3384 while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
3385 ++f;
3386
3387 /* Copy until we get to the next logical recipe line. */
3388 while (*f != '\0')
3389 {
3390 /* Remove the escaped newlines in the command, and the
3391 blanks that follow them. Windows shells cannot handle
3392 escaped newlines. */
3393 if (*f == '\\' && f[1] == '\n')
3394 {
3395 f += 2;
3396 while (ISBLANK (*f))
3397 ++f;
3398 }
3399 *(t++) = *(f++);
3400 /* On an unescaped newline, we're done with this
3401 line. */
3402 if (f[-1] == '\n')
3403 break;
3404 }
3405 /* Write another line into the batch file. */
3406 if (t > tstart)
3407 {
3408 char c = *t;
3409 *t = '\0';
3410 fputs (tstart, batch);
3411 DB (DB_JOBS, ("\t%s", tstart));
3412 tstart = t;
3413 *t = c;
3414 }
3415 }
3416 DB (DB_JOBS, ("\n"));
3417 fclose (batch);
3418
3419 /* Create an argv list for the shell command line that
3420 will run the batch file. */
3421 new_argv = xmalloc (2 * sizeof (char *));
3422 new_argv[0] = xstrdup (*batch_filename);
3423 new_argv[1] = NULL;
3424 return new_argv;
3425 }
3426#endif /* WINDOWS32 */
3427 /* Create an argv list for the shell command line. */
3428 {
3429 int n = 0;
3430
3431 new_argv = xmalloc ((4 + sflags_len/2) * sizeof (char *));
3432 new_argv[n++] = xstrdup (shell);
3433
3434 /* Chop up the shellflags (if any) and assign them. */
3435 if (! shellflags)
3436 new_argv[n++] = xstrdup ("");
3437 else
3438 {
3439 const char *s = shellflags;
3440 char *t;
3441 unsigned int len;
3442 while ((t = find_next_token (&s, &len)) != 0)
3443 new_argv[n++] = xstrndup (t, len);
3444 }
3445
3446 /* Set the command to invoke. */
3447 new_argv[n++] = line;
3448 new_argv[n++] = NULL;
3449 }
3450 return new_argv;
3451 }
3452
3453 new_line = xmalloc ((shell_len*2) + 1 + sflags_len + 1
3454 + (line_len*2) + 1);
3455 ap = new_line;
3456 /* Copy SHELL, escaping any characters special to the shell. If
3457 we don't escape them, construct_command_argv_internal will
3458 recursively call itself ad nauseam, or until stack overflow,
3459 whichever happens first. */
3460 for (cp = shell; *cp != '\0'; ++cp)
3461 {
3462 if (strchr (sh_chars, *cp) != 0)
3463 *(ap++) = '\\';
3464 *(ap++) = *cp;
3465 }
3466 *(ap++) = ' ';
3467 if (shellflags)
3468 memcpy (ap, shellflags, sflags_len);
3469 ap += sflags_len;
3470 *(ap++) = ' ';
3471#ifdef WINDOWS32
3472 command_ptr = ap;
3473#endif
3474 for (p = line; *p != '\0'; ++p)
3475 {
3476 if (restp != NULL && *p == '\n')
3477 {
3478 *restp = p;
3479 break;
3480 }
3481 else if (*p == '\\' && p[1] == '\n')
3482 {
3483 /* POSIX says we keep the backslash-newline. If we don't have a
3484 POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
3485 and remove the backslash/newline. */
3486#if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
3487# define PRESERVE_BSNL unixy_shell
3488#else
3489# define PRESERVE_BSNL 1
3490#endif
3491 if (PRESERVE_BSNL)
3492 {
3493 *(ap++) = '\\';
3494 /* Only non-batch execution needs another backslash,
3495 because it will be passed through a recursive
3496 invocation of this function. */
3497 if (!batch_mode_shell)
3498 *(ap++) = '\\';
3499 *(ap++) = '\n';
3500 }
3501 ++p;
3502 continue;
3503 }
3504
3505 /* DOS shells don't know about backslash-escaping. */
3506 if (unixy_shell && !batch_mode_shell &&
3507 (*p == '\\' || *p == '\'' || *p == '"'
3508 || ISSPACE (*p)
3509 || strchr (sh_chars, *p) != 0))
3510 *ap++ = '\\';
3511#ifdef __MSDOS__
3512 else if (unixy_shell && strneq (p, "...", 3))
3513 {
3514 /* The case of '...' wildcard again. */
3515 strcpy (ap, "\\.\\.\\");
3516 ap += 5;
3517 p += 2;
3518 }
3519#endif
3520 *ap++ = *p;
3521 }
3522 if (ap == new_line + shell_len + sflags_len + 2)
3523 {
3524 /* Line was empty. */
3525 free (new_line);
3526 return 0;
3527 }
3528 *ap = '\0';
3529
3530#ifdef WINDOWS32
3531 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3532 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3533 cases, run commands via a script file. */
3534 if (just_print_flag && !(flags & COMMANDS_RECURSE))
3535 {
3536 /* Need to allocate new_argv, although it's unused, because
3537 start_job_command will want to free it and its 0'th element. */
3538 new_argv = xmalloc (2 * sizeof (char *));
3539 new_argv[0] = xstrdup ("");
3540 new_argv[1] = NULL;
3541 }
3542 else if ((no_default_sh_exe || batch_mode_shell) && batch_filename)
3543 {
3544 int temp_fd;
3545 FILE* batch = NULL;
3546 int id = GetCurrentProcessId ();
3547 PATH_VAR (fbuf);
3548
3549 /* create a file name */
3550 sprintf (fbuf, "make%d", id);
3551 *batch_filename = create_batch_file (fbuf, unixy_shell, &temp_fd);
3552
3553 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3554 *batch_filename));
3555
3556 /* Create a FILE object for the batch file, and write to it the
3557 commands to be executed. Put the batch file in TEXT mode. */
3558 _setmode (temp_fd, _O_TEXT);
3559 batch = _fdopen (temp_fd, "wt");
3560 if (!unixy_shell)
3561 fputs ("@echo off\n", batch);
3562 fputs (command_ptr, batch);
3563 fputc ('\n', batch);
3564 fclose (batch);
3565 DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
3566 !unixy_shell ? "\n\t@echo off" : "", command_ptr));
3567
3568 /* create argv */
3569 new_argv = xmalloc (3 * sizeof (char *));
3570 if (unixy_shell)
3571 {
3572 new_argv[0] = xstrdup (shell);
3573 new_argv[1] = *batch_filename; /* only argv[0] gets freed later */
3574 }
3575 else
3576 {
3577 new_argv[0] = xstrdup (*batch_filename);
3578 new_argv[1] = NULL;
3579 }
3580 new_argv[2] = NULL;
3581 }
3582 else
3583#endif /* WINDOWS32 */
3584
3585 if (unixy_shell)
3586 new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0,
3587 flags, 0);
3588
3589#ifdef __EMX__
3590 else if (!unixy_shell)
3591 {
3592 /* new_line is local, must not be freed therefore
3593 We use line here instead of new_line because we run the shell
3594 manually. */
3595 size_t line_len = strlen (line);
3596 char *p = new_line;
3597 char *q = new_line;
3598 memcpy (new_line, line, line_len + 1);
3599 /* Replace all backslash-newline combination and also following tabs.
3600 Important: stop at the first '\n' because that's what the loop above
3601 did. The next line starting at restp[0] will be executed during the
3602 next call of this function. */
3603 while (*q != '\0' && *q != '\n')
3604 {
3605 if (q[0] == '\\' && q[1] == '\n')
3606 q += 2; /* remove '\\' and '\n' */
3607 else
3608 *p++ = *q++;
3609 }
3610 *p = '\0';
3611
3612# ifndef NO_CMD_DEFAULT
3613 if (strnicmp (new_line, "echo", 4) == 0
3614 && (new_line[4] == ' ' || new_line[4] == '\t'))
3615 {
3616 /* the builtin echo command: handle it separately */
3617 size_t echo_len = line_len - 5;
3618 char *echo_line = new_line + 5;
3619
3620 /* special case: echo 'x="y"'
3621 cmd works this way: a string is printed as is, i.e., no quotes
3622 are removed. But autoconf uses a command like echo 'x="y"' to
3623 determine whether make works. autoconf expects the output x="y"
3624 so we will do exactly that.
3625 Note: if we do not allow cmd to be the default shell
3626 we do not need this kind of voodoo */
3627 if (echo_line[0] == '\''
3628 && echo_line[echo_len - 1] == '\''
3629 && strncmp (echo_line + 1, "ac_maketemp=",
3630 strlen ("ac_maketemp=")) == 0)
3631 {
3632 /* remove the enclosing quotes */
3633 memmove (echo_line, echo_line + 1, echo_len - 2);
3634 echo_line[echo_len - 2] = '\0';
3635 }
3636 }
3637# endif
3638
3639 {
3640 /* Let the shell decide what to do. Put the command line into the
3641 2nd command line argument and hope for the best ;-) */
3642 size_t sh_len = strlen (shell);
3643
3644 /* exactly 3 arguments + NULL */
3645 new_argv = xmalloc (4 * sizeof (char *));
3646 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3647 the trailing '\0' */
3648 new_argv[0] = xmalloc (sh_len + line_len + 5);
3649 memcpy (new_argv[0], shell, sh_len + 1);
3650 new_argv[1] = new_argv[0] + sh_len + 1;
3651 memcpy (new_argv[1], "/c", 3);
3652 new_argv[2] = new_argv[1] + 3;
3653 memcpy (new_argv[2], new_line, line_len + 1);
3654 new_argv[3] = NULL;
3655 }
3656 }
3657#elif defined(__MSDOS__)
3658 else
3659 {
3660 /* With MSDOS shells, we must construct the command line here
3661 instead of recursively calling ourselves, because we
3662 cannot backslash-escape the special characters (see above). */
3663 new_argv = xmalloc (sizeof (char *));
3664 line_len = strlen (new_line) - shell_len - sflags_len - 2;
3665 new_argv[0] = xmalloc (line_len + 1);
3666 strncpy (new_argv[0],
3667 new_line + shell_len + sflags_len + 2, line_len);
3668 new_argv[0][line_len] = '\0';
3669 }
3670#else
3671 else
3672 fatal (NILF, CSTRLEN (__FILE__) + INTSTR_LENGTH,
3673 _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3674 __FILE__, __LINE__);
3675#endif
3676
3677 free (new_line);
3678 }
3679#endif /* ! AMIGA */
3680
3681 return new_argv;
3682}
3683#endif /* !VMS */
3684
3685/* Figure out the argument list necessary to run LINE as a command. Try to
3686 avoid using a shell. This routine handles only ' quoting, and " quoting
3687 when no backslash, $ or ' characters are seen in the quotes. Starting
3688 quotes may be escaped with a backslash. If any of the characters in
3689 sh_chars is seen, or any of the builtin commands listed in sh_cmds
3690 is the first word of a line, the shell is used.
3691
3692 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3693 If *RESTP is NULL, newlines will be ignored.
3694
3695 FILE is the target whose commands these are. It is used for
3696 variable expansion for $(SHELL) and $(IFS). */
3697
3698char **
3699construct_command_argv (char *line, char **restp, struct file *file,
3700 int cmd_flags, char **batch_filename)
3701{
3702 char *shell, *ifs, *shellflags;
3703 char **argv;
3704
3705#ifdef VMS
3706 char *cptr;
3707 int argc;
3708
3709 argc = 0;
3710 cptr = line;
3711 for (;;)
3712 {
3713 while ((*cptr != 0) && (ISSPACE (*cptr)))
3714 cptr++;
3715 if (*cptr == 0)
3716 break;
3717 while ((*cptr != 0) && (!ISSPACE (*cptr)))
3718 cptr++;
3719 argc++;
3720 }
3721
3722 argv = xmalloc (argc * sizeof (char *));
3723 if (argv == 0)
3724 abort ();
3725
3726 cptr = line;
3727 argc = 0;
3728 for (;;)
3729 {
3730 while ((*cptr != 0) && (ISSPACE (*cptr)))
3731 cptr++;
3732 if (*cptr == 0)
3733 break;
3734 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3735 argv[argc++] = cptr;
3736 while ((*cptr != 0) && (!ISSPACE (*cptr)))
3737 cptr++;
3738 if (*cptr != 0)
3739 *cptr++ = 0;
3740 }
3741#else
3742 {
3743 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3744 int save = warn_undefined_variables_flag;
3745 warn_undefined_variables_flag = 0;
3746
3747 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3748#ifdef WINDOWS32
3749 /*
3750 * Convert to forward slashes so that construct_command_argv_internal()
3751 * is not confused.
3752 */
3753 if (shell)
3754 {
3755 char *p = w32ify (shell, 0);
3756 strcpy (shell, p);
3757 }
3758#endif
3759#ifdef __EMX__
3760 {
3761 static const char *unixroot = NULL;
3762 static const char *last_shell = "";
3763 static int init = 0;
3764 if (init == 0)
3765 {
3766 unixroot = getenv ("UNIXROOT");
3767 /* unixroot must be NULL or not empty */
3768 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3769 init = 1;
3770 }
3771
3772 /* if we have an unixroot drive and if shell is not default_shell
3773 (which means it's either cmd.exe or the test has already been
3774 performed) and if shell is an absolute path without drive letter,
3775 try whether it exists e.g.: if "/bin/sh" does not exist use
3776 "$UNIXROOT/bin/sh" instead. */
3777 if (unixroot && shell && strcmp (shell, last_shell) != 0
3778 && (shell[0] == '/' || shell[0] == '\\'))
3779 {
3780 /* trying a new shell, check whether it exists */
3781 size_t size = strlen (shell);
3782 char *buf = xmalloc (size + 7);
3783 memcpy (buf, shell, size);
3784 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3785 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3786 {
3787 /* try the same for the unixroot drive */
3788 memmove (buf + 2, buf, size + 5);
3789 buf[0] = unixroot[0];
3790 buf[1] = unixroot[1];
3791 if (access (buf, F_OK) == 0)
3792 /* we have found a shell! */
3793 /* free(shell); */
3794 shell = buf;
3795 else
3796 free (buf);
3797 }
3798 else
3799 free (buf);
3800 }
3801 }
3802#endif /* __EMX__ */
3803
3804 shellflags = allocated_variable_expand_for_file ("$(.SHELLFLAGS)", file);
3805 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3806
3807 warn_undefined_variables_flag = save;
3808 }
3809
3810# ifdef CONFIG_WITH_KMK_BUILTIN
3811 /* If it's a kmk_builtin command, make sure we're treated like a
3812 unix shell and and don't get batch files. */
3813 if ( ( !unixy_shell
3814 || batch_mode_shell
3815# ifdef WINDOWS32
3816 || no_default_sh_exe
3817# endif
3818 )
3819 && line
3820 && !strncmp (line, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
3821 {
3822 int saved_batch_mode_shell = batch_mode_shell;
3823 int saved_unixy_shell = unixy_shell;
3824# ifdef WINDOWS32
3825 int saved_no_default_sh_exe = no_default_sh_exe;
3826 no_default_sh_exe = 0;
3827# endif
3828 unixy_shell = 1;
3829 batch_mode_shell = 0;
3830 argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
3831 cmd_flags, batch_filename);
3832 batch_mode_shell = saved_batch_mode_shell;
3833 unixy_shell = saved_unixy_shell;
3834# ifdef WINDOWS32
3835 no_default_sh_exe = saved_no_default_sh_exe;
3836# endif
3837 }
3838 else
3839# endif /* CONFIG_WITH_KMK_BUILTIN */
3840 argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
3841 cmd_flags, batch_filename);
3842
3843 free (shell);
3844 free (shellflags);
3845 free (ifs);
3846#endif /* !VMS */
3847 return argv;
3848}
3849
3850
3851#if !defined(HAVE_DUP2) && !defined(_AMIGA)
3852int
3853dup2 (int old, int new)
3854{
3855 int fd;
3856
3857 (void) close (new);
3858 EINTRLOOP (fd, dup (old));
3859 if (fd != new)
3860 {
3861 (void) close (fd);
3862 errno = EMFILE;
3863 return -1;
3864 }
3865
3866 return fd;
3867}
3868#endif /* !HAVE_DUP2 && !_AMIGA */
3869
3870#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
3871/* Prints the time elapsed while executing the commands for the given job. */
3872void print_job_time (struct child *c)
3873{
3874 if ( !handling_fatal_signal
3875 && print_time_min != -1
3876 && c->start_ts != -1)
3877 {
3878 big_int elapsed = nano_timestamp () - c->start_ts;
3879 if (elapsed >= print_time_min * BIG_INT_C(1000000000))
3880 {
3881 char buf[64];
3882 int len = format_elapsed_nano (buf, sizeof (buf), elapsed);
3883 if (len > print_time_width)
3884 print_time_width = len;
3885 message (1, print_time_width + strlen (c->file->name),
3886 _("%*s - %s"), print_time_width, buf, c->file->name);
3887 }
3888 }
3889}
3890#endif
3891
3892/* On VMS systems, include special VMS functions. */
3893
3894#ifdef VMS
3895#include "vmsjobs.c"
3896#endif
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette