VirtualBox

source: kBuild/trunk/src/kmk/job.c@ 2844

Last change on this file since 2844 was 2844, checked in by bird, 8 years ago

kSubmit/kWorker: updates

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

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