VirtualBox

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

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

More proper .NOTPARALLEL.

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

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