VirtualBox

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

Last change on this file since 232 was 232, checked in by bird, 20 years ago

Don't let kBuild ash force slow shell path.

  • Property svn:eol-style set to native
File size: 102.6 KB
Line 
1/* Job execution and handling for GNU Make.
2Copyright (C) 1988,89,90,91,92,93,94,95,96,97,99 Free Software Foundation, Inc.
3This file is part of GNU Make.
4
5GNU Make is free software; you can redistribute it and/or modify
6it under the terms of the GNU General Public License as published by
7the Free Software Foundation; either version 2, or (at your option)
8any later version.
9
10GNU Make is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with GNU Make; see the file COPYING. If not, write to
17the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18Boston, MA 02111-1307, USA. */
19
20#include "make.h"
21
22#include <assert.h>
23
24#include "job.h"
25#include "debug.h"
26#include "filedef.h"
27#include "commands.h"
28#include "variable.h"
29#include "debug.h"
30#ifdef CONFIG_WITH_KMK_BUILTIN
31#include "kmkbuiltin.h"
32#endif
33
34
35#include <string.h>
36
37#ifdef MAKE_DLLSHELL
38#include <dlfcn.h>
39#endif
40
41/* Default shell to use. */
42#ifdef WINDOWS32
43
44char *default_shell = "sh.exe";
45int no_default_sh_exe = 1;
46int batch_mode_shell = 1;
47
48#elif defined (_AMIGA)
49
50char default_shell[] = "";
51extern int MyExecute (char **);
52int batch_mode_shell = 0;
53
54#elif defined (__MSDOS__)
55
56/* The default shell is a pointer so we can change it if Makefile
57 says so. It is without an explicit path so we get a chance
58 to search the $PATH for it (since MSDOS doesn't have standard
59 directories we could trust). */
60char *default_shell = "command.com";
61int batch_mode_shell = 0;
62
63#elif defined (__EMX__)
64
65char *default_shell = "sh.exe";
66int batch_mode_shell = 0;
67
68#elif defined (VMS)
69
70# include <descrip.h>
71char default_shell[] = "";
72int batch_mode_shell = 0;
73
74#else
75
76char default_shell[] = "/bin/sh";
77int batch_mode_shell = 0;
78
79#endif
80
81#ifdef __MSDOS__
82# include <process.h>
83static int execute_by_shell;
84static int dos_pid = 123;
85int dos_status;
86int dos_command_running;
87#endif /* __MSDOS__ */
88
89#ifdef _AMIGA
90# include <proto/dos.h>
91static int amiga_pid = 123;
92static int amiga_status;
93static char amiga_bname[32];
94static int amiga_batch_file;
95#endif /* Amiga. */
96
97#ifdef VMS
98# ifndef __GNUC__
99# include <processes.h>
100# endif
101# include <starlet.h>
102# include <lib$routines.h>
103#endif
104
105#ifdef WINDOWS32
106# include <windows.h>
107# include <io.h>
108# include <process.h>
109# include "sub_proc.h"
110# include "w32err.h"
111# include "pathstuff.h"
112#endif /* WINDOWS32 */
113
114#ifdef __EMX__
115# include <process.h>
116#endif
117
118#if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
119# include <sys/wait.h>
120#endif
121
122#ifdef HAVE_WAITPID
123# define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
124#else /* Don't have waitpid. */
125# ifdef HAVE_WAIT3
126# ifndef wait3
127extern int wait3 ();
128# endif
129# define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
130# endif /* Have wait3. */
131#endif /* Have waitpid. */
132
133#if !defined (wait) && !defined (POSIX)
134extern int wait ();
135#endif
136
137#ifndef HAVE_UNION_WAIT
138
139# define WAIT_T int
140
141# ifndef WTERMSIG
142# define WTERMSIG(x) ((x) & 0x7f)
143# endif
144# ifndef WCOREDUMP
145# define WCOREDUMP(x) ((x) & 0x80)
146# endif
147# ifndef WEXITSTATUS
148# define WEXITSTATUS(x) (((x) >> 8) & 0xff)
149# endif
150# ifndef WIFSIGNALED
151# define WIFSIGNALED(x) (WTERMSIG (x) != 0)
152# endif
153# ifndef WIFEXITED
154# define WIFEXITED(x) (WTERMSIG (x) == 0)
155# endif
156
157#else /* Have `union wait'. */
158
159# define WAIT_T union wait
160# ifndef WTERMSIG
161# define WTERMSIG(x) ((x).w_termsig)
162# endif
163# ifndef WCOREDUMP
164# define WCOREDUMP(x) ((x).w_coredump)
165# endif
166# ifndef WEXITSTATUS
167# define WEXITSTATUS(x) ((x).w_retcode)
168# endif
169# ifndef WIFSIGNALED
170# define WIFSIGNALED(x) (WTERMSIG(x) != 0)
171# endif
172# ifndef WIFEXITED
173# define WIFEXITED(x) (WTERMSIG(x) == 0)
174# endif
175
176#endif /* Don't have `union wait'. */
177
178#ifdef VMS
179static int vms_jobsefnmask = 0;
180#endif /* !VMS */
181
182#ifndef HAVE_UNISTD_H
183extern int dup2 ();
184extern int execve ();
185extern void _exit ();
186# ifndef VMS
187extern int geteuid ();
188extern int getegid ();
189extern int setgid ();
190extern int getgid ();
191# endif
192#endif
193
194extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
195
196extern int getloadavg PARAMS ((double loadavg[], int nelem));
197extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
198 int *is_remote, int *id_ptr, int *used_stdin));
199extern int start_remote_job_p PARAMS ((int));
200extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
201 int *coredump_ptr, int block));
202
203RETSIGTYPE child_handler PARAMS ((int));
204static void free_child PARAMS ((struct child *));
205static void start_job_command PARAMS ((struct child *child));
206static int load_too_high PARAMS ((void));
207static int job_next_command PARAMS ((struct child *));
208static int start_waiting_job PARAMS ((struct child *));
209#ifdef VMS
210static void vmsWaitForChildren PARAMS ((int *));
211#endif
212#ifdef MAKE_DLLSHELL
213static int spawn_command PARAMS ((char **argv, char **envp, struct child *child));
214#endif
215
216
217/* Chain of all live (or recently deceased) children. */
218
219struct child *children = 0;
220
221/* Number of children currently running. */
222
223unsigned int job_slots_used = 0;
224
225/* Nonzero if the `good' standard input is in use. */
226
227static int good_stdin_used = 0;
228
229/* Chain of children waiting to run until the load average goes down. */
230
231static struct child *waiting_jobs = 0;
232
233/* Non-zero if we use a *real* shell (always so on Unix). */
234
235int unixy_shell = 1;
236
237/* Number of jobs started in the current second. */
238
239unsigned long job_counter = 0;
240
241
242
243#ifdef WINDOWS32
244/*
245 * The macro which references this function is defined in make.h.
246 */
247int
248w32_kill(int pid, int sig)
249{
250 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
251}
252#endif /* WINDOWS32 */
253
254#ifdef __EMX__
255/* returns whether path is assumed to be a unix like shell. */
256int
257_is_unixy_shell (const char *path)
258{
259 /* list of non unix shells */
260 const char *known_os2shells[] = {
261 "cmd.exe",
262 "cmd",
263 "4os2.exe",
264 "4os2",
265 "4dos.exe",
266 "4dos",
267 "command.com",
268 "command",
269 NULL
270 };
271
272 /* find the rightmost '/' or '\\' */
273 const char *name = strrchr (path, '/');
274 const char *p = strrchr (path, '\\');
275 unsigned i;
276
277 if (name && p) /* take the max */
278 name = (name > p) ? name : p;
279 else if (p) /* name must be 0 */
280 name = p;
281 else if (!name) /* name and p must be 0 */
282 name = path;
283
284 if (*name == '/' || *name == '\\') name++;
285
286 i = 0;
287 while (known_os2shells[i] != NULL) {
288 if (stricmp (name, known_os2shells[i]) == 0) /* strcasecmp() */
289 return 0; /* not a unix shell */
290 i++;
291 }
292
293 /* in doubt assume a unix like shell */
294 return 1;
295}
296#endif /* __EMX__ */
297
298
299
300/* Write an error message describing the exit status given in
301 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
302 Append "(ignored)" if IGNORED is nonzero. */
303
304static void
305child_error (char *target_name, int exit_code, int exit_sig, int coredump,
306 int ignored)
307{
308 if (ignored && silent_flag)
309 return;
310
311#ifdef VMS
312 if (!(exit_code & 1))
313 error (NILF,
314 (ignored ? _("*** [%s] Error 0x%x (ignored)")
315 : _("*** [%s] Error 0x%x")),
316 target_name, exit_code);
317#else
318 if (exit_sig == 0)
319 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
320 _("*** [%s] Error %d"),
321 target_name, exit_code);
322 else
323 error (NILF, "*** [%s] %s%s",
324 target_name, strsignal (exit_sig),
325 coredump ? _(" (core dumped)") : "");
326#endif /* VMS */
327}
328
329
330#ifdef VMS
331/* Wait for nchildren children to terminate */
332static void
333vmsWaitForChildren(int *status)
334{
335 while (1)
336 {
337 if (!vms_jobsefnmask)
338 {
339 *status = 0;
340 return;
341 }
342
343 *status = sys$wflor (32, vms_jobsefnmask);
344 }
345 return;
346}
347
348/* Set up IO redirection. */
349
350char *
351vms_redirect (struct dsc$descriptor_s *desc, char *fname, char *ibuf)
352{
353 char *fptr;
354 extern char *vmsify ();
355
356 ibuf++;
357 while (isspace ((unsigned char)*ibuf))
358 ibuf++;
359 fptr = ibuf;
360 while (*ibuf && !isspace ((unsigned char)*ibuf))
361 ibuf++;
362 *ibuf = 0;
363 if (strcmp (fptr, "/dev/null") != 0)
364 {
365 strcpy (fname, vmsify (fptr, 0));
366 if (strchr (fname, '.') == 0)
367 strcat (fname, ".");
368 }
369 desc->dsc$w_length = strlen(fname);
370 desc->dsc$a_pointer = fname;
371 desc->dsc$b_dtype = DSC$K_DTYPE_T;
372 desc->dsc$b_class = DSC$K_CLASS_S;
373
374 if (*fname == 0)
375 printf (_("Warning: Empty redirection\n"));
376 return ibuf;
377}
378
379
380/* found apostrophe at (p-1)
381 inc p until after closing apostrophe.
382 */
383
384static char *
385vms_handle_apos (char *p)
386{
387 int alast;
388
389#define SEPCHARS ",/()= "
390
391 alast = 0;
392
393 while (*p != 0)
394 {
395 if (*p == '"')
396 {
397 if (alast)
398 {
399 alast = 0;
400 p++;
401 }
402 else
403 {
404 p++;
405 if (strchr (SEPCHARS, *p))
406 break;
407 alast = 1;
408 }
409 }
410 else
411 p++;
412 }
413
414 return p;
415}
416
417#endif
418
419
420/* Handle a dead child. This handler may or may not ever be installed.
421
422 If we're using the jobserver feature, we need it. First, installing it
423 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
424 read FD to ensure we don't enter another blocking read without reaping all
425 the dead children. In this case we don't need the dead_children count.
426
427 If we don't have either waitpid or wait3, then make is unreliable, but we
428 use the dead_children count to reap children as best we can. */
429
430static unsigned int dead_children = 0;
431
432RETSIGTYPE
433child_handler (int sig UNUSED)
434{
435 ++dead_children;
436
437 if (job_rfd >= 0)
438 {
439 close (job_rfd);
440 job_rfd = -1;
441 }
442
443#if defined __EMX__ && !defined(__INNOTEK_LIBC__)
444 /* The signal handler must called only once! */
445 signal (SIGCHLD, SIG_DFL);
446#endif
447
448 /* This causes problems if the SIGCHLD interrupts a printf().
449 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
450 */
451}
452
453extern int shell_function_pid, shell_function_completed;
454
455/* Reap all dead children, storing the returned status and the new command
456 state (`cs_finished') in the `file' member of the `struct child' for the
457 dead child, and removing the child from the chain. In addition, if BLOCK
458 nonzero, we block in this function until we've reaped at least one
459 complete child, waiting for it to die if necessary. If ERR is nonzero,
460 print an error message first. */
461
462void
463reap_children (int block, int err)
464{
465 WAIT_T status;
466 /* Initially, assume we have some. */
467 int reap_more = 1;
468
469#ifdef WAIT_NOHANG
470# define REAP_MORE reap_more
471#else
472# define REAP_MORE dead_children
473#endif
474
475 /* As long as:
476
477 We have at least one child outstanding OR a shell function in progress,
478 AND
479 We're blocking for a complete child OR there are more children to reap
480
481 we'll keep reaping children. */
482
483 while ((children != 0 || shell_function_pid != 0)
484 && (block || REAP_MORE))
485 {
486 int remote = 0;
487 register int pid;
488 int exit_code, exit_sig, coredump;
489 register struct child *lastc, *c;
490 int child_failed;
491 int any_remote, any_local;
492#if defined(CONFIG_WITH_KMK_BUILTIN) || defined(MAKE_DLLSHELL)
493 struct child *completed_child = 0;
494#endif
495
496 if (err && block)
497 {
498 /* We might block for a while, so let the user know why. */
499 fflush (stdout);
500 error (NILF, _("*** Waiting for unfinished jobs...."));
501 }
502
503 /* We have one less dead child to reap. As noted in
504 child_handler() above, this count is completely unimportant for
505 all modern, POSIX-y systems that support wait3() or waitpid().
506 The rest of this comment below applies only to early, broken
507 pre-POSIX systems. We keep the count only because... it's there...
508
509 The test and decrement are not atomic; if it is compiled into:
510 register = dead_children - 1;
511 dead_children = register;
512 a SIGCHLD could come between the two instructions.
513 child_handler increments dead_children.
514 The second instruction here would lose that increment. But the
515 only effect of dead_children being wrong is that we might wait
516 longer than necessary to reap a child, and lose some parallelism;
517 and we might print the "Waiting for unfinished jobs" message above
518 when not necessary. */
519
520 if (dead_children > 0)
521 --dead_children;
522
523 any_remote = 0;
524 any_local = shell_function_pid != 0;
525 for (c = children; c != 0; c = c->next)
526 {
527 any_remote |= c->remote;
528 any_local |= ! c->remote;
529#if defined(CONFIG_WITH_KMK_BUILTIN) || defined(MAKE_DLLSHELL)
530 if (c->have_status)
531 completed_child = c;
532#endif
533 DB (DB_JOBS, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
534 (unsigned long int) c, c->file->name,
535 (long) c->pid, c->remote ? _(" (remote)") : ""));
536#ifdef VMS
537 break;
538#endif
539 }
540
541 /* First, check for remote children. */
542 if (any_remote)
543 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
544 else
545 pid = 0;
546
547 if (pid > 0)
548 /* We got a remote child. */
549 remote = 1;
550 else if (pid < 0)
551 {
552 /* A remote status command failed miserably. Punt. */
553 remote_status_lose:
554 pfatal_with_name ("remote_status");
555 }
556 else
557 {
558 /* No remote children. Check for local children. */
559#if defined(CONFIG_WITH_KMK_BUILTIN) || defined(MAKE_DLLSHELL)
560 if (completed_child)
561 {
562 pid = completed_child->pid;
563 status = (WAIT_T)completed_child->status;
564 }
565 else
566#endif
567#if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
568 if (any_local)
569 {
570#ifdef VMS
571 vmsWaitForChildren (&status);
572 pid = c->pid;
573#elif MAKE_DLLSHELL
574 pid = wait_jobs((int*)&status, block);
575#else
576#ifdef WAIT_NOHANG
577 if (!block)
578 pid = WAIT_NOHANG (&status);
579 else
580#endif
581 pid = wait (&status);
582#endif /* !VMS */
583 }
584 else
585 pid = 0;
586
587 if (pid < 0)
588 {
589 /* The wait*() failed miserably. Punt. */
590 pfatal_with_name ("wait");
591 }
592 else if (pid > 0)
593 {
594 /* We got a child exit; chop the status word up. */
595 exit_code = WEXITSTATUS (status);
596 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
597 coredump = WCOREDUMP (status);
598
599 /* If we have started jobs in this second, remove one. */
600 if (job_counter)
601 --job_counter;
602 }
603 else
604 {
605 /* No local children are dead. */
606 reap_more = 0;
607
608 if (!block || !any_remote)
609 break;
610
611 /* Now try a blocking wait for a remote child. */
612 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
613 if (pid < 0)
614 goto remote_status_lose;
615 else if (pid == 0)
616 /* No remote children either. Finally give up. */
617 break;
618
619 /* We got a remote child. */
620 remote = 1;
621 }
622#endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
623
624#ifdef __MSDOS__
625 /* Life is very different on MSDOS. */
626 pid = dos_pid - 1;
627 status = dos_status;
628 exit_code = WEXITSTATUS (status);
629 if (exit_code == 0xff)
630 exit_code = -1;
631 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
632 coredump = 0;
633#endif /* __MSDOS__ */
634#ifdef _AMIGA
635 /* Same on Amiga */
636 pid = amiga_pid - 1;
637 status = amiga_status;
638 exit_code = amiga_status;
639 exit_sig = 0;
640 coredump = 0;
641#endif /* _AMIGA */
642#ifdef WINDOWS32
643 {
644 HANDLE hPID;
645 int err;
646
647 /* wait for anything to finish */
648 if (hPID = process_wait_for_any()) {
649
650 /* was an error found on this process? */
651 err = process_last_err(hPID);
652
653 /* get exit data */
654 exit_code = process_exit_code(hPID);
655
656 if (err)
657 fprintf(stderr, "make (e=%d): %s",
658 exit_code, map_windows32_error_to_string(exit_code));
659
660 /* signal */
661 exit_sig = process_signal(hPID);
662
663 /* cleanup process */
664 process_cleanup(hPID);
665
666 coredump = 0;
667 }
668 pid = (int) hPID;
669 }
670#endif /* WINDOWS32 */
671 }
672
673 /* Check if this is the child of the `shell' function. */
674 if (!remote && pid == shell_function_pid)
675 {
676 /* It is. Leave an indicator for the `shell' function. */
677 if (exit_sig == 0 && exit_code == 127)
678 shell_function_completed = -1;
679 else
680 shell_function_completed = 1;
681 break;
682 }
683
684 child_failed = exit_sig != 0 || exit_code != 0;
685
686 /* Search for a child matching the deceased one. */
687 lastc = 0;
688 for (c = children; c != 0; lastc = c, c = c->next)
689 if (c->remote == remote && c->pid == pid)
690 break;
691
692 if (c == 0)
693 /* An unknown child died.
694 Ignore it; it was inherited from our invoker. */
695 continue;
696
697 DB (DB_JOBS, (child_failed
698 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
699 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
700 (unsigned long int) c, (long) c->pid,
701 c->remote ? _(" (remote)") : ""));
702
703 if (c->sh_batch_file) {
704 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
705 c->sh_batch_file));
706
707 /* just try and remove, don't care if this fails */
708 remove (c->sh_batch_file);
709
710 /* all done with memory */
711 free (c->sh_batch_file);
712 c->sh_batch_file = NULL;
713 }
714
715 /* If this child had the good stdin, say it is now free. */
716 if (c->good_stdin)
717 good_stdin_used = 0;
718
719 if (child_failed && !c->noerror && !ignore_errors_flag)
720 {
721 /* The commands failed. Write an error message,
722 delete non-precious targets, and abort. */
723 static int delete_on_error = -1;
724 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
725 c->file->update_status = 2;
726 if (delete_on_error == -1)
727 {
728 struct file *f = lookup_file (".DELETE_ON_ERROR");
729 delete_on_error = f != 0 && f->is_target;
730 }
731 if (exit_sig != 0 || delete_on_error)
732 delete_child_targets (c);
733 }
734 else
735 {
736 if (child_failed)
737 {
738 /* The commands failed, but we don't care. */
739 child_error (c->file->name,
740 exit_code, exit_sig, coredump, 1);
741 child_failed = 0;
742 }
743
744 /* If there are more commands to run, try to start them. */
745 if (job_next_command (c))
746 {
747 if (handling_fatal_signal)
748 {
749 /* Never start new commands while we are dying.
750 Since there are more commands that wanted to be run,
751 the target was not completely remade. So we treat
752 this as if a command had failed. */
753 c->file->update_status = 2;
754 }
755 else
756 {
757 /* Check again whether to start remotely.
758 Whether or not we want to changes over time.
759 Also, start_remote_job may need state set up
760 by start_remote_job_p. */
761 c->remote = start_remote_job_p (0);
762 start_job_command (c);
763 /* Fatal signals are left blocked in case we were
764 about to put that child on the chain. But it is
765 already there, so it is safe for a fatal signal to
766 arrive now; it will clean up this child's targets. */
767 unblock_sigs ();
768 if (c->file->command_state == cs_running)
769 /* We successfully started the new command.
770 Loop to reap more children. */
771 continue;
772 }
773
774 if (c->file->update_status != 0)
775 /* We failed to start the commands. */
776 delete_child_targets (c);
777 }
778 else
779 /* There are no more commands. We got through them all
780 without an unignored error. Now the target has been
781 successfully updated. */
782 c->file->update_status = 0;
783 }
784
785 /* When we get here, all the commands for C->file are finished
786 (or aborted) and C->file->update_status contains 0 or 2. But
787 C->file->command_state is still cs_running if all the commands
788 ran; notice_finish_file looks for cs_running to tell it that
789 it's interesting to check the file's modtime again now. */
790
791 if (! handling_fatal_signal)
792 /* Notice if the target of the commands has been changed.
793 This also propagates its values for command_state and
794 update_status to its also_make files. */
795 notice_finished_file (c->file);
796
797 DB (DB_JOBS, (_("Removing child 0x%08lx PID %ld%s from chain.\n"),
798 (unsigned long int) c, (long) c->pid,
799 c->remote ? _(" (remote)") : ""));
800
801 /* Block fatal signals while frobnicating the list, so that
802 children and job_slots_used are always consistent. Otherwise
803 a fatal signal arriving after the child is off the chain and
804 before job_slots_used is decremented would believe a child was
805 live and call reap_children again. */
806 block_sigs ();
807
808 /* There is now another slot open. */
809 if (job_slots_used > 0)
810 --job_slots_used;
811
812 /* Remove the child from the chain and free it. */
813 if (lastc == 0)
814 children = c->next;
815 else
816 lastc->next = c->next;
817
818 free_child (c);
819
820 unblock_sigs ();
821
822 /* If the job failed, and the -k flag was not given, die,
823 unless we are already in the process of dying. */
824 if (!err && child_failed && !keep_going_flag &&
825 /* fatal_error_signal will die with the right signal. */
826 !handling_fatal_signal)
827 die (2);
828
829 /* Only block for one child. */
830 block = 0;
831 }
832
833 return;
834}
835
836
837/* Free the storage allocated for CHILD. */
838
839static void
840free_child (struct child *child)
841{
842 /* If this child is the only one it was our "free" job, so don't put a
843 token back for it. This child has already been removed from the list,
844 so if there any left this wasn't the last one. */
845
846 if (job_fds[1] >= 0 && children)
847 {
848 char token = '+';
849 int r;
850
851 /* Write a job token back to the pipe. */
852
853 EINTRLOOP (r, write (job_fds[1], &token, 1));
854 if (r != 1)
855 pfatal_with_name (_("write jobserver"));
856
857 DB (DB_JOBS, (_("Released token for child 0x%08lx (%s).\n"),
858 (unsigned long int) child, child->file->name));
859 }
860
861 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
862 return;
863
864 if (child->command_lines != 0)
865 {
866 register unsigned int i;
867 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
868 free (child->command_lines[i]);
869 free ((char *) child->command_lines);
870 }
871
872 if (child->environment != 0)
873 {
874 register char **ep = child->environment;
875 while (*ep != 0)
876 free (*ep++);
877 free ((char *) child->environment);
878 }
879
880 free ((char *) child);
881}
882
883
884#ifdef POSIX
885extern sigset_t fatal_signal_set;
886#endif
887
888void
889block_sigs (void)
890{
891#ifdef POSIX
892 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
893#else
894# ifdef HAVE_SIGSETMASK
895 (void) sigblock (fatal_signal_mask);
896# endif
897#endif
898}
899
900#ifdef POSIX
901void
902unblock_sigs (void)
903{
904 sigset_t empty;
905 sigemptyset (&empty);
906 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
907}
908#endif
909
910#ifdef MAKE_JOBSERVER
911/* Set the child handler action flags to FLAGS. */
912static void
913set_child_handler_action_flags (int flags)
914{
915 struct sigaction sa;
916 bzero ((char *) &sa, sizeof sa);
917 sa.sa_handler = child_handler;
918 sa.sa_flags = flags;
919#if defined SIGCHLD
920 sigaction (SIGCHLD, &sa, NULL);
921#endif
922#if defined SIGCLD && SIGCLD != SIGCHLD
923 sigaction (SIGCLD, &sa, NULL);
924#endif
925}
926#endif
927
928
929/* Start a job to run the commands specified in CHILD.
930 CHILD is updated to reflect the commands and ID of the child process.
931
932 NOTE: On return fatal signals are blocked! The caller is responsible
933 for calling `unblock_sigs', once the new child is safely on the chain so
934 it can be cleaned up in the event of a fatal signal. */
935
936static void
937start_job_command (struct child *child)
938{
939#ifndef _AMIGA
940 static int bad_stdin = -1;
941#endif
942 register char *p;
943 int flags;
944#ifdef VMS
945 char *argv;
946#else
947 char **argv;
948#endif
949
950 /* If we have a completely empty commandset, stop now. */
951 if (!child->command_ptr)
952 goto next_command;
953
954 /* Combine the flags parsed for the line itself with
955 the flags specified globally for this target. */
956 flags = (child->file->command_flags
957 | child->file->cmds->lines_flags[child->command_line - 1]);
958
959 p = child->command_ptr;
960 child->noerror = flags & COMMANDS_NOERROR;
961
962 while (*p != '\0')
963 {
964 if (*p == '@')
965 flags |= COMMANDS_SILENT;
966 else if (*p == '+')
967 flags |= COMMANDS_RECURSE;
968 else if (*p == '-')
969 child->noerror = 1;
970 else if (!isblank ((unsigned char)*p))
971 {
972#ifdef CONFIG_WITH_KMK_BUILTIN
973 if ( !(flags & COMMANDS_BUILTIN)
974 && !strncmp(p, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
975 flags |= COMMANDS_BUILTIN;
976#endif /* CONFIG_WITH_KMK_BUILTIN */
977 break;
978 }
979 ++p;
980 }
981
982 /* Update the file's command flags with any new ones we found. We only
983 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
984 now marking more commands recursive than should be in the case of
985 multiline define/endef scripts where only one line is marked "+". In
986 order to really fix this, we'll have to keep a lines_flags for every
987 actual line, after expansion. */
988 child->file->cmds->lines_flags[child->command_line - 1]
989 |= flags & COMMANDS_RECURSE;
990
991 /* Figure out an argument list from this command line. */
992
993 {
994 char *end = 0;
995#ifdef VMS
996 argv = p;
997#else
998 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
999#endif
1000 if (end == NULL)
1001 child->command_ptr = NULL;
1002 else
1003 {
1004 *end++ = '\0';
1005 child->command_ptr = end;
1006 }
1007 }
1008
1009 /* If -q was given, say that updating `failed' if there was any text on the
1010 command line, or `succeeded' otherwise. The exit status of 1 tells the
1011 user that -q is saying `something to do'; the exit status for a random
1012 error is 2. */
1013 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
1014 {
1015#ifndef VMS
1016 free (argv[0]);
1017 free ((char *) argv);
1018#endif
1019 child->file->update_status = 1;
1020 notice_finished_file (child->file);
1021 return;
1022 }
1023
1024 if (touch_flag && !(flags & COMMANDS_RECURSE))
1025 {
1026 /* Go on to the next command. It might be the recursive one.
1027 We construct ARGV only to find the end of the command line. */
1028#ifndef VMS
1029 if (argv)
1030 {
1031 free (argv[0]);
1032 free ((char *) argv);
1033 }
1034#endif
1035 argv = 0;
1036 }
1037
1038 if (argv == 0)
1039 {
1040 next_command:
1041#ifdef __MSDOS__
1042 execute_by_shell = 0; /* in case construct_command_argv sets it */
1043#endif
1044 /* This line has no commands. Go to the next. */
1045 if (job_next_command (child))
1046 start_job_command (child);
1047 else
1048 {
1049 /* No more commands. Make sure we're "running"; we might not be if
1050 (e.g.) all commands were skipped due to -n. */
1051 set_command_state (child->file, cs_running);
1052 child->file->update_status = 0;
1053 notice_finished_file (child->file);
1054 }
1055 return;
1056 }
1057
1058 /* Print out the command. If silent, we call `message' with null so it
1059 can log the working directory before the command's own error messages
1060 appear. */
1061
1062 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
1063 ? "%s" : (char *) 0, p);
1064
1065 /* Tell update_goal_chain that a command has been started on behalf of
1066 this target. It is important that this happens here and not in
1067 reap_children (where we used to do it), because reap_children might be
1068 reaping children from a different target. We want this increment to
1069 guaranteedly indicate that a command was started for the dependency
1070 chain (i.e., update_file recursion chain) we are processing. */
1071
1072 ++commands_started;
1073
1074 /* Optimize an empty command. People use this for timestamp rules,
1075 so avoid forking a useless shell. Do this after we increment
1076 commands_started so make still treats this special case as if it
1077 performed some action (makes a difference as to what messages are
1078 printed, etc. */
1079
1080#if !defined(VMS) && !defined(_AMIGA)
1081 if (
1082#if defined __MSDOS__ || defined (__EMX__)
1083 unixy_shell /* the test is complicated and we already did it */
1084#else
1085 (argv[0] && !strcmp (argv[0], "/bin/sh"))
1086#endif
1087 && (argv[1]
1088 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
1089 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1090 && argv[3] == NULL)
1091 {
1092 free (argv[0]);
1093 free ((char *) argv);
1094 goto next_command;
1095 }
1096#endif /* !VMS && !_AMIGA */
1097
1098 /* If -n was given, recurse to get the next line in the sequence. */
1099
1100 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1101 {
1102#ifndef VMS
1103 free (argv[0]);
1104 free ((char *) argv);
1105#endif
1106 goto next_command;
1107 }
1108
1109#ifdef CONFIG_WITH_KMK_BUILTIN
1110 /* If builtin command then pass it on to the builtin shell interpreter. */
1111
1112 if ((flags & COMMANDS_BUILTIN) && !just_print_flag)
1113 {
1114 int rc;
1115 char **p2 = argv;
1116 while (*p2 && strncmp(*p2, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
1117 p2++;
1118 assert(*p2);
1119 set_command_state (child->file, cs_running);
1120 if (p2 != argv)
1121 rc = kmk_builtin_command(*p2);
1122 else
1123 {
1124 int argc = 1;
1125 while (argv[argc])
1126 argc++;
1127 rc = kmk_builtin_command_parsed(argc, argv);
1128 }
1129#ifndef VMS
1130 free (argv[0]);
1131 free ((char *) argv);
1132#endif
1133 if (!rc)
1134 goto next_command;
1135 child->pid = (pid_t)42424242;
1136 child->status = rc << 8;
1137 child->have_status = 1;
1138 return;
1139 }
1140#endif /* CONFIG_WITH_KMK_BUILTIN */
1141
1142 /* Flush the output streams so they won't have things written twice. */
1143
1144 fflush (stdout);
1145 fflush (stderr);
1146
1147#ifndef VMS
1148#if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1149
1150 /* Set up a bad standard input that reads from a broken pipe. */
1151
1152 if (bad_stdin == -1)
1153 {
1154 /* Make a file descriptor that is the read end of a broken pipe.
1155 This will be used for some children's standard inputs. */
1156 int pd[2];
1157 if (pipe (pd) == 0)
1158 {
1159 /* Close the write side. */
1160 (void) close (pd[1]);
1161 /* Save the read side. */
1162 bad_stdin = pd[0];
1163
1164 /* Set the descriptor to close on exec, so it does not litter any
1165 child's descriptor table. When it is dup2'd onto descriptor 0,
1166 that descriptor will not close on exec. */
1167 CLOSE_ON_EXEC (bad_stdin);
1168 }
1169 }
1170
1171#endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1172
1173 /* Decide whether to give this child the `good' standard input
1174 (one that points to the terminal or whatever), or the `bad' one
1175 that points to the read side of a broken pipe. */
1176
1177 child->good_stdin = !good_stdin_used;
1178 if (child->good_stdin)
1179 good_stdin_used = 1;
1180
1181#endif /* !VMS */
1182
1183 child->deleted = 0;
1184
1185#ifndef _AMIGA
1186 /* Set up the environment for the child. */
1187 if (child->environment == 0)
1188 child->environment = target_environment (child->file);
1189#endif
1190
1191#if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1192
1193#ifndef VMS
1194 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1195 if (child->remote)
1196 {
1197 int is_remote, id, used_stdin;
1198 if (start_remote_job (argv, child->environment,
1199 child->good_stdin ? 0 : bad_stdin,
1200 &is_remote, &id, &used_stdin))
1201 /* Don't give up; remote execution may fail for various reasons. If
1202 so, simply run the job locally. */
1203 goto run_local;
1204 else
1205 {
1206 if (child->good_stdin && !used_stdin)
1207 {
1208 child->good_stdin = 0;
1209 good_stdin_used = 0;
1210 }
1211 child->remote = is_remote;
1212 child->pid = id;
1213 }
1214 }
1215 else
1216#endif /* !VMS */
1217 {
1218 /* Fork the child process. */
1219
1220 char **parent_environ;
1221
1222 run_local:
1223 block_sigs ();
1224
1225 child->remote = 0;
1226
1227#ifdef VMS
1228
1229 if (!child_execute_job (argv, child)) {
1230 /* Fork failed! */
1231 perror_with_name ("vfork", "");
1232 goto error;
1233 }
1234
1235#else
1236
1237 parent_environ = environ;
1238
1239# ifdef __EMX__
1240 /* If we aren't running a recursive command and we have a jobserver
1241 pipe, close it before exec'ing. */
1242 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1243 {
1244 CLOSE_ON_EXEC (job_fds[0]);
1245 CLOSE_ON_EXEC (job_fds[1]);
1246 }
1247 if (job_rfd >= 0)
1248 CLOSE_ON_EXEC (job_rfd);
1249
1250 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1251 child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1252 argv, child->environment, child);
1253 if (child->pid < 0)
1254 {
1255 /* spawn failed! */
1256 unblock_sigs ();
1257 perror_with_name ("spawn", "");
1258 goto error;
1259 }
1260
1261 /* undo CLOSE_ON_EXEC() after the child process has been started */
1262 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1263 {
1264 fcntl (job_fds[0], F_SETFD, 0);
1265 fcntl (job_fds[1], F_SETFD, 0);
1266 }
1267 if (job_rfd >= 0)
1268 fcntl (job_rfd, F_SETFD, 0);
1269
1270#else /* !__EMX__ */
1271
1272 child->pid = vfork ();
1273 environ = parent_environ; /* Restore value child may have clobbered. */
1274 if (child->pid == 0)
1275 {
1276 /* We are the child side. */
1277 unblock_sigs ();
1278
1279 /* If we aren't running a recursive command and we have a jobserver
1280 pipe, close it before exec'ing. */
1281 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1282 {
1283 close (job_fds[0]);
1284 close (job_fds[1]);
1285 }
1286 if (job_rfd >= 0)
1287 close (job_rfd);
1288
1289 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1290 argv, child->environment);
1291 }
1292 else if (child->pid < 0)
1293 {
1294 /* Fork failed! */
1295 unblock_sigs ();
1296 perror_with_name ("vfork", "");
1297 goto error;
1298 }
1299# endif /* !__EMX__ */
1300#endif /* !VMS */
1301 }
1302
1303#else /* __MSDOS__ or Amiga or WINDOWS32 */
1304#ifdef __MSDOS__
1305 {
1306 int proc_return;
1307
1308 block_sigs ();
1309 dos_status = 0;
1310
1311 /* We call `system' to do the job of the SHELL, since stock DOS
1312 shell is too dumb. Our `system' knows how to handle long
1313 command lines even if pipes/redirection is needed; it will only
1314 call COMMAND.COM when its internal commands are used. */
1315 if (execute_by_shell)
1316 {
1317 char *cmdline = argv[0];
1318 /* We don't have a way to pass environment to `system',
1319 so we need to save and restore ours, sigh... */
1320 char **parent_environ = environ;
1321
1322 environ = child->environment;
1323
1324 /* If we have a *real* shell, tell `system' to call
1325 it to do everything for us. */
1326 if (unixy_shell)
1327 {
1328 /* A *real* shell on MSDOS may not support long
1329 command lines the DJGPP way, so we must use `system'. */
1330 cmdline = argv[2]; /* get past "shell -c" */
1331 }
1332
1333 dos_command_running = 1;
1334 proc_return = system (cmdline);
1335 environ = parent_environ;
1336 execute_by_shell = 0; /* for the next time */
1337 }
1338 else
1339 {
1340 dos_command_running = 1;
1341 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1342 }
1343
1344 /* Need to unblock signals before turning off
1345 dos_command_running, so that child's signals
1346 will be treated as such (see fatal_error_signal). */
1347 unblock_sigs ();
1348 dos_command_running = 0;
1349
1350 /* If the child got a signal, dos_status has its
1351 high 8 bits set, so be careful not to alter them. */
1352 if (proc_return == -1)
1353 dos_status |= 0xff;
1354 else
1355 dos_status |= (proc_return & 0xff);
1356 ++dead_children;
1357 child->pid = dos_pid++;
1358 }
1359#endif /* __MSDOS__ */
1360#ifdef _AMIGA
1361 amiga_status = MyExecute (argv);
1362
1363 ++dead_children;
1364 child->pid = amiga_pid++;
1365 if (amiga_batch_file)
1366 {
1367 amiga_batch_file = 0;
1368 DeleteFile (amiga_bname); /* Ignore errors. */
1369 }
1370#endif /* Amiga */
1371#ifdef WINDOWS32
1372 {
1373 HANDLE hPID;
1374 char* arg0;
1375
1376 /* make UNC paths safe for CreateProcess -- backslash format */
1377 arg0 = argv[0];
1378 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1379 for ( ; arg0 && *arg0; arg0++)
1380 if (*arg0 == '/')
1381 *arg0 = '\\';
1382
1383 /* make sure CreateProcess() has Path it needs */
1384 sync_Path_environment();
1385
1386 hPID = process_easy(argv, child->environment);
1387
1388 if (hPID != INVALID_HANDLE_VALUE)
1389 child->pid = (int) hPID;
1390 else {
1391 int i;
1392 unblock_sigs();
1393 fprintf(stderr,
1394 _("process_easy() failed failed to launch process (e=%d)\n"),
1395 process_last_err(hPID));
1396 for (i = 0; argv[i]; i++)
1397 fprintf(stderr, "%s ", argv[i]);
1398 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1399 }
1400 }
1401#endif /* WINDOWS32 */
1402#endif /* __MSDOS__ or Amiga or WINDOWS32 */
1403
1404 /* Bump the number of jobs started in this second. */
1405 ++job_counter;
1406
1407 /* We are the parent side. Set the state to
1408 say the commands are running and return. */
1409
1410 set_command_state (child->file, cs_running);
1411
1412 /* Free the storage used by the child's argument list. */
1413#ifndef VMS
1414 free (argv[0]);
1415 free ((char *) argv);
1416#endif
1417
1418 return;
1419
1420 error:
1421 child->file->update_status = 2;
1422 notice_finished_file (child->file);
1423 return;
1424}
1425
1426/* Try to start a child running.
1427 Returns nonzero if the child was started (and maybe finished), or zero if
1428 the load was too high and the child was put on the `waiting_jobs' chain. */
1429
1430static int
1431start_waiting_job (struct child *c)
1432{
1433 struct file *f = c->file;
1434 DB (DB_KMK, (_("start_waiting_job %p (`%s') command_flags=%#x\n"), c, c->file->name, c->file->command_flags));
1435
1436 /* If we can start a job remotely, we always want to, and don't care about
1437 the local load average. We record that the job should be started
1438 remotely in C->remote for start_job_command to test. */
1439
1440 c->remote = start_remote_job_p (1);
1441
1442 /* If we are running at least one job already and the load average
1443 is too high, make this one wait. */
1444 if (!c->remote && job_slots_used > 0 &&
1445 (not_parallel || (c->file->command_flags & COMMANDS_NOTPARALLEL) || load_too_high ()))
1446 {
1447 /* Put this child on the chain of children waiting for the load average
1448 to go down. if not paralell, put it last. */
1449 set_command_state (f, cs_running);
1450 c->next = waiting_jobs;
1451 if (c->next && (c->file->command_flags & COMMANDS_NOTPARALLEL))
1452 {
1453 struct child *prev = waiting_jobs;
1454 while (prev->next)
1455 prev = prev->next;
1456 c->next = 0;
1457 prev->next = c;
1458 }
1459 else
1460 waiting_jobs = c;
1461 DB (DB_KMK, (_("queued child %p (`%s')\n"), c, c->file->name));
1462 return 0;
1463 }
1464
1465 if (c->file->command_flags & COMMANDS_NOTPARALLEL)
1466 {
1467 assert(not_parallel == 0);
1468 DB (DB_KMK, (_("not_parallel %d -> %d (file=%p `%s')\n"), not_parallel, not_parallel + 1, c->file, c->file->name));
1469 ++not_parallel;
1470 }
1471
1472
1473 /* Start the first command; reap_children will run later command lines. */
1474 start_job_command (c);
1475
1476 switch (f->command_state)
1477 {
1478 case cs_running:
1479 c->next = children;
1480 DB (DB_JOBS, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1481 (unsigned long int) c, c->file->name,
1482 (long) c->pid, c->remote ? _(" (remote)") : ""));
1483 children = c;
1484 /* One more job slot is in use. */
1485 ++job_slots_used;
1486 unblock_sigs ();
1487 break;
1488
1489 case cs_not_started:
1490 /* All the command lines turned out to be empty. */
1491 f->update_status = 0;
1492 /* FALLTHROUGH */
1493
1494 case cs_finished:
1495 notice_finished_file (f);
1496 free_child (c);
1497 break;
1498
1499 default:
1500 assert (f->command_state == cs_finished);
1501 break;
1502 }
1503
1504 return 1;
1505}
1506
1507/* Create a `struct child' for FILE and start its commands running. */
1508
1509void
1510new_job (struct file *file)
1511{
1512 register struct commands *cmds = file->cmds;
1513 register struct child *c;
1514 char **lines;
1515 register unsigned int i;
1516
1517 /* Let any previously decided-upon jobs that are waiting
1518 for the load to go down start before this new one. */
1519 start_waiting_jobs ();
1520
1521 /* Reap any children that might have finished recently. */
1522 reap_children (0, 0);
1523
1524 /* Chop the commands up into lines if they aren't already. */
1525 chop_commands (cmds);
1526
1527 /* Expand the command lines and store the results in LINES. */
1528 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1529 for (i = 0; i < cmds->ncommand_lines; ++i)
1530 {
1531 /* Collapse backslash-newline combinations that are inside variable
1532 or function references. These are left alone by the parser so
1533 that they will appear in the echoing of commands (where they look
1534 nice); and collapsed by construct_command_argv when it tokenizes.
1535 But letting them survive inside function invocations loses because
1536 we don't want the functions to see them as part of the text. */
1537
1538 char *in, *out, *ref;
1539
1540 /* IN points to where in the line we are scanning.
1541 OUT points to where in the line we are writing.
1542 When we collapse a backslash-newline combination,
1543 IN gets ahead of OUT. */
1544
1545 in = out = cmds->command_lines[i];
1546 while ((ref = strchr (in, '$')) != 0)
1547 {
1548 ++ref; /* Move past the $. */
1549
1550 if (out != in)
1551 /* Copy the text between the end of the last chunk
1552 we processed (where IN points) and the new chunk
1553 we are about to process (where REF points). */
1554 bcopy (in, out, ref - in);
1555
1556 /* Move both pointers past the boring stuff. */
1557 out += ref - in;
1558 in = ref;
1559
1560 if (*ref == '(' || *ref == '{')
1561 {
1562 char openparen = *ref;
1563 char closeparen = openparen == '(' ? ')' : '}';
1564 int count;
1565 char *p;
1566
1567 *out++ = *in++; /* Copy OPENPAREN. */
1568 /* IN now points past the opening paren or brace.
1569 Count parens or braces until it is matched. */
1570 count = 0;
1571 while (*in != '\0')
1572 {
1573 if (*in == closeparen && --count < 0)
1574 break;
1575 else if (*in == '\\' && in[1] == '\n')
1576 {
1577 /* We have found a backslash-newline inside a
1578 variable or function reference. Eat it and
1579 any following whitespace. */
1580
1581 int quoted = 0;
1582 for (p = in - 1; p > ref && *p == '\\'; --p)
1583 quoted = !quoted;
1584
1585 if (quoted)
1586 /* There were two or more backslashes, so this is
1587 not really a continuation line. We don't collapse
1588 the quoting backslashes here as is done in
1589 collapse_continuations, because the line will
1590 be collapsed again after expansion. */
1591 *out++ = *in++;
1592 else
1593 {
1594 /* Skip the backslash, newline and
1595 any following whitespace. */
1596 in = next_token (in + 2);
1597
1598 /* Discard any preceding whitespace that has
1599 already been written to the output. */
1600 while (out > ref
1601 && isblank ((unsigned char)out[-1]))
1602 --out;
1603
1604 /* Replace it all with a single space. */
1605 *out++ = ' ';
1606 }
1607 }
1608 else
1609 {
1610 if (*in == openparen)
1611 ++count;
1612
1613 *out++ = *in++;
1614 }
1615 }
1616 }
1617 }
1618
1619 /* There are no more references in this line to worry about.
1620 Copy the remaining uninteresting text to the output. */
1621 if (out != in)
1622 strcpy (out, in);
1623
1624 /* Finally, expand the line. */
1625 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1626 file);
1627 }
1628
1629 /* Start the command sequence, record it in a new
1630 `struct child', and add that to the chain. */
1631
1632 c = (struct child *) xmalloc (sizeof (struct child));
1633 bzero ((char *)c, sizeof (struct child));
1634 c->file = file;
1635 c->command_lines = lines;
1636 c->sh_batch_file = NULL;
1637
1638 /* Fetch the first command line to be run. */
1639 job_next_command (c);
1640
1641 /* Wait for a job slot to be freed up. If we allow an infinite number
1642 don't bother; also job_slots will == 0 if we're using the jobserver. */
1643
1644 if (job_slots != 0)
1645 while (job_slots_used == job_slots)
1646 reap_children (1, 0);
1647
1648#ifdef MAKE_JOBSERVER
1649 /* If we are controlling multiple jobs make sure we have a token before
1650 starting the child. */
1651
1652 /* This can be inefficient. There's a decent chance that this job won't
1653 actually have to run any subprocesses: the command script may be empty
1654 or otherwise optimized away. It would be nice if we could defer
1655 obtaining a token until just before we need it, in start_job_command.
1656 To do that we'd need to keep track of whether we'd already obtained a
1657 token (since start_job_command is called for each line of the job, not
1658 just once). Also more thought needs to go into the entire algorithm;
1659 this is where the old parallel job code waits, so... */
1660
1661 else if (job_fds[0] >= 0)
1662 while (1)
1663 {
1664 char token;
1665 int got_token;
1666 int saved_errno;
1667
1668 DB (DB_JOBS, ("Need a job token; we %shave children\n",
1669 children ? "" : "don't "));
1670
1671 /* If we don't already have a job started, use our "free" token. */
1672 if (!children)
1673 break;
1674
1675 /* Read a token. As long as there's no token available we'll block.
1676 We enable interruptible system calls before the read(2) so that if
1677 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1678 we can process the death(s) and return tokens to the free pool.
1679
1680 Once we return from the read, we immediately reinstate restartable
1681 system calls. This allows us to not worry about checking for
1682 EINTR on all the other system calls in the program.
1683
1684 There is one other twist: there is a span between the time
1685 reap_children() does its last check for dead children and the time
1686 the read(2) call is entered, below, where if a child dies we won't
1687 notice. This is extremely serious as it could cause us to
1688 deadlock, given the right set of events.
1689
1690 To avoid this, we do the following: before we reap_children(), we
1691 dup(2) the read FD on the jobserver pipe. The read(2) call below
1692 uses that new FD. In the signal handler, we close that FD. That
1693 way, if a child dies during the section mentioned above, the
1694 read(2) will be invoked with an invalid FD and will return
1695 immediately with EBADF. */
1696
1697 /* Make sure we have a dup'd FD. */
1698 if (job_rfd < 0)
1699 {
1700 DB (DB_JOBS, ("Duplicate the job FD\n"));
1701 job_rfd = dup (job_fds[0]);
1702 }
1703
1704 /* Reap anything that's currently waiting. */
1705 reap_children (0, 0);
1706
1707 /* If our "free" token has become available, use it. */
1708 if (!children)
1709 break;
1710
1711 /* Set interruptible system calls, and read() for a job token. */
1712 set_child_handler_action_flags (0);
1713 got_token = read (job_rfd, &token, 1);
1714 saved_errno = errno;
1715#if defined(__EMX__) && !defined(__INNOTEK_LIBC__)
1716 /* The child handler must be turned off here. */
1717 signal (SIGCHLD, SIG_DFL);
1718#endif
1719 set_child_handler_action_flags (SA_RESTART);
1720
1721 /* If we got one, we're done here. */
1722 if (got_token == 1)
1723 {
1724 DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1725 (unsigned long int) c, c->file->name));
1726 break;
1727 }
1728
1729 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1730 go back and reap_children(), and try again. */
1731 errno = saved_errno;
1732 if (errno != EINTR && errno != EBADF)
1733 pfatal_with_name (_("read jobs pipe"));
1734 if (errno == EBADF)
1735 DB (DB_JOBS, ("Read returned EBADF.\n"));
1736 }
1737#endif
1738
1739 /* The job is now primed. Start it running.
1740 (This will notice if there are in fact no commands.) */
1741 (void) start_waiting_job (c);
1742
1743 if (job_slots == 1 || not_parallel < 0)
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)
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 if (max_load_average < 0)
1827 return 0;
1828
1829 /* Find the real system load average. */
1830 make_access ();
1831 if (getloadavg (&load, 1) != 1)
1832 {
1833 static int lossage = -1;
1834 /* Complain only once for the same error. */
1835 if (lossage == -1 || errno != lossage)
1836 {
1837 if (errno == 0)
1838 /* An errno value of zero means getloadavg is just unsupported. */
1839 error (NILF,
1840 _("cannot enforce load limits on this operating system"));
1841 else
1842 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1843 }
1844 lossage = errno;
1845 load = 0;
1846 }
1847 user_access ();
1848
1849 /* If we're in a new second zero the counter and correct the backlog
1850 value. Only keep the backlog for one extra second; after that it's 0. */
1851 now = time (NULL);
1852 if (last_now < now)
1853 {
1854 if (last_now == now - 1)
1855 last_sec = LOAD_WEIGHT_B * job_counter;
1856 else
1857 last_sec = 0.0;
1858
1859 job_counter = 0;
1860 last_now = now;
1861 }
1862
1863 /* Try to guess what the load would be right now. */
1864 guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
1865
1866 DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1867 guess, load, max_load_average));
1868
1869 return guess >= max_load_average;
1870#endif
1871}
1872
1873/* Start jobs that are waiting for the load to be lower. */
1874
1875void
1876start_waiting_jobs (void)
1877{
1878 struct child *job;
1879
1880 if (waiting_jobs == 0)
1881 return;
1882
1883 do
1884 {
1885 /* Check for recently deceased descendants. */
1886 reap_children (0, 0);
1887
1888 /* Take a job off the waiting list. */
1889 job = waiting_jobs;
1890 waiting_jobs = job->next;
1891
1892 /* Try to start that job. We break out of the loop as soon
1893 as start_waiting_job puts one back on the waiting list. */
1894 }
1895 while (start_waiting_job (job) && waiting_jobs != 0);
1896
1897 return;
1898}
1899
1900
1901#ifndef WINDOWS32
1902#ifdef VMS
1903#include <descrip.h>
1904#include <clidef.h>
1905
1906/* This is called as an AST when a child process dies (it won't get
1907 interrupted by anything except a higher level AST).
1908*/
1909int vmsHandleChildTerm(struct child *child)
1910{
1911 int status;
1912 register struct child *lastc, *c;
1913 int child_failed;
1914
1915 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1916
1917 lib$free_ef(&child->efn);
1918
1919 (void) sigblock (fatal_signal_mask);
1920
1921 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1922
1923 /* Search for a child matching the deceased one. */
1924 lastc = 0;
1925#if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1926 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1927#else
1928 c = child;
1929#endif
1930
1931 if (child_failed && !c->noerror && !ignore_errors_flag)
1932 {
1933 /* The commands failed. Write an error message,
1934 delete non-precious targets, and abort. */
1935 child_error (c->file->name, c->cstatus, 0, 0, 0);
1936 c->file->update_status = 1;
1937 delete_child_targets (c);
1938 }
1939 else
1940 {
1941 if (child_failed)
1942 {
1943 /* The commands failed, but we don't care. */
1944 child_error (c->file->name, c->cstatus, 0, 0, 1);
1945 child_failed = 0;
1946 }
1947
1948#if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1949 /* If there are more commands to run, try to start them. */
1950 start_job (c);
1951
1952 switch (c->file->command_state)
1953 {
1954 case cs_running:
1955 /* Successfully started. */
1956 break;
1957
1958 case cs_finished:
1959 if (c->file->update_status != 0) {
1960 /* We failed to start the commands. */
1961 delete_child_targets (c);
1962 }
1963 break;
1964
1965 default:
1966 error (NILF, _("internal error: `%s' command_state"),
1967 c->file->name);
1968 abort ();
1969 break;
1970 }
1971#endif /* RECURSIVEJOBS */
1972 }
1973
1974 /* Set the state flag to say the commands have finished. */
1975 c->file->command_state = cs_finished;
1976 notice_finished_file (c->file);
1977
1978#if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1979 /* Remove the child from the chain and free it. */
1980 if (lastc == 0)
1981 children = c->next;
1982 else
1983 lastc->next = c->next;
1984 free_child (c);
1985#endif /* RECURSIVEJOBS */
1986
1987 /* There is now another slot open. */
1988 if (job_slots_used > 0)
1989 --job_slots_used;
1990
1991 /* If the job failed, and the -k flag was not given, die. */
1992 if (child_failed && !keep_going_flag)
1993 die (EXIT_FAILURE);
1994
1995 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1996
1997 return 1;
1998}
1999
2000/* VMS:
2001 Spawn a process executing the command in ARGV and return its pid. */
2002
2003#define MAXCMDLEN 200
2004
2005/* local helpers to make ctrl+c and ctrl+y working, see below */
2006#include <iodef.h>
2007#include <libclidef.h>
2008#include <ssdef.h>
2009
2010static int ctrlMask= LIB$M_CLI_CTRLY;
2011static int oldCtrlMask;
2012static int setupYAstTried= 0;
2013static int pidToAbort= 0;
2014static int chan= 0;
2015
2016static void reEnableAst(void) {
2017 lib$enable_ctrl (&oldCtrlMask,0);
2018}
2019
2020static astHandler (void) {
2021 if (pidToAbort) {
2022 sys$forcex (&pidToAbort, 0, SS$_ABORT);
2023 pidToAbort= 0;
2024 }
2025 kill (getpid(),SIGQUIT);
2026}
2027
2028static void tryToSetupYAst(void) {
2029 $DESCRIPTOR(inputDsc,"SYS$COMMAND");
2030 int status;
2031 struct {
2032 short int status, count;
2033 int dvi;
2034 } iosb;
2035
2036 setupYAstTried++;
2037
2038 if (!chan) {
2039 status= sys$assign(&inputDsc,&chan,0,0);
2040 if (!(status&SS$_NORMAL)) {
2041 lib$signal(status);
2042 return;
2043 }
2044 }
2045 status= sys$qiow (0, chan, IO$_SETMODE|IO$M_CTRLYAST,&iosb,0,0,
2046 astHandler,0,0,0,0,0);
2047 if (status==SS$_ILLIOFUNC) {
2048 sys$dassgn(chan);
2049#ifdef CTRLY_ENABLED_ANYWAY
2050 fprintf (stderr,
2051 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
2052#else
2053 return;
2054#endif
2055 }
2056 if (status==SS$_NORMAL)
2057 status= iosb.status;
2058 if (!(status&SS$_NORMAL)) {
2059 lib$signal(status);
2060 return;
2061 }
2062
2063 /* called from AST handler ? */
2064 if (setupYAstTried>1)
2065 return;
2066 if (atexit(reEnableAst))
2067 fprintf (stderr,
2068 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
2069 status= lib$disable_ctrl (&ctrlMask, &oldCtrlMask);
2070 if (!(status&SS$_NORMAL)) {
2071 lib$signal(status);
2072 return;
2073 }
2074}
2075int
2076child_execute_job (char *argv, struct child *child)
2077{
2078 int i;
2079 static struct dsc$descriptor_s cmddsc;
2080 static struct dsc$descriptor_s pnamedsc;
2081 static struct dsc$descriptor_s ifiledsc;
2082 static struct dsc$descriptor_s ofiledsc;
2083 static struct dsc$descriptor_s efiledsc;
2084 int have_redirection = 0;
2085 int have_newline = 0;
2086
2087 int spflags = CLI$M_NOWAIT;
2088 int status;
2089 char *cmd = alloca (strlen (argv) + 512), *p, *q;
2090 char ifile[256], ofile[256], efile[256];
2091 char *comname = 0;
2092 char procname[100];
2093
2094 /* Parse IO redirection. */
2095
2096 ifile[0] = 0;
2097 ofile[0] = 0;
2098 efile[0] = 0;
2099
2100 DB (DB_JOBS, ("child_execute_job (%s)\n", argv));
2101
2102 while (isspace ((unsigned char)*argv))
2103 argv++;
2104
2105 if (*argv == 0)
2106 return 0;
2107
2108 sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
2109 pnamedsc.dsc$w_length = strlen(procname);
2110 pnamedsc.dsc$a_pointer = procname;
2111 pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
2112 pnamedsc.dsc$b_class = DSC$K_CLASS_S;
2113
2114 /* Handle comments and redirection. */
2115 for (p = argv, q = cmd; *p; p++, q++)
2116 {
2117 switch (*p)
2118 {
2119 case '#':
2120 *p-- = 0;
2121 *q-- = 0;
2122 break;
2123 case '\\':
2124 p++;
2125 if (*p == '\n')
2126 p++;
2127 if (isspace ((unsigned char)*p))
2128 {
2129 do { p++; } while (isspace ((unsigned char)*p));
2130 p--;
2131 }
2132 *q = *p;
2133 break;
2134 case '<':
2135 p = vms_redirect (&ifiledsc, ifile, p);
2136 *q = ' ';
2137 have_redirection = 1;
2138 break;
2139 case '>':
2140 have_redirection = 1;
2141 if (*(p-1) == '2')
2142 {
2143 q--;
2144 if (strncmp (p, ">&1", 3) == 0)
2145 {
2146 p += 3;
2147 strcpy (efile, "sys$output");
2148 efiledsc.dsc$w_length = strlen(efile);
2149 efiledsc.dsc$a_pointer = efile;
2150 efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
2151 efiledsc.dsc$b_class = DSC$K_CLASS_S;
2152 }
2153 else
2154 {
2155 p = vms_redirect (&efiledsc, efile, p);
2156 }
2157 }
2158 else
2159 {
2160 p = vms_redirect (&ofiledsc, ofile, p);
2161 }
2162 *q = ' ';
2163 break;
2164 case '\n':
2165 have_newline = 1;
2166 default:
2167 *q = *p;
2168 break;
2169 }
2170 }
2171 *q = *p;
2172
2173 if (strncmp (cmd, "builtin_", 8) == 0)
2174 {
2175 child->pid = 270163;
2176 child->efn = 0;
2177 child->cstatus = 1;
2178
2179 DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));
2180
2181 p = cmd + 8;
2182
2183 if ((*(p) == 'c')
2184 && (*(p+1) == 'd')
2185 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
2186 {
2187 p += 3;
2188 while ((*p == ' ') || (*p == '\t'))
2189 p++;
2190 DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
2191 if (chdir (p))
2192 return 0;
2193 else
2194 return 1;
2195 }
2196 else if ((*(p) == 'r')
2197 && (*(p+1) == 'm')
2198 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
2199 {
2200 int in_arg;
2201
2202 /* rm */
2203 p += 3;
2204 while ((*p == ' ') || (*p == '\t'))
2205 p++;
2206 in_arg = 1;
2207
2208 DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
2209 while (*p)
2210 {
2211 switch (*p)
2212 {
2213 case ' ':
2214 case '\t':
2215 if (in_arg)
2216 {
2217 *p++ = ';';
2218 in_arg = 0;
2219 }
2220 break;
2221 default:
2222 break;
2223 }
2224 p++;
2225 }
2226 }
2227 else
2228 {
2229 printf(_("Unknown builtin command '%s'\n"), cmd);
2230 fflush(stdout);
2231 return 0;
2232 }
2233 }
2234
2235 /* Create a *.com file if either the command is too long for
2236 lib$spawn, or the command contains a newline, or if redirection
2237 is desired. Forcing commands with newlines into DCLs allows to
2238 store search lists on user mode logicals. */
2239
2240 if (strlen (cmd) > MAXCMDLEN
2241 || (have_redirection != 0)
2242 || (have_newline != 0))
2243 {
2244 FILE *outfile;
2245 char c;
2246 char *sep;
2247 int alevel = 0; /* apostrophe level */
2248
2249 if (strlen (cmd) == 0)
2250 {
2251 printf (_("Error, empty command\n"));
2252 fflush (stdout);
2253 return 0;
2254 }
2255
2256 outfile = open_tmpfile (&comname, "sys$scratch:CMDXXXXXX.COM");
2257 if (outfile == 0)
2258 pfatal_with_name (_("fopen (temporary file)"));
2259
2260 if (ifile[0])
2261 {
2262 fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
2263 DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
2264 ifiledsc.dsc$w_length = 0;
2265 }
2266
2267 if (efile[0])
2268 {
2269 fprintf (outfile, "$ define sys$error %s\n", efile);
2270 DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
2271 efiledsc.dsc$w_length = 0;
2272 }
2273
2274 if (ofile[0])
2275 {
2276 fprintf (outfile, "$ define sys$output %s\n", ofile);
2277 DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
2278 ofiledsc.dsc$w_length = 0;
2279 }
2280
2281 p = sep = q = cmd;
2282 for (c = '\n'; c; c = *q++)
2283 {
2284 switch (c)
2285 {
2286 case '\n':
2287 /* At a newline, skip any whitespace around a leading $
2288 from the command and issue exactly one $ into the DCL. */
2289 while (isspace ((unsigned char)*p))
2290 p++;
2291 if (*p == '$')
2292 p++;
2293 while (isspace ((unsigned char)*p))
2294 p++;
2295 fwrite (p, 1, q - p, outfile);
2296 fputc ('$', outfile);
2297 fputc (' ', outfile);
2298 /* Reset variables. */
2299 p = sep = q;
2300 break;
2301
2302 /* Nice places for line breaks are after strings, after
2303 comma or space and before slash. */
2304 case '"':
2305 q = vms_handle_apos (q);
2306 sep = q;
2307 break;
2308 case ',':
2309 case ' ':
2310 sep = q;
2311 break;
2312 case '/':
2313 case '\0':
2314 sep = q - 1;
2315 break;
2316 default:
2317 break;
2318 }
2319 if (sep - p > 78)
2320 {
2321 /* Enough stuff for a line. */
2322 fwrite (p, 1, sep - p, outfile);
2323 p = sep;
2324 if (*sep)
2325 {
2326 /* The command continues. */
2327 fputc ('-', outfile);
2328 }
2329 fputc ('\n', outfile);
2330 }
2331 }
2332
2333 fwrite (p, 1, q - p, outfile);
2334 fputc ('\n', outfile);
2335
2336 fclose (outfile);
2337
2338 sprintf (cmd, "$ @%s", comname);
2339
2340 DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
2341 }
2342
2343 cmddsc.dsc$w_length = strlen(cmd);
2344 cmddsc.dsc$a_pointer = cmd;
2345 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
2346 cmddsc.dsc$b_class = DSC$K_CLASS_S;
2347
2348 child->efn = 0;
2349 while (child->efn < 32 || child->efn > 63)
2350 {
2351 status = lib$get_ef ((unsigned long *)&child->efn);
2352 if (!(status & 1))
2353 return 0;
2354 }
2355
2356 sys$clref (child->efn);
2357
2358 vms_jobsefnmask |= (1 << (child->efn - 32));
2359
2360/*
2361 LIB$SPAWN [command-string]
2362 [,input-file]
2363 [,output-file]
2364 [,flags]
2365 [,process-name]
2366 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2367 [,AST-address] [,varying-AST-argument]
2368 [,prompt-string] [,cli] [,table]
2369*/
2370
2371#ifndef DONTWAITFORCHILD
2372/*
2373 * Code to make ctrl+c and ctrl+y working.
2374 * The problem starts with the synchronous case where after lib$spawn is
2375 * called any input will go to the child. But with input re-directed,
2376 * both control characters won't make it to any of the programs, neither
2377 * the spawning nor to the spawned one. Hence the caller needs to spawn
2378 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2379 * has to follow to simulate the wanted synchronous behaviour.
2380 * The next problem is ctrl+y which isn't caught by the crtl and
2381 * therefore isn't converted to SIGQUIT (for a signal handler which is
2382 * already established). The only way to catch ctrl+y, is an AST
2383 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2384 * disabled, otherwise it will handle it. Not to mention the previous
2385 * ctrl+y handling of DCL needs to be re-established before make exits.
2386 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2387 * make it to the signal handler after the child "normally" terminates.
2388 * This isn't enough. It seems reasonable for simple command lines like
2389 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2390 * spawning make. Therefore we need to abort the process in the AST.
2391 *
2392 * Prior to the spawn it is checked if an AST is already set up for
2393 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2394 * this will work except if make is run in a batch environment, but there
2395 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2396 * is disabled and an exit handler is established to re-enable it.
2397 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2398 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2399 * the already established handler and will bring us back to common code.
2400 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2401 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2402 * which the crtl converts to SIGINT and which is caught by the common
2403 * signal handler. Because signals were blocked before entering this code
2404 * sys$waitfr will always complete and the SIGQUIT will be processed after
2405 * it (after termination of the current block, somewhere in common code).
2406 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2407 * current command completes. Anyway it's better than nothing :-)
2408 */
2409
2410 if (!setupYAstTried)
2411 tryToSetupYAst();
2412 status = lib$spawn (&cmddsc, /* cmd-string */
2413 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file */
2414 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
2415 &spflags, /* flags */
2416 &pnamedsc, /* proc name */
2417 &child->pid, &child->cstatus, &child->efn,
2418 0, 0,
2419 0, 0, 0);
2420 if (status & 1)
2421 {
2422 pidToAbort= child->pid;
2423 status= sys$waitfr (child->efn);
2424 pidToAbort= 0;
2425 vmsHandleChildTerm(child);
2426 }
2427#else
2428 status = lib$spawn (&cmddsc,
2429 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
2430 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
2431 &spflags,
2432 &pnamedsc,
2433 &child->pid, &child->cstatus, &child->efn,
2434 vmsHandleChildTerm, child,
2435 0, 0, 0);
2436#endif
2437
2438 if (!(status & 1))
2439 {
2440 printf (_("Error spawning, %d\n") ,status);
2441 fflush (stdout);
2442 switch (status)
2443 {
2444 case 0x1c:
2445 errno = EPROCLIM;
2446 break;
2447 default:
2448 errno = EFAIL;
2449 }
2450 }
2451
2452 if (comname && !ISDB (DB_JOBS))
2453 unlink (comname);
2454
2455 return (status & 1);
2456}
2457
2458#else /* !VMS */
2459
2460/* EMX: Start a child process. This function returns the new pid. */
2461# if defined __MSDOS__ || defined __EMX__
2462/* The child argument can be NULL (that's why we return the pid), if it is
2463 and the shell is a dllshell:// a child structure is created and inserted
2464 into the child list so reap_children can do its job.
2465
2466 BTW. the name of this function in this port is very misleading, spawn_job
2467 would perhaps be more appropriate. */
2468
2469int
2470child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp,
2471 struct child *child)
2472{
2473 int pid;
2474 /* stdin_fd == 0 means: nothing to do for stdin;
2475 stdout_fd == 1 means: nothing to do for stdout */
2476 int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
2477 int save_stdout = (stdout_fd != 1) ? dup (1): 1;
2478
2479 /* < 0 only if dup() failed */
2480 if (save_stdin < 0)
2481 fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
2482 if (save_stdout < 0)
2483 fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
2484
2485 /* Close unnecessary file handles for the child. */
2486 if (save_stdin != 0)
2487 CLOSE_ON_EXEC (save_stdin);
2488 if (save_stdout != 1)
2489 CLOSE_ON_EXEC (save_stdout);
2490
2491 /* Connect the pipes to the child process. */
2492 if (stdin_fd != 0)
2493 (void) dup2 (stdin_fd, 0);
2494 if (stdout_fd != 1)
2495 (void) dup2 (stdout_fd, 1);
2496
2497 /* stdin_fd and stdout_fd must be closed on exit because we are
2498 still in the parent process */
2499 if (stdin_fd != 0)
2500 CLOSE_ON_EXEC (stdin_fd);
2501 if (stdout_fd != 1)
2502 CLOSE_ON_EXEC (stdout_fd);
2503
2504#ifdef MAKE_DLLSHELL
2505 pid = spawn_command(argv, envp, child);
2506#else
2507 /* Run the command. */
2508 pid = exec_command (argv, envp);
2509#endif
2510
2511 /* Restore stdout/stdin of the parent process. */
2512 if (stdin_fd != 0 && dup2 (save_stdin, 0) != 0)
2513 fatal (NILF, _("restoring of stdin failed\n"));
2514 if (stdout_fd != 1 && dup2 (save_stdout, 1) != 1)
2515 fatal (NILF, _("restoring of stdout failed\n"));
2516
2517 /* Cleanup handles */
2518 if (stdin_fd != 0)
2519 close (save_stdin);
2520 if (stdout_fd != 1)
2521 close (save_stdout);
2522
2523 return pid;
2524}
2525
2526#elif !defined (_AMIGA) && !defined (__MSDOS__)
2527
2528/* UNIX:
2529 Replace the current process with one executing the command in ARGV.
2530 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2531 the environment of the new program. This function does not return. */
2532void
2533child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2534{
2535 if (stdin_fd != 0)
2536 (void) dup2 (stdin_fd, 0);
2537 if (stdout_fd != 1)
2538 (void) dup2 (stdout_fd, 1);
2539 if (stdin_fd != 0)
2540 (void) close (stdin_fd);
2541 if (stdout_fd != 1)
2542 (void) close (stdout_fd);
2543
2544 /* Run the command. */
2545 exec_command (argv, envp);
2546}
2547#endif /* !AMIGA && !__MSDOS__ */
2548#endif /* !VMS */
2549#endif /* !WINDOWS32 */
2550
2551
2552#ifdef MAKE_DLLSHELL
2553/* Globals for the currently loaded dllshell. */
2554char *dllshell_spec;
2555void *dllshell_dl;
2556void *dllshell_instance;
2557void *(*dllshell_init) PARAMS ((const char *spec));
2558pid_t (*dllshell_spawn) PARAMS ((void *instance, char **argv, char **envp, int *status, char *done));
2559pid_t (*dllshell_wait) PARAMS ((void *instance, int *status, int block));
2560
2561/* This is called when all pipes and such are configured for the
2562 child process. The child argument may be null, see child_execute_job. */
2563static int spawn_command (char **argv, char **envp, struct child *c)
2564{
2565 /* Now let's see if there is a DLLSHELL specifier in the
2566 first argument. */
2567 if (!strncmp(argv[0], "dllshell://", 11))
2568 {
2569 /* dllshell://<dllname>[!<realshell>[!whatever]] */
2570 char *name, *name_end;
2571 int insert_child = 0;
2572
2573 /* parse it */
2574 name = argv[0] + 11;
2575 name_end = strchr (name, '!');
2576 if (!name_end)
2577 name_end = strchr (name, '\0');
2578 if (name_end == name)
2579 fatal (NILF, _("%s : malformed specifier!\n"), argv[0]);
2580
2581 /* need loading? */
2582 if (!dllshell_spec || strcmp (argv[0], dllshell_spec))
2583 {
2584 if (dllshell_spec)
2585 fatal (NILF, _("cannot change the dllshell!!!\n"));
2586
2587 dllshell_spec = strdup (argv[0]);
2588 dllshell_spec[name_end - argv[0]] = '\0';
2589 dllshell_dl = dlopen (dllshell_spec + (name - argv[0]), RTLD_LOCAL);
2590 if (!dllshell_dl)
2591 fatal (NILF, _("%s : failed to load! dlerror: '%s'\n"), argv[0], dlerror());
2592 dllshell_spec[name_end - name] = '!';
2593
2594 /* get symbols */
2595 dllshell_init = dlsym (dllshell_dl, "dllshell_init");
2596 if (!dllshell_init)
2597 fatal (NILF, _("%s : failed to find symbols 'dllshell_init' dlerror: %s\n"), argv[0], dlerror());
2598 dllshell_spawn = dlsym (dllshell_dl, "dllshell_spawn");
2599 if (!dllshell_spawn)
2600 fatal (NILF, _("%s : failed to find symbols 'dllshell_spawn' dlerror: %s\n"), argv[0], dlerror());
2601 dllshell_wait = dlsym (dllshell_dl, "dllshell_wait");
2602 if (!dllshell_wait)
2603 fatal (NILF, _("%s : failed to find symbols 'dllshell_wait' dlerror: %s\n"), argv[0], dlerror());
2604
2605 /* init */
2606 dllshell_instance = dllshell_init(dllshell_spec);
2607 if (!dllshell_instance)
2608 fatal (NILF, _("%s : init failed!!!\n"), argv[0]);
2609 }
2610
2611 /* make child struct? */
2612 if (!c)
2613 {
2614 c = (struct child *) xmalloc (sizeof (struct child));
2615 bzero ((char *)c, sizeof (struct child));
2616 insert_child = 1;
2617 }
2618
2619 /* call it. return value is 0 on succes, -1 on failure. */
2620 c->pid = dllshell_spawn (dllshell_instance, argv, envp, &c->status, &c->dllshell_done);
2621 DB (DB_JOBS, (_("dllshell pid=%x\n"), c->pid));
2622
2623 if (insert_child && c->pid > 0)
2624 {
2625 c->next = children;
2626 DB (DB_JOBS, (_("Putting child 0x%08lx (-) PID %ld on the chain.\n"),
2627 (unsigned long int) c, (long) c->pid));
2628 children = c;
2629 /* One more job slot is in use. */
2630 ++job_slots_used;
2631 }
2632 }
2633 else
2634 {
2635 /* Run the command. */
2636#ifdef __EMX__
2637 c->pid =
2638 exec_command (argv, envp);
2639#else
2640# error MAKE_DLLSHELL is not ported to your platform yet.
2641#endif
2642 DB (DB_JOBS, (_("spawn pid=%x\n"), c->pid));
2643 }
2644
2645 return c->pid;
2646}
2647
2648/* Waits or pools for a job to finish.
2649 If the block argument the the function will not return
2650 till a job is completed (if there are any jobs).
2651 Returns pid of completed job.
2652 Returns 0 if no jobs are finished.
2653 Returns -1 if no jobs are running. */
2654pid_t wait_jobs (int *status, int block)
2655{
2656 pid_t pid;
2657 if (dllshell_wait)
2658 pid = dllshell_wait(dllshell_instance, status, block);
2659 else
2660 {
2661 if (block)
2662 pid = WAIT_NOHANG(status);
2663 else
2664 pid = wait(status);
2665 }
2666 return pid;
2667}
2668
2669#endif /* MAKE_DLLSHELL */
2670
2671
2672#ifndef _AMIGA
2673/* Replace the current process with one running the command in ARGV,
2674 with environment ENVP. This function does not return. */
2675
2676/* EMX: This function returns the pid of the child process. */
2677# ifdef __EMX__
2678int
2679# else
2680 void
2681# endif
2682exec_command (char **argv, char **envp)
2683{
2684#ifdef VMS
2685 /* to work around a problem with signals and execve: ignore them */
2686#ifdef SIGCHLD
2687 signal (SIGCHLD,SIG_IGN);
2688#endif
2689 /* Run the program. */
2690 execve (argv[0], argv, envp);
2691 perror_with_name ("execve: ", argv[0]);
2692 _exit (EXIT_FAILURE);
2693#else
2694#ifdef WINDOWS32
2695 HANDLE hPID;
2696 HANDLE hWaitPID;
2697 int err = 0;
2698 int exit_code = EXIT_FAILURE;
2699
2700 /* make sure CreateProcess() has Path it needs */
2701 sync_Path_environment();
2702
2703 /* launch command */
2704 hPID = process_easy(argv, envp);
2705
2706 /* make sure launch ok */
2707 if (hPID == INVALID_HANDLE_VALUE)
2708 {
2709 int i;
2710 fprintf(stderr,
2711 _("process_easy() failed failed to launch process (e=%d)\n"),
2712 process_last_err(hPID));
2713 for (i = 0; argv[i]; i++)
2714 fprintf(stderr, "%s ", argv[i]);
2715 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2716 exit(EXIT_FAILURE);
2717 }
2718
2719 /* wait and reap last child */
2720 while (hWaitPID = process_wait_for_any())
2721 {
2722 /* was an error found on this process? */
2723 err = process_last_err(hWaitPID);
2724
2725 /* get exit data */
2726 exit_code = process_exit_code(hWaitPID);
2727
2728 if (err)
2729 fprintf(stderr, "make (e=%d, rc=%d): %s",
2730 err, exit_code, map_windows32_error_to_string(err));
2731
2732 /* cleanup process */
2733 process_cleanup(hWaitPID);
2734
2735 /* expect to find only last pid, warn about other pids reaped */
2736 if (hWaitPID == hPID)
2737 break;
2738 else
2739 fprintf(stderr,
2740 _("make reaped child pid %d, still waiting for pid %d\n"),
2741 hWaitPID, hPID);
2742 }
2743
2744 /* return child's exit code as our exit code */
2745 exit(exit_code);
2746
2747#else /* !WINDOWS32 */
2748
2749# ifdef __EMX__
2750 int pid;
2751# endif
2752
2753 /* Be the user, permanently. */
2754 child_access ();
2755
2756# ifdef __EMX__
2757
2758 /* Run the program. */
2759 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2760
2761 if (pid >= 0)
2762 return pid;
2763
2764 /* the file might have a strange shell extension */
2765 if (errno == ENOENT)
2766 errno = ENOEXEC;
2767
2768# else
2769
2770 /* Run the program. */
2771 environ = envp;
2772 execvp (argv[0], argv);
2773
2774# endif /* !__EMX__ */
2775
2776 switch (errno)
2777 {
2778 case ENOENT:
2779 error (NILF, _("%s: Command not found"), argv[0]);
2780 break;
2781 case ENOEXEC:
2782 {
2783 /* The file is not executable. Try it as a shell script. */
2784 extern char *getenv ();
2785 char *shell;
2786 char **new_argv;
2787 int argc;
2788
2789# ifdef __EMX__
2790 /* Do not use $SHELL from the environment */
2791 struct variable *p = lookup_variable ("SHELL", 5);
2792 if (p)
2793 shell = p->value;
2794 else
2795 shell = 0;
2796# else
2797 shell = getenv ("SHELL");
2798# endif
2799 if (shell == 0)
2800 shell = default_shell;
2801
2802 argc = 1;
2803 while (argv[argc] != 0)
2804 ++argc;
2805
2806 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
2807 new_argv[0] = shell;
2808 new_argv[1] = argv[0];
2809 while (argc > 0)
2810 {
2811 new_argv[1 + argc] = argv[argc];
2812 --argc;
2813 }
2814
2815# ifdef __EMX__
2816 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2817 if (pid >= 0)
2818 break;
2819# else
2820 execvp (shell, new_argv);
2821# endif
2822 if (errno == ENOENT)
2823 error (NILF, _("%s: Shell program not found"), shell);
2824 else
2825 perror_with_name ("execvp: ", shell);
2826 break;
2827 }
2828
2829# ifdef __EMX__
2830 case EINVAL:
2831 /* this nasty error was driving me nuts :-( */
2832 error (NILF, _("spawnvpe: environment space might be exhausted"));
2833 /* FALLTHROUGH */
2834# endif
2835
2836 default:
2837 perror_with_name ("execvp: ", argv[0]);
2838 break;
2839 }
2840
2841# ifdef __EMX__
2842 return pid;
2843# else
2844 _exit (127);
2845# endif
2846#endif /* !WINDOWS32 */
2847#endif /* !VMS */
2848}
2849#else /* On Amiga */
2850void exec_command (char **argv)
2851{
2852 MyExecute (argv);
2853}
2854
2855void clean_tmp (void)
2856{
2857 DeleteFile (amiga_bname);
2858}
2859
2860#endif /* On Amiga */
2861
2862
2863#ifndef VMS
2864/* Figure out the argument list necessary to run LINE as a command. Try to
2865 avoid using a shell. This routine handles only ' quoting, and " quoting
2866 when no backslash, $ or ` characters are seen in the quotes. Starting
2867 quotes may be escaped with a backslash. If any of the characters in
2868 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2869 is the first word of a line, the shell is used.
2870
2871 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2872 If *RESTP is NULL, newlines will be ignored.
2873
2874 SHELL is the shell to use, or nil to use the default shell.
2875 IFS is the value of $IFS, or nil (meaning the default). */
2876
2877static char **
2878construct_command_argv_internal (char *line, char **restp, char *shell,
2879 char *ifs, char **batch_filename_ptr)
2880{
2881#ifdef __MSDOS__
2882 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2883 We call `system' for anything that requires ``slow'' processing,
2884 because DOS shells are too dumb. When $SHELL points to a real
2885 (unix-style) shell, `system' just calls it to do everything. When
2886 $SHELL points to a DOS shell, `system' does most of the work
2887 internally, calling the shell only for its internal commands.
2888 However, it looks on the $PATH first, so you can e.g. have an
2889 external command named `mkdir'.
2890
2891 Since we call `system', certain characters and commands below are
2892 actually not specific to COMMAND.COM, but to the DJGPP implementation
2893 of `system'. In particular:
2894
2895 The shell wildcard characters are in DOS_CHARS because they will
2896 not be expanded if we call the child via `spawnXX'.
2897
2898 The `;' is in DOS_CHARS, because our `system' knows how to run
2899 multiple commands on a single line.
2900
2901 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2902 won't have to tell one from another and have one more set of
2903 commands and special characters. */
2904 static char sh_chars_dos[] = "*?[];|<>%^&()";
2905 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2906 "copy", "ctty", "date", "del", "dir", "echo",
2907 "erase", "exit", "for", "goto", "if", "md",
2908 "mkdir", "path", "pause", "prompt", "rd",
2909 "rmdir", "rem", "ren", "rename", "set",
2910 "shift", "time", "type", "ver", "verify",
2911 "vol", ":", 0 };
2912
2913 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2914 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2915 "logout", "set", "umask", "wait", "while",
2916 "for", "case", "if", ":", ".", "break",
2917 "continue", "export", "read", "readonly",
2918 "shift", "times", "trap", "switch", "unset",
2919 0 };
2920
2921 char *sh_chars;
2922 char **sh_cmds;
2923#elif defined (__EMX__)
2924 static char sh_chars_dos[] = "*?[];|<>%^&()";
2925 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2926 "copy", "ctty", "date", "del", "dir", "echo",
2927 "erase", "exit", "for", "goto", "if", "md",
2928 "mkdir", "path", "pause", "prompt", "rd",
2929 "rmdir", "rem", "ren", "rename", "set",
2930 "shift", "time", "type", "ver", "verify",
2931 "vol", ":", 0 };
2932
2933 static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
2934 static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2935 "date", "del", "detach", "dir", "echo",
2936 "endlocal", "erase", "exit", "for", "goto", "if",
2937 "keys", "md", "mkdir", "move", "path", "pause",
2938 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2939 "set", "setlocal", "shift", "start", "time",
2940 "type", "ver", "verify", "vol", ":", 0 };
2941
2942 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~'";
2943 static char *sh_cmds_sh[] = { "echo", "cd", "eval", "exec", "exit", "login",
2944 "logout", "set", "umask", "wait", "while",
2945 "for", "case", "if", ":", ".", "break",
2946 "continue", "export", "read", "readonly",
2947 "shift", "times", "trap", "switch", "unset",
2948 0 };
2949 char *sh_chars;
2950 char **sh_cmds;
2951
2952#elif defined (_AMIGA)
2953 static char sh_chars[] = "#;\"|<>()?*$`";
2954 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2955 "rename", "set", "setenv", "date", "makedir",
2956 "skip", "else", "endif", "path", "prompt",
2957 "unset", "unsetenv", "version",
2958 0 };
2959#elif defined (WINDOWS32)
2960 static char sh_chars_dos[] = "\"|&<>";
2961 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2962 "copy", "ctty", "date", "del", "dir", "echo",
2963 "erase", "exit", "for", "goto", "if", "if", "md",
2964 "mkdir", "path", "pause", "prompt", "rd", "rem",
2965 "ren", "rename", "rmdir", "set", "shift", "time",
2966 "type", "ver", "verify", "vol", ":", 0 };
2967 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2968 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2969 "logout", "set", "umask", "wait", "while", "for",
2970 "case", "if", ":", ".", "break", "continue",
2971 "export", "read", "readonly", "shift", "times",
2972 "trap", "switch", "test",
2973#ifdef BATCH_MODE_ONLY_SHELL
2974 "echo",
2975#endif
2976 0 };
2977 char* sh_chars;
2978 char** sh_cmds;
2979#else /* must be UNIX-ish */
2980 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~!";
2981 static char *sh_cmds[] = { ".", ":", "break", "case", "cd", "continue",
2982 "eval", "exec", "exit", "export", "for", "if",
2983 "login", "logout", "read", "readonly", "set",
2984 "shift", "switch", "test", "times", "trap",
2985 "umask", "wait", "while", 0 };
2986#endif
2987 register int i;
2988 register char *p;
2989 register char *ap;
2990 char *end;
2991 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2992 char **new_argv = 0;
2993#ifdef WINDOWS32
2994 int slow_flag = 0;
2995
2996 if (no_default_sh_exe) {
2997 sh_cmds = sh_cmds_dos;
2998 sh_chars = sh_chars_dos;
2999 } else {
3000 sh_cmds = sh_cmds_sh;
3001 sh_chars = sh_chars_sh;
3002 }
3003#endif /* WINDOWS32 */
3004
3005 if (restp != NULL)
3006 *restp = NULL;
3007
3008 /* Make sure not to bother processing an empty line. */
3009 while (isblank ((unsigned char)*line))
3010 ++line;
3011 if (*line == '\0')
3012 return 0;
3013
3014 /* See if it is safe to parse commands internally. */
3015 if (shell == 0)
3016 shell = default_shell;
3017#ifdef WINDOWS32
3018 else if (strcmp (shell, default_shell))
3019 {
3020 char *s1 = _fullpath(NULL, shell, 0);
3021 char *s2 = _fullpath(NULL, default_shell, 0);
3022
3023 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
3024
3025 if (s1)
3026 free (s1);
3027 if (s2)
3028 free (s2);
3029 }
3030 if (slow_flag)
3031 goto slow;
3032#else /* not WINDOWS32 */
3033#if defined (__MSDOS__) || defined (__EMX__)
3034 else if (stricmp (shell, default_shell))
3035 {
3036 extern int _is_unixy_shell (const char *_path);
3037
3038 DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
3039 default_shell, shell));
3040 unixy_shell = _is_unixy_shell (shell);
3041 /* we must allocate a copy of shell: construct_command_argv() will free
3042 * shell after this function returns. */
3043 default_shell = xstrdup (shell);
3044 }
3045 if (unixy_shell)
3046 {
3047 sh_chars = sh_chars_sh;
3048 sh_cmds = sh_cmds_sh;
3049 }
3050 else
3051 {
3052 sh_chars = sh_chars_dos;
3053 sh_cmds = sh_cmds_dos;
3054# ifdef __EMX__
3055 if (_osmode == OS2_MODE)
3056 {
3057 sh_chars = sh_chars_os2;
3058 sh_cmds = sh_cmds_os2;
3059 }
3060# endif
3061 }
3062#else /* !__MSDOS__ */
3063 else if (strcmp (shell, default_shell))
3064 {
3065 /* Allow ash from kBuild. */
3066 const char *psz = strstr(shell, "/ash");
3067 if ( !psz
3068 || (!psz[4] && psz[4] == '.')
3069 || !strstr(shell, "/kBuild/bin/"))
3070 goto slow;
3071 }
3072#endif /* !__MSDOS__ && !__EMX__ */
3073#endif /* not WINDOWS32 */
3074
3075 if (ifs != 0)
3076 for (ap = ifs; *ap != '\0'; ++ap)
3077 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
3078 goto slow;
3079
3080 i = strlen (line) + 1;
3081
3082 /* More than 1 arg per character is impossible. */
3083 new_argv = (char **) xmalloc (i * sizeof (char *));
3084
3085 /* All the args can fit in a buffer as big as LINE is. */
3086 ap = new_argv[0] = (char *) xmalloc (i);
3087 end = ap + i;
3088
3089 /* I is how many complete arguments have been found. */
3090 i = 0;
3091 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
3092 for (p = line; *p != '\0'; ++p)
3093 {
3094 if (ap > end)
3095 abort ();
3096
3097 if (instring)
3098 {
3099 string_char:
3100 /* Inside a string, just copy any char except a closing quote
3101 or a backslash-newline combination. */
3102 if (*p == instring)
3103 {
3104 instring = 0;
3105 if (ap == new_argv[0] || *(ap-1) == '\0')
3106 last_argument_was_empty = 1;
3107 }
3108 else if (*p == '\\' && p[1] == '\n')
3109 goto swallow_escaped_newline;
3110 else if (*p == '\n' && restp != NULL)
3111 {
3112 /* End of the command line. */
3113 *restp = p;
3114 goto end_of_line;
3115 }
3116 /* Backslash, $, and ` are special inside double quotes.
3117 If we see any of those, punt.
3118 But on MSDOS, if we use COMMAND.COM, double and single
3119 quotes have the same effect. */
3120 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
3121 goto slow;
3122 else
3123 *ap++ = *p;
3124 }
3125 else if (strchr (sh_chars, *p) != 0)
3126 /* Not inside a string, but it's a special char. */
3127 goto slow;
3128#ifdef __MSDOS__
3129 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
3130 /* `...' is a wildcard in DJGPP. */
3131 goto slow;
3132#endif
3133 else
3134 /* Not a special char. */
3135 switch (*p)
3136 {
3137 case '=':
3138 /* Equals is a special character in leading words before the
3139 first word with no equals sign in it. This is not the case
3140 with sh -k, but we never get here when using nonstandard
3141 shell flags. */
3142 if (! seen_nonequals && unixy_shell)
3143 goto slow;
3144 word_has_equals = 1;
3145 *ap++ = '=';
3146 break;
3147
3148 case '\\':
3149 /* Backslash-newline combinations are eaten. */
3150 if (p[1] == '\n')
3151 {
3152 swallow_escaped_newline:
3153
3154 /* Eat the backslash, the newline, and following whitespace,
3155 replacing it all with a single space. */
3156 p += 2;
3157
3158 /* If there is a tab after a backslash-newline,
3159 remove it from the source line which will be echoed,
3160 since it was most likely used to line
3161 up the continued line with the previous one. */
3162 if (*p == '\t')
3163 /* Note these overlap and strcpy() is undefined for
3164 overlapping objects in ANSI C. The strlen() _IS_ right,
3165 since we need to copy the nul byte too. */
3166 bcopy (p + 1, p, strlen (p));
3167
3168 if (instring)
3169 goto string_char;
3170 else
3171 {
3172 if (ap != new_argv[i])
3173 /* Treat this as a space, ending the arg.
3174 But if it's at the beginning of the arg, it should
3175 just get eaten, rather than becoming an empty arg. */
3176 goto end_of_arg;
3177 else
3178 p = next_token (p) - 1;
3179 }
3180 }
3181 else if (p[1] != '\0')
3182 {
3183#ifdef HAVE_DOS_PATHS
3184 /* Only remove backslashes before characters special
3185 to Unixy shells. All other backslashes are copied
3186 verbatim, since they are probably DOS-style
3187 directory separators. This still leaves a small
3188 window for problems, but at least it should work
3189 for the vast majority of naive users. */
3190
3191#ifdef __MSDOS__
3192 /* A dot is only special as part of the "..."
3193 wildcard. */
3194 if (strneq (p + 1, ".\\.\\.", 5))
3195 {
3196 *ap++ = '.';
3197 *ap++ = '.';
3198 p += 4;
3199 }
3200 else
3201#endif
3202 if (p[1] != '\\' && p[1] != '\''
3203 && !isspace ((unsigned char)p[1])
3204 && (strchr (sh_chars_sh, p[1]) == 0))
3205 /* back up one notch, to copy the backslash */
3206 --p;
3207#endif /* HAVE_DOS_PATHS */
3208
3209 /* Copy and skip the following char. */
3210 *ap++ = *++p;
3211 }
3212 break;
3213
3214 case '\'':
3215 case '"':
3216 instring = *p;
3217 break;
3218
3219 case '\n':
3220 if (restp != NULL)
3221 {
3222 /* End of the command line. */
3223 *restp = p;
3224 goto end_of_line;
3225 }
3226 else
3227 /* Newlines are not special. */
3228 *ap++ = '\n';
3229 break;
3230
3231 case ' ':
3232 case '\t':
3233 end_of_arg:
3234 /* We have the end of an argument.
3235 Terminate the text of the argument. */
3236 *ap++ = '\0';
3237 new_argv[++i] = ap;
3238 last_argument_was_empty = 0;
3239
3240 /* Update SEEN_NONEQUALS, which tells us if every word
3241 heretofore has contained an `='. */
3242 seen_nonequals |= ! word_has_equals;
3243 if (word_has_equals && ! seen_nonequals)
3244 /* An `=' in a word before the first
3245 word without one is magical. */
3246 goto slow;
3247 word_has_equals = 0; /* Prepare for the next word. */
3248
3249 /* If this argument is the command name,
3250 see if it is a built-in shell command.
3251 If so, have the shell handle it. */
3252 if (i == 1)
3253 {
3254 register int j;
3255 for (j = 0; sh_cmds[j] != 0; ++j)
3256 if (streq (sh_cmds[j], new_argv[0]))
3257 goto slow;
3258 }
3259
3260 /* Ignore multiple whitespace chars. */
3261 p = next_token (p);
3262 /* Next iteration should examine the first nonwhite char. */
3263 --p;
3264 break;
3265
3266 default:
3267 *ap++ = *p;
3268 break;
3269 }
3270 }
3271 end_of_line:
3272
3273 if (instring)
3274 /* Let the shell deal with an unterminated quote. */
3275 goto slow;
3276
3277 /* Terminate the last argument and the argument list. */
3278
3279 *ap = '\0';
3280 if (new_argv[i][0] != '\0' || last_argument_was_empty)
3281 ++i;
3282 new_argv[i] = 0;
3283
3284 if (i == 1)
3285 {
3286 register int j;
3287 for (j = 0; sh_cmds[j] != 0; ++j)
3288 if (streq (sh_cmds[j], new_argv[0]))
3289 goto slow;
3290 }
3291
3292 if (new_argv[0] == 0)
3293 /* Line was empty. */
3294 return 0;
3295 else
3296 return new_argv;
3297
3298 slow:;
3299 /* We must use the shell. */
3300
3301 if (new_argv != 0)
3302 {
3303 /* Free the old argument list we were working on. */
3304 free (new_argv[0]);
3305 free ((void *)new_argv);
3306 }
3307
3308#ifdef __MSDOS__
3309 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
3310#endif
3311
3312#ifdef _AMIGA
3313 {
3314 char *ptr;
3315 char *buffer;
3316 char *dptr;
3317
3318 buffer = (char *)xmalloc (strlen (line)+1);
3319
3320 ptr = line;
3321 for (dptr=buffer; *ptr; )
3322 {
3323 if (*ptr == '\\' && ptr[1] == '\n')
3324 ptr += 2;
3325 else if (*ptr == '@') /* Kludge: multiline commands */
3326 {
3327 ptr += 2;
3328 *dptr++ = '\n';
3329 }
3330 else
3331 *dptr++ = *ptr++;
3332 }
3333 *dptr = 0;
3334
3335 new_argv = (char **) xmalloc (2 * sizeof (char *));
3336 new_argv[0] = buffer;
3337 new_argv[1] = 0;
3338 }
3339#else /* Not Amiga */
3340#ifdef WINDOWS32
3341 /*
3342 * Not eating this whitespace caused things like
3343 *
3344 * sh -c "\n"
3345 *
3346 * which gave the shell fits. I think we have to eat
3347 * whitespace here, but this code should be considered
3348 * suspicious if things start failing....
3349 */
3350
3351 /* Make sure not to bother processing an empty line. */
3352 while (isspace ((unsigned char)*line))
3353 ++line;
3354 if (*line == '\0')
3355 return 0;
3356#endif /* WINDOWS32 */
3357 {
3358 /* SHELL may be a multi-word command. Construct a command line
3359 "SHELL -c LINE", with all special chars in LINE escaped.
3360 Then recurse, expanding this command line to get the final
3361 argument list. */
3362
3363 unsigned int shell_len = strlen (shell);
3364#ifndef VMS
3365 static char minus_c[] = " -c ";
3366#else
3367 static char minus_c[] = "";
3368#endif
3369 unsigned int line_len = strlen (line);
3370
3371 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
3372 + (line_len * 2) + 1);
3373 char *command_ptr = NULL; /* used for batch_mode_shell mode */
3374
3375# ifdef __EMX__ /* is this necessary? */
3376 if (!unixy_shell)
3377 minus_c[1] = '/'; /* " /c " */
3378# endif
3379
3380 ap = new_line;
3381 bcopy (shell, ap, shell_len);
3382 ap += shell_len;
3383 bcopy (minus_c, ap, sizeof (minus_c) - 1);
3384 ap += sizeof (minus_c) - 1;
3385 command_ptr = ap;
3386 for (p = line; *p != '\0'; ++p)
3387 {
3388 if (restp != NULL && *p == '\n')
3389 {
3390 *restp = p;
3391 break;
3392 }
3393 else if (*p == '\\' && p[1] == '\n')
3394 {
3395 /* Eat the backslash, the newline, and following whitespace,
3396 replacing it all with a single space (which is escaped
3397 from the shell). */
3398 p += 2;
3399
3400 /* If there is a tab after a backslash-newline,
3401 remove it from the source line which will be echoed,
3402 since it was most likely used to line
3403 up the continued line with the previous one. */
3404 if (*p == '\t')
3405 bcopy (p + 1, p, strlen (p));
3406
3407 p = next_token (p);
3408 --p;
3409 if (unixy_shell && !batch_mode_shell)
3410 *ap++ = '\\';
3411 *ap++ = ' ';
3412 continue;
3413 }
3414
3415 /* DOS shells don't know about backslash-escaping. */
3416 if (unixy_shell && !batch_mode_shell &&
3417 (*p == '\\' || *p == '\'' || *p == '"'
3418 || isspace ((unsigned char)*p)
3419 || strchr (sh_chars, *p) != 0))
3420 *ap++ = '\\';
3421#ifdef __MSDOS__
3422 else if (unixy_shell && strneq (p, "...", 3))
3423 {
3424 /* The case of `...' wildcard again. */
3425 strcpy (ap, "\\.\\.\\");
3426 ap += 5;
3427 p += 2;
3428 }
3429#endif
3430 *ap++ = *p;
3431 }
3432 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
3433 /* Line was empty. */
3434 return 0;
3435 *ap = '\0';
3436
3437#ifdef WINDOWS32
3438 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3439 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3440 cases, run commands via a script file. */
3441 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
3442 FILE* batch = NULL;
3443 int id = GetCurrentProcessId();
3444 PATH_VAR(fbuf);
3445 char* fname = NULL;
3446
3447 /* create a file name */
3448 sprintf(fbuf, "make%d", id);
3449 fname = tempnam(".", fbuf);
3450
3451 /* create batch file name */
3452 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
3453 strcpy(*batch_filename_ptr, fname);
3454
3455 /* make sure path name is in DOS backslash format */
3456 if (!unixy_shell) {
3457 fname = *batch_filename_ptr;
3458 for (i = 0; fname[i] != '\0'; ++i)
3459 if (fname[i] == '/')
3460 fname[i] = '\\';
3461 strcat(*batch_filename_ptr, ".bat");
3462 } else {
3463 strcat(*batch_filename_ptr, ".sh");
3464 }
3465
3466 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3467 *batch_filename_ptr));
3468
3469 /* create batch file to execute command */
3470 batch = fopen (*batch_filename_ptr, "w");
3471 if (!unixy_shell)
3472 fputs ("@echo off\n", batch);
3473 fputs (command_ptr, batch);
3474 fputc ('\n', batch);
3475 fclose (batch);
3476
3477 /* create argv */
3478 new_argv = (char **) xmalloc(3 * sizeof (char *));
3479 if (unixy_shell) {
3480 new_argv[0] = xstrdup (shell);
3481 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
3482 } else {
3483 new_argv[0] = xstrdup (*batch_filename_ptr);
3484 new_argv[1] = NULL;
3485 }
3486 new_argv[2] = NULL;
3487 } else
3488#endif /* WINDOWS32 */
3489 if (unixy_shell)
3490 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
3491 (char *) 0, (char *) 0,
3492 (char **) 0);
3493# ifdef __EMX__
3494 else if (!unixy_shell)
3495 {
3496 /* new_line is local, must not be freed therefore */
3497 char *p, *q;
3498 int quote;
3499 size_t index;
3500 size_t len;
3501
3502 /* handle quotes
3503 We have to remove all double quotes and to split the line
3504 into distinct arguments because of the strange handling
3505 of builtin commands by cmd: 'echo "bla"' prints "bla"
3506 (with quotes) while 'c:\bin\echo.exe "bla"' prints bla
3507 (without quotes). Some programs like autoconf rely
3508 on the second behaviour. */
3509
3510 len = strlen (new_line) + 1;
3511
3512 /* More than 1 arg per character is impossible. */
3513 new_argv = (char **) xmalloc (len * sizeof (char *));
3514
3515 /* All the args can fit in a buffer as big as new_line is. */
3516 new_argv[0] = (char *) xmalloc (len);
3517
3518 index = 0;
3519 quote = 0;
3520 q = new_line;
3521 p = new_argv[index];
3522 while(*q != '\0')
3523 {
3524 /* searching for closing quote */
3525 if (quote)
3526 {
3527 if (*q == quote)
3528 {
3529 /* remove the quote */
3530 q++;
3531 quote = 0;
3532 }
3533 else /* normal character: copy it */
3534 *p++ = *q++;
3535 }
3536
3537 /* searching for opening quote */
3538 else if (*q == '\"'
3539# ifndef NO_CMD_DEFAULT
3540 || *q == '\''
3541# endif
3542 )
3543 {
3544 /* remove opening quote */
3545 quote = *q;
3546 q++;
3547 }
3548
3549 /* spaces outside of a quoted string: remove them
3550 and start a new argument */
3551 else if (*q == ' ' || *q == '\t')
3552 {
3553 *p++ = '\0'; /* trailing '\0' for last argument */
3554
3555 /* remove all successive spaces */
3556 do
3557 {
3558 q++;
3559 }
3560 while(*q == ' ' || *q == '\t');
3561
3562 /* start new argument */
3563 index++;
3564 new_argv[index] = p;
3565 }
3566
3567 /* normal character (no space) outside a quoted string*/
3568 else
3569 *p++ = *q++;
3570 } /* end while() */
3571
3572 *p = '\0'; /* trailing '\0' for the last argument */
3573 new_argv[index + 1] = NULL;
3574
3575# ifndef NO_CMD_DEFAULT
3576 /* special case: echo x="y"
3577 (e.g. autoconf uses this to determine whether make works)
3578 this is pure idioty but cmd works this way:
3579 if 'echo' and 'x="y"' are two different arguments cmd
3580 will print '"x="y""' but if they are only one argument
3581 cmd will print 'bla="blurb"' as it should be
3582 note: if we do not allow cmd to be the default shell
3583 we do not need this kind of voodoo */
3584 if (index == 3 && strcasecmp(new_argv[2], "echo") == 0)
3585 {
3586 new_argv[2][4] = ' ';
3587 new_argv[3] = NULL;
3588 }
3589# endif
3590 }
3591#elif defined(__MSDOS__)
3592 else
3593 {
3594 /* With MSDOS shells, we must construct the command line here
3595 instead of recursively calling ourselves, because we
3596 cannot backslash-escape the special characters (see above). */
3597 new_argv = (char **) xmalloc (sizeof (char *));
3598 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
3599 new_argv[0] = xmalloc (line_len + 1);
3600 strncpy (new_argv[0],
3601 new_line + shell_len + sizeof (minus_c) - 1, line_len);
3602 new_argv[0][line_len] = '\0';
3603 }
3604#else
3605 else
3606 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3607 __FILE__, __LINE__);
3608#endif
3609 }
3610#endif /* ! AMIGA */
3611
3612 return new_argv;
3613}
3614#endif /* !VMS */
3615
3616/* Figure out the argument list necessary to run LINE as a command. Try to
3617 avoid using a shell. This routine handles only ' quoting, and " quoting
3618 when no backslash, $ or ` characters are seen in the quotes. Starting
3619 quotes may be escaped with a backslash. If any of the characters in
3620 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3621 is the first word of a line, the shell is used.
3622
3623 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3624 If *RESTP is NULL, newlines will be ignored.
3625
3626 FILE is the target whose commands these are. It is used for
3627 variable expansion for $(SHELL) and $(IFS). */
3628
3629char **
3630construct_command_argv (char *line, char **restp, struct file *file,
3631 char **batch_filename_ptr)
3632{
3633 char *shell, *ifs;
3634 char **argv;
3635
3636#ifdef VMS
3637 char *cptr;
3638 int argc;
3639
3640 argc = 0;
3641 cptr = line;
3642 for (;;)
3643 {
3644 while ((*cptr != 0)
3645 && (isspace ((unsigned char)*cptr)))
3646 cptr++;
3647 if (*cptr == 0)
3648 break;
3649 while ((*cptr != 0)
3650 && (!isspace((unsigned char)*cptr)))
3651 cptr++;
3652 argc++;
3653 }
3654
3655 argv = (char **)malloc (argc * sizeof (char *));
3656 if (argv == 0)
3657 abort ();
3658
3659 cptr = line;
3660 argc = 0;
3661 for (;;)
3662 {
3663 while ((*cptr != 0)
3664 && (isspace ((unsigned char)*cptr)))
3665 cptr++;
3666 if (*cptr == 0)
3667 break;
3668 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3669 argv[argc++] = cptr;
3670 while ((*cptr != 0)
3671 && (!isspace((unsigned char)*cptr)))
3672 cptr++;
3673 if (*cptr != 0)
3674 *cptr++ = 0;
3675 }
3676#else
3677 {
3678 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3679 int save = warn_undefined_variables_flag;
3680 warn_undefined_variables_flag = 0;
3681
3682 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3683#ifdef WINDOWS32
3684 /*
3685 * Convert to forward slashes so that construct_command_argv_internal()
3686 * is not confused.
3687 */
3688 if (shell) {
3689 char *p = w32ify (shell, 0);
3690 strcpy (shell, p);
3691 }
3692#endif
3693#ifdef __EMX__
3694 {
3695 static const char *unixroot = NULL;
3696 static const char *last_shell = "";
3697 static int init = 0;
3698 if (init == 0)
3699 {
3700 unixroot = getenv ("UNIXROOT");
3701 /* unixroot must be NULL or not empty */
3702 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3703 init = 1;
3704 }
3705
3706 /* if we have an unixroot drive and if shell is not default_shell
3707 (which means it's either cmd.exe or the test has already been
3708 performed) and if shell is an absolute path without drive letter,
3709 try whether it exists e.g.: if "/bin/sh" does not exist use
3710 "$UNIXROOT/bin/sh" instead. */
3711 if (unixroot && shell && strcmp (shell, last_shell) != 0
3712 && (shell[0] == '/' || shell[0] == '\\'))
3713 {
3714 /* trying a new shell, check whether it exists */
3715 size_t size = strlen (shell);
3716 char *buf = xmalloc (size + 7);
3717 memcpy (buf, shell, size);
3718 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3719 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3720 {
3721 /* try the same for the unixroot drive */
3722 memmove (buf + 2, buf, size + 5);
3723 buf[0] = unixroot[0];
3724 buf[1] = unixroot[1];
3725 if (access (buf, F_OK) == 0)
3726 /* we have found a shell! */
3727 /* free(shell); */
3728 shell = buf;
3729 else
3730 free (buf);
3731 }
3732 else
3733 free (buf);
3734 }
3735 }
3736#endif /* __EMX__ */
3737
3738 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3739
3740 warn_undefined_variables_flag = save;
3741 }
3742
3743 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
3744
3745 free (shell);
3746 free (ifs);
3747#endif /* !VMS */
3748 return argv;
3749}
3750
3751
3752#if !defined(HAVE_DUP2) && !defined(_AMIGA)
3753int
3754dup2 (int old, int new)
3755{
3756 int fd;
3757
3758 (void) close (new);
3759 fd = dup (old);
3760 if (fd != new)
3761 {
3762 (void) close (fd);
3763 errno = EMFILE;
3764 return -1;
3765 }
3766
3767 return fd;
3768}
3769#endif /* !HAPE_DUP2 && !_AMIGA */
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