source: trunk/src/gmake/job.c@ 57

Last change on this file since 57 was 57, checked in by bird, 22 years ago

Config & adjustments for OS/2 LIBC. dllshell.

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