source: trunk/src/gmake/job.c@ 751

Last change on this file since 751 was 751, checked in by bird, 19 years ago

print the failing command if it was a silent one.

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