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

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

2nd try on .NOTPARALLEL.

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