* Various fixes for problems in the 3.79.0.1 pretest.
[make.git] / job.c
blob1c11a38a0071189b360f046ee39b1dc13a53f62f
1 /* Job execution and handling for GNU Make.
2 Copyright (C) 1988,89,90,91,92,93,94,95,96,97,99 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 GNU Make is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNU Make; see the file COPYING. If not, write to
17 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 #include "make.h"
22 #include <assert.h>
24 #include "job.h"
25 #include "debug.h"
26 #include "filedef.h"
27 #include "commands.h"
28 #include "variable.h"
29 #include "debug.h"
31 #include <string.h>
33 /* Default shell to use. */
34 #ifdef WINDOWS32
35 char *default_shell = "sh.exe";
36 int no_default_sh_exe = 1;
37 int batch_mode_shell = 1;
38 #else /* WINDOWS32 */
39 # ifdef _AMIGA
40 char default_shell[] = "";
41 extern int MyExecute (char **);
42 # else /* _AMIGA */
43 # ifdef __MSDOS__
44 /* The default shell is a pointer so we can change it if Makefile
45 says so. It is without an explicit path so we get a chance
46 to search the $PATH for it (since MSDOS doesn't have standard
47 directories we could trust). */
48 char *default_shell = "command.com";
49 # else /* __MSDOS__ */
50 # ifdef VMS
51 # include <descrip.h>
52 char default_shell[] = "";
53 # else
54 char default_shell[] = "/bin/sh";
55 # endif /* VMS */
56 # endif /* __MSDOS__ */
57 int batch_mode_shell = 0;
58 # endif /* _AMIGA */
59 #endif /* WINDOWS32 */
61 #ifdef __MSDOS__
62 # include <process.h>
63 static int execute_by_shell;
64 static int dos_pid = 123;
65 int dos_status;
66 int dos_command_running;
67 #endif /* __MSDOS__ */
69 #ifdef _AMIGA
70 # include <proto/dos.h>
71 static int amiga_pid = 123;
72 static int amiga_status;
73 static char amiga_bname[32];
74 static int amiga_batch_file;
75 #endif /* Amiga. */
77 #ifdef VMS
78 # ifndef __GNUC__
79 # include <processes.h>
80 # endif
81 # include <starlet.h>
82 # include <lib$routines.h>
83 #endif
85 #ifdef WINDOWS32
86 # include <windows.h>
87 # include <io.h>
88 # include <process.h>
89 # include "sub_proc.h"
90 # include "w32err.h"
91 # include "pathstuff.h"
92 #endif /* WINDOWS32 */
94 #ifdef HAVE_FCNTL_H
95 # include <fcntl.h>
96 #else
97 # include <sys/file.h>
98 #endif
100 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
101 # include <sys/wait.h>
102 #endif
104 #ifdef HAVE_WAITPID
105 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
106 #else /* Don't have waitpid. */
107 # ifdef HAVE_WAIT3
108 # ifndef wait3
109 extern int wait3 ();
110 # endif
111 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
112 # endif /* Have wait3. */
113 #endif /* Have waitpid. */
115 #if !defined (wait) && !defined (POSIX)
116 extern int wait ();
117 #endif
119 #ifndef HAVE_UNION_WAIT
121 # define WAIT_T int
123 # ifndef WTERMSIG
124 # define WTERMSIG(x) ((x) & 0x7f)
125 # endif
126 # ifndef WCOREDUMP
127 # define WCOREDUMP(x) ((x) & 0x80)
128 # endif
129 # ifndef WEXITSTATUS
130 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
131 # endif
132 # ifndef WIFSIGNALED
133 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
134 # endif
135 # ifndef WIFEXITED
136 # define WIFEXITED(x) (WTERMSIG (x) == 0)
137 # endif
139 #else /* Have `union wait'. */
141 # define WAIT_T union wait
142 # ifndef WTERMSIG
143 # define WTERMSIG(x) ((x).w_termsig)
144 # endif
145 # ifndef WCOREDUMP
146 # define WCOREDUMP(x) ((x).w_coredump)
147 # endif
148 # ifndef WEXITSTATUS
149 # define WEXITSTATUS(x) ((x).w_retcode)
150 # endif
151 # ifndef WIFSIGNALED
152 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
153 # endif
154 # ifndef WIFEXITED
155 # define WIFEXITED(x) (WTERMSIG(x) == 0)
156 # endif
158 #endif /* Don't have `union wait'. */
160 /* How to set close-on-exec for a file descriptor. */
162 #if !defined F_SETFD
163 # define CLOSE_ON_EXEC(_d)
164 #else
165 # ifndef FD_CLOEXEC
166 # define FD_CLOEXEC 1
167 # endif
168 # define CLOSE_ON_EXEC(_d) (void) fcntl ((_d), F_SETFD, FD_CLOEXEC)
169 #endif
171 #ifdef VMS
172 static int vms_jobsefnmask = 0;
173 #endif /* !VMS */
175 #ifndef HAVE_UNISTD_H
176 extern int dup2 ();
177 extern int execve ();
178 extern void _exit ();
179 # ifndef VMS
180 extern int geteuid ();
181 extern int getegid ();
182 extern int setgid ();
183 extern int getgid ();
184 # endif
185 #endif
187 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
189 extern int getloadavg PARAMS ((double loadavg[], int nelem));
190 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
191 int *is_remote, int *id_ptr, int *used_stdin));
192 extern int start_remote_job_p PARAMS ((int));
193 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
194 int *coredump_ptr, int block));
196 RETSIGTYPE child_handler PARAMS ((int));
197 static void free_child PARAMS ((struct child *));
198 static void start_job_command PARAMS ((struct child *child));
199 static int load_too_high PARAMS ((void));
200 static int job_next_command PARAMS ((struct child *));
201 static int start_waiting_job PARAMS ((struct child *));
202 #ifdef VMS
203 static void vmsWaitForChildren PARAMS ((int *));
204 #endif
206 /* Chain of all live (or recently deceased) children. */
208 struct child *children = 0;
210 /* Number of children currently running. */
212 unsigned int job_slots_used = 0;
214 /* Nonzero if the `good' standard input is in use. */
216 static int good_stdin_used = 0;
218 /* Chain of children waiting to run until the load average goes down. */
220 static struct child *waiting_jobs = 0;
222 /* Non-zero if we use a *real* shell (always so on Unix). */
224 int unixy_shell = 1;
227 #ifdef WINDOWS32
229 * The macro which references this function is defined in make.h.
231 int w32_kill(int pid, int sig)
233 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
235 #endif /* WINDOWS32 */
237 /* Write an error message describing the exit status given in
238 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
239 Append "(ignored)" if IGNORED is nonzero. */
241 static void
242 child_error (target_name, exit_code, exit_sig, coredump, ignored)
243 char *target_name;
244 int exit_code, exit_sig, coredump;
245 int ignored;
247 if (ignored && silent_flag)
248 return;
250 #ifdef VMS
251 if (!(exit_code & 1))
252 error (NILF,
253 (ignored ? _("*** [%s] Error 0x%x (ignored)")
254 : _("*** [%s] Error 0x%x")),
255 target_name, exit_code);
256 #else
257 if (exit_sig == 0)
258 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
259 _("*** [%s] Error %d"),
260 target_name, exit_code);
261 else
262 error (NILF, "*** [%s] %s%s",
263 target_name, strsignal (exit_sig),
264 coredump ? _(" (core dumped)") : "");
265 #endif /* VMS */
268 #ifdef VMS
269 /* Wait for nchildren children to terminate */
270 static void
271 vmsWaitForChildren(int *status)
273 while (1)
275 if (!vms_jobsefnmask)
277 *status = 0;
278 return;
281 *status = sys$wflor (32, vms_jobsefnmask);
283 return;
286 /* Set up IO redirection. */
288 char *
289 vms_redirect (desc, fname, ibuf)
290 struct dsc$descriptor_s *desc;
291 char *fname;
292 char *ibuf;
294 char *fptr;
295 extern char *vmsify ();
297 ibuf++;
298 while (isspace ((unsigned char)*ibuf))
299 ibuf++;
300 fptr = ibuf;
301 while (*ibuf && !isspace ((unsigned char)*ibuf))
302 ibuf++;
303 *ibuf = 0;
304 if (strcmp (fptr, "/dev/null") != 0)
306 strcpy (fname, vmsify (fptr, 0));
307 if (strchr (fname, '.') == 0)
308 strcat (fname, ".");
310 desc->dsc$w_length = strlen(fname);
311 desc->dsc$a_pointer = fname;
312 desc->dsc$b_dtype = DSC$K_DTYPE_T;
313 desc->dsc$b_class = DSC$K_CLASS_S;
315 if (*fname == 0)
316 printf (_("Warning: Empty redirection\n"));
317 return ibuf;
322 found apostrophe at (p-1)
324 inc p until after closing apostrophe. */
326 static char *
327 handle_apos (char *p)
329 int alast;
330 int inside;
332 #define SEPCHARS ",/()= "
334 inside = 0;
336 while (*p != 0)
338 if (*p == '"')
340 if (inside)
342 while ((alast > 0)
343 && (*p == '"'))
345 p++;
346 alast--;
348 if (alast == 0)
349 inside = 0;
350 else
352 fprintf (stderr, _("Syntax error, still inside '\"'\n"));
353 exit (3);
356 else
358 p++;
359 if (strchr (SEPCHARS, *p))
360 break;
361 inside = 1;
362 alast = 1;
363 while (*p == '"')
365 alast++;
366 p++;
370 else
371 p++;
374 return p;
377 #endif
380 /* Handle a dead child. This handler may or may not ever be installed.
382 If we're using the jobserver feature, we need it. First, installing it
383 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
384 read FD to ensure we don't enter another blocking read without reaping all
385 the dead children. In this case we don't need the dead_children count.
387 If we don't have either waitpid or wait3, then make is unreliable, but we
388 use the dead_children count to reap children as best we can. */
390 static unsigned int dead_children = 0;
392 RETSIGTYPE
393 child_handler (sig)
394 int sig;
396 ++dead_children;
398 if (job_rfd >= 0)
400 close (job_rfd);
401 job_rfd = -1;
404 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
408 extern int shell_function_pid, shell_function_completed;
410 /* Reap all dead children, storing the returned status and the new command
411 state (`cs_finished') in the `file' member of the `struct child' for the
412 dead child, and removing the child from the chain. In addition, if BLOCK
413 nonzero, we block in this function until we've reaped at least one
414 complete child, waiting for it to die if necessary. If ERR is nonzero,
415 print an error message first. */
417 void
418 reap_children (block, err)
419 int block, err;
421 WAIT_T status;
422 /* Initially, assume we have some. */
423 int reap_more = 1;
425 #ifdef WAIT_NOHANG
426 # define REAP_MORE reap_more
427 #else
428 # define REAP_MORE dead_children
429 #endif
431 /* As long as:
433 We have at least one child outstanding OR a shell function in progress,
435 We're blocking for a complete child OR there are more children to reap
437 we'll keep reaping children. */
439 while ((children != 0 || shell_function_pid != 0) &&
440 (block || REAP_MORE))
442 int remote = 0;
443 register int pid;
444 int exit_code, exit_sig, coredump;
445 register struct child *lastc, *c;
446 int child_failed;
447 int any_remote, any_local;
449 if (err && block)
451 /* We might block for a while, so let the user know why. */
452 fflush (stdout);
453 error (NILF, _("*** Waiting for unfinished jobs...."));
456 /* We have one less dead child to reap. As noted in
457 child_handler() above, this count is completely unimportant for
458 all modern, POSIX-y systems that support wait3() or waitpid().
459 The rest of this comment below applies only to early, broken
460 pre-POSIX systems. We keep the count only because... it's there...
462 The test and decrement are not atomic; if it is compiled into:
463 register = dead_children - 1;
464 dead_children = register;
465 a SIGCHLD could come between the two instructions.
466 child_handler increments dead_children.
467 The second instruction here would lose that increment. But the
468 only effect of dead_children being wrong is that we might wait
469 longer than necessary to reap a child, and lose some parallelism;
470 and we might print the "Waiting for unfinished jobs" message above
471 when not necessary. */
473 if (dead_children > 0)
474 --dead_children;
476 any_remote = 0;
477 any_local = shell_function_pid != 0;
478 for (c = children; c != 0; c = c->next)
480 any_remote |= c->remote;
481 any_local |= ! c->remote;
482 DB (DB_JOBS, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
483 (unsigned long int) c, c->file->name,
484 (long) c->pid, c->remote ? _(" (remote)") : ""));
485 #ifdef VMS
486 break;
487 #endif
490 /* First, check for remote children. */
491 if (any_remote)
492 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
493 else
494 pid = 0;
496 if (pid > 0)
497 /* We got a remote child. */
498 remote = 1;
499 else if (pid < 0)
501 /* A remote status command failed miserably. Punt. */
502 remote_status_lose:
503 if (EINTR_SET)
504 continue;
506 pfatal_with_name ("remote_status");
508 else
510 /* No remote children. Check for local children. */
511 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
512 if (any_local)
514 local_wait:
515 #ifdef VMS
516 vmsWaitForChildren (&status);
517 pid = c->pid;
518 #else
519 #ifdef WAIT_NOHANG
520 if (!block)
521 pid = WAIT_NOHANG (&status);
522 else
523 #endif
524 pid = wait (&status);
525 #endif /* !VMS */
527 else
528 pid = 0;
530 if (pid < 0)
532 /* EINTR? Try again. */
533 if (EINTR_SET)
534 goto local_wait;
536 /* The wait*() failed miserably. Punt. */
537 pfatal_with_name ("wait");
539 else if (pid > 0)
541 /* We got a child exit; chop the status word up. */
542 exit_code = WEXITSTATUS (status);
543 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
544 coredump = WCOREDUMP (status);
546 else
548 /* No local children are dead. */
549 reap_more = 0;
551 if (!block || !any_remote)
552 break;
554 /* Now try a blocking wait for a remote child. */
555 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
556 if (pid < 0)
557 goto remote_status_lose;
558 else if (pid == 0)
559 /* No remote children either. Finally give up. */
560 break;
562 /* We got a remote child. */
563 remote = 1;
565 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
567 #ifdef __MSDOS__
568 /* Life is very different on MSDOS. */
569 pid = dos_pid - 1;
570 status = dos_status;
571 exit_code = WEXITSTATUS (status);
572 if (exit_code == 0xff)
573 exit_code = -1;
574 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
575 coredump = 0;
576 #endif /* __MSDOS__ */
577 #ifdef _AMIGA
578 /* Same on Amiga */
579 pid = amiga_pid - 1;
580 status = amiga_status;
581 exit_code = amiga_status;
582 exit_sig = 0;
583 coredump = 0;
584 #endif /* _AMIGA */
585 #ifdef WINDOWS32
587 HANDLE hPID;
588 int err;
590 /* wait for anything to finish */
591 if (hPID = process_wait_for_any()) {
593 /* was an error found on this process? */
594 err = process_last_err(hPID);
596 /* get exit data */
597 exit_code = process_exit_code(hPID);
599 if (err)
600 fprintf(stderr, "make (e=%d): %s",
601 exit_code, map_windows32_error_to_string(exit_code));
603 /* signal */
604 exit_sig = process_signal(hPID);
606 /* cleanup process */
607 process_cleanup(hPID);
609 coredump = 0;
611 pid = (int) hPID;
613 #endif /* WINDOWS32 */
616 /* Check if this is the child of the `shell' function. */
617 if (!remote && pid == shell_function_pid)
619 /* It is. Leave an indicator for the `shell' function. */
620 if (exit_sig == 0 && exit_code == 127)
621 shell_function_completed = -1;
622 else
623 shell_function_completed = 1;
624 break;
627 child_failed = exit_sig != 0 || exit_code != 0;
629 /* Search for a child matching the deceased one. */
630 lastc = 0;
631 for (c = children; c != 0; lastc = c, c = c->next)
632 if (c->remote == remote && c->pid == pid)
633 break;
635 if (c == 0)
636 /* An unknown child died.
637 Ignore it; it was inherited from our invoker. */
638 continue;
640 DB (DB_JOBS, (child_failed
641 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
642 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
643 (unsigned long int) c, (long) c->pid,
644 c->remote ? _(" (remote)") : ""));
646 if (c->sh_batch_file) {
647 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
648 c->sh_batch_file));
650 /* just try and remove, don't care if this fails */
651 remove (c->sh_batch_file);
653 /* all done with memory */
654 free (c->sh_batch_file);
655 c->sh_batch_file = NULL;
658 /* If this child had the good stdin, say it is now free. */
659 if (c->good_stdin)
660 good_stdin_used = 0;
662 if (child_failed && !c->noerror && !ignore_errors_flag)
664 /* The commands failed. Write an error message,
665 delete non-precious targets, and abort. */
666 static int delete_on_error = -1;
667 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
668 c->file->update_status = 2;
669 if (delete_on_error == -1)
671 struct file *f = lookup_file (".DELETE_ON_ERROR");
672 delete_on_error = f != 0 && f->is_target;
674 if (exit_sig != 0 || delete_on_error)
675 delete_child_targets (c);
677 else
679 if (child_failed)
681 /* The commands failed, but we don't care. */
682 child_error (c->file->name,
683 exit_code, exit_sig, coredump, 1);
684 child_failed = 0;
687 /* If there are more commands to run, try to start them. */
688 if (job_next_command (c))
690 if (handling_fatal_signal)
692 /* Never start new commands while we are dying.
693 Since there are more commands that wanted to be run,
694 the target was not completely remade. So we treat
695 this as if a command had failed. */
696 c->file->update_status = 2;
698 else
700 /* Check again whether to start remotely.
701 Whether or not we want to changes over time.
702 Also, start_remote_job may need state set up
703 by start_remote_job_p. */
704 c->remote = start_remote_job_p (0);
705 start_job_command (c);
706 /* Fatal signals are left blocked in case we were
707 about to put that child on the chain. But it is
708 already there, so it is safe for a fatal signal to
709 arrive now; it will clean up this child's targets. */
710 unblock_sigs ();
711 if (c->file->command_state == cs_running)
712 /* We successfully started the new command.
713 Loop to reap more children. */
714 continue;
717 if (c->file->update_status != 0)
718 /* We failed to start the commands. */
719 delete_child_targets (c);
721 else
722 /* There are no more commands. We got through them all
723 without an unignored error. Now the target has been
724 successfully updated. */
725 c->file->update_status = 0;
728 /* When we get here, all the commands for C->file are finished
729 (or aborted) and C->file->update_status contains 0 or 2. But
730 C->file->command_state is still cs_running if all the commands
731 ran; notice_finish_file looks for cs_running to tell it that
732 it's interesting to check the file's modtime again now. */
734 if (! handling_fatal_signal)
735 /* Notice if the target of the commands has been changed.
736 This also propagates its values for command_state and
737 update_status to its also_make files. */
738 notice_finished_file (c->file);
740 DB (DB_JOBS, (_("Removing child 0x%08lx PID %ld %s from chain.\n"),
741 (unsigned long int) c, (long) c->pid,
742 c->remote ? _(" (remote)") : ""));
744 /* Block fatal signals while frobnicating the list, so that
745 children and job_slots_used are always consistent. Otherwise
746 a fatal signal arriving after the child is off the chain and
747 before job_slots_used is decremented would believe a child was
748 live and call reap_children again. */
749 block_sigs ();
751 /* There is now another slot open. */
752 if (job_slots_used > 0)
753 --job_slots_used;
755 /* Remove the child from the chain and free it. */
756 if (lastc == 0)
757 children = c->next;
758 else
759 lastc->next = c->next;
761 free_child (c);
763 unblock_sigs ();
765 /* If the job failed, and the -k flag was not given, die,
766 unless we are already in the process of dying. */
767 if (!err && child_failed && !keep_going_flag &&
768 /* fatal_error_signal will die with the right signal. */
769 !handling_fatal_signal)
770 die (2);
772 /* Only block for one child. */
773 block = 0;
776 return;
779 /* Free the storage allocated for CHILD. */
781 static void
782 free_child (child)
783 register struct child *child;
785 /* If this child is the only one it was our "free" job, so don't put a
786 token back for it. This child has already been removed from the list,
787 so if there any left this wasn't the last one. */
789 if (job_fds[1] >= 0 && children)
791 char token = '+';
793 /* Write a job token back to the pipe. */
795 while (write (job_fds[1], &token, 1) != 1)
796 if (!EINTR_SET)
797 pfatal_with_name (_("write jobserver"));
799 DB (DB_JOBS, (_("Released token for child 0x%08lx (%s).\n"),
800 (unsigned long int) child, child->file->name));
803 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
804 return;
806 if (child->command_lines != 0)
808 register unsigned int i;
809 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
810 free (child->command_lines[i]);
811 free ((char *) child->command_lines);
814 if (child->environment != 0)
816 register char **ep = child->environment;
817 while (*ep != 0)
818 free (*ep++);
819 free ((char *) child->environment);
822 free ((char *) child);
825 #ifdef POSIX
826 extern sigset_t fatal_signal_set;
827 #endif
829 void
830 block_sigs ()
832 #ifdef POSIX
833 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
834 #else
835 # ifdef HAVE_SIGSETMASK
836 (void) sigblock (fatal_signal_mask);
837 # endif
838 #endif
841 #ifdef POSIX
842 void
843 unblock_sigs ()
845 sigset_t empty;
846 sigemptyset (&empty);
847 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
849 #endif
851 /* Start a job to run the commands specified in CHILD.
852 CHILD is updated to reflect the commands and ID of the child process.
854 NOTE: On return fatal signals are blocked! The caller is responsible
855 for calling `unblock_sigs', once the new child is safely on the chain so
856 it can be cleaned up in the event of a fatal signal. */
858 static void
859 start_job_command (child)
860 register struct child *child;
862 #ifndef _AMIGA
863 static int bad_stdin = -1;
864 #endif
865 register char *p;
866 int flags;
867 #ifdef VMS
868 char *argv;
869 #else
870 char **argv;
871 #endif
873 /* If we have a completely empty commandset, stop now. */
874 if (!child->command_ptr)
875 goto next_command;
877 /* Combine the flags parsed for the line itself with
878 the flags specified globally for this target. */
879 flags = (child->file->command_flags
880 | child->file->cmds->lines_flags[child->command_line - 1]);
882 p = child->command_ptr;
883 child->noerror = flags & COMMANDS_NOERROR;
885 while (*p != '\0')
887 if (*p == '@')
888 flags |= COMMANDS_SILENT;
889 else if (*p == '+')
890 flags |= COMMANDS_RECURSE;
891 else if (*p == '-')
892 child->noerror = 1;
893 else if (!isblank ((unsigned char)*p))
894 break;
895 ++p;
898 /* Update the file's command flags with any new ones we found. */
899 child->file->cmds->lines_flags[child->command_line - 1] |= flags;
901 /* If -q was given, just say that updating `failed'. The exit status of
902 1 tells the user that -q is saying `something to do'; the exit status
903 for a random error is 2. */
904 if (question_flag && !(flags & COMMANDS_RECURSE))
906 child->file->update_status = 1;
907 notice_finished_file (child->file);
908 return;
911 /* There may be some preceding whitespace left if there
912 was nothing but a backslash on the first line. */
913 p = next_token (p);
915 /* Figure out an argument list from this command line. */
918 char *end = 0;
919 #ifdef VMS
920 argv = p;
921 #else
922 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
923 #endif
924 if (end == NULL)
925 child->command_ptr = NULL;
926 else
928 *end++ = '\0';
929 child->command_ptr = end;
933 if (touch_flag && !(flags & COMMANDS_RECURSE))
935 /* Go on to the next command. It might be the recursive one.
936 We construct ARGV only to find the end of the command line. */
937 #ifndef VMS
938 free (argv[0]);
939 free ((char *) argv);
940 #endif
941 argv = 0;
944 if (argv == 0)
946 next_command:
947 #ifdef __MSDOS__
948 execute_by_shell = 0; /* in case construct_command_argv sets it */
949 #endif
950 /* This line has no commands. Go to the next. */
951 if (job_next_command (child))
952 start_job_command (child);
953 else
955 /* No more commands. Make sure we're "running"; we might not be if
956 (e.g.) all commands were skipped due to -n. */
957 set_command_state (child->file, cs_running);
958 child->file->update_status = 0;
959 notice_finished_file (child->file);
961 return;
964 /* Print out the command. If silent, we call `message' with null so it
965 can log the working directory before the command's own error messages
966 appear. */
968 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
969 ? "%s" : (char *) 0, p);
971 /* Optimize an empty command. People use this for timestamp rules,
972 so avoid forking a useless shell. */
974 #if !defined(VMS) && !defined(_AMIGA)
975 if (
976 #ifdef __MSDOS__
977 unixy_shell /* the test is complicated and we already did it */
978 #else
979 (argv[0] && !strcmp (argv[0], "/bin/sh"))
980 #endif
981 && (argv[1]
982 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
983 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
984 && argv[3] == NULL)
986 free (argv[0]);
987 free ((char *) argv);
988 goto next_command;
990 #endif /* !VMS && !_AMIGA */
992 /* Tell update_goal_chain that a command has been started on behalf of
993 this target. It is important that this happens here and not in
994 reap_children (where we used to do it), because reap_children might be
995 reaping children from a different target. We want this increment to
996 guaranteedly indicate that a command was started for the dependency
997 chain (i.e., update_file recursion chain) we are processing. */
999 ++commands_started;
1001 /* If -n was given, recurse to get the next line in the sequence. */
1003 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1005 #ifndef VMS
1006 free (argv[0]);
1007 free ((char *) argv);
1008 #endif
1009 goto next_command;
1012 /* Flush the output streams so they won't have things written twice. */
1014 fflush (stdout);
1015 fflush (stderr);
1017 #ifndef VMS
1018 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1020 /* Set up a bad standard input that reads from a broken pipe. */
1022 if (bad_stdin == -1)
1024 /* Make a file descriptor that is the read end of a broken pipe.
1025 This will be used for some children's standard inputs. */
1026 int pd[2];
1027 if (pipe (pd) == 0)
1029 /* Close the write side. */
1030 (void) close (pd[1]);
1031 /* Save the read side. */
1032 bad_stdin = pd[0];
1034 /* Set the descriptor to close on exec, so it does not litter any
1035 child's descriptor table. When it is dup2'd onto descriptor 0,
1036 that descriptor will not close on exec. */
1037 CLOSE_ON_EXEC (bad_stdin);
1041 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1043 /* Decide whether to give this child the `good' standard input
1044 (one that points to the terminal or whatever), or the `bad' one
1045 that points to the read side of a broken pipe. */
1047 child->good_stdin = !good_stdin_used;
1048 if (child->good_stdin)
1049 good_stdin_used = 1;
1051 #endif /* !VMS */
1053 child->deleted = 0;
1055 #ifndef _AMIGA
1056 /* Set up the environment for the child. */
1057 if (child->environment == 0)
1058 child->environment = target_environment (child->file);
1059 #endif
1061 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1063 #ifndef VMS
1064 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1065 if (child->remote)
1067 int is_remote, id, used_stdin;
1068 if (start_remote_job (argv, child->environment,
1069 child->good_stdin ? 0 : bad_stdin,
1070 &is_remote, &id, &used_stdin))
1071 /* Don't give up; remote execution may fail for various reasons. If
1072 so, simply run the job locally. */
1073 goto run_local;
1074 else
1076 if (child->good_stdin && !used_stdin)
1078 child->good_stdin = 0;
1079 good_stdin_used = 0;
1081 child->remote = is_remote;
1082 child->pid = id;
1085 else
1086 #endif /* !VMS */
1088 /* Fork the child process. */
1090 char **parent_environ;
1092 run_local:
1093 block_sigs ();
1095 child->remote = 0;
1097 #ifdef VMS
1099 if (!child_execute_job (argv, child)) {
1100 /* Fork failed! */
1101 perror_with_name ("vfork", "");
1102 goto error;
1105 #else
1107 parent_environ = environ;
1108 child->pid = vfork ();
1109 environ = parent_environ; /* Restore value child may have clobbered. */
1110 if (child->pid == 0)
1112 /* We are the child side. */
1113 unblock_sigs ();
1115 /* If we aren't running a recursive command and we have a jobserver
1116 pipe, close it before exec'ing. */
1117 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1119 close (job_fds[0]);
1120 close (job_fds[1]);
1122 if (job_rfd >= 0)
1123 close (job_rfd);
1125 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1126 argv, child->environment);
1128 else if (child->pid < 0)
1130 /* Fork failed! */
1131 unblock_sigs ();
1132 perror_with_name ("vfork", "");
1133 goto error;
1135 #endif /* !VMS */
1138 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1139 #ifdef __MSDOS__
1141 int proc_return;
1143 block_sigs ();
1144 dos_status = 0;
1146 /* We call `system' to do the job of the SHELL, since stock DOS
1147 shell is too dumb. Our `system' knows how to handle long
1148 command lines even if pipes/redirection is needed; it will only
1149 call COMMAND.COM when its internal commands are used. */
1150 if (execute_by_shell)
1152 char *cmdline = argv[0];
1153 /* We don't have a way to pass environment to `system',
1154 so we need to save and restore ours, sigh... */
1155 char **parent_environ = environ;
1157 environ = child->environment;
1159 /* If we have a *real* shell, tell `system' to call
1160 it to do everything for us. */
1161 if (unixy_shell)
1163 /* A *real* shell on MSDOS may not support long
1164 command lines the DJGPP way, so we must use `system'. */
1165 cmdline = argv[2]; /* get past "shell -c" */
1168 dos_command_running = 1;
1169 proc_return = system (cmdline);
1170 environ = parent_environ;
1171 execute_by_shell = 0; /* for the next time */
1173 else
1175 dos_command_running = 1;
1176 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1179 /* Need to unblock signals before turning off
1180 dos_command_running, so that child's signals
1181 will be treated as such (see fatal_error_signal). */
1182 unblock_sigs ();
1183 dos_command_running = 0;
1185 /* If the child got a signal, dos_status has its
1186 high 8 bits set, so be careful not to alter them. */
1187 if (proc_return == -1)
1188 dos_status |= 0xff;
1189 else
1190 dos_status |= (proc_return & 0xff);
1191 ++dead_children;
1192 child->pid = dos_pid++;
1194 #endif /* __MSDOS__ */
1195 #ifdef _AMIGA
1196 amiga_status = MyExecute (argv);
1198 ++dead_children;
1199 child->pid = amiga_pid++;
1200 if (amiga_batch_file)
1202 amiga_batch_file = 0;
1203 DeleteFile (amiga_bname); /* Ignore errors. */
1205 #endif /* Amiga */
1206 #ifdef WINDOWS32
1208 HANDLE hPID;
1209 char* arg0;
1211 /* make UNC paths safe for CreateProcess -- backslash format */
1212 arg0 = argv[0];
1213 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1214 for ( ; arg0 && *arg0; arg0++)
1215 if (*arg0 == '/')
1216 *arg0 = '\\';
1218 /* make sure CreateProcess() has Path it needs */
1219 sync_Path_environment();
1221 hPID = process_easy(argv, child->environment);
1223 if (hPID != INVALID_HANDLE_VALUE)
1224 child->pid = (int) hPID;
1225 else {
1226 int i;
1227 unblock_sigs();
1228 fprintf(stderr,
1229 _("process_easy() failed failed to launch process (e=%d)\n"),
1230 process_last_err(hPID));
1231 for (i = 0; argv[i]; i++)
1232 fprintf(stderr, "%s ", argv[i]);
1233 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1236 #endif /* WINDOWS32 */
1237 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1239 /* We are the parent side. Set the state to
1240 say the commands are running and return. */
1242 set_command_state (child->file, cs_running);
1244 /* Free the storage used by the child's argument list. */
1245 #ifndef VMS
1246 free (argv[0]);
1247 free ((char *) argv);
1248 #endif
1250 return;
1252 error:
1253 child->file->update_status = 2;
1254 notice_finished_file (child->file);
1255 return;
1258 /* Try to start a child running.
1259 Returns nonzero if the child was started (and maybe finished), or zero if
1260 the load was too high and the child was put on the `waiting_jobs' chain. */
1262 static int
1263 start_waiting_job (c)
1264 struct child *c;
1266 struct file *f = c->file;
1268 /* If we can start a job remotely, we always want to, and don't care about
1269 the local load average. We record that the job should be started
1270 remotely in C->remote for start_job_command to test. */
1272 c->remote = start_remote_job_p (1);
1274 /* If we are running at least one job already and the load average
1275 is too high, make this one wait. */
1276 if (!c->remote && job_slots_used > 0 && load_too_high ())
1278 /* Put this child on the chain of children waiting for the load average
1279 to go down. */
1280 set_command_state (f, cs_running);
1281 c->next = waiting_jobs;
1282 waiting_jobs = c;
1283 return 0;
1286 /* Start the first command; reap_children will run later command lines. */
1287 start_job_command (c);
1289 switch (f->command_state)
1291 case cs_running:
1292 c->next = children;
1293 DB (DB_JOBS, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1294 (unsigned long int) c, c->file->name,
1295 (long) c->pid, c->remote ? _(" (remote)") : ""));
1296 children = c;
1297 /* One more job slot is in use. */
1298 ++job_slots_used;
1299 unblock_sigs ();
1300 break;
1302 case cs_not_started:
1303 /* All the command lines turned out to be empty. */
1304 f->update_status = 0;
1305 /* FALLTHROUGH */
1307 case cs_finished:
1308 notice_finished_file (f);
1309 free_child (c);
1310 break;
1312 default:
1313 assert (f->command_state == cs_finished);
1314 break;
1317 return 1;
1320 /* Create a `struct child' for FILE and start its commands running. */
1322 void
1323 new_job (file)
1324 register struct file *file;
1326 register struct commands *cmds = file->cmds;
1327 register struct child *c;
1328 char **lines;
1329 register unsigned int i;
1331 /* Let any previously decided-upon jobs that are waiting
1332 for the load to go down start before this new one. */
1333 start_waiting_jobs ();
1335 /* Reap any children that might have finished recently. */
1336 reap_children (0, 0);
1338 /* Chop the commands up into lines if they aren't already. */
1339 chop_commands (cmds);
1341 /* Expand the command lines and store the results in LINES. */
1342 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1343 for (i = 0; i < cmds->ncommand_lines; ++i)
1345 /* Collapse backslash-newline combinations that are inside variable
1346 or function references. These are left alone by the parser so
1347 that they will appear in the echoing of commands (where they look
1348 nice); and collapsed by construct_command_argv when it tokenizes.
1349 But letting them survive inside function invocations loses because
1350 we don't want the functions to see them as part of the text. */
1352 char *in, *out, *ref;
1354 /* IN points to where in the line we are scanning.
1355 OUT points to where in the line we are writing.
1356 When we collapse a backslash-newline combination,
1357 IN gets ahead of OUT. */
1359 in = out = cmds->command_lines[i];
1360 while ((ref = strchr (in, '$')) != 0)
1362 ++ref; /* Move past the $. */
1364 if (out != in)
1365 /* Copy the text between the end of the last chunk
1366 we processed (where IN points) and the new chunk
1367 we are about to process (where REF points). */
1368 bcopy (in, out, ref - in);
1370 /* Move both pointers past the boring stuff. */
1371 out += ref - in;
1372 in = ref;
1374 if (*ref == '(' || *ref == '{')
1376 char openparen = *ref;
1377 char closeparen = openparen == '(' ? ')' : '}';
1378 int count;
1379 char *p;
1381 *out++ = *in++; /* Copy OPENPAREN. */
1382 /* IN now points past the opening paren or brace.
1383 Count parens or braces until it is matched. */
1384 count = 0;
1385 while (*in != '\0')
1387 if (*in == closeparen && --count < 0)
1388 break;
1389 else if (*in == '\\' && in[1] == '\n')
1391 /* We have found a backslash-newline inside a
1392 variable or function reference. Eat it and
1393 any following whitespace. */
1395 int quoted = 0;
1396 for (p = in - 1; p > ref && *p == '\\'; --p)
1397 quoted = !quoted;
1399 if (quoted)
1400 /* There were two or more backslashes, so this is
1401 not really a continuation line. We don't collapse
1402 the quoting backslashes here as is done in
1403 collapse_continuations, because the line will
1404 be collapsed again after expansion. */
1405 *out++ = *in++;
1406 else
1408 /* Skip the backslash, newline and
1409 any following whitespace. */
1410 in = next_token (in + 2);
1412 /* Discard any preceding whitespace that has
1413 already been written to the output. */
1414 while (out > ref
1415 && isblank ((unsigned char)out[-1]))
1416 --out;
1418 /* Replace it all with a single space. */
1419 *out++ = ' ';
1422 else
1424 if (*in == openparen)
1425 ++count;
1427 *out++ = *in++;
1433 /* There are no more references in this line to worry about.
1434 Copy the remaining uninteresting text to the output. */
1435 if (out != in)
1436 strcpy (out, in);
1438 /* Finally, expand the line. */
1439 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1440 file);
1443 /* Start the command sequence, record it in a new
1444 `struct child', and add that to the chain. */
1446 c = (struct child *) xmalloc (sizeof (struct child));
1447 bzero ((char *)c, sizeof (struct child));
1448 c->file = file;
1449 c->command_lines = lines;
1450 c->sh_batch_file = NULL;
1452 /* Fetch the first command line to be run. */
1453 job_next_command (c);
1455 /* Wait for a job slot to be freed up. If we allow an infinite number
1456 don't bother; also job_slots will == 0 if we're using the jobserver. */
1458 if (job_slots != 0)
1459 while (job_slots_used == job_slots)
1460 reap_children (1, 0);
1462 #ifdef MAKE_JOBSERVER
1463 /* If we are controlling multiple jobs make sure we have a token before
1464 starting the child. */
1466 /* This can be inefficient. There's a decent chance that this job won't
1467 actually have to run any subprocesses: the command script may be empty
1468 or otherwise optimized away. It would be nice if we could defer
1469 obtaining a token until just before we need it, in start_job_command.
1470 To do that we'd need to keep track of whether we'd already obtained a
1471 token (since start_job_command is called for each line of the job, not
1472 just once). Also more thought needs to go into the entire algorithm;
1473 this is where the old parallel job code waits, so... */
1475 else if (job_fds[0] >= 0)
1476 while (1)
1478 char token;
1480 /* If we don't already have a job started, use our "free" token. */
1481 if (!children)
1482 break;
1484 /* Read a token. As long as there's no token available we'll block.
1485 If we get a SIGCHLD we'll return with EINTR. If one happened
1486 before we got here we'll return immediately with EBADF because
1487 the signal handler closes the dup'd file descriptor. */
1489 if (read (job_rfd, &token, 1) == 1)
1491 DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1492 (unsigned long int) c, c->file->name));
1493 break;
1496 if (errno != EINTR && errno != EBADF)
1497 pfatal_with_name (_("read jobs pipe"));
1499 /* Re-dup the read side of the pipe, so the signal handler can
1500 notify us if we miss a child. */
1501 if (job_rfd < 0)
1502 job_rfd = dup (job_fds[0]);
1504 /* Something's done. We don't want to block for a whole child,
1505 just reap whatever's there. */
1506 reap_children (0, 0);
1508 #endif
1510 /* The job is now primed. Start it running.
1511 (This will notice if there are in fact no commands.) */
1512 (void) start_waiting_job (c);
1514 if (job_slots == 1 || not_parallel)
1515 /* Since there is only one job slot, make things run linearly.
1516 Wait for the child to die, setting the state to `cs_finished'. */
1517 while (file->command_state == cs_running)
1518 reap_children (1, 0);
1520 return;
1523 /* Move CHILD's pointers to the next command for it to execute.
1524 Returns nonzero if there is another command. */
1526 static int
1527 job_next_command (child)
1528 struct child *child;
1530 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1532 /* There are no more lines in the expansion of this line. */
1533 if (child->command_line == child->file->cmds->ncommand_lines)
1535 /* There are no more lines to be expanded. */
1536 child->command_ptr = 0;
1537 return 0;
1539 else
1540 /* Get the next line to run. */
1541 child->command_ptr = child->command_lines[child->command_line++];
1543 return 1;
1546 static int
1547 load_too_high ()
1549 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1550 return 1;
1551 #else
1552 double load;
1554 if (max_load_average < 0)
1555 return 0;
1557 make_access ();
1558 if (getloadavg (&load, 1) != 1)
1560 static int lossage = -1;
1561 /* Complain only once for the same error. */
1562 if (lossage == -1 || errno != lossage)
1564 if (errno == 0)
1565 /* An errno value of zero means getloadavg is just unsupported. */
1566 error (NILF,
1567 _("cannot enforce load limits on this operating system"));
1568 else
1569 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1571 lossage = errno;
1572 load = 0;
1574 user_access ();
1576 return load >= max_load_average;
1577 #endif
1580 /* Start jobs that are waiting for the load to be lower. */
1582 void
1583 start_waiting_jobs ()
1585 struct child *job;
1587 if (waiting_jobs == 0)
1588 return;
1592 /* Check for recently deceased descendants. */
1593 reap_children (0, 0);
1595 /* Take a job off the waiting list. */
1596 job = waiting_jobs;
1597 waiting_jobs = job->next;
1599 /* Try to start that job. We break out of the loop as soon
1600 as start_waiting_job puts one back on the waiting list. */
1602 while (start_waiting_job (job) && waiting_jobs != 0);
1604 return;
1607 #ifndef WINDOWS32
1608 #ifdef VMS
1609 #include <descrip.h>
1610 #include <clidef.h>
1612 /* This is called as an AST when a child process dies (it won't get
1613 interrupted by anything except a higher level AST).
1615 int vmsHandleChildTerm(struct child *child)
1617 int status;
1618 register struct child *lastc, *c;
1619 int child_failed;
1621 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1623 lib$free_ef(&child->efn);
1625 (void) sigblock (fatal_signal_mask);
1627 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1629 /* Search for a child matching the deceased one. */
1630 lastc = 0;
1631 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1632 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1633 #else
1634 c = child;
1635 #endif
1637 if (child_failed && !c->noerror && !ignore_errors_flag)
1639 /* The commands failed. Write an error message,
1640 delete non-precious targets, and abort. */
1641 child_error (c->file->name, c->cstatus, 0, 0, 0);
1642 c->file->update_status = 1;
1643 delete_child_targets (c);
1645 else
1647 if (child_failed)
1649 /* The commands failed, but we don't care. */
1650 child_error (c->file->name, c->cstatus, 0, 0, 1);
1651 child_failed = 0;
1654 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1655 /* If there are more commands to run, try to start them. */
1656 start_job (c);
1658 switch (c->file->command_state)
1660 case cs_running:
1661 /* Successfully started. */
1662 break;
1664 case cs_finished:
1665 if (c->file->update_status != 0) {
1666 /* We failed to start the commands. */
1667 delete_child_targets (c);
1669 break;
1671 default:
1672 error (NILF, _("internal error: `%s' command_state"),
1673 c->file->name);
1674 abort ();
1675 break;
1677 #endif /* RECURSIVEJOBS */
1680 /* Set the state flag to say the commands have finished. */
1681 c->file->command_state = cs_finished;
1682 notice_finished_file (c->file);
1684 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1685 /* Remove the child from the chain and free it. */
1686 if (lastc == 0)
1687 children = c->next;
1688 else
1689 lastc->next = c->next;
1690 free_child (c);
1691 #endif /* RECURSIVEJOBS */
1693 /* There is now another slot open. */
1694 if (job_slots_used > 0)
1695 --job_slots_used;
1697 /* If the job failed, and the -k flag was not given, die. */
1698 if (child_failed && !keep_going_flag)
1699 die (EXIT_FAILURE);
1701 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1703 return 1;
1706 /* VMS:
1707 Spawn a process executing the command in ARGV and return its pid. */
1709 #define MAXCMDLEN 200
1711 /* local helpers to make ctrl+c and ctrl+y working, see below */
1712 #include <iodef.h>
1713 #include <libclidef.h>
1714 #include <ssdef.h>
1716 static int ctrlMask= LIB$M_CLI_CTRLY;
1717 static int oldCtrlMask;
1718 static int setupYAstTried= 0;
1719 static int pidToAbort= 0;
1720 static int chan= 0;
1722 static void reEnableAst(void) {
1723 lib$enable_ctrl (&oldCtrlMask,0);
1726 static astHandler (void) {
1727 if (pidToAbort) {
1728 sys$forcex (&pidToAbort, 0, SS$_ABORT);
1729 pidToAbort= 0;
1731 kill (getpid(),SIGQUIT);
1734 static void tryToSetupYAst(void) {
1735 $DESCRIPTOR(inputDsc,"SYS$COMMAND");
1736 int status;
1737 struct {
1738 short int status, count;
1739 int dvi;
1740 } iosb;
1742 setupYAstTried++;
1744 if (!chan) {
1745 status= sys$assign(&inputDsc,&chan,0,0);
1746 if (!(status&SS$_NORMAL)) {
1747 lib$signal(status);
1748 return;
1751 status= sys$qiow (0, chan, IO$_SETMODE|IO$M_CTRLYAST,&iosb,0,0,
1752 astHandler,0,0,0,0,0);
1753 if (status==SS$_ILLIOFUNC) {
1754 sys$dassgn(chan);
1755 #ifdef CTRLY_ENABLED_ANYWAY
1756 fprintf (stderr,
1757 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
1758 #else
1759 return;
1760 #endif
1762 if (status==SS$_NORMAL)
1763 status= iosb.status;
1764 if (!(status&SS$_NORMAL)) {
1765 lib$signal(status);
1766 return;
1769 /* called from AST handler ? */
1770 if (setupYAstTried>1)
1771 return;
1772 if (atexit(reEnableAst))
1773 fprintf (stderr,
1774 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
1775 status= lib$disable_ctrl (&ctrlMask, &oldCtrlMask);
1776 if (!(status&SS$_NORMAL)) {
1777 lib$signal(status);
1778 return;
1782 child_execute_job (argv, child)
1783 char *argv;
1784 struct child *child;
1786 int i;
1787 static struct dsc$descriptor_s cmddsc;
1788 static struct dsc$descriptor_s pnamedsc;
1789 static struct dsc$descriptor_s ifiledsc;
1790 static struct dsc$descriptor_s ofiledsc;
1791 static struct dsc$descriptor_s efiledsc;
1792 int have_redirection = 0;
1793 int have_newline = 0;
1795 int spflags = CLI$M_NOWAIT;
1796 int status;
1797 char *cmd = alloca (strlen (argv) + 512), *p, *q;
1798 char ifile[256], ofile[256], efile[256];
1799 char *comname = 0;
1800 char procname[100];
1802 /* Parse IO redirection. */
1804 ifile[0] = 0;
1805 ofile[0] = 0;
1806 efile[0] = 0;
1808 DB (DB_JOBS, ("child_execute_job (%s)\n", argv));
1810 while (isspace ((unsigned char)*argv))
1811 argv++;
1813 if (*argv == 0)
1814 return 0;
1816 sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
1817 pnamedsc.dsc$w_length = strlen(procname);
1818 pnamedsc.dsc$a_pointer = procname;
1819 pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
1820 pnamedsc.dsc$b_class = DSC$K_CLASS_S;
1822 /* Handle comments and redirection. */
1823 for (p = argv, q = cmd; *p; p++, q++)
1825 switch (*p)
1827 case '#':
1828 *p-- = 0;
1829 *q-- = 0;
1830 break;
1831 case '\\':
1832 p++;
1833 if (*p == '\n')
1834 p++;
1835 if (isspace ((unsigned char)*p))
1837 do { p++; } while (isspace ((unsigned char)*p));
1838 p--;
1840 *q = *p;
1841 break;
1842 case '<':
1843 p = vms_redirect (&ifiledsc, ifile, p);
1844 *q = ' ';
1845 have_redirection = 1;
1846 break;
1847 case '>':
1848 have_redirection = 1;
1849 if (*(p-1) == '2')
1851 q--;
1852 if (strncmp (p, ">&1", 3) == 0)
1854 p += 3;
1855 strcpy (efile, "sys$output");
1856 efiledsc.dsc$w_length = strlen(efile);
1857 efiledsc.dsc$a_pointer = efile;
1858 efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
1859 efiledsc.dsc$b_class = DSC$K_CLASS_S;
1861 else
1863 p = vms_redirect (&efiledsc, efile, p);
1866 else
1868 p = vms_redirect (&ofiledsc, ofile, p);
1870 *q = ' ';
1871 break;
1872 case '\n':
1873 have_newline = 1;
1874 default:
1875 *q = *p;
1876 break;
1879 *q = *p;
1881 if (strncmp (cmd, "builtin_", 8) == 0)
1883 child->pid = 270163;
1884 child->efn = 0;
1885 child->cstatus = 1;
1887 DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));
1889 p = cmd + 8;
1891 if ((*(p) == 'c')
1892 && (*(p+1) == 'd')
1893 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
1895 p += 3;
1896 while ((*p == ' ') || (*p == '\t'))
1897 p++;
1898 DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
1899 if (chdir (p))
1900 return 0;
1901 else
1902 return 1;
1904 else if ((*(p) == 'r')
1905 && (*(p+1) == 'm')
1906 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
1908 int in_arg;
1910 /* rm */
1911 p += 3;
1912 while ((*p == ' ') || (*p == '\t'))
1913 p++;
1914 in_arg = 1;
1916 DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
1917 while (*p)
1919 switch (*p)
1921 case ' ':
1922 case '\t':
1923 if (in_arg)
1925 *p++ = ';';
1926 in_arg = 0;
1928 break;
1929 default:
1930 break;
1932 p++;
1935 else
1937 printf(_("Unknown builtin command '%s'\n"), cmd);
1938 fflush(stdout);
1939 return 0;
1943 /* Create a *.com file if either the command is too long for
1944 lib$spawn, or the command contains a newline, or if redirection
1945 is desired. Forcing commands with newlines into DCLs allows to
1946 store search lists on user mode logicals. */
1948 if (strlen (cmd) > MAXCMDLEN
1949 || (have_redirection != 0)
1950 || (have_newline != 0))
1952 FILE *outfile;
1953 char c;
1954 char *sep;
1955 int alevel = 0; /* apostrophe level */
1957 if (strlen (cmd) == 0)
1959 printf (_("Error, empty command\n"));
1960 fflush (stdout);
1961 return 0;
1964 outfile = open_tmpfile (&comname, "sys$scratch:CMDXXXXXX.COM");
1965 if (outfile == 0)
1966 pfatal_with_name (_("fopen (temporary file)"));
1968 if (ifile[0])
1970 fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
1971 DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
1972 ifiledsc.dsc$w_length = 0;
1975 if (efile[0])
1977 fprintf (outfile, "$ define sys$error %s\n", efile);
1978 DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
1979 efiledsc.dsc$w_length = 0;
1982 if (ofile[0])
1984 fprintf (outfile, "$ define sys$output %s\n", ofile);
1985 DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
1986 ofiledsc.dsc$w_length = 0;
1989 p = sep = q = cmd;
1990 for (c = '\n'; c; c = *q++)
1992 switch (c)
1994 case '\n':
1995 /* At a newline, skip any whitespace around a leading $
1996 from the command and issue exactly one $ into the DCL. */
1997 while (isspace ((unsigned char)*p))
1998 p++;
1999 if (*p == '$')
2000 p++;
2001 while (isspace ((unsigned char)*p))
2002 p++;
2003 fwrite (p, 1, q - p, outfile);
2004 fputc ('$', outfile);
2005 fputc (' ', outfile);
2006 /* Reset variables. */
2007 p = sep = q;
2008 break;
2010 /* Nice places for line breaks are after strings, after
2011 comma or space and before slash. */
2012 case '"':
2013 q = handle_apos (q + 1);
2014 sep = q;
2015 break;
2016 case ',':
2017 case ' ':
2018 sep = q;
2019 break;
2020 case '/':
2021 case '\0':
2022 sep = q - 1;
2023 break;
2024 default:
2025 break;
2027 if (sep - p > 78)
2029 /* Enough stuff for a line. */
2030 fwrite (p, 1, sep - p, outfile);
2031 p = sep;
2032 if (*sep)
2034 /* The command continues. */
2035 fputc ('-', outfile);
2037 fputc ('\n', outfile);
2041 fwrite (p, 1, q - p, outfile);
2042 fputc ('\n', outfile);
2044 fclose (outfile);
2046 sprintf (cmd, "$ @%s", comname);
2048 DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
2051 cmddsc.dsc$w_length = strlen(cmd);
2052 cmddsc.dsc$a_pointer = cmd;
2053 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
2054 cmddsc.dsc$b_class = DSC$K_CLASS_S;
2056 child->efn = 0;
2057 while (child->efn < 32 || child->efn > 63)
2059 status = lib$get_ef ((unsigned long *)&child->efn);
2060 if (!(status & 1))
2061 return 0;
2064 sys$clref (child->efn);
2066 vms_jobsefnmask |= (1 << (child->efn - 32));
2069 LIB$SPAWN [command-string]
2070 [,input-file]
2071 [,output-file]
2072 [,flags]
2073 [,process-name]
2074 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2075 [,AST-address] [,varying-AST-argument]
2076 [,prompt-string] [,cli] [,table]
2079 #ifndef DONTWAITFORCHILD
2081 * Code to make ctrl+c and ctrl+y working.
2082 * The problem starts with the synchronous case where after lib$spawn is
2083 * called any input will go to the child. But with input re-directed,
2084 * both control characters won't make it to any of the programs, neither
2085 * the spawning nor to the spawned one. Hence the caller needs to spawn
2086 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2087 * has to follow to simulate the wanted synchronous behaviour.
2088 * The next problem is ctrl+y which isn't caught by the crtl and
2089 * therefore isn't converted to SIGQUIT (for a signal handler which is
2090 * already established). The only way to catch ctrl+y, is an AST
2091 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2092 * disabled, otherwise it will handle it. Not to mention the previous
2093 * ctrl+y handling of DCL needs to be re-established before make exits.
2094 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2095 * make it to the signal handler after the child "normally" terminates.
2096 * This isn't enough. It seems reasonable for simple command lines like
2097 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2098 * spawning make. Therefore we need to abort the process in the AST.
2100 * Prior to the spawn it is checked if an AST is already set up for
2101 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2102 * this will work except if make is run in a batch environment, but there
2103 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2104 * is disabled and an exit handler is established to re-enable it.
2105 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2106 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2107 * the already established handler and will bring us back to common code.
2108 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2109 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2110 * which the crtl converts to SIGINT and which is caught by the common
2111 * signal handler. Because signals were blocked before entering this code
2112 * sys$waitfr will always complete and the SIGQUIT will be processed after
2113 * it (after termination of the current block, somewhere in common code).
2114 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2115 * current command completes. Anyway it's better than nothing :-)
2118 if (!setupYAstTried)
2119 tryToSetupYAst();
2120 status = lib$spawn (&cmddsc, /* cmd-string */
2121 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file */
2122 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
2123 &spflags, /* flags */
2124 &pnamedsc, /* proc name */
2125 &child->pid, &child->cstatus, &child->efn,
2126 0, 0,
2127 0, 0, 0);
2128 pidToAbort= child->pid;
2129 status= sys$waitfr (child->efn);
2130 pidToAbort= 0;
2131 vmsHandleChildTerm(child);
2132 #else
2133 status = lib$spawn (&cmddsc,
2134 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
2135 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
2136 &spflags,
2137 &pnamedsc,
2138 &child->pid, &child->cstatus, &child->efn,
2139 vmsHandleChildTerm, child,
2140 0, 0, 0);
2141 #endif
2143 if (!(status & 1))
2145 printf (_("Error spawning, %d\n") ,status);
2146 fflush (stdout);
2149 if (comname && !ISDB (DB_JOBS))
2150 unlink (comname);
2152 return (status & 1);
2155 #else /* !VMS */
2157 #if !defined (_AMIGA) && !defined (__MSDOS__)
2158 /* UNIX:
2159 Replace the current process with one executing the command in ARGV.
2160 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2161 the environment of the new program. This function does not return. */
2163 void
2164 child_execute_job (stdin_fd, stdout_fd, argv, envp)
2165 int stdin_fd, stdout_fd;
2166 char **argv, **envp;
2168 if (stdin_fd != 0)
2169 (void) dup2 (stdin_fd, 0);
2170 if (stdout_fd != 1)
2171 (void) dup2 (stdout_fd, 1);
2172 if (stdin_fd != 0)
2173 (void) close (stdin_fd);
2174 if (stdout_fd != 1)
2175 (void) close (stdout_fd);
2177 /* Run the command. */
2178 exec_command (argv, envp);
2180 #endif /* !AMIGA && !__MSDOS__ */
2181 #endif /* !VMS */
2182 #endif /* !WINDOWS32 */
2184 #ifndef _AMIGA
2185 /* Replace the current process with one running the command in ARGV,
2186 with environment ENVP. This function does not return. */
2188 void
2189 exec_command (argv, envp)
2190 char **argv, **envp;
2192 #ifdef VMS
2193 /* to work around a problem with signals and execve: ignore them */
2194 #ifdef SIGCHLD
2195 signal (SIGCHLD,SIG_IGN);
2196 #endif
2197 /* Run the program. */
2198 execve (argv[0], argv, envp);
2199 perror_with_name ("execve: ", argv[0]);
2200 _exit (EXIT_FAILURE);
2201 #else
2202 #ifdef WINDOWS32
2203 HANDLE hPID;
2204 HANDLE hWaitPID;
2205 int err = 0;
2206 int exit_code = EXIT_FAILURE;
2208 /* make sure CreateProcess() has Path it needs */
2209 sync_Path_environment();
2211 /* launch command */
2212 hPID = process_easy(argv, envp);
2214 /* make sure launch ok */
2215 if (hPID == INVALID_HANDLE_VALUE)
2217 int i;
2218 fprintf(stderr,
2219 _("process_easy() failed failed to launch process (e=%d)\n"),
2220 process_last_err(hPID));
2221 for (i = 0; argv[i]; i++)
2222 fprintf(stderr, "%s ", argv[i]);
2223 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2224 exit(EXIT_FAILURE);
2227 /* wait and reap last child */
2228 while (hWaitPID = process_wait_for_any())
2230 /* was an error found on this process? */
2231 err = process_last_err(hWaitPID);
2233 /* get exit data */
2234 exit_code = process_exit_code(hWaitPID);
2236 if (err)
2237 fprintf(stderr, "make (e=%d, rc=%d): %s",
2238 err, exit_code, map_windows32_error_to_string(err));
2240 /* cleanup process */
2241 process_cleanup(hWaitPID);
2243 /* expect to find only last pid, warn about other pids reaped */
2244 if (hWaitPID == hPID)
2245 break;
2246 else
2247 fprintf(stderr,
2248 _("make reaped child pid %d, still waiting for pid %d\n"),
2249 hWaitPID, hPID);
2252 /* return child's exit code as our exit code */
2253 exit(exit_code);
2255 #else /* !WINDOWS32 */
2257 /* Be the user, permanently. */
2258 child_access ();
2260 /* Run the program. */
2261 environ = envp;
2262 execvp (argv[0], argv);
2264 switch (errno)
2266 case ENOENT:
2267 error (NILF, _("%s: Command not found"), argv[0]);
2268 break;
2269 case ENOEXEC:
2271 /* The file is not executable. Try it as a shell script. */
2272 extern char *getenv ();
2273 char *shell;
2274 char **new_argv;
2275 int argc;
2277 shell = getenv ("SHELL");
2278 if (shell == 0)
2279 shell = default_shell;
2281 argc = 1;
2282 while (argv[argc] != 0)
2283 ++argc;
2285 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
2286 new_argv[0] = shell;
2287 new_argv[1] = argv[0];
2288 while (argc > 0)
2290 new_argv[1 + argc] = argv[argc];
2291 --argc;
2294 execvp (shell, new_argv);
2295 if (errno == ENOENT)
2296 error (NILF, _("%s: Shell program not found"), shell);
2297 else
2298 perror_with_name ("execvp: ", shell);
2299 break;
2302 default:
2303 perror_with_name ("execvp: ", argv[0]);
2304 break;
2307 _exit (127);
2308 #endif /* !WINDOWS32 */
2309 #endif /* !VMS */
2311 #else /* On Amiga */
2312 void exec_command (argv)
2313 char **argv;
2315 MyExecute (argv);
2318 void clean_tmp (void)
2320 DeleteFile (amiga_bname);
2323 #endif /* On Amiga */
2325 #ifndef VMS
2326 /* Figure out the argument list necessary to run LINE as a command. Try to
2327 avoid using a shell. This routine handles only ' quoting, and " quoting
2328 when no backslash, $ or ` characters are seen in the quotes. Starting
2329 quotes may be escaped with a backslash. If any of the characters in
2330 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2331 is the first word of a line, the shell is used.
2333 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2334 If *RESTP is NULL, newlines will be ignored.
2336 SHELL is the shell to use, or nil to use the default shell.
2337 IFS is the value of $IFS, or nil (meaning the default). */
2339 static char **
2340 construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr)
2341 char *line, **restp;
2342 char *shell, *ifs;
2343 char **batch_filename_ptr;
2345 #ifdef __MSDOS__
2346 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2347 We call `system' for anything that requires ``slow'' processing,
2348 because DOS shells are too dumb. When $SHELL points to a real
2349 (unix-style) shell, `system' just calls it to do everything. When
2350 $SHELL points to a DOS shell, `system' does most of the work
2351 internally, calling the shell only for its internal commands.
2352 However, it looks on the $PATH first, so you can e.g. have an
2353 external command named `mkdir'.
2355 Since we call `system', certain characters and commands below are
2356 actually not specific to COMMAND.COM, but to the DJGPP implementation
2357 of `system'. In particular:
2359 The shell wildcard characters are in DOS_CHARS because they will
2360 not be expanded if we call the child via `spawnXX'.
2362 The `;' is in DOS_CHARS, because our `system' knows how to run
2363 multiple commands on a single line.
2365 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2366 won't have to tell one from another and have one more set of
2367 commands and special characters. */
2368 static char sh_chars_dos[] = "*?[];|<>%^&()";
2369 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2370 "copy", "ctty", "date", "del", "dir", "echo",
2371 "erase", "exit", "for", "goto", "if", "md",
2372 "mkdir", "path", "pause", "prompt", "rd",
2373 "rmdir", "rem", "ren", "rename", "set",
2374 "shift", "time", "type", "ver", "verify",
2375 "vol", ":", 0 };
2377 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2378 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2379 "logout", "set", "umask", "wait", "while",
2380 "for", "case", "if", ":", ".", "break",
2381 "continue", "export", "read", "readonly",
2382 "shift", "times", "trap", "switch", "unset",
2383 0 };
2385 char *sh_chars;
2386 char **sh_cmds;
2387 #else
2388 #ifdef _AMIGA
2389 static char sh_chars[] = "#;\"|<>()?*$`";
2390 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2391 "rename", "set", "setenv", "date", "makedir",
2392 "skip", "else", "endif", "path", "prompt",
2393 "unset", "unsetenv", "version",
2394 0 };
2395 #else
2396 #ifdef WINDOWS32
2397 static char sh_chars_dos[] = "\"|&<>";
2398 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2399 "copy", "ctty", "date", "del", "dir", "echo",
2400 "erase", "exit", "for", "goto", "if", "if", "md",
2401 "mkdir", "path", "pause", "prompt", "rd", "rem",
2402 "ren", "rename", "rmdir", "set", "shift", "time",
2403 "type", "ver", "verify", "vol", ":", 0 };
2404 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2405 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2406 "logout", "set", "umask", "wait", "while", "for",
2407 "case", "if", ":", ".", "break", "continue",
2408 "export", "read", "readonly", "shift", "times",
2409 "trap", "switch", "test",
2410 #ifdef BATCH_MODE_ONLY_SHELL
2411 "echo",
2412 #endif
2413 0 };
2414 char* sh_chars;
2415 char** sh_cmds;
2416 #else /* WINDOWS32 */
2417 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
2418 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
2419 "logout", "set", "umask", "wait", "while", "for",
2420 "case", "if", ":", ".", "break", "continue",
2421 "export", "read", "readonly", "shift", "times",
2422 "trap", "switch", 0 };
2423 #endif /* WINDOWS32 */
2424 #endif /* Amiga */
2425 #endif /* __MSDOS__ */
2426 register int i;
2427 register char *p;
2428 register char *ap;
2429 char *end;
2430 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2431 char **new_argv = 0;
2432 #ifdef WINDOWS32
2433 int slow_flag = 0;
2435 if (no_default_sh_exe) {
2436 sh_cmds = sh_cmds_dos;
2437 sh_chars = sh_chars_dos;
2438 } else {
2439 sh_cmds = sh_cmds_sh;
2440 sh_chars = sh_chars_sh;
2442 #endif /* WINDOWS32 */
2444 if (restp != NULL)
2445 *restp = NULL;
2447 /* Make sure not to bother processing an empty line. */
2448 while (isblank ((unsigned char)*line))
2449 ++line;
2450 if (*line == '\0')
2451 return 0;
2453 /* See if it is safe to parse commands internally. */
2454 if (shell == 0)
2455 shell = default_shell;
2456 #ifdef WINDOWS32
2457 else if (strcmp (shell, default_shell))
2459 char *s1 = _fullpath(NULL, shell, 0);
2460 char *s2 = _fullpath(NULL, default_shell, 0);
2462 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2464 if (s1)
2465 free (s1);
2466 if (s2)
2467 free (s2);
2469 if (slow_flag)
2470 goto slow;
2471 #else /* not WINDOWS32 */
2472 #ifdef __MSDOS__
2473 else if (stricmp (shell, default_shell))
2475 extern int _is_unixy_shell (const char *_path);
2477 message (1, _("$SHELL changed (was `%s', now `%s')"), default_shell, shell);
2478 unixy_shell = _is_unixy_shell (shell);
2479 default_shell = shell;
2481 if (unixy_shell)
2483 sh_chars = sh_chars_sh;
2484 sh_cmds = sh_cmds_sh;
2486 else
2488 sh_chars = sh_chars_dos;
2489 sh_cmds = sh_cmds_dos;
2491 #else /* not __MSDOS__ */
2492 else if (strcmp (shell, default_shell))
2493 goto slow;
2494 #endif /* not __MSDOS__ */
2495 #endif /* not WINDOWS32 */
2497 if (ifs != 0)
2498 for (ap = ifs; *ap != '\0'; ++ap)
2499 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2500 goto slow;
2502 i = strlen (line) + 1;
2504 /* More than 1 arg per character is impossible. */
2505 new_argv = (char **) xmalloc (i * sizeof (char *));
2507 /* All the args can fit in a buffer as big as LINE is. */
2508 ap = new_argv[0] = (char *) xmalloc (i);
2509 end = ap + i;
2511 /* I is how many complete arguments have been found. */
2512 i = 0;
2513 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2514 for (p = line; *p != '\0'; ++p)
2516 if (ap > end)
2517 abort ();
2519 if (instring)
2521 string_char:
2522 /* Inside a string, just copy any char except a closing quote
2523 or a backslash-newline combination. */
2524 if (*p == instring)
2526 instring = 0;
2527 if (ap == new_argv[0] || *(ap-1) == '\0')
2528 last_argument_was_empty = 1;
2530 else if (*p == '\\' && p[1] == '\n')
2531 goto swallow_escaped_newline;
2532 else if (*p == '\n' && restp != NULL)
2534 /* End of the command line. */
2535 *restp = p;
2536 goto end_of_line;
2538 /* Backslash, $, and ` are special inside double quotes.
2539 If we see any of those, punt.
2540 But on MSDOS, if we use COMMAND.COM, double and single
2541 quotes have the same effect. */
2542 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2543 goto slow;
2544 else
2545 *ap++ = *p;
2547 else if (strchr (sh_chars, *p) != 0)
2548 /* Not inside a string, but it's a special char. */
2549 goto slow;
2550 #ifdef __MSDOS__
2551 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2552 /* `...' is a wildcard in DJGPP. */
2553 goto slow;
2554 #endif
2555 else
2556 /* Not a special char. */
2557 switch (*p)
2559 case '=':
2560 /* Equals is a special character in leading words before the
2561 first word with no equals sign in it. This is not the case
2562 with sh -k, but we never get here when using nonstandard
2563 shell flags. */
2564 if (! seen_nonequals && unixy_shell)
2565 goto slow;
2566 word_has_equals = 1;
2567 *ap++ = '=';
2568 break;
2570 case '\\':
2571 /* Backslash-newline combinations are eaten. */
2572 if (p[1] == '\n')
2574 swallow_escaped_newline:
2576 /* Eat the backslash, the newline, and following whitespace,
2577 replacing it all with a single space. */
2578 p += 2;
2580 /* If there is a tab after a backslash-newline,
2581 remove it from the source line which will be echoed,
2582 since it was most likely used to line
2583 up the continued line with the previous one. */
2584 if (*p == '\t')
2585 /* Note these overlap and strcpy() is undefined for
2586 overlapping objects in ANSI C. The strlen() _IS_ right,
2587 since we need to copy the nul byte too. */
2588 bcopy (p + 1, p, strlen (p));
2590 if (instring)
2591 goto string_char;
2592 else
2594 if (ap != new_argv[i])
2595 /* Treat this as a space, ending the arg.
2596 But if it's at the beginning of the arg, it should
2597 just get eaten, rather than becoming an empty arg. */
2598 goto end_of_arg;
2599 else
2600 p = next_token (p) - 1;
2603 else if (p[1] != '\0')
2605 #if defined(__MSDOS__) || defined(WINDOWS32)
2606 /* Only remove backslashes before characters special
2607 to Unixy shells. All other backslashes are copied
2608 verbatim, since they are probably DOS-style
2609 directory separators. This still leaves a small
2610 window for problems, but at least it should work
2611 for the vast majority of naive users. */
2613 #ifdef __MSDOS__
2614 /* A dot is only special as part of the "..."
2615 wildcard. */
2616 if (strneq (p + 1, ".\\.\\.", 5))
2618 *ap++ = '.';
2619 *ap++ = '.';
2620 p += 4;
2622 else
2623 #endif
2624 if (p[1] != '\\' && p[1] != '\''
2625 && !isspace ((unsigned char)p[1])
2626 && (strchr (sh_chars_sh, p[1]) == 0))
2627 /* back up one notch, to copy the backslash */
2628 --p;
2630 #endif /* __MSDOS__ || WINDOWS32 */
2631 /* Copy and skip the following char. */
2632 *ap++ = *++p;
2634 break;
2636 case '\'':
2637 case '"':
2638 instring = *p;
2639 break;
2641 case '\n':
2642 if (restp != NULL)
2644 /* End of the command line. */
2645 *restp = p;
2646 goto end_of_line;
2648 else
2649 /* Newlines are not special. */
2650 *ap++ = '\n';
2651 break;
2653 case ' ':
2654 case '\t':
2655 end_of_arg:
2656 /* We have the end of an argument.
2657 Terminate the text of the argument. */
2658 *ap++ = '\0';
2659 new_argv[++i] = ap;
2660 last_argument_was_empty = 0;
2662 /* Update SEEN_NONEQUALS, which tells us if every word
2663 heretofore has contained an `='. */
2664 seen_nonequals |= ! word_has_equals;
2665 if (word_has_equals && ! seen_nonequals)
2666 /* An `=' in a word before the first
2667 word without one is magical. */
2668 goto slow;
2669 word_has_equals = 0; /* Prepare for the next word. */
2671 /* If this argument is the command name,
2672 see if it is a built-in shell command.
2673 If so, have the shell handle it. */
2674 if (i == 1)
2676 register int j;
2677 for (j = 0; sh_cmds[j] != 0; ++j)
2678 if (streq (sh_cmds[j], new_argv[0]))
2679 goto slow;
2682 /* Ignore multiple whitespace chars. */
2683 p = next_token (p);
2684 /* Next iteration should examine the first nonwhite char. */
2685 --p;
2686 break;
2688 default:
2689 *ap++ = *p;
2690 break;
2693 end_of_line:
2695 if (instring)
2696 /* Let the shell deal with an unterminated quote. */
2697 goto slow;
2699 /* Terminate the last argument and the argument list. */
2701 *ap = '\0';
2702 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2703 ++i;
2704 new_argv[i] = 0;
2706 if (i == 1)
2708 register int j;
2709 for (j = 0; sh_cmds[j] != 0; ++j)
2710 if (streq (sh_cmds[j], new_argv[0]))
2711 goto slow;
2714 if (new_argv[0] == 0)
2715 /* Line was empty. */
2716 return 0;
2717 else
2718 return new_argv;
2720 slow:;
2721 /* We must use the shell. */
2723 if (new_argv != 0)
2725 /* Free the old argument list we were working on. */
2726 free (new_argv[0]);
2727 free ((void *)new_argv);
2730 #ifdef __MSDOS__
2731 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2732 #endif
2734 #ifdef _AMIGA
2736 char *ptr;
2737 char *buffer;
2738 char *dptr;
2740 buffer = (char *)xmalloc (strlen (line)+1);
2742 ptr = line;
2743 for (dptr=buffer; *ptr; )
2745 if (*ptr == '\\' && ptr[1] == '\n')
2746 ptr += 2;
2747 else if (*ptr == '@') /* Kludge: multiline commands */
2749 ptr += 2;
2750 *dptr++ = '\n';
2752 else
2753 *dptr++ = *ptr++;
2755 *dptr = 0;
2757 new_argv = (char **) xmalloc (2 * sizeof (char *));
2758 new_argv[0] = buffer;
2759 new_argv[1] = 0;
2761 #else /* Not Amiga */
2762 #ifdef WINDOWS32
2764 * Not eating this whitespace caused things like
2766 * sh -c "\n"
2768 * which gave the shell fits. I think we have to eat
2769 * whitespace here, but this code should be considered
2770 * suspicious if things start failing....
2773 /* Make sure not to bother processing an empty line. */
2774 while (isspace ((unsigned char)*line))
2775 ++line;
2776 if (*line == '\0')
2777 return 0;
2778 #endif /* WINDOWS32 */
2780 /* SHELL may be a multi-word command. Construct a command line
2781 "SHELL -c LINE", with all special chars in LINE escaped.
2782 Then recurse, expanding this command line to get the final
2783 argument list. */
2785 unsigned int shell_len = strlen (shell);
2786 #ifndef VMS
2787 static char minus_c[] = " -c ";
2788 #else
2789 static char minus_c[] = "";
2790 #endif
2791 unsigned int line_len = strlen (line);
2793 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2794 + (line_len * 2) + 1);
2795 char *command_ptr = NULL; /* used for batch_mode_shell mode */
2797 ap = new_line;
2798 bcopy (shell, ap, shell_len);
2799 ap += shell_len;
2800 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2801 ap += sizeof (minus_c) - 1;
2802 command_ptr = ap;
2803 for (p = line; *p != '\0'; ++p)
2805 if (restp != NULL && *p == '\n')
2807 *restp = p;
2808 break;
2810 else if (*p == '\\' && p[1] == '\n')
2812 /* Eat the backslash, the newline, and following whitespace,
2813 replacing it all with a single space (which is escaped
2814 from the shell). */
2815 p += 2;
2817 /* If there is a tab after a backslash-newline,
2818 remove it from the source line which will be echoed,
2819 since it was most likely used to line
2820 up the continued line with the previous one. */
2821 if (*p == '\t')
2822 bcopy (p + 1, p, strlen (p));
2824 p = next_token (p);
2825 --p;
2826 if (unixy_shell && !batch_mode_shell)
2827 *ap++ = '\\';
2828 *ap++ = ' ';
2829 continue;
2832 /* DOS shells don't know about backslash-escaping. */
2833 if (unixy_shell && !batch_mode_shell &&
2834 (*p == '\\' || *p == '\'' || *p == '"'
2835 || isspace ((unsigned char)*p)
2836 || strchr (sh_chars, *p) != 0))
2837 *ap++ = '\\';
2838 #ifdef __MSDOS__
2839 else if (unixy_shell && strneq (p, "...", 3))
2841 /* The case of `...' wildcard again. */
2842 strcpy (ap, "\\.\\.\\");
2843 ap += 5;
2844 p += 2;
2846 #endif
2847 *ap++ = *p;
2849 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2850 /* Line was empty. */
2851 return 0;
2852 *ap = '\0';
2854 #ifdef WINDOWS32
2855 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2856 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2857 cases, run commands via a script file. */
2858 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2859 FILE* batch = NULL;
2860 int id = GetCurrentProcessId();
2861 PATH_VAR(fbuf);
2862 char* fname = NULL;
2864 /* create a file name */
2865 sprintf(fbuf, "make%d", id);
2866 fname = tempnam(".", fbuf);
2868 /* create batch file name */
2869 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
2870 strcpy(*batch_filename_ptr, fname);
2872 /* make sure path name is in DOS backslash format */
2873 if (!unixy_shell) {
2874 fname = *batch_filename_ptr;
2875 for (i = 0; fname[i] != '\0'; ++i)
2876 if (fname[i] == '/')
2877 fname[i] = '\\';
2878 strcat(*batch_filename_ptr, ".bat");
2879 } else {
2880 strcat(*batch_filename_ptr, ".sh");
2883 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
2884 *batch_filename_ptr));
2886 /* create batch file to execute command */
2887 batch = fopen (*batch_filename_ptr, "w");
2888 if (!unixy_shell)
2889 fputs ("@echo off\n", batch);
2890 fputs (command_ptr, batch);
2891 fputc ('\n', batch);
2892 fclose (batch);
2894 /* create argv */
2895 new_argv = (char **) xmalloc(3 * sizeof (char *));
2896 if (unixy_shell) {
2897 new_argv[0] = xstrdup (shell);
2898 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2899 } else {
2900 new_argv[0] = xstrdup (*batch_filename_ptr);
2901 new_argv[1] = NULL;
2903 new_argv[2] = NULL;
2904 } else
2905 #endif /* WINDOWS32 */
2906 if (unixy_shell)
2907 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2908 (char *) 0, (char *) 0,
2909 (char **) 0);
2910 #ifdef __MSDOS__
2911 else
2913 /* With MSDOS shells, we must construct the command line here
2914 instead of recursively calling ourselves, because we
2915 cannot backslash-escape the special characters (see above). */
2916 new_argv = (char **) xmalloc (sizeof (char *));
2917 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2918 new_argv[0] = xmalloc (line_len + 1);
2919 strncpy (new_argv[0],
2920 new_line + shell_len + sizeof (minus_c) - 1, line_len);
2921 new_argv[0][line_len] = '\0';
2923 #else
2924 else
2925 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2926 __FILE__, __LINE__);
2927 #endif
2929 #endif /* ! AMIGA */
2931 return new_argv;
2933 #endif /* !VMS */
2935 /* Figure out the argument list necessary to run LINE as a command. Try to
2936 avoid using a shell. This routine handles only ' quoting, and " quoting
2937 when no backslash, $ or ` characters are seen in the quotes. Starting
2938 quotes may be escaped with a backslash. If any of the characters in
2939 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2940 is the first word of a line, the shell is used.
2942 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2943 If *RESTP is NULL, newlines will be ignored.
2945 FILE is the target whose commands these are. It is used for
2946 variable expansion for $(SHELL) and $(IFS). */
2948 char **
2949 construct_command_argv (line, restp, file, batch_filename_ptr)
2950 char *line, **restp;
2951 struct file *file;
2952 char** batch_filename_ptr;
2954 char *shell, *ifs;
2955 char **argv;
2957 #ifdef VMS
2958 char *cptr;
2959 int argc;
2961 argc = 0;
2962 cptr = line;
2963 for (;;)
2965 while ((*cptr != 0)
2966 && (isspace ((unsigned char)*cptr)))
2967 cptr++;
2968 if (*cptr == 0)
2969 break;
2970 while ((*cptr != 0)
2971 && (!isspace((unsigned char)*cptr)))
2972 cptr++;
2973 argc++;
2976 argv = (char **)malloc (argc * sizeof (char *));
2977 if (argv == 0)
2978 abort ();
2980 cptr = line;
2981 argc = 0;
2982 for (;;)
2984 while ((*cptr != 0)
2985 && (isspace ((unsigned char)*cptr)))
2986 cptr++;
2987 if (*cptr == 0)
2988 break;
2989 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
2990 argv[argc++] = cptr;
2991 while ((*cptr != 0)
2992 && (!isspace((unsigned char)*cptr)))
2993 cptr++;
2994 if (*cptr != 0)
2995 *cptr++ = 0;
2997 #else
2999 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3000 int save = warn_undefined_variables_flag;
3001 warn_undefined_variables_flag = 0;
3003 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3004 #ifdef WINDOWS32
3006 * Convert to forward slashes so that construct_command_argv_internal()
3007 * is not confused.
3009 if (shell) {
3010 char *p = w32ify(shell, 0);
3011 strcpy(shell, p);
3013 #endif
3014 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3016 warn_undefined_variables_flag = save;
3019 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
3021 free (shell);
3022 free (ifs);
3023 #endif /* !VMS */
3024 return argv;
3027 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3029 dup2 (old, new)
3030 int old, new;
3032 int fd;
3034 (void) close (new);
3035 fd = dup (old);
3036 if (fd != new)
3038 (void) close (fd);
3039 errno = EMFILE;
3040 return -1;
3043 return fd;
3045 #endif /* !HAPE_DUP2 && !_AMIGA */