VirtualBox

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

Last change on this file since 53 was 53, checked in by bird, 21 years ago

Initial revision

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