VirtualBox

source: kBuild/vendor/gnumake/3.81-beta1/job.c@ 1158

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

GNU Make 3.81beta1.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette