Fix bug #2892.
[make/kirr.git] / job.c
blobb0832146f5d48c2338ddc2b3852be704167571af
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
36 char *default_shell = "sh.exe";
37 int no_default_sh_exe = 1;
38 int batch_mode_shell = 1;
40 #elif defined (_AMIGA)
42 char default_shell[] = "";
43 extern int MyExecute (char **);
44 int batch_mode_shell = 0;
46 #elif defined (__MSDOS__)
48 /* The default shell is a pointer so we can change it if Makefile
49 says so. It is without an explicit path so we get a chance
50 to search the $PATH for it (since MSDOS doesn't have standard
51 directories we could trust). */
52 char *default_shell = "command.com";
53 int batch_mode_shell = 0;
55 #elif defined (__EMX__)
57 const char *default_shell = "/bin/sh";
58 int batch_mode_shell = 0;
60 #elif defined (VMS)
62 # include <descrip.h>
63 char default_shell[] = "";
64 int batch_mode_shell = 0;
66 #else
68 char default_shell[] = "/bin/sh";
69 int batch_mode_shell = 0;
71 #endif
73 #ifdef __MSDOS__
74 # include <process.h>
75 static int execute_by_shell;
76 static int dos_pid = 123;
77 int dos_status;
78 int dos_command_running;
79 #endif /* __MSDOS__ */
81 #ifdef _AMIGA
82 # include <proto/dos.h>
83 static int amiga_pid = 123;
84 static int amiga_status;
85 static char amiga_bname[32];
86 static int amiga_batch_file;
87 #endif /* Amiga. */
89 #ifdef VMS
90 # ifndef __GNUC__
91 # include <processes.h>
92 # endif
93 # include <starlet.h>
94 # include <lib$routines.h>
95 #endif
97 #ifdef WINDOWS32
98 # include <windows.h>
99 # include <io.h>
100 # include <process.h>
101 # include "sub_proc.h"
102 # include "w32err.h"
103 # include "pathstuff.h"
104 #endif /* WINDOWS32 */
106 #ifdef __EMX__
107 # include <sys/file.h>
108 #endif
110 #if defined (HAVE_SYS_WAIT_H) || defined (HAVE_UNION_WAIT)
111 # include <sys/wait.h>
112 #endif
114 #ifdef HAVE_WAITPID
115 # define WAIT_NOHANG(status) waitpid (-1, (status), WNOHANG)
116 #else /* Don't have waitpid. */
117 # ifdef HAVE_WAIT3
118 # ifndef wait3
119 extern int wait3 ();
120 # endif
121 # define WAIT_NOHANG(status) wait3 ((status), WNOHANG, (struct rusage *) 0)
122 # endif /* Have wait3. */
123 #endif /* Have waitpid. */
125 #if !defined (wait) && !defined (POSIX)
126 extern int wait ();
127 #endif
129 #ifndef HAVE_UNION_WAIT
131 # define WAIT_T int
133 # ifndef WTERMSIG
134 # define WTERMSIG(x) ((x) & 0x7f)
135 # endif
136 # ifndef WCOREDUMP
137 # define WCOREDUMP(x) ((x) & 0x80)
138 # endif
139 # ifndef WEXITSTATUS
140 # define WEXITSTATUS(x) (((x) >> 8) & 0xff)
141 # endif
142 # ifndef WIFSIGNALED
143 # define WIFSIGNALED(x) (WTERMSIG (x) != 0)
144 # endif
145 # ifndef WIFEXITED
146 # define WIFEXITED(x) (WTERMSIG (x) == 0)
147 # endif
149 #else /* Have `union wait'. */
151 # define WAIT_T union wait
152 # ifndef WTERMSIG
153 # define WTERMSIG(x) ((x).w_termsig)
154 # endif
155 # ifndef WCOREDUMP
156 # define WCOREDUMP(x) ((x).w_coredump)
157 # endif
158 # ifndef WEXITSTATUS
159 # define WEXITSTATUS(x) ((x).w_retcode)
160 # endif
161 # ifndef WIFSIGNALED
162 # define WIFSIGNALED(x) (WTERMSIG(x) != 0)
163 # endif
164 # ifndef WIFEXITED
165 # define WIFEXITED(x) (WTERMSIG(x) == 0)
166 # endif
168 #endif /* Don't have `union wait'. */
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.
231 w32_kill(int pid, int sig)
233 return ((process_kill(pid, sig) == TRUE) ? 0 : -1);
235 #endif /* WINDOWS32 */
237 #ifdef __EMX__
238 /* returns whether path is assumed to be a unix like shell. */
240 _is_unixy_shell (const char *path)
242 /* list of non unix shells */
243 const char *known_os2shells[] = {
244 "cmd.exe",
245 "cmd",
246 "4os2.exe",
247 "4os2",
248 "4dos.exe",
249 "4dos",
250 "command.com",
251 "command",
252 NULL
255 /* find the rightmost '/' or '\\' */
256 const char *name = strrchr (path, '/');
257 const char *p = strrchr (path, '\\');
258 unsigned i;
260 if (name && p) /* take the max */
261 name = (name > p) ? name : p;
262 else if (p) /* name must be 0 */
263 name = p;
264 else if (!name) /* name and p must be 0 */
265 name = path;
267 if (*name == '/' || *name == '\\') name++;
269 i = 0;
270 while (known_os2shells[i] != NULL) {
271 if (stricmp (name, known_os2shells[i]) == 0) /* strcasecmp() */
272 return 0; /* not a unix shell */
273 i++;
276 /* in doubt assume a unix like shell */
277 return 1;
279 #endif /* __EMX__ */
282 /* Write an error message describing the exit status given in
283 EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
284 Append "(ignored)" if IGNORED is nonzero. */
286 static void
287 child_error (char *target_name, int exit_code, int exit_sig, int coredump,
288 int ignored)
290 if (ignored && silent_flag)
291 return;
293 #ifdef VMS
294 if (!(exit_code & 1))
295 error (NILF,
296 (ignored ? _("*** [%s] Error 0x%x (ignored)")
297 : _("*** [%s] Error 0x%x")),
298 target_name, exit_code);
299 #else
300 if (exit_sig == 0)
301 error (NILF, ignored ? _("[%s] Error %d (ignored)") :
302 _("*** [%s] Error %d"),
303 target_name, exit_code);
304 else
305 error (NILF, "*** [%s] %s%s",
306 target_name, strsignal (exit_sig),
307 coredump ? _(" (core dumped)") : "");
308 #endif /* VMS */
311 #ifdef VMS
312 /* Wait for nchildren children to terminate */
313 static void
314 vmsWaitForChildren(int *status)
316 while (1)
318 if (!vms_jobsefnmask)
320 *status = 0;
321 return;
324 *status = sys$wflor (32, vms_jobsefnmask);
326 return;
329 /* Set up IO redirection. */
331 char *
332 vms_redirect (struct dsc$descriptor_s *desc, char *fname, char *ibuf)
334 char *fptr;
335 extern char *vmsify ();
337 ibuf++;
338 while (isspace ((unsigned char)*ibuf))
339 ibuf++;
340 fptr = ibuf;
341 while (*ibuf && !isspace ((unsigned char)*ibuf))
342 ibuf++;
343 *ibuf = 0;
344 if (strcmp (fptr, "/dev/null") != 0)
346 strcpy (fname, vmsify (fptr, 0));
347 if (strchr (fname, '.') == 0)
348 strcat (fname, ".");
350 desc->dsc$w_length = strlen(fname);
351 desc->dsc$a_pointer = fname;
352 desc->dsc$b_dtype = DSC$K_DTYPE_T;
353 desc->dsc$b_class = DSC$K_CLASS_S;
355 if (*fname == 0)
356 printf (_("Warning: Empty redirection\n"));
357 return ibuf;
362 found apostrophe at (p-1)
364 inc p until after closing apostrophe. */
366 static char *
367 handle_apos (char *p)
369 int alast;
370 int inside;
372 #define SEPCHARS ",/()= "
374 inside = 0;
376 while (*p != 0)
378 if (*p == '"')
380 if (inside)
382 while ((alast > 0)
383 && (*p == '"'))
385 p++;
386 alast--;
388 if (alast == 0)
389 inside = 0;
390 else
392 fprintf (stderr, _("Syntax error, still inside '\"'\n"));
393 exit (3);
396 else
398 p++;
399 if (strchr (SEPCHARS, *p))
400 break;
401 inside = 1;
402 alast = 1;
403 while (*p == '"')
405 alast++;
406 p++;
410 else
411 p++;
414 return p;
417 #endif
420 /* Handle a dead child. This handler may or may not ever be installed.
422 If we're using the jobserver feature, we need it. First, installing it
423 ensures the read will interrupt on SIGCHLD. Second, we close the dup'd
424 read FD to ensure we don't enter another blocking read without reaping all
425 the dead children. In this case we don't need the dead_children count.
427 If we don't have either waitpid or wait3, then make is unreliable, but we
428 use the dead_children count to reap children as best we can. */
430 static unsigned int dead_children = 0;
432 #ifndef __EMX__ /* Don't use SIGCHLD handler on OS/2. */
433 RETSIGTYPE
434 child_handler (int sig)
436 ++dead_children;
438 if (job_rfd >= 0)
440 close (job_rfd);
441 job_rfd = -1;
444 DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
446 #endif /* !__EMX__ */
448 extern int shell_function_pid, shell_function_completed;
450 /* Reap all dead children, storing the returned status and the new command
451 state (`cs_finished') in the `file' member of the `struct child' for the
452 dead child, and removing the child from the chain. In addition, if BLOCK
453 nonzero, we block in this function until we've reaped at least one
454 complete child, waiting for it to die if necessary. If ERR is nonzero,
455 print an error message first. */
457 void
458 reap_children (int block, int err)
460 WAIT_T status;
461 /* Initially, assume we have some. */
462 int reap_more = 1;
464 #ifdef WAIT_NOHANG
465 # define REAP_MORE reap_more
466 #else
467 # define REAP_MORE dead_children
468 #endif
470 /* As long as:
472 We have at least one child outstanding OR a shell function in progress,
474 We're blocking for a complete child OR there are more children to reap
476 we'll keep reaping children. */
478 while ((children != 0 || shell_function_pid != 0)
479 && (block || REAP_MORE))
481 int remote = 0;
482 register int pid;
483 int exit_code, exit_sig, coredump;
484 register struct child *lastc, *c;
485 int child_failed;
486 int any_remote, any_local;
488 if (err && block)
490 /* We might block for a while, so let the user know why. */
491 fflush (stdout);
492 error (NILF, _("*** Waiting for unfinished jobs...."));
495 /* We have one less dead child to reap. As noted in
496 child_handler() above, this count is completely unimportant for
497 all modern, POSIX-y systems that support wait3() or waitpid().
498 The rest of this comment below applies only to early, broken
499 pre-POSIX systems. We keep the count only because... it's there...
501 The test and decrement are not atomic; if it is compiled into:
502 register = dead_children - 1;
503 dead_children = register;
504 a SIGCHLD could come between the two instructions.
505 child_handler increments dead_children.
506 The second instruction here would lose that increment. But the
507 only effect of dead_children being wrong is that we might wait
508 longer than necessary to reap a child, and lose some parallelism;
509 and we might print the "Waiting for unfinished jobs" message above
510 when not necessary. */
512 if (dead_children > 0)
513 --dead_children;
515 any_remote = 0;
516 any_local = shell_function_pid != 0;
517 for (c = children; c != 0; c = c->next)
519 any_remote |= c->remote;
520 any_local |= ! c->remote;
521 DB (DB_JOBS, (_("Live child 0x%08lx (%s) PID %ld %s\n"),
522 (unsigned long int) c, c->file->name,
523 (long) c->pid, c->remote ? _(" (remote)") : ""));
524 #ifdef VMS
525 break;
526 #endif
529 /* First, check for remote children. */
530 if (any_remote)
531 pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
532 else
533 pid = 0;
535 if (pid > 0)
536 /* We got a remote child. */
537 remote = 1;
538 else if (pid < 0)
540 /* A remote status command failed miserably. Punt. */
541 remote_status_lose:
542 pfatal_with_name ("remote_status");
544 else
546 /* No remote children. Check for local children. */
547 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
548 if (any_local)
550 #ifdef VMS
551 vmsWaitForChildren (&status);
552 pid = c->pid;
553 #else
554 #ifdef WAIT_NOHANG
555 if (!block)
556 pid = WAIT_NOHANG (&status);
557 else
558 #endif
559 pid = wait (&status);
560 #endif /* !VMS */
562 else
563 pid = 0;
565 if (pid < 0)
567 /* The wait*() failed miserably. Punt. */
568 pfatal_with_name ("wait");
570 else if (pid > 0)
572 /* We got a child exit; chop the status word up. */
573 exit_code = WEXITSTATUS (status);
574 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
575 coredump = WCOREDUMP (status);
577 #ifdef __EMX__
578 /* the SIGCHLD handler must not be used on OS/2 because, unlike
579 on UNIX systems, it had to call wait() itself. Therefore
580 job_rfd has to be closed here. */
581 if (job_rfd >= 0)
583 close (job_rfd);
584 job_rfd = -1;
586 #endif
589 else
591 /* No local children are dead. */
592 reap_more = 0;
594 if (!block || !any_remote)
595 break;
597 /* Now try a blocking wait for a remote child. */
598 pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
599 if (pid < 0)
600 goto remote_status_lose;
601 else if (pid == 0)
602 /* No remote children either. Finally give up. */
603 break;
605 /* We got a remote child. */
606 remote = 1;
608 #endif /* !__MSDOS__, !Amiga, !WINDOWS32. */
610 #ifdef __MSDOS__
611 /* Life is very different on MSDOS. */
612 pid = dos_pid - 1;
613 status = dos_status;
614 exit_code = WEXITSTATUS (status);
615 if (exit_code == 0xff)
616 exit_code = -1;
617 exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
618 coredump = 0;
619 #endif /* __MSDOS__ */
620 #ifdef _AMIGA
621 /* Same on Amiga */
622 pid = amiga_pid - 1;
623 status = amiga_status;
624 exit_code = amiga_status;
625 exit_sig = 0;
626 coredump = 0;
627 #endif /* _AMIGA */
628 #ifdef WINDOWS32
630 HANDLE hPID;
631 int err;
633 /* wait for anything to finish */
634 if (hPID = process_wait_for_any()) {
636 /* was an error found on this process? */
637 err = process_last_err(hPID);
639 /* get exit data */
640 exit_code = process_exit_code(hPID);
642 if (err)
643 fprintf(stderr, "make (e=%d): %s",
644 exit_code, map_windows32_error_to_string(exit_code));
646 /* signal */
647 exit_sig = process_signal(hPID);
649 /* cleanup process */
650 process_cleanup(hPID);
652 coredump = 0;
654 pid = (int) hPID;
656 #endif /* WINDOWS32 */
659 /* Check if this is the child of the `shell' function. */
660 if (!remote && pid == shell_function_pid)
662 /* It is. Leave an indicator for the `shell' function. */
663 if (exit_sig == 0 && exit_code == 127)
664 shell_function_completed = -1;
665 else
666 shell_function_completed = 1;
667 break;
670 child_failed = exit_sig != 0 || exit_code != 0;
672 /* Search for a child matching the deceased one. */
673 lastc = 0;
674 for (c = children; c != 0; lastc = c, c = c->next)
675 if (c->remote == remote && c->pid == pid)
676 break;
678 if (c == 0)
679 /* An unknown child died.
680 Ignore it; it was inherited from our invoker. */
681 continue;
683 DB (DB_JOBS, (child_failed
684 ? _("Reaping losing child 0x%08lx PID %ld %s\n")
685 : _("Reaping winning child 0x%08lx PID %ld %s\n"),
686 (unsigned long int) c, (long) c->pid,
687 c->remote ? _(" (remote)") : ""));
689 if (c->sh_batch_file) {
690 DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
691 c->sh_batch_file));
693 /* just try and remove, don't care if this fails */
694 remove (c->sh_batch_file);
696 /* all done with memory */
697 free (c->sh_batch_file);
698 c->sh_batch_file = NULL;
701 /* If this child had the good stdin, say it is now free. */
702 if (c->good_stdin)
703 good_stdin_used = 0;
705 if (child_failed && !c->noerror && !ignore_errors_flag)
707 /* The commands failed. Write an error message,
708 delete non-precious targets, and abort. */
709 static int delete_on_error = -1;
710 child_error (c->file->name, exit_code, exit_sig, coredump, 0);
711 c->file->update_status = 2;
712 if (delete_on_error == -1)
714 struct file *f = lookup_file (".DELETE_ON_ERROR");
715 delete_on_error = f != 0 && f->is_target;
717 if (exit_sig != 0 || delete_on_error)
718 delete_child_targets (c);
720 else
722 if (child_failed)
724 /* The commands failed, but we don't care. */
725 child_error (c->file->name,
726 exit_code, exit_sig, coredump, 1);
727 child_failed = 0;
730 /* If there are more commands to run, try to start them. */
731 if (job_next_command (c))
733 if (handling_fatal_signal)
735 /* Never start new commands while we are dying.
736 Since there are more commands that wanted to be run,
737 the target was not completely remade. So we treat
738 this as if a command had failed. */
739 c->file->update_status = 2;
741 else
743 /* Check again whether to start remotely.
744 Whether or not we want to changes over time.
745 Also, start_remote_job may need state set up
746 by start_remote_job_p. */
747 c->remote = start_remote_job_p (0);
748 start_job_command (c);
749 /* Fatal signals are left blocked in case we were
750 about to put that child on the chain. But it is
751 already there, so it is safe for a fatal signal to
752 arrive now; it will clean up this child's targets. */
753 unblock_sigs ();
754 if (c->file->command_state == cs_running)
755 /* We successfully started the new command.
756 Loop to reap more children. */
757 continue;
760 if (c->file->update_status != 0)
761 /* We failed to start the commands. */
762 delete_child_targets (c);
764 else
765 /* There are no more commands. We got through them all
766 without an unignored error. Now the target has been
767 successfully updated. */
768 c->file->update_status = 0;
771 /* When we get here, all the commands for C->file are finished
772 (or aborted) and C->file->update_status contains 0 or 2. But
773 C->file->command_state is still cs_running if all the commands
774 ran; notice_finish_file looks for cs_running to tell it that
775 it's interesting to check the file's modtime again now. */
777 if (! handling_fatal_signal)
778 /* Notice if the target of the commands has been changed.
779 This also propagates its values for command_state and
780 update_status to its also_make files. */
781 notice_finished_file (c->file);
783 DB (DB_JOBS, (_("Removing child 0x%08lx PID %ld%s from chain.\n"),
784 (unsigned long int) c, (long) c->pid,
785 c->remote ? _(" (remote)") : ""));
787 /* Block fatal signals while frobnicating the list, so that
788 children and job_slots_used are always consistent. Otherwise
789 a fatal signal arriving after the child is off the chain and
790 before job_slots_used is decremented would believe a child was
791 live and call reap_children again. */
792 block_sigs ();
794 /* There is now another slot open. */
795 if (job_slots_used > 0)
796 --job_slots_used;
798 /* Remove the child from the chain and free it. */
799 if (lastc == 0)
800 children = c->next;
801 else
802 lastc->next = c->next;
804 free_child (c);
806 unblock_sigs ();
808 /* If the job failed, and the -k flag was not given, die,
809 unless we are already in the process of dying. */
810 if (!err && child_failed && !keep_going_flag &&
811 /* fatal_error_signal will die with the right signal. */
812 !handling_fatal_signal)
813 die (2);
815 /* Only block for one child. */
816 block = 0;
819 return;
822 /* Free the storage allocated for CHILD. */
824 static void
825 free_child (struct child *child)
827 /* If this child is the only one it was our "free" job, so don't put a
828 token back for it. This child has already been removed from the list,
829 so if there any left this wasn't the last one. */
831 if (job_fds[1] >= 0 && children)
833 char token = '+';
834 int r;
836 /* Write a job token back to the pipe. */
838 EINTRLOOP (r, write (job_fds[1], &token, 1));
839 if (r != 1)
840 pfatal_with_name (_("write jobserver"));
842 DB (DB_JOBS, (_("Released token for child 0x%08lx (%s).\n"),
843 (unsigned long int) child, child->file->name));
846 if (handling_fatal_signal) /* Don't bother free'ing if about to die. */
847 return;
849 if (child->command_lines != 0)
851 register unsigned int i;
852 for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
853 free (child->command_lines[i]);
854 free ((char *) child->command_lines);
857 if (child->environment != 0)
859 register char **ep = child->environment;
860 while (*ep != 0)
861 free (*ep++);
862 free ((char *) child->environment);
865 free ((char *) child);
868 #ifdef POSIX
869 extern sigset_t fatal_signal_set;
870 #endif
872 void
873 block_sigs (void)
875 #ifdef POSIX
876 (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
877 #else
878 # ifdef HAVE_SIGSETMASK
879 (void) sigblock (fatal_signal_mask);
880 # endif
881 #endif
884 #ifdef POSIX
885 void
886 unblock_sigs (void)
888 sigset_t empty;
889 sigemptyset (&empty);
890 sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
892 #endif
894 #ifdef MAKE_JOBSERVER
895 # ifdef __EMX__
896 /* Never install the SIGCHLD handler for EMX!!! */
897 # define set_child_handler_action_flags(x)
898 # else
899 /* Set the child handler action flags to FLAGS. */
900 static void
901 set_child_handler_action_flags (int flags)
903 struct sigaction sa;
904 bzero ((char *) &sa, sizeof sa);
905 sa.sa_handler = child_handler;
906 sa.sa_flags = flags;
907 #if defined SIGCHLD
908 sigaction (SIGCHLD, &sa, NULL);
909 #endif
910 #if defined SIGCLD && SIGCLD != SIGCHLD
911 sigaction (SIGCLD, &sa, NULL);
912 #endif
914 #endif /* !__EMX__ */
915 #endif
918 /* Start a job to run the commands specified in CHILD.
919 CHILD is updated to reflect the commands and ID of the child process.
921 NOTE: On return fatal signals are blocked! The caller is responsible
922 for calling `unblock_sigs', once the new child is safely on the chain so
923 it can be cleaned up in the event of a fatal signal. */
925 static void
926 start_job_command (struct child *child)
928 #ifndef _AMIGA
929 static int bad_stdin = -1;
930 #endif
931 register char *p;
932 int flags;
933 #ifdef VMS
934 char *argv;
935 #else
936 char **argv;
937 #endif
939 /* If we have a completely empty commandset, stop now. */
940 if (!child->command_ptr)
941 goto next_command;
943 /* Combine the flags parsed for the line itself with
944 the flags specified globally for this target. */
945 flags = (child->file->command_flags
946 | child->file->cmds->lines_flags[child->command_line - 1]);
948 p = child->command_ptr;
949 child->noerror = flags & COMMANDS_NOERROR;
951 while (*p != '\0')
953 if (*p == '@')
954 flags |= COMMANDS_SILENT;
955 else if (*p == '+')
956 flags |= COMMANDS_RECURSE;
957 else if (*p == '-')
958 child->noerror = 1;
959 else if (!isblank ((unsigned char)*p))
960 break;
961 ++p;
964 /* Update the file's command flags with any new ones we found. We only
965 keep the COMMANDS_RECURSE setting. Even this isn't 100% correct; we are
966 now marking more commands recursive than should be in the case of
967 multiline define/endef scripts where only one line is marked "+". In
968 order to really fix this, we'll have to keep a lines_flags for every
969 actual line, after expansion. */
970 child->file->cmds->lines_flags[child->command_line - 1]
971 |= flags & COMMANDS_RECURSE;
973 /* Figure out an argument list from this command line. */
976 char *end = 0;
977 #ifdef VMS
978 argv = p;
979 #else
980 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
981 #endif
982 if (end == NULL)
983 child->command_ptr = NULL;
984 else
986 *end++ = '\0';
987 child->command_ptr = end;
991 /* If -q was given, say that updating `failed' if there was any text on the
992 command line, or `succeeded' otherwise. The exit status of 1 tells the
993 user that -q is saying `something to do'; the exit status for a random
994 error is 2. */
995 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
997 #ifndef VMS
998 free (argv[0]);
999 free ((char *) argv);
1000 #endif
1001 child->file->update_status = 1;
1002 notice_finished_file (child->file);
1003 return;
1006 if (touch_flag && !(flags & COMMANDS_RECURSE))
1008 /* Go on to the next command. It might be the recursive one.
1009 We construct ARGV only to find the end of the command line. */
1010 #ifndef VMS
1011 if (argv)
1013 free (argv[0]);
1014 free ((char *) argv);
1016 #endif
1017 argv = 0;
1020 if (argv == 0)
1022 next_command:
1023 #ifdef __MSDOS__
1024 execute_by_shell = 0; /* in case construct_command_argv sets it */
1025 #endif
1026 /* This line has no commands. Go to the next. */
1027 if (job_next_command (child))
1028 start_job_command (child);
1029 else
1031 /* No more commands. Make sure we're "running"; we might not be if
1032 (e.g.) all commands were skipped due to -n. */
1033 set_command_state (child->file, cs_running);
1034 child->file->update_status = 0;
1035 notice_finished_file (child->file);
1037 return;
1040 /* Print out the command. If silent, we call `message' with null so it
1041 can log the working directory before the command's own error messages
1042 appear. */
1044 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
1045 ? "%s" : (char *) 0, p);
1047 /* Tell update_goal_chain that a command has been started on behalf of
1048 this target. It is important that this happens here and not in
1049 reap_children (where we used to do it), because reap_children might be
1050 reaping children from a different target. We want this increment to
1051 guaranteedly indicate that a command was started for the dependency
1052 chain (i.e., update_file recursion chain) we are processing. */
1054 ++commands_started;
1056 /* Optimize an empty command. People use this for timestamp rules,
1057 so avoid forking a useless shell. Do this after we increment
1058 commands_started so make still treats this special case as if it
1059 performed some action (makes a difference as to what messages are
1060 printed, etc. */
1062 #if !defined(VMS) && !defined(_AMIGA)
1063 if (
1064 #if defined __MSDOS__ || defined (__EMX__)
1065 unixy_shell /* the test is complicated and we already did it */
1066 #else
1067 (argv[0] && !strcmp (argv[0], "/bin/sh"))
1068 #endif
1069 && (argv[1]
1070 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
1071 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1072 && argv[3] == NULL)
1074 free (argv[0]);
1075 free ((char *) argv);
1076 goto next_command;
1078 #endif /* !VMS && !_AMIGA */
1080 /* If -n was given, recurse to get the next line in the sequence. */
1082 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1084 #ifndef VMS
1085 free (argv[0]);
1086 free ((char *) argv);
1087 #endif
1088 goto next_command;
1091 /* Flush the output streams so they won't have things written twice. */
1093 fflush (stdout);
1094 fflush (stderr);
1096 #ifndef VMS
1097 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1099 /* Set up a bad standard input that reads from a broken pipe. */
1101 if (bad_stdin == -1)
1103 /* Make a file descriptor that is the read end of a broken pipe.
1104 This will be used for some children's standard inputs. */
1105 int pd[2];
1106 if (pipe (pd) == 0)
1108 /* Close the write side. */
1109 (void) close (pd[1]);
1110 /* Save the read side. */
1111 bad_stdin = pd[0];
1113 /* Set the descriptor to close on exec, so it does not litter any
1114 child's descriptor table. When it is dup2'd onto descriptor 0,
1115 that descriptor will not close on exec. */
1116 CLOSE_ON_EXEC (bad_stdin);
1120 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1122 /* Decide whether to give this child the `good' standard input
1123 (one that points to the terminal or whatever), or the `bad' one
1124 that points to the read side of a broken pipe. */
1126 child->good_stdin = !good_stdin_used;
1127 if (child->good_stdin)
1128 good_stdin_used = 1;
1130 #endif /* !VMS */
1132 child->deleted = 0;
1134 #ifndef _AMIGA
1135 /* Set up the environment for the child. */
1136 if (child->environment == 0)
1137 child->environment = target_environment (child->file);
1138 #endif
1140 #if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1142 #ifndef VMS
1143 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1144 if (child->remote)
1146 int is_remote, id, used_stdin;
1147 if (start_remote_job (argv, child->environment,
1148 child->good_stdin ? 0 : bad_stdin,
1149 &is_remote, &id, &used_stdin))
1150 /* Don't give up; remote execution may fail for various reasons. If
1151 so, simply run the job locally. */
1152 goto run_local;
1153 else
1155 if (child->good_stdin && !used_stdin)
1157 child->good_stdin = 0;
1158 good_stdin_used = 0;
1160 child->remote = is_remote;
1161 child->pid = id;
1164 else
1165 #endif /* !VMS */
1167 /* Fork the child process. */
1169 char **parent_environ;
1171 run_local:
1172 block_sigs ();
1174 child->remote = 0;
1176 #ifdef VMS
1178 if (!child_execute_job (argv, child)) {
1179 /* Fork failed! */
1180 perror_with_name ("vfork", "");
1181 goto error;
1184 #else
1186 parent_environ = environ;
1188 # ifdef __EMX__
1189 /* If we aren't running a recursive command and we have a jobserver
1190 pipe, close it before exec'ing. */
1191 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1193 CLOSE_ON_EXEC (job_fds[0]);
1194 CLOSE_ON_EXEC (job_fds[1]);
1196 if (job_rfd >= 0)
1197 CLOSE_ON_EXEC (job_rfd);
1199 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1200 child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1201 argv, child->environment);
1202 if (child->pid < 0)
1204 /* spawn failed! */
1205 unblock_sigs ();
1206 perror_with_name ("spawn", "");
1207 goto error;
1210 /* undo CLOSE_ON_EXEC() after the child process has been started */
1211 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1213 fcntl (job_fds[0], F_SETFD, 0);
1214 fcntl (job_fds[1], F_SETFD, 0);
1216 if (job_rfd >= 0)
1217 fcntl (job_rfd, F_SETFD, 0);
1219 #else /* !__EMX__ */
1221 child->pid = vfork ();
1222 environ = parent_environ; /* Restore value child may have clobbered. */
1223 if (child->pid == 0)
1225 /* We are the child side. */
1226 unblock_sigs ();
1228 /* If we aren't running a recursive command and we have a jobserver
1229 pipe, close it before exec'ing. */
1230 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1232 close (job_fds[0]);
1233 close (job_fds[1]);
1235 if (job_rfd >= 0)
1236 close (job_rfd);
1238 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1239 argv, child->environment);
1241 else if (child->pid < 0)
1243 /* Fork failed! */
1244 unblock_sigs ();
1245 perror_with_name ("vfork", "");
1246 goto error;
1248 # endif /* !__EMX__ */
1249 #endif /* !VMS */
1252 #else /* __MSDOS__ or Amiga or WINDOWS32 */
1253 #ifdef __MSDOS__
1255 int proc_return;
1257 block_sigs ();
1258 dos_status = 0;
1260 /* We call `system' to do the job of the SHELL, since stock DOS
1261 shell is too dumb. Our `system' knows how to handle long
1262 command lines even if pipes/redirection is needed; it will only
1263 call COMMAND.COM when its internal commands are used. */
1264 if (execute_by_shell)
1266 char *cmdline = argv[0];
1267 /* We don't have a way to pass environment to `system',
1268 so we need to save and restore ours, sigh... */
1269 char **parent_environ = environ;
1271 environ = child->environment;
1273 /* If we have a *real* shell, tell `system' to call
1274 it to do everything for us. */
1275 if (unixy_shell)
1277 /* A *real* shell on MSDOS may not support long
1278 command lines the DJGPP way, so we must use `system'. */
1279 cmdline = argv[2]; /* get past "shell -c" */
1282 dos_command_running = 1;
1283 proc_return = system (cmdline);
1284 environ = parent_environ;
1285 execute_by_shell = 0; /* for the next time */
1287 else
1289 dos_command_running = 1;
1290 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1293 /* Need to unblock signals before turning off
1294 dos_command_running, so that child's signals
1295 will be treated as such (see fatal_error_signal). */
1296 unblock_sigs ();
1297 dos_command_running = 0;
1299 /* If the child got a signal, dos_status has its
1300 high 8 bits set, so be careful not to alter them. */
1301 if (proc_return == -1)
1302 dos_status |= 0xff;
1303 else
1304 dos_status |= (proc_return & 0xff);
1305 ++dead_children;
1306 child->pid = dos_pid++;
1308 #endif /* __MSDOS__ */
1309 #ifdef _AMIGA
1310 amiga_status = MyExecute (argv);
1312 ++dead_children;
1313 child->pid = amiga_pid++;
1314 if (amiga_batch_file)
1316 amiga_batch_file = 0;
1317 DeleteFile (amiga_bname); /* Ignore errors. */
1319 #endif /* Amiga */
1320 #ifdef WINDOWS32
1322 HANDLE hPID;
1323 char* arg0;
1325 /* make UNC paths safe for CreateProcess -- backslash format */
1326 arg0 = argv[0];
1327 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1328 for ( ; arg0 && *arg0; arg0++)
1329 if (*arg0 == '/')
1330 *arg0 = '\\';
1332 /* make sure CreateProcess() has Path it needs */
1333 sync_Path_environment();
1335 hPID = process_easy(argv, child->environment);
1337 if (hPID != INVALID_HANDLE_VALUE)
1338 child->pid = (int) hPID;
1339 else {
1340 int i;
1341 unblock_sigs();
1342 fprintf(stderr,
1343 _("process_easy() failed failed to launch process (e=%d)\n"),
1344 process_last_err(hPID));
1345 for (i = 0; argv[i]; i++)
1346 fprintf(stderr, "%s ", argv[i]);
1347 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1350 #endif /* WINDOWS32 */
1351 #endif /* __MSDOS__ or Amiga or WINDOWS32 */
1353 /* We are the parent side. Set the state to
1354 say the commands are running and return. */
1356 set_command_state (child->file, cs_running);
1358 /* Free the storage used by the child's argument list. */
1359 #ifndef VMS
1360 free (argv[0]);
1361 free ((char *) argv);
1362 #endif
1364 return;
1366 error:
1367 child->file->update_status = 2;
1368 notice_finished_file (child->file);
1369 return;
1372 /* Try to start a child running.
1373 Returns nonzero if the child was started (and maybe finished), or zero if
1374 the load was too high and the child was put on the `waiting_jobs' chain. */
1376 static int
1377 start_waiting_job (struct child *c)
1379 struct file *f = c->file;
1381 /* If we can start a job remotely, we always want to, and don't care about
1382 the local load average. We record that the job should be started
1383 remotely in C->remote for start_job_command to test. */
1385 c->remote = start_remote_job_p (1);
1387 /* If we are running at least one job already and the load average
1388 is too high, make this one wait. */
1389 if (!c->remote && job_slots_used > 0 && load_too_high ())
1391 /* Put this child on the chain of children waiting for the load average
1392 to go down. */
1393 set_command_state (f, cs_running);
1394 c->next = waiting_jobs;
1395 waiting_jobs = c;
1396 return 0;
1399 /* Start the first command; reap_children will run later command lines. */
1400 start_job_command (c);
1402 switch (f->command_state)
1404 case cs_running:
1405 c->next = children;
1406 DB (DB_JOBS, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1407 (unsigned long int) c, c->file->name,
1408 (long) c->pid, c->remote ? _(" (remote)") : ""));
1409 children = c;
1410 /* One more job slot is in use. */
1411 ++job_slots_used;
1412 unblock_sigs ();
1413 break;
1415 case cs_not_started:
1416 /* All the command lines turned out to be empty. */
1417 f->update_status = 0;
1418 /* FALLTHROUGH */
1420 case cs_finished:
1421 notice_finished_file (f);
1422 free_child (c);
1423 break;
1425 default:
1426 assert (f->command_state == cs_finished);
1427 break;
1430 return 1;
1433 /* Create a `struct child' for FILE and start its commands running. */
1435 void
1436 new_job (struct file *file)
1438 register struct commands *cmds = file->cmds;
1439 register struct child *c;
1440 char **lines;
1441 register unsigned int i;
1443 /* Let any previously decided-upon jobs that are waiting
1444 for the load to go down start before this new one. */
1445 start_waiting_jobs ();
1447 /* Reap any children that might have finished recently. */
1448 reap_children (0, 0);
1450 /* Chop the commands up into lines if they aren't already. */
1451 chop_commands (cmds);
1453 /* Expand the command lines and store the results in LINES. */
1454 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1455 for (i = 0; i < cmds->ncommand_lines; ++i)
1457 /* Collapse backslash-newline combinations that are inside variable
1458 or function references. These are left alone by the parser so
1459 that they will appear in the echoing of commands (where they look
1460 nice); and collapsed by construct_command_argv when it tokenizes.
1461 But letting them survive inside function invocations loses because
1462 we don't want the functions to see them as part of the text. */
1464 char *in, *out, *ref;
1466 /* IN points to where in the line we are scanning.
1467 OUT points to where in the line we are writing.
1468 When we collapse a backslash-newline combination,
1469 IN gets ahead of OUT. */
1471 in = out = cmds->command_lines[i];
1472 while ((ref = strchr (in, '$')) != 0)
1474 ++ref; /* Move past the $. */
1476 if (out != in)
1477 /* Copy the text between the end of the last chunk
1478 we processed (where IN points) and the new chunk
1479 we are about to process (where REF points). */
1480 bcopy (in, out, ref - in);
1482 /* Move both pointers past the boring stuff. */
1483 out += ref - in;
1484 in = ref;
1486 if (*ref == '(' || *ref == '{')
1488 char openparen = *ref;
1489 char closeparen = openparen == '(' ? ')' : '}';
1490 int count;
1491 char *p;
1493 *out++ = *in++; /* Copy OPENPAREN. */
1494 /* IN now points past the opening paren or brace.
1495 Count parens or braces until it is matched. */
1496 count = 0;
1497 while (*in != '\0')
1499 if (*in == closeparen && --count < 0)
1500 break;
1501 else if (*in == '\\' && in[1] == '\n')
1503 /* We have found a backslash-newline inside a
1504 variable or function reference. Eat it and
1505 any following whitespace. */
1507 int quoted = 0;
1508 for (p = in - 1; p > ref && *p == '\\'; --p)
1509 quoted = !quoted;
1511 if (quoted)
1512 /* There were two or more backslashes, so this is
1513 not really a continuation line. We don't collapse
1514 the quoting backslashes here as is done in
1515 collapse_continuations, because the line will
1516 be collapsed again after expansion. */
1517 *out++ = *in++;
1518 else
1520 /* Skip the backslash, newline and
1521 any following whitespace. */
1522 in = next_token (in + 2);
1524 /* Discard any preceding whitespace that has
1525 already been written to the output. */
1526 while (out > ref
1527 && isblank ((unsigned char)out[-1]))
1528 --out;
1530 /* Replace it all with a single space. */
1531 *out++ = ' ';
1534 else
1536 if (*in == openparen)
1537 ++count;
1539 *out++ = *in++;
1545 /* There are no more references in this line to worry about.
1546 Copy the remaining uninteresting text to the output. */
1547 if (out != in)
1548 strcpy (out, in);
1550 /* Finally, expand the line. */
1551 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1552 file);
1555 /* Start the command sequence, record it in a new
1556 `struct child', and add that to the chain. */
1558 c = (struct child *) xmalloc (sizeof (struct child));
1559 bzero ((char *)c, sizeof (struct child));
1560 c->file = file;
1561 c->command_lines = lines;
1562 c->sh_batch_file = NULL;
1564 /* Fetch the first command line to be run. */
1565 job_next_command (c);
1567 /* Wait for a job slot to be freed up. If we allow an infinite number
1568 don't bother; also job_slots will == 0 if we're using the jobserver. */
1570 if (job_slots != 0)
1571 while (job_slots_used == job_slots)
1572 reap_children (1, 0);
1574 #ifdef MAKE_JOBSERVER
1575 /* If we are controlling multiple jobs make sure we have a token before
1576 starting the child. */
1578 /* This can be inefficient. There's a decent chance that this job won't
1579 actually have to run any subprocesses: the command script may be empty
1580 or otherwise optimized away. It would be nice if we could defer
1581 obtaining a token until just before we need it, in start_job_command.
1582 To do that we'd need to keep track of whether we'd already obtained a
1583 token (since start_job_command is called for each line of the job, not
1584 just once). Also more thought needs to go into the entire algorithm;
1585 this is where the old parallel job code waits, so... */
1587 else if (job_fds[0] >= 0)
1588 while (1)
1590 char token;
1591 int got_token;
1592 int saved_errno;
1594 DB (DB_JOBS, ("Need a job token; we %shave children\n",
1595 children ? "" : "don't "));
1597 /* If we don't already have a job started, use our "free" token. */
1598 if (!children)
1599 break;
1601 /* Read a token. As long as there's no token available we'll block.
1602 We enable interruptible system calls before the read(2) so that if
1603 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1604 we can process the death(s) and return tokens to the free pool.
1606 Once we return from the read, we immediately reinstate restartable
1607 system calls. This allows us to not worry about checking for
1608 EINTR on all the other system calls in the program.
1610 There is one other twist: there is a span between the time
1611 reap_children() does its last check for dead children and the time
1612 the read(2) call is entered, below, where if a child dies we won't
1613 notice. This is extremely serious as it could cause us to
1614 deadlock, given the right set of events.
1616 To avoid this, we do the following: before we reap_children(), we
1617 dup(2) the read FD on the jobserver pipe. The read(2) call below
1618 uses that new FD. In the signal handler, we close that FD. That
1619 way, if a child dies during the section mentioned above, the
1620 read(2) will be invoked with an invalid FD and will return
1621 immediately with EBADF. */
1623 /* Make sure we have a dup'd FD. */
1624 if (job_rfd < 0)
1626 DB (DB_JOBS, ("Duplicate the job FD\n"));
1627 job_rfd = dup (job_fds[0]);
1630 /* Reap anything that's currently waiting. */
1631 reap_children (0, 0);
1633 /* If our "free" token has become available, use it. */
1634 if (!children)
1635 break;
1637 /* Set interruptible system calls, and read() for a job token. */
1638 set_child_handler_action_flags (0);
1639 got_token = read (job_rfd, &token, 1);
1640 saved_errno = errno;
1641 set_child_handler_action_flags (SA_RESTART);
1643 /* If we got one, we're done here. */
1644 if (got_token == 1)
1646 DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1647 (unsigned long int) c, c->file->name));
1648 break;
1651 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1652 go back and reap_children(), and try again. */
1653 errno = saved_errno;
1654 if (errno != EINTR && errno != EBADF)
1655 pfatal_with_name (_("read jobs pipe"));
1656 if (errno == EBADF)
1657 DB (DB_JOBS, ("Read returned EBADF.\n"));
1659 #endif
1661 /* The job is now primed. Start it running.
1662 (This will notice if there are in fact no commands.) */
1663 (void) start_waiting_job (c);
1665 if (job_slots == 1 || not_parallel)
1666 /* Since there is only one job slot, make things run linearly.
1667 Wait for the child to die, setting the state to `cs_finished'. */
1668 while (file->command_state == cs_running)
1669 reap_children (1, 0);
1671 return;
1674 /* Move CHILD's pointers to the next command for it to execute.
1675 Returns nonzero if there is another command. */
1677 static int
1678 job_next_command (struct child *child)
1680 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1682 /* There are no more lines in the expansion of this line. */
1683 if (child->command_line == child->file->cmds->ncommand_lines)
1685 /* There are no more lines to be expanded. */
1686 child->command_ptr = 0;
1687 return 0;
1689 else
1690 /* Get the next line to run. */
1691 child->command_ptr = child->command_lines[child->command_line++];
1693 return 1;
1696 static int
1697 load_too_high (void)
1699 #if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA)
1700 return 1;
1701 #else
1702 double load;
1704 if (max_load_average < 0)
1705 return 0;
1707 make_access ();
1708 if (getloadavg (&load, 1) != 1)
1710 static int lossage = -1;
1711 /* Complain only once for the same error. */
1712 if (lossage == -1 || errno != lossage)
1714 if (errno == 0)
1715 /* An errno value of zero means getloadavg is just unsupported. */
1716 error (NILF,
1717 _("cannot enforce load limits on this operating system"));
1718 else
1719 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1721 lossage = errno;
1722 load = 0;
1724 user_access ();
1726 DB (DB_JOBS, ("Current system load = %f (max requested = %f)\n",
1727 load, max_load_average));
1728 return load >= max_load_average;
1729 #endif
1732 /* Start jobs that are waiting for the load to be lower. */
1734 void
1735 start_waiting_jobs (void)
1737 struct child *job;
1739 if (waiting_jobs == 0)
1740 return;
1744 /* Check for recently deceased descendants. */
1745 reap_children (0, 0);
1747 /* Take a job off the waiting list. */
1748 job = waiting_jobs;
1749 waiting_jobs = job->next;
1751 /* Try to start that job. We break out of the loop as soon
1752 as start_waiting_job puts one back on the waiting list. */
1754 while (start_waiting_job (job) && waiting_jobs != 0);
1756 return;
1759 #ifndef WINDOWS32
1760 #ifdef VMS
1761 #include <descrip.h>
1762 #include <clidef.h>
1764 /* This is called as an AST when a child process dies (it won't get
1765 interrupted by anything except a higher level AST).
1767 int vmsHandleChildTerm(struct child *child)
1769 int status;
1770 register struct child *lastc, *c;
1771 int child_failed;
1773 vms_jobsefnmask &= ~(1 << (child->efn - 32));
1775 lib$free_ef(&child->efn);
1777 (void) sigblock (fatal_signal_mask);
1779 child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
1781 /* Search for a child matching the deceased one. */
1782 lastc = 0;
1783 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1784 for (c = children; c != 0 && c != child; lastc = c, c = c->next);
1785 #else
1786 c = child;
1787 #endif
1789 if (child_failed && !c->noerror && !ignore_errors_flag)
1791 /* The commands failed. Write an error message,
1792 delete non-precious targets, and abort. */
1793 child_error (c->file->name, c->cstatus, 0, 0, 0);
1794 c->file->update_status = 1;
1795 delete_child_targets (c);
1797 else
1799 if (child_failed)
1801 /* The commands failed, but we don't care. */
1802 child_error (c->file->name, c->cstatus, 0, 0, 1);
1803 child_failed = 0;
1806 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1807 /* If there are more commands to run, try to start them. */
1808 start_job (c);
1810 switch (c->file->command_state)
1812 case cs_running:
1813 /* Successfully started. */
1814 break;
1816 case cs_finished:
1817 if (c->file->update_status != 0) {
1818 /* We failed to start the commands. */
1819 delete_child_targets (c);
1821 break;
1823 default:
1824 error (NILF, _("internal error: `%s' command_state"),
1825 c->file->name);
1826 abort ();
1827 break;
1829 #endif /* RECURSIVEJOBS */
1832 /* Set the state flag to say the commands have finished. */
1833 c->file->command_state = cs_finished;
1834 notice_finished_file (c->file);
1836 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
1837 /* Remove the child from the chain and free it. */
1838 if (lastc == 0)
1839 children = c->next;
1840 else
1841 lastc->next = c->next;
1842 free_child (c);
1843 #endif /* RECURSIVEJOBS */
1845 /* There is now another slot open. */
1846 if (job_slots_used > 0)
1847 --job_slots_used;
1849 /* If the job failed, and the -k flag was not given, die. */
1850 if (child_failed && !keep_going_flag)
1851 die (EXIT_FAILURE);
1853 (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
1855 return 1;
1858 /* VMS:
1859 Spawn a process executing the command in ARGV and return its pid. */
1861 #define MAXCMDLEN 200
1863 /* local helpers to make ctrl+c and ctrl+y working, see below */
1864 #include <iodef.h>
1865 #include <libclidef.h>
1866 #include <ssdef.h>
1868 static int ctrlMask= LIB$M_CLI_CTRLY;
1869 static int oldCtrlMask;
1870 static int setupYAstTried= 0;
1871 static int pidToAbort= 0;
1872 static int chan= 0;
1874 static void reEnableAst(void) {
1875 lib$enable_ctrl (&oldCtrlMask,0);
1878 static astHandler (void) {
1879 if (pidToAbort) {
1880 sys$forcex (&pidToAbort, 0, SS$_ABORT);
1881 pidToAbort= 0;
1883 kill (getpid(),SIGQUIT);
1886 static void tryToSetupYAst(void) {
1887 $DESCRIPTOR(inputDsc,"SYS$COMMAND");
1888 int status;
1889 struct {
1890 short int status, count;
1891 int dvi;
1892 } iosb;
1894 setupYAstTried++;
1896 if (!chan) {
1897 status= sys$assign(&inputDsc,&chan,0,0);
1898 if (!(status&SS$_NORMAL)) {
1899 lib$signal(status);
1900 return;
1903 status= sys$qiow (0, chan, IO$_SETMODE|IO$M_CTRLYAST,&iosb,0,0,
1904 astHandler,0,0,0,0,0);
1905 if (status==SS$_ILLIOFUNC) {
1906 sys$dassgn(chan);
1907 #ifdef CTRLY_ENABLED_ANYWAY
1908 fprintf (stderr,
1909 _("-warning, CTRL-Y will leave sub-process(es) around.\n"));
1910 #else
1911 return;
1912 #endif
1914 if (status==SS$_NORMAL)
1915 status= iosb.status;
1916 if (!(status&SS$_NORMAL)) {
1917 lib$signal(status);
1918 return;
1921 /* called from AST handler ? */
1922 if (setupYAstTried>1)
1923 return;
1924 if (atexit(reEnableAst))
1925 fprintf (stderr,
1926 _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
1927 status= lib$disable_ctrl (&ctrlMask, &oldCtrlMask);
1928 if (!(status&SS$_NORMAL)) {
1929 lib$signal(status);
1930 return;
1934 child_execute_job (char *argv, struct child *child)
1936 int i;
1937 static struct dsc$descriptor_s cmddsc;
1938 static struct dsc$descriptor_s pnamedsc;
1939 static struct dsc$descriptor_s ifiledsc;
1940 static struct dsc$descriptor_s ofiledsc;
1941 static struct dsc$descriptor_s efiledsc;
1942 int have_redirection = 0;
1943 int have_newline = 0;
1945 int spflags = CLI$M_NOWAIT;
1946 int status;
1947 char *cmd = alloca (strlen (argv) + 512), *p, *q;
1948 char ifile[256], ofile[256], efile[256];
1949 char *comname = 0;
1950 char procname[100];
1952 /* Parse IO redirection. */
1954 ifile[0] = 0;
1955 ofile[0] = 0;
1956 efile[0] = 0;
1958 DB (DB_JOBS, ("child_execute_job (%s)\n", argv));
1960 while (isspace ((unsigned char)*argv))
1961 argv++;
1963 if (*argv == 0)
1964 return 0;
1966 sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
1967 pnamedsc.dsc$w_length = strlen(procname);
1968 pnamedsc.dsc$a_pointer = procname;
1969 pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
1970 pnamedsc.dsc$b_class = DSC$K_CLASS_S;
1972 /* Handle comments and redirection. */
1973 for (p = argv, q = cmd; *p; p++, q++)
1975 switch (*p)
1977 case '#':
1978 *p-- = 0;
1979 *q-- = 0;
1980 break;
1981 case '\\':
1982 p++;
1983 if (*p == '\n')
1984 p++;
1985 if (isspace ((unsigned char)*p))
1987 do { p++; } while (isspace ((unsigned char)*p));
1988 p--;
1990 *q = *p;
1991 break;
1992 case '<':
1993 p = vms_redirect (&ifiledsc, ifile, p);
1994 *q = ' ';
1995 have_redirection = 1;
1996 break;
1997 case '>':
1998 have_redirection = 1;
1999 if (*(p-1) == '2')
2001 q--;
2002 if (strncmp (p, ">&1", 3) == 0)
2004 p += 3;
2005 strcpy (efile, "sys$output");
2006 efiledsc.dsc$w_length = strlen(efile);
2007 efiledsc.dsc$a_pointer = efile;
2008 efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
2009 efiledsc.dsc$b_class = DSC$K_CLASS_S;
2011 else
2013 p = vms_redirect (&efiledsc, efile, p);
2016 else
2018 p = vms_redirect (&ofiledsc, ofile, p);
2020 *q = ' ';
2021 break;
2022 case '\n':
2023 have_newline = 1;
2024 default:
2025 *q = *p;
2026 break;
2029 *q = *p;
2031 if (strncmp (cmd, "builtin_", 8) == 0)
2033 child->pid = 270163;
2034 child->efn = 0;
2035 child->cstatus = 1;
2037 DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));
2039 p = cmd + 8;
2041 if ((*(p) == 'c')
2042 && (*(p+1) == 'd')
2043 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
2045 p += 3;
2046 while ((*p == ' ') || (*p == '\t'))
2047 p++;
2048 DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
2049 if (chdir (p))
2050 return 0;
2051 else
2052 return 1;
2054 else if ((*(p) == 'r')
2055 && (*(p+1) == 'm')
2056 && ((*(p+2) == ' ') || (*(p+2) == '\t')))
2058 int in_arg;
2060 /* rm */
2061 p += 3;
2062 while ((*p == ' ') || (*p == '\t'))
2063 p++;
2064 in_arg = 1;
2066 DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
2067 while (*p)
2069 switch (*p)
2071 case ' ':
2072 case '\t':
2073 if (in_arg)
2075 *p++ = ';';
2076 in_arg = 0;
2078 break;
2079 default:
2080 break;
2082 p++;
2085 else
2087 printf(_("Unknown builtin command '%s'\n"), cmd);
2088 fflush(stdout);
2089 return 0;
2093 /* Create a *.com file if either the command is too long for
2094 lib$spawn, or the command contains a newline, or if redirection
2095 is desired. Forcing commands with newlines into DCLs allows to
2096 store search lists on user mode logicals. */
2098 if (strlen (cmd) > MAXCMDLEN
2099 || (have_redirection != 0)
2100 || (have_newline != 0))
2102 FILE *outfile;
2103 char c;
2104 char *sep;
2105 int alevel = 0; /* apostrophe level */
2107 if (strlen (cmd) == 0)
2109 printf (_("Error, empty command\n"));
2110 fflush (stdout);
2111 return 0;
2114 outfile = open_tmpfile (&comname, "sys$scratch:CMDXXXXXX.COM");
2115 if (outfile == 0)
2116 pfatal_with_name (_("fopen (temporary file)"));
2118 if (ifile[0])
2120 fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
2121 DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
2122 ifiledsc.dsc$w_length = 0;
2125 if (efile[0])
2127 fprintf (outfile, "$ define sys$error %s\n", efile);
2128 DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
2129 efiledsc.dsc$w_length = 0;
2132 if (ofile[0])
2134 fprintf (outfile, "$ define sys$output %s\n", ofile);
2135 DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
2136 ofiledsc.dsc$w_length = 0;
2139 p = sep = q = cmd;
2140 for (c = '\n'; c; c = *q++)
2142 switch (c)
2144 case '\n':
2145 /* At a newline, skip any whitespace around a leading $
2146 from the command and issue exactly one $ into the DCL. */
2147 while (isspace ((unsigned char)*p))
2148 p++;
2149 if (*p == '$')
2150 p++;
2151 while (isspace ((unsigned char)*p))
2152 p++;
2153 fwrite (p, 1, q - p, outfile);
2154 fputc ('$', outfile);
2155 fputc (' ', outfile);
2156 /* Reset variables. */
2157 p = sep = q;
2158 break;
2160 /* Nice places for line breaks are after strings, after
2161 comma or space and before slash. */
2162 case '"':
2163 q = handle_apos (q + 1);
2164 sep = q;
2165 break;
2166 case ',':
2167 case ' ':
2168 sep = q;
2169 break;
2170 case '/':
2171 case '\0':
2172 sep = q - 1;
2173 break;
2174 default:
2175 break;
2177 if (sep - p > 78)
2179 /* Enough stuff for a line. */
2180 fwrite (p, 1, sep - p, outfile);
2181 p = sep;
2182 if (*sep)
2184 /* The command continues. */
2185 fputc ('-', outfile);
2187 fputc ('\n', outfile);
2191 fwrite (p, 1, q - p, outfile);
2192 fputc ('\n', outfile);
2194 fclose (outfile);
2196 sprintf (cmd, "$ @%s", comname);
2198 DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
2201 cmddsc.dsc$w_length = strlen(cmd);
2202 cmddsc.dsc$a_pointer = cmd;
2203 cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
2204 cmddsc.dsc$b_class = DSC$K_CLASS_S;
2206 child->efn = 0;
2207 while (child->efn < 32 || child->efn > 63)
2209 status = lib$get_ef ((unsigned long *)&child->efn);
2210 if (!(status & 1))
2211 return 0;
2214 sys$clref (child->efn);
2216 vms_jobsefnmask |= (1 << (child->efn - 32));
2219 LIB$SPAWN [command-string]
2220 [,input-file]
2221 [,output-file]
2222 [,flags]
2223 [,process-name]
2224 [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
2225 [,AST-address] [,varying-AST-argument]
2226 [,prompt-string] [,cli] [,table]
2229 #ifndef DONTWAITFORCHILD
2231 * Code to make ctrl+c and ctrl+y working.
2232 * The problem starts with the synchronous case where after lib$spawn is
2233 * called any input will go to the child. But with input re-directed,
2234 * both control characters won't make it to any of the programs, neither
2235 * the spawning nor to the spawned one. Hence the caller needs to spawn
2236 * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
2237 * has to follow to simulate the wanted synchronous behaviour.
2238 * The next problem is ctrl+y which isn't caught by the crtl and
2239 * therefore isn't converted to SIGQUIT (for a signal handler which is
2240 * already established). The only way to catch ctrl+y, is an AST
2241 * assigned to the input channel. But ctrl+y handling of DCL needs to be
2242 * disabled, otherwise it will handle it. Not to mention the previous
2243 * ctrl+y handling of DCL needs to be re-established before make exits.
2244 * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
2245 * make it to the signal handler after the child "normally" terminates.
2246 * This isn't enough. It seems reasonable for simple command lines like
2247 * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
2248 * spawning make. Therefore we need to abort the process in the AST.
2250 * Prior to the spawn it is checked if an AST is already set up for
2251 * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
2252 * this will work except if make is run in a batch environment, but there
2253 * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
2254 * is disabled and an exit handler is established to re-enable it.
2255 * If the user interrupts with ctrl+y, the assigned AST will fire, force
2256 * an abort to the subprocess and signal SIGQUIT, which will be caught by
2257 * the already established handler and will bring us back to common code.
2258 * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
2259 * enables the ctrl+y be delivered to this code. And the ctrl+c too,
2260 * which the crtl converts to SIGINT and which is caught by the common
2261 * signal handler. Because signals were blocked before entering this code
2262 * sys$waitfr will always complete and the SIGQUIT will be processed after
2263 * it (after termination of the current block, somewhere in common code).
2264 * And SIGINT too will be delayed. That is ctrl+c can only abort when the
2265 * current command completes. Anyway it's better than nothing :-)
2268 if (!setupYAstTried)
2269 tryToSetupYAst();
2270 status = lib$spawn (&cmddsc, /* cmd-string */
2271 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file */
2272 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
2273 &spflags, /* flags */
2274 &pnamedsc, /* proc name */
2275 &child->pid, &child->cstatus, &child->efn,
2276 0, 0,
2277 0, 0, 0);
2278 if (status & 1)
2280 pidToAbort= child->pid;
2281 status= sys$waitfr (child->efn);
2282 pidToAbort= 0;
2283 vmsHandleChildTerm(child);
2285 #else
2286 status = lib$spawn (&cmddsc,
2287 (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
2288 (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
2289 &spflags,
2290 &pnamedsc,
2291 &child->pid, &child->cstatus, &child->efn,
2292 vmsHandleChildTerm, child,
2293 0, 0, 0);
2294 #endif
2296 if (!(status & 1))
2298 printf (_("Error spawning, %d\n") ,status);
2299 fflush (stdout);
2300 switch (status)
2302 case 0x1c:
2303 errno = EPROCLIM;
2304 break;
2305 default:
2306 errno = EFAIL;
2310 if (comname && !ISDB (DB_JOBS))
2311 unlink (comname);
2313 return (status & 1);
2316 #else /* !VMS */
2318 /* EMX: Start a child process. This function returns the new pid. */
2319 # if defined __MSDOS__ || defined __EMX__
2321 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2323 int pid;
2324 /* stdin_fd == 0 means: nothing to do for stdin;
2325 stdout_fd == 1 means: nothing to do for stdout */
2326 int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
2327 int save_stdout = (stdout_fd != 1) ? dup (1): 1;
2329 /* < 0 only if dup() failed */
2330 if (save_stdin < 0)
2331 fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
2332 if (save_stdout < 0)
2333 fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
2335 /* Close unnecessary file handles for the child. */
2336 if (save_stdin != 0)
2337 CLOSE_ON_EXEC (save_stdin);
2338 if (save_stdout != 1)
2339 CLOSE_ON_EXEC (save_stdout);
2341 /* Connect the pipes to the child process. */
2342 if (stdin_fd != 0)
2343 (void) dup2 (stdin_fd, 0);
2344 if (stdout_fd != 1)
2345 (void) dup2 (stdout_fd, 1);
2347 /* stdin_fd and stdout_fd must be closed on exit because we are
2348 still in the parent process */
2349 if (stdin_fd != 0)
2350 CLOSE_ON_EXEC (stdin_fd);
2351 if (stdout_fd != 1)
2352 CLOSE_ON_EXEC (stdout_fd);
2354 /* Run the command. */
2355 pid = exec_command (argv, envp);
2357 /* Restore stdout/stdin of the parent process. */
2358 if (stdin_fd != 0 && dup2 (save_stdin, 0) != 0)
2359 fatal (NILF, _("restoring of stdin failed\n"));
2360 if (stdout_fd != 1 && dup2 (save_stdout, 1) != 1)
2361 fatal (NILF, _("restoring of stdout failed\n"));
2363 return pid;
2366 #elif !defined (_AMIGA) && !defined (__MSDOS__)
2368 /* UNIX:
2369 Replace the current process with one executing the command in ARGV.
2370 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2371 the environment of the new program. This function does not return. */
2372 void
2373 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2375 if (stdin_fd != 0)
2376 (void) dup2 (stdin_fd, 0);
2377 if (stdout_fd != 1)
2378 (void) dup2 (stdout_fd, 1);
2379 if (stdin_fd != 0)
2380 (void) close (stdin_fd);
2381 if (stdout_fd != 1)
2382 (void) close (stdout_fd);
2384 /* Run the command. */
2385 exec_command (argv, envp);
2387 #endif /* !AMIGA && !__MSDOS__ */
2388 #endif /* !VMS */
2389 #endif /* !WINDOWS32 */
2391 #ifndef _AMIGA
2392 /* Replace the current process with one running the command in ARGV,
2393 with environment ENVP. This function does not return. */
2395 /* EMX: This function returns the pid of the child process. */
2396 # ifdef __EMX__
2398 # else
2399 void
2400 # endif
2401 exec_command (char **argv, char **envp)
2403 #ifdef VMS
2404 /* to work around a problem with signals and execve: ignore them */
2405 #ifdef SIGCHLD
2406 signal (SIGCHLD,SIG_IGN);
2407 #endif
2408 /* Run the program. */
2409 execve (argv[0], argv, envp);
2410 perror_with_name ("execve: ", argv[0]);
2411 _exit (EXIT_FAILURE);
2412 #else
2413 #ifdef WINDOWS32
2414 HANDLE hPID;
2415 HANDLE hWaitPID;
2416 int err = 0;
2417 int exit_code = EXIT_FAILURE;
2419 /* make sure CreateProcess() has Path it needs */
2420 sync_Path_environment();
2422 /* launch command */
2423 hPID = process_easy(argv, envp);
2425 /* make sure launch ok */
2426 if (hPID == INVALID_HANDLE_VALUE)
2428 int i;
2429 fprintf(stderr,
2430 _("process_easy() failed failed to launch process (e=%d)\n"),
2431 process_last_err(hPID));
2432 for (i = 0; argv[i]; i++)
2433 fprintf(stderr, "%s ", argv[i]);
2434 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2435 exit(EXIT_FAILURE);
2438 /* wait and reap last child */
2439 while (hWaitPID = process_wait_for_any())
2441 /* was an error found on this process? */
2442 err = process_last_err(hWaitPID);
2444 /* get exit data */
2445 exit_code = process_exit_code(hWaitPID);
2447 if (err)
2448 fprintf(stderr, "make (e=%d, rc=%d): %s",
2449 err, exit_code, map_windows32_error_to_string(err));
2451 /* cleanup process */
2452 process_cleanup(hWaitPID);
2454 /* expect to find only last pid, warn about other pids reaped */
2455 if (hWaitPID == hPID)
2456 break;
2457 else
2458 fprintf(stderr,
2459 _("make reaped child pid %d, still waiting for pid %d\n"),
2460 hWaitPID, hPID);
2463 /* return child's exit code as our exit code */
2464 exit(exit_code);
2466 #else /* !WINDOWS32 */
2468 # ifdef __EMX__
2469 int pid;
2470 # endif
2472 /* Be the user, permanently. */
2473 child_access ();
2475 # ifdef __EMX__
2477 /* Run the program. */
2478 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2480 if (pid >= 0)
2481 return pid;
2483 /* the file might have a strange shell extension */
2484 if (errno == ENOENT)
2485 errno = ENOEXEC;
2487 # else
2489 /* Run the program. */
2490 environ = envp;
2491 execvp (argv[0], argv);
2493 # endif /* !__EMX__ */
2495 switch (errno)
2497 case ENOENT:
2498 error (NILF, _("%s: Command not found"), argv[0]);
2499 break;
2500 case ENOEXEC:
2502 /* The file is not executable. Try it as a shell script. */
2503 extern char *getenv ();
2504 char *shell;
2505 char **new_argv;
2506 int argc;
2508 # ifdef __EMX__
2509 /* Do not use $SHELL from the environment */
2510 shell = lookup_variable ("SHELL", 5);
2511 if (shell)
2512 shell = shell->value;
2513 else
2514 shell = 0;
2515 # else
2516 shell = getenv ("SHELL");
2517 # endif
2518 if (shell == 0)
2519 shell = default_shell;
2521 argc = 1;
2522 while (argv[argc] != 0)
2523 ++argc;
2525 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
2526 new_argv[0] = shell;
2527 new_argv[1] = argv[0];
2528 while (argc > 0)
2530 new_argv[1 + argc] = argv[argc];
2531 --argc;
2534 # ifdef __EMX__
2535 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2536 if (pid >= 0)
2537 break;
2538 # else
2539 execvp (shell, new_argv);
2540 # endif
2541 if (errno == ENOENT)
2542 error (NILF, _("%s: Shell program not found"), shell);
2543 else
2544 perror_with_name ("execvp: ", shell);
2545 break;
2548 # ifdef __EMX__
2549 case EINVAL:
2550 /* this nasty error was driving me nuts :-( */
2551 error (NILF, _("spawnvpe: environment space might be exhausted"));
2552 /* FALLTHROUGH */
2553 # endif
2555 default:
2556 perror_with_name ("execvp: ", argv[0]);
2557 break;
2560 # ifdef __EMX__
2561 return pid;
2562 # else
2563 _exit (127);
2564 # endif
2565 #endif /* !WINDOWS32 */
2566 #endif /* !VMS */
2568 #else /* On Amiga */
2569 void exec_command (char **argv)
2571 MyExecute (argv);
2574 void clean_tmp (void)
2576 DeleteFile (amiga_bname);
2579 #endif /* On Amiga */
2581 #ifndef VMS
2582 /* Figure out the argument list necessary to run LINE as a command. Try to
2583 avoid using a shell. This routine handles only ' quoting, and " quoting
2584 when no backslash, $ or ` characters are seen in the quotes. Starting
2585 quotes may be escaped with a backslash. If any of the characters in
2586 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2587 is the first word of a line, the shell is used.
2589 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2590 If *RESTP is NULL, newlines will be ignored.
2592 SHELL is the shell to use, or nil to use the default shell.
2593 IFS is the value of $IFS, or nil (meaning the default). */
2595 static char **
2596 construct_command_argv_internal (char *line, char **restp, char *shell,
2597 char *ifs, char **batch_filename_ptr)
2599 #ifdef __MSDOS__
2600 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2601 We call `system' for anything that requires ``slow'' processing,
2602 because DOS shells are too dumb. When $SHELL points to a real
2603 (unix-style) shell, `system' just calls it to do everything. When
2604 $SHELL points to a DOS shell, `system' does most of the work
2605 internally, calling the shell only for its internal commands.
2606 However, it looks on the $PATH first, so you can e.g. have an
2607 external command named `mkdir'.
2609 Since we call `system', certain characters and commands below are
2610 actually not specific to COMMAND.COM, but to the DJGPP implementation
2611 of `system'. In particular:
2613 The shell wildcard characters are in DOS_CHARS because they will
2614 not be expanded if we call the child via `spawnXX'.
2616 The `;' is in DOS_CHARS, because our `system' knows how to run
2617 multiple commands on a single line.
2619 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2620 won't have to tell one from another and have one more set of
2621 commands and special characters. */
2622 static char sh_chars_dos[] = "*?[];|<>%^&()";
2623 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2624 "copy", "ctty", "date", "del", "dir", "echo",
2625 "erase", "exit", "for", "goto", "if", "md",
2626 "mkdir", "path", "pause", "prompt", "rd",
2627 "rmdir", "rem", "ren", "rename", "set",
2628 "shift", "time", "type", "ver", "verify",
2629 "vol", ":", 0 };
2631 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2632 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2633 "logout", "set", "umask", "wait", "while",
2634 "for", "case", "if", ":", ".", "break",
2635 "continue", "export", "read", "readonly",
2636 "shift", "times", "trap", "switch", "unset",
2637 0 };
2639 char *sh_chars;
2640 char **sh_cmds;
2641 #elif defined (__EMX__)
2642 static char sh_chars_dos[] = "*?[];|<>%^&()";
2643 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2644 "copy", "ctty", "date", "del", "dir", "echo",
2645 "erase", "exit", "for", "goto", "if", "md",
2646 "mkdir", "path", "pause", "prompt", "rd",
2647 "rmdir", "rem", "ren", "rename", "set",
2648 "shift", "time", "type", "ver", "verify",
2649 "vol", ":", 0 };
2651 static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
2652 static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2653 "date", "del", "detach", "dir", "echo",
2654 "endlocal", "erase", "exit", "for", "goto", "if",
2655 "keys", "md", "mkdir", "move", "path", "pause",
2656 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2657 "set", "setlocal", "shift", "start", "time",
2658 "type", "ver", "verify", "vol", ":", 0 };
2660 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~'";
2661 static char *sh_cmds_sh[] = { "echo", "cd", "eval", "exec", "exit", "login",
2662 "logout", "set", "umask", "wait", "while",
2663 "for", "case", "if", ":", ".", "break",
2664 "continue", "export", "read", "readonly",
2665 "shift", "times", "trap", "switch", "unset",
2666 0 };
2667 char *sh_chars;
2668 char **sh_cmds;
2670 #elif defined (_AMIGA)
2671 static char sh_chars[] = "#;\"|<>()?*$`";
2672 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2673 "rename", "set", "setenv", "date", "makedir",
2674 "skip", "else", "endif", "path", "prompt",
2675 "unset", "unsetenv", "version",
2676 0 };
2677 #elif defined (WINDOWS32)
2678 static char sh_chars_dos[] = "\"|&<>";
2679 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2680 "copy", "ctty", "date", "del", "dir", "echo",
2681 "erase", "exit", "for", "goto", "if", "if", "md",
2682 "mkdir", "path", "pause", "prompt", "rd", "rem",
2683 "ren", "rename", "rmdir", "set", "shift", "time",
2684 "type", "ver", "verify", "vol", ":", 0 };
2685 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2686 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2687 "logout", "set", "umask", "wait", "while", "for",
2688 "case", "if", ":", ".", "break", "continue",
2689 "export", "read", "readonly", "shift", "times",
2690 "trap", "switch", "test",
2691 #ifdef BATCH_MODE_ONLY_SHELL
2692 "echo",
2693 #endif
2694 0 };
2695 char* sh_chars;
2696 char** sh_cmds;
2697 #else /* must be UNIX-ish */
2698 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~";
2699 static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
2700 "logout", "set", "umask", "wait", "while", "for",
2701 "case", "if", ":", ".", "break", "continue",
2702 "export", "read", "readonly", "shift", "times",
2703 "trap", "switch", 0 };
2704 #endif /* __MSDOS__ */
2705 register int i;
2706 register char *p;
2707 register char *ap;
2708 char *end;
2709 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2710 char **new_argv = 0;
2711 #ifdef WINDOWS32
2712 int slow_flag = 0;
2714 if (no_default_sh_exe) {
2715 sh_cmds = sh_cmds_dos;
2716 sh_chars = sh_chars_dos;
2717 } else {
2718 sh_cmds = sh_cmds_sh;
2719 sh_chars = sh_chars_sh;
2721 #endif /* WINDOWS32 */
2723 if (restp != NULL)
2724 *restp = NULL;
2726 /* Make sure not to bother processing an empty line. */
2727 while (isblank ((unsigned char)*line))
2728 ++line;
2729 if (*line == '\0')
2730 return 0;
2732 /* See if it is safe to parse commands internally. */
2733 if (shell == 0)
2734 shell = default_shell;
2735 #ifdef WINDOWS32
2736 else if (strcmp (shell, default_shell))
2738 char *s1 = _fullpath(NULL, shell, 0);
2739 char *s2 = _fullpath(NULL, default_shell, 0);
2741 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2743 if (s1)
2744 free (s1);
2745 if (s2)
2746 free (s2);
2748 if (slow_flag)
2749 goto slow;
2750 #else /* not WINDOWS32 */
2751 #if defined (__MSDOS__) || defined (__EMX__)
2752 else if (stricmp (shell, default_shell))
2754 extern int _is_unixy_shell (const char *_path);
2756 DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
2757 default_shell, shell));
2758 unixy_shell = _is_unixy_shell (shell);
2759 default_shell = shell;
2760 /* we must allocate a copy of shell: construct_command_argv() will free
2761 * shell after this function returns. */
2762 default_shell = xmalloc (strlen (shell) + 1);
2763 strcpy (default_shell, shell);
2765 if (unixy_shell)
2767 sh_chars = sh_chars_sh;
2768 sh_cmds = sh_cmds_sh;
2770 else
2772 sh_chars = sh_chars_dos;
2773 sh_cmds = sh_cmds_dos;
2774 # ifdef __EMX__
2775 if (_osmode == OS2_MODE)
2777 sh_chars = sh_chars_os2;
2778 sh_cmds = sh_cmds_os2;
2780 # endif
2781 #else /* !__MSDOS__ */
2782 else if (strcmp (shell, default_shell))
2783 goto slow;
2784 #endif /* !__MSDOS__ && !__EMX__ */
2785 #endif /* not WINDOWS32 */
2787 if (ifs != 0)
2788 for (ap = ifs; *ap != '\0'; ++ap)
2789 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2790 goto slow;
2792 i = strlen (line) + 1;
2794 /* More than 1 arg per character is impossible. */
2795 new_argv = (char **) xmalloc (i * sizeof (char *));
2797 /* All the args can fit in a buffer as big as LINE is. */
2798 ap = new_argv[0] = (char *) xmalloc (i);
2799 end = ap + i;
2801 /* I is how many complete arguments have been found. */
2802 i = 0;
2803 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2804 for (p = line; *p != '\0'; ++p)
2806 if (ap > end)
2807 abort ();
2809 if (instring)
2811 string_char:
2812 /* Inside a string, just copy any char except a closing quote
2813 or a backslash-newline combination. */
2814 if (*p == instring)
2816 instring = 0;
2817 if (ap == new_argv[0] || *(ap-1) == '\0')
2818 last_argument_was_empty = 1;
2820 else if (*p == '\\' && p[1] == '\n')
2821 goto swallow_escaped_newline;
2822 else if (*p == '\n' && restp != NULL)
2824 /* End of the command line. */
2825 *restp = p;
2826 goto end_of_line;
2828 /* Backslash, $, and ` are special inside double quotes.
2829 If we see any of those, punt.
2830 But on MSDOS, if we use COMMAND.COM, double and single
2831 quotes have the same effect. */
2832 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2833 goto slow;
2834 else
2835 *ap++ = *p;
2837 else if (strchr (sh_chars, *p) != 0)
2838 /* Not inside a string, but it's a special char. */
2839 goto slow;
2840 #ifdef __MSDOS__
2841 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2842 /* `...' is a wildcard in DJGPP. */
2843 goto slow;
2844 #endif
2845 else
2846 /* Not a special char. */
2847 switch (*p)
2849 case '=':
2850 /* Equals is a special character in leading words before the
2851 first word with no equals sign in it. This is not the case
2852 with sh -k, but we never get here when using nonstandard
2853 shell flags. */
2854 if (! seen_nonequals && unixy_shell)
2855 goto slow;
2856 word_has_equals = 1;
2857 *ap++ = '=';
2858 break;
2860 case '\\':
2861 /* Backslash-newline combinations are eaten. */
2862 if (p[1] == '\n')
2864 swallow_escaped_newline:
2866 /* Eat the backslash, the newline, and following whitespace,
2867 replacing it all with a single space. */
2868 p += 2;
2870 /* If there is a tab after a backslash-newline,
2871 remove it from the source line which will be echoed,
2872 since it was most likely used to line
2873 up the continued line with the previous one. */
2874 if (*p == '\t')
2875 /* Note these overlap and strcpy() is undefined for
2876 overlapping objects in ANSI C. The strlen() _IS_ right,
2877 since we need to copy the nul byte too. */
2878 bcopy (p + 1, p, strlen (p));
2880 if (instring)
2881 goto string_char;
2882 else
2884 if (ap != new_argv[i])
2885 /* Treat this as a space, ending the arg.
2886 But if it's at the beginning of the arg, it should
2887 just get eaten, rather than becoming an empty arg. */
2888 goto end_of_arg;
2889 else
2890 p = next_token (p) - 1;
2893 else if (p[1] != '\0')
2895 #ifdef HAVE_DOS_PATHS
2896 /* Only remove backslashes before characters special
2897 to Unixy shells. All other backslashes are copied
2898 verbatim, since they are probably DOS-style
2899 directory separators. This still leaves a small
2900 window for problems, but at least it should work
2901 for the vast majority of naive users. */
2903 #ifdef __MSDOS__
2904 /* A dot is only special as part of the "..."
2905 wildcard. */
2906 if (strneq (p + 1, ".\\.\\.", 5))
2908 *ap++ = '.';
2909 *ap++ = '.';
2910 p += 4;
2912 else
2913 #endif
2914 if (p[1] != '\\' && p[1] != '\''
2915 && !isspace ((unsigned char)p[1])
2916 && (strchr (sh_chars_sh, p[1]) == 0))
2917 /* back up one notch, to copy the backslash */
2918 --p;
2919 #endif /* HAVE_DOS_PATHS */
2921 /* Copy and skip the following char. */
2922 *ap++ = *++p;
2924 break;
2926 case '\'':
2927 case '"':
2928 instring = *p;
2929 break;
2931 case '\n':
2932 if (restp != NULL)
2934 /* End of the command line. */
2935 *restp = p;
2936 goto end_of_line;
2938 else
2939 /* Newlines are not special. */
2940 *ap++ = '\n';
2941 break;
2943 case ' ':
2944 case '\t':
2945 end_of_arg:
2946 /* We have the end of an argument.
2947 Terminate the text of the argument. */
2948 *ap++ = '\0';
2949 new_argv[++i] = ap;
2950 last_argument_was_empty = 0;
2952 /* Update SEEN_NONEQUALS, which tells us if every word
2953 heretofore has contained an `='. */
2954 seen_nonequals |= ! word_has_equals;
2955 if (word_has_equals && ! seen_nonequals)
2956 /* An `=' in a word before the first
2957 word without one is magical. */
2958 goto slow;
2959 word_has_equals = 0; /* Prepare for the next word. */
2961 /* If this argument is the command name,
2962 see if it is a built-in shell command.
2963 If so, have the shell handle it. */
2964 if (i == 1)
2966 register int j;
2967 for (j = 0; sh_cmds[j] != 0; ++j)
2968 if (streq (sh_cmds[j], new_argv[0]))
2969 goto slow;
2972 /* Ignore multiple whitespace chars. */
2973 p = next_token (p);
2974 /* Next iteration should examine the first nonwhite char. */
2975 --p;
2976 break;
2978 default:
2979 *ap++ = *p;
2980 break;
2983 end_of_line:
2985 if (instring)
2986 /* Let the shell deal with an unterminated quote. */
2987 goto slow;
2989 /* Terminate the last argument and the argument list. */
2991 *ap = '\0';
2992 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2993 ++i;
2994 new_argv[i] = 0;
2996 if (i == 1)
2998 register int j;
2999 for (j = 0; sh_cmds[j] != 0; ++j)
3000 if (streq (sh_cmds[j], new_argv[0]))
3001 goto slow;
3004 if (new_argv[0] == 0)
3005 /* Line was empty. */
3006 return 0;
3007 else
3008 return new_argv;
3010 slow:;
3011 /* We must use the shell. */
3013 if (new_argv != 0)
3015 /* Free the old argument list we were working on. */
3016 free (new_argv[0]);
3017 free ((void *)new_argv);
3020 #ifdef __MSDOS__
3021 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
3022 #endif
3024 #ifdef _AMIGA
3026 char *ptr;
3027 char *buffer;
3028 char *dptr;
3030 buffer = (char *)xmalloc (strlen (line)+1);
3032 ptr = line;
3033 for (dptr=buffer; *ptr; )
3035 if (*ptr == '\\' && ptr[1] == '\n')
3036 ptr += 2;
3037 else if (*ptr == '@') /* Kludge: multiline commands */
3039 ptr += 2;
3040 *dptr++ = '\n';
3042 else
3043 *dptr++ = *ptr++;
3045 *dptr = 0;
3047 new_argv = (char **) xmalloc (2 * sizeof (char *));
3048 new_argv[0] = buffer;
3049 new_argv[1] = 0;
3051 #else /* Not Amiga */
3052 #ifdef WINDOWS32
3054 * Not eating this whitespace caused things like
3056 * sh -c "\n"
3058 * which gave the shell fits. I think we have to eat
3059 * whitespace here, but this code should be considered
3060 * suspicious if things start failing....
3063 /* Make sure not to bother processing an empty line. */
3064 while (isspace ((unsigned char)*line))
3065 ++line;
3066 if (*line == '\0')
3067 return 0;
3068 #endif /* WINDOWS32 */
3070 /* SHELL may be a multi-word command. Construct a command line
3071 "SHELL -c LINE", with all special chars in LINE escaped.
3072 Then recurse, expanding this command line to get the final
3073 argument list. */
3075 unsigned int shell_len = strlen (shell);
3076 #ifndef VMS
3077 static char minus_c[] = " -c ";
3078 #else
3079 static char minus_c[] = "";
3080 #endif
3081 unsigned int line_len = strlen (line);
3083 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
3084 + (line_len * 2) + 1);
3085 char *command_ptr = NULL; /* used for batch_mode_shell mode */
3087 # ifdef __EMX__ /* is this necessary? */
3088 if (!unixy_shell)
3089 minus_c[1] = '/'; /* " /c " */
3090 # endif
3092 ap = new_line;
3093 bcopy (shell, ap, shell_len);
3094 ap += shell_len;
3095 bcopy (minus_c, ap, sizeof (minus_c) - 1);
3096 ap += sizeof (minus_c) - 1;
3097 command_ptr = ap;
3098 for (p = line; *p != '\0'; ++p)
3100 if (restp != NULL && *p == '\n')
3102 *restp = p;
3103 break;
3105 else if (*p == '\\' && p[1] == '\n')
3107 /* Eat the backslash, the newline, and following whitespace,
3108 replacing it all with a single space (which is escaped
3109 from the shell). */
3110 p += 2;
3112 /* If there is a tab after a backslash-newline,
3113 remove it from the source line which will be echoed,
3114 since it was most likely used to line
3115 up the continued line with the previous one. */
3116 if (*p == '\t')
3117 bcopy (p + 1, p, strlen (p));
3119 p = next_token (p);
3120 --p;
3121 if (unixy_shell && !batch_mode_shell)
3122 *ap++ = '\\';
3123 *ap++ = ' ';
3124 continue;
3127 /* DOS shells don't know about backslash-escaping. */
3128 if (unixy_shell && !batch_mode_shell &&
3129 (*p == '\\' || *p == '\'' || *p == '"'
3130 || isspace ((unsigned char)*p)
3131 || strchr (sh_chars, *p) != 0))
3132 *ap++ = '\\';
3133 #ifdef __MSDOS__
3134 else if (unixy_shell && strneq (p, "...", 3))
3136 /* The case of `...' wildcard again. */
3137 strcpy (ap, "\\.\\.\\");
3138 ap += 5;
3139 p += 2;
3141 #endif
3142 *ap++ = *p;
3144 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
3145 /* Line was empty. */
3146 return 0;
3147 *ap = '\0';
3149 #ifdef WINDOWS32
3150 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
3151 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
3152 cases, run commands via a script file. */
3153 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
3154 FILE* batch = NULL;
3155 int id = GetCurrentProcessId();
3156 PATH_VAR(fbuf);
3157 char* fname = NULL;
3159 /* create a file name */
3160 sprintf(fbuf, "make%d", id);
3161 fname = tempnam(".", fbuf);
3163 /* create batch file name */
3164 *batch_filename_ptr = xmalloc(strlen(fname) + 5);
3165 strcpy(*batch_filename_ptr, fname);
3167 /* make sure path name is in DOS backslash format */
3168 if (!unixy_shell) {
3169 fname = *batch_filename_ptr;
3170 for (i = 0; fname[i] != '\0'; ++i)
3171 if (fname[i] == '/')
3172 fname[i] = '\\';
3173 strcat(*batch_filename_ptr, ".bat");
3174 } else {
3175 strcat(*batch_filename_ptr, ".sh");
3178 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
3179 *batch_filename_ptr));
3181 /* create batch file to execute command */
3182 batch = fopen (*batch_filename_ptr, "w");
3183 if (!unixy_shell)
3184 fputs ("@echo off\n", batch);
3185 fputs (command_ptr, batch);
3186 fputc ('\n', batch);
3187 fclose (batch);
3189 /* create argv */
3190 new_argv = (char **) xmalloc(3 * sizeof (char *));
3191 if (unixy_shell) {
3192 new_argv[0] = xstrdup (shell);
3193 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
3194 } else {
3195 new_argv[0] = xstrdup (*batch_filename_ptr);
3196 new_argv[1] = NULL;
3198 new_argv[2] = NULL;
3199 } else
3200 #endif /* WINDOWS32 */
3201 if (unixy_shell)
3202 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
3203 (char *) 0, (char *) 0,
3204 (char **) 0);
3205 # ifdef __EMX__
3206 else if (!unixy_shell)
3208 /* new_line is local, must not be freed therefore */
3209 char *p, *q;
3210 int quote;
3211 size_t index;
3212 size_t len;
3214 /* handle quotes
3215 We have to remove all double quotes and to split the line
3216 into distinct arguments because of the strange handling
3217 of builtin commands by cmd: 'echo "bla"' prints "bla"
3218 (with quotes) while 'c:\bin\echo.exe "bla"' prints bla
3219 (without quotes). Some programs like autoconf rely
3220 on the second behaviour. */
3222 len = strlen (new_line) + 1;
3224 /* More than 1 arg per character is impossible. */
3225 new_argv = (char **) xmalloc (len * sizeof (char *));
3227 /* All the args can fit in a buffer as big as new_line is. */
3228 new_argv[0] = (char *) xmalloc (len);
3230 index = 0;
3231 quote = 0;
3232 q = new_line;
3233 p = new_argv[index];
3234 while(*q != '\0')
3236 /* searching for closing quote */
3237 if (quote)
3239 if (*q == quote)
3241 /* remove the quote */
3242 q++;
3243 quote = 0;
3245 else /* normal character: copy it */
3246 *p++ = *q++;
3249 /* searching for opening quote */
3250 else if (*q == '\"'
3251 # ifndef NO_CMD_DEFAULT
3252 || *q == '\''
3253 # endif
3256 /* remove opening quote */
3257 quote = *q;
3258 q++;
3261 /* spaces outside of a quoted string: remove them
3262 and start a new argument */
3263 else if (*q == ' ' || *q == '\t')
3265 *p++ = '\0'; /* trailing '\0' for last argument */
3267 /* remove all successive spaces */
3270 q++;
3272 while(*q == ' ' || *q == '\t');
3274 /* start new argument */
3275 index++;
3276 new_argv[index] = p;
3279 /* normal character (no space) outside a quoted string*/
3280 else
3281 *p++ = *q++;
3282 } /* end while() */
3284 *p = '\0'; /* trailing '\0' for the last argument */
3285 new_argv[index + 1] = NULL;
3287 # ifndef NO_CMD_DEFAULT
3288 /* special case: echo x="y"
3289 (e.g. autoconf uses this to determine whether make works)
3290 this is pure idioty but cmd works this way:
3291 if 'echo' and 'x="y"' are two different arguments cmd
3292 will print '"x="y""' but if they are only one argument
3293 cmd will print 'bla="blurb"' as it should be
3294 note: if we do not allow cmd to be the default shell
3295 we do not need this kind of voodoo */
3296 if (index == 3 && strcasecmp(new_argv[2], "echo") == 0)
3298 new_argv[2][4] = ' ';
3299 new_argv[3] = NULL;
3301 # endif
3303 #elif defined(__MSDOS__)
3304 else
3306 /* With MSDOS shells, we must construct the command line here
3307 instead of recursively calling ourselves, because we
3308 cannot backslash-escape the special characters (see above). */
3309 new_argv = (char **) xmalloc (sizeof (char *));
3310 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
3311 new_argv[0] = xmalloc (line_len + 1);
3312 strncpy (new_argv[0],
3313 new_line + shell_len + sizeof (minus_c) - 1, line_len);
3314 new_argv[0][line_len] = '\0';
3316 #else
3317 else
3318 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3319 __FILE__, __LINE__);
3320 #endif
3322 #endif /* ! AMIGA */
3324 return new_argv;
3326 #endif /* !VMS */
3328 /* Figure out the argument list necessary to run LINE as a command. Try to
3329 avoid using a shell. This routine handles only ' quoting, and " quoting
3330 when no backslash, $ or ` characters are seen in the quotes. Starting
3331 quotes may be escaped with a backslash. If any of the characters in
3332 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3333 is the first word of a line, the shell is used.
3335 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3336 If *RESTP is NULL, newlines will be ignored.
3338 FILE is the target whose commands these are. It is used for
3339 variable expansion for $(SHELL) and $(IFS). */
3341 char **
3342 construct_command_argv (char *line, char **restp, struct file *file,
3343 char **batch_filename_ptr)
3345 char *shell, *ifs;
3346 char **argv;
3348 #ifdef VMS
3349 char *cptr;
3350 int argc;
3352 argc = 0;
3353 cptr = line;
3354 for (;;)
3356 while ((*cptr != 0)
3357 && (isspace ((unsigned char)*cptr)))
3358 cptr++;
3359 if (*cptr == 0)
3360 break;
3361 while ((*cptr != 0)
3362 && (!isspace((unsigned char)*cptr)))
3363 cptr++;
3364 argc++;
3367 argv = (char **)malloc (argc * sizeof (char *));
3368 if (argv == 0)
3369 abort ();
3371 cptr = line;
3372 argc = 0;
3373 for (;;)
3375 while ((*cptr != 0)
3376 && (isspace ((unsigned char)*cptr)))
3377 cptr++;
3378 if (*cptr == 0)
3379 break;
3380 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3381 argv[argc++] = cptr;
3382 while ((*cptr != 0)
3383 && (!isspace((unsigned char)*cptr)))
3384 cptr++;
3385 if (*cptr != 0)
3386 *cptr++ = 0;
3388 #else
3390 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3391 int save = warn_undefined_variables_flag;
3392 warn_undefined_variables_flag = 0;
3394 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3395 #ifdef WINDOWS32
3397 * Convert to forward slashes so that construct_command_argv_internal()
3398 * is not confused.
3400 if (shell) {
3401 char *p = w32ify (shell, 0);
3402 strcpy (shell, p);
3404 #endif
3405 #ifdef __EMX__
3407 static const char *unixroot = NULL;
3408 static const char *last_shell = "";
3409 static int init = 0;
3410 if (init == 0)
3412 unixroot = getenv ("UNIXROOT");
3413 /* unixroot must be NULL or not empty */
3414 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3415 init = 1;
3418 /* if we have an unixroot drive and if shell is not default_shell
3419 (which means it's either cmd.exe or the test has already been
3420 performed) and if shell is an absolute path without drive letter,
3421 try whether it exists e.g.: if "/bin/sh" does not exist use
3422 "$UNIXROOT/bin/sh" instead. */
3423 if (unixroot && shell && strcmp (shell, last_shell) != 0
3424 && (shell[0] == '/' || shell[0] == '\\'))
3426 /* trying a new shell, check whether it exists */
3427 size_t size = strlen (shell);
3428 char *buf = xmalloc (size + 7);
3429 memcpy (buf, shell, size);
3430 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3431 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3433 /* try the same for the unixroot drive */
3434 memmove (buf + 2, buf, size + 5);
3435 buf[0] = unixroot[0];
3436 buf[1] = unixroot[1];
3437 if (access (buf, F_OK) == 0)
3438 /* we have found a shell! */
3439 /* free(shell); */
3440 shell = buf;
3441 else
3442 free (buf);
3444 else
3445 free (buf);
3448 #endif __EMX__
3450 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3452 warn_undefined_variables_flag = save;
3455 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
3457 free (shell);
3458 free (ifs);
3459 #endif /* !VMS */
3460 return argv;
3463 #if !defined(HAVE_DUP2) && !defined(_AMIGA)
3465 dup2 (int old, int new)
3467 int fd;
3469 (void) close (new);
3470 fd = dup (old);
3471 if (fd != new)
3473 (void) close (fd);
3474 errno = EMFILE;
3475 return -1;
3478 return fd;
3480 #endif /* !HAPE_DUP2 && !_AMIGA */