VirtualBox

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

Last change on this file since 2467 was 2467, checked in by bird, 14 years ago

kmk/job.c: bitch if sigaction fails.

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

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