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

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

Win32 batch hack.

  • Property svn:eol-style set to native
File size: 92.7 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#ifdef CONFIG_WITH_KMK_BUILTIN
1019 |= flags & (COMMANDS_RECURSE | COMMANDS_BUILTIN);
1020#else
1021 |= flags & COMMANDS_RECURSE;
1022#endif
1023
1024 /* Figure out an argument list from this command line. */
1025
1026 {
1027 char *end = 0;
1028#ifdef VMS
1029 argv = p;
1030#else
1031 argv = construct_command_argv (p, &end, child->file, &child->sh_batch_file);
1032#endif
1033 if (end == NULL)
1034 child->command_ptr = NULL;
1035 else
1036 {
1037 *end++ = '\0';
1038 child->command_ptr = end;
1039 }
1040 }
1041
1042 /* If -q was given, say that updating `failed' if there was any text on the
1043 command line, or `succeeded' otherwise. The exit status of 1 tells the
1044 user that -q is saying `something to do'; the exit status for a random
1045 error is 2. */
1046 if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
1047 {
1048#ifndef VMS
1049 free (argv[0]);
1050 free ((char *) argv);
1051#endif
1052 child->file->update_status = 1;
1053 notice_finished_file (child->file);
1054 return;
1055 }
1056
1057 if (touch_flag && !(flags & COMMANDS_RECURSE))
1058 {
1059 /* Go on to the next command. It might be the recursive one.
1060 We construct ARGV only to find the end of the command line. */
1061#ifndef VMS
1062 if (argv)
1063 {
1064 free (argv[0]);
1065 free ((char *) argv);
1066 }
1067#endif
1068 argv = 0;
1069 }
1070
1071 if (argv == 0)
1072 {
1073 next_command:
1074#ifdef __MSDOS__
1075 execute_by_shell = 0; /* in case construct_command_argv sets it */
1076#endif
1077 /* This line has no commands. Go to the next. */
1078 if (job_next_command (child))
1079 start_job_command (child);
1080 else
1081 {
1082 /* No more commands. Make sure we're "running"; we might not be if
1083 (e.g.) all commands were skipped due to -n. */
1084 set_command_state (child->file, cs_running);
1085 child->file->update_status = 0;
1086 notice_finished_file (child->file);
1087 }
1088 return;
1089 }
1090
1091 /* Print out the command. If silent, we call `message' with null so it
1092 can log the working directory before the command's own error messages
1093 appear. */
1094
1095 message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
1096 ? "%s" : (char *) 0, p);
1097
1098 /* Tell update_goal_chain that a command has been started on behalf of
1099 this target. It is important that this happens here and not in
1100 reap_children (where we used to do it), because reap_children might be
1101 reaping children from a different target. We want this increment to
1102 guaranteedly indicate that a command was started for the dependency
1103 chain (i.e., update_file recursion chain) we are processing. */
1104
1105 ++commands_started;
1106
1107 /* Optimize an empty command. People use this for timestamp rules,
1108 so avoid forking a useless shell. Do this after we increment
1109 commands_started so make still treats this special case as if it
1110 performed some action (makes a difference as to what messages are
1111 printed, etc. */
1112
1113#if !defined(VMS) && !defined(_AMIGA)
1114 if (
1115#if defined __MSDOS__ || defined (__EMX__)
1116 unixy_shell /* the test is complicated and we already did it */
1117#else
1118 (argv[0] && !strcmp (argv[0], "/bin/sh"))
1119#endif
1120 && (argv[1]
1121 && argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0')
1122 && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
1123 && argv[3] == NULL)
1124 {
1125 free (argv[0]);
1126 free ((char *) argv);
1127 goto next_command;
1128 }
1129#endif /* !VMS && !_AMIGA */
1130
1131 /* If -n was given, recurse to get the next line in the sequence. */
1132
1133 if (just_print_flag && !(flags & COMMANDS_RECURSE))
1134 {
1135#ifndef VMS
1136 free (argv[0]);
1137 free ((char *) argv);
1138#endif
1139 goto next_command;
1140 }
1141
1142#ifdef CONFIG_WITH_KMK_BUILTIN
1143 /* If builtin command then pass it on to the builtin shell interpreter. */
1144
1145 if ((flags & COMMANDS_BUILTIN) && !just_print_flag)
1146 {
1147 int rc;
1148 char **p2 = argv;
1149 while (*p2 && strncmp(*p2, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
1150 p2++;
1151 assert(*p2);
1152 set_command_state (child->file, cs_running);
1153 if (p2 != argv)
1154 rc = kmk_builtin_command(*p2);
1155 else
1156 {
1157 int argc = 1;
1158 while (argv[argc])
1159 argc++;
1160 rc = kmk_builtin_command_parsed(argc, argv);
1161 }
1162#ifndef VMS
1163 free (argv[0]);
1164 free ((char *) argv);
1165#endif
1166 if (!rc)
1167 goto next_command;
1168 child->pid = (pid_t)42424242;
1169 child->status = rc << 8;
1170 child->have_status = 1;
1171 return;
1172 }
1173#endif /* CONFIG_WITH_KMK_BUILTIN */
1174
1175 /* Flush the output streams so they won't have things written twice. */
1176
1177 fflush (stdout);
1178 fflush (stderr);
1179
1180#ifndef VMS
1181#if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
1182
1183 /* Set up a bad standard input that reads from a broken pipe. */
1184
1185 if (bad_stdin == -1)
1186 {
1187 /* Make a file descriptor that is the read end of a broken pipe.
1188 This will be used for some children's standard inputs. */
1189 int pd[2];
1190 if (pipe (pd) == 0)
1191 {
1192 /* Close the write side. */
1193 (void) close (pd[1]);
1194 /* Save the read side. */
1195 bad_stdin = pd[0];
1196
1197 /* Set the descriptor to close on exec, so it does not litter any
1198 child's descriptor table. When it is dup2'd onto descriptor 0,
1199 that descriptor will not close on exec. */
1200 CLOSE_ON_EXEC (bad_stdin);
1201 }
1202 }
1203
1204#endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
1205
1206 /* Decide whether to give this child the `good' standard input
1207 (one that points to the terminal or whatever), or the `bad' one
1208 that points to the read side of a broken pipe. */
1209
1210 child->good_stdin = !good_stdin_used;
1211 if (child->good_stdin)
1212 good_stdin_used = 1;
1213
1214#endif /* !VMS */
1215
1216 child->deleted = 0;
1217
1218#ifndef _AMIGA
1219 /* Set up the environment for the child. */
1220 if (child->environment == 0)
1221 child->environment = target_environment (child->file);
1222#endif
1223
1224#if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
1225
1226#ifndef VMS
1227 /* start_waiting_job has set CHILD->remote if we can start a remote job. */
1228 if (child->remote)
1229 {
1230 int is_remote, id, used_stdin;
1231 if (start_remote_job (argv, child->environment,
1232 child->good_stdin ? 0 : bad_stdin,
1233 &is_remote, &id, &used_stdin))
1234 /* Don't give up; remote execution may fail for various reasons. If
1235 so, simply run the job locally. */
1236 goto run_local;
1237 else
1238 {
1239 if (child->good_stdin && !used_stdin)
1240 {
1241 child->good_stdin = 0;
1242 good_stdin_used = 0;
1243 }
1244 child->remote = is_remote;
1245 child->pid = id;
1246 }
1247 }
1248 else
1249#endif /* !VMS */
1250 {
1251 /* Fork the child process. */
1252
1253 char **parent_environ;
1254
1255 run_local:
1256 block_sigs ();
1257
1258 child->remote = 0;
1259
1260#ifdef VMS
1261 if (!child_execute_job (argv, child)) {
1262 /* Fork failed! */
1263 perror_with_name ("vfork", "");
1264 goto error;
1265 }
1266
1267#else
1268
1269 parent_environ = environ;
1270
1271# ifdef __EMX__
1272 /* If we aren't running a recursive command and we have a jobserver
1273 pipe, close it before exec'ing. */
1274 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1275 {
1276 CLOSE_ON_EXEC (job_fds[0]);
1277 CLOSE_ON_EXEC (job_fds[1]);
1278 }
1279 if (job_rfd >= 0)
1280 CLOSE_ON_EXEC (job_rfd);
1281
1282 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1283 child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1284 argv, child->environment, child);
1285 if (child->pid < 0)
1286 {
1287 /* spawn failed! */
1288 unblock_sigs ();
1289 perror_with_name ("spawn", "");
1290 goto error;
1291 }
1292
1293 /* undo CLOSE_ON_EXEC() after the child process has been started */
1294 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1295 {
1296 fcntl (job_fds[0], F_SETFD, 0);
1297 fcntl (job_fds[1], F_SETFD, 0);
1298 }
1299 if (job_rfd >= 0)
1300 fcntl (job_rfd, F_SETFD, 0);
1301
1302#else /* !__EMX__ */
1303
1304 child->pid = vfork ();
1305 environ = parent_environ; /* Restore value child may have clobbered. */
1306 if (child->pid == 0)
1307 {
1308 /* We are the child side. */
1309 unblock_sigs ();
1310
1311 /* If we aren't running a recursive command and we have a jobserver
1312 pipe, close it before exec'ing. */
1313 if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
1314 {
1315 close (job_fds[0]);
1316 close (job_fds[1]);
1317 }
1318 if (job_rfd >= 0)
1319 close (job_rfd);
1320
1321 child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
1322 argv, child->environment);
1323 }
1324 else if (child->pid < 0)
1325 {
1326 /* Fork failed! */
1327 unblock_sigs ();
1328 perror_with_name ("vfork", "");
1329 goto error;
1330 }
1331# endif /* !__EMX__ */
1332#endif /* !VMS */
1333 }
1334
1335#else /* __MSDOS__ or Amiga or WINDOWS32 */
1336#ifdef __MSDOS__
1337 {
1338 int proc_return;
1339
1340 block_sigs ();
1341 dos_status = 0;
1342
1343 /* We call `system' to do the job of the SHELL, since stock DOS
1344 shell is too dumb. Our `system' knows how to handle long
1345 command lines even if pipes/redirection is needed; it will only
1346 call COMMAND.COM when its internal commands are used. */
1347 if (execute_by_shell)
1348 {
1349 char *cmdline = argv[0];
1350 /* We don't have a way to pass environment to `system',
1351 so we need to save and restore ours, sigh... */
1352 char **parent_environ = environ;
1353
1354 environ = child->environment;
1355
1356 /* If we have a *real* shell, tell `system' to call
1357 it to do everything for us. */
1358 if (unixy_shell)
1359 {
1360 /* A *real* shell on MSDOS may not support long
1361 command lines the DJGPP way, so we must use `system'. */
1362 cmdline = argv[2]; /* get past "shell -c" */
1363 }
1364
1365 dos_command_running = 1;
1366 proc_return = system (cmdline);
1367 environ = parent_environ;
1368 execute_by_shell = 0; /* for the next time */
1369 }
1370 else
1371 {
1372 dos_command_running = 1;
1373 proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
1374 }
1375
1376 /* Need to unblock signals before turning off
1377 dos_command_running, so that child's signals
1378 will be treated as such (see fatal_error_signal). */
1379 unblock_sigs ();
1380 dos_command_running = 0;
1381
1382 /* If the child got a signal, dos_status has its
1383 high 8 bits set, so be careful not to alter them. */
1384 if (proc_return == -1)
1385 dos_status |= 0xff;
1386 else
1387 dos_status |= (proc_return & 0xff);
1388 ++dead_children;
1389 child->pid = dos_pid++;
1390 }
1391#endif /* __MSDOS__ */
1392#ifdef _AMIGA
1393 amiga_status = MyExecute (argv);
1394
1395 ++dead_children;
1396 child->pid = amiga_pid++;
1397 if (amiga_batch_file)
1398 {
1399 amiga_batch_file = 0;
1400 DeleteFile (amiga_bname); /* Ignore errors. */
1401 }
1402#endif /* Amiga */
1403#ifdef WINDOWS32
1404 {
1405 HANDLE hPID;
1406 char* arg0;
1407
1408 /* make UNC paths safe for CreateProcess -- backslash format */
1409 arg0 = argv[0];
1410 if (arg0 && arg0[0] == '/' && arg0[1] == '/')
1411 for ( ; arg0 && *arg0; arg0++)
1412 if (*arg0 == '/')
1413 *arg0 = '\\';
1414
1415 /* make sure CreateProcess() has Path it needs */
1416 sync_Path_environment();
1417
1418 hPID = process_easy(argv, child->environment);
1419
1420 if (hPID != INVALID_HANDLE_VALUE)
1421 child->pid = (int) hPID;
1422 else {
1423 int i;
1424 unblock_sigs();
1425 fprintf(stderr,
1426 _("process_easy() failed failed to launch process (e=%d)\n"),
1427 process_last_err(hPID));
1428 for (i = 0; argv[i]; i++)
1429 fprintf(stderr, "%s ", argv[i]);
1430 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
1431 }
1432 }
1433#endif /* WINDOWS32 */
1434#endif /* __MSDOS__ or Amiga or WINDOWS32 */
1435
1436 /* Bump the number of jobs started in this second. */
1437 ++job_counter;
1438
1439 /* We are the parent side. Set the state to
1440 say the commands are running and return. */
1441
1442 set_command_state (child->file, cs_running);
1443
1444 /* Free the storage used by the child's argument list. */
1445#ifndef VMS
1446 free (argv[0]);
1447 free ((char *) argv);
1448#endif
1449
1450 return;
1451
1452 error:
1453 child->file->update_status = 2;
1454 notice_finished_file (child->file);
1455 return;
1456}
1457
1458/* Try to start a child running.
1459 Returns nonzero if the child was started (and maybe finished), or zero if
1460 the load was too high and the child was put on the `waiting_jobs' chain. */
1461
1462static int
1463start_waiting_job (struct child *c)
1464{
1465 struct file *f = c->file;
1466 DB (DB_KMK, (_("start_waiting_job %p (`%s') command_flags=%#x\n"), c, c->file->name, c->file->command_flags));
1467
1468 /* If we can start a job remotely, we always want to, and don't care about
1469 the local load average. We record that the job should be started
1470 remotely in C->remote for start_job_command to test. */
1471
1472 c->remote = start_remote_job_p (1);
1473
1474 /* If we are running at least one job already and the load average
1475 is too high, make this one wait. */
1476 if (!c->remote && job_slots_used > 0 &&
1477 (not_parallel || (c->file->command_flags & COMMANDS_NOTPARALLEL) || load_too_high ()))
1478 {
1479 /* Put this child on the chain of children waiting for the load average
1480 to go down. if not paralell, put it last. */
1481 set_command_state (f, cs_running);
1482 c->next = waiting_jobs;
1483 if (c->next && (c->file->command_flags & COMMANDS_NOTPARALLEL))
1484 {
1485 struct child *prev = waiting_jobs;
1486 while (prev->next)
1487 prev = prev->next;
1488 c->next = 0;
1489 prev->next = c;
1490 }
1491 else
1492 waiting_jobs = c;
1493 DB (DB_KMK, (_("queued child %p (`%s')\n"), c, c->file->name));
1494 return 0;
1495 }
1496
1497 if (c->file->command_flags & COMMANDS_NOTPARALLEL)
1498 {
1499 DB (DB_KMK, (_("not_parallel %d -> %d (file=%p `%s')\n"), not_parallel, not_parallel + 1, c->file, c->file->name));
1500 assert(not_parallel == 0);
1501 ++not_parallel;
1502 }
1503
1504
1505 /* Start the first command; reap_children will run later command lines. */
1506 start_job_command (c);
1507
1508 switch (f->command_state)
1509 {
1510 case cs_running:
1511 c->next = children;
1512 DB (DB_JOBS, (_("Putting child 0x%08lx (%s) PID %ld%s on the chain.\n"),
1513 (unsigned long int) c, c->file->name,
1514 (long) c->pid, c->remote ? _(" (remote)") : ""));
1515 children = c;
1516 /* One more job slot is in use. */
1517 ++job_slots_used;
1518 unblock_sigs ();
1519 break;
1520
1521 case cs_not_started:
1522 /* All the command lines turned out to be empty. */
1523 f->update_status = 0;
1524 /* FALLTHROUGH */
1525
1526 case cs_finished:
1527 notice_finished_file (f);
1528 free_child (c);
1529 break;
1530
1531 default:
1532 assert (f->command_state == cs_finished);
1533 break;
1534 }
1535
1536 return 1;
1537}
1538
1539/* Create a `struct child' for FILE and start its commands running. */
1540
1541void
1542new_job (struct file *file)
1543{
1544 register struct commands *cmds = file->cmds;
1545 register struct child *c;
1546 char **lines;
1547 register unsigned int i;
1548
1549 /* Let any previously decided-upon jobs that are waiting
1550 for the load to go down start before this new one. */
1551 start_waiting_jobs ();
1552
1553 /* Reap any children that might have finished recently. */
1554 reap_children (0, 0);
1555
1556 /* Chop the commands up into lines if they aren't already. */
1557 chop_commands (cmds);
1558
1559 /* Expand the command lines and store the results in LINES. */
1560 lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
1561 for (i = 0; i < cmds->ncommand_lines; ++i)
1562 {
1563 /* Collapse backslash-newline combinations that are inside variable
1564 or function references. These are left alone by the parser so
1565 that they will appear in the echoing of commands (where they look
1566 nice); and collapsed by construct_command_argv when it tokenizes.
1567 But letting them survive inside function invocations loses because
1568 we don't want the functions to see them as part of the text. */
1569
1570 char *in, *out, *ref;
1571
1572 /* IN points to where in the line we are scanning.
1573 OUT points to where in the line we are writing.
1574 When we collapse a backslash-newline combination,
1575 IN gets ahead of OUT. */
1576
1577 in = out = cmds->command_lines[i];
1578 while ((ref = strchr (in, '$')) != 0)
1579 {
1580 ++ref; /* Move past the $. */
1581
1582 if (out != in)
1583 /* Copy the text between the end of the last chunk
1584 we processed (where IN points) and the new chunk
1585 we are about to process (where REF points). */
1586 bcopy (in, out, ref - in);
1587
1588 /* Move both pointers past the boring stuff. */
1589 out += ref - in;
1590 in = ref;
1591
1592 if (*ref == '(' || *ref == '{')
1593 {
1594 char openparen = *ref;
1595 char closeparen = openparen == '(' ? ')' : '}';
1596 int count;
1597 char *p;
1598
1599 *out++ = *in++; /* Copy OPENPAREN. */
1600 /* IN now points past the opening paren or brace.
1601 Count parens or braces until it is matched. */
1602 count = 0;
1603 while (*in != '\0')
1604 {
1605 if (*in == closeparen && --count < 0)
1606 break;
1607 else if (*in == '\\' && in[1] == '\n')
1608 {
1609 /* We have found a backslash-newline inside a
1610 variable or function reference. Eat it and
1611 any following whitespace. */
1612
1613 int quoted = 0;
1614 for (p = in - 1; p > ref && *p == '\\'; --p)
1615 quoted = !quoted;
1616
1617 if (quoted)
1618 /* There were two or more backslashes, so this is
1619 not really a continuation line. We don't collapse
1620 the quoting backslashes here as is done in
1621 collapse_continuations, because the line will
1622 be collapsed again after expansion. */
1623 *out++ = *in++;
1624 else
1625 {
1626 /* Skip the backslash, newline and
1627 any following whitespace. */
1628 in = next_token (in + 2);
1629
1630 /* Discard any preceding whitespace that has
1631 already been written to the output. */
1632 while (out > ref
1633 && isblank ((unsigned char)out[-1]))
1634 --out;
1635
1636 /* Replace it all with a single space. */
1637 *out++ = ' ';
1638 }
1639 }
1640 else
1641 {
1642 if (*in == openparen)
1643 ++count;
1644
1645 *out++ = *in++;
1646 }
1647 }
1648 }
1649 }
1650
1651 /* There are no more references in this line to worry about.
1652 Copy the remaining uninteresting text to the output. */
1653 if (out != in)
1654 strcpy (out, in);
1655
1656 /* Finally, expand the line. */
1657 lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
1658 file);
1659 }
1660
1661 /* Start the command sequence, record it in a new
1662 `struct child', and add that to the chain. */
1663
1664 c = (struct child *) xmalloc (sizeof (struct child));
1665 bzero ((char *)c, sizeof (struct child));
1666 c->file = file;
1667 c->command_lines = lines;
1668 c->sh_batch_file = NULL;
1669
1670 /* Fetch the first command line to be run. */
1671 job_next_command (c);
1672
1673 /* Wait for a job slot to be freed up. If we allow an infinite number
1674 don't bother; also job_slots will == 0 if we're using the jobserver. */
1675
1676 if (job_slots != 0)
1677 while (job_slots_used == job_slots)
1678 reap_children (1, 0);
1679
1680#ifdef MAKE_JOBSERVER
1681 /* If we are controlling multiple jobs make sure we have a token before
1682 starting the child. */
1683
1684 /* This can be inefficient. There's a decent chance that this job won't
1685 actually have to run any subprocesses: the command script may be empty
1686 or otherwise optimized away. It would be nice if we could defer
1687 obtaining a token until just before we need it, in start_job_command.
1688 To do that we'd need to keep track of whether we'd already obtained a
1689 token (since start_job_command is called for each line of the job, not
1690 just once). Also more thought needs to go into the entire algorithm;
1691 this is where the old parallel job code waits, so... */
1692
1693 else if (job_fds[0] >= 0)
1694 while (1)
1695 {
1696 char token;
1697 int got_token;
1698 int saved_errno;
1699
1700 DB (DB_JOBS, ("Need a job token; we %shave children\n",
1701 children ? "" : "don't "));
1702
1703 /* If we don't already have a job started, use our "free" token. */
1704 if (!jobserver_tokens)
1705 break;
1706
1707 /* Read a token. As long as there's no token available we'll block.
1708 We enable interruptible system calls before the read(2) so that if
1709 we get a SIGCHLD while we're waiting, we'll return with EINTR and
1710 we can process the death(s) and return tokens to the free pool.
1711
1712 Once we return from the read, we immediately reinstate restartable
1713 system calls. This allows us to not worry about checking for
1714 EINTR on all the other system calls in the program.
1715
1716 There is one other twist: there is a span between the time
1717 reap_children() does its last check for dead children and the time
1718 the read(2) call is entered, below, where if a child dies we won't
1719 notice. This is extremely serious as it could cause us to
1720 deadlock, given the right set of events.
1721
1722 To avoid this, we do the following: before we reap_children(), we
1723 dup(2) the read FD on the jobserver pipe. The read(2) call below
1724 uses that new FD. In the signal handler, we close that FD. That
1725 way, if a child dies during the section mentioned above, the
1726 read(2) will be invoked with an invalid FD and will return
1727 immediately with EBADF. */
1728
1729 /* Make sure we have a dup'd FD. */
1730 if (job_rfd < 0)
1731 {
1732 DB (DB_JOBS, ("Duplicate the job FD\n"));
1733 job_rfd = dup (job_fds[0]);
1734 }
1735
1736 /* Reap anything that's currently waiting. */
1737 reap_children (0, 0);
1738
1739 /* Kick off any jobs we have waiting for an opportunity that
1740 can run now (ie waiting for load). */
1741 start_waiting_jobs ();
1742
1743 /* If our "free" slot has become available, use it; we don't need an
1744 actual token. */
1745 if (!jobserver_tokens)
1746 break;
1747
1748 /* There must be at least one child already, or we have no business
1749 waiting for a token. */
1750 if (!children)
1751 fatal (NILF, "INTERNAL: no children as we go to sleep on read\n");
1752
1753 /* Set interruptible system calls, and read() for a job token. */
1754 set_child_handler_action_flags (1, waiting_jobs != NULL);
1755 got_token = read (job_rfd, &token, 1);
1756 saved_errno = errno;
1757 set_child_handler_action_flags (0, waiting_jobs != NULL);
1758
1759 /* If we got one, we're done here. */
1760 if (got_token == 1)
1761 {
1762 DB (DB_JOBS, (_("Obtained token for child 0x%08lx (%s).\n"),
1763 (unsigned long int) c, c->file->name));
1764 break;
1765 }
1766
1767 /* If the error _wasn't_ expected (EINTR or EBADF), punt. Otherwise,
1768 go back and reap_children(), and try again. */
1769 errno = saved_errno;
1770 if (errno != EINTR && errno != EBADF)
1771 pfatal_with_name (_("read jobs pipe"));
1772 if (errno == EBADF)
1773 DB (DB_JOBS, ("Read returned EBADF.\n"));
1774 }
1775#endif
1776
1777 ++jobserver_tokens;
1778
1779 /* The job is now primed. Start it running.
1780 (This will notice if there are in fact no commands.) */
1781 (void) start_waiting_job (c);
1782
1783 if (job_slots == 1 || not_parallel < 0)
1784 /* Since there is only one job slot, make things run linearly.
1785 Wait for the child to die, setting the state to `cs_finished'. */
1786 while (file->command_state == cs_running)
1787 reap_children (1, 0);
1788
1789 return;
1790}
1791
1792
1793/* Move CHILD's pointers to the next command for it to execute.
1794 Returns nonzero if there is another command. */
1795
1796static int
1797job_next_command (struct child *child)
1798{
1799 while (child->command_ptr == 0 || *child->command_ptr == '\0')
1800 {
1801 /* There are no more lines in the expansion of this line. */
1802 if (child->command_line == child->file->cmds->ncommand_lines)
1803 {
1804 /* There are no more lines to be expanded. */
1805 child->command_ptr = 0;
1806 return 0;
1807 }
1808 else
1809 /* Get the next line to run. */
1810 child->command_ptr = child->command_lines[child->command_line++];
1811 }
1812 return 1;
1813}
1814
1815/* Determine if the load average on the system is too high to start a new job.
1816 The real system load average is only recomputed once a second. However, a
1817 very parallel make can easily start tens or even hundreds of jobs in a
1818 second, which brings the system to its knees for a while until that first
1819 batch of jobs clears out.
1820
1821 To avoid this we use a weighted algorithm to try to account for jobs which
1822 have been started since the last second, and guess what the load average
1823 would be now if it were computed.
1824
1825 This algorithm was provided by Thomas Riedl <thomas.riedl@siemens.com>,
1826 who writes:
1827
1828! calculate something load-oid and add to the observed sys.load,
1829! so that latter can catch up:
1830! - every job started increases jobctr;
1831! - every dying job decreases a positive jobctr;
1832! - the jobctr value gets zeroed every change of seconds,
1833! after its value*weight_b is stored into the 'backlog' value last_sec
1834! - weight_a times the sum of jobctr and last_sec gets
1835! added to the observed sys.load.
1836!
1837! The two weights have been tried out on 24 and 48 proc. Sun Solaris-9
1838! machines, using a several-thousand-jobs-mix of cpp, cc, cxx and smallish
1839! sub-shelled commands (rm, echo, sed...) for tests.
1840! lowering the 'direct influence' factor weight_a (e.g. to 0.1)
1841! resulted in significant excession of the load limit, raising it
1842! (e.g. to 0.5) took bad to small, fast-executing jobs and didn't
1843! reach the limit in most test cases.
1844!
1845! lowering the 'history influence' weight_b (e.g. to 0.1) resulted in
1846! exceeding the limit for longer-running stuff (compile jobs in
1847! the .5 to 1.5 sec. range),raising it (e.g. to 0.5) overrepresented
1848! small jobs' effects.
1849
1850 */
1851
1852#define LOAD_WEIGHT_A 0.25
1853#define LOAD_WEIGHT_B 0.25
1854
1855static int
1856load_too_high (void)
1857{
1858#if defined(__MSDOS__) || defined(VMS) || defined(_AMIGA) || defined(__riscos__)
1859 return 1;
1860#else
1861 static double last_sec;
1862 static time_t last_now;
1863 double load, guess;
1864 time_t now;
1865
1866 if (max_load_average < 0)
1867 return 0;
1868
1869 /* Find the real system load average. */
1870 make_access ();
1871 if (getloadavg (&load, 1) != 1)
1872 {
1873 static int lossage = -1;
1874 /* Complain only once for the same error. */
1875 if (lossage == -1 || errno != lossage)
1876 {
1877 if (errno == 0)
1878 /* An errno value of zero means getloadavg is just unsupported. */
1879 error (NILF,
1880 _("cannot enforce load limits on this operating system"));
1881 else
1882 perror_with_name (_("cannot enforce load limit: "), "getloadavg");
1883 }
1884 lossage = errno;
1885 load = 0;
1886 }
1887 user_access ();
1888
1889 /* If we're in a new second zero the counter and correct the backlog
1890 value. Only keep the backlog for one extra second; after that it's 0. */
1891 now = time (NULL);
1892 if (last_now < now)
1893 {
1894 if (last_now == now - 1)
1895 last_sec = LOAD_WEIGHT_B * job_counter;
1896 else
1897 last_sec = 0.0;
1898
1899 job_counter = 0;
1900 last_now = now;
1901 }
1902
1903 /* Try to guess what the load would be right now. */
1904 guess = load + (LOAD_WEIGHT_A * (job_counter + last_sec));
1905
1906 DB (DB_JOBS, ("Estimated system load = %f (actual = %f) (max requested = %f)\n",
1907 guess, load, max_load_average));
1908
1909 return guess >= max_load_average;
1910#endif
1911}
1912
1913/* Start jobs that are waiting for the load to be lower. */
1914
1915void
1916start_waiting_jobs (void)
1917{
1918 struct child *job;
1919
1920 if (waiting_jobs == 0)
1921 return;
1922
1923 do
1924 {
1925 /* Check for recently deceased descendants. */
1926 reap_children (0, 0);
1927
1928 /* Take a job off the waiting list. */
1929 job = waiting_jobs;
1930 waiting_jobs = job->next;
1931
1932 /* Try to start that job. We break out of the loop as soon
1933 as start_waiting_job puts one back on the waiting list. */
1934 }
1935 while (start_waiting_job (job) && waiting_jobs != 0);
1936
1937 return;
1938}
1939
1940
1941#ifndef WINDOWS32
1942
1943/* EMX: Start a child process. This function returns the new pid. */
1944/* The child argument can be NULL (that's why we return the pid), if it is
1945 and the shell is a dllshell:// a child structure is created and inserted
1946 into the child list so reap_children can do its job.
1947
1948 BTW. the name of this function in this port is very misleading, spawn_job
1949 would perhaps be more appropriate. */
1950# if defined __MSDOS__ || defined __EMX__
1951int
1952child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp,
1953 struct child *child)
1954{
1955 int pid;
1956 /* stdin_fd == 0 means: nothing to do for stdin;
1957 stdout_fd == 1 means: nothing to do for stdout */
1958 int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
1959 int save_stdout = (stdout_fd != 1) ? dup (1): 1;
1960
1961 /* < 0 only if dup() failed */
1962 if (save_stdin < 0)
1963 fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
1964 if (save_stdout < 0)
1965 fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
1966
1967 /* Close unnecessary file handles for the child. */
1968 if (save_stdin != 0)
1969 CLOSE_ON_EXEC (save_stdin);
1970 if (save_stdout != 1)
1971 CLOSE_ON_EXEC (save_stdout);
1972
1973 /* Connect the pipes to the child process. */
1974 if (stdin_fd != 0)
1975 (void) dup2 (stdin_fd, 0);
1976 if (stdout_fd != 1)
1977 (void) dup2 (stdout_fd, 1);
1978
1979 /* stdin_fd and stdout_fd must be closed on exit because we are
1980 still in the parent process */
1981 if (stdin_fd != 0)
1982 CLOSE_ON_EXEC (stdin_fd);
1983 if (stdout_fd != 1)
1984 CLOSE_ON_EXEC (stdout_fd);
1985
1986#ifdef MAKE_DLLSHELL
1987 pid = spawn_command(argv, envp, child);
1988#else
1989 /* Run the command. */
1990 pid = exec_command (argv, envp);
1991#endif
1992
1993 /* Restore stdout/stdin of the parent and close temporary FDs. */
1994 if (stdin_fd != 0)
1995 {
1996 if (dup2 (save_stdin, 0) != 0)
1997 fatal (NILF, _("Could not restore stdin\n"));
1998 else
1999 close (save_stdin);
2000 }
2001
2002 if (stdout_fd != 1)
2003 {
2004 if (dup2 (save_stdout, 1) != 1)
2005 fatal (NILF, _("Could not restore stdout\n"));
2006 else
2007 close (save_stdout);
2008 }
2009
2010 return pid;
2011}
2012
2013#elif !defined (_AMIGA) && !defined (__MSDOS__)
2014
2015/* UNIX:
2016 Replace the current process with one executing the command in ARGV.
2017 STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
2018 the environment of the new program. This function does not return. */
2019void
2020child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
2021{
2022 if (stdin_fd != 0)
2023 (void) dup2 (stdin_fd, 0);
2024 if (stdout_fd != 1)
2025 (void) dup2 (stdout_fd, 1);
2026 if (stdin_fd != 0)
2027 (void) close (stdin_fd);
2028 if (stdout_fd != 1)
2029 (void) close (stdout_fd);
2030
2031 /* Run the command. */
2032 exec_command (argv, envp);
2033}
2034#endif /* !AMIGA && !__MSDOS__ */
2035#endif /* !WINDOWS32 */
2036
2037
2038#ifdef MAKE_DLLSHELL
2039/* Globals for the currently loaded dllshell. */
2040char *dllshell_spec;
2041void *dllshell_dl;
2042void *dllshell_instance;
2043void *(*dllshell_init) PARAMS ((const char *spec));
2044pid_t (*dllshell_spawn) PARAMS ((void *instance, char **argv, char **envp, int *status, char *done));
2045pid_t (*dllshell_wait) PARAMS ((void *instance, int *status, int block));
2046
2047/* This is called when all pipes and such are configured for the
2048 child process. The child argument may be null, see child_execute_job. */
2049static int spawn_command (char **argv, char **envp, struct child *c)
2050{
2051 /* Now let's see if there is a DLLSHELL specifier in the
2052 first argument. */
2053 if (!strncmp(argv[0], "dllshell://", 11))
2054 {
2055 /* dllshell://<dllname>[!<realshell>[!whatever]] */
2056 char *name, *name_end;
2057 int insert_child = 0;
2058
2059 /* parse it */
2060 name = argv[0] + 11;
2061 name_end = strchr (name, '!');
2062 if (!name_end)
2063 name_end = strchr (name, '\0');
2064 if (name_end == name)
2065 fatal (NILF, _("%s : malformed specifier!\n"), argv[0]);
2066
2067 /* need loading? */
2068 if (!dllshell_spec || strcmp (argv[0], dllshell_spec))
2069 {
2070 if (dllshell_spec)
2071 fatal (NILF, _("cannot change the dllshell!!!\n"));
2072
2073 dllshell_spec = strdup (argv[0]);
2074 dllshell_spec[name_end - argv[0]] = '\0';
2075 dllshell_dl = dlopen (dllshell_spec + (name - argv[0]), RTLD_LOCAL);
2076 if (!dllshell_dl)
2077 fatal (NILF, _("%s : failed to load! dlerror: '%s'\n"), argv[0], dlerror());
2078 dllshell_spec[name_end - name] = '!';
2079
2080 /* get symbols */
2081 dllshell_init = dlsym (dllshell_dl, "dllshell_init");
2082 if (!dllshell_init)
2083 fatal (NILF, _("%s : failed to find symbols 'dllshell_init' dlerror: %s\n"), argv[0], dlerror());
2084 dllshell_spawn = dlsym (dllshell_dl, "dllshell_spawn");
2085 if (!dllshell_spawn)
2086 fatal (NILF, _("%s : failed to find symbols 'dllshell_spawn' dlerror: %s\n"), argv[0], dlerror());
2087 dllshell_wait = dlsym (dllshell_dl, "dllshell_wait");
2088 if (!dllshell_wait)
2089 fatal (NILF, _("%s : failed to find symbols 'dllshell_wait' dlerror: %s\n"), argv[0], dlerror());
2090
2091 /* init */
2092 dllshell_instance = dllshell_init(dllshell_spec);
2093 if (!dllshell_instance)
2094 fatal (NILF, _("%s : init failed!!!\n"), argv[0]);
2095 }
2096
2097 /* make child struct? */
2098 if (!c)
2099 {
2100 c = (struct child *) xmalloc (sizeof (struct child));
2101 bzero ((char *)c, sizeof (struct child));
2102 insert_child = 1;
2103 }
2104
2105 /* call it. return value is 0 on succes, -1 on failure. */
2106 c->pid = dllshell_spawn (dllshell_instance, argv, envp, &c->status, &c->dllshell_done);
2107 DB (DB_JOBS, (_("dllshell pid=%x\n"), c->pid));
2108
2109 if (insert_child && c->pid > 0)
2110 {
2111 c->next = children;
2112 DB (DB_JOBS, (_("Putting child 0x%08lx (-) PID %ld on the chain.\n"),
2113 (unsigned long int) c, (long) c->pid));
2114 children = c;
2115 /* One more job slot is in use. */
2116 ++job_slots_used;
2117 }
2118 }
2119 else
2120 {
2121 /* Run the command. */
2122#ifdef __EMX__
2123 c->pid =
2124 exec_command (argv, envp);
2125#else
2126# error MAKE_DLLSHELL is not ported to your platform yet.
2127#endif
2128 DB (DB_JOBS, (_("spawn pid=%x\n"), c->pid));
2129 }
2130
2131 return c->pid;
2132}
2133
2134/* Waits or pools for a job to finish.
2135 If the block argument the the function will not return
2136 till a job is completed (if there are any jobs).
2137 Returns pid of completed job.
2138 Returns 0 if no jobs are finished.
2139 Returns -1 if no jobs are running. */
2140pid_t wait_jobs (int *status, int block)
2141{
2142 pid_t pid;
2143 if (dllshell_wait)
2144 pid = dllshell_wait(dllshell_instance, status, block);
2145 else
2146 {
2147 if (block)
2148 pid = WAIT_NOHANG(status);
2149 else
2150 pid = wait(status);
2151 }
2152 return pid;
2153}
2154
2155#endif /* MAKE_DLLSHELL */
2156
2157
2158#ifndef _AMIGA
2159/* Replace the current process with one running the command in ARGV,
2160 with environment ENVP. This function does not return. */
2161
2162/* EMX: This function returns the pid of the child process. */
2163# ifdef __EMX__
2164int
2165# else
2166void
2167# endif
2168exec_command (char **argv, char **envp)
2169{
2170#ifdef VMS
2171 /* to work around a problem with signals and execve: ignore them */
2172#ifdef SIGCHLD
2173 signal (SIGCHLD,SIG_IGN);
2174#endif
2175 /* Run the program. */
2176 execve (argv[0], argv, envp);
2177 perror_with_name ("execve: ", argv[0]);
2178 _exit (EXIT_FAILURE);
2179#else
2180#ifdef WINDOWS32
2181 HANDLE hPID;
2182 HANDLE hWaitPID;
2183 int err = 0;
2184 int exit_code = EXIT_FAILURE;
2185
2186 /* make sure CreateProcess() has Path it needs */
2187 sync_Path_environment();
2188
2189 /* launch command */
2190 hPID = process_easy(argv, envp);
2191
2192 /* make sure launch ok */
2193 if (hPID == INVALID_HANDLE_VALUE)
2194 {
2195 int i;
2196 fprintf(stderr,
2197 _("process_easy() failed failed to launch process (e=%d)\n"),
2198 process_last_err(hPID));
2199 for (i = 0; argv[i]; i++)
2200 fprintf(stderr, "%s ", argv[i]);
2201 fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
2202 exit(EXIT_FAILURE);
2203 }
2204
2205 /* wait and reap last child */
2206 hWaitPID = process_wait_for_any();
2207 while (hWaitPID)
2208 {
2209 /* was an error found on this process? */
2210 err = process_last_err(hWaitPID);
2211
2212 /* get exit data */
2213 exit_code = process_exit_code(hWaitPID);
2214
2215 if (err)
2216 fprintf(stderr, "make (e=%d, rc=%d): %s",
2217 err, exit_code, map_windows32_error_to_string(err));
2218
2219 /* cleanup process */
2220 process_cleanup(hWaitPID);
2221
2222 /* expect to find only last pid, warn about other pids reaped */
2223 if (hWaitPID == hPID)
2224 break;
2225 else
2226 fprintf(stderr,
2227 _("make reaped child pid %d, still waiting for pid %d\n"),
2228 hWaitPID, hPID);
2229 }
2230
2231 /* return child's exit code as our exit code */
2232 exit(exit_code);
2233
2234#else /* !WINDOWS32 */
2235
2236# ifdef __EMX__
2237 int pid;
2238# endif
2239
2240 /* Be the user, permanently. */
2241 child_access ();
2242
2243# ifdef __EMX__
2244
2245 /* Run the program. */
2246 pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
2247
2248 if (pid >= 0)
2249 return pid;
2250
2251 /* the file might have a strange shell extension */
2252 if (errno == ENOENT)
2253 errno = ENOEXEC;
2254
2255# else
2256
2257 /* Run the program. */
2258 environ = envp;
2259 execvp (argv[0], argv);
2260
2261# endif /* !__EMX__ */
2262
2263 switch (errno)
2264 {
2265 case ENOENT:
2266 error (NILF, _("%s: Command not found"), argv[0]);
2267 break;
2268 case ENOEXEC:
2269 {
2270 /* The file is not executable. Try it as a shell script. */
2271 extern char *getenv ();
2272 char *shell;
2273 char **new_argv;
2274 int argc;
2275 int i=1;
2276
2277# ifdef __EMX__
2278 /* Do not use $SHELL from the environment */
2279 struct variable *p = lookup_variable ("SHELL", 5);
2280 if (p)
2281 shell = p->value;
2282 else
2283 shell = 0;
2284# else
2285 shell = getenv ("SHELL");
2286# endif
2287 if (shell == 0)
2288 shell = default_shell;
2289
2290 argc = 1;
2291 while (argv[argc] != 0)
2292 ++argc;
2293
2294# ifdef __EMX__
2295 if (!unixy_shell)
2296 ++argc;
2297# endif
2298
2299 new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
2300 new_argv[0] = shell;
2301
2302# ifdef __EMX__
2303 if (!unixy_shell)
2304 {
2305 new_argv[1] = "/c";
2306 ++i;
2307 --argc;
2308 }
2309# endif
2310
2311 new_argv[i] = argv[0];
2312 while (argc > 0)
2313 {
2314 new_argv[i + argc] = argv[argc];
2315 --argc;
2316 }
2317
2318# ifdef __EMX__
2319 pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
2320 if (pid >= 0)
2321 break;
2322# else
2323 execvp (shell, new_argv);
2324# endif
2325 if (errno == ENOENT)
2326 error (NILF, _("%s: Shell program not found"), shell);
2327 else
2328 perror_with_name ("execvp: ", shell);
2329 break;
2330 }
2331
2332# ifdef __EMX__
2333 case EINVAL:
2334 /* this nasty error was driving me nuts :-( */
2335 error (NILF, _("spawnvpe: environment space might be exhausted"));
2336 /* FALLTHROUGH */
2337# endif
2338
2339 default:
2340 perror_with_name ("execvp: ", argv[0]);
2341 break;
2342 }
2343
2344# ifdef __EMX__
2345 return pid;
2346# else
2347 _exit (127);
2348# endif
2349#endif /* !WINDOWS32 */
2350#endif /* !VMS */
2351}
2352#else /* On Amiga */
2353void exec_command (char **argv)
2354{
2355 MyExecute (argv);
2356}
2357
2358void clean_tmp (void)
2359{
2360 DeleteFile (amiga_bname);
2361}
2362
2363#endif /* On Amiga */
2364
2365
2366#ifndef VMS
2367/* Figure out the argument list necessary to run LINE as a command. Try to
2368 avoid using a shell. This routine handles only ' quoting, and " quoting
2369 when no backslash, $ or ` characters are seen in the quotes. Starting
2370 quotes may be escaped with a backslash. If any of the characters in
2371 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
2372 is the first word of a line, the shell is used.
2373
2374 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
2375 If *RESTP is NULL, newlines will be ignored.
2376
2377 SHELL is the shell to use, or nil to use the default shell.
2378 IFS is the value of $IFS, or nil (meaning the default). */
2379
2380static char **
2381construct_command_argv_internal (char *line, char **restp, char *shell,
2382 char *ifs, char **batch_filename_ptr)
2383{
2384#ifdef __MSDOS__
2385 /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
2386 We call `system' for anything that requires ``slow'' processing,
2387 because DOS shells are too dumb. When $SHELL points to a real
2388 (unix-style) shell, `system' just calls it to do everything. When
2389 $SHELL points to a DOS shell, `system' does most of the work
2390 internally, calling the shell only for its internal commands.
2391 However, it looks on the $PATH first, so you can e.g. have an
2392 external command named `mkdir'.
2393
2394 Since we call `system', certain characters and commands below are
2395 actually not specific to COMMAND.COM, but to the DJGPP implementation
2396 of `system'. In particular:
2397
2398 The shell wildcard characters are in DOS_CHARS because they will
2399 not be expanded if we call the child via `spawnXX'.
2400
2401 The `;' is in DOS_CHARS, because our `system' knows how to run
2402 multiple commands on a single line.
2403
2404 DOS_CHARS also include characters special to 4DOS/NDOS, so we
2405 won't have to tell one from another and have one more set of
2406 commands and special characters. */
2407 static char sh_chars_dos[] = "*?[];|<>%^&()";
2408 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2409 "copy", "ctty", "date", "del", "dir", "echo",
2410 "erase", "exit", "for", "goto", "if", "md",
2411 "mkdir", "path", "pause", "prompt", "rd",
2412 "rmdir", "rem", "ren", "rename", "set",
2413 "shift", "time", "type", "ver", "verify",
2414 "vol", ":", 0 };
2415
2416 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2417 static char *sh_cmds_sh[] = { "cd", "echo", "eval", "exec", "exit", "login",
2418 "logout", "set", "umask", "wait", "while",
2419 "for", "case", "if", ":", ".", "break",
2420 "continue", "export", "read", "readonly",
2421 "shift", "times", "trap", "switch", "unset",
2422 0 };
2423
2424 char *sh_chars;
2425 char **sh_cmds;
2426#elif defined (__EMX__)
2427 static char sh_chars_dos[] = "*?[];|<>%^&()";
2428 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2429 "copy", "ctty", "date", "del", "dir", "echo",
2430 "erase", "exit", "for", "goto", "if", "md",
2431 "mkdir", "path", "pause", "prompt", "rd",
2432 "rmdir", "rem", "ren", "rename", "set",
2433 "shift", "time", "type", "ver", "verify",
2434 "vol", ":", 0 };
2435
2436 static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
2437 static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
2438 "date", "del", "detach", "dir", "echo",
2439 "endlocal", "erase", "exit", "for", "goto", "if",
2440 "keys", "md", "mkdir", "move", "path", "pause",
2441 "prompt", "rd", "rem", "ren", "rename", "rmdir",
2442 "set", "setlocal", "shift", "start", "time",
2443 "type", "ver", "verify", "vol", ":", 0 };
2444
2445 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~'";
2446 static char *sh_cmds_sh[] = { "echo", "cd", "eval", "exec", "exit", "login",
2447 "logout", "set", "umask", "wait", "while",
2448 "for", "case", "if", ":", ".", "break",
2449 "continue", "export", "read", "readonly",
2450 "shift", "times", "trap", "switch", "unset",
2451 0 };
2452 char *sh_chars;
2453 char **sh_cmds;
2454
2455#elif defined (_AMIGA)
2456 static char sh_chars[] = "#;\"|<>()?*$`";
2457 static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
2458 "rename", "set", "setenv", "date", "makedir",
2459 "skip", "else", "endif", "path", "prompt",
2460 "unset", "unsetenv", "version",
2461 0 };
2462#elif defined (WINDOWS32)
2463 static char sh_chars_dos[] = "\"|&<>";
2464 static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
2465 "copy", "ctty", "date", "del", "dir", "echo",
2466 "erase", "exit", "for", "goto", "if", "if", "md",
2467 "mkdir", "path", "pause", "prompt", "rd", "rem",
2468 "ren", "rename", "rmdir", "set", "shift", "time",
2469 "type", "ver", "verify", "vol", ":", 0 };
2470 static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
2471 static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
2472 "logout", "set", "umask", "wait", "while", "for",
2473 "case", "if", ":", ".", "break", "continue",
2474 "export", "read", "readonly", "shift", "times",
2475 "trap", "switch", "test",
2476#ifdef BATCH_MODE_ONLY_SHELL
2477 "echo",
2478#endif
2479 0 };
2480 char* sh_chars;
2481 char** sh_cmds;
2482#elif defined(__riscos__)
2483 static char sh_chars[] = "";
2484 static char *sh_cmds[] = { 0 };
2485#else /* must be UNIX-ish */
2486 static char sh_chars[] = "#;\"*?[]&|<>(){}$`^~!";
2487 static char *sh_cmds[] = { ".", ":", "break", "case", "cd", "continue",
2488 "eval", "exec", "exit", "export", "for", "if",
2489 "login", "logout", "read", "readonly", "set",
2490 "shift", "switch", "test", "times", "trap",
2491 "umask", "wait", "while", 0 };
2492#endif
2493 register int i;
2494 register char *p;
2495 register char *ap;
2496 char *end;
2497 int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
2498 char **new_argv = 0;
2499#ifdef WINDOWS32
2500 int slow_flag = 0;
2501
2502 if (no_default_sh_exe) {
2503 sh_cmds = sh_cmds_dos;
2504 sh_chars = sh_chars_dos;
2505 } else {
2506 sh_cmds = sh_cmds_sh;
2507 sh_chars = sh_chars_sh;
2508 }
2509#endif /* WINDOWS32 */
2510
2511 if (restp != NULL)
2512 *restp = NULL;
2513
2514 /* Make sure not to bother processing an empty line. */
2515 while (isblank ((unsigned char)*line))
2516 ++line;
2517 if (*line == '\0')
2518 return 0;
2519
2520 /* See if it is safe to parse commands internally. */
2521 if (shell == 0)
2522 shell = default_shell;
2523#ifdef WINDOWS32
2524 else if (strcmp (shell, default_shell))
2525 {
2526 char *s1 = _fullpath(NULL, shell, 0);
2527 char *s2 = _fullpath(NULL, default_shell, 0);
2528
2529 slow_flag = strcmp((s1 ? s1 : ""), (s2 ? s2 : ""));
2530
2531 if (s1)
2532 free (s1);
2533 if (s2)
2534 free (s2);
2535 }
2536 if (slow_flag)
2537 goto slow;
2538#else /* not WINDOWS32 */
2539#if defined (__MSDOS__) || defined (__EMX__)
2540 else if (stricmp (shell, default_shell))
2541 {
2542 extern int _is_unixy_shell (const char *_path);
2543
2544 DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
2545 default_shell, shell));
2546 unixy_shell = _is_unixy_shell (shell);
2547 /* we must allocate a copy of shell: construct_command_argv() will free
2548 * shell after this function returns. */
2549 default_shell = xstrdup (shell);
2550 }
2551 if (unixy_shell)
2552 {
2553 sh_chars = sh_chars_sh;
2554 sh_cmds = sh_cmds_sh;
2555 }
2556 else
2557 {
2558 sh_chars = sh_chars_dos;
2559 sh_cmds = sh_cmds_dos;
2560# ifdef __EMX__
2561 if (_osmode == OS2_MODE)
2562 {
2563 sh_chars = sh_chars_os2;
2564 sh_cmds = sh_cmds_os2;
2565 }
2566# endif
2567 }
2568#else /* !__MSDOS__ */
2569 else if (strcmp (shell, default_shell))
2570 {
2571 /* Allow ash from kBuild. */
2572 const char *psz = strstr(shell, "/kmk_ash");
2573 if ( !psz
2574 || (!psz[sizeof("/kmk_ash")] && psz[sizeof("/kmk_ash")] == '.'))
2575 goto slow;
2576 }
2577#endif /* !__MSDOS__ && !__EMX__ */
2578#endif /* not WINDOWS32 */
2579
2580 if (ifs != 0)
2581 for (ap = ifs; *ap != '\0'; ++ap)
2582 if (*ap != ' ' && *ap != '\t' && *ap != '\n')
2583 goto slow;
2584
2585 i = strlen (line) + 1;
2586
2587 /* More than 1 arg per character is impossible. */
2588 new_argv = (char **) xmalloc (i * sizeof (char *));
2589
2590 /* All the args can fit in a buffer as big as LINE is. */
2591 ap = new_argv[0] = (char *) xmalloc (i);
2592 end = ap + i;
2593
2594 /* I is how many complete arguments have been found. */
2595 i = 0;
2596 instring = word_has_equals = seen_nonequals = last_argument_was_empty = 0;
2597 for (p = line; *p != '\0'; ++p)
2598 {
2599 if (ap > end)
2600 abort ();
2601
2602 if (instring)
2603 {
2604 string_char:
2605 /* Inside a string, just copy any char except a closing quote
2606 or a backslash-newline combination. */
2607 if (*p == instring)
2608 {
2609 instring = 0;
2610 if (ap == new_argv[0] || *(ap-1) == '\0')
2611 last_argument_was_empty = 1;
2612 }
2613 else if (*p == '\\' && p[1] == '\n')
2614 goto swallow_escaped_newline;
2615 else if (*p == '\n' && restp != NULL)
2616 {
2617 /* End of the command line. */
2618 *restp = p;
2619 goto end_of_line;
2620 }
2621 /* Backslash, $, and ` are special inside double quotes.
2622 If we see any of those, punt.
2623 But on MSDOS, if we use COMMAND.COM, double and single
2624 quotes have the same effect. */
2625 else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
2626 goto slow;
2627 else
2628 *ap++ = *p;
2629 }
2630 else if (strchr (sh_chars, *p) != 0)
2631 /* Not inside a string, but it's a special char. */
2632 goto slow;
2633#ifdef __MSDOS__
2634 else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
2635 /* `...' is a wildcard in DJGPP. */
2636 goto slow;
2637#endif
2638 else
2639 /* Not a special char. */
2640 switch (*p)
2641 {
2642 case '=':
2643 /* Equals is a special character in leading words before the
2644 first word with no equals sign in it. This is not the case
2645 with sh -k, but we never get here when using nonstandard
2646 shell flags. */
2647 if (! seen_nonequals && unixy_shell)
2648 goto slow;
2649 word_has_equals = 1;
2650 *ap++ = '=';
2651 break;
2652
2653 case '\\':
2654 /* Backslash-newline combinations are eaten. */
2655 if (p[1] == '\n')
2656 {
2657 swallow_escaped_newline:
2658
2659 /* Eat the backslash, the newline, and following whitespace,
2660 replacing it all with a single space. */
2661 p += 2;
2662
2663 /* If there is a tab after a backslash-newline,
2664 remove it from the source line which will be echoed,
2665 since it was most likely used to line
2666 up the continued line with the previous one. */
2667 if (*p == '\t')
2668 /* Note these overlap and strcpy() is undefined for
2669 overlapping objects in ANSI C. The strlen() _IS_ right,
2670 since we need to copy the nul byte too. */
2671 bcopy (p + 1, p, strlen (p));
2672
2673 if (instring)
2674 goto string_char;
2675 else
2676 {
2677 if (ap != new_argv[i])
2678 /* Treat this as a space, ending the arg.
2679 But if it's at the beginning of the arg, it should
2680 just get eaten, rather than becoming an empty arg. */
2681 goto end_of_arg;
2682 else
2683 p = next_token (p) - 1;
2684 }
2685 }
2686 else if (p[1] != '\0')
2687 {
2688#ifdef HAVE_DOS_PATHS
2689 /* Only remove backslashes before characters special
2690 to Unixy shells. All other backslashes are copied
2691 verbatim, since they are probably DOS-style
2692 directory separators. This still leaves a small
2693 window for problems, but at least it should work
2694 for the vast majority of naive users. */
2695
2696#ifdef __MSDOS__
2697 /* A dot is only special as part of the "..."
2698 wildcard. */
2699 if (strneq (p + 1, ".\\.\\.", 5))
2700 {
2701 *ap++ = '.';
2702 *ap++ = '.';
2703 p += 4;
2704 }
2705 else
2706#endif
2707 if (p[1] != '\\' && p[1] != '\''
2708 && !isspace ((unsigned char)p[1])
2709 && (strchr (sh_chars_sh, p[1]) == 0))
2710 /* back up one notch, to copy the backslash */
2711 --p;
2712#endif /* HAVE_DOS_PATHS */
2713
2714 /* Copy and skip the following char. */
2715 *ap++ = *++p;
2716 }
2717 break;
2718
2719 case '\'':
2720 case '"':
2721 instring = *p;
2722 break;
2723
2724 case '\n':
2725 if (restp != NULL)
2726 {
2727 /* End of the command line. */
2728 *restp = p;
2729 goto end_of_line;
2730 }
2731 else
2732 /* Newlines are not special. */
2733 *ap++ = '\n';
2734 break;
2735
2736 case ' ':
2737 case '\t':
2738 end_of_arg:
2739 /* We have the end of an argument.
2740 Terminate the text of the argument. */
2741 *ap++ = '\0';
2742 new_argv[++i] = ap;
2743 last_argument_was_empty = 0;
2744
2745 /* Update SEEN_NONEQUALS, which tells us if every word
2746 heretofore has contained an `='. */
2747 seen_nonequals |= ! word_has_equals;
2748 if (word_has_equals && ! seen_nonequals)
2749 /* An `=' in a word before the first
2750 word without one is magical. */
2751 goto slow;
2752 word_has_equals = 0; /* Prepare for the next word. */
2753
2754 /* If this argument is the command name,
2755 see if it is a built-in shell command.
2756 If so, have the shell handle it. */
2757 if (i == 1)
2758 {
2759 register int j;
2760 for (j = 0; sh_cmds[j] != 0; ++j)
2761 {
2762 if (streq (sh_cmds[j], new_argv[0]))
2763 goto slow;
2764# ifdef __EMX__
2765 /* Non-Unix shells are case insensitive. */
2766 if (!unixy_shell
2767 && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
2768 goto slow;
2769# endif
2770 }
2771 }
2772
2773 /* Ignore multiple whitespace chars. */
2774 p = next_token (p);
2775 /* Next iteration should examine the first nonwhite char. */
2776 --p;
2777 break;
2778
2779 default:
2780 *ap++ = *p;
2781 break;
2782 }
2783 }
2784 end_of_line:
2785
2786 if (instring)
2787 /* Let the shell deal with an unterminated quote. */
2788 goto slow;
2789
2790 /* Terminate the last argument and the argument list. */
2791
2792 *ap = '\0';
2793 if (new_argv[i][0] != '\0' || last_argument_was_empty)
2794 ++i;
2795 new_argv[i] = 0;
2796
2797 if (i == 1)
2798 {
2799 register int j;
2800 for (j = 0; sh_cmds[j] != 0; ++j)
2801 if (streq (sh_cmds[j], new_argv[0]))
2802 goto slow;
2803 }
2804
2805 if (new_argv[0] == 0)
2806 /* Line was empty. */
2807 return 0;
2808
2809 return new_argv;
2810
2811 slow:;
2812 /* We must use the shell. */
2813
2814 if (new_argv != 0)
2815 {
2816 /* Free the old argument list we were working on. */
2817 free (new_argv[0]);
2818 free ((void *)new_argv);
2819 }
2820
2821#ifdef __MSDOS__
2822 execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
2823#endif
2824
2825#ifdef _AMIGA
2826 {
2827 char *ptr;
2828 char *buffer;
2829 char *dptr;
2830
2831 buffer = (char *)xmalloc (strlen (line)+1);
2832
2833 ptr = line;
2834 for (dptr=buffer; *ptr; )
2835 {
2836 if (*ptr == '\\' && ptr[1] == '\n')
2837 ptr += 2;
2838 else if (*ptr == '@') /* Kludge: multiline commands */
2839 {
2840 ptr += 2;
2841 *dptr++ = '\n';
2842 }
2843 else
2844 *dptr++ = *ptr++;
2845 }
2846 *dptr = 0;
2847
2848 new_argv = (char **) xmalloc (2 * sizeof (char *));
2849 new_argv[0] = buffer;
2850 new_argv[1] = 0;
2851 }
2852#else /* Not Amiga */
2853#ifdef WINDOWS32
2854 /*
2855 * Not eating this whitespace caused things like
2856 *
2857 * sh -c "\n"
2858 *
2859 * which gave the shell fits. I think we have to eat
2860 * whitespace here, but this code should be considered
2861 * suspicious if things start failing....
2862 */
2863
2864 /* Make sure not to bother processing an empty line. */
2865 while (isspace ((unsigned char)*line))
2866 ++line;
2867 if (*line == '\0')
2868 return 0;
2869#endif /* WINDOWS32 */
2870 {
2871 /* SHELL may be a multi-word command. Construct a command line
2872 "SHELL -c LINE", with all special chars in LINE escaped.
2873 Then recurse, expanding this command line to get the final
2874 argument list. */
2875
2876 unsigned int shell_len = strlen (shell);
2877#ifndef VMS
2878 static char minus_c[] = " -c ";
2879#else
2880 static char minus_c[] = "";
2881#endif
2882 unsigned int line_len = strlen (line);
2883
2884 char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
2885 + (line_len * 2) + 1);
2886 char *command_ptr = NULL; /* used for batch_mode_shell mode */
2887
2888# ifdef __EMX__ /* is this necessary? */
2889 if (!unixy_shell)
2890 minus_c[1] = '/'; /* " /c " */
2891# endif
2892
2893 ap = new_line;
2894 bcopy (shell, ap, shell_len);
2895 ap += shell_len;
2896 bcopy (minus_c, ap, sizeof (minus_c) - 1);
2897 ap += sizeof (minus_c) - 1;
2898 command_ptr = ap;
2899 for (p = line; *p != '\0'; ++p)
2900 {
2901 if (restp != NULL && *p == '\n')
2902 {
2903 *restp = p;
2904 break;
2905 }
2906 else if (*p == '\\' && p[1] == '\n')
2907 {
2908 /* Eat the backslash, the newline, and following whitespace,
2909 replacing it all with a single space (which is escaped
2910 from the shell). */
2911 p += 2;
2912
2913 /* If there is a tab after a backslash-newline,
2914 remove it from the source line which will be echoed,
2915 since it was most likely used to line
2916 up the continued line with the previous one. */
2917 if (*p == '\t')
2918 bcopy (p + 1, p, strlen (p));
2919
2920 p = next_token (p);
2921 --p;
2922 if (unixy_shell && !batch_mode_shell)
2923 *ap++ = '\\';
2924 *ap++ = ' ';
2925 continue;
2926 }
2927
2928 /* DOS shells don't know about backslash-escaping. */
2929 if (unixy_shell && !batch_mode_shell &&
2930 (*p == '\\' || *p == '\'' || *p == '"'
2931 || isspace ((unsigned char)*p)
2932 || strchr (sh_chars, *p) != 0))
2933 *ap++ = '\\';
2934#ifdef __MSDOS__
2935 else if (unixy_shell && strneq (p, "...", 3))
2936 {
2937 /* The case of `...' wildcard again. */
2938 strcpy (ap, "\\.\\.\\");
2939 ap += 5;
2940 p += 2;
2941 }
2942#endif
2943 *ap++ = *p;
2944 }
2945 if (ap == new_line + shell_len + sizeof (minus_c) - 1)
2946 /* Line was empty. */
2947 return 0;
2948 *ap = '\0';
2949
2950#ifdef WINDOWS32
2951 /* Some shells do not work well when invoked as 'sh -c xxx' to run a
2952 command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems). In these
2953 cases, run commands via a script file. */
2954 if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
2955 FILE* batch = NULL;
2956 int id = GetCurrentProcessId();
2957 PATH_VAR(fbuf);
2958
2959 /* create a file name */
2960 sprintf(fbuf, "make%d", id);
2961 *batch_filename_ptr = create_batch_filename (fbuf, unixy_shell);
2962
2963 DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
2964 *batch_filename_ptr));
2965
2966 /* create batch file to execute command */
2967 batch = fopen (*batch_filename_ptr, "w");
2968 if (!unixy_shell)
2969 fputs ("@echo off\n", batch);
2970 fputs (command_ptr, batch);
2971 fputc ('\n', batch);
2972 fclose (batch);
2973
2974 /* create argv */
2975 new_argv = (char **) xmalloc(3 * sizeof (char *));
2976 if (unixy_shell) {
2977 new_argv[0] = xstrdup (shell);
2978 new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
2979 } else {
2980 new_argv[0] = xstrdup (*batch_filename_ptr);
2981 new_argv[1] = NULL;
2982 }
2983 new_argv[2] = NULL;
2984 } else
2985#endif /* WINDOWS32 */
2986 if (unixy_shell)
2987 new_argv = construct_command_argv_internal (new_line, (char **) NULL,
2988 (char *) 0, (char *) 0,
2989 (char **) 0);
2990#ifdef __EMX__
2991 else if (!unixy_shell)
2992 {
2993 /* new_line is local, must not be freed therefore
2994 We use line here instead of new_line because we run the shell
2995 manually. */
2996 size_t line_len = strlen (line);
2997 char *p = new_line;
2998 char *q = new_line;
2999 memcpy (new_line, line, line_len + 1);
3000 /* replace all backslash-newline combination and also following tabs */
3001 while (*q != '\0')
3002 {
3003 if (q[0] == '\\' && q[1] == '\n')
3004 {
3005 q += 2; /* remove '\\' and '\n' */
3006 if (q[0] == '\t')
3007 q++; /* remove 1st tab in the next line */
3008 }
3009 else
3010 *p++ = *q++;
3011 }
3012 *p = '\0';
3013
3014# ifndef NO_CMD_DEFAULT
3015 if (strnicmp (new_line, "echo", 4) == 0
3016 && (new_line[4] == ' ' || new_line[4] == '\t'))
3017 {
3018 /* the builtin echo command: handle it separately */
3019 size_t echo_len = line_len - 5;
3020 char *echo_line = new_line + 5;
3021
3022 /* special case: echo 'x="y"'
3023 cmd works this way: a string is printed as is, i.e., no quotes
3024 are removed. But autoconf uses a command like echo 'x="y"' to
3025 determine whether make works. autoconf expects the output x="y"
3026 so we will do exactly that.
3027 Note: if we do not allow cmd to be the default shell
3028 we do not need this kind of voodoo */
3029 if (echo_line[0] == '\''
3030 && echo_line[echo_len - 1] == '\''
3031 && strncmp (echo_line + 1, "ac_maketemp=",
3032 strlen ("ac_maketemp=")) == 0)
3033 {
3034 /* remove the enclosing quotes */
3035 memmove (echo_line, echo_line + 1, echo_len - 2);
3036 echo_line[echo_len - 2] = '\0';
3037 }
3038 }
3039# endif
3040
3041 {
3042 /* Let the shell decide what to do. Put the command line into the
3043 2nd command line argument and hope for the best ;-) */
3044 size_t sh_len = strlen (shell);
3045
3046 /* exactly 3 arguments + NULL */
3047 new_argv = (char **) xmalloc (4 * sizeof (char *));
3048 /* Exactly strlen(shell) + strlen("/c") + strlen(line) + 3 times
3049 the trailing '\0' */
3050 new_argv[0] = (char *) malloc (sh_len + line_len + 5);
3051 memcpy (new_argv[0], shell, sh_len + 1);
3052 new_argv[1] = new_argv[0] + sh_len + 1;
3053 memcpy (new_argv[1], "/c", 3);
3054 new_argv[2] = new_argv[1] + 3;
3055 memcpy (new_argv[2], new_line, line_len + 1);
3056 new_argv[3] = NULL;
3057 }
3058 }
3059#elif defined(__MSDOS__)
3060 else
3061 {
3062 /* With MSDOS shells, we must construct the command line here
3063 instead of recursively calling ourselves, because we
3064 cannot backslash-escape the special characters (see above). */
3065 new_argv = (char **) xmalloc (sizeof (char *));
3066 line_len = strlen (new_line) - shell_len - sizeof (minus_c) + 1;
3067 new_argv[0] = xmalloc (line_len + 1);
3068 strncpy (new_argv[0],
3069 new_line + shell_len + sizeof (minus_c) - 1, line_len);
3070 new_argv[0][line_len] = '\0';
3071 }
3072#else
3073 else
3074 fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
3075 __FILE__, __LINE__);
3076#endif
3077 }
3078#endif /* ! AMIGA */
3079
3080 return new_argv;
3081}
3082#endif /* !VMS */
3083
3084/* Figure out the argument list necessary to run LINE as a command. Try to
3085 avoid using a shell. This routine handles only ' quoting, and " quoting
3086 when no backslash, $ or ` characters are seen in the quotes. Starting
3087 quotes may be escaped with a backslash. If any of the characters in
3088 sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
3089 is the first word of a line, the shell is used.
3090
3091 If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
3092 If *RESTP is NULL, newlines will be ignored.
3093
3094 FILE is the target whose commands these are. It is used for
3095 variable expansion for $(SHELL) and $(IFS). */
3096
3097char **
3098construct_command_argv (char *line, char **restp, struct file *file,
3099 char **batch_filename_ptr)
3100{
3101 char *shell, *ifs;
3102 char **argv;
3103
3104#ifdef VMS
3105 char *cptr;
3106 int argc;
3107
3108 argc = 0;
3109 cptr = line;
3110 for (;;)
3111 {
3112 while ((*cptr != 0)
3113 && (isspace ((unsigned char)*cptr)))
3114 cptr++;
3115 if (*cptr == 0)
3116 break;
3117 while ((*cptr != 0)
3118 && (!isspace((unsigned char)*cptr)))
3119 cptr++;
3120 argc++;
3121 }
3122
3123 argv = (char **)malloc (argc * sizeof (char *));
3124 if (argv == 0)
3125 abort ();
3126
3127 cptr = line;
3128 argc = 0;
3129 for (;;)
3130 {
3131 while ((*cptr != 0)
3132 && (isspace ((unsigned char)*cptr)))
3133 cptr++;
3134 if (*cptr == 0)
3135 break;
3136 DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
3137 argv[argc++] = cptr;
3138 while ((*cptr != 0)
3139 && (!isspace((unsigned char)*cptr)))
3140 cptr++;
3141 if (*cptr != 0)
3142 *cptr++ = 0;
3143 }
3144#else
3145 {
3146 /* Turn off --warn-undefined-variables while we expand SHELL and IFS. */
3147 int save = warn_undefined_variables_flag;
3148 warn_undefined_variables_flag = 0;
3149
3150 shell = allocated_variable_expand_for_file ("$(SHELL)", file);
3151#ifdef WINDOWS32
3152 /*
3153 * Convert to forward slashes so that construct_command_argv_internal()
3154 * is not confused.
3155 */
3156 if (shell) {
3157 char *p = w32ify (shell, 0);
3158 strcpy (shell, p);
3159 }
3160#endif
3161#ifdef __EMX__
3162 {
3163 static const char *unixroot = NULL;
3164 static const char *last_shell = "";
3165 static int init = 0;
3166 if (init == 0)
3167 {
3168 unixroot = getenv ("UNIXROOT");
3169 /* unixroot must be NULL or not empty */
3170 if (unixroot && unixroot[0] == '\0') unixroot = NULL;
3171 init = 1;
3172 }
3173
3174 /* if we have an unixroot drive and if shell is not default_shell
3175 (which means it's either cmd.exe or the test has already been
3176 performed) and if shell is an absolute path without drive letter,
3177 try whether it exists e.g.: if "/bin/sh" does not exist use
3178 "$UNIXROOT/bin/sh" instead. */
3179 if (unixroot && shell && strcmp (shell, last_shell) != 0
3180 && (shell[0] == '/' || shell[0] == '\\'))
3181 {
3182 /* trying a new shell, check whether it exists */
3183 size_t size = strlen (shell);
3184 char *buf = xmalloc (size + 7);
3185 memcpy (buf, shell, size);
3186 memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
3187 if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
3188 {
3189 /* try the same for the unixroot drive */
3190 memmove (buf + 2, buf, size + 5);
3191 buf[0] = unixroot[0];
3192 buf[1] = unixroot[1];
3193 if (access (buf, F_OK) == 0)
3194 /* we have found a shell! */
3195 /* free(shell); */
3196 shell = buf;
3197 else
3198 free (buf);
3199 }
3200 else
3201 free (buf);
3202 }
3203 }
3204#endif /* __EMX__ */
3205
3206 ifs = allocated_variable_expand_for_file ("$(IFS)", file);
3207
3208 warn_undefined_variables_flag = save;
3209 }
3210#if defined(CONFIG_WITH_KMK_BUILTIN) && defined(WINDOWS32)
3211 if (!strncmp(line, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
3212 {
3213 int saved_batch_mode_shell = batch_mode_shell;
3214 int saved_no_default_sh_exe = no_default_sh_exe;
3215 int saved_unixy_shell = unixy_shell;
3216 unixy_shell = 1;
3217 batch_mode_shell = 0;
3218 no_default_sh_exe = 0;
3219 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
3220 no_default_sh_exe = saved_no_default_sh_exe;
3221 batch_mode_shell = saved_batch_mode_shell;
3222 unixy_shell = saved_unixy_shell;
3223 }
3224 else
3225#endif
3226 argv = construct_command_argv_internal (line, restp, shell, ifs, batch_filename_ptr);
3227
3228 free (shell);
3229 free (ifs);
3230#endif /* !VMS */
3231 return argv;
3232}
3233
3234
3235#if !defined(HAVE_DUP2) && !defined(_AMIGA)
3236int
3237dup2 (int old, int new)
3238{
3239 int fd;
3240
3241 (void) close (new);
3242 fd = dup (old);
3243 if (fd != new)
3244 {
3245 (void) close (fd);
3246 errno = EMFILE;
3247 return -1;
3248 }
3249
3250 return fd;
3251}
3252#endif /* !HAPE_DUP2 && !_AMIGA */
3253
3254/* On VMS systems, include special VMS functions. */
3255
3256#ifdef VMS
3257#include "vmsjobs.c"
3258#endif
Note: See TracBrowser for help on using the repository browser.