VirtualBox

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

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

Load make-3.81/ into vendor/gnumake/current.

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