* Typo.
[make.git] / job.c
blob3698f6984277b97d9909b37011a563e78f690c26
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 <assert.h>
22 #include "make.h"
23 #include "job.h"
24 #include "debug.h"
25 #include "filedef.h"
26 #include "commands.h"
27 #include "variable.h"
28 #include "debug.h"
30 #include <string.h>
32 /* Default shell to use. */
33 #ifdef WINDOWS32
34 char *default_shell = "sh.exe";
35 int no_default_sh_exe = 1;
36 int batch_mode_shell = 1;
37 #else /* WINDOWS32 */
38 # ifdef _AMIGA
39 char default_shell[] = "";
40 extern int MyExecute (char **);
41 # else /* _AMIGA */
42 # ifdef __MSDOS__
43 /* The default shell is a pointer so we can change it if Makefile
44 says so. It is without an explicit path so we get a chance
45 to search the $PATH for it (since MSDOS doesn't have standard
46 directories we could trust). */
47 char *default_shell = "command.com";
48 # else /* __MSDOS__ */
49 # ifdef VMS
50 # include <descrip.h>
51 char default_shell[] = "";
52 # else
53 char default_shell[] = "/bin/sh";
54 # endif /* VMS */
55 # endif /* __MSDOS__ */
56 int batch_mode_shell = 0;
57 # endif /* _AMIGA */
58 #endif /* WINDOWS32 */
60 #ifdef __MSDOS__
61 # include <process.h>
62 static int execute_by_shell;
63 static int dos_pid = 123;
64 int dos_status;
65 int dos_command_running;
66 #endif /* __MSDOS__ */
68 #ifdef _AMIGA
69 # include <proto/dos.h>
70 static int amiga_pid = 123;
71 static int amiga_status;
72 static char amiga_bname[32];
73 static int amiga_batch_file;
74 #endif /* Amiga. */
76 #ifdef VMS
77 # ifndef __GNUC__
78 # include <processes.h>
79 # endif
80 # include <starlet.h>
81 # include <lib$routines.h>
82 #endif
84 #ifdef WINDOWS32
85 # include <windows.h>
86 # include <io.h>
87 # include <process.h>
88 # include "sub_proc.h"
89 # include "w32err.h"
90 # include "pathstuff.h"
91 #endif /* WINDOWS32 */
93 #ifdef HAVE_FCNTL_H
94 # include <fcntl.h>
95 #else
96 # include <sys/file.h>
97 #endif
99 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
100 # include <sys/wait.h>
101 #endif
103 #ifdef HAVE_WAITPID
104 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
105 #else /* Don't have waitpid. */
106 # ifdef HAVE_WAIT3
107 # ifndef wait3
108 extern int wait3 ();
109 # endif
110 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
111 # endif /* Have wait3. */
112 #endif /* Have waitpid. */
114 #if !defined (wait) && !defined (POSIX)
115 extern int wait ();
116 #endif
118 #ifndef HAVE_UNION_WAIT
120 # define WAIT_T int
122 # ifndef WTERMSIG
123 # define WTERMSIG(x) ((x) & 0x7f)
124 # endif
125 # ifndef WCOREDUMP
126 # define WCOREDUMP(x) ((x) & 0x80)
127 # endif
128 # ifndef WEXITSTATUS
129 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
130 # endif
131 # ifndef WIFSIGNALED
132 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
133 # endif
134 # ifndef WIFEXITED
135 # define WIFEXITED(x) (WTERMSIG (x) == 0)
136 # endif
138 #else /* Have `union wait'. */
140 # define WAIT_T union wait
141 # ifndef WTERMSIG
142 # define WTERMSIG(x) ((x).w_termsig)
143 # endif
144 # ifndef WCOREDUMP
145 # define WCOREDUMP(x) ((x).w_coredump)
146 # endif
147 # ifndef WEXITSTATUS
148 # define WEXITSTATUS(x) ((x).w_retcode)
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
157 #endif /* Don't have `union wait'. */
159 /* How to set close-on-exec for a file descriptor. */
161 #if !defined F_SETFD
162 # define CLOSE_ON_EXEC(_d)
163 #else
164 # ifndef FD_CLOEXEC
165 # define FD_CLOEXEC 1
166 # endif
167 # define CLOSE_ON_EXEC(_d) (void) fcntl ((_d), F_SETFD, FD_CLOEXEC)
168 #endif
170 #ifdef VMS
171 static int vms_jobsefnmask = 0;
172 #endif /* !VMS */
174 #ifndef HAVE_UNISTD_H
175 extern int dup2 ();
176 extern int execve ();
177 extern void _exit ();
178 # ifndef VMS
179 extern int geteuid ();
180 extern int getegid ();
181 extern int setgid ();
182 extern int getgid ();
183 # endif
184 #endif
186 extern char *allocated_variable_expand_for_file PARAMS ((char *line, struct file *file));
188 extern int getloadavg PARAMS ((double loadavg[], int nelem));
189 extern int start_remote_job PARAMS ((char **argv, char **envp, int stdin_fd,
190 int *is_remote, int *id_ptr, int *used_stdin));
191 extern int start_remote_job_p PARAMS ((int));
192 extern int remote_status PARAMS ((int *exit_code_ptr, int *signal_ptr,
193 int *coredump_ptr, int block));
195 RETSIGTYPE child_handler PARAMS ((int));
196 static void free_child PARAMS ((struct child *));
197 static void start_job_command PARAMS ((struct child *child));
198 static int load_too_high PARAMS ((void));
199 static int job_next_command PARAMS ((struct child *));
200 static int start_waiting_job PARAMS ((struct child *));
201 #ifdef VMS
202 static void vmsWaitForChildren PARAMS ((int *));
203 #endif
205 /* Chain of all live (or recently deceased) children. */
207 struct child *children = 0;
209 /* Number of children currently running. */
211 unsigned int job_slots_used = 0;
213 /* Nonzero if the `good' standard input is in use. */
215 static int good_stdin_used = 0;
217 /* Chain of children waiting to run until the load average goes down. */
219 static struct child *waiting_jobs = 0;
221 /* Non-zero if we use a *real* shell (always so on Unix). */
223 int unixy_shell = 1;
226 #ifdef WINDOWS32
228 * The macro which references this function is defined in make.h.
230 int w32_kill(int pid, int sig)
232 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
234 #endif /* WINDOWS32 */
236 /* Write an error message describing the exit status given in
237 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
238 Append "(ignored)" if IGNORED is nonzero. */
240 static void
241 child_error (target_name, exit_code, exit_sig, coredump, ignored)
242 char *target_name;
243 int exit_code, exit_sig, coredump;
244 int ignored;
246 if (ignored && silent_flag)
247 return;
249 #ifdef VMS
250 if (!(exit_code & 1))
251 error (NILF,
252 (ignored ? _("*** [%s] Error 0x%x (ignored)")
253 : _("*** [%s] Error 0x%x")),
254 target_name, exit_code);
255 #else
256 if (exit_sig == 0)
257 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
258 _("*** [%s] Error %d"),
259 target_name, exit_code);
260 else
261 error (NILF, "*** [%s] %s%s",
262 target_name, strsignal (exit_sig),
263 coredump ? _(" (core dumped)") : "");
264 #endif /* VMS */
267 #ifdef VMS
268 /* Wait for nchildren children to terminate */
269 static void
270 vmsWaitForChildren(int *status)
272 while (1)
274 if (!vms_jobsefnmask)
276 *status = 0;
277 return;
280 *status = sys$wflor (32, vms_jobsefnmask);
282 return;
285 /* Set up IO redirection. */
287 char *
288 vms_redirect (desc, fname, ibuf)
289 struct dsc$descriptor_s *desc;
290 char *fname;
291 char *ibuf;
293 char *fptr;
294 extern char *vmsify ();
296 ibuf++;
297 while (isspace ((unsigned char)*ibuf))
298 ibuf++;
299 fptr = ibuf;
300 while (*ibuf && !isspace ((unsigned char)*ibuf))
301 ibuf++;
302 *ibuf = 0;
303 if (strcmp (fptr, "/dev/null") != 0)
305 strcpy (fname, vmsify (fptr, 0));
306 if (strchr (fname, '.') == 0)
307 strcat (fname, ".");
309 desc->dsc$w_length = strlen(fname);
310 desc->dsc$a_pointer = fname;
311 desc->dsc$b_dtype = DSC$K_DTYPE_T;
312 desc->dsc$b_class = DSC$K_CLASS_S;
314 if (*fname == 0)
315 printf (_("Warning: Empty redirection\n"));
316 return ibuf;
321 found apostrophe at (p-1)
323 inc p until after closing apostrophe. */
325 static char *
326 handle_apos (char *p)
328 int alast;
329 int inside;
331 #define SEPCHARS ",/()= "
333 inside = 0;
335 while (*p != 0)
337 if (*p == '"')
339 if (inside)
341 while ((alast > 0)
342 && (*p == '"'))
344 p++;
345 alast--;
347 if (alast == 0)
348 inside = 0;
349 else
351 fprintf (stderr, _("Syntax error, still inside '\"'\n"));
352 exit (3);
355 else
357 p++;
358 if (strchr (SEPCHARS, *p))
359 break;
360 inside = 1;
361 alast = 1;
362 while (*p == '"')
364 alast++;
365 p++;
369 else
370 p++;
373 return p;
376 #endif
379 /* Handle a dead child. This handler may or may not ever be installed.
381 If we're using the jobserver feature, we need it. First, installing it
382 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
383 read FD to ensure we don't enter another blocking read without reaping all
384 the dead children. In this case we don't need the dead_children count.
386 If we don't have either waitpid or wait3, then make is unreliable, but we
387 use the dead_children count to reap children as best we can. */
389 static unsigned int dead_children = 0;
391 RETSIGTYPE
392 child_handler (sig)
393 int sig;
395 ++dead_children;
397 if (job_rfd >= 0)
399 close (job_rfd);
400 job_rfd = -1;
403 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
407 extern int shell_function_pid, shell_function_completed;
409 /* Reap all dead children, storing the returned status and the new command
410 state (`cs_finished') in the `file' member of the `struct child' for the
411 dead child, and removing the child from the chain. In addition, if BLOCK
412 nonzero, we block in this function until we've reaped at least one
413 complete child, waiting for it to die if necessary. If ERR is nonzero,
414 print an error message first. */
416 void
417 reap_children (block, err)
418 int block, err;
420 WAIT_T status;
421 /* Initially, assume we have some. */
422 int reap_more = 1;
424 #ifdef WAIT_NOHANG
425 # define REAP_MORE reap_more
426 #else
427 # define REAP_MORE dead_children
428 #endif
430 /* As long as:
432 We have at least one child outstanding OR a shell function in progress,
434 We're blocking for a complete child OR there are more children to reap
436 we'll keep reaping children. */
438 while ((children != 0 || shell_function_pid != 0) &&
439 (block || REAP_MORE))
441 int remote = 0;
442 register int pid;
443 int exit_code, exit_sig, coredump;
444 register struct child *lastc, *c;
445 int child_failed;
446 int any_remote, any_local;
448 if (err && block)
450 /* We might block for a while, so let the user know why. */
451 fflush (stdout);
452 error (NILF, _("*** Waiting for unfinished jobs...."));
455 /* We have one less dead child to reap. As noted in
456 child_handler() above, this count is completely unimportant for
457 all modern, POSIX-y systems that support wait3() or waitpid().
458 The rest of this comment below applies only to early, broken
459 pre-POSIX systems. We keep the count only because... it's there...
461 The test and decrement are not atomic; if it is compiled into:
462 register = dead_children - 1;
463 dead_children = register;
464 a SIGCHLD could come between the two instructions.
465 child_handler increments dead_children.
466 The second instruction here would lose that increment. But the
467 only effect of dead_children being wrong is that we might wait
468 longer than necessary to reap a child, and lose some parallelism;
469 and we might print the "Waiting for unfinished jobs" message above
470 when not necessary. */
472 if (dead_children > 0)
473 --dead_children;
475 any_remote = 0;
476 any_local = shell_function_pid != 0;
477 for (c = children; c != 0; c = c->next)
479 any_remote |= c->remote;
480 any_local |= ! c->remote;
481 DB (DB_JOBS, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
482 (unsigned long int) c, c->file->name,
483 (long) c->pid, c->remote ? _(" (remote)") : ""));
484 #ifdef VMS
485 break;
486 #endif
489 /* First, check for remote children. */
490 if (any_remote)
491 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
492 else
493 pid = 0;
495 if (pid > 0)
496 /* We got a remote child. */
497 remote = 1;
498 else if (pid < 0)
500 /* A remote status command failed miserably. Punt. */
501 remote_status_lose:
502 if (EINTR_SET)
503 continue;
505 pfatal_with_name ("remote_status");
507 else
509 /* No remote children. Check for local children. */
510 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
511 if (any_local)
513 local_wait:
514 #ifdef VMS
515 vmsWaitForChildren (&status);
516 pid = c->pid;
517 #else
518 #ifdef WAIT_NOHANG
519 if (!block)
520 pid = WAIT_NOHANG (&status);
521 else
522 #endif
523 pid = wait (&status);
524 #endif /* !VMS */
526 else
527 pid = 0;
529 if (pid < 0)
531 /* EINTR? Try again. */
532 if (EINTR_SET)
533 goto local_wait;
535 /* The wait*() failed miserably. Punt. */
536 pfatal_with_name ("wait");
538 else if (pid > 0)
540 /* We got a child exit; chop the status word up. */
541 exit_code = WEXITSTATUS (status);
542 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
543 coredump = WCOREDUMP (status);
545 else
547 /* No local children are dead. */
548 reap_more = 0;
550 if (!block || !any_remote)
551 break;
553 /* Now try a blocking wait for a remote child. */
554 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
555 if (pid < 0)
556 goto remote_status_lose;
557 else if (pid == 0)
558 /* No remote children either. Finally give up. */
559 break;
561 /* We got a remote child. */
562 remote = 1;
564 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
566 #ifdef __MSDOS__
567 /* Life is very different on MSDOS. */
568 pid = dos_pid - 1;
569 status = dos_status;
570 exit_code = WEXITSTATUS (status);
571 if (exit_code == 0xff)
572 exit_code = -1;
573 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
574 coredump = 0;
575 #endif /* __MSDOS__ */
576 #ifdef _AMIGA
577 /* Same on Amiga */
578 pid = amiga_pid - 1;
579 status = amiga_status;
580 exit_code = amiga_status;
581 exit_sig = 0;
582 coredump = 0;
583 #endif /* _AMIGA */
584 #ifdef WINDOWS32
586 HANDLE hPID;
587 int err;
589 /* wait for anything to finish */
590 if (hPID = process_wait_for_any()) {
592 /* was an error found on this process? */
593 err = process_last_err(hPID);
595 /* get exit data */
596 exit_code = process_exit_code(hPID);
598 if (err)
599 fprintf(stderr, "make (e=%d): %s",
600 exit_code, map_windows32_error_to_string(exit_code));
602 /* signal */
603 exit_sig = process_signal(hPID);
605 /* cleanup process */
606 process_cleanup(hPID);
608 coredump = 0;
610 pid = (int) hPID;
612 #endif /* WINDOWS32 */
615 /* Check if this is the child of the `shell' function. */
616 if (!remote && pid == shell_function_pid)
618 /* It is. Leave an indicator for the `shell' function. */
619 if (exit_sig == 0 && exit_code == 127)
620 shell_function_completed = -1;
621 else
622 shell_function_completed = 1;
623 break;
626 child_failed = exit_sig != 0 || exit_code != 0;
628 /* Search for a child matching the deceased one. */
629 lastc = 0;
630 for (c = children; c != 0; lastc = c, c = c->next)
631 if (c->remote == remote && c->pid == pid)
632 break;
634 if (c == 0)
635 /* An unknown child died.
636 Ignore it; it was inherited from our invoker. */
637 continue;
639 DB (DB_JOBS, (child_failed
640 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
641 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
642 (unsigned long int) c, (long) c->pid,
643 c->remote ? _(" (remote)") : ""));
645 if (c->sh_batch_file) {
646 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
647 c->sh_batch_file));
649 /* just try and remove, don't care if this fails */
650 remove (c->sh_batch_file);
652 /* all done with memory */
653 free (c->sh_batch_file);
654 c->sh_batch_file = NULL;
657 /* If this child had the good stdin, say it is now free. */
658 if (c->good_stdin)
659 good_stdin_used = 0;
661 if (child_failed && !c->noerror && !ignore_errors_flag)
663 /* The commands failed. Write an error message,
664 delete non-precious targets, and abort. */
665 static int delete_on_error = -1;
666 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
667 c->file->update_status = 2;
668 if (delete_on_error == -1)
670 struct file *f = lookup_file (".DELETE_ON_ERROR");
671 delete_on_error = f != 0 && f->is_target;
673 if (exit_sig != 0 || delete_on_error)
674 delete_child_targets (c);
676 else
678 if (child_failed)
680 /* The commands failed, but we don't care. */
681 child_error (c->file->name,
682 exit_code, exit_sig, coredump, 1);
683 child_failed = 0;
686 /* If there are more commands to run, try to start them. */
687 if (job_next_command (c))
689 if (handling_fatal_signal)
691 /* Never start new commands while we are dying.
692 Since there are more commands that wanted to be run,
693 the target was not completely remade. So we treat
694 this as if a command had failed. */
695 c->file->update_status = 2;
697 else
699 /* Check again whether to start remotely.
700 Whether or not we want to changes over time.
701 Also, start_remote_job may need state set up
702 by start_remote_job_p. */
703 c->remote = start_remote_job_p (0);
704 start_job_command (c);
705 /* Fatal signals are left blocked in case we were
706 about to put that child on the chain. But it is
707 already there, so it is safe for a fatal signal to
708 arrive now; it will clean up this child's targets. */
709 unblock_sigs ();
710 if (c->file->command_state == cs_running)
711 /* We successfully started the new command.
712 Loop to reap more children. */
713 continue;
716 if (c->file->update_status != 0)
717 /* We failed to start the commands. */
718 delete_child_targets (c);
720 else
721 /* There are no more commands. We got through them all
722 without an unignored error. Now the target has been
723 successfully updated. */
724 c->file->update_status = 0;
727 /* When we get here, all the commands for C->file are finished
728 (or aborted) and C->file->update_status contains 0 or 2. But
729 C->file->command_state is still cs_running if all the commands
730 ran; notice_finish_file looks for cs_running to tell it that
731 it's interesting to check the file's modtime again now. */
733 if (! handling_fatal_signal)
734 /* Notice if the target of the commands has been changed.
735 This also propagates its values for command_state and
736 update_status to its also_make files. */
737 notice_finished_file (c->file);
739 DB (DB_JOBS, (_("Removing child 0x%08lx PID %ld %s from chain.\n"),
740 (unsigned long int) c, (long) c->pid,
741 c->remote ? _(" (remote)") : ""));
743 /* Block fatal signals while frobnicating the list, so that
744 children and job_slots_used are always consistent. Otherwise
745 a fatal signal arriving after the child is off the chain and
746 before job_slots_used is decremented would believe a child was
747 live and call reap_children again. */
748 block_sigs ();
750 /* There is now another slot open. */
751 if (job_slots_used > 0)
752 --job_slots_used;
754 /* Remove the child from the chain and free it. */
755 if (lastc == 0)
756 children = c->next;
757 else
758 lastc->next = c->next;
760 free_child (c);
762 unblock_sigs ();
764 /* If the job failed, and the -k flag was not given, die,
765 unless we are already in the process of dying. */
766 if (!err && child_failed && !keep_going_flag &&
767 /* fatal_error_signal will die with the right signal. */
768 !handling_fatal_signal)
769 die (2);
771 /* Only block for one child. */
772 block = 0;
775 return;
778 /* Free the storage allocated for CHILD. */
780 static void
781 free_child (child)
782 register struct child *child;
784 /* If this child is the only one it was our "free" job, so don't put a
785 token back for it. This child has already been removed from the list,
786 so if there any left this wasn't the last one. */
788 if (job_fds[1] >= 0 && children)
790 char token = '+';
792 /* Write a job token back to the pipe. */
794 while (write (job_fds[1], &token, 1) != 1)
795 if (!EINTR_SET)
796 pfatal_with_name (_("write jobserver"));
798 DB (DB_JOBS, (_("Released token for child 0x%08lx (%s).\n"),
799 (unsigned long int) child, child->file->name));
802 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
803 return;
805 if (child->command_lines != 0)
807 register unsigned int i;
808 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
809 free (child->command_lines[i]);
810 free ((char *) child->command_lines);
813 if (child->environment != 0)
815 register char **ep = child->environment;
816 while (*ep != 0)
817 free (*ep++);
818 free ((char *) child->environment);
821 free ((char *) child);
824 #ifdef POSIX
825 extern sigset_t fatal_signal_set;
826 #endif
828 void
829 block_sigs ()
831 #ifdef POSIX
832 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
833 #else
834 # ifdef HAVE_SIGSETMASK
835 (void) sigblock (fatal_signal_mask);
836 # endif
837 #endif
840 #ifdef POSIX
841 void
842 unblock_sigs ()
844 sigset_t empty;
845 sigemptyset (&empty);
846 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
848 #endif
850 /* Start a job to run the commands specified in CHILD.
851 CHILD is updated to reflect the commands and ID of the child process.
853 NOTE: On return fatal signals are blocked! The caller is responsible
854 for calling `unblock_sigs', once the new child is safely on the chain so
855 it can be cleaned up in the event of a fatal signal. */
857 static void
858 start_job_command (child)
859 register struct child *child;
861 #ifndef _AMIGA
862 static int bad_stdin = -1;
863 #endif
864 register char *p;
865 int flags;
866 #ifdef VMS
867 char *argv;
868 #else
869 char **argv;
870 #endif
872 /* If we have a completely empty commandset, stop now. */
873 if (!child->command_ptr)
874 goto next_command;
876 /* Combine the flags parsed for the line itself with
877 the flags specified globally for this target. */
878 flags = (child->file->command_flags
879 | child->file->cmds->lines_flags[child->command_line - 1]);
881 p = child->command_ptr;
882 child->noerror = flags & COMMANDS_NOERROR;
884 while (*p != '\0')
886 if (*p == '@')
887 flags |= COMMANDS_SILENT;
888 else if (*p == '+')
889 flags |= COMMANDS_RECURSE;
890 else if (*p == '-')
891 child->noerror = 1;
892 else if (!isblank ((unsigned char)*p))
893 break;
894 ++p;
897 /* Update the file's command flags with any new ones we found. */
898 child->file->cmds->lines_flags[child->command_line - 1] |= flags;
900 /* If -q was given, just say that updating `failed'. The exit status of
901 1 tells the user that -q is saying `something to do'; the exit status
902 for a random error is 2. */
903 if (question_flag && !(flags & COMMANDS_RECURSE))
905 child->file->update_status = 1;
906 notice_finished_file (child->file);
907 return;
910 /* There may be some preceding whitespace left if there
911 was nothing but a backslash on the first line. */
912 p = next_token (p);
914 /* Figure out an argument list from this command line. */
917 char *end = 0;
918 #ifdef VMS
919 argv = p;
920 #else
921 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
922 #endif
923 if (end == NULL)
924 child->command_ptr = NULL;
925 else
927 *end++ = '\0';
928 child->command_ptr = end;
932 if (touch_flag && !(flags & COMMANDS_RECURSE))
934 /* Go on to the next command. It might be the recursive one.
935 We construct ARGV only to find the end of the command line. */
936 #ifndef VMS
937 free (argv[0]);
938 free ((char *) argv);
939 #endif
940 argv = 0;
943 if (argv == 0)
945 next_command:
946 #ifdef __MSDOS__
947 execute_by_shell = 0; /* in case construct_command_argv sets it */
948 #endif
949 /* This line has no commands. Go to the next. */
950 if (job_next_command (child))
951 start_job_command (child);
952 else
954 /* No more commands. Make sure we're "running"; we might not be if
955 (e.g.) all commands were skipped due to -n. */
956 set_command_state (child->file, cs_running);
957 child->file->update_status = 0;
958 notice_finished_file (child->file);
960 return;
963 /* Print out the command. If silent, we call `message' with null so it
964 can log the working directory before the command's own error messages
965 appear. */
967 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
968 ? "%s" : (char *) 0, p);
970 /* Optimize an empty command. People use this for timestamp rules,
971 so avoid forking a useless shell. */
973 #if !defined(VMS) && !defined(_AMIGA)
974 if (
975 #ifdef __MSDOS__
976 unixy_shell /* the test is complicated and we already did it */
977 #else
978 (argv[0] && !strcmp (argv[0], "/bin/sh"))
979 #endif
980 && (argv[1]
981 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
982 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
983 && argv[3] == NULL)
985 free (argv[0]);
986 free ((char *) argv);
987 goto next_command;
989 #endif /* !VMS && !_AMIGA */
991 /* Tell update_goal_chain that a command has been started on behalf of
992 this target. It is important that this happens here and not in
993 reap_children (where we used to do it), because reap_children might be
994 reaping children from a different target. We want this increment to
995 guaranteedly indicate that a command was started for the dependency
996 chain (i.e., update_file recursion chain) we are processing. */
998 ++commands_started;
1000 /* If -n was given, recurse to get the next line in the sequence. */
1002 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1004 #ifndef VMS
1005 free (argv[0]);
1006 free ((char *) argv);
1007 #endif
1008 goto next_command;
1011 /* Flush the output streams so they won't have things written twice. */
1013 fflush (stdout);
1014 fflush (stderr);
1016 #ifndef VMS
1017 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1019 /* Set up a bad standard input that reads from a broken pipe. */
1021 if (bad_stdin == -1)
1023 /* Make a file descriptor that is the read end of a broken pipe.
1024 This will be used for some children's standard inputs. */
1025 int pd[2];
1026 if (pipe (pd) == 0)
1028 /* Close the write side. */
1029 (void) close (pd[1]);
1030 /* Save the read side. */
1031 bad_stdin = pd[0];
1033 /* Set the descriptor to close on exec, so it does not litter any
1034 child's descriptor table. When it is dup2'd onto descriptor 0,
1035 that descriptor will not close on exec. */
1036 CLOSE_ON_EXEC (bad_stdin);
1040 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1042 /* Decide whether to give this child the `good' standard input
1043 (one that points to the terminal or whatever), or the `bad' one
1044 that points to the read side of a broken pipe. */
1046 child->good_stdin = !good_stdin_used;
1047 if (child->good_stdin)
1048 good_stdin_used = 1;
1050 #endif /* !VMS */
1052 child->deleted = 0;
1054 #ifndef _AMIGA
1055 /* Set up the environment for the child. */
1056 if (child->environment == 0)
1057 child->environment = target_environment (child->file);
1058 #endif
1060 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1062 #ifndef VMS
1063 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1064 if (child->remote)
1066 int is_remote, id, used_stdin;
1067 if (start_remote_job (argv, child->environment,
1068 child->good_stdin ? 0 : bad_stdin,
1069 &is_remote, &id, &used_stdin))
1070 /* Don't give up; remote execution may fail for various reasons. If
1071 so, simply run the job locally. */
1072 goto run_local;
1073 else
1075 if (child->good_stdin && !used_stdin)
1077 child->good_stdin = 0;
1078 good_stdin_used = 0;
1080 child->remote = is_remote;
1081 child->pid = id;
1084 else
1085 #endif /* !VMS */
1087 /* Fork the child process. */
1089 char **parent_environ;
1091 run_local:
1092 block_sigs ();
1094 child->remote = 0;
1096 #ifdef VMS
1098 if (!child_execute_job (argv, child)) {
1099 /* Fork failed! */
1100 perror_with_name ("vfork", "");
1101 goto error;
1104 #else
1106 parent_environ = environ;
1107 child->pid = vfork ();
1108 environ = parent_environ; /* Restore value child may have clobbered. */
1109 if (child->pid == 0)
1111 /* We are the child side. */
1112 unblock_sigs ();
1114 /* If we aren't running a recursive command and we have a jobserver
1115 pipe, close it before exec'ing. */
1116 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1118 close (job_fds[0]);
1119 close (job_fds[1]);
1121 if (job_rfd >= 0)
1122 close (job_rfd);
1124 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1125 argv, child->environment);
1127 else if (child->pid < 0)
1129 /* Fork failed! */
1130 unblock_sigs ();
1131 perror_with_name ("vfork", "");
1132 goto error;
1134 #endif /* !VMS */
1137 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1138 #ifdef __MSDOS__
1140 int proc_return;
1142 block_sigs ();
1143 dos_status = 0;
1145 /* We call `system' to do the job of the SHELL, since stock DOS
1146 shell is too dumb. Our `system' knows how to handle long
1147 command lines even if pipes/redirection is needed; it will only
1148 call COMMAND.COM when its internal commands are used. */
1149 if (execute_by_shell)
1151 char *cmdline = argv[0];
1152 /* We don't have a way to pass environment to `system',
1153 so we need to save and restore ours, sigh... */
1154 char **parent_environ = environ;
1156 environ = child->environment;
1158 /* If we have a *real* shell, tell `system' to call
1159 it to do everything for us. */
1160 if (unixy_shell)
1162 /* A *real* shell on MSDOS may not support long
1163 command lines the DJGPP way, so we must use `system'. */
1164 cmdline = argv[2]; /* get past "shell -c" */
1167 dos_command_running = 1;
1168 proc_return = system (cmdline);
1169 environ = parent_environ;
1170 execute_by_shell = 0; /* for the next time */
1172 else
1174 dos_command_running = 1;
1175 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1178 /* Need to unblock signals before turning off
1179 dos_command_running, so that child's signals
1180 will be treated as such (see fatal_error_signal). */
1181 unblock_sigs ();
1182 dos_command_running = 0;
1184 /* If the child got a signal, dos_status has its
1185 high 8 bits set, so be careful not to alter them. */
1186 if (proc_return == -1)
1187 dos_status |= 0xff;
1188 else
1189 dos_status |= (proc_return & 0xff);
1190 ++dead_children;
1191 child->pid = dos_pid++;
1193 #endif /* __MSDOS__ */
1194 #ifdef _AMIGA
1195 amiga_status = MyExecute (argv);
1197 ++dead_children;
1198 child->pid = amiga_pid++;
1199 if (amiga_batch_file)
1201 amiga_batch_file = 0;
1202 DeleteFile (amiga_bname); /* Ignore errors. */
1204 #endif /* Amiga */
1205 #ifdef WINDOWS32
1207 HANDLE hPID;
1208 char* arg0;
1210 /* make UNC paths safe for CreateProcess -- backslash format */
1211 arg0 = argv[0];
1212 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1213 for ( ; arg0 && *arg0; arg0++)
1214 if (*arg0 == '/')
1215 *arg0 = '\\';
1217 /* make sure CreateProcess() has Path it needs */
1218 sync_Path_environment();
1220 hPID = process_easy(argv, child->environment);
1222 if (hPID != INVALID_HANDLE_VALUE)
1223 child->pid = (int) hPID;
1224 else {
1225 int i;
1226 unblock_sigs();
1227 fprintf(stderr,
1228 _("process_easy() failed failed to launch process (e=%d)\n"),
1229 process_last_err(hPID));
1230 for (i = 0; argv[i]; i++)
1231 fprintf(stderr, "%s ", argv[i]);
1232 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1235 #endif /* WINDOWS32 */
1236 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1238 /* We are the parent side. Set the state to
1239 say the commands are running and return. */
1241 set_command_state (child->file, cs_running);
1243 /* Free the storage used by the child's argument list. */
1244 #ifndef VMS
1245 free (argv[0]);
1246 free ((char *) argv);
1247 #endif
1249 return;
1251 error:
1252 child->file->update_status = 2;
1253 notice_finished_file (child->file);
1254 return;
1257 /* Try to start a child running.
1258 Returns nonzero if the child was started (and maybe finished), or zero if
1259 the load was too high and the child was put on the `waiting_jobs' chain. */
1261 static int
1262 start_waiting_job (c)
1263 struct child *c;
1265 struct file *f = c->file;
1267 /* If we can start a job remotely, we always want to, and don't care about
1268 the local load average. We record that the job should be started
1269 remotely in C->remote for start_job_command to test. */
1271 c->remote = start_remote_job_p (1);
1273 /* If we are running at least one job already and the load average
1274 is too high, make this one wait. */
1275 if (!c->remote && job_slots_used > 0 && load_too_high ())
1277 /* Put this child on the chain of children waiting for the load average
1278 to go down. */
1279 set_command_state (f, cs_running);
1280 c->next = waiting_jobs;
1281 waiting_jobs = c;
1282 return 0;
1285 /* Start the first command; reap_children will run later command lines. */
1286 start_job_command (c);
1288 switch (f->command_state)
1290 case cs_running:
1291 c->next = children;
1292 DB (DB_JOBS, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1293 (unsigned long int) c, c->file->name,
1294 (long) c->pid, c->remote ? _(" (remote)") : ""));
1295 children = c;
1296 /* One more job slot is in use. */
1297 ++job_slots_used;
1298 unblock_sigs ();
1299 break;
1301 case cs_not_started:
1302 /* All the command lines turned out to be empty. */
1303 f->update_status = 0;
1304 /* FALLTHROUGH */
1306 case cs_finished:
1307 notice_finished_file (f);
1308 free_child (c);
1309 break;
1311 default:
1312 assert (f->command_state == cs_finished);
1313 break;
1316 return 1;
1319 /* Create a `struct child' for FILE and start its commands running. */
1321 void
1322 new_job (file)
1323 register struct file *file;
1325 register struct commands *cmds = file->cmds;
1326 register struct child *c;
1327 char **lines;
1328 register unsigned int i;
1330 /* Let any previously decided-upon jobs that are waiting
1331 for the load to go down start before this new one. */
1332 start_waiting_jobs ();
1334 /* Reap any children that might have finished recently. */
1335 reap_children (0, 0);
1337 /* Chop the commands up into lines if they aren't already. */
1338 chop_commands (cmds);
1340 /* Expand the command lines and store the results in LINES. */
1341 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1342 for (i = 0; i < cmds->ncommand_lines; ++i)
1344 /* Collapse backslash-newline combinations that are inside variable
1345 or function references. These are left alone by the parser so
1346 that they will appear in the echoing of commands (where they look
1347 nice); and collapsed by construct_command_argv when it tokenizes.
1348 But letting them survive inside function invocations loses because
1349 we don't want the functions to see them as part of the text. */
1351 char *in, *out, *ref;
1353 /* IN points to where in the line we are scanning.
1354 OUT points to where in the line we are writing.
1355 When we collapse a backslash-newline combination,
1356 IN gets ahead of OUT. */
1358 in = out = cmds->command_lines[i];
1359 while ((ref = strchr (in, '$')) != 0)
1361 ++ref; /* Move past the $. */
1363 if (out != in)
1364 /* Copy the text between the end of the last chunk
1365 we processed (where IN points) and the new chunk
1366 we are about to process (where REF points). */
1367 bcopy (in, out, ref - in);
1369 /* Move both pointers past the boring stuff. */
1370 out += ref - in;
1371 in = ref;
1373 if (*ref == '(' || *ref == '{')
1375 char openparen = *ref;
1376 char closeparen = openparen == '(' ? ')' : '}';
1377 int count;
1378 char *p;
1380 *out++ = *in++; /* Copy OPENPAREN. */
1381 /* IN now points past the opening paren or brace.
1382 Count parens or braces until it is matched. */
1383 count = 0;
1384 while (*in != '\0')
1386 if (*in == closeparen && --count < 0)
1387 break;
1388 else if (*in == '\\' && in[1] == '\n')
1390 /* We have found a backslash-newline inside a
1391 variable or function reference. Eat it and
1392 any following whitespace. */
1394 int quoted = 0;
1395 for (p = in - 1; p > ref && *p == '\\'; --p)
1396 quoted = !quoted;
1398 if (quoted)
1399 /* There were two or more backslashes, so this is
1400 not really a continuation line. We don't collapse
1401 the quoting backslashes here as is done in
1402 collapse_continuations, because the line will
1403 be collapsed again after expansion. */
1404 *out++ = *in++;
1405 else
1407 /* Skip the backslash, newline and
1408 any following whitespace. */
1409 in = next_token (in + 2);
1411 /* Discard any preceding whitespace that has
1412 already been written to the output. */
1413 while (out > ref
1414 && isblank ((unsigned char)out[-1]))
1415 --out;
1417 /* Replace it all with a single space. */
1418 *out++ = ' ';
1421 else
1423 if (*in == openparen)
1424 ++count;
1426 *out++ = *in++;
1432 /* There are no more references in this line to worry about.
1433 Copy the remaining uninteresting text to the output. */
1434 if (out != in)
1435 strcpy (out, in);
1437 /* Finally, expand the line. */
1438 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1439 file);
1442 /* Start the command sequence, record it in a new
1443 `struct child', and add that to the chain. */
1445 c = (struct child *) xmalloc (sizeof (struct child));
1446 bzero ((char *)c, sizeof (struct child));
1447 c->file = file;
1448 c->command_lines = lines;
1449 c->sh_batch_file = NULL;
1451 /* Fetch the first command line to be run. */
1452 job_next_command (c);
1454 /* Wait for a job slot to be freed up. If we allow an infinite number
1455 don't bother; also job_slots will == 0 if we're using the jobserver. */
1457 if (job_slots != 0)
1458 while (job_slots_used == job_slots)
1459 reap_children (1, 0);
1461 #ifdef MAKE_JOBSERVER
1462 /* If we are controlling multiple jobs make sure we have a token before
1463 starting the child. */
1465 /* This can be inefficient. There's a decent chance that this job won't
1466 actually have to run any subprocesses: the command script may be empty
1467 or otherwise optimized away. It would be nice if we could defer
1468 obtaining a token until just before we need it, in start_job_command.
1469 To do that we'd need to keep track of whether we'd already obtained a
1470 token (since start_job_command is called for each line of the job, not
1471 just once). Also more thought needs to go into the entire algorithm;
1472 this is where the old parallel job code waits, so... */
1474 else if (job_fds[0] >= 0)
1475 while (1)
1477 char token;
1479 /* If we don't already have a job started, use our "free" token. */
1480 if (!children)
1481 break;
1483 /* Read a token. As long as there's no token available we'll block.
1484 If we get a SIGCHLD we'll return with EINTR. If one happened
1485 before we got here we'll return immediately with EBADF because
1486 the signal handler closes the dup'd file descriptor. */
1488 if (read (job_rfd, &token, 1) == 1)
1490 DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1491 (unsigned long int) c, c->file->name));
1492 break;
1495 if (errno != EINTR && errno != EBADF)
1496 pfatal_with_name (_("read jobs pipe"));
1498 /* Re-dup the read side of the pipe, so the signal handler can
1499 notify us if we miss a child. */
1500 if (job_rfd < 0)
1501 job_rfd = dup (job_fds[0]);
1503 /* Something's done. We don't want to block for a whole child,
1504 just reap whatever's there. */
1505 reap_children (0, 0);
1507 #endif
1509 /* The job is now primed. Start it running.
1510 (This will notice if there are in fact no commands.) */
1511 (void) start_waiting_job (c);
1513 if (job_slots == 1 || not_parallel)
1514 /* Since there is only one job slot, make things run linearly.
1515 Wait for the child to die, setting the state to `cs_finished'. */
1516 while (file->command_state == cs_running)
1517 reap_children (1, 0);
1519 return;
1522 /* Move CHILD's pointers to the next command for it to execute.
1523 Returns nonzero if there is another command. */
1525 static int
1526 job_next_command (child)
1527 struct child *child;
1529 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1531 /* There are no more lines in the expansion of this line. */
1532 if (child->command_line == child->file->cmds->ncommand_lines)
1534 /* There are no more lines to be expanded. */
1535 child->command_ptr = 0;
1536 return 0;
1538 else
1539 /* Get the next line to run. */
1540 child->command_ptr = child->command_lines[child->command_line++];
1542 return 1;
1545 static int
1546 load_too_high ()
1548 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1549 return 1;
1550 #else
1551 double load;
1553 if (max_load_average < 0)
1554 return 0;
1556 make_access ();
1557 if (getloadavg (&load, 1) != 1)
1559 static int lossage = -1;
1560 /* Complain only once for the same error. */
1561 if (lossage == -1 || errno != lossage)
1563 if (errno == 0)
1564 /* An errno value of zero means getloadavg is just unsupported. */
1565 error (NILF,
1566 _("cannot enforce load limits on this operating system"));
1567 else
1568 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1570 lossage = errno;
1571 load = 0;
1573 user_access ();
1575 return load >= max_load_average;
1576 #endif
1579 /* Start jobs that are waiting for the load to be lower. */
1581 void
1582 start_waiting_jobs ()
1584 struct child *job;
1586 if (waiting_jobs == 0)
1587 return;
1591 /* Check for recently deceased descendants. */
1592 reap_children (0, 0);
1594 /* Take a job off the waiting list. */
1595 job = waiting_jobs;
1596 waiting_jobs = job->next;
1598 /* Try to start that job. We break out of the loop as soon
1599 as start_waiting_job puts one back on the waiting list. */
1601 while (start_waiting_job (job) && waiting_jobs != 0);
1603 return;
1606 #ifndef WINDOWS32
1607 #ifdef VMS
1608 #include <descrip.h>
1609 #include <clidef.h>
1611 /* This is called as an AST when a child process dies (it won't get
1612 interrupted by anything except a higher level AST).
1614 int vmsHandleChildTerm(struct child *child)
1616 int status;
1617 register struct child *lastc, *c;
1618 int child_failed;
1620 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1622 lib$free_ef(&child->efn);
1624 (void) sigblock (fatal_signal_mask);
1626 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1628 /* Search for a child matching the deceased one. */
1629 lastc = 0;
1630 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1631 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1632 #else
1633 c = child;
1634 #endif
1636 if (child_failed && !c->noerror && !ignore_errors_flag)
1638 /* The commands failed. Write an error message,
1639 delete non-precious targets, and abort. */
1640 child_error (c->file->name, c->cstatus, 0, 0, 0);
1641 c->file->update_status = 1;
1642 delete_child_targets (c);
1644 else
1646 if (child_failed)
1648 /* The commands failed, but we don't care. */
1649 child_error (c->file->name, c->cstatus, 0, 0, 1);
1650 child_failed = 0;
1653 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1654 /* If there are more commands to run, try to start them. */
1655 start_job (c);
1657 switch (c->file->command_state)
1659 case cs_running:
1660 /* Successfully started. */
1661 break;
1663 case cs_finished:
1664 if (c->file->update_status != 0) {
1665 /* We failed to start the commands. */
1666 delete_child_targets (c);
1668 break;
1670 default:
1671 error (NILF, _("internal error: `%s' command_state"),
1672 c->file->name);
1673 abort ();
1674 break;
1676 #endif /* RECURSIVEJOBS */
1679 /* Set the state flag to say the commands have finished. */
1680 c->file->command_state = cs_finished;
1681 notice_finished_file (c->file);
1683 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1684 /* Remove the child from the chain and free it. */
1685 if (lastc == 0)
1686 children = c->next;
1687 else
1688 lastc->next = c->next;
1689 free_child (c);
1690 #endif /* RECURSIVEJOBS */
1692 /* There is now another slot open. */
1693 if (job_slots_used > 0)
1694 --job_slots_used;
1696 /* If the job failed, and the -k flag was not given, die. */
1697 if (child_failed && !keep_going_flag)
1698 die (EXIT_FAILURE);
1700 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1702 return 1;
1705 /* VMS:
1706 Spawn a process executing the command in ARGV and return its pid. */
1708 #define MAXCMDLEN 200
1710 /* local helpers to make ctrl+c and ctrl+y working, see below */
1711 #include <iodef.h>
1712 #include <libclidef.h>
1713 #include <ssdef.h>
1715 static int ctrlMask= LIB$M_CLI_CTRLY;
1716 static int oldCtrlMask;
1717 static int setupYAstTried= 0;
1718 static int pidToAbort= 0;
1719 static int chan= 0;
1721 static void reEnableAst(void) {
1722 lib$enable_ctrl (&oldCtrlMask,0);
1725 static astHandler (void) {
1726 if (pidToAbort) {
1727 sys$forcex (&pidToAbort, 0, SS$_ABORT);
1728 pidToAbort= 0;
1730 kill (getpid(),SIGQUIT);
1733 static void tryToSetupYAst(void) {
1734 $DESCRIPTOR(inputDsc,"SYS$COMMAND");
1735 int status;
1736 struct {
1737 short int status, count;
1738 int dvi;
1739 } iosb;
1741 setupYAstTried++;
1743 if (!chan) {
1744 status= sys$assign(&inputDsc,&chan,0,0);
1745 if (!(status&SS$_NORMAL)) {
1746 lib$signal(status);
1747 return;
1750 status= sys$qiow (0, chan, IO$_SETMODE|IO$M_CTRLYAST,&iosb,0,0,
1751 astHandler,0,0,0,0,0);
1752 if (status==SS$_ILLIOFUNC) {
1753 sys$dassgn(chan);
1754 #ifdef CTRLY_ENABLED_ANYWAY
1755 fprintf (stderr,
1756 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
1757 #else
1758 return;
1759 #endif
1761 if (status==SS$_NORMAL)
1762 status= iosb.status;
1763 if (!(status&SS$_NORMAL)) {
1764 lib$signal(status);
1765 return;
1768 /* called from AST handler ? */
1769 if (setupYAstTried>1)
1770 return;
1771 if (atexit(reEnableAst))
1772 fprintf (stderr,
1773 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
1774 status= lib$disable_ctrl (&ctrlMask, &oldCtrlMask);
1775 if (!(status&SS$_NORMAL)) {
1776 lib$signal(status);
1777 return;
1781 child_execute_job (argv, child)
1782 char *argv;
1783 struct child *child;
1785 int i;
1786 static struct dsc$descriptor_s cmddsc;
1787 static struct dsc$descriptor_s pnamedsc;
1788 static struct dsc$descriptor_s ifiledsc;
1789 static struct dsc$descriptor_s ofiledsc;
1790 static struct dsc$descriptor_s efiledsc;
1791 int have_redirection = 0;
1792 int have_newline = 0;
1794 int spflags = CLI$M_NOWAIT;
1795 int status;
1796 char *cmd = alloca (strlen (argv) + 512), *p, *q;
1797 char ifile[256], ofile[256], efile[256];
1798 char *comname = 0;
1799 char procname[100];
1801 /* Parse IO redirection. */
1803 ifile[0] = 0;
1804 ofile[0] = 0;
1805 efile[0] = 0;
1807 DB (DB_JOBS, ("child_execute_job (%s)\n", argv));
1809 while (isspace ((unsigned char)*argv))
1810 argv++;
1812 if (*argv == 0)
1813 return 0;
1815 sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
1816 pnamedsc.dsc$w_length = strlen(procname);
1817 pnamedsc.dsc$a_pointer = procname;
1818 pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
1819 pnamedsc.dsc$b_class = DSC$K_CLASS_S;
1821 /* Handle comments and redirection. */
1822 for (p = argv, q = cmd; *p; p++, q++)
1824 switch (*p)
1826 case '#':
1827 *p-- = 0;
1828 *q-- = 0;
1829 break;
1830 case '\\':
1831 p++;
1832 if (*p == '\n')
1833 p++;
1834 if (isspace ((unsigned char)*p))
1836 do { p++; } while (isspace ((unsigned char)*p));
1837 p--;
1839 *q = *p;
1840 break;
1841 case '<':
1842 p = vms_redirect (&ifiledsc, ifile, p);
1843 *q = ' ';
1844 have_redirection = 1;
1845 break;
1846 case '>':
1847 have_redirection = 1;
1848 if (*(p-1) == '2')
1850 q--;
1851 if (strncmp (p, ">&1", 3) == 0)
1853 p += 3;
1854 strcpy (efile, "sys$output");
1855 efiledsc.dsc$w_length = strlen(efile);
1856 efiledsc.dsc$a_pointer = efile;
1857 efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
1858 efiledsc.dsc$b_class = DSC$K_CLASS_S;
1860 else
1862 p = vms_redirect (&efiledsc, efile, p);
1865 else
1867 p = vms_redirect (&ofiledsc, ofile, p);
1869 *q = ' ';
1870 break;
1871 case '\n':
1872 have_newline = 1;
1873 default:
1874 *q = *p;
1875 break;
1878 *q = *p;
1880 if (strncmp (cmd, "builtin_", 8) == 0)
1882 child->pid = 270163;
1883 child->efn = 0;
1884 child->cstatus = 1;
1886 DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));
1888 p = cmd + 8;
1890 if ((*(p) == 'c')
1891 && (*(p+1) == 'd')
1892 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
1894 p += 3;
1895 while ((*p == ' ') || (*p == '\t'))
1896 p++;
1897 DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
1898 if (chdir (p))
1899 return 0;
1900 else
1901 return 1;
1903 else if ((*(p) == 'r')
1904 && (*(p+1) == 'm')
1905 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
1907 int in_arg;
1909 /* rm */
1910 p += 3;
1911 while ((*p == ' ') || (*p == '\t'))
1912 p++;
1913 in_arg = 1;
1915 DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
1916 while (*p)
1918 switch (*p)
1920 case ' ':
1921 case '\t':
1922 if (in_arg)
1924 *p++ = ';';
1925 in_arg = 0;
1927 break;
1928 default:
1929 break;
1931 p++;
1934 else
1936 printf(_("Unknown builtin command '%s'\n"), cmd);
1937 fflush(stdout);
1938 return 0;
1942 /* Create a *.com file if either the command is too long for
1943 lib$spawn, or the command contains a newline, or if redirection
1944 is desired. Forcing commands with newlines into DCLs allows to
1945 store search lists on user mode logicals. */
1947 if (strlen (cmd) > MAXCMDLEN
1948 || (have_redirection != 0)
1949 || (have_newline != 0))
1951 FILE *outfile;
1952 char c;
1953 char *sep;
1954 int alevel = 0; /* apostrophe level */
1956 if (strlen (cmd) == 0)
1958 printf (_("Error, empty command\n"));
1959 fflush (stdout);
1960 return 0;
1963 outfile = open_tmpfile (&comname, "sys$scratch:CMDXXXXXX.COM");
1964 if (outfile == 0)
1965 pfatal_with_name (_("fopen (temporary file)"));
1967 if (ifile[0])
1969 fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
1970 DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
1971 ifiledsc.dsc$w_length = 0;
1974 if (efile[0])
1976 fprintf (outfile, "$ define sys$error %s\n", efile);
1977 DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
1978 efiledsc.dsc$w_length = 0;
1981 if (ofile[0])
1983 fprintf (outfile, "$ define sys$output %s\n", ofile);
1984 DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
1985 ofiledsc.dsc$w_length = 0;
1988 p = sep = q = cmd;
1989 for (c = '\n'; c; c = *q++)
1991 switch (c)
1993 case '\n':
1994 /* At a newline, skip any whitespace around a leading $
1995 from the command and issue exactly one $ into the DCL. */
1996 while (isspace ((unsigned char)*p))
1997 p++;
1998 if (*p == '$')
1999 p++;
2000 while (isspace ((unsigned char)*p))
2001 p++;
2002 fwrite (p, 1, q - p, outfile);
2003 fputc ('$', outfile);
2004 fputc (' ', outfile);
2005 /* Reset variables. */
2006 p = sep = q;
2007 break;
2009 /* Nice places for line breaks are after strings, after
2010 comma or space and before slash. */
2011 case '"':
2012 q = handle_apos (q + 1);
2013 sep = q;
2014 break;
2015 case ',':
2016 case ' ':
2017 sep = q;
2018 break;
2019 case '/':
2020 case '\0':
2021 sep = q - 1;
2022 break;
2023 default:
2024 break;
2026 if (sep - p > 78)
2028 /* Enough stuff for a line. */
2029 fwrite (p, 1, sep - p, outfile);
2030 p = sep;
2031 if (*sep)
2033 /* The command continues. */
2034 fputc ('-', outfile);
2036 fputc ('\n', outfile);
2040 fwrite (p, 1, q - p, outfile);
2041 fputc ('\n', outfile);
2043 fclose (outfile);
2045 sprintf (cmd, "$ @%s", comname);
2047 DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
2050 cmddsc.dsc$w_length = strlen(cmd);
2051 cmddsc.dsc$a_pointer = cmd;
2052 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
2053 cmddsc.dsc$b_class = DSC$K_CLASS_S;
2055 child->efn = 0;
2056 while (child->efn < 32 || child->efn > 63)
2058 status = lib$get_ef ((unsigned long *)&child->efn);
2059 if (!(status & 1))
2060 return 0;
2063 sys$clref (child->efn);
2065 vms_jobsefnmask |= (1 << (child->efn - 32));
2068 LIB$SPAWN [command-string]
2069 [,input-file]
2070 [,output-file]
2071 [,flags]
2072 [,process-name]
2073 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2074 [,AST-address] [,varying-AST-argument]
2075 [,prompt-string] [,cli] [,table]
2078 #ifndef DONTWAITFORCHILD
2080 * Code to make ctrl+c and ctrl+y working.
2081 * The problem starts with the synchronous case where after lib$spawn is
2082 * called any input will go to the child. But with input re-directed,
2083 * both control characters won't make it to any of the programs, neither
2084 * the spawning nor to the spawned one. Hence the caller needs to spawn
2085 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2086 * has to follow to simulate the wanted synchronous behaviour.
2087 * The next problem is ctrl+y which isn't caught by the crtl and
2088 * therefore isn't converted to SIGQUIT (for a signal handler which is
2089 * already established). The only way to catch ctrl+y, is an AST
2090 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2091 * disabled, otherwise it will handle it. Not to mention the previous
2092 * ctrl+y handling of DCL needs to be re-established before make exits.
2093 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2094 * make it to the signal handler after the child "normally" terminates.
2095 * This isn't enough. It seems reasonable for simple command lines like
2096 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2097 * spawning make. Therefore we need to abort the process in the AST.
2099 * Prior to the spawn it is checked if an AST is already set up for
2100 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2101 * this will work except if make is run in a batch environment, but there
2102 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2103 * is disabled and an exit handler is established to re-enable it.
2104 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2105 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2106 * the already established handler and will bring us back to common code.
2107 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2108 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2109 * which the crtl converts to SIGINT and which is caught by the common
2110 * signal handler. Because signals were blocked before entering this code
2111 * sys$waitfr will always complete and the SIGQUIT will be processed after
2112 * it (after termination of the current block, somewhere in common code).
2113 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2114 * current command completes. Anyway it's better than nothing :-)
2117 if (!setupYAstTried)
2118 tryToSetupYAst();
2119 status = lib$spawn (&cmddsc, /* cmd-string */
2120 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file */
2121 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
2122 &spflags, /* flags */
2123 &pnamedsc, /* proc name */
2124 &child->pid, &child->cstatus, &child->efn,
2125 0, 0,
2126 0, 0, 0);
2127 pidToAbort= child->pid;
2128 status= sys$waitfr (child->efn);
2129 pidToAbort= 0;
2130 vmsHandleChildTerm(child);
2131 #else
2132 status = lib$spawn (&cmddsc,
2133 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
2134 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
2135 &spflags,
2136 &pnamedsc,
2137 &child->pid, &child->cstatus, &child->efn,
2138 vmsHandleChildTerm, child,
2139 0, 0, 0);
2140 #endif
2142 if (!(status & 1))
2144 printf (_("Error spawning, %d\n") ,status);
2145 fflush (stdout);
2148 if (comname && !ISDB (DB_JOBS))
2149 unlink (comname);
2151 return (status & 1);
2154 #else /* !VMS */
2156 #if !defined (_AMIGA) && !defined (__MSDOS__)
2157 /* UNIX:
2158 Replace the current process with one executing the command in ARGV.
2159 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2160 the environment of the new program. This function does not return. */
2162 void
2163 child_execute_job (stdin_fd, stdout_fd, argv, envp)
2164 int stdin_fd, stdout_fd;
2165 char **argv, **envp;
2167 if (stdin_fd != 0)
2168 (void) dup2 (stdin_fd, 0);
2169 if (stdout_fd != 1)
2170 (void) dup2 (stdout_fd, 1);
2171 if (stdin_fd != 0)
2172 (void) close (stdin_fd);
2173 if (stdout_fd != 1)
2174 (void) close (stdout_fd);
2176 /* Run the command. */
2177 exec_command (argv, envp);
2179 #endif /* !AMIGA && !__MSDOS__ */
2180 #endif /* !VMS */
2181 #endif /* !WINDOWS32 */
2183 #ifndef _AMIGA
2184 /* Replace the current process with one running the command in ARGV,
2185 with environment ENVP. This function does not return. */
2187 void
2188 exec_command (argv, envp)
2189 char **argv, **envp;
2191 #ifdef VMS
2192 /* to work around a problem with signals and execve: ignore them */
2193 #ifdef SIGCHLD
2194 signal (SIGCHLD,SIG_IGN);
2195 #endif
2196 /* Run the program. */
2197 execve (argv[0], argv, envp);
2198 perror_with_name ("execve: ", argv[0]);
2199 _exit (EXIT_FAILURE);
2200 #else
2201 #ifdef WINDOWS32
2202 HANDLE hPID;
2203 HANDLE hWaitPID;
2204 int err = 0;
2205 int exit_code = EXIT_FAILURE;
2207 /* make sure CreateProcess() has Path it needs */
2208 sync_Path_environment();
2210 /* launch command */
2211 hPID = process_easy(argv, envp);
2213 /* make sure launch ok */
2214 if (hPID == INVALID_HANDLE_VALUE)
2216 int i;
2217 fprintf(stderr,
2218 _("process_easy() failed failed to launch process (e=%d)\n"),
2219 process_last_err(hPID));
2220 for (i = 0; argv[i]; i++)
2221 fprintf(stderr, "%s ", argv[i]);
2222 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2223 exit(EXIT_FAILURE);
2226 /* wait and reap last child */
2227 while (hWaitPID = process_wait_for_any())
2229 /* was an error found on this process? */
2230 err = process_last_err(hWaitPID);
2232 /* get exit data */
2233 exit_code = process_exit_code(hWaitPID);
2235 if (err)
2236 fprintf(stderr, "make (e=%d, rc=%d): %s",
2237 err, exit_code, map_windows32_error_to_string(err));
2239 /* cleanup process */
2240 process_cleanup(hWaitPID);
2242 /* expect to find only last pid, warn about other pids reaped */
2243 if (hWaitPID == hPID)
2244 break;
2245 else
2246 fprintf(stderr,
2247 _("make reaped child pid %d, still waiting for pid %d\n"),
2248 hWaitPID, hPID);
2251 /* return child's exit code as our exit code */
2252 exit(exit_code);
2254 #else /* !WINDOWS32 */
2256 /* Be the user, permanently. */
2257 child_access ();
2259 /* Run the program. */
2260 environ = envp;
2261 execvp (argv[0], argv);
2263 switch (errno)
2265 case ENOENT:
2266 error (NILF, _("%s: Command not found"), argv[0]);
2267 break;
2268 case ENOEXEC:
2270 /* The file is not executable. Try it as a shell script. */
2271 extern char *getenv ();
2272 char *shell;
2273 char **new_argv;
2274 int argc;
2276 shell = getenv ("SHELL");
2277 if (shell == 0)
2278 shell = default_shell;
2280 argc = 1;
2281 while (argv[argc] != 0)
2282 ++argc;
2284 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
2285 new_argv[0] = shell;
2286 new_argv[1] = argv[0];
2287 while (argc > 0)
2289 new_argv[1 + argc] = argv[argc];
2290 --argc;
2293 execvp (shell, new_argv);
2294 if (errno == ENOENT)
2295 error (NILF, _("%s: Shell program not found"), shell);
2296 else
2297 perror_with_name ("execvp: ", shell);
2298 break;
2301 default:
2302 perror_with_name ("execvp: ", argv[0]);
2303 break;
2306 _exit (127);
2307 #endif /* !WINDOWS32 */
2308 #endif /* !VMS */
2310 #else /* On Amiga */
2311 void exec_command (argv)
2312 char **argv;
2314 MyExecute (argv);
2317 void clean_tmp (void)
2319 DeleteFile (amiga_bname);
2322 #endif /* On Amiga */
2324 #ifndef VMS
2325 /* Figure out the argument list necessary to run LINE as a command. Try to
2326 avoid using a shell. This routine handles only ' quoting, and " quoting
2327 when no backslash, $ or ` characters are seen in the quotes. Starting
2328 quotes may be escaped with a backslash. If any of the characters in
2329 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2330 is the first word of a line, the shell is used.
2332 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2333 If *RESTP is NULL, newlines will be ignored.
2335 SHELL is the shell to use, or nil to use the default shell.
2336 IFS is the value of $IFS, or nil (meaning the default). */
2338 static char **
2339 construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr)
2340 char *line, **restp;
2341 char *shell, *ifs;
2342 char **batch_filename_ptr;
2344 #ifdef __MSDOS__
2345 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2346 We call `system' for anything that requires ``slow'' processing,
2347 because DOS shells are too dumb. When $SHELL points to a real
2348 (unix-style) shell, `system' just calls it to do everything. When
2349 $SHELL points to a DOS shell, `system' does most of the work
2350 internally, calling the shell only for its internal commands.
2351 However, it looks on the $PATH first, so you can e.g. have an
2352 external command named `mkdir'.
2354 Since we call `system', certain characters and commands below are
2355 actually not specific to COMMAND.COM, but to the DJGPP implementation
2356 of `system'. In particular:
2358 The shell wildcard characters are in DOS_CHARS because they will
2359 not be expanded if we call the child via `spawnXX'.
2361 The `;' is in DOS_CHARS, because our `system' knows how to run
2362 multiple commands on a single line.
2364 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2365 won't have to tell one from another and have one more set of
2366 commands and special characters. */
2367 static char sh_chars_dos[] = "*?[];|<>%^&()";
2368 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2369 "copy", "ctty", "date", "del", "dir", "echo",
2370 "erase", "exit", "for", "goto", "if", "md",
2371 "mkdir", "path", "pause", "prompt", "rd",
2372 "rmdir", "rem", "ren", "rename", "set",
2373 "shift", "time", "type", "ver", "verify",
2374 "vol", ":", 0 };
2376 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2377 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2378 "logout", "set", "umask", "wait", "while",
2379 "for", "case", "if", ":", ".", "break",
2380 "continue", "export", "read", "readonly",
2381 "shift", "times", "trap", "switch", "unset",
2382 0 };
2384 char *sh_chars;
2385 char **sh_cmds;
2386 #else
2387 #ifdef _AMIGA
2388 static char sh_chars[] = "#;\"|<>()?*$`";
2389 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2390 "rename", "set", "setenv", "date", "makedir",
2391 "skip", "else", "endif", "path", "prompt",
2392 "unset", "unsetenv", "version",
2393 0 };
2394 #else
2395 #ifdef WINDOWS32
2396 static char sh_chars_dos[] = "\"|&<>";
2397 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2398 "copy", "ctty", "date", "del", "dir", "echo",
2399 "erase", "exit", "for", "goto", "if", "if", "md",
2400 "mkdir", "path", "pause", "prompt", "rd", "rem",
2401 "ren", "rename", "rmdir", "set", "shift", "time",
2402 "type", "ver", "verify", "vol", ":", 0 };
2403 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2404 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2405 "logout", "set", "umask", "wait", "while", "for",
2406 "case", "if", ":", ".", "break", "continue",
2407 "export", "read", "readonly", "shift", "times",
2408 "trap", "switch", "test",
2409 #ifdef BATCH_MODE_ONLY_SHELL
2410 "echo",
2411 #endif
2412 0 };
2413 char* sh_chars;
2414 char** sh_cmds;
2415 #else /* WINDOWS32 */
2416 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
2417 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
2418 "logout", "set", "umask", "wait", "while", "for",
2419 "case", "if", ":", ".", "break", "continue",
2420 "export", "read", "readonly", "shift", "times",
2421 "trap", "switch", 0 };
2422 #endif /* WINDOWS32 */
2423 #endif /* Amiga */
2424 #endif /* __MSDOS__ */
2425 register int i;
2426 register char *p;
2427 register char *ap;
2428 char *end;
2429 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2430 char **new_argv = 0;
2431 #ifdef WINDOWS32
2432 int slow_flag = 0;
2434 if (no_default_sh_exe) {
2435 sh_cmds = sh_cmds_dos;
2436 sh_chars = sh_chars_dos;
2437 } else {
2438 sh_cmds = sh_cmds_sh;
2439 sh_chars = sh_chars_sh;
2441 #endif /* WINDOWS32 */
2443 if (restp != NULL)
2444 *restp = NULL;
2446 /* Make sure not to bother processing an empty line. */
2447 while (isblank ((unsigned char)*line))
2448 ++line;
2449 if (*line == '\0')
2450 return 0;
2452 /* See if it is safe to parse commands internally. */
2453 if (shell == 0)
2454 shell = default_shell;
2455 #ifdef WINDOWS32
2456 else if (strcmp (shell, default_shell))
2458 char *s1 = _fullpath(NULL, shell, 0);
2459 char *s2 = _fullpath(NULL, default_shell, 0);
2461 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2463 if (s1)
2464 free (s1);
2465 if (s2)
2466 free (s2);
2468 if (slow_flag)
2469 goto slow;
2470 #else /* not WINDOWS32 */
2471 #ifdef __MSDOS__
2472 else if (stricmp (shell, default_shell))
2474 extern int _is_unixy_shell (const char *_path);
2476 message (1, _("$SHELL changed (was `%s', now `%s')"), default_shell, shell);
2477 unixy_shell = _is_unixy_shell (shell);
2478 default_shell = shell;
2480 if (unixy_shell)
2482 sh_chars = sh_chars_sh;
2483 sh_cmds = sh_cmds_sh;
2485 else
2487 sh_chars = sh_chars_dos;
2488 sh_cmds = sh_cmds_dos;
2490 #else /* not __MSDOS__ */
2491 else if (strcmp (shell, default_shell))
2492 goto slow;
2493 #endif /* not __MSDOS__ */
2494 #endif /* not WINDOWS32 */
2496 if (ifs != 0)
2497 for (ap = ifs; *ap != '\0'; ++ap)
2498 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2499 goto slow;
2501 i = strlen (line) + 1;
2503 /* More than 1 arg per character is impossible. */
2504 new_argv = (char **) xmalloc (i * sizeof (char *));
2506 /* All the args can fit in a buffer as big as LINE is. */
2507 ap = new_argv[0] = (char *) xmalloc (i);
2508 end = ap + i;
2510 /* I is how many complete arguments have been found. */
2511 i = 0;
2512 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2513 for (p = line; *p != '\0'; ++p)
2515 if (ap > end)
2516 abort ();
2518 if (instring)
2520 string_char:
2521 /* Inside a string, just copy any char except a closing quote
2522 or a backslash-newline combination. */
2523 if (*p == instring)
2525 instring = 0;
2526 if (ap == new_argv[0] || *(ap-1) == '\0')
2527 last_argument_was_empty = 1;
2529 else if (*p == '\\' && p[1] == '\n')
2530 goto swallow_escaped_newline;
2531 else if (*p == '\n' && restp != NULL)
2533 /* End of the command line. */
2534 *restp = p;
2535 goto end_of_line;
2537 /* Backslash, $, and ` are special inside double quotes.
2538 If we see any of those, punt.
2539 But on MSDOS, if we use COMMAND.COM, double and single
2540 quotes have the same effect. */
2541 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2542 goto slow;
2543 else
2544 *ap++ = *p;
2546 else if (strchr (sh_chars, *p) != 0)
2547 /* Not inside a string, but it's a special char. */
2548 goto slow;
2549 #ifdef __MSDOS__
2550 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2551 /* `...' is a wildcard in DJGPP. */
2552 goto slow;
2553 #endif
2554 else
2555 /* Not a special char. */
2556 switch (*p)
2558 case '=':
2559 /* Equals is a special character in leading words before the
2560 first word with no equals sign in it. This is not the case
2561 with sh -k, but we never get here when using nonstandard
2562 shell flags. */
2563 if (! seen_nonequals && unixy_shell)
2564 goto slow;
2565 word_has_equals = 1;
2566 *ap++ = '=';
2567 break;
2569 case '\\':
2570 /* Backslash-newline combinations are eaten. */
2571 if (p[1] == '\n')
2573 swallow_escaped_newline:
2575 /* Eat the backslash, the newline, and following whitespace,
2576 replacing it all with a single space. */
2577 p += 2;
2579 /* If there is a tab after a backslash-newline,
2580 remove it from the source line which will be echoed,
2581 since it was most likely used to line
2582 up the continued line with the previous one. */
2583 if (*p == '\t')
2584 /* Note these overlap and strcpy() is undefined for
2585 overlapping objects in ANSI C. The strlen() _IS_ right,
2586 since we need to copy the nul byte too. */
2587 bcopy (p + 1, p, strlen (p));
2589 if (instring)
2590 goto string_char;
2591 else
2593 if (ap != new_argv[i])
2594 /* Treat this as a space, ending the arg.
2595 But if it's at the beginning of the arg, it should
2596 just get eaten, rather than becoming an empty arg. */
2597 goto end_of_arg;
2598 else
2599 p = next_token (p) - 1;
2602 else if (p[1] != '\0')
2604 #if defined(__MSDOS__) || defined(WINDOWS32)
2605 /* Only remove backslashes before characters special
2606 to Unixy shells. All other backslashes are copied
2607 verbatim, since they are probably DOS-style
2608 directory separators. This still leaves a small
2609 window for problems, but at least it should work
2610 for the vast majority of naive users. */
2612 #ifdef __MSDOS__
2613 /* A dot is only special as part of the "..."
2614 wildcard. */
2615 if (strneq (p + 1, ".\\.\\.", 5))
2617 *ap++ = '.';
2618 *ap++ = '.';
2619 p += 4;
2621 else
2622 #endif
2623 if (p[1] != '\\' && p[1] != '\''
2624 && !isspace ((unsigned char)p[1])
2625 && (strchr (sh_chars_sh, p[1]) == 0))
2626 /* back up one notch, to copy the backslash */
2627 --p;
2629 #endif /* __MSDOS__ || WINDOWS32 */
2630 /* Copy and skip the following char. */
2631 *ap++ = *++p;
2633 break;
2635 case '\'':
2636 case '"':
2637 instring = *p;
2638 break;
2640 case '\n':
2641 if (restp != NULL)
2643 /* End of the command line. */
2644 *restp = p;
2645 goto end_of_line;
2647 else
2648 /* Newlines are not special. */
2649 *ap++ = '\n';
2650 break;
2652 case ' ':
2653 case '\t':
2654 end_of_arg:
2655 /* We have the end of an argument.
2656 Terminate the text of the argument. */
2657 *ap++ = '\0';
2658 new_argv[++i] = ap;
2659 last_argument_was_empty = 0;
2661 /* Update SEEN_NONEQUALS, which tells us if every word
2662 heretofore has contained an `='. */
2663 seen_nonequals |= ! word_has_equals;
2664 if (word_has_equals && ! seen_nonequals)
2665 /* An `=' in a word before the first
2666 word without one is magical. */
2667 goto slow;
2668 word_has_equals = 0; /* Prepare for the next word. */
2670 /* If this argument is the command name,
2671 see if it is a built-in shell command.
2672 If so, have the shell handle it. */
2673 if (i == 1)
2675 register int j;
2676 for (j = 0; sh_cmds[j] != 0; ++j)
2677 if (streq (sh_cmds[j], new_argv[0]))
2678 goto slow;
2681 /* Ignore multiple whitespace chars. */
2682 p = next_token (p);
2683 /* Next iteration should examine the first nonwhite char. */
2684 --p;
2685 break;
2687 default:
2688 *ap++ = *p;
2689 break;
2692 end_of_line:
2694 if (instring)
2695 /* Let the shell deal with an unterminated quote. */
2696 goto slow;
2698 /* Terminate the last argument and the argument list. */
2700 *ap = '\0';
2701 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2702 ++i;
2703 new_argv[i] = 0;
2705 if (i == 1)
2707 register int j;
2708 for (j = 0; sh_cmds[j] != 0; ++j)
2709 if (streq (sh_cmds[j], new_argv[0]))
2710 goto slow;
2713 if (new_argv[0] == 0)
2714 /* Line was empty. */
2715 return 0;
2716 else
2717 return new_argv;
2719 slow:;
2720 /* We must use the shell. */
2722 if (new_argv != 0)
2724 /* Free the old argument list we were working on. */
2725 free (new_argv[0]);
2726 free ((void *)new_argv);
2729 #ifdef __MSDOS__
2730 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2731 #endif
2733 #ifdef _AMIGA
2735 char *ptr;
2736 char *buffer;
2737 char *dptr;
2739 buffer = (char *)xmalloc (strlen (line)+1);
2741 ptr = line;
2742 for (dptr=buffer; *ptr; )
2744 if (*ptr == '\\' && ptr[1] == '\n')
2745 ptr += 2;
2746 else if (*ptr == '@') /* Kludge: multiline commands */
2748 ptr += 2;
2749 *dptr++ = '\n';
2751 else
2752 *dptr++ = *ptr++;
2754 *dptr = 0;
2756 new_argv = (char **) xmalloc (2 * sizeof (char *));
2757 new_argv[0] = buffer;
2758 new_argv[1] = 0;
2760 #else /* Not Amiga */
2761 #ifdef WINDOWS32
2763 * Not eating this whitespace caused things like
2765 * sh -c "\n"
2767 * which gave the shell fits. I think we have to eat
2768 * whitespace here, but this code should be considered
2769 * suspicious if things start failing....
2772 /* Make sure not to bother processing an empty line. */
2773 while (isspace ((unsigned char)*line))
2774 ++line;
2775 if (*line == '\0')
2776 return 0;
2777 #endif /* WINDOWS32 */
2779 /* SHELL may be a multi-word command. Construct a command line
2780 "SHELL -c LINE", with all special chars in LINE escaped.
2781 Then recurse, expanding this command line to get the final
2782 argument list. */
2784 unsigned int shell_len = strlen (shell);
2785 #ifndef VMS
2786 static char minus_c[] = " -c ";
2787 #else
2788 static char minus_c[] = "";
2789 #endif
2790 unsigned int line_len = strlen (line);
2792 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2793 + (line_len * 2) + 1);
2794 char *command_ptr = NULL; /* used for batch_mode_shell mode */
2796 ap = new_line;
2797 bcopy (shell, ap, shell_len);
2798 ap += shell_len;
2799 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2800 ap += sizeof (minus_c) - 1;
2801 command_ptr = ap;
2802 for (p = line; *p != '\0'; ++p)
2804 if (restp != NULL && *p == '\n')
2806 *restp = p;
2807 break;
2809 else if (*p == '\\' && p[1] == '\n')
2811 /* Eat the backslash, the newline, and following whitespace,
2812 replacing it all with a single space (which is escaped
2813 from the shell). */
2814 p += 2;
2816 /* If there is a tab after a backslash-newline,
2817 remove it from the source line which will be echoed,
2818 since it was most likely used to line
2819 up the continued line with the previous one. */
2820 if (*p == '\t')
2821 bcopy (p + 1, p, strlen (p));
2823 p = next_token (p);
2824 --p;
2825 if (unixy_shell && !batch_mode_shell)
2826 *ap++ = '\\';
2827 *ap++ = ' ';
2828 continue;
2831 /* DOS shells don't know about backslash-escaping. */
2832 if (unixy_shell && !batch_mode_shell &&
2833 (*p == '\\' || *p == '\'' || *p == '"'
2834 || isspace ((unsigned char)*p)
2835 || strchr (sh_chars, *p) != 0))
2836 *ap++ = '\\';
2837 #ifdef __MSDOS__
2838 else if (unixy_shell && strneq (p, "...", 3))
2840 /* The case of `...' wildcard again. */
2841 strcpy (ap, "\\.\\.\\");
2842 ap += 5;
2843 p += 2;
2845 #endif
2846 *ap++ = *p;
2848 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2849 /* Line was empty. */
2850 return 0;
2851 *ap = '\0';
2853 #ifdef WINDOWS32
2854 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2855 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2856 cases, run commands via a script file. */
2857 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2858 FILE* batch = NULL;
2859 int id = GetCurrentProcessId();
2860 PATH_VAR(fbuf);
2861 char* fname = NULL;
2863 /* create a file name */
2864 sprintf(fbuf, "make%d", id);
2865 fname = tempnam(".", fbuf);
2867 /* create batch file name */
2868 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
2869 strcpy(*batch_filename_ptr, fname);
2871 /* make sure path name is in DOS backslash format */
2872 if (!unixy_shell) {
2873 fname = *batch_filename_ptr;
2874 for (i = 0; fname[i] != '\0'; ++i)
2875 if (fname[i] == '/')
2876 fname[i] = '\\';
2877 strcat(*batch_filename_ptr, ".bat");
2878 } else {
2879 strcat(*batch_filename_ptr, ".sh");
2882 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
2883 *batch_filename_ptr));
2885 /* create batch file to execute command */
2886 batch = fopen (*batch_filename_ptr, "w");
2887 if (!unixy_shell)
2888 fputs ("@echo off\n", batch);
2889 fputs (command_ptr, batch);
2890 fputc ('\n', batch);
2891 fclose (batch);
2893 /* create argv */
2894 new_argv = (char **) xmalloc(3 * sizeof (char *));
2895 if (unixy_shell) {
2896 new_argv[0] = xstrdup (shell);
2897 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2898 } else {
2899 new_argv[0] = xstrdup (*batch_filename_ptr);
2900 new_argv[1] = NULL;
2902 new_argv[2] = NULL;
2903 } else
2904 #endif /* WINDOWS32 */
2905 if (unixy_shell)
2906 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2907 (char *) 0, (char *) 0,
2908 (char **) 0);
2909 #ifdef __MSDOS__
2910 else
2912 /* With MSDOS shells, we must construct the command line here
2913 instead of recursively calling ourselves, because we
2914 cannot backslash-escape the special characters (see above). */
2915 new_argv = (char **) xmalloc (sizeof (char *));
2916 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
2917 new_argv[0] = xmalloc (line_len + 1);
2918 strncpy (new_argv[0],
2919 new_line + shell_len + sizeof (minus_c) - 1, line_len);
2920 new_argv[0][line_len] = '\0';
2922 #else
2923 else
2924 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
2925 __FILE__, __LINE__);
2926 #endif
2928 #endif /* ! AMIGA */
2930 return new_argv;
2932 #endif /* !VMS */
2934 /* Figure out the argument list necessary to run LINE as a command. Try to
2935 avoid using a shell. This routine handles only ' quoting, and " quoting
2936 when no backslash, $ or ` characters are seen in the quotes. Starting
2937 quotes may be escaped with a backslash. If any of the characters in
2938 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2939 is the first word of a line, the shell is used.
2941 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2942 If *RESTP is NULL, newlines will be ignored.
2944 FILE is the target whose commands these are. It is used for
2945 variable expansion for $(SHELL) and $(IFS). */
2947 char **
2948 construct_command_argv (line, restp, file, batch_filename_ptr)
2949 char *line, **restp;
2950 struct file *file;
2951 char** batch_filename_ptr;
2953 char *shell, *ifs;
2954 char **argv;
2956 #ifdef VMS
2957 char *cptr;
2958 int argc;
2960 argc = 0;
2961 cptr = line;
2962 for (;;)
2964 while ((*cptr != 0)
2965 && (isspace ((unsigned char)*cptr)))
2966 cptr++;
2967 if (*cptr == 0)
2968 break;
2969 while ((*cptr != 0)
2970 && (!isspace((unsigned char)*cptr)))
2971 cptr++;
2972 argc++;
2975 argv = (char **)malloc (argc * sizeof (char *));
2976 if (argv == 0)
2977 abort ();
2979 cptr = line;
2980 argc = 0;
2981 for (;;)
2983 while ((*cptr != 0)
2984 && (isspace ((unsigned char)*cptr)))
2985 cptr++;
2986 if (*cptr == 0)
2987 break;
2988 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
2989 argv[argc++] = cptr;
2990 while ((*cptr != 0)
2991 && (!isspace((unsigned char)*cptr)))
2992 cptr++;
2993 if (*cptr != 0)
2994 *cptr++ = 0;
2996 #else
2998 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
2999 int save = warn_undefined_variables_flag;
3000 warn_undefined_variables_flag = 0;
3002 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3003 #ifdef WINDOWS32
3005 * Convert to forward slashes so that construct_command_argv_internal()
3006 * is not confused.
3008 if (shell) {
3009 char *p = w32ify(shell, 0);
3010 strcpy(shell, p);
3012 #endif
3013 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3015 warn_undefined_variables_flag = save;
3018 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
3020 free (shell);
3021 free (ifs);
3022 #endif /* !VMS */
3023 return argv;
3026 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3028 dup2 (old, new)
3029 int old, new;
3031 int fd;
3033 (void) close (new);
3034 fd = dup (old);
3035 if (fd != new)
3037 (void) close (fd);
3038 errno = EMFILE;
3039 return -1;
3042 return fd;
3044 #endif /* !HAPE_DUP2 && !_AMIGA */