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

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

Made it build on windows.

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