VirtualBox

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

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

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