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

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

Untested merge with GNU Make v3.81 (vendor/gnumake/2005-05-16 -> vendor/gnumake/current).

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