Debian Codegraph @

src/job.c

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