VirtualBox

source: kBuild/trunk/src/gmake/job.c@ 684

Last change on this file since 684 was 591, checked in by bird, 18 years ago

Added --pretty-command-printing for simplifying makefile debugging.

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