VirtualBox

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

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

misc gcc warning fixes

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