VirtualBox

source: kBuild/vendor/gnumake/current/job.c@ 2596

Last change on this file since 2596 was 2596, checked in by bird, 12 years ago

gnumake/current -> 3.82-cvs.

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