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

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

kMk builtin command basics. KMK_VERSION variable.

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