VirtualBox

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

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

msvcrt build.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette