VirtualBox

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

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

kmk: Merged in changes from GNU make 4.2.1 (2e55f5e4abdc0e38c1d64be703b446695e70b3b6 / https://git.savannah.gnu.org/git/make.git).

  • Property svn:eol-style set to native
File size: 116.9 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 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# if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32) && !defined(VMS)
1177 char ** volatile volatile_argv;
1178 int volatile volatile_flags;
1179# endif
1180#endif
1181
1182 /* If we have a completely empty commandset, stop now. */
1183 if (!child->command_ptr)
1184 goto next_command;
1185
1186#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
1187 if (child->start_ts == -1)
1188 child->start_ts = nano_timestamp ();
1189#endif
1190
1191 /* Combine the flags parsed for the line itself with
1192 the flags specified globally for this target. */
1193 flags = (child->file->command_flags
1194 | child->file->cmds->lines_flags[child->command_line - 1]);
1195
1196 p = child->command_ptr;
1197 child->noerror = ((flags & COMMANDS_NOERROR) != 0);
1198
1199 while (*p != '\0')
1200 {
1201 if (*p == '@')
1202 flags |= COMMANDS_SILENT;
1203 else if (*p == '+')
1204 flags |= COMMANDS_RECURSE;
1205 else if (*p == '-')
1206 child->noerror = 1;
1207#ifdef CONFIG_WITH_COMMANDS_FUNC
1208 else if (*p == '%')
1209 flags |= COMMAND_GETTER_SKIP_IT;
1210#endif
1211 /* Don't skip newlines. */
1212 else if (!ISBLANK (*p))
1213#ifndef CONFIG_WITH_KMK_BUILTIN
1214 break;
1215#else /* CONFIG_WITH_KMK_BUILTIN */
1216
1217 {
1218 if ( !(flags & COMMANDS_KMK_BUILTIN)
1219 && !strncmp(p, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
1220 flags |= COMMANDS_KMK_BUILTIN;
1221 break;
1222 }
1223#endif /* CONFIG_WITH_KMK_BUILTIN */
1224 ++p;
1225 }
1226
1227 child->recursive = ((flags & COMMANDS_RECURSE) != 0);
1228
1229 /* Update the file's command flags with any new ones we found. We only
1230 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
1231 now marking more commands recursive than should be in the case of
1232 multiline define/endef scripts where only one line is marked "+". In
1233 order to really fix this, we'll have to keep a lines_flags for every
1234 actual line, after expansion. */
1235 child->file->cmds->lines_flags[child->command_line - 1] |= flags & COMMANDS_RECURSE;
1236
1237 /* POSIX requires that a recipe prefix after a backslash-newline should
1238 be ignored. Remove it now so the output is correct. */
1239 {
1240 char prefix = child->file->cmds->recipe_prefix;
1241 char *p1, *p2;
1242 p1 = p2 = p;
1243 while (*p1 != '\0')
1244 {
1245 *(p2++) = *p1;
1246 if (p1[0] == '\n' && p1[1] == prefix)
1247 ++p1;
1248 ++p1;
1249 }
1250 *p2 = *p1;
1251 }
1252
1253 /* Figure out an argument list from this command line. */
1254 {
1255 char *end = 0;
1256#ifdef VMS
1257 /* Skip any leading whitespace */
1258 while (*p)
1259 {
1260 if (!ISSPACE (*p))
1261 {
1262 if (*p != '\\')
1263 break;
1264 if ((p[1] != '\n') && (p[1] != 'n') && (p[1] != 't'))
1265 break;
1266 }
1267 p++;
1268 }
1269
1270 argv = p;
1271 /* Although construct_command_argv contains some code for VMS, it was/is
1272 not called/used. Please note, for VMS argv is a string (not an array
1273 of strings) which contains the complete command line, which for
1274 multi-line variables still includes the newlines. So detect newlines
1275 and set 'end' (which is used for child->command_ptr) instead of
1276 (re-)writing construct_command_argv */
1277 if (!one_shell)
1278 {
1279 char *s = p;
1280 int instring = 0;
1281 while (*s)
1282 {
1283 if (*s == '"')
1284 instring = !instring;
1285 else if (*s == '\\' && !instring && *(s+1) != 0)
1286 s++;
1287 else if (*s == '\n' && !instring)
1288 {
1289 end = s;
1290 break;
1291 }
1292 ++s;
1293 }
1294 }
1295#else
1296 argv = construct_command_argv (p, &end, child->file,
1297 child->file->cmds->lines_flags[child->command_line - 1],
1298 &child->sh_batch_file);
1299#endif
1300 if (end == NULL)
1301 child->command_ptr = NULL;
1302 else
1303 {
1304 *end++ = '\0';
1305 child->command_ptr = end;
1306 }
1307 }
1308
1309 /* If -q was given, say that updating 'failed' if there was any text on the
1310 command line, or 'succeeded' otherwise. The exit status of 1 tells the
1311 user that -q is saying 'something to do'; the exit status for a random
1312 error is 2. */
1313 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
1314 {
1315#ifndef VMS
1316 free (argv[0]);
1317 free (argv);
1318#endif
1319#ifdef VMS
1320 /* On VMS, argv[0] can be a null string here */
1321 if (argv[0] != 0)
1322 {
1323#endif
1324 child->file->update_status = us_question;
1325 notice_finished_file (child->file);
1326 return;
1327#ifdef VMS
1328 }
1329#endif
1330 }
1331
1332 if (touch_flag && !(flags & COMMANDS_RECURSE))
1333 {
1334 /* Go on to the next command. It might be the recursive one.
1335 We construct ARGV only to find the end of the command line. */
1336#ifndef VMS
1337 if (argv)
1338 {
1339 free (argv[0]);
1340 free (argv);
1341 }
1342#endif
1343 argv = 0;
1344 }
1345
1346 if (argv == 0)
1347 {
1348 next_command:
1349#ifdef __MSDOS__
1350 execute_by_shell = 0; /* in case construct_command_argv sets it */
1351#endif
1352 /* This line has no commands. Go to the next. */
1353 if (job_next_command (child))
1354 start_job_command (child);
1355 else
1356 {
1357 /* No more commands. Make sure we're "running"; we might not be if
1358 (e.g.) all commands were skipped due to -n. */
1359 set_command_state (child->file, cs_running);
1360 child->file->update_status = us_success;
1361 notice_finished_file (child->file);
1362 }
1363
1364 OUTPUT_UNSET();
1365 return;
1366 }
1367
1368 /* Are we going to synchronize this command's output? Do so if either we're
1369 in SYNC_RECURSE mode or this command is not recursive. We'll also check
1370 output_sync separately below in case it changes due to error. */
1371 child->output.syncout = output_sync && (output_sync == OUTPUT_SYNC_RECURSE
1372 || !(flags & COMMANDS_RECURSE));
1373 OUTPUT_SET (&child->output);
1374
1375#ifndef NO_OUTPUT_SYNC
1376 if (! child->output.syncout)
1377 /* We don't want to sync this command: to avoid misordered
1378 output ensure any already-synced content is written. */
1379 output_dump (&child->output);
1380#endif
1381
1382 /* Print the command if appropriate. */
1383#ifdef CONFIG_PRETTY_COMMAND_PRINTING
1384 if ( pretty_command_printing
1385 && (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
1386 && argv[0][0] != '\0')
1387 {
1388 unsigned i;
1389 for (i = 0; argv[i]; i++)
1390 OSSS ( message, 0, "%s'%s'%s", i ? "\t" : "> ", argv[i], argv[i + 1] ? " \\" : "");
1391 }
1392 else
1393#endif /* CONFIG_PRETTY_COMMAND_PRINTING */
1394 if (just_print_flag || trace_flag
1395 || (!(flags & COMMANDS_SILENT) && !silent_flag))
1396 OS (message, 0, "%s", p);
1397
1398 /* Tell update_goal_chain that a command has been started on behalf of
1399 this target. It is important that this happens here and not in
1400 reap_children (where we used to do it), because reap_children might be
1401 reaping children from a different target. We want this increment to
1402 guaranteedly indicate that a command was started for the dependency
1403 chain (i.e., update_file recursion chain) we are processing. */
1404
1405 ++commands_started;
1406
1407 /* Optimize an empty command. People use this for timestamp rules,
1408 so avoid forking a useless shell. Do this after we increment
1409 commands_started so make still treats this special case as if it
1410 performed some action (makes a difference as to what messages are
1411 printed, etc. */
1412
1413#if !defined(VMS) && !defined(_AMIGA)
1414 if (
1415#if defined __MSDOS__ || defined (__EMX__)
1416 unixy_shell /* the test is complicated and we already did it */
1417#else
1418 (argv[0] && is_bourne_compatible_shell (argv[0]))
1419#endif
1420 && (argv[1] && argv[1][0] == '-'
1421 &&
1422 ((argv[1][1] == 'c' && argv[1][2] == '\0')
1423 ||
1424 (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
1425 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1426 && argv[3] == NULL)
1427 {
1428 free (argv[0]);
1429 free (argv);
1430 goto next_command;
1431 }
1432#endif /* !VMS && !_AMIGA */
1433
1434 /* If -n was given, recurse to get the next line in the sequence. */
1435
1436 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1437 {
1438#ifndef VMS
1439 free (argv[0]);
1440 free (argv);
1441#endif
1442 goto next_command;
1443 }
1444
1445#ifdef CONFIG_WITH_KMK_BUILTIN
1446 /* If builtin command then pass it on to the builtin shell interpreter. */
1447
1448 if ((flags & COMMANDS_KMK_BUILTIN) && !just_print_flag)
1449 {
1450 int rc;
1451 char **argv_spawn = NULL;
1452 char **p2 = argv;
1453 while (*p2 && strncmp (*p2, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
1454 p2++;
1455 assert (*p2);
1456 set_command_state (child->file, cs_running);
1457 child->deleted = 0;
1458 child->pid = 0;
1459 if (p2 != argv)
1460 rc = kmk_builtin_command (*p2, child, &argv_spawn, &child->pid);
1461 else
1462 {
1463 int argc = 1;
1464 while (argv[argc])
1465 argc++;
1466 rc = kmk_builtin_command_parsed (argc, argv, child, &argv_spawn, &child->pid);
1467 }
1468
1469# ifndef VMS
1470 free (argv[0]);
1471 free ((char *) argv);
1472# endif
1473
1474 if (!rc)
1475 {
1476 /* spawned a child? */
1477 if (child->pid)
1478 {
1479 ++job_counter;
1480 return;
1481 }
1482
1483 /* synchronous command execution? */
1484 if (!argv_spawn)
1485 goto next_command;
1486 }
1487
1488 /* failure? */
1489 if (rc)
1490 {
1491 child->pid = (pid_t)42424242;
1492 child->status = rc << 8;
1493 child->has_status = 1;
1494 unblock_sigs();
1495 return;
1496 }
1497
1498 /* conditional check == true; kicking off a child (not kmk_builtin_*). */
1499 argv = argv_spawn;
1500 }
1501#endif /* CONFIG_WITH_KMK_BUILTIN */
1502
1503 /* We're sure we're going to invoke a command: set up the output. */
1504 output_start ();
1505
1506 /* Flush the output streams so they won't have things written twice. */
1507
1508 fflush (stdout);
1509 fflush (stderr);
1510
1511 /* Decide whether to give this child the 'good' standard input
1512 (one that points to the terminal or whatever), or the 'bad' one
1513 that points to the read side of a broken pipe. */
1514
1515 child->good_stdin = !good_stdin_used;
1516 if (child->good_stdin)
1517 good_stdin_used = 1;
1518
1519 child->deleted = 0;
1520
1521#ifndef _AMIGA
1522 /* Set up the environment for the child. */
1523 if (child->environment == 0)
1524 child->environment = target_environment (child->file);
1525#endif
1526
1527#if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1528
1529#ifndef VMS
1530 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1531 if (child->remote)
1532 {
1533 int is_remote, id, used_stdin;
1534 if (start_remote_job (argv, child->environment,
1535 child->good_stdin ? 0 : get_bad_stdin (),
1536 &is_remote, &id, &used_stdin))
1537 /* Don't give up; remote execution may fail for various reasons. If
1538 so, simply run the job locally. */
1539 goto run_local;
1540 else
1541 {
1542 if (child->good_stdin && !used_stdin)
1543 {
1544 child->good_stdin = 0;
1545 good_stdin_used = 0;
1546 }
1547 child->remote = is_remote;
1548 child->pid = id;
1549 }
1550 }
1551 else
1552#endif /* !VMS */
1553 {
1554 /* Fork the child process. */
1555
1556 char **parent_environ;
1557
1558 run_local:
1559 block_sigs ();
1560
1561 child->remote = 0;
1562
1563#ifdef VMS
1564 if (!child_execute_job (child, argv))
1565 {
1566 /* Fork failed! */
1567 perror_with_name ("fork", "");
1568 goto error;
1569 }
1570
1571#else
1572
1573 parent_environ = environ;
1574
1575 jobserver_pre_child (flags & COMMANDS_RECURSE);
1576
1577 child->pid = child_execute_job (&child->output, child->good_stdin, argv, child->environment);
1578
1579 environ = parent_environ; /* Restore value child may have clobbered. */
1580 jobserver_post_child (flags & COMMANDS_RECURSE);
1581
1582 if (child->pid < 0)
1583 {
1584 /* Fork failed! */
1585 unblock_sigs ();
1586 perror_with_name ("fork", "");
1587 goto error;
1588 }
1589#endif /* !VMS */
1590 }
1591
1592#else /* __MSDOS__ or Amiga or WINDOWS32 */
1593#ifdef __MSDOS__
1594 {
1595 int proc_return;
1596
1597 block_sigs ();
1598 dos_status = 0;
1599
1600 /* We call 'system' to do the job of the SHELL, since stock DOS
1601 shell is too dumb. Our 'system' knows how to handle long
1602 command lines even if pipes/redirection is needed; it will only
1603 call COMMAND.COM when its internal commands are used. */
1604 if (execute_by_shell)
1605 {
1606 char *cmdline = argv[0];
1607 /* We don't have a way to pass environment to 'system',
1608 so we need to save and restore ours, sigh... */
1609 char **parent_environ = environ;
1610
1611 environ = child->environment;
1612
1613 /* If we have a *real* shell, tell 'system' to call
1614 it to do everything for us. */
1615 if (unixy_shell)
1616 {
1617 /* A *real* shell on MSDOS may not support long
1618 command lines the DJGPP way, so we must use 'system'. */
1619 cmdline = argv[2]; /* get past "shell -c" */
1620 }
1621
1622 dos_command_running = 1;
1623 proc_return = system (cmdline);
1624 environ = parent_environ;
1625 execute_by_shell = 0; /* for the next time */
1626 }
1627 else
1628 {
1629 dos_command_running = 1;
1630 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1631 }
1632
1633 /* Need to unblock signals before turning off
1634 dos_command_running, so that child's signals
1635 will be treated as such (see fatal_error_signal). */
1636 unblock_sigs ();
1637 dos_command_running = 0;
1638
1639 /* If the child got a signal, dos_status has its
1640 high 8 bits set, so be careful not to alter them. */
1641 if (proc_return == -1)
1642 dos_status |= 0xff;
1643 else
1644 dos_status |= (proc_return & 0xff);
1645 ++dead_children;
1646 child->pid = dos_pid++;
1647 }
1648#endif /* __MSDOS__ */
1649#ifdef _AMIGA
1650 amiga_status = MyExecute (argv);
1651
1652 ++dead_children;
1653 child->pid = amiga_pid++;
1654 if (amiga_batch_file)
1655 {
1656 amiga_batch_file = 0;
1657 DeleteFile (amiga_bname); /* Ignore errors. */
1658 }
1659#endif /* Amiga */
1660#ifdef WINDOWS32
1661 {
1662 HANDLE hPID;
1663 char* arg0;
1664 int outfd = FD_STDOUT;
1665 int errfd = FD_STDERR;
1666
1667 /* make UNC paths safe for CreateProcess -- backslash format */
1668 arg0 = argv[0];
1669 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1670 for ( ; arg0 && *arg0; arg0++)
1671 if (*arg0 == '/')
1672 *arg0 = '\\';
1673
1674 /* make sure CreateProcess() has Path it needs */
1675 sync_Path_environment ();
1676
1677#ifndef NO_OUTPUT_SYNC
1678 /* Divert child output if output_sync in use. */
1679 if (child->output.syncout)
1680 {
1681 if (child->output.out >= 0)
1682 outfd = child->output.out;
1683 if (child->output.err >= 0)
1684 errfd = child->output.err;
1685 }
1686#else
1687 outfd = errfd = -1;
1688#endif
1689 hPID = process_easy (argv, child->environment, outfd, errfd);
1690
1691 if (hPID != INVALID_HANDLE_VALUE)
1692 child->pid = (pid_t) hPID;
1693 else
1694 {
1695 int i;
1696 unblock_sigs ();
1697 fprintf (stderr,
1698 _("process_easy() failed to launch process (e=%ld)\n"),
1699 process_last_err (hPID));
1700 for (i = 0; argv[i]; i++)
1701 fprintf (stderr, "%s ", argv[i]);
1702 fprintf (stderr, _("\nCounted %d args in failed launch\n"), i);
1703 goto error;
1704 }
1705 }
1706#endif /* WINDOWS32 */
1707#endif /* __MSDOS__ or Amiga or WINDOWS32 */
1708
1709 /* Bump the number of jobs started in this second. */
1710 ++job_counter;
1711
1712 /* We are the parent side. Set the state to
1713 say the commands are running and return. */
1714
1715 set_command_state (child->file, cs_running);
1716
1717 /* Free the storage used by the child's argument list. */
1718#ifdef KMK /* leak */
1719 cleanup_argv:
1720#endif
1721#ifndef VMS
1722 free (argv[0]);
1723 free (argv);
1724#endif
1725
1726 OUTPUT_UNSET();
1727 return;
1728
1729 error:
1730 child->file->update_status = us_failed;
1731 notice_finished_file (child->file);
1732#ifdef KMK /* fix leak */
1733 goto cleanup_argv;
1734#else
1735 OUTPUT_UNSET();
1736#endif
1737}
1738
1739/* Try to start a child running.
1740 Returns nonzero if the child was started (and maybe finished), or zero if
1741 the load was too high and the child was put on the 'waiting_jobs' chain. */
1742
1743static int
1744start_waiting_job (struct child *c)
1745{
1746 struct file *f = c->file;
1747#ifdef DB_KMK
1748 DB (DB_KMK, (_("start_waiting_job %p (`%s') command_flags=%#x slots=%d/%d\n"),
1749 (void *)c, c->file->name, c->file->command_flags, job_slots_used, job_slots));
1750#endif
1751
1752 /* If we can start a job remotely, we always want to, and don't care about
1753 the local load average. We record that the job should be started
1754 remotely in C->remote for start_job_command to test. */
1755
1756 c->remote = start_remote_job_p (1);
1757
1758#ifdef CONFIG_WITH_EXTENDED_NOTPARALLEL
1759 if (c->file->command_flags & COMMANDS_NOTPARALLEL)
1760 {
1761 DB (DB_KMK, (_("not_parallel %d -> %d (file=%p `%s') [start_waiting_job]\n"),
1762 not_parallel, not_parallel + 1, (void *)c->file, c->file->name));
1763 assert(not_parallel >= 0);
1764 ++not_parallel;
1765 }
1766#endif /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
1767
1768 /* If we are running at least one job already and the load average
1769 is too high, make this one wait. */
1770 if (!c->remote
1771#ifdef CONFIG_WITH_EXTENDED_NOTPARALLEL
1772 && ((job_slots_used > 0 && (not_parallel > 0 || load_too_high ()))
1773#else
1774 && ((job_slots_used > 0 && load_too_high ())
1775#endif
1776#ifdef WINDOWS32
1777 || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
1778#endif
1779 ))
1780 {
1781#ifndef CONFIG_WITH_EXTENDED_NOTPARALLEL
1782 /* Put this child on the chain of children waiting for the load average
1783 to go down. */
1784 set_command_state (f, cs_running);
1785 c->next = waiting_jobs;
1786 waiting_jobs = c;
1787
1788#else /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
1789
1790 /* Put this child on the chain of children waiting for the load average
1791 to go down. If not parallel, put it last. */
1792 set_command_state (f, cs_running);
1793 c->next = waiting_jobs;
1794 if (c->next && (c->file->command_flags & COMMANDS_NOTPARALLEL))
1795 {
1796 struct child *prev = waiting_jobs;
1797 while (prev->next)
1798 prev = prev->next;
1799 c->next = 0;
1800 prev->next = c;
1801 }
1802 else /* FIXME: insert after the last node with COMMANDS_NOTPARALLEL set */
1803 waiting_jobs = c;
1804 DB (DB_KMK, (_("queued child %p (`%s')\n"), (void *)c, c->file->name));
1805#endif /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
1806 return 0;
1807 }
1808
1809 /* Start the first command; reap_children will run later command lines. */
1810 start_job_command (c);
1811
1812 switch (f->command_state)
1813 {
1814 case cs_running:
1815 c->next = children;
1816 DB (DB_JOBS, (_("Putting child %p (%s) PID %s%s on the chain.\n"),
1817 (void *)c, c->file->name, pid2str (c->pid),
1818 c->remote ? _(" (remote)") : ""));
1819 children = c;
1820 /* One more job slot is in use. */
1821 ++job_slots_used;
1822 unblock_sigs ();
1823 break;
1824
1825 case cs_not_started:
1826 /* All the command lines turned out to be empty. */
1827 f->update_status = us_success;
1828 /* FALLTHROUGH */
1829
1830 case cs_finished:
1831 notice_finished_file (f);
1832 free_child (c);
1833 break;
1834
1835 default:
1836 assert (f->command_state == cs_finished);
1837 break;
1838 }
1839
1840 return 1;
1841}
1842
1843/* Create a 'struct child' for FILE and start its commands running. */
1844
1845void
1846new_job (struct file *file)
1847{
1848 struct commands *cmds = file->cmds;
1849 struct child *c;
1850 char **lines;
1851 unsigned int i;
1852
1853 /* Let any previously decided-upon jobs that are waiting
1854 for the load to go down start before this new one. */
1855 start_waiting_jobs ();
1856
1857 /* Reap any children that might have finished recently. */
1858 reap_children (0, 0);
1859
1860 /* Chop the commands up into lines if they aren't already. */
1861 chop_commands (cmds);
1862#ifdef CONFIG_WITH_MEMORY_OPTIMIZATIONS
1863 cmds->refs++; /* retain the chopped lines. */
1864#endif
1865
1866 /* Start the command sequence, record it in a new
1867 'struct child', and add that to the chain. */
1868
1869 c = xcalloc (sizeof (struct child));
1870 output_init (&c->output);
1871
1872 c->file = file;
1873 c->sh_batch_file = NULL;
1874
1875 /* Cache dontcare flag because file->dontcare can be changed once we
1876 return. Check dontcare inheritance mechanism for details. */
1877 c->dontcare = file->dontcare;
1878
1879 /* Start saving output in case the expansion uses $(info ...) etc. */
1880 OUTPUT_SET (&c->output);
1881
1882 /* Expand the command lines and store the results in LINES. */
1883 lines = xmalloc (cmds->ncommand_lines * sizeof (char *));
1884 for (i = 0; i < cmds->ncommand_lines; ++i)
1885 {
1886 /* Collapse backslash-newline combinations that are inside variable
1887 or function references. These are left alone by the parser so
1888 that they will appear in the echoing of commands (where they look
1889 nice); and collapsed by construct_command_argv when it tokenizes.
1890 But letting them survive inside function invocations loses because
1891 we don't want the functions to see them as part of the text. */
1892
1893 char *in, *out, *ref;
1894
1895 /* IN points to where in the line we are scanning.
1896 OUT points to where in the line we are writing.
1897 When we collapse a backslash-newline combination,
1898 IN gets ahead of OUT. */
1899
1900 in = out = cmds->command_lines[i];
1901 while ((ref = strchr (in, '$')) != 0)
1902 {
1903 ++ref; /* Move past the $. */
1904
1905 if (out != in)
1906 /* Copy the text between the end of the last chunk
1907 we processed (where IN points) and the new chunk
1908 we are about to process (where REF points). */
1909 memmove (out, in, ref - in);
1910
1911 /* Move both pointers past the boring stuff. */
1912 out += ref - in;
1913 in = ref;
1914
1915 if (*ref == '(' || *ref == '{')
1916 {
1917 char openparen = *ref;
1918 char closeparen = openparen == '(' ? ')' : '}';
1919 char *outref;
1920 int count;
1921 char *p;
1922
1923 *out++ = *in++; /* Copy OPENPAREN. */
1924 outref = out;
1925 /* IN now points past the opening paren or brace.
1926 Count parens or braces until it is matched. */
1927 count = 0;
1928 while (*in != '\0')
1929 {
1930 if (*in == closeparen && --count < 0)
1931 break;
1932 else if (*in == '\\' && in[1] == '\n')
1933 {
1934 /* We have found a backslash-newline inside a
1935 variable or function reference. Eat it and
1936 any following whitespace. */
1937
1938 int quoted = 0;
1939 for (p = in - 1; p > ref && *p == '\\'; --p)
1940 quoted = !quoted;
1941
1942 if (quoted)
1943 /* There were two or more backslashes, so this is
1944 not really a continuation line. We don't collapse
1945 the quoting backslashes here as is done in
1946 collapse_continuations, because the line will
1947 be collapsed again after expansion. */
1948 *out++ = *in++;
1949 else
1950 {
1951 /* Skip the backslash, newline, and whitespace. */
1952 in += 2;
1953 NEXT_TOKEN (in);
1954
1955 /* Discard any preceding whitespace that has
1956 already been written to the output. */
1957 while (out > outref && ISBLANK (out[-1]))
1958 --out;
1959
1960 /* Replace it all with a single space. */
1961 *out++ = ' ';
1962 }
1963 }
1964 else
1965 {
1966 if (*in == openparen)
1967 ++count;
1968
1969 *out++ = *in++;
1970 }
1971 }
1972 }
1973 }
1974
1975 /* There are no more references in this line to worry about.
1976 Copy the remaining uninteresting text to the output. */
1977 if (out != in)
1978 memmove (out, in, strlen (in) + 1);
1979
1980 /* Finally, expand the line. */
1981 cmds->fileinfo.offset = i;
1982 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1983 file);
1984 }
1985
1986 cmds->fileinfo.offset = 0;
1987 c->command_lines = lines;
1988#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
1989 c->start_ts = -1;
1990#endif
1991
1992 /* Fetch the first command line to be run. */
1993 job_next_command (c);
1994
1995 /* Wait for a job slot to be freed up. If we allow an infinite number
1996 don't bother; also job_slots will == 0 if we're using the jobserver. */
1997
1998 if (job_slots != 0)
1999 while (job_slots_used == job_slots)
2000 reap_children (1, 0);
2001
2002#ifdef MAKE_JOBSERVER
2003 /* If we are controlling multiple jobs make sure we have a token before
2004 starting the child. */
2005
2006 /* This can be inefficient. There's a decent chance that this job won't
2007 actually have to run any subprocesses: the command script may be empty
2008 or otherwise optimized away. It would be nice if we could defer
2009 obtaining a token until just before we need it, in start_job_command.
2010 To do that we'd need to keep track of whether we'd already obtained a
2011 token (since start_job_command is called for each line of the job, not
2012 just once). Also more thought needs to go into the entire algorithm;
2013 this is where the old parallel job code waits, so... */
2014
2015 else if (jobserver_enabled ())
2016 while (1)
2017 {
2018 int got_token;
2019
2020 DB (DB_JOBS, ("Need a job token; we %shave children\n",
2021 children ? "" : "don't "));
2022
2023 /* If we don't already have a job started, use our "free" token. */
2024 if (!jobserver_tokens)
2025 break;
2026
2027 /* Prepare for jobserver token acquisition. */
2028 jobserver_pre_acquire ();
2029
2030 /* Reap anything that's currently waiting. */
2031 reap_children (0, 0);
2032
2033 /* Kick off any jobs we have waiting for an opportunity that
2034 can run now (i.e., waiting for load). */
2035 start_waiting_jobs ();
2036
2037 /* If our "free" slot is available, use it; we don't need a token. */
2038 if (!jobserver_tokens)
2039 break;
2040
2041 /* There must be at least one child already, or we have no business
2042 waiting for a token. */
2043 if (!children)
2044 O (fatal, NILF, "INTERNAL: no children as we go to sleep on read\n");
2045
2046 /* Get a token. */
2047 got_token = jobserver_acquire (waiting_jobs != NULL);
2048
2049 /* If we got one, we're done here. */
2050 if (got_token == 1)
2051 {
2052 DB (DB_JOBS, (_("Obtained token for child %p (%s).\n"),
2053 (void *)c, c->file->name));
2054 break;
2055 }
2056 }
2057#endif
2058
2059 ++jobserver_tokens;
2060
2061 /* Trace the build.
2062 Use message here so that changes to working directories are logged. */
2063 if (trace_flag)
2064 {
2065 char *newer = allocated_variable_expand_for_file ("$?", c->file);
2066 const char *nm;
2067
2068 if (! cmds->fileinfo.filenm)
2069 nm = _("<builtin>");
2070 else
2071 {
2072 char *n = alloca (strlen (cmds->fileinfo.filenm) + 1 + 11 + 1);
2073 sprintf (n, "%s:%lu", cmds->fileinfo.filenm, cmds->fileinfo.lineno);
2074 nm = n;
2075 }
2076
2077 if (newer[0] == '\0')
2078 OSS (message, 0,
2079 _("%s: target '%s' does not exist"), nm, c->file->name);
2080 else
2081 OSSS (message, 0,
2082 _("%s: update target '%s' due to: %s"), nm, c->file->name, newer);
2083
2084 free (newer);
2085 }
2086
2087 /* The job is now primed. Start it running.
2088 (This will notice if there is in fact no recipe.) */
2089 start_waiting_job (c);
2090
2091#ifndef CONFIG_WITH_EXTENDED_NOTPARALLEL
2092 if (job_slots == 1 || not_parallel)
2093 /* Since there is only one job slot, make things run linearly.
2094 Wait for the child to die, setting the state to 'cs_finished'. */
2095 while (file->command_state == cs_running)
2096 reap_children (1, 0);
2097
2098#else /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
2099
2100 if (job_slots == 1 || not_parallel < 0)
2101 {
2102 /* Since there is only one job slot, make things run linearly.
2103 Wait for the child to die, setting the state to `cs_finished'. */
2104 while (file->command_state == cs_running)
2105 reap_children (1, 0);
2106 }
2107 else if (not_parallel > 0)
2108 {
2109 /* wait for all live children to finish and then continue
2110 with the not-parallel child(s). FIXME: this loop could be better? */
2111 while (file->command_state == cs_running
2112 && (children != 0 || shell_function_pid != 0) /* reap_child condition */
2113 && not_parallel > 0)
2114 reap_children (1, 0);
2115 }
2116#endif /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
2117
2118 OUTPUT_UNSET ();
2119 return;
2120}
2121
2122
2123/* Move CHILD's pointers to the next command for it to execute.
2124 Returns nonzero if there is another command. */
2125
2126static int
2127job_next_command (struct child *child)
2128{
2129 while (child->command_ptr == 0 || *child->command_ptr == '\0')
2130 {
2131 /* There are no more lines in the expansion of this line. */
2132 if (child->command_line == child->file->cmds->ncommand_lines)
2133 {
2134 /* There are no more lines to be expanded. */
2135 child->command_ptr = 0;
2136 child->file->cmds->fileinfo.offset = 0;
2137 return 0;
2138 }
2139 else
2140 /* Get the next line to run. */
2141 child->command_ptr = child->command_lines[child->command_line++];
2142 }
2143
2144 child->file->cmds->fileinfo.offset = child->command_line - 1;
2145 return 1;
2146}
2147
2148/* Determine if the load average on the system is too high to start a new job.
2149 The real system load average is only recomputed once a second. However, a
2150 very parallel make can easily start tens or even hundreds of jobs in a
2151 second, which brings the system to its knees for a while until that first
2152 batch of jobs clears out.
2153
2154 To avoid this we use a weighted algorithm to try to account for jobs which
2155 have been started since the last second, and guess what the load average
2156 would be now if it were computed.
2157
2158 This algorithm was provided by Thomas Riedl <[email protected]>,
2159 who writes:
2160
2161! calculate something load-oid and add to the observed sys.load,
2162! so that latter can catch up:
2163! - every job started increases jobctr;
2164! - every dying job decreases a positive jobctr;
2165! - the jobctr value gets zeroed every change of seconds,
2166! after its value*weight_b is stored into the 'backlog' value last_sec
2167! - weight_a times the sum of jobctr and last_sec gets
2168! added to the observed sys.load.
2169!
2170! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
2171! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
2172! sub-shelled commands (rm, echo, sed...) for tests.
2173! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
2174! resulted in significant excession of the load limit, raising it
2175! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
2176! reach the limit in most test cases.
2177!
2178! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
2179! exceeding the limit for longer-running stuff (compile jobs in
2180! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
2181! small jobs' effects.
2182
2183 */
2184
2185#define LOAD_WEIGHT_A 0.25
2186#define LOAD_WEIGHT_B 0.25
2187
2188static int
2189load_too_high (void)
2190{
2191#if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__) || defined(__HAIKU__)
2192 return 1;
2193#else
2194 static double last_sec;
2195 static time_t last_now;
2196 double load, guess;
2197 time_t now;
2198
2199#ifdef WINDOWS32
2200 /* sub_proc.c cannot wait for more than MAXIMUM_WAIT_OBJECTS children */
2201 if (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
2202 return 1;
2203#endif
2204
2205 if (max_load_average < 0)
2206 return 0;
2207
2208 /* Find the real system load average. */
2209 make_access ();
2210 if (getloadavg (&load, 1) != 1)
2211 {
2212 static int lossage = -1;
2213 /* Complain only once for the same error. */
2214 if (lossage == -1 || errno != lossage)
2215 {
2216 if (errno == 0)
2217 /* An errno value of zero means getloadavg is just unsupported. */
2218 O (error, NILF,
2219 _("cannot enforce load limits on this operating system"));
2220 else
2221 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
2222 }
2223 lossage = errno;
2224 load = 0;
2225 }
2226 user_access ();
2227
2228 /* If we're in a new second zero the counter and correct the backlog
2229 value. Only keep the backlog for one extra second; after that it's 0. */
2230 now = time (NULL);
2231 if (last_now < now)
2232 {
2233 if (last_now == now - 1)
2234 last_sec = LOAD_WEIGHT_B * job_counter;
2235 else
2236 last_sec = 0.0;
2237
2238 job_counter = 0;
2239 last_now = now;
2240 }
2241
2242 /* Try to guess what the load would be right now. */
2243 guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
2244
2245 DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
2246 guess, load, max_load_average));
2247
2248 return guess >= max_load_average;
2249#endif
2250}
2251
2252/* Start jobs that are waiting for the load to be lower. */
2253
2254void
2255start_waiting_jobs (void)
2256{
2257 struct child *job;
2258
2259 if (waiting_jobs == 0)
2260 return;
2261
2262 do
2263 {
2264 /* Check for recently deceased descendants. */
2265 reap_children (0, 0);
2266
2267 /* Take a job off the waiting list. */
2268 job = waiting_jobs;
2269 waiting_jobs = job->next;
2270
2271#ifdef CONFIG_WITH_EXTENDED_NOTPARALLEL
2272 /* If it's a not-parallel job, we've already counted it once
2273 when it was queued in start_waiting_job, so decrement
2274 before sending it to start_waiting_job again. */
2275 if (job->file->command_flags & COMMANDS_NOTPARALLEL)
2276 {
2277 DB (DB_KMK, (_("not_parallel %d -> %d (file=%p `%s') [start_waiting_jobs]\n"),
2278 not_parallel, not_parallel - 1, (void *) job->file, job->file->name));
2279 assert(not_parallel > 0);
2280 --not_parallel;
2281 }
2282#endif /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
2283
2284 /* Try to start that job. We break out of the loop as soon
2285 as start_waiting_job puts one back on the waiting list. */
2286 }
2287 while (start_waiting_job (job) && waiting_jobs != 0);
2288
2289 return;
2290}
2291
2292
2293#ifndef WINDOWS32
2294
2295/* EMX: Start a child process. This function returns the new pid. */
2296# if defined __EMX__
2297int
2298child_execute_job (struct output *out, int good_stdin, char **argv, char **envp)
2299{
2300 int pid;
2301 int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
2302 int fdout = FD_STDOUT;
2303 int fderr = FD_STDERR;
2304 int save_fdin = -1;
2305 int save_fdout = -1;
2306 int save_fderr = -1;
2307
2308 /* Divert child output if we want to capture output. */
2309 if (out && out->syncout)
2310 {
2311 if (out->out >= 0)
2312 fdout = out->out;
2313 if (out->err >= 0)
2314 fderr = out->err;
2315 }
2316
2317 /* For each FD which needs to be redirected first make a dup of the standard
2318 FD to save and mark it close on exec so our child won't see it. Then
2319 dup2() the standard FD to the redirect FD, and also mark the redirect FD
2320 as close on exec. */
2321 if (fdin != FD_STDIN)
2322 {
2323 save_fdin = dup (FD_STDIN);
2324 if (save_fdin < 0)
2325 O (fatal, NILF, _("no more file handles: could not duplicate stdin\n"));
2326 CLOSE_ON_EXEC (save_fdin);
2327
2328 dup2 (fdin, FD_STDIN);
2329 CLOSE_ON_EXEC (fdin);
2330 }
2331
2332 if (fdout != FD_STDOUT)
2333 {
2334 save_fdout = dup (FD_STDOUT);
2335 if (save_fdout < 0)
2336 O (fatal, NILF,
2337 _("no more file handles: could not duplicate stdout\n"));
2338 CLOSE_ON_EXEC (save_fdout);
2339
2340 dup2 (fdout, FD_STDOUT);
2341 CLOSE_ON_EXEC (fdout);
2342 }
2343
2344 if (fderr != FD_STDERR)
2345 {
2346 if (fderr != fdout)
2347 {
2348 save_fderr = dup (FD_STDERR);
2349 if (save_fderr < 0)
2350 O (fatal, NILF,
2351 _("no more file handles: could not duplicate stderr\n"));
2352 CLOSE_ON_EXEC (save_fderr);
2353 }
2354
2355 dup2 (fderr, FD_STDERR);
2356 CLOSE_ON_EXEC (fderr);
2357 }
2358
2359 /* Run the command. */
2360 pid = exec_command (argv, envp);
2361
2362 /* Restore stdout/stdin/stderr of the parent and close temporary FDs. */
2363 if (save_fdin >= 0)
2364 {
2365 if (dup2 (save_fdin, FD_STDIN) != FD_STDIN)
2366 O (fatal, NILF, _("Could not restore stdin\n"));
2367 else
2368 close (save_fdin);
2369 }
2370
2371 if (save_fdout >= 0)
2372 {
2373 if (dup2 (save_fdout, FD_STDOUT) != FD_STDOUT)
2374 O (fatal, NILF, _("Could not restore stdout\n"));
2375 else
2376 close (save_fdout);
2377 }
2378
2379 if (save_fderr >= 0)
2380 {
2381 if (dup2 (save_fderr, FD_STDERR) != FD_STDERR)
2382 O (fatal, NILF, _("Could not restore stderr\n"));
2383 else
2384 close (save_fderr);
2385 }
2386
2387 return pid;
2388}
2389
2390#elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
2391
2392/* POSIX:
2393 Create a child process executing the command in ARGV.
2394 ENVP is the environment of the new program. Returns the PID or -1. */
2395int
2396child_execute_job (struct output *out, int good_stdin, char **argv, char **envp)
2397{
2398 int r;
2399 int pid;
2400 int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
2401 int fdout = FD_STDOUT;
2402 int fderr = FD_STDERR;
2403
2404 /* Divert child output if we want to capture it. */
2405 if (out && out->syncout)
2406 {
2407 if (out->out >= 0)
2408 fdout = out->out;
2409 if (out->err >= 0)
2410 fderr = out->err;
2411 }
2412
2413 pid = vfork();
2414 if (pid != 0)
2415 return pid;
2416
2417 /* We are the child. */
2418 unblock_sigs ();
2419
2420#ifdef SET_STACK_SIZE
2421 /* Reset limits, if necessary. */
2422 if (stack_limit.rlim_cur)
2423 setrlimit (RLIMIT_STACK, &stack_limit);
2424#endif
2425
2426 /* For any redirected FD, dup2() it to the standard FD.
2427 They are all marked close-on-exec already. */
2428 if (fdin != FD_STDIN)
2429 EINTRLOOP (r, dup2 (fdin, FD_STDIN));
2430 if (fdout != FD_STDOUT)
2431 EINTRLOOP (r, dup2 (fdout, FD_STDOUT));
2432 if (fderr != FD_STDERR)
2433 EINTRLOOP (r, dup2 (fderr, FD_STDERR));
2434
2435 /* Run the command. */
2436 exec_command (argv, envp);
2437}
2438#endif /* !AMIGA && !__MSDOS__ && !VMS */
2439#endif /* !WINDOWS32 */
2440
2441
2442#ifndef _AMIGA
2443/* Replace the current process with one running the command in ARGV,
2444 with environment ENVP. This function does not return. */
2445
2446/* EMX: This function returns the pid of the child process. */
2447# ifdef __EMX__
2448int
2449# else
2450void
2451# endif
2452exec_command (char **argv, char **envp)
2453{
2454#ifdef VMS
2455 /* to work around a problem with signals and execve: ignore them */
2456#ifdef SIGCHLD
2457 signal (SIGCHLD,SIG_IGN);
2458#endif
2459 /* Run the program. */
2460 execve (argv[0], argv, envp);
2461 perror_with_name ("execve: ", argv[0]);
2462 _exit (EXIT_FAILURE);
2463#else
2464#ifdef WINDOWS32
2465 HANDLE hPID;
2466 HANDLE hWaitPID;
2467 int exit_code = EXIT_FAILURE;
2468
2469 /* make sure CreateProcess() has Path it needs */
2470 sync_Path_environment ();
2471
2472 /* launch command */
2473 hPID = process_easy (argv, envp, -1, -1);
2474
2475 /* make sure launch ok */
2476 if (hPID == INVALID_HANDLE_VALUE)
2477 {
2478 int i;
2479 fprintf (stderr, _("process_easy() failed to launch process (e=%ld)\n"),
2480 process_last_err (hPID));
2481 for (i = 0; argv[i]; i++)
2482 fprintf (stderr, "%s ", argv[i]);
2483 fprintf (stderr, _("\nCounted %d args in failed launch\n"), i);
2484 exit (EXIT_FAILURE);
2485 }
2486
2487 /* wait and reap last child */
2488 hWaitPID = process_wait_for_any (1, 0);
2489 while (hWaitPID)
2490 {
2491 /* was an error found on this process? */
2492 int err = process_last_err (hWaitPID);
2493
2494 /* get exit data */
2495 exit_code = process_exit_code (hWaitPID);
2496
2497 if (err)
2498 fprintf (stderr, "make (e=%d, rc=%d): %s",
2499 err, exit_code, map_windows32_error_to_string (err));
2500
2501 /* cleanup process */
2502 process_cleanup (hWaitPID);
2503
2504 /* expect to find only last pid, warn about other pids reaped */
2505 if (hWaitPID == hPID)
2506 break;
2507 else
2508 {
2509 char *pidstr = xstrdup (pid2str ((pid_t)hWaitPID));
2510
2511 fprintf (stderr,
2512 _("make reaped child pid %s, still waiting for pid %s\n"),
2513 pidstr, pid2str ((pid_t)hPID));
2514 free (pidstr);
2515 }
2516 }
2517
2518 /* return child's exit code as our exit code */
2519 exit (exit_code);
2520
2521#else /* !WINDOWS32 */
2522
2523# ifdef __EMX__
2524 int pid;
2525# endif
2526
2527 /* Be the user, permanently. */
2528 child_access ();
2529
2530# ifdef __EMX__
2531 /* Run the program. */
2532 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2533 if (pid >= 0)
2534 return pid;
2535
2536 /* the file might have a strange shell extension */
2537 if (errno == ENOENT)
2538 errno = ENOEXEC;
2539
2540# else
2541 /* Run the program. */
2542 environ = envp;
2543 execvp (argv[0], argv);
2544
2545# endif /* !__EMX__ */
2546
2547 switch (errno)
2548 {
2549 case ENOENT:
2550 /* We are in the child: don't use the output buffer.
2551 It's not right to run fprintf() here! */
2552 if (makelevel == 0)
2553 fprintf (stderr, _("%s: %s: Command not found\n"), program, argv[0]);
2554 else
2555 fprintf (stderr, _("%s[%u]: %s: Command not found\n"),
2556 program, makelevel, argv[0]);
2557 break;
2558 case ENOEXEC:
2559 {
2560 /* The file is not executable. Try it as a shell script. */
2561 const char *shell;
2562 char **new_argv;
2563 int argc;
2564 int i=1;
2565
2566# ifdef __EMX__
2567 /* Do not use $SHELL from the environment */
2568 struct variable *p = lookup_variable ("SHELL", 5);
2569 if (p)
2570 shell = p->value;
2571 else
2572 shell = 0;
2573# else
2574 shell = getenv ("SHELL");
2575# endif
2576 if (shell == 0)
2577 shell = default_shell;
2578
2579 argc = 1;
2580 while (argv[argc] != 0)
2581 ++argc;
2582
2583# ifdef __EMX__
2584 if (!unixy_shell)
2585 ++argc;
2586# endif
2587
2588 new_argv = alloca ((1 + argc + 1) * sizeof (char *));
2589 new_argv[0] = (char *)shell;
2590
2591# ifdef __EMX__
2592 if (!unixy_shell)
2593 {
2594 new_argv[1] = "/c";
2595 ++i;
2596 --argc;
2597 }
2598# endif
2599
2600 new_argv[i] = argv[0];
2601 while (argc > 0)
2602 {
2603 new_argv[i + argc] = argv[argc];
2604 --argc;
2605 }
2606
2607# ifdef __EMX__
2608 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2609 if (pid >= 0)
2610 break;
2611# else
2612 execvp (shell, new_argv);
2613# endif
2614 if (errno == ENOENT)
2615 OS (error, NILF, _("%s: Shell program not found"), shell);
2616 else
2617 perror_with_name ("execvp: ", shell);
2618 break;
2619 }
2620
2621# ifdef __EMX__
2622 case EINVAL:
2623 /* this nasty error was driving me nuts :-( */
2624 O (error, NILF, _("spawnvpe: environment space might be exhausted"));
2625 /* FALLTHROUGH */
2626# endif
2627
2628 default:
2629 perror_with_name ("execvp: ", argv[0]);
2630 break;
2631 }
2632
2633# ifdef __EMX__
2634 return pid;
2635# else
2636 _exit (127);
2637# endif
2638#endif /* !WINDOWS32 */
2639#endif /* !VMS */
2640}
2641#else /* On Amiga */
2642void
2643exec_command (char **argv)
2644{
2645 MyExecute (argv);
2646}
2647
2648void clean_tmp (void)
2649{
2650 DeleteFile (amiga_bname);
2651}
2652
2653#endif /* On Amiga */
2654
2655
2656#ifndef VMS
2657/* Figure out the argument list necessary to run LINE as a command. Try to
2658 avoid using a shell. This routine handles only ' quoting, and " quoting
2659 when no backslash, $ or ' characters are seen in the quotes. Starting
2660 quotes may be escaped with a backslash. If any of the characters in
2661 sh_chars is seen, or any of the builtin commands listed in sh_cmds
2662 is the first word of a line, the shell is used.
2663
2664 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2665 If *RESTP is NULL, newlines will be ignored.
2666
2667 SHELL is the shell to use, or nil to use the default shell.
2668 IFS is the value of $IFS, or nil (meaning the default).
2669
2670 FLAGS is the value of lines_flags for this command line. It is
2671 used in the WINDOWS32 port to check whether + or $(MAKE) were found
2672 in this command line, in which case the effect of just_print_flag
2673 is overridden. */
2674
2675static char **
2676construct_command_argv_internal (char *line, char **restp, const char *shell,
2677 const char *shellflags, const char *ifs,
2678 int flags, char **batch_filename UNUSED)
2679{
2680#ifdef __MSDOS__
2681 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2682 We call 'system' for anything that requires ''slow'' processing,
2683 because DOS shells are too dumb. When $SHELL points to a real
2684 (unix-style) shell, 'system' just calls it to do everything. When
2685 $SHELL points to a DOS shell, 'system' does most of the work
2686 internally, calling the shell only for its internal commands.
2687 However, it looks on the $PATH first, so you can e.g. have an
2688 external command named 'mkdir'.
2689
2690 Since we call 'system', certain characters and commands below are
2691 actually not specific to COMMAND.COM, but to the DJGPP implementation
2692 of 'system'. In particular:
2693
2694 The shell wildcard characters are in DOS_CHARS because they will
2695 not be expanded if we call the child via 'spawnXX'.
2696
2697 The ';' is in DOS_CHARS, because our 'system' knows how to run
2698 multiple commands on a single line.
2699
2700 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2701 won't have to tell one from another and have one more set of
2702 commands and special characters. */
2703 static const char *sh_chars_dos = "*?[];|<>%^&()";
2704 static const char *sh_cmds_dos[] =
2705 { "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty", "date",
2706 "del", "dir", "echo", "erase", "exit", "for", "goto", "if", "md",
2707 "mkdir", "path", "pause", "prompt", "rd", "rmdir", "rem", "ren",
2708 "rename", "set", "shift", "time", "type", "ver", "verify", "vol", ":",
2709 0 };
2710
2711 static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^";
2712 static const char *sh_cmds_sh[] =
2713 { "cd", "echo", "eval", "exec", "exit", "login", "logout", "set", "umask",
2714 "wait", "while", "for", "case", "if", ":", ".", "break", "continue",
2715 "export", "read", "readonly", "shift", "times", "trap", "switch",
2716 "unset", "ulimit", 0 };
2717
2718 const char *sh_chars;
2719 const char **sh_cmds;
2720
2721#elif defined (__EMX__)
2722 static const char *sh_chars_dos = "*?[];|<>%^&()";
2723 static const char *sh_cmds_dos[] =
2724 { "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty", "date",
2725 "del", "dir", "echo", "erase", "exit", "for", "goto", "if", "md",
2726 "mkdir", "path", "pause", "prompt", "rd", "rmdir", "rem", "ren",
2727 "rename", "set", "shift", "time", "type", "ver", "verify", "vol", ":",
2728 0 };
2729
2730 static const char *sh_chars_os2 = "*?[];|<>%^()\"'&";
2731 static const char *sh_cmds_os2[] =
2732 { "call", "cd", "chcp", "chdir", "cls", "copy", "date", "del", "detach",
2733 "dir", "echo", "endlocal", "erase", "exit", "for", "goto", "if", "keys",
2734 "md", "mkdir", "move", "path", "pause", "prompt", "rd", "rem", "ren",
2735 "rename", "rmdir", "set", "setlocal", "shift", "start", "time", "type",
2736 "ver", "verify", "vol", ":", 0 };
2737
2738 static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^~'";
2739 static const char *sh_cmds_sh[] =
2740 { "echo", "cd", "eval", "exec", "exit", "login", "logout", "set", "umask",
2741 "wait", "while", "for", "case", "if", ":", ".", "break", "continue",
2742 "export", "read", "readonly", "shift", "times", "trap", "switch",
2743 "unset", 0 };
2744
2745 const char *sh_chars;
2746 const char **sh_cmds;
2747
2748#elif defined (_AMIGA)
2749 static const char *sh_chars = "#;\"|<>()?*$`";
2750 static const char *sh_cmds[] =
2751 { "cd", "eval", "if", "delete", "echo", "copy", "rename", "set", "setenv",
2752 "date", "makedir", "skip", "else", "endif", "path", "prompt", "unset",
2753 "unsetenv", "version", 0 };
2754
2755#elif defined (WINDOWS32)
2756 /* We used to have a double quote (") in sh_chars_dos[] below, but
2757 that caused any command line with quoted file names be run
2758 through a temporary batch file, which introduces command-line
2759 limit of 4K charcaters imposed by cmd.exe. Since CreateProcess
2760 can handle quoted file names just fine, removing the quote lifts
2761 the limit from a very frequent use case, because using quoted
2762 file names is commonplace on MS-Windows. */
2763 static const char *sh_chars_dos = "|&<>";
2764 static const char *sh_cmds_dos[] =
2765 { "assoc", "break", "call", "cd", "chcp", "chdir", "cls", "color", "copy",
2766 "ctty", "date", "del", "dir", "echo", "echo.", "endlocal", "erase",
2767 "exit", "for", "ftype", "goto", "if", "if", "md", "mkdir", "move",
2768 "path", "pause", "prompt", "rd", "rem", "ren", "rename", "rmdir",
2769 "set", "setlocal", "shift", "time", "title", "type", "ver", "verify",
2770 "vol", ":", 0 };
2771
2772 static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^";
2773 static const char *sh_cmds_sh[] =
2774 { "cd", "eval", "exec", "exit", "login", "logout", "set", "umask", "wait",
2775 "while", "for", "case", "if", ":", ".", "break", "continue", "export",
2776 "read", "readonly", "shift", "times", "trap", "switch", "test",
2777#ifdef BATCH_MODE_ONLY_SHELL
2778 "echo",
2779#endif
2780 0 };
2781
2782 const char *sh_chars;
2783 const char **sh_cmds;
2784#elif defined(__riscos__)
2785 static const char *sh_chars = "";
2786 static const char *sh_cmds[] = { 0 };
2787#else /* must be UNIX-ish */
2788 static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^~!"; /* kmk: +_sh */
2789 static const char *sh_cmds_sh[] = /* kmk: +_sh */
2790 { ".", ":", "break", "case", "cd", "continue", "eval", "exec", "exit",
2791 "export", "for", "if", "login", "logout", "read", "readonly", "set",
2792 "shift", "switch", "test", "times", "trap", "ulimit", "umask", "unset",
2793 "wait", "while", 0 };
2794
2795# if 0 /*def HAVE_DOS_PATHS - kmk */
2796 /* This is required if the MSYS/Cygwin ports (which do not define
2797 WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
2798 sh_chars_sh directly (see below). The value must be identical
2799 to that of sh_chars immediately above. */
2800 static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^~!";
2801# endif /* HAVE_DOS_PATHS */
2802 char* sh_chars = sh_chars_sh; /* kmk: +_sh */
2803 char** sh_cmds = sh_cmds_sh; /* kmk: +_sh */
2804#endif
2805#ifdef KMK
2806 static char sh_chars_kash[] = "#;*?[]&|<>(){}$`^~!"; /* note: no \" - good idea? */
2807 static char *sh_cmds_kash[] = {
2808 ".", ":", "break", "case", "cd", "continue", "echo", "eval", "exec", "exit",
2809 "export", "for", "if", "login", "logout", "read", "readonly", "set",
2810 "shift", "switch", "test", "times", "trap", "umask", "wait", "while", 0 /* +echo, -ulimit, -unset */
2811 };
2812 int is_kmk_shell = 0;
2813#endif
2814 int i;
2815 char *p;
2816#ifndef NDEBUG
2817 char *end;
2818#endif
2819 char *ap;
2820 const char *cap;
2821 const char *cp;
2822 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2823 char **new_argv = 0;
2824 char *argstr = 0;
2825#ifdef WINDOWS32
2826 int slow_flag = 0;
2827
2828 if (!unixy_shell)
2829 {
2830 sh_cmds = sh_cmds_dos;
2831 sh_chars = sh_chars_dos;
2832 }
2833 else
2834 {
2835 sh_cmds = sh_cmds_sh;
2836 sh_chars = sh_chars_sh;
2837 }
2838#endif /* WINDOWS32 */
2839
2840 if (restp != NULL)
2841 *restp = NULL;
2842
2843 /* Make sure not to bother processing an empty line but stop at newline. */
2844 while (ISBLANK (*line))
2845 ++line;
2846 if (*line == '\0')
2847 return 0;
2848
2849 if (shellflags == 0)
2850 shellflags = posix_pedantic ? "-ec" : "-c";
2851
2852 /* See if it is safe to parse commands internally. */
2853#ifdef KMK /* kmk_ash and kmk_kash are both fine, kmk_ash is the default btw. */
2854 if (shell == 0)
2855 {
2856 is_kmk_shell = 1;
2857 shell = (char *)get_default_kbuild_shell ();
2858 }
2859 else if (!strcmp (shell, get_default_kbuild_shell()))
2860 is_kmk_shell = 1;
2861 else
2862 {
2863 const char *psz = strstr (shell, "/kmk_ash");
2864 if (psz)
2865 psz += sizeof ("/kmk_ash") - 1;
2866 else
2867 {
2868 psz = strstr (shell, "/kmk_kash");
2869 if (psz)
2870 psz += sizeof ("/kmk_kash") - 1;
2871 }
2872# if defined (__OS2__) || defined (_WIN32) || defined (WINDOWS32)
2873 is_kmk_shell = psz && (*psz == '\0' || !stricmp (psz, ".exe"));
2874# else
2875 is_kmk_shell = psz && *psz == '\0';
2876# endif
2877 }
2878 if (is_kmk_shell)
2879 {
2880 sh_chars = sh_chars_kash;
2881 sh_cmds = sh_cmds_kash;
2882 }
2883#else /* !KMK */
2884 if (shell == 0)
2885 shell = default_shell;
2886#endif /* !KMK */
2887#ifdef WINDOWS32
2888 else if (strcmp (shell, default_shell))
2889 {
2890 char *s1 = _fullpath (NULL, shell, 0);
2891 char *s2 = _fullpath (NULL, default_shell, 0);
2892
2893 slow_flag = strcmp ((s1 ? s1 : ""), (s2 ? s2 : ""));
2894
2895 free (s1);
2896 free (s2);
2897 }
2898 if (slow_flag)
2899 goto slow;
2900#else /* not WINDOWS32 */
2901#if defined (__MSDOS__) || defined (__EMX__)
2902 else if (strcasecmp (shell, default_shell))
2903 {
2904 extern int _is_unixy_shell (const char *_path);
2905
2906 DB (DB_BASIC, (_("$SHELL changed (was '%s', now '%s')\n"),
2907 default_shell, shell));
2908 unixy_shell = _is_unixy_shell (shell);
2909 /* we must allocate a copy of shell: construct_command_argv() will free
2910 * shell after this function returns. */
2911 default_shell = xstrdup (shell);
2912 }
2913# ifdef KMK
2914 if (is_kmk_shell)
2915 { /* done above already */ }
2916 else
2917# endif
2918 if (unixy_shell)
2919 {
2920 sh_chars = sh_chars_sh;
2921 sh_cmds = sh_cmds_sh;
2922 }
2923 else
2924 {
2925 sh_chars = sh_chars_dos;
2926 sh_cmds = sh_cmds_dos;
2927# ifdef __EMX__
2928 if (_osmode == OS2_MODE)
2929 {
2930 sh_chars = sh_chars_os2;
2931 sh_cmds = sh_cmds_os2;
2932 }
2933# endif
2934 }
2935#else /* !__MSDOS__ */
2936 else if (strcmp (shell, default_shell))
2937 goto slow;
2938#endif /* !__MSDOS__ && !__EMX__ */
2939#endif /* not WINDOWS32 */
2940
2941 if (ifs)
2942 for (cap = ifs; *cap != '\0'; ++cap)
2943 if (*cap != ' ' && *cap != '\t' && *cap != '\n')
2944 goto slow;
2945
2946 if (shellflags)
2947 if (shellflags[0] != '-'
2948 || ((shellflags[1] != 'c' || shellflags[2] != '\0')
2949 && (shellflags[1] != 'e' || shellflags[2] != 'c' || shellflags[3] != '\0')))
2950 goto slow;
2951
2952 i = strlen (line) + 1;
2953
2954 /* More than 1 arg per character is impossible. */
2955 new_argv = xmalloc (i * sizeof (char *));
2956
2957 /* All the args can fit in a buffer as big as LINE is. */
2958 ap = new_argv[0] = argstr = xmalloc (i);
2959#ifndef NDEBUG
2960 end = ap + i;
2961#endif
2962
2963 /* I is how many complete arguments have been found. */
2964 i = 0;
2965 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2966 for (p = line; *p != '\0'; ++p)
2967 {
2968 assert (ap <= end);
2969
2970 if (instring)
2971 {
2972 /* Inside a string, just copy any char except a closing quote
2973 or a backslash-newline combination. */
2974 if (*p == instring)
2975 {
2976 instring = 0;
2977 if (ap == new_argv[0] || *(ap-1) == '\0')
2978 last_argument_was_empty = 1;
2979 }
2980 else if (*p == '\\' && p[1] == '\n')
2981 {
2982 /* Backslash-newline is handled differently depending on what
2983 kind of string we're in: inside single-quoted strings you
2984 keep them; in double-quoted strings they disappear. For
2985 DOS/Windows/OS2, if we don't have a POSIX shell, we keep the
2986 pre-POSIX behavior of removing the backslash-newline. */
2987 if (instring == '"'
2988#if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2989 || !unixy_shell
2990#endif
2991 )
2992 ++p;
2993 else
2994 {
2995 *(ap++) = *(p++);
2996 *(ap++) = *p;
2997 }
2998 }
2999 else if (*p == '\n' && restp != NULL)
3000 {
3001 /* End of the command line. */
3002 *restp = p;
3003 goto end_of_line;
3004 }
3005 /* Backslash, $, and ` are special inside double quotes.
3006 If we see any of those, punt.
3007 But on MSDOS, if we use COMMAND.COM, double and single
3008 quotes have the same effect. */
3009 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
3010 goto slow;
3011#ifdef WINDOWS32
3012 /* Quoted wildcard characters must be passed quoted to the
3013 command, so give up the fast route. */
3014 else if (instring == '"' && strchr ("*?", *p) != 0 && !unixy_shell)
3015 goto slow;
3016 else if (instring == '"' && strncmp (p, "\\\"", 2) == 0)
3017 *ap++ = *++p;
3018#endif
3019 else
3020 *ap++ = *p;
3021 }
3022 else if (strchr (sh_chars, *p) != 0)
3023#ifdef KMK
3024 {
3025 /* Tilde is only special if at the start of a path spec,
3026 i.e. don't get excited when we by 8.3 files on windows. */
3027 if ( *p == '~'
3028 && p > line
3029 && !ISSPACE (p[-1])
3030 && p[-1] != '='
3031 && p[-1] != ':'
3032 && p[-1] != '"'
3033 && p[-1] != '\'')
3034 *ap++ = *p;
3035 else
3036 /* Not inside a string, but it's a special char. */
3037 goto slow;
3038 }
3039#else /* !KMK */
3040 /* Not inside a string, but it's a special char. */
3041 goto slow;
3042#endif /* !KMK */
3043 else if (one_shell && *p == '\n')
3044 /* In .ONESHELL mode \n is a separator like ; or && */
3045 goto slow;
3046#ifdef __MSDOS__
3047 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
3048 /* '...' is a wildcard in DJGPP. */
3049 goto slow;
3050#endif
3051 else
3052 /* Not a special char. */
3053 switch (*p)
3054 {
3055 case '=':
3056 /* Equals is a special character in leading words before the
3057 first word with no equals sign in it. This is not the case
3058 with sh -k, but we never get here when using nonstandard
3059 shell flags. */
3060 if (! seen_nonequals && unixy_shell)
3061 goto slow;
3062 word_has_equals = 1;
3063 *ap++ = '=';
3064 break;
3065
3066 case '\\':
3067 /* Backslash-newline has special case handling, ref POSIX.
3068 We're in the fastpath, so emulate what the shell would do. */
3069 if (p[1] == '\n')
3070 {
3071 /* Throw out the backslash and newline. */
3072 ++p;
3073
3074 /* At the beginning of the argument, skip any whitespace other
3075 than newline before the start of the next word. */
3076 if (ap == new_argv[i])
3077 while (ISBLANK (p[1]))
3078 ++p;
3079 }
3080#ifdef WINDOWS32
3081 /* Backslash before whitespace is not special if our shell
3082 is not Unixy. */
3083 else if (ISSPACE (p[1]) && !unixy_shell)
3084 {
3085 *ap++ = *p;
3086 break;
3087 }
3088#endif
3089 else if (p[1] != '\0')
3090 {
3091#ifdef HAVE_DOS_PATHS
3092 /* Only remove backslashes before characters special to Unixy
3093 shells. All other backslashes are copied verbatim, since
3094 they are probably DOS-style directory separators. This
3095 still leaves a small window for problems, but at least it
3096 should work for the vast majority of naive users. */
3097
3098#ifdef __MSDOS__
3099 /* A dot is only special as part of the "..."
3100 wildcard. */
3101 if (strneq (p + 1, ".\\.\\.", 5))
3102 {
3103 *ap++ = '.';
3104 *ap++ = '.';
3105 p += 4;
3106 }
3107 else
3108#endif
3109 if (p[1] != '\\' && p[1] != '\''
3110 && !ISSPACE (p[1])
3111# ifdef KMK
3112 && strchr (sh_chars, p[1]) == 0
3113 && (p[1] != '"' || !unixy_shell))
3114# else
3115 && strchr (sh_chars_sh, p[1]) == 0)
3116# endif
3117 /* back up one notch, to copy the backslash */
3118 --p;
3119#endif /* HAVE_DOS_PATHS */
3120
3121 /* Copy and skip the following char. */
3122 *ap++ = *++p;
3123 }
3124 break;
3125
3126 case '\'':
3127 case '"':
3128 instring = *p;
3129 break;
3130
3131 case '\n':
3132 if (restp != NULL)
3133 {
3134 /* End of the command line. */
3135 *restp = p;
3136 goto end_of_line;
3137 }
3138 else
3139 /* Newlines are not special. */
3140 *ap++ = '\n';
3141 break;
3142
3143 case ' ':
3144 case '\t':
3145 /* We have the end of an argument.
3146 Terminate the text of the argument. */
3147 *ap++ = '\0';
3148 new_argv[++i] = ap;
3149 last_argument_was_empty = 0;
3150
3151 /* Update SEEN_NONEQUALS, which tells us if every word
3152 heretofore has contained an '='. */
3153 seen_nonequals |= ! word_has_equals;
3154 if (word_has_equals && ! seen_nonequals)
3155 /* An '=' in a word before the first
3156 word without one is magical. */
3157 goto slow;
3158 word_has_equals = 0; /* Prepare for the next word. */
3159
3160 /* If this argument is the command name,
3161 see if it is a built-in shell command.
3162 If so, have the shell handle it. */
3163 if (i == 1)
3164 {
3165 register int j;
3166 for (j = 0; sh_cmds[j] != 0; ++j)
3167 {
3168 if (streq (sh_cmds[j], new_argv[0]))
3169 goto slow;
3170#if defined(__EMX__) || defined(WINDOWS32)
3171 /* Non-Unix shells are case insensitive. */
3172 if (!unixy_shell
3173 && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
3174 goto slow;
3175#endif
3176 }
3177 }
3178
3179 /* Skip whitespace chars, but not newlines. */
3180 while (ISBLANK (p[1]))
3181 ++p;
3182 break;
3183
3184 default:
3185 *ap++ = *p;
3186 break;
3187 }
3188 }
3189 end_of_line:
3190
3191 if (instring)
3192 /* Let the shell deal with an unterminated quote. */
3193 goto slow;
3194
3195 /* Terminate the last argument and the argument list. */
3196
3197 *ap = '\0';
3198 if (new_argv[i][0] != '\0' || last_argument_was_empty)
3199 ++i;
3200 new_argv[i] = 0;
3201
3202 if (i == 1)
3203 {
3204 register int j;
3205 for (j = 0; sh_cmds[j] != 0; ++j)
3206 if (streq (sh_cmds[j], new_argv[0]))
3207 goto slow;
3208 }
3209
3210 if (new_argv[0] == 0)
3211 {
3212 /* Line was empty. */
3213 free (argstr);
3214 free (new_argv);
3215 return 0;
3216 }
3217
3218 return new_argv;
3219
3220 slow:;
3221 /* We must use the shell. */
3222
3223 if (new_argv != 0)
3224 {
3225 /* Free the old argument list we were working on. */
3226 free (argstr);
3227 free (new_argv);
3228 }
3229
3230#ifdef __MSDOS__
3231 execute_by_shell = 1; /* actually, call 'system' if shell isn't unixy */
3232#endif
3233
3234#ifdef _AMIGA
3235 {
3236 char *ptr;
3237 char *buffer;
3238 char *dptr;
3239
3240 buffer = xmalloc (strlen (line)+1);
3241
3242 ptr = line;
3243 for (dptr=buffer; *ptr; )
3244 {
3245 if (*ptr == '\\' && ptr[1] == '\n')
3246 ptr += 2;
3247 else if (*ptr == '@') /* Kludge: multiline commands */
3248 {
3249 ptr += 2;
3250 *dptr++ = '\n';
3251 }
3252 else
3253 *dptr++ = *ptr++;
3254 }
3255 *dptr = 0;
3256
3257 new_argv = xmalloc (2 * sizeof (char *));
3258 new_argv[0] = buffer;
3259 new_argv[1] = 0;
3260 }
3261#else /* Not Amiga */
3262#ifdef WINDOWS32
3263 /*
3264 * Not eating this whitespace caused things like
3265 *
3266 * sh -c "\n"
3267 *
3268 * which gave the shell fits. I think we have to eat
3269 * whitespace here, but this code should be considered
3270 * suspicious if things start failing....
3271 */
3272
3273 /* Make sure not to bother processing an empty line. */
3274 NEXT_TOKEN (line);
3275 if (*line == '\0')
3276 return 0;
3277#endif /* WINDOWS32 */
3278
3279 {
3280 /* SHELL may be a multi-word command. Construct a command line
3281 "$(SHELL) $(.SHELLFLAGS) LINE", with all special chars in LINE escaped.
3282 Then recurse, expanding this command line to get the final
3283 argument list. */
3284
3285 char *new_line;
3286 unsigned int shell_len = strlen (shell);
3287 unsigned int line_len = strlen (line);
3288 unsigned int sflags_len = shellflags ? strlen (shellflags) : 0;
3289#ifdef WINDOWS32
3290 char *command_ptr = NULL; /* used for batch_mode_shell mode */
3291#endif
3292
3293# ifdef __EMX__ /* is this necessary? */
3294 if (!unixy_shell && shellflags)
3295 shellflags[0] = '/'; /* "/c" */
3296# endif
3297
3298 /* In .ONESHELL mode we are allowed to throw the entire current
3299 recipe string at a single shell and trust that the user
3300 has configured the shell and shell flags, and formatted
3301 the string, appropriately. */
3302 if (one_shell)
3303 {
3304 /* If the shell is Bourne compatible, we must remove and ignore
3305 interior special chars [@+-] because they're meaningless to
3306 the shell itself. If, however, we're in .ONESHELL mode and
3307 have changed SHELL to something non-standard, we should
3308 leave those alone because they could be part of the
3309 script. In this case we must also leave in place
3310 any leading [@+-] for the same reason. */
3311
3312 /* Remove and ignore interior prefix chars [@+-] because they're
3313 meaningless given a single shell. */
3314#if defined __MSDOS__ || defined (__EMX__)
3315 if (unixy_shell) /* the test is complicated and we already did it */
3316#else
3317 if (is_bourne_compatible_shell (shell)
3318#ifdef WINDOWS32
3319 /* If we didn't find any sh.exe, don't behave is if we did! */
3320 && !no_default_sh_exe
3321#endif
3322 )
3323#endif
3324 {
3325 const char *f = line;
3326 char *t = line;
3327
3328 /* Copy the recipe, removing and ignoring interior prefix chars
3329 [@+-]: they're meaningless in .ONESHELL mode. */
3330 while (f[0] != '\0')
3331 {
3332 int esc = 0;
3333
3334 /* This is the start of a new recipe line. Skip whitespace
3335 and prefix characters but not newlines. */
3336 while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
3337 ++f;
3338
3339 /* Copy until we get to the next logical recipe line. */
3340 while (*f != '\0')
3341 {
3342 *(t++) = *(f++);
3343 if (f[-1] == '\\')
3344 esc = !esc;
3345 else
3346 {
3347 /* On unescaped newline, we're done with this line. */
3348 if (f[-1] == '\n' && ! esc)
3349 break;
3350
3351 /* Something else: reset the escape sequence. */
3352 esc = 0;
3353 }
3354 }
3355 }
3356 *t = '\0';
3357 }
3358#ifdef WINDOWS32
3359 else /* non-Posix shell (cmd.exe etc.) */
3360 {
3361 const char *f = line;
3362 char *t = line;
3363 char *tstart = t;
3364 int temp_fd;
3365 FILE* batch = NULL;
3366 int id = GetCurrentProcessId ();
3367 PATH_VAR(fbuf);
3368
3369 /* Generate a file name for the temporary batch file. */
3370 sprintf (fbuf, "make%d", id);
3371 *batch_filename = create_batch_file (fbuf, 0, &temp_fd);
3372 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3373 *batch_filename));
3374
3375 /* Create a FILE object for the batch file, and write to it the
3376 commands to be executed. Put the batch file in TEXT mode. */
3377 _setmode (temp_fd, _O_TEXT);
3378 batch = _fdopen (temp_fd, "wt");
3379 fputs ("@echo off\n", batch);
3380 DB (DB_JOBS, (_("Batch file contents:\n\t@echo off\n")));
3381
3382 /* Copy the recipe, removing and ignoring interior prefix chars
3383 [@+-]: they're meaningless in .ONESHELL mode. */
3384 while (*f != '\0')
3385 {
3386 /* This is the start of a new recipe line. Skip whitespace
3387 and prefix characters but not newlines. */
3388 while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
3389 ++f;
3390
3391 /* Copy until we get to the next logical recipe line. */
3392 while (*f != '\0')
3393 {
3394 /* Remove the escaped newlines in the command, and the
3395 blanks that follow them. Windows shells cannot handle
3396 escaped newlines. */
3397 if (*f == '\\' && f[1] == '\n')
3398 {
3399 f += 2;
3400 while (ISBLANK (*f))
3401 ++f;
3402 }
3403 *(t++) = *(f++);
3404 /* On an unescaped newline, we're done with this
3405 line. */
3406 if (f[-1] == '\n')
3407 break;
3408 }
3409 /* Write another line into the batch file. */
3410 if (t > tstart)
3411 {
3412 char c = *t;
3413 *t = '\0';
3414 fputs (tstart, batch);
3415 DB (DB_JOBS, ("\t%s", tstart));
3416 tstart = t;
3417 *t = c;
3418 }
3419 }
3420 DB (DB_JOBS, ("\n"));
3421 fclose (batch);
3422
3423 /* Create an argv list for the shell command line that
3424 will run the batch file. */
3425 new_argv = xmalloc (2 * sizeof (char *));
3426 new_argv[0] = xstrdup (*batch_filename);
3427 new_argv[1] = NULL;
3428 return new_argv;
3429 }
3430#endif /* WINDOWS32 */
3431 /* Create an argv list for the shell command line. */
3432 {
3433 int n = 0;
3434
3435 new_argv = xmalloc ((4 + sflags_len/2) * sizeof (char *));
3436 new_argv[n++] = xstrdup (shell);
3437
3438 /* Chop up the shellflags (if any) and assign them. */
3439 if (! shellflags)
3440 new_argv[n++] = xstrdup ("");
3441 else
3442 {
3443 const char *s = shellflags;
3444 char *t;
3445 unsigned int len;
3446 while ((t = find_next_token (&s, &len)) != 0)
3447 new_argv[n++] = xstrndup (t, len);
3448 }
3449
3450 /* Set the command to invoke. */
3451 new_argv[n++] = line;
3452 new_argv[n++] = NULL;
3453 }
3454 return new_argv;
3455 }
3456
3457 new_line = xmalloc ((shell_len*2) + 1 + sflags_len + 1
3458 + (line_len*2) + 1);
3459 ap = new_line;
3460 /* Copy SHELL, escaping any characters special to the shell. If
3461 we don't escape them, construct_command_argv_internal will
3462 recursively call itself ad nauseam, or until stack overflow,
3463 whichever happens first. */
3464 for (cp = shell; *cp != '\0'; ++cp)
3465 {
3466 if (strchr (sh_chars, *cp) != 0)
3467 *(ap++) = '\\';
3468 *(ap++) = *cp;
3469 }
3470 *(ap++) = ' ';
3471 if (shellflags)
3472 memcpy (ap, shellflags, sflags_len);
3473 ap += sflags_len;
3474 *(ap++) = ' ';
3475#ifdef WINDOWS32
3476 command_ptr = ap;
3477#endif
3478 for (p = line; *p != '\0'; ++p)
3479 {
3480 if (restp != NULL && *p == '\n')
3481 {
3482 *restp = p;
3483 break;
3484 }
3485 else if (*p == '\\' && p[1] == '\n')
3486 {
3487 /* POSIX says we keep the backslash-newline. If we don't have a
3488 POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
3489 and remove the backslash/newline. */
3490#if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
3491# define PRESERVE_BSNL unixy_shell
3492#else
3493# define PRESERVE_BSNL 1
3494#endif
3495 if (PRESERVE_BSNL)
3496 {
3497 *(ap++) = '\\';
3498 /* Only non-batch execution needs another backslash,
3499 because it will be passed through a recursive
3500 invocation of this function. */
3501 if (!batch_mode_shell)
3502 *(ap++) = '\\';
3503 *(ap++) = '\n';
3504 }
3505 ++p;
3506 continue;
3507 }
3508
3509 /* DOS shells don't know about backslash-escaping. */
3510 if (unixy_shell && !batch_mode_shell &&
3511 (*p == '\\' || *p == '\'' || *p == '"'
3512 || ISSPACE (*p)
3513 || strchr (sh_chars, *p) != 0))
3514 *ap++ = '\\';
3515#ifdef __MSDOS__
3516 else if (unixy_shell && strneq (p, "...", 3))
3517 {
3518 /* The case of '...' wildcard again. */
3519 strcpy (ap, "\\.\\.\\");
3520 ap += 5;
3521 p += 2;
3522 }
3523#endif
3524 *ap++ = *p;
3525 }
3526 if (ap == new_line + shell_len + sflags_len + 2)
3527 {
3528 /* Line was empty. */
3529 free (new_line);
3530 return 0;
3531 }
3532 *ap = '\0';
3533
3534#ifdef WINDOWS32
3535 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3536 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3537 cases, run commands via a script file. */
3538 if (just_print_flag && !(flags & COMMANDS_RECURSE))
3539 {
3540 /* Need to allocate new_argv, although it's unused, because
3541 start_job_command will want to free it and its 0'th element. */
3542 new_argv = xmalloc (2 * sizeof (char *));
3543 new_argv[0] = xstrdup ("");
3544 new_argv[1] = NULL;
3545 }
3546 else if ((no_default_sh_exe || batch_mode_shell) && batch_filename)
3547 {
3548 int temp_fd;
3549 FILE* batch = NULL;
3550 int id = GetCurrentProcessId ();
3551 PATH_VAR (fbuf);
3552
3553 /* create a file name */
3554 sprintf (fbuf, "make%d", id);
3555 *batch_filename = create_batch_file (fbuf, unixy_shell, &temp_fd);
3556
3557 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3558 *batch_filename));
3559
3560 /* Create a FILE object for the batch file, and write to it the
3561 commands to be executed. Put the batch file in TEXT mode. */
3562 _setmode (temp_fd, _O_TEXT);
3563 batch = _fdopen (temp_fd, "wt");
3564 if (!unixy_shell)
3565 fputs ("@echo off\n", batch);
3566 fputs (command_ptr, batch);
3567 fputc ('\n', batch);
3568 fclose (batch);
3569 DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
3570 !unixy_shell ? "\n\t@echo off" : "", command_ptr));
3571
3572 /* create argv */
3573 new_argv = xmalloc (3 * sizeof (char *));
3574 if (unixy_shell)
3575 {
3576 new_argv[0] = xstrdup (shell);
3577 new_argv[1] = *batch_filename; /* only argv[0] gets freed later */
3578 }
3579 else
3580 {
3581 new_argv[0] = xstrdup (*batch_filename);
3582 new_argv[1] = NULL;
3583 }
3584 new_argv[2] = NULL;
3585 }
3586 else
3587#endif /* WINDOWS32 */
3588
3589 if (unixy_shell)
3590 new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0,
3591 flags, 0);
3592
3593#ifdef __EMX__
3594 else if (!unixy_shell)
3595 {
3596 /* new_line is local, must not be freed therefore
3597 We use line here instead of new_line because we run the shell
3598 manually. */
3599 size_t line_len = strlen (line);
3600 char *p = new_line;
3601 char *q = new_line;
3602 memcpy (new_line, line, line_len + 1);
3603 /* Replace all backslash-newline combination and also following tabs.
3604 Important: stop at the first '\n' because that's what the loop above
3605 did. The next line starting at restp[0] will be executed during the
3606 next call of this function. */
3607 while (*q != '\0' && *q != '\n')
3608 {
3609 if (q[0] == '\\' && q[1] == '\n')
3610 q += 2; /* remove '\\' and '\n' */
3611 else
3612 *p++ = *q++;
3613 }
3614 *p = '\0';
3615
3616# ifndef NO_CMD_DEFAULT
3617 if (strnicmp (new_line, "echo", 4) == 0
3618 && (new_line[4] == ' ' || new_line[4] == '\t'))
3619 {
3620 /* the builtin echo command: handle it separately */
3621 size_t echo_len = line_len - 5;
3622 char *echo_line = new_line + 5;
3623
3624 /* special case: echo 'x="y"'
3625 cmd works this way: a string is printed as is, i.e., no quotes
3626 are removed. But autoconf uses a command like echo 'x="y"' to
3627 determine whether make works. autoconf expects the output x="y"
3628 so we will do exactly that.
3629 Note: if we do not allow cmd to be the default shell
3630 we do not need this kind of voodoo */
3631 if (echo_line[0] == '\''
3632 && echo_line[echo_len - 1] == '\''
3633 && strncmp (echo_line + 1, "ac_maketemp=",
3634 strlen ("ac_maketemp=")) == 0)
3635 {
3636 /* remove the enclosing quotes */
3637 memmove (echo_line, echo_line + 1, echo_len - 2);
3638 echo_line[echo_len - 2] = '\0';
3639 }
3640 }
3641# endif
3642
3643 {
3644 /* Let the shell decide what to do. Put the command line into the
3645 2nd command line argument and hope for the best ;-) */
3646 size_t sh_len = strlen (shell);
3647
3648 /* exactly 3 arguments + NULL */
3649 new_argv = xmalloc (4 * sizeof (char *));
3650 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3651 the trailing '\0' */
3652 new_argv[0] = xmalloc (sh_len + line_len + 5);
3653 memcpy (new_argv[0], shell, sh_len + 1);
3654 new_argv[1] = new_argv[0] + sh_len + 1;
3655 memcpy (new_argv[1], "/c", 3);
3656 new_argv[2] = new_argv[1] + 3;
3657 memcpy (new_argv[2], new_line, line_len + 1);
3658 new_argv[3] = NULL;
3659 }
3660 }
3661#elif defined(__MSDOS__)
3662 else
3663 {
3664 /* With MSDOS shells, we must construct the command line here
3665 instead of recursively calling ourselves, because we
3666 cannot backslash-escape the special characters (see above). */
3667 new_argv = xmalloc (sizeof (char *));
3668 line_len = strlen (new_line) - shell_len - sflags_len - 2;
3669 new_argv[0] = xmalloc (line_len + 1);
3670 strncpy (new_argv[0],
3671 new_line + shell_len + sflags_len + 2, line_len);
3672 new_argv[0][line_len] = '\0';
3673 }
3674#else
3675 else
3676 fatal (NILF, CSTRLEN (__FILE__) + INTSTR_LENGTH,
3677 _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3678 __FILE__, __LINE__);
3679#endif
3680
3681 free (new_line);
3682 }
3683#endif /* ! AMIGA */
3684
3685 return new_argv;
3686}
3687#endif /* !VMS */
3688
3689/* Figure out the argument list necessary to run LINE as a command. Try to
3690 avoid using a shell. This routine handles only ' quoting, and " quoting
3691 when no backslash, $ or ' characters are seen in the quotes. Starting
3692 quotes may be escaped with a backslash. If any of the characters in
3693 sh_chars is seen, or any of the builtin commands listed in sh_cmds
3694 is the first word of a line, the shell is used.
3695
3696 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3697 If *RESTP is NULL, newlines will be ignored.
3698
3699 FILE is the target whose commands these are. It is used for
3700 variable expansion for $(SHELL) and $(IFS). */
3701
3702char **
3703construct_command_argv (char *line, char **restp, struct file *file,
3704 int cmd_flags, char **batch_filename)
3705{
3706 char *shell, *ifs, *shellflags;
3707 char **argv;
3708
3709#ifdef VMS
3710 char *cptr;
3711 int argc;
3712
3713 argc = 0;
3714 cptr = line;
3715 for (;;)
3716 {
3717 while ((*cptr != 0) && (ISSPACE (*cptr)))
3718 cptr++;
3719 if (*cptr == 0)
3720 break;
3721 while ((*cptr != 0) && (!ISSPACE (*cptr)))
3722 cptr++;
3723 argc++;
3724 }
3725
3726 argv = xmalloc (argc * sizeof (char *));
3727 if (argv == 0)
3728 abort ();
3729
3730 cptr = line;
3731 argc = 0;
3732 for (;;)
3733 {
3734 while ((*cptr != 0) && (ISSPACE (*cptr)))
3735 cptr++;
3736 if (*cptr == 0)
3737 break;
3738 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3739 argv[argc++] = cptr;
3740 while ((*cptr != 0) && (!ISSPACE (*cptr)))
3741 cptr++;
3742 if (*cptr != 0)
3743 *cptr++ = 0;
3744 }
3745#else
3746 {
3747 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3748 int save = warn_undefined_variables_flag;
3749 warn_undefined_variables_flag = 0;
3750
3751 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3752#ifdef WINDOWS32
3753 /*
3754 * Convert to forward slashes so that construct_command_argv_internal()
3755 * is not confused.
3756 */
3757 if (shell)
3758 {
3759 char *p = w32ify (shell, 0);
3760 strcpy (shell, p);
3761 }
3762#endif
3763#ifdef __EMX__
3764 {
3765 static const char *unixroot = NULL;
3766 static const char *last_shell = "";
3767 static int init = 0;
3768 if (init == 0)
3769 {
3770 unixroot = getenv ("UNIXROOT");
3771 /* unixroot must be NULL or not empty */
3772 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3773 init = 1;
3774 }
3775
3776 /* if we have an unixroot drive and if shell is not default_shell
3777 (which means it's either cmd.exe or the test has already been
3778 performed) and if shell is an absolute path without drive letter,
3779 try whether it exists e.g.: if "/bin/sh" does not exist use
3780 "$UNIXROOT/bin/sh" instead. */
3781 if (unixroot && shell && strcmp (shell, last_shell) != 0
3782 && (shell[0] == '/' || shell[0] == '\\'))
3783 {
3784 /* trying a new shell, check whether it exists */
3785 size_t size = strlen (shell);
3786 char *buf = xmalloc (size + 7);
3787 memcpy (buf, shell, size);
3788 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3789 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3790 {
3791 /* try the same for the unixroot drive */
3792 memmove (buf + 2, buf, size + 5);
3793 buf[0] = unixroot[0];
3794 buf[1] = unixroot[1];
3795 if (access (buf, F_OK) == 0)
3796 /* we have found a shell! */
3797 /* free(shell); */
3798 shell = buf;
3799 else
3800 free (buf);
3801 }
3802 else
3803 free (buf);
3804 }
3805 }
3806#endif /* __EMX__ */
3807
3808 shellflags = allocated_variable_expand_for_file ("$(.SHELLFLAGS)", file);
3809 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3810
3811 warn_undefined_variables_flag = save;
3812 }
3813
3814# ifdef CONFIG_WITH_KMK_BUILTIN
3815 /* If it's a kmk_builtin command, make sure we're treated like a
3816 unix shell and and don't get batch files. */
3817 if ( ( !unixy_shell
3818 || batch_mode_shell
3819# ifdef WINDOWS32
3820 || no_default_sh_exe
3821# endif
3822 )
3823 && line
3824 && !strncmp (line, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
3825 {
3826 int saved_batch_mode_shell = batch_mode_shell;
3827 int saved_unixy_shell = unixy_shell;
3828# ifdef WINDOWS32
3829 int saved_no_default_sh_exe = no_default_sh_exe;
3830 no_default_sh_exe = 0;
3831# endif
3832 unixy_shell = 1;
3833 batch_mode_shell = 0;
3834 argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
3835 cmd_flags, batch_filename);
3836 batch_mode_shell = saved_batch_mode_shell;
3837 unixy_shell = saved_unixy_shell;
3838# ifdef WINDOWS32
3839 no_default_sh_exe = saved_no_default_sh_exe;
3840# endif
3841 }
3842 else
3843# endif /* CONFIG_WITH_KMK_BUILTIN */
3844 argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
3845 cmd_flags, batch_filename);
3846
3847 free (shell);
3848 free (shellflags);
3849 free (ifs);
3850#endif /* !VMS */
3851 return argv;
3852}
3853
3854
3855#if !defined(HAVE_DUP2) && !defined(_AMIGA)
3856int
3857dup2 (int old, int new)
3858{
3859 int fd;
3860
3861 (void) close (new);
3862 EINTRLOOP (fd, dup (old));
3863 if (fd != new)
3864 {
3865 (void) close (fd);
3866 errno = EMFILE;
3867 return -1;
3868 }
3869
3870 return fd;
3871}
3872#endif /* !HAVE_DUP2 && !_AMIGA */
3873
3874#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
3875/* Prints the time elapsed while executing the commands for the given job. */
3876void print_job_time (struct child *c)
3877{
3878 if ( !handling_fatal_signal
3879 && print_time_min != -1
3880 && c->start_ts != -1)
3881 {
3882 big_int elapsed = nano_timestamp () - c->start_ts;
3883 if (elapsed >= print_time_min * BIG_INT_C(1000000000))
3884 {
3885 char buf[64];
3886 int len = format_elapsed_nano (buf, sizeof (buf), elapsed);
3887 if (len > print_time_width)
3888 print_time_width = len;
3889 message (1, print_time_width + strlen (c->file->name),
3890 _("%*s - %s"), print_time_width, buf, c->file->name);
3891 }
3892 }
3893}
3894#endif
3895
3896/* On VMS systems, include special VMS functions. */
3897
3898#ifdef VMS
3899#include "vmsjobs.c"
3900#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