VirtualBox

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

Last change on this file since 881 was 876, checked in by bird, 18 years ago

Dont add COMMANDS_KMK_BUILTIN to the lines_flags as it will screw up 'lines' containing newlines and so are split up into multiple commands.

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