source: trunk/src/kmk/job.c@ 1293

Last change on this file since 1293 was 1290, checked in by bird, 18 years ago

Allow builtins to spawn and schedule spawning.

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