VirtualBox

source: kBuild/trunk/src/gmake/job.c@ 311

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

join + optimizations.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette