VirtualBox

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

Last change on this file since 1989 was 1989, checked in by bird, 16 years ago

Load gnumake-2008-10-28-CVS into vendor/gnumake/current.

  • Property svn:eol-style set to native
File size: 87.3 KB
Line 
1/* Job execution and handling for GNU Make.
2Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
31998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 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 3 of the License, or (at your option) any later
10version.
11
12GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License along with
17this program. If not, see <http://www.gnu.org/licenses/>. */
18
19#include "make.h"
20
21#include <assert.h>
22
23#include "job.h"
24#include "debug.h"
25#include "filedef.h"
26#include "commands.h"
27#include "variable.h"
28#include "debug.h"
29
30#include <string.h>
31
32/* Default shell to use. */
33#ifdef WINDOWS32
34#include <windows.h>
35
36char *default_shell = "sh.exe";
37int no_default_sh_exe = 1;
38int batch_mode_shell = 1;
39HANDLE main_thread;
40
41#elif defined (_AMIGA)
42
43char default_shell[] = "";
44extern int MyExecute (char **);
45int batch_mode_shell = 0;
46
47#elif defined (__MSDOS__)
48
49/* The default shell is a pointer so we can change it if Makefile
50 says so. It is without an explicit path so we get a chance
51 to search the $PATH for it (since MSDOS doesn't have standard
52 directories we could trust). */
53char *default_shell = "command.com";
54int batch_mode_shell = 0;
55
56#elif defined (__EMX__)
57
58char *default_shell = "/bin/sh";
59int batch_mode_shell = 0;
60
61#elif defined (VMS)
62
63# include <descrip.h>
64char default_shell[] = "";
65int batch_mode_shell = 0;
66
67#elif defined (__riscos__)
68
69char default_shell[] = "";
70int batch_mode_shell = 0;
71
72#else
73
74char default_shell[] = "/bin/sh";
75int batch_mode_shell = 0;
76
77#endif
78
79#ifdef __MSDOS__
80# include <process.h>
81static int execute_by_shell;
82static int dos_pid = 123;
83int dos_status;
84int dos_command_running;
85#endif /* __MSDOS__ */
86
87#ifdef _AMIGA
88# include <proto/dos.h>
89static int amiga_pid = 123;
90static int amiga_status;
91static char amiga_bname[32];
92static int amiga_batch_file;
93#endif /* Amiga. */
94
95#ifdef VMS
96# ifndef __GNUC__
97# include <processes.h>
98# endif
99# include <starlet.h>
100# include <lib$routines.h>
101static void vmsWaitForChildren (int *);
102#endif
103
104#ifdef WINDOWS32
105# include <windows.h>
106# include <io.h>
107# include <process.h>
108# include "sub_proc.h"
109# include "w32err.h"
110# include "pathstuff.h"
111#endif /* WINDOWS32 */
112
113#ifdef __EMX__
114# include <process.h>
115#endif
116
117#if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
118# include <sys/wait.h>
119#endif
120
121#ifdef HAVE_WAITPID
122# define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
123#else /* Don't have waitpid. */
124# ifdef HAVE_WAIT3
125# ifndef wait3
126extern int wait3 ();
127# endif
128# define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
129# endif /* Have wait3. */
130#endif /* Have waitpid. */
131
132#if !defined (wait) && !defined (POSIX)
133int wait ();
134#endif
135
136#ifndef HAVE_UNION_WAIT
137
138# define WAIT_T int
139
140# ifndef WTERMSIG
141# define WTERMSIG(x) ((x) & 0x7f)
142# endif
143# ifndef WCOREDUMP
144# define WCOREDUMP(x) ((x) & 0x80)
145# endif
146# ifndef WEXITSTATUS
147# define WEXITSTATUS(x) (((x) >> 8) & 0xff)
148# endif
149# ifndef WIFSIGNALED
150# define WIFSIGNALED(x) (WTERMSIG (x) != 0)
151# endif
152# ifndef WIFEXITED
153# define WIFEXITED(x) (WTERMSIG (x) == 0)
154# endif
155
156#else /* Have `union wait'. */
157
158# define WAIT_T union wait
159# ifndef WTERMSIG
160# define WTERMSIG(x) ((x).w_termsig)
161# endif
162# ifndef WCOREDUMP
163# define WCOREDUMP(x) ((x).w_coredump)
164# endif
165# ifndef WEXITSTATUS
166# define WEXITSTATUS(x) ((x).w_retcode)
167# endif
168# ifndef WIFSIGNALED
169# define WIFSIGNALED(x) (WTERMSIG(x) != 0)
170# endif
171# ifndef WIFEXITED
172# define WIFEXITED(x) (WTERMSIG(x) == 0)
173# endif
174
175#endif /* Don't have `union wait'. */
176
177#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,
1026 child->file->cmds->lines_flags[child->command_line - 1],
1027 &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 (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 (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 (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 (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 (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 struct commands *cmds = file->cmds;
1494 struct child *c;
1495 char **lines;
1496 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 = 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 memmove (out, in, 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 = xmalloc (sizeof (struct child));
1614 memset (c, '\0', 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 is in fact no recipe.) */
1734 if (cmds->fileinfo.filenm)
1735 DB (DB_BASIC, (_("Invoking recipe from %s:%lu to update target `%s'.\n"),
1736 cmds->fileinfo.filenm, cmds->fileinfo.lineno,
1737 c->file->name));
1738 else
1739 DB (DB_BASIC, (_("Invoking builtin recipe to update target `%s'.\n"),
1740 c->file->name));
1741
1742
1743 start_waiting_job (c);
1744
1745 if (job_slots == 1 || not_parallel)
1746 /* Since there is only one job slot, make things run linearly.
1747 Wait for the child to die, setting the state to `cs_finished'. */
1748 while (file->command_state == cs_running)
1749 reap_children (1, 0);
1750
1751 return;
1752}
1753
1754
1755/* Move CHILD's pointers to the next command for it to execute.
1756 Returns nonzero if there is another command. */
1757
1758static int
1759job_next_command (struct child *child)
1760{
1761 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1762 {
1763 /* There are no more lines in the expansion of this line. */
1764 if (child->command_line == child->file->cmds->ncommand_lines)
1765 {
1766 /* There are no more lines to be expanded. */
1767 child->command_ptr = 0;
1768 return 0;
1769 }
1770 else
1771 /* Get the next line to run. */
1772 child->command_ptr = child->command_lines[child->command_line++];
1773 }
1774 return 1;
1775}
1776
1777/* Determine if the load average on the system is too high to start a new job.
1778 The real system load average is only recomputed once a second. However, a
1779 very parallel make can easily start tens or even hundreds of jobs in a
1780 second, which brings the system to its knees for a while until that first
1781 batch of jobs clears out.
1782
1783 To avoid this we use a weighted algorithm to try to account for jobs which
1784 have been started since the last second, and guess what the load average
1785 would be now if it were computed.
1786
1787 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1788 who writes:
1789
1790! calculate something load-oid and add to the observed sys.load,
1791! so that latter can catch up:
1792! - every job started increases jobctr;
1793! - every dying job decreases a positive jobctr;
1794! - the jobctr value gets zeroed every change of seconds,
1795! after its value*weight_b is stored into the 'backlog' value last_sec
1796! - weight_a times the sum of jobctr and last_sec gets
1797! added to the observed sys.load.
1798!
1799! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1800! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1801! sub-shelled commands (rm, echo, sed...) for tests.
1802! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1803! resulted in significant excession of the load limit, raising it
1804! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1805! reach the limit in most test cases.
1806!
1807! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1808! exceeding the limit for longer-running stuff (compile jobs in
1809! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1810! small jobs' effects.
1811
1812 */
1813
1814#define LOAD_WEIGHT_A 0.25
1815#define LOAD_WEIGHT_B 0.25
1816
1817static int
1818load_too_high (void)
1819{
1820#if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
1821 return 1;
1822#else
1823 static double last_sec;
1824 static time_t last_now;
1825 double load, guess;
1826 time_t now;
1827
1828#ifdef WINDOWS32
1829 /* sub_proc.c cannot wait for more than MAXIMUM_WAIT_OBJECTS children */
1830 if (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
1831 return 1;
1832#endif
1833
1834 if (max_load_average < 0)
1835 return 0;
1836
1837 /* Find the real system load average. */
1838 make_access ();
1839 if (getloadavg (&load, 1) != 1)
1840 {
1841 static int lossage = -1;
1842 /* Complain only once for the same error. */
1843 if (lossage == -1 || errno != lossage)
1844 {
1845 if (errno == 0)
1846 /* An errno value of zero means getloadavg is just unsupported. */
1847 error (NILF,
1848 _("cannot enforce load limits on this operating system"));
1849 else
1850 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1851 }
1852 lossage = errno;
1853 load = 0;
1854 }
1855 user_access ();
1856
1857 /* If we're in a new second zero the counter and correct the backlog
1858 value. Only keep the backlog for one extra second; after that it's 0. */
1859 now = time (NULL);
1860 if (last_now < now)
1861 {
1862 if (last_now == now - 1)
1863 last_sec = LOAD_WEIGHT_B * job_counter;
1864 else
1865 last_sec = 0.0;
1866
1867 job_counter = 0;
1868 last_now = now;
1869 }
1870
1871 /* Try to guess what the load would be right now. */
1872 guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
1873
1874 DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1875 guess, load, max_load_average));
1876
1877 return guess >= max_load_average;
1878#endif
1879}
1880
1881/* Start jobs that are waiting for the load to be lower. */
1882
1883void
1884start_waiting_jobs (void)
1885{
1886 struct child *job;
1887
1888 if (waiting_jobs == 0)
1889 return;
1890
1891 do
1892 {
1893 /* Check for recently deceased descendants. */
1894 reap_children (0, 0);
1895
1896 /* Take a job off the waiting list. */
1897 job = waiting_jobs;
1898 waiting_jobs = job->next;
1899
1900 /* Try to start that job. We break out of the loop as soon
1901 as start_waiting_job puts one back on the waiting list. */
1902 }
1903 while (start_waiting_job (job) && waiting_jobs != 0);
1904
1905 return;
1906}
1907
1908
1909#ifndef WINDOWS32
1910
1911/* EMX: Start a child process. This function returns the new pid. */
1912# if defined __EMX__
1913int
1914child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
1915{
1916 int pid;
1917 /* stdin_fd == 0 means: nothing to do for stdin;
1918 stdout_fd == 1 means: nothing to do for stdout */
1919 int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
1920 int save_stdout = (stdout_fd != 1) ? dup (1): 1;
1921
1922 /* < 0 only if dup() failed */
1923 if (save_stdin < 0)
1924 fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
1925 if (save_stdout < 0)
1926 fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
1927
1928 /* Close unnecessary file handles for the child. */
1929 if (save_stdin != 0)
1930 CLOSE_ON_EXEC (save_stdin);
1931 if (save_stdout != 1)
1932 CLOSE_ON_EXEC (save_stdout);
1933
1934 /* Connect the pipes to the child process. */
1935 if (stdin_fd != 0)
1936 (void) dup2 (stdin_fd, 0);
1937 if (stdout_fd != 1)
1938 (void) dup2 (stdout_fd, 1);
1939
1940 /* stdin_fd and stdout_fd must be closed on exit because we are
1941 still in the parent process */
1942 if (stdin_fd != 0)
1943 CLOSE_ON_EXEC (stdin_fd);
1944 if (stdout_fd != 1)
1945 CLOSE_ON_EXEC (stdout_fd);
1946
1947 /* Run the command. */
1948 pid = exec_command (argv, envp);
1949
1950 /* Restore stdout/stdin of the parent and close temporary FDs. */
1951 if (stdin_fd != 0)
1952 {
1953 if (dup2 (save_stdin, 0) != 0)
1954 fatal (NILF, _("Could not restore stdin\n"));
1955 else
1956 close (save_stdin);
1957 }
1958
1959 if (stdout_fd != 1)
1960 {
1961 if (dup2 (save_stdout, 1) != 1)
1962 fatal (NILF, _("Could not restore stdout\n"));
1963 else
1964 close (save_stdout);
1965 }
1966
1967 return pid;
1968}
1969
1970#elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
1971
1972/* UNIX:
1973 Replace the current process with one executing the command in ARGV.
1974 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
1975 the environment of the new program. This function does not return. */
1976void
1977child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
1978{
1979 if (stdin_fd != 0)
1980 (void) dup2 (stdin_fd, 0);
1981 if (stdout_fd != 1)
1982 (void) dup2 (stdout_fd, 1);
1983 if (stdin_fd != 0)
1984 (void) close (stdin_fd);
1985 if (stdout_fd != 1)
1986 (void) close (stdout_fd);
1987
1988 /* Run the command. */
1989 exec_command (argv, envp);
1990}
1991#endif /* !AMIGA && !__MSDOS__ && !VMS */
1992#endif /* !WINDOWS32 */
1993
1994
1995#ifndef _AMIGA
1996/* Replace the current process with one running the command in ARGV,
1997 with environment ENVP. This function does not return. */
1998
1999/* EMX: This function returns the pid of the child process. */
2000# ifdef __EMX__
2001int
2002# else
2003void
2004# endif
2005exec_command (char **argv, char **envp)
2006{
2007#ifdef VMS
2008 /* to work around a problem with signals and execve: ignore them */
2009#ifdef SIGCHLD
2010 signal (SIGCHLD,SIG_IGN);
2011#endif
2012 /* Run the program. */
2013 execve (argv[0], argv, envp);
2014 perror_with_name ("execve: ", argv[0]);
2015 _exit (EXIT_FAILURE);
2016#else
2017#ifdef WINDOWS32
2018 HANDLE hPID;
2019 HANDLE hWaitPID;
2020 int err = 0;
2021 int exit_code = EXIT_FAILURE;
2022
2023 /* make sure CreateProcess() has Path it needs */
2024 sync_Path_environment();
2025
2026 /* launch command */
2027 hPID = process_easy(argv, envp);
2028
2029 /* make sure launch ok */
2030 if (hPID == INVALID_HANDLE_VALUE)
2031 {
2032 int i;
2033 fprintf(stderr,
2034 _("process_easy() failed failed to launch process (e=%ld)\n"),
2035 process_last_err(hPID));
2036 for (i = 0; argv[i]; i++)
2037 fprintf(stderr, "%s ", argv[i]);
2038 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2039 exit(EXIT_FAILURE);
2040 }
2041
2042 /* wait and reap last child */
2043 hWaitPID = process_wait_for_any();
2044 while (hWaitPID)
2045 {
2046 /* was an error found on this process? */
2047 err = process_last_err(hWaitPID);
2048
2049 /* get exit data */
2050 exit_code = process_exit_code(hWaitPID);
2051
2052 if (err)
2053 fprintf(stderr, "make (e=%d, rc=%d): %s",
2054 err, exit_code, map_windows32_error_to_string(err));
2055
2056 /* cleanup process */
2057 process_cleanup(hWaitPID);
2058
2059 /* expect to find only last pid, warn about other pids reaped */
2060 if (hWaitPID == hPID)
2061 break;
2062 else
2063 fprintf(stderr,
2064 _("make reaped child pid %ld, still waiting for pid %ld\n"),
2065 (DWORD)hWaitPID, (DWORD)hPID);
2066 }
2067
2068 /* return child's exit code as our exit code */
2069 exit(exit_code);
2070
2071#else /* !WINDOWS32 */
2072
2073# ifdef __EMX__
2074 int pid;
2075# endif
2076
2077 /* Be the user, permanently. */
2078 child_access ();
2079
2080# ifdef __EMX__
2081
2082 /* Run the program. */
2083 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2084
2085 if (pid >= 0)
2086 return pid;
2087
2088 /* the file might have a strange shell extension */
2089 if (errno == ENOENT)
2090 errno = ENOEXEC;
2091
2092# else
2093
2094 /* Run the program. */
2095 environ = envp;
2096 execvp (argv[0], argv);
2097
2098# endif /* !__EMX__ */
2099
2100 switch (errno)
2101 {
2102 case ENOENT:
2103 error (NILF, _("%s: Command not found"), argv[0]);
2104 break;
2105 case ENOEXEC:
2106 {
2107 /* The file is not executable. Try it as a shell script. */
2108 extern char *getenv ();
2109 char *shell;
2110 char **new_argv;
2111 int argc;
2112 int i=1;
2113
2114# ifdef __EMX__
2115 /* Do not use $SHELL from the environment */
2116 struct variable *p = lookup_variable ("SHELL", 5);
2117 if (p)
2118 shell = p->value;
2119 else
2120 shell = 0;
2121# else
2122 shell = getenv ("SHELL");
2123# endif
2124 if (shell == 0)
2125 shell = default_shell;
2126
2127 argc = 1;
2128 while (argv[argc] != 0)
2129 ++argc;
2130
2131# ifdef __EMX__
2132 if (!unixy_shell)
2133 ++argc;
2134# endif
2135
2136 new_argv = alloca ((1 + argc + 1) * sizeof (char *));
2137 new_argv[0] = shell;
2138
2139# ifdef __EMX__
2140 if (!unixy_shell)
2141 {
2142 new_argv[1] = "/c";
2143 ++i;
2144 --argc;
2145 }
2146# endif
2147
2148 new_argv[i] = argv[0];
2149 while (argc > 0)
2150 {
2151 new_argv[i + argc] = argv[argc];
2152 --argc;
2153 }
2154
2155# ifdef __EMX__
2156 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2157 if (pid >= 0)
2158 break;
2159# else
2160 execvp (shell, new_argv);
2161# endif
2162 if (errno == ENOENT)
2163 error (NILF, _("%s: Shell program not found"), shell);
2164 else
2165 perror_with_name ("execvp: ", shell);
2166 break;
2167 }
2168
2169# ifdef __EMX__
2170 case EINVAL:
2171 /* this nasty error was driving me nuts :-( */
2172 error (NILF, _("spawnvpe: environment space might be exhausted"));
2173 /* FALLTHROUGH */
2174# endif
2175
2176 default:
2177 perror_with_name ("execvp: ", argv[0]);
2178 break;
2179 }
2180
2181# ifdef __EMX__
2182 return pid;
2183# else
2184 _exit (127);
2185# endif
2186#endif /* !WINDOWS32 */
2187#endif /* !VMS */
2188}
2189#else /* On Amiga */
2190void exec_command (char **argv)
2191{
2192 MyExecute (argv);
2193}
2194
2195void clean_tmp (void)
2196{
2197 DeleteFile (amiga_bname);
2198}
2199
2200#endif /* On Amiga */
2201
2202
2203#ifndef VMS
2204/* Figure out the argument list necessary to run LINE as a command. Try to
2205 avoid using a shell. This routine handles only ' quoting, and " quoting
2206 when no backslash, $ or ` characters are seen in the quotes. Starting
2207 quotes may be escaped with a backslash. If any of the characters in
2208 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2209 is the first word of a line, the shell is used.
2210
2211 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2212 If *RESTP is NULL, newlines will be ignored.
2213
2214 SHELL is the shell to use, or nil to use the default shell.
2215 IFS is the value of $IFS, or nil (meaning the default).
2216
2217 FLAGS is the value of lines_flags for this command line. It is
2218 used in the WINDOWS32 port to check whether + or $(MAKE) were found
2219 in this command line, in which case the effect of just_print_flag
2220 is overridden. */
2221
2222static char **
2223construct_command_argv_internal (char *line, char **restp, char *shell,
2224 char *ifs, int flags,
2225 char **batch_filename_ptr)
2226{
2227#ifdef __MSDOS__
2228 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2229 We call `system' for anything that requires ``slow'' processing,
2230 because DOS shells are too dumb. When $SHELL points to a real
2231 (unix-style) shell, `system' just calls it to do everything. When
2232 $SHELL points to a DOS shell, `system' does most of the work
2233 internally, calling the shell only for its internal commands.
2234 However, it looks on the $PATH first, so you can e.g. have an
2235 external command named `mkdir'.
2236
2237 Since we call `system', certain characters and commands below are
2238 actually not specific to COMMAND.COM, but to the DJGPP implementation
2239 of `system'. In particular:
2240
2241 The shell wildcard characters are in DOS_CHARS because they will
2242 not be expanded if we call the child via `spawnXX'.
2243
2244 The `;' is in DOS_CHARS, because our `system' knows how to run
2245 multiple commands on a single line.
2246
2247 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2248 won't have to tell one from another and have one more set of
2249 commands and special characters. */
2250 static char sh_chars_dos[] = "*?[];|<>%^&()";
2251 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2252 "copy", "ctty", "date", "del", "dir", "echo",
2253 "erase", "exit", "for", "goto", "if", "md",
2254 "mkdir", "path", "pause", "prompt", "rd",
2255 "rmdir", "rem", "ren", "rename", "set",
2256 "shift", "time", "type", "ver", "verify",
2257 "vol", ":", 0 };
2258
2259 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2260 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2261 "logout", "set", "umask", "wait", "while",
2262 "for", "case", "if", ":", ".", "break",
2263 "continue", "export", "read", "readonly",
2264 "shift", "times", "trap", "switch", "unset",
2265 0 };
2266
2267 char *sh_chars;
2268 char **sh_cmds;
2269#elif defined (__EMX__)
2270 static char sh_chars_dos[] = "*?[];|<>%^&()";
2271 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2272 "copy", "ctty", "date", "del", "dir", "echo",
2273 "erase", "exit", "for", "goto", "if", "md",
2274 "mkdir", "path", "pause", "prompt", "rd",
2275 "rmdir", "rem", "ren", "rename", "set",
2276 "shift", "time", "type", "ver", "verify",
2277 "vol", ":", 0 };
2278
2279 static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
2280 static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2281 "date", "del", "detach", "dir", "echo",
2282 "endlocal", "erase", "exit", "for", "goto", "if",
2283 "keys", "md", "mkdir", "move", "path", "pause",
2284 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2285 "set", "setlocal", "shift", "start", "time",
2286 "type", "ver", "verify", "vol", ":", 0 };
2287
2288 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~'";
2289 static char *sh_cmds_sh[] = { "echo", "cd", "eval", "exec", "exit", "login",
2290 "logout", "set", "umask", "wait", "while",
2291 "for", "case", "if", ":", ".", "break",
2292 "continue", "export", "read", "readonly",
2293 "shift", "times", "trap", "switch", "unset",
2294 0 };
2295 char *sh_chars;
2296 char **sh_cmds;
2297
2298#elif defined (_AMIGA)
2299 static char sh_chars[] = "#;\"|<>()?*$`";
2300 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2301 "rename", "set", "setenv", "date", "makedir",
2302 "skip", "else", "endif", "path", "prompt",
2303 "unset", "unsetenv", "version",
2304 0 };
2305#elif defined (WINDOWS32)
2306 static char sh_chars_dos[] = "\"|&<>";
2307 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2308 "copy", "ctty", "date", "del", "dir", "echo",
2309 "erase", "exit", "for", "goto", "if", "if", "md",
2310 "mkdir", "path", "pause", "prompt", "rd", "rem",
2311 "ren", "rename", "rmdir", "set", "shift", "time",
2312 "type", "ver", "verify", "vol", ":", 0 };
2313 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2314 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2315 "logout", "set", "umask", "wait", "while", "for",
2316 "case", "if", ":", ".", "break", "continue",
2317 "export", "read", "readonly", "shift", "times",
2318 "trap", "switch", "test",
2319#ifdef BATCH_MODE_ONLY_SHELL
2320 "echo",
2321#endif
2322 0 };
2323 char* sh_chars;
2324 char** sh_cmds;
2325#elif defined(__riscos__)
2326 static char sh_chars[] = "";
2327 static char *sh_cmds[] = { 0 };
2328#else /* must be UNIX-ish */
2329 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~!";
2330 static char *sh_cmds[] = { ".", ":", "break", "case", "cd", "continue",
2331 "eval", "exec", "exit", "export", "for", "if",
2332 "login", "logout", "read", "readonly", "set",
2333 "shift", "switch", "test", "times", "trap",
2334 "umask", "wait", "while", 0 };
2335# ifdef HAVE_DOS_PATHS
2336 /* This is required if the MSYS/Cygwin ports (which do not define
2337 WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
2338 sh_chars_sh[] directly (see below). */
2339 static char *sh_chars_sh = sh_chars;
2340# endif /* HAVE_DOS_PATHS */
2341#endif
2342 int i;
2343 char *p;
2344 char *ap;
2345 char *end;
2346 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2347 char **new_argv = 0;
2348 char *argstr = 0;
2349#ifdef WINDOWS32
2350 int slow_flag = 0;
2351
2352 if (!unixy_shell) {
2353 sh_cmds = sh_cmds_dos;
2354 sh_chars = sh_chars_dos;
2355 } else {
2356 sh_cmds = sh_cmds_sh;
2357 sh_chars = sh_chars_sh;
2358 }
2359#endif /* WINDOWS32 */
2360
2361 if (restp != NULL)
2362 *restp = NULL;
2363
2364 /* Make sure not to bother processing an empty line. */
2365 while (isblank ((unsigned char)*line))
2366 ++line;
2367 if (*line == '\0')
2368 return 0;
2369
2370 /* See if it is safe to parse commands internally. */
2371 if (shell == 0)
2372 shell = default_shell;
2373#ifdef WINDOWS32
2374 else if (strcmp (shell, default_shell))
2375 {
2376 char *s1 = _fullpath (NULL, shell, 0);
2377 char *s2 = _fullpath (NULL, default_shell, 0);
2378
2379 slow_flag = strcmp ((s1 ? s1 : ""), (s2 ? s2 : ""));
2380
2381 if (s1)
2382 free (s1);
2383 if (s2)
2384 free (s2);
2385 }
2386 if (slow_flag)
2387 goto slow;
2388#else /* not WINDOWS32 */
2389#if defined (__MSDOS__) || defined (__EMX__)
2390 else if (strcasecmp (shell, default_shell))
2391 {
2392 extern int _is_unixy_shell (const char *_path);
2393
2394 DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
2395 default_shell, shell));
2396 unixy_shell = _is_unixy_shell (shell);
2397 /* we must allocate a copy of shell: construct_command_argv() will free
2398 * shell after this function returns. */
2399 default_shell = xstrdup (shell);
2400 }
2401 if (unixy_shell)
2402 {
2403 sh_chars = sh_chars_sh;
2404 sh_cmds = sh_cmds_sh;
2405 }
2406 else
2407 {
2408 sh_chars = sh_chars_dos;
2409 sh_cmds = sh_cmds_dos;
2410# ifdef __EMX__
2411 if (_osmode == OS2_MODE)
2412 {
2413 sh_chars = sh_chars_os2;
2414 sh_cmds = sh_cmds_os2;
2415 }
2416# endif
2417 }
2418#else /* !__MSDOS__ */
2419 else if (strcmp (shell, default_shell))
2420 goto slow;
2421#endif /* !__MSDOS__ && !__EMX__ */
2422#endif /* not WINDOWS32 */
2423
2424 if (ifs != 0)
2425 for (ap = ifs; *ap != '\0'; ++ap)
2426 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2427 goto slow;
2428
2429 i = strlen (line) + 1;
2430
2431 /* More than 1 arg per character is impossible. */
2432 new_argv = xmalloc (i * sizeof (char *));
2433
2434 /* All the args can fit in a buffer as big as LINE is. */
2435 ap = new_argv[0] = argstr = xmalloc (i);
2436 end = ap + i;
2437
2438 /* I is how many complete arguments have been found. */
2439 i = 0;
2440 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2441 for (p = line; *p != '\0'; ++p)
2442 {
2443 assert (ap <= end);
2444
2445 if (instring)
2446 {
2447 /* Inside a string, just copy any char except a closing quote
2448 or a backslash-newline combination. */
2449 if (*p == instring)
2450 {
2451 instring = 0;
2452 if (ap == new_argv[0] || *(ap-1) == '\0')
2453 last_argument_was_empty = 1;
2454 }
2455 else if (*p == '\\' && p[1] == '\n')
2456 {
2457 /* Backslash-newline is handled differently depending on what
2458 kind of string we're in: inside single-quoted strings you
2459 keep them; in double-quoted strings they disappear.
2460 For DOS/Windows/OS2, if we don't have a POSIX shell,
2461 we keep the pre-POSIX behavior of removing the
2462 backslash-newline. */
2463 if (instring == '"'
2464#if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2465 || !unixy_shell
2466#endif
2467 )
2468 ++p;
2469 else
2470 {
2471 *(ap++) = *(p++);
2472 *(ap++) = *p;
2473 }
2474 }
2475 else if (*p == '\n' && restp != NULL)
2476 {
2477 /* End of the command line. */
2478 *restp = p;
2479 goto end_of_line;
2480 }
2481 /* Backslash, $, and ` are special inside double quotes.
2482 If we see any of those, punt.
2483 But on MSDOS, if we use COMMAND.COM, double and single
2484 quotes have the same effect. */
2485 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2486 goto slow;
2487 else
2488 *ap++ = *p;
2489 }
2490 else if (strchr (sh_chars, *p) != 0)
2491 /* Not inside a string, but it's a special char. */
2492 goto slow;
2493#ifdef __MSDOS__
2494 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2495 /* `...' is a wildcard in DJGPP. */
2496 goto slow;
2497#endif
2498 else
2499 /* Not a special char. */
2500 switch (*p)
2501 {
2502 case '=':
2503 /* Equals is a special character in leading words before the
2504 first word with no equals sign in it. This is not the case
2505 with sh -k, but we never get here when using nonstandard
2506 shell flags. */
2507 if (! seen_nonequals && unixy_shell)
2508 goto slow;
2509 word_has_equals = 1;
2510 *ap++ = '=';
2511 break;
2512
2513 case '\\':
2514 /* Backslash-newline has special case handling, ref POSIX.
2515 We're in the fastpath, so emulate what the shell would do. */
2516 if (p[1] == '\n')
2517 {
2518 /* Throw out the backslash and newline. */
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. If we don't have a
2749 POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
2750 and remove the backslash/newline. */
2751#if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
2752# define PRESERVE_BSNL unixy_shell
2753#else
2754# define PRESERVE_BSNL 1
2755#endif
2756 if (PRESERVE_BSNL)
2757 {
2758 *(ap++) = '\\';
2759 /* Only non-batch execution needs another backslash,
2760 because it will be passed through a recursive
2761 invocation of this function. */
2762 if (!batch_mode_shell)
2763 *(ap++) = '\\';
2764 *(ap++) = '\n';
2765 }
2766 ++p;
2767 continue;
2768 }
2769
2770 /* DOS shells don't know about backslash-escaping. */
2771 if (unixy_shell && !batch_mode_shell &&
2772 (*p == '\\' || *p == '\'' || *p == '"'
2773 || isspace ((unsigned char)*p)
2774 || strchr (sh_chars, *p) != 0))
2775 *ap++ = '\\';
2776#ifdef __MSDOS__
2777 else if (unixy_shell && strneq (p, "...", 3))
2778 {
2779 /* The case of `...' wildcard again. */
2780 strcpy (ap, "\\.\\.\\");
2781 ap += 5;
2782 p += 2;
2783 }
2784#endif
2785 *ap++ = *p;
2786 }
2787 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2788 /* Line was empty. */
2789 return 0;
2790 *ap = '\0';
2791
2792#ifdef WINDOWS32
2793 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2794 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2795 cases, run commands via a script file. */
2796 if (just_print_flag && !(flags & COMMANDS_RECURSE)) {
2797 /* Need to allocate new_argv, although it's unused, because
2798 start_job_command will want to free it and its 0'th element. */
2799 new_argv = xmalloc(2 * sizeof (char *));
2800 new_argv[0] = xstrdup ("");
2801 new_argv[1] = NULL;
2802 } else if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2803 int temp_fd;
2804 FILE* batch = NULL;
2805 int id = GetCurrentProcessId();
2806 PATH_VAR(fbuf);
2807
2808 /* create a file name */
2809 sprintf(fbuf, "make%d", id);
2810 *batch_filename_ptr = create_batch_file (fbuf, unixy_shell, &temp_fd);
2811
2812 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
2813 *batch_filename_ptr));
2814
2815 /* Create a FILE object for the batch file, and write to it the
2816 commands to be executed. Put the batch file in TEXT mode. */
2817 _setmode (temp_fd, _O_TEXT);
2818 batch = _fdopen (temp_fd, "wt");
2819 if (!unixy_shell)
2820 fputs ("@echo off\n", batch);
2821 fputs (command_ptr, batch);
2822 fputc ('\n', batch);
2823 fclose (batch);
2824 DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
2825 !unixy_shell ? "\n\t@echo off" : "", command_ptr));
2826
2827 /* create argv */
2828 new_argv = xmalloc(3 * sizeof (char *));
2829 if (unixy_shell) {
2830 new_argv[0] = xstrdup (shell);
2831 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2832 } else {
2833 new_argv[0] = xstrdup (*batch_filename_ptr);
2834 new_argv[1] = NULL;
2835 }
2836 new_argv[2] = NULL;
2837 } else
2838#endif /* WINDOWS32 */
2839 if (unixy_shell)
2840 new_argv = construct_command_argv_internal (new_line, 0, 0, 0, flags, 0);
2841#ifdef __EMX__
2842 else if (!unixy_shell)
2843 {
2844 /* new_line is local, must not be freed therefore
2845 We use line here instead of new_line because we run the shell
2846 manually. */
2847 size_t line_len = strlen (line);
2848 char *p = new_line;
2849 char *q = new_line;
2850 memcpy (new_line, line, line_len + 1);
2851 /* replace all backslash-newline combination and also following tabs */
2852 while (*q != '\0')
2853 {
2854 if (q[0] == '\\' && q[1] == '\n')
2855 q += 2; /* remove '\\' and '\n' */
2856 else
2857 *p++ = *q++;
2858 }
2859 *p = '\0';
2860
2861# ifndef NO_CMD_DEFAULT
2862 if (strnicmp (new_line, "echo", 4) == 0
2863 && (new_line[4] == ' ' || new_line[4] == '\t'))
2864 {
2865 /* the builtin echo command: handle it separately */
2866 size_t echo_len = line_len - 5;
2867 char *echo_line = new_line + 5;
2868
2869 /* special case: echo 'x="y"'
2870 cmd works this way: a string is printed as is, i.e., no quotes
2871 are removed. But autoconf uses a command like echo 'x="y"' to
2872 determine whether make works. autoconf expects the output x="y"
2873 so we will do exactly that.
2874 Note: if we do not allow cmd to be the default shell
2875 we do not need this kind of voodoo */
2876 if (echo_line[0] == '\''
2877 && echo_line[echo_len - 1] == '\''
2878 && strncmp (echo_line + 1, "ac_maketemp=",
2879 strlen ("ac_maketemp=")) == 0)
2880 {
2881 /* remove the enclosing quotes */
2882 memmove (echo_line, echo_line + 1, echo_len - 2);
2883 echo_line[echo_len - 2] = '\0';
2884 }
2885 }
2886# endif
2887
2888 {
2889 /* Let the shell decide what to do. Put the command line into the
2890 2nd command line argument and hope for the best ;-) */
2891 size_t sh_len = strlen (shell);
2892
2893 /* exactly 3 arguments + NULL */
2894 new_argv = xmalloc (4 * sizeof (char *));
2895 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
2896 the trailing '\0' */
2897 new_argv[0] = xmalloc (sh_len + line_len + 5);
2898 memcpy (new_argv[0], shell, sh_len + 1);
2899 new_argv[1] = new_argv[0] + sh_len + 1;
2900 memcpy (new_argv[1], "/c", 3);
2901 new_argv[2] = new_argv[1] + 3;
2902 memcpy (new_argv[2], new_line, line_len + 1);
2903 new_argv[3] = NULL;
2904 }
2905 }
2906#elif defined(__MSDOS__)
2907 else
2908 {
2909 /* With MSDOS shells, we must construct the command line here
2910 instead of recursively calling ourselves, because we
2911 cannot backslash-escape the special characters (see above). */
2912 new_argv = xmalloc (sizeof (char *));
2913 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2914 new_argv[0] = xmalloc (line_len + 1);
2915 strncpy (new_argv[0],
2916 new_line + shell_len + sizeof (minus_c) - 1, line_len);
2917 new_argv[0][line_len] = '\0';
2918 }
2919#else
2920 else
2921 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2922 __FILE__, __LINE__);
2923#endif
2924 }
2925#endif /* ! AMIGA */
2926
2927 return new_argv;
2928}
2929#endif /* !VMS */
2930
2931/* Figure out the argument list necessary to run LINE as a command. Try to
2932 avoid using a shell. This routine handles only ' quoting, and " quoting
2933 when no backslash, $ or ` characters are seen in the quotes. Starting
2934 quotes may be escaped with a backslash. If any of the characters in
2935 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2936 is the first word of a line, the shell is used.
2937
2938 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2939 If *RESTP is NULL, newlines will be ignored.
2940
2941 FILE is the target whose commands these are. It is used for
2942 variable expansion for $(SHELL) and $(IFS). */
2943
2944char **
2945construct_command_argv (char *line, char **restp, struct file *file,
2946 int cmd_flags, char **batch_filename_ptr)
2947{
2948 char *shell, *ifs;
2949 char **argv;
2950
2951#ifdef VMS
2952 char *cptr;
2953 int argc;
2954
2955 argc = 0;
2956 cptr = line;
2957 for (;;)
2958 {
2959 while ((*cptr != 0)
2960 && (isspace ((unsigned char)*cptr)))
2961 cptr++;
2962 if (*cptr == 0)
2963 break;
2964 while ((*cptr != 0)
2965 && (!isspace((unsigned char)*cptr)))
2966 cptr++;
2967 argc++;
2968 }
2969
2970 argv = xmalloc (argc * sizeof (char *));
2971 if (argv == 0)
2972 abort ();
2973
2974 cptr = line;
2975 argc = 0;
2976 for (;;)
2977 {
2978 while ((*cptr != 0)
2979 && (isspace ((unsigned char)*cptr)))
2980 cptr++;
2981 if (*cptr == 0)
2982 break;
2983 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
2984 argv[argc++] = cptr;
2985 while ((*cptr != 0)
2986 && (!isspace((unsigned char)*cptr)))
2987 cptr++;
2988 if (*cptr != 0)
2989 *cptr++ = 0;
2990 }
2991#else
2992 {
2993 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2994 int save = warn_undefined_variables_flag;
2995 warn_undefined_variables_flag = 0;
2996
2997 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
2998#ifdef WINDOWS32
2999 /*
3000 * Convert to forward slashes so that construct_command_argv_internal()
3001 * is not confused.
3002 */
3003 if (shell) {
3004 char *p = w32ify (shell, 0);
3005 strcpy (shell, p);
3006 }
3007#endif
3008#ifdef __EMX__
3009 {
3010 static const char *unixroot = NULL;
3011 static const char *last_shell = "";
3012 static int init = 0;
3013 if (init == 0)
3014 {
3015 unixroot = getenv ("UNIXROOT");
3016 /* unixroot must be NULL or not empty */
3017 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3018 init = 1;
3019 }
3020
3021 /* if we have an unixroot drive and if shell is not default_shell
3022 (which means it's either cmd.exe or the test has already been
3023 performed) and if shell is an absolute path without drive letter,
3024 try whether it exists e.g.: if "/bin/sh" does not exist use
3025 "$UNIXROOT/bin/sh" instead. */
3026 if (unixroot && shell && strcmp (shell, last_shell) != 0
3027 && (shell[0] == '/' || shell[0] == '\\'))
3028 {
3029 /* trying a new shell, check whether it exists */
3030 size_t size = strlen (shell);
3031 char *buf = xmalloc (size + 7);
3032 memcpy (buf, shell, size);
3033 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3034 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3035 {
3036 /* try the same for the unixroot drive */
3037 memmove (buf + 2, buf, size + 5);
3038 buf[0] = unixroot[0];
3039 buf[1] = unixroot[1];
3040 if (access (buf, F_OK) == 0)
3041 /* we have found a shell! */
3042 /* free(shell); */
3043 shell = buf;
3044 else
3045 free (buf);
3046 }
3047 else
3048 free (buf);
3049 }
3050 }
3051#endif /* __EMX__ */
3052
3053 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3054
3055 warn_undefined_variables_flag = save;
3056 }
3057
3058 argv = construct_command_argv_internal (line, restp, shell, ifs,
3059 cmd_flags, batch_filename_ptr);
3060
3061 free (shell);
3062 free (ifs);
3063#endif /* !VMS */
3064 return argv;
3065}
3066
3067
3068#if !defined(HAVE_DUP2) && !defined(_AMIGA)
3069int
3070dup2 (int old, int new)
3071{
3072 int fd;
3073
3074 (void) close (new);
3075 fd = dup (old);
3076 if (fd != new)
3077 {
3078 (void) close (fd);
3079 errno = EMFILE;
3080 return -1;
3081 }
3082
3083 return fd;
3084}
3085#endif /* !HAPE_DUP2 && !_AMIGA */
3086
3087/* On VMS systems, include special VMS functions. */
3088
3089#ifdef VMS
3090#include "vmsjobs.c"
3091#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