job.c revision 1.265 1 /* $NetBSD: job.c,v 1.265 2020/10/18 13:02:10 rillig Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 /*
36 * Copyright (c) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
39 *
40 * This code is derived from software contributed to Berkeley by
41 * Adam de Boor.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
58 *
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
70 */
71
72 /*-
73 * job.c --
74 * handle the creation etc. of our child processes.
75 *
76 * Interface:
77 * Job_Make Start the creation of the given target.
78 *
79 * Job_CatchChildren
80 * Check for and handle the termination of any
81 * children. This must be called reasonably
82 * frequently to keep the whole make going at
83 * a decent clip, since job table entries aren't
84 * removed until their process is caught this way.
85 *
86 * Job_CatchOutput
87 * Print any output our children have produced.
88 * Should also be called fairly frequently to
89 * keep the user informed of what's going on.
90 * If no output is waiting, it will block for
91 * a time given by the SEL_* constants, below,
92 * or until output is ready.
93 *
94 * Job_Init Called to initialize this module. in addition,
95 * any commands attached to the .BEGIN target
96 * are executed before this function returns.
97 * Hence, the makefile must have been parsed
98 * before this function is called.
99 *
100 * Job_End Clean up any memory used.
101 *
102 * Job_ParseShell Given the line following a .SHELL target, parse
103 * the line as a shell specification. Returns
104 * FALSE if the spec was incorrect.
105 *
106 * Job_Finish Perform any final processing which needs doing.
107 * This includes the execution of any commands
108 * which have been/were attached to the .END
109 * target. It should only be called when the
110 * job table is empty.
111 *
112 * Job_AbortAll Abort all currently running jobs. It doesn't
113 * handle output or do anything for the jobs,
114 * just kills them. It should only be called in
115 * an emergency, as it were.
116 *
117 * Job_CheckCommands
118 * Verify that the commands for a target are
119 * ok. Provide them if necessary and possible.
120 *
121 * Job_Touch Update a target without really updating it.
122 *
123 * Job_Wait Wait for all currently-running jobs to finish.
124 */
125
126 #include <sys/types.h>
127 #include <sys/stat.h>
128 #include <sys/file.h>
129 #include <sys/time.h>
130 #include <sys/wait.h>
131
132 #include <errno.h>
133 #ifndef USE_SELECT
134 #include <poll.h>
135 #endif
136 #include <signal.h>
137 #include <utime.h>
138
139 #include "make.h"
140 #include "dir.h"
141 #include "job.h"
142 #include "pathnames.h"
143 #include "trace.h"
144
145 /* "@(#)job.c 8.2 (Berkeley) 3/19/94" */
146 MAKE_RCSID("$NetBSD: job.c,v 1.265 2020/10/18 13:02:10 rillig Exp $");
147
148 # define STATIC static
149
150 /*
151 * error handling variables
152 */
153 static int errors = 0; /* number of errors reported */
154 static int aborting = 0; /* why is the make aborting? */
155 #define ABORT_ERROR 1 /* Because of an error */
156 #define ABORT_INTERRUPT 2 /* Because it was interrupted */
157 #define ABORT_WAIT 3 /* Waiting for jobs to finish */
158 #define JOB_TOKENS "+EI+" /* Token to requeue for each abort state */
159
160 /*
161 * this tracks the number of tokens currently "out" to build jobs.
162 */
163 int jobTokensRunning = 0;
164
165 /* The number of commands actually printed for a target.
166 * XXX: Why printed? Shouldn't that be run/printed instead, depending on the
167 * command line options?
168 * Should this number be 0, no shell will be executed. */
169 static int numCommands;
170
171 /*
172 * Return values from JobStart.
173 */
174 #define JOB_RUNNING 0 /* Job is running */
175 #define JOB_ERROR 1 /* Error in starting the job */
176 #define JOB_FINISHED 2 /* The job is already finished */
177
178 /*
179 * Descriptions for various shells.
180 *
181 * The build environment may set DEFSHELL_INDEX to one of
182 * DEFSHELL_INDEX_SH, DEFSHELL_INDEX_KSH, or DEFSHELL_INDEX_CSH, to
183 * select one of the predefined shells as the default shell.
184 *
185 * Alternatively, the build environment may set DEFSHELL_CUSTOM to the
186 * name or the full path of a sh-compatible shell, which will be used as
187 * the default shell.
188 *
189 * ".SHELL" lines in Makefiles can choose the default shell from the
190 # set defined here, or add additional shells.
191 */
192
193 #ifdef DEFSHELL_CUSTOM
194 #define DEFSHELL_INDEX_CUSTOM 0
195 #define DEFSHELL_INDEX_SH 1
196 #define DEFSHELL_INDEX_KSH 2
197 #define DEFSHELL_INDEX_CSH 3
198 #else /* !DEFSHELL_CUSTOM */
199 #define DEFSHELL_INDEX_SH 0
200 #define DEFSHELL_INDEX_KSH 1
201 #define DEFSHELL_INDEX_CSH 2
202 #endif /* !DEFSHELL_CUSTOM */
203
204 #ifndef DEFSHELL_INDEX
205 #define DEFSHELL_INDEX 0 /* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */
206 #endif /* !DEFSHELL_INDEX */
207
208 static Shell shells[] = {
209 #ifdef DEFSHELL_CUSTOM
210 /*
211 * An sh-compatible shell with a non-standard name.
212 *
213 * Keep this in sync with the "sh" description below, but avoid
214 * non-portable features that might not be supplied by all
215 * sh-compatible shells.
216 */
217 {
218 DEFSHELL_CUSTOM,
219 FALSE, "", "", "", 0,
220 FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
221 "",
222 "",
223 },
224 #endif /* DEFSHELL_CUSTOM */
225 /*
226 * SH description. Echo control is also possible and, under
227 * sun UNIX anyway, one can even control error checking.
228 */
229 {
230 "sh",
231 FALSE, "", "", "", 0,
232 FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
233 #if defined(MAKE_NATIVE) && defined(__NetBSD__)
234 "q",
235 #else
236 "",
237 #endif
238 "",
239 },
240 /*
241 * KSH description.
242 */
243 {
244 "ksh",
245 TRUE, "set +v", "set -v", "set +v", 6,
246 FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#',
247 "v",
248 "",
249 },
250 /*
251 * CSH description. The csh can do echo control by playing
252 * with the setting of the 'echo' shell variable. Sadly,
253 * however, it is unable to do error control nicely.
254 */
255 {
256 "csh",
257 TRUE, "unset verbose", "set verbose", "unset verbose", 13,
258 FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"\n", "", "'\\\n'", '#',
259 "v", "e",
260 },
261 /*
262 * UNKNOWN.
263 */
264 {
265 NULL,
266 FALSE, NULL, NULL, NULL, 0,
267 FALSE, NULL, NULL, NULL, NULL, 0,
268 NULL, NULL,
269 }
270 };
271
272 /* This is the shell to which we pass all commands in the Makefile.
273 * It is set by the Job_ParseShell function. */
274 static Shell *commandShell = &shells[DEFSHELL_INDEX];
275 const char *shellPath = NULL; /* full pathname of executable image */
276 const char *shellName = NULL; /* last component of shellPath */
277 char *shellErrFlag = NULL;
278 static char *shellArgv = NULL; /* Custom shell args */
279
280
281 STATIC Job *job_table; /* The structures that describe them */
282 STATIC Job *job_table_end; /* job_table + maxJobs */
283 static unsigned int wantToken; /* we want a token */
284 static int lurking_children = 0;
285 static int make_suspended = 0; /* non-zero if we've seen a SIGTSTP (etc) */
286
287 /*
288 * Set of descriptors of pipes connected to
289 * the output channels of children
290 */
291 static struct pollfd *fds = NULL;
292 static Job **jobfds = NULL;
293 static nfds_t nfds = 0;
294 static void watchfd(Job *);
295 static void clearfd(Job *);
296 static int readyfd(Job *);
297
298 STATIC GNode *lastNode; /* The node for which output was most recently
299 * produced. */
300 static char *targPrefix = NULL; /* What we print at the start of TARG_FMT */
301 static Job tokenWaitJob; /* token wait pseudo-job */
302
303 static Job childExitJob; /* child exit pseudo-job */
304 #define CHILD_EXIT "."
305 #define DO_JOB_RESUME "R"
306
307 enum { npseudojobs = 2 }; /* number of pseudo-jobs */
308
309 #define TARG_FMT "%s %s ---\n" /* Default format */
310 #define MESSAGE(fp, gn) \
311 if (maxJobs != 1 && targPrefix && *targPrefix) \
312 (void)fprintf(fp, TARG_FMT, targPrefix, gn->name)
313
314 static sigset_t caught_signals; /* Set of signals we handle */
315
316 static void JobDoOutput(Job *, Boolean);
317 static void JobInterrupt(int, int) MAKE_ATTR_DEAD;
318 static void JobRestartJobs(void);
319 static void JobSigReset(void);
320
321 static unsigned
322 nfds_per_job(void)
323 {
324 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
325 if (useMeta)
326 return 2;
327 #endif
328 return 1;
329 }
330
331 static void
332 job_table_dump(const char *where)
333 {
334 Job *job;
335
336 debug_printf("job table @ %s\n", where);
337 for (job = job_table; job < job_table_end; job++) {
338 debug_printf("job %d, status %d, flags %d, pid %d\n",
339 (int)(job - job_table), job->job_state, job->flags, job->pid);
340 }
341 }
342
343 /*
344 * Delete the target of a failed, interrupted, or otherwise
345 * unsuccessful job unless inhibited by .PRECIOUS.
346 */
347 static void
348 JobDeleteTarget(GNode *gn)
349 {
350 if ((gn->type & (OP_JOIN|OP_PHONY)) == 0 && !Targ_Precious(gn)) {
351 char *file = (gn->path == NULL ? gn->name : gn->path);
352 if (!noExecute && eunlink(file) != -1) {
353 Error("*** %s removed", file);
354 }
355 }
356 }
357
358 /*
359 * JobSigLock/JobSigUnlock
360 *
361 * Signal lock routines to get exclusive access. Currently used to
362 * protect `jobs' and `stoppedJobs' list manipulations.
363 */
364 static void JobSigLock(sigset_t *omaskp)
365 {
366 if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) {
367 Punt("JobSigLock: sigprocmask: %s", strerror(errno));
368 sigemptyset(omaskp);
369 }
370 }
371
372 static void JobSigUnlock(sigset_t *omaskp)
373 {
374 (void)sigprocmask(SIG_SETMASK, omaskp, NULL);
375 }
376
377 static void
378 JobCreatePipe(Job *job, int minfd)
379 {
380 int i, fd, flags;
381 int pipe_fds[2];
382
383 if (pipe(pipe_fds) == -1)
384 Punt("Cannot create pipe: %s", strerror(errno));
385
386 for (i = 0; i < 2; i++) {
387 /* Avoid using low numbered fds */
388 fd = fcntl(pipe_fds[i], F_DUPFD, minfd);
389 if (fd != -1) {
390 close(pipe_fds[i]);
391 pipe_fds[i] = fd;
392 }
393 }
394
395 job->inPipe = pipe_fds[0];
396 job->outPipe = pipe_fds[1];
397
398 /* Set close-on-exec flag for both */
399 if (fcntl(job->inPipe, F_SETFD, FD_CLOEXEC) == -1)
400 Punt("Cannot set close-on-exec: %s", strerror(errno));
401 if (fcntl(job->outPipe, F_SETFD, FD_CLOEXEC) == -1)
402 Punt("Cannot set close-on-exec: %s", strerror(errno));
403
404 /*
405 * We mark the input side of the pipe non-blocking; we poll(2) the
406 * pipe when we're waiting for a job token, but we might lose the
407 * race for the token when a new one becomes available, so the read
408 * from the pipe should not block.
409 */
410 flags = fcntl(job->inPipe, F_GETFL, 0);
411 if (flags == -1)
412 Punt("Cannot get flags: %s", strerror(errno));
413 flags |= O_NONBLOCK;
414 if (fcntl(job->inPipe, F_SETFL, flags) == -1)
415 Punt("Cannot set flags: %s", strerror(errno));
416 }
417
418 /* Pass the signal to each running job. */
419 static void
420 JobCondPassSig(int signo)
421 {
422 Job *job;
423
424 DEBUG1(JOB, "JobCondPassSig(%d) called.\n", signo);
425
426 for (job = job_table; job < job_table_end; job++) {
427 if (job->job_state != JOB_ST_RUNNING)
428 continue;
429 DEBUG2(JOB, "JobCondPassSig passing signal %d to child %d.\n",
430 signo, job->pid);
431 KILLPG(job->pid, signo);
432 }
433 }
434
435 /* SIGCHLD handler.
436 *
437 * Sends a token on the child exit pipe to wake us up from select()/poll(). */
438 static void
439 JobChildSig(int signo MAKE_ATTR_UNUSED)
440 {
441 while (write(childExitJob.outPipe, CHILD_EXIT, 1) == -1 && errno == EAGAIN)
442 continue;
443 }
444
445
446 /* Resume all stopped jobs. */
447 static void
448 JobContinueSig(int signo MAKE_ATTR_UNUSED)
449 {
450 /*
451 * Defer sending to SIGCONT to our stopped children until we return
452 * from the signal handler.
453 */
454 while (write(childExitJob.outPipe, DO_JOB_RESUME, 1) == -1 &&
455 errno == EAGAIN)
456 continue;
457 }
458
459 /* Pass a signal on to all jobs, then resend to ourselves.
460 * We die by the same signal. */
461 MAKE_ATTR_DEAD static void
462 JobPassSig_int(int signo)
463 {
464 /* Run .INTERRUPT target then exit */
465 JobInterrupt(TRUE, signo);
466 }
467
468 /* Pass a signal on to all jobs, then resend to ourselves.
469 * We die by the same signal. */
470 MAKE_ATTR_DEAD static void
471 JobPassSig_term(int signo)
472 {
473 /* Dont run .INTERRUPT target then exit */
474 JobInterrupt(FALSE, signo);
475 }
476
477 static void
478 JobPassSig_suspend(int signo)
479 {
480 sigset_t nmask, omask;
481 struct sigaction act;
482
483 /* Suppress job started/continued messages */
484 make_suspended = 1;
485
486 /* Pass the signal onto every job */
487 JobCondPassSig(signo);
488
489 /*
490 * Send ourselves the signal now we've given the message to everyone else.
491 * Note we block everything else possible while we're getting the signal.
492 * This ensures that all our jobs get continued when we wake up before
493 * we take any other signal.
494 */
495 sigfillset(&nmask);
496 sigdelset(&nmask, signo);
497 (void)sigprocmask(SIG_SETMASK, &nmask, &omask);
498
499 act.sa_handler = SIG_DFL;
500 sigemptyset(&act.sa_mask);
501 act.sa_flags = 0;
502 (void)sigaction(signo, &act, NULL);
503
504 if (DEBUG(JOB))
505 debug_printf("JobPassSig passing signal %d to self.\n", signo);
506
507 (void)kill(getpid(), signo);
508
509 /*
510 * We've been continued.
511 *
512 * A whole host of signals continue to happen!
513 * SIGCHLD for any processes that actually suspended themselves.
514 * SIGCHLD for any processes that exited while we were alseep.
515 * The SIGCONT that actually caused us to wakeup.
516 *
517 * Since we defer passing the SIGCONT on to our children until
518 * the main processing loop, we can be sure that all the SIGCHLD
519 * events will have happened by then - and that the waitpid() will
520 * collect the child 'suspended' events.
521 * For correct sequencing we just need to ensure we process the
522 * waitpid() before passign on the SIGCONT.
523 *
524 * In any case nothing else is needed here.
525 */
526
527 /* Restore handler and signal mask */
528 act.sa_handler = JobPassSig_suspend;
529 (void)sigaction(signo, &act, NULL);
530 (void)sigprocmask(SIG_SETMASK, &omask, NULL);
531 }
532
533 static Job *
534 JobFindPid(int pid, int status, Boolean isJobs)
535 {
536 Job *job;
537
538 for (job = job_table; job < job_table_end; job++) {
539 if ((job->job_state == status) && job->pid == pid)
540 return job;
541 }
542 if (DEBUG(JOB) && isJobs)
543 job_table_dump("no pid");
544 return NULL;
545 }
546
547 /*-
548 *-----------------------------------------------------------------------
549 * JobPrintCommand --
550 * Put out another command for the given job. If the command starts
551 * with an @ or a - we process it specially. In the former case,
552 * so long as the -s and -n flags weren't given to make, we stick
553 * a shell-specific echoOff command in the script. In the latter,
554 * we ignore errors for the entire job, unless the shell has error
555 * control.
556 * If the command is just "..." we take all future commands for this
557 * job to be commands to be executed once the entire graph has been
558 * made and return non-zero to signal that the end of the commands
559 * was reached. These commands are later attached to the postCommands
560 * node and executed by Job_End when all things are done.
561 * This function is called from JobStart via Lst_ForEachUntil.
562 *
563 * Input:
564 * cmdp command string to print
565 * jobp job for which to print it
566 *
567 * Results:
568 * 0, unless the command was "..."
569 *
570 * Side Effects:
571 * If the command begins with a '-' and the shell has no error control,
572 * the JOB_IGNERR flag is set in the job descriptor.
573 * If the command is "..." and we're not ignoring such things,
574 * tailCmds is set to the successor node of the cmd.
575 * numCommands is incremented if the command is actually printed.
576 *-----------------------------------------------------------------------
577 */
578 static int
579 JobPrintCommand(void *cmdp, void *jobp)
580 {
581 Boolean noSpecials; /* true if we shouldn't worry about
582 * inserting special commands into
583 * the input stream. */
584 Boolean shutUp = FALSE; /* true if we put a no echo command
585 * into the command file */
586 Boolean errOff = FALSE; /* true if we turned error checking
587 * off before printing the command
588 * and need to turn it back on */
589 const char *cmdTemplate; /* Template to use when printing the
590 * command */
591 char *cmdStart; /* Start of expanded command */
592 char *escCmd = NULL; /* Command with quotes/backticks escaped */
593 char *cmd = (char *)cmdp;
594 Job *job = (Job *)jobp;
595
596 noSpecials = NoExecute(job->node);
597
598 if (strcmp(cmd, "...") == 0) {
599 job->node->type |= OP_SAVE_CMDS;
600 if ((job->flags & JOB_IGNDOTS) == 0) {
601 StringListNode *dotsNode = Lst_FindDatum(job->node->commands, cmd);
602 job->tailCmds = dotsNode != NULL ? dotsNode->next : NULL;
603 return 1;
604 }
605 return 0;
606 }
607
608 #define DBPRINTF(fmt, arg) if (DEBUG(JOB)) { \
609 debug_printf(fmt, arg); \
610 } \
611 (void)fprintf(job->cmdFILE, fmt, arg); \
612 (void)fflush(job->cmdFILE);
613
614 numCommands++;
615
616 Var_Subst(cmd, job->node, VARE_WANTRES, &cmd);
617 /* TODO: handle errors */
618 cmdStart = cmd;
619
620 cmdTemplate = "%s\n";
621
622 /*
623 * Check for leading @' and -'s to control echoing and error checking.
624 */
625 while (*cmd == '@' || *cmd == '-' || (*cmd == '+')) {
626 switch (*cmd) {
627 case '@':
628 shutUp = DEBUG(LOUD) ? FALSE : TRUE;
629 break;
630 case '-':
631 errOff = TRUE;
632 break;
633 case '+':
634 if (noSpecials) {
635 /*
636 * We're not actually executing anything...
637 * but this one needs to be - use compat mode just for it.
638 */
639 Compat_RunCommand(cmdp, job->node);
640 free(cmdStart);
641 return 0;
642 }
643 break;
644 }
645 cmd++;
646 }
647
648 pp_skip_whitespace(&cmd);
649
650 /*
651 * If the shell doesn't have error control the alternate echo'ing will
652 * be done (to avoid showing additional error checking code)
653 * and this will need the characters '$ ` \ "' escaped
654 */
655
656 if (!commandShell->hasErrCtl) {
657 int i, j;
658
659 /* Worst that could happen is every char needs escaping. */
660 escCmd = bmake_malloc((strlen(cmd) * 2) + 1);
661 for (i = 0, j = 0; cmd[i] != '\0'; i++, j++) {
662 if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' ||
663 cmd[i] == '"')
664 escCmd[j++] = '\\';
665 escCmd[j] = cmd[i];
666 }
667 escCmd[j] = '\0';
668 }
669
670 if (shutUp) {
671 if (!(job->flags & JOB_SILENT) && !noSpecials &&
672 commandShell->hasEchoCtl) {
673 DBPRINTF("%s\n", commandShell->echoOff);
674 } else {
675 if (commandShell->hasErrCtl)
676 shutUp = FALSE;
677 }
678 }
679
680 if (errOff) {
681 if (!noSpecials) {
682 if (commandShell->hasErrCtl) {
683 /*
684 * we don't want the error-control commands showing
685 * up either, so we turn off echoing while executing
686 * them. We could put another field in the shell
687 * structure to tell JobDoOutput to look for this
688 * string too, but why make it any more complex than
689 * it already is?
690 */
691 if (!(job->flags & JOB_SILENT) && !shutUp &&
692 commandShell->hasEchoCtl) {
693 DBPRINTF("%s\n", commandShell->echoOff);
694 DBPRINTF("%s\n", commandShell->ignErr);
695 DBPRINTF("%s\n", commandShell->echoOn);
696 } else {
697 DBPRINTF("%s\n", commandShell->ignErr);
698 }
699 } else if (commandShell->ignErr &&
700 commandShell->ignErr[0] != '\0')
701 {
702 /*
703 * The shell has no error control, so we need to be
704 * weird to get it to ignore any errors from the command.
705 * If echoing is turned on, we turn it off and use the
706 * errCheck template to echo the command. Leave echoing
707 * off so the user doesn't see the weirdness we go through
708 * to ignore errors. Set cmdTemplate to use the weirdness
709 * instead of the simple "%s\n" template.
710 */
711 job->flags |= JOB_IGNERR;
712 if (!(job->flags & JOB_SILENT) && !shutUp) {
713 if (commandShell->hasEchoCtl) {
714 DBPRINTF("%s\n", commandShell->echoOff);
715 }
716 DBPRINTF(commandShell->errCheck, escCmd);
717 shutUp = TRUE;
718 } else {
719 if (!shutUp) {
720 DBPRINTF(commandShell->errCheck, escCmd);
721 }
722 }
723 cmdTemplate = commandShell->ignErr;
724 /*
725 * The error ignoration (hee hee) is already taken care
726 * of by the ignErr template, so pretend error checking
727 * is still on.
728 */
729 errOff = FALSE;
730 } else {
731 errOff = FALSE;
732 }
733 } else {
734 errOff = FALSE;
735 }
736 } else {
737
738 /*
739 * If errors are being checked and the shell doesn't have error control
740 * but does supply an errOut template, then setup commands to run
741 * through it.
742 */
743
744 if (!commandShell->hasErrCtl && commandShell->errOut &&
745 commandShell->errOut[0] != '\0') {
746 if (!(job->flags & JOB_SILENT) && !shutUp) {
747 if (commandShell->hasEchoCtl) {
748 DBPRINTF("%s\n", commandShell->echoOff);
749 }
750 DBPRINTF(commandShell->errCheck, escCmd);
751 shutUp = TRUE;
752 }
753 /* If it's a comment line or blank, treat as an ignored error */
754 if ((escCmd[0] == commandShell->commentChar) ||
755 (escCmd[0] == 0))
756 cmdTemplate = commandShell->ignErr;
757 else
758 cmdTemplate = commandShell->errOut;
759 errOff = FALSE;
760 }
761 }
762
763 if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 &&
764 (job->flags & JOB_TRACED) == 0) {
765 DBPRINTF("set -%s\n", "x");
766 job->flags |= JOB_TRACED;
767 }
768
769 DBPRINTF(cmdTemplate, cmd);
770 free(cmdStart);
771 free(escCmd);
772 if (errOff) {
773 /*
774 * If echoing is already off, there's no point in issuing the
775 * echoOff command. Otherwise we issue it and pretend it was on
776 * for the whole command...
777 */
778 if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
779 DBPRINTF("%s\n", commandShell->echoOff);
780 shutUp = TRUE;
781 }
782 DBPRINTF("%s\n", commandShell->errCheck);
783 }
784 if (shutUp && commandShell->hasEchoCtl) {
785 DBPRINTF("%s\n", commandShell->echoOn);
786 }
787 return 0;
788 }
789
790 /* Save the delayed commands, to be executed when everything else is done. */
791 static void
792 JobSaveCommands(Job *job)
793 {
794 StringListNode *node;
795
796 for (node = job->tailCmds; node != NULL; node = node->next) {
797 const char *cmd = node->datum;
798 char *expanded_cmd;
799 /* XXX: This Var_Subst is only intended to expand the dynamic
800 * variables such as .TARGET, .IMPSRC. It is not intended to
801 * expand the other variables as well; see deptgt-end.mk. */
802 (void)Var_Subst(cmd, job->node, VARE_WANTRES, &expanded_cmd);
803 /* TODO: handle errors */
804 Lst_Append(Targ_GetEndNode()->commands, expanded_cmd);
805 }
806 }
807
808
809 /* Called to close both input and output pipes when a job is finished. */
810 static void
811 JobClose(Job *job)
812 {
813 clearfd(job);
814 (void)close(job->outPipe);
815 job->outPipe = -1;
816
817 JobDoOutput(job, TRUE);
818 (void)close(job->inPipe);
819 job->inPipe = -1;
820 }
821
822 /*-
823 *-----------------------------------------------------------------------
824 * JobFinish --
825 * Do final processing for the given job including updating
826 * parents and starting new jobs as available/necessary. Note
827 * that we pay no attention to the JOB_IGNERR flag here.
828 * This is because when we're called because of a noexecute flag
829 * or something, jstat.w_status is 0 and when called from
830 * Job_CatchChildren, the status is zeroed if it s/b ignored.
831 *
832 * Input:
833 * job job to finish
834 * status sub-why job went away
835 *
836 * Side Effects:
837 * Final commands for the job are placed on postCommands.
838 *
839 * If we got an error and are aborting (aborting == ABORT_ERROR) and
840 * the job list is now empty, we are done for the day.
841 * If we recognized an error (errors !=0), we set the aborting flag
842 * to ABORT_ERROR so no more jobs will be started.
843 *-----------------------------------------------------------------------
844 */
845 static void
846 JobFinish(Job *job, int status)
847 {
848 Boolean done, return_job_token;
849
850 DEBUG3(JOB, "JobFinish: %d [%s], status %d\n",
851 job->pid, job->node->name, status);
852
853 if ((WIFEXITED(status) &&
854 (((WEXITSTATUS(status) != 0) && !(job->flags & JOB_IGNERR)))) ||
855 WIFSIGNALED(status))
856 {
857 /*
858 * If it exited non-zero and either we're doing things our
859 * way or we're not ignoring errors, the job is finished.
860 * Similarly, if the shell died because of a signal
861 * the job is also finished. In these
862 * cases, finish out the job's output before printing the exit
863 * status...
864 */
865 JobClose(job);
866 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
867 (void)fclose(job->cmdFILE);
868 job->cmdFILE = NULL;
869 }
870 done = TRUE;
871 } else if (WIFEXITED(status)) {
872 /*
873 * Deal with ignored errors in -B mode. We need to print a message
874 * telling of the ignored error as well as setting status.w_status
875 * to 0 so the next command gets run. To do this, we set done to be
876 * TRUE if in -B mode and the job exited non-zero.
877 */
878 done = WEXITSTATUS(status) != 0;
879 /*
880 * Old comment said: "Note we don't
881 * want to close down any of the streams until we know we're at the
882 * end."
883 * But we do. Otherwise when are we going to print the rest of the
884 * stuff?
885 */
886 JobClose(job);
887 } else {
888 /*
889 * No need to close things down or anything.
890 */
891 done = FALSE;
892 }
893
894 if (done) {
895 if (WIFEXITED(status)) {
896 DEBUG2(JOB, "Process %d [%s] exited.\n",
897 job->pid, job->node->name);
898 if (WEXITSTATUS(status) != 0) {
899 if (job->node != lastNode) {
900 MESSAGE(stdout, job->node);
901 lastNode = job->node;
902 }
903 #ifdef USE_META
904 if (useMeta) {
905 meta_job_error(job, job->node, job->flags, WEXITSTATUS(status));
906 }
907 #endif
908 if (!dieQuietly(job->node, -1))
909 (void)printf("*** [%s] Error code %d%s\n",
910 job->node->name,
911 WEXITSTATUS(status),
912 (job->flags & JOB_IGNERR) ? " (ignored)" : "");
913 if (job->flags & JOB_IGNERR) {
914 status = 0;
915 } else {
916 if (deleteOnError) {
917 JobDeleteTarget(job->node);
918 }
919 PrintOnError(job->node, NULL);
920 }
921 } else if (DEBUG(JOB)) {
922 if (job->node != lastNode) {
923 MESSAGE(stdout, job->node);
924 lastNode = job->node;
925 }
926 (void)printf("*** [%s] Completed successfully\n",
927 job->node->name);
928 }
929 } else {
930 if (job->node != lastNode) {
931 MESSAGE(stdout, job->node);
932 lastNode = job->node;
933 }
934 (void)printf("*** [%s] Signal %d\n",
935 job->node->name, WTERMSIG(status));
936 if (deleteOnError) {
937 JobDeleteTarget(job->node);
938 }
939 }
940 (void)fflush(stdout);
941 }
942
943 #ifdef USE_META
944 if (useMeta) {
945 int x;
946
947 if ((x = meta_job_finish(job)) != 0 && status == 0) {
948 status = x;
949 }
950 }
951 #endif
952
953 return_job_token = FALSE;
954
955 Trace_Log(JOBEND, job);
956 if (!(job->flags & JOB_SPECIAL)) {
957 if ((status != 0) ||
958 (aborting == ABORT_ERROR) ||
959 (aborting == ABORT_INTERRUPT))
960 return_job_token = TRUE;
961 }
962
963 if ((aborting != ABORT_ERROR) && (aborting != ABORT_INTERRUPT) && (status == 0)) {
964 /*
965 * As long as we aren't aborting and the job didn't return a non-zero
966 * status that we shouldn't ignore, we call Make_Update to update
967 * the parents.
968 */
969 JobSaveCommands(job);
970 job->node->made = MADE;
971 if (!(job->flags & JOB_SPECIAL))
972 return_job_token = TRUE;
973 Make_Update(job->node);
974 job->job_state = JOB_ST_FREE;
975 } else if (status != 0) {
976 errors++;
977 job->job_state = JOB_ST_FREE;
978 }
979
980 /*
981 * Set aborting if any error.
982 */
983 if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
984 /*
985 * If we found any errors in this batch of children and the -k flag
986 * wasn't given, we set the aborting flag so no more jobs get
987 * started.
988 */
989 aborting = ABORT_ERROR;
990 }
991
992 if (return_job_token)
993 Job_TokenReturn();
994
995 if (aborting == ABORT_ERROR && jobTokensRunning == 0) {
996 /*
997 * If we are aborting and the job table is now empty, we finish.
998 */
999 Finish(errors);
1000 }
1001 }
1002
1003 /* Touch the given target. Called by JobStart when the -t flag was given.
1004 *
1005 * The modification date of the file is changed.
1006 * If the file did not exist, it is created. */
1007 void
1008 Job_Touch(GNode *gn, Boolean silent)
1009 {
1010 int streamID; /* ID of stream opened to do the touch */
1011 struct utimbuf times; /* Times for utime() call */
1012
1013 if (gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC|OP_OPTIONAL|
1014 OP_SPECIAL|OP_PHONY)) {
1015 /*
1016 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
1017 * and, as such, shouldn't really be created.
1018 */
1019 return;
1020 }
1021
1022 if (!silent || NoExecute(gn)) {
1023 (void)fprintf(stdout, "touch %s\n", gn->name);
1024 (void)fflush(stdout);
1025 }
1026
1027 if (NoExecute(gn)) {
1028 return;
1029 }
1030
1031 if (gn->type & OP_ARCHV) {
1032 Arch_Touch(gn);
1033 } else if (gn->type & OP_LIB) {
1034 Arch_TouchLib(gn);
1035 } else {
1036 char *file = gn->path ? gn->path : gn->name;
1037
1038 times.actime = times.modtime = now;
1039 if (utime(file, ×) < 0){
1040 streamID = open(file, O_RDWR | O_CREAT, 0666);
1041
1042 if (streamID >= 0) {
1043 char c;
1044
1045 /*
1046 * Read and write a byte to the file to change the
1047 * modification time, then close the file.
1048 */
1049 if (read(streamID, &c, 1) == 1) {
1050 (void)lseek(streamID, (off_t)0, SEEK_SET);
1051 while (write(streamID, &c, 1) == -1 && errno == EAGAIN)
1052 continue;
1053 }
1054
1055 (void)close(streamID);
1056 } else {
1057 (void)fprintf(stdout, "*** couldn't touch %s: %s",
1058 file, strerror(errno));
1059 (void)fflush(stdout);
1060 }
1061 }
1062 }
1063 }
1064
1065 /* Make sure the given node has all the commands it needs.
1066 *
1067 * The node will have commands from the .DEFAULT rule added to it if it
1068 * needs them.
1069 *
1070 * Input:
1071 * gn The target whose commands need verifying
1072 * abortProc Function to abort with message
1073 *
1074 * Results:
1075 * TRUE if the commands list is/was ok.
1076 */
1077 Boolean
1078 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1079 {
1080 if (OP_NOP(gn->type) && Lst_IsEmpty(gn->commands) &&
1081 ((gn->type & OP_LIB) == 0 || Lst_IsEmpty(gn->children))) {
1082 /*
1083 * No commands. Look for .DEFAULT rule from which we might infer
1084 * commands
1085 */
1086 if ((DEFAULT != NULL) && !Lst_IsEmpty(DEFAULT->commands) &&
1087 (gn->type & OP_SPECIAL) == 0) {
1088 char *p1;
1089 /*
1090 * Make only looks for a .DEFAULT if the node was never the
1091 * target of an operator, so that's what we do too. If
1092 * a .DEFAULT was given, we substitute its commands for gn's
1093 * commands and set the IMPSRC variable to be the target's name
1094 * The DEFAULT node acts like a transformation rule, in that
1095 * gn also inherits any attributes or sources attached to
1096 * .DEFAULT itself.
1097 */
1098 Make_HandleUse(DEFAULT, gn);
1099 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn);
1100 bmake_free(p1);
1101 } else if (Dir_MTime(gn, 0) == 0 && (gn->type & OP_SPECIAL) == 0) {
1102 /*
1103 * The node wasn't the target of an operator. We have no .DEFAULT
1104 * rule to go on and the target doesn't already exist. There's
1105 * nothing more we can do for this branch. If the -k flag wasn't
1106 * given, we stop in our tracks, otherwise we just don't update
1107 * this node's parents so they never get examined.
1108 */
1109 static const char msg[] = ": don't know how to make";
1110
1111 if (gn->flags & FROM_DEPEND) {
1112 if (!Job_RunTarget(".STALE", gn->fname))
1113 fprintf(stdout, "%s: %s, %d: ignoring stale %s for %s\n",
1114 progname, gn->fname, gn->lineno, makeDependfile,
1115 gn->name);
1116 return TRUE;
1117 }
1118
1119 if (gn->type & OP_OPTIONAL) {
1120 (void)fprintf(stdout, "%s%s %s (ignored)\n", progname,
1121 msg, gn->name);
1122 (void)fflush(stdout);
1123 } else if (keepgoing) {
1124 (void)fprintf(stdout, "%s%s %s (continuing)\n", progname,
1125 msg, gn->name);
1126 (void)fflush(stdout);
1127 return FALSE;
1128 } else {
1129 (*abortProc)("%s%s %s. Stop", progname, msg, gn->name);
1130 return FALSE;
1131 }
1132 }
1133 }
1134 return TRUE;
1135 }
1136
1137 /* Execute the shell for the given job. Called from JobStart
1138 *
1139 * A shell is executed, its output is altered and the Job structure added
1140 * to the job table.
1141 */
1142 static void
1143 JobExec(Job *job, char **argv)
1144 {
1145 int cpid; /* ID of new child */
1146 sigset_t mask;
1147
1148 job->flags &= ~JOB_TRACED;
1149
1150 if (DEBUG(JOB)) {
1151 int i;
1152
1153 debug_printf("Running %s %sly\n", job->node->name, "local");
1154 debug_printf("\tCommand: ");
1155 for (i = 0; argv[i] != NULL; i++) {
1156 debug_printf("%s ", argv[i]);
1157 }
1158 debug_printf("\n");
1159 }
1160
1161 /*
1162 * Some jobs produce no output and it's disconcerting to have
1163 * no feedback of their running (since they produce no output, the
1164 * banner with their name in it never appears). This is an attempt to
1165 * provide that feedback, even if nothing follows it.
1166 */
1167 if ((lastNode != job->node) && !(job->flags & JOB_SILENT)) {
1168 MESSAGE(stdout, job->node);
1169 lastNode = job->node;
1170 }
1171
1172 /* No interruptions until this job is on the `jobs' list */
1173 JobSigLock(&mask);
1174
1175 /* Pre-emptively mark job running, pid still zero though */
1176 job->job_state = JOB_ST_RUNNING;
1177
1178 cpid = vFork();
1179 if (cpid == -1)
1180 Punt("Cannot vfork: %s", strerror(errno));
1181
1182 if (cpid == 0) {
1183 /* Child */
1184 sigset_t tmask;
1185
1186 #ifdef USE_META
1187 if (useMeta) {
1188 meta_job_child(job);
1189 }
1190 #endif
1191 /*
1192 * Reset all signal handlers; this is necessary because we also
1193 * need to unblock signals before we exec(2).
1194 */
1195 JobSigReset();
1196
1197 /* Now unblock signals */
1198 sigemptyset(&tmask);
1199 JobSigUnlock(&tmask);
1200
1201 /*
1202 * Must duplicate the input stream down to the child's input and
1203 * reset it to the beginning (again). Since the stream was marked
1204 * close-on-exec, we must clear that bit in the new input.
1205 */
1206 if (dup2(fileno(job->cmdFILE), 0) == -1)
1207 execDie("dup2", "job->cmdFILE");
1208 if (fcntl(0, F_SETFD, 0) == -1)
1209 execDie("fcntl clear close-on-exec", "stdin");
1210 if (lseek(0, (off_t)0, SEEK_SET) == -1)
1211 execDie("lseek to 0", "stdin");
1212
1213 if (job->node->type & (OP_MAKE | OP_SUBMAKE)) {
1214 /*
1215 * Pass job token pipe to submakes.
1216 */
1217 if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1)
1218 execDie("clear close-on-exec", "tokenWaitJob.inPipe");
1219 if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1)
1220 execDie("clear close-on-exec", "tokenWaitJob.outPipe");
1221 }
1222
1223 /*
1224 * Set up the child's output to be routed through the pipe
1225 * we've created for it.
1226 */
1227 if (dup2(job->outPipe, 1) == -1)
1228 execDie("dup2", "job->outPipe");
1229
1230 /*
1231 * The output channels are marked close on exec. This bit was
1232 * duplicated by the dup2(on some systems), so we have to clear
1233 * it before routing the shell's error output to the same place as
1234 * its standard output.
1235 */
1236 if (fcntl(1, F_SETFD, 0) == -1)
1237 execDie("clear close-on-exec", "stdout");
1238 if (dup2(1, 2) == -1)
1239 execDie("dup2", "1, 2");
1240
1241 /*
1242 * We want to switch the child into a different process family so
1243 * we can kill it and all its descendants in one fell swoop,
1244 * by killing its process family, but not commit suicide.
1245 */
1246 #if defined(MAKE_NATIVE) || defined(HAVE_SETPGID)
1247 #if defined(SYSV)
1248 /* XXX: dsl - I'm sure this should be setpgrp()... */
1249 (void)setsid();
1250 #else
1251 (void)setpgid(0, getpid());
1252 #endif
1253 #endif
1254
1255 Var_ExportVars();
1256
1257 (void)execv(shellPath, argv);
1258 execDie("exec", shellPath);
1259 }
1260
1261 /* Parent, continuing after the child exec */
1262 job->pid = cpid;
1263
1264 Trace_Log(JOBSTART, job);
1265
1266 #ifdef USE_META
1267 if (useMeta) {
1268 meta_job_parent(job, cpid);
1269 }
1270 #endif
1271
1272 /*
1273 * Set the current position in the buffer to the beginning
1274 * and mark another stream to watch in the outputs mask
1275 */
1276 job->curPos = 0;
1277
1278 watchfd(job);
1279
1280 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1281 (void)fclose(job->cmdFILE);
1282 job->cmdFILE = NULL;
1283 }
1284
1285 /*
1286 * Now the job is actually running, add it to the table.
1287 */
1288 if (DEBUG(JOB)) {
1289 debug_printf("JobExec(%s): pid %d added to jobs table\n",
1290 job->node->name, job->pid);
1291 job_table_dump("job started");
1292 }
1293 JobSigUnlock(&mask);
1294 }
1295
1296 /* Create the argv needed to execute the shell for a given job. */
1297 static void
1298 JobMakeArgv(Job *job, char **argv)
1299 {
1300 int argc;
1301 static char args[10]; /* For merged arguments */
1302
1303 argv[0] = UNCONST(shellName);
1304 argc = 1;
1305
1306 if ((commandShell->exit && commandShell->exit[0] != '-') ||
1307 (commandShell->echo && commandShell->echo[0] != '-'))
1308 {
1309 /*
1310 * At least one of the flags doesn't have a minus before it, so
1311 * merge them together. Have to do this because the *(&(@*#*&#$#
1312 * Bourne shell thinks its second argument is a file to source.
1313 * Grrrr. Note the ten-character limitation on the combined arguments.
1314 */
1315 (void)snprintf(args, sizeof(args), "-%s%s",
1316 ((job->flags & JOB_IGNERR) ? "" :
1317 (commandShell->exit ? commandShell->exit : "")),
1318 ((job->flags & JOB_SILENT) ? "" :
1319 (commandShell->echo ? commandShell->echo : "")));
1320
1321 if (args[1]) {
1322 argv[argc] = args;
1323 argc++;
1324 }
1325 } else {
1326 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1327 argv[argc] = UNCONST(commandShell->exit);
1328 argc++;
1329 }
1330 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1331 argv[argc] = UNCONST(commandShell->echo);
1332 argc++;
1333 }
1334 }
1335 argv[argc] = NULL;
1336 }
1337
1338 /*-
1339 *-----------------------------------------------------------------------
1340 * JobStart --
1341 * Start a target-creation process going for the target described
1342 * by the graph node gn.
1343 *
1344 * Input:
1345 * gn target to create
1346 * flags flags for the job to override normal ones.
1347 * e.g. JOB_SPECIAL or JOB_IGNDOTS
1348 * previous The previous Job structure for this node, if any.
1349 *
1350 * Results:
1351 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1352 * if there isn't actually anything left to do for the job and
1353 * JOB_RUNNING if the job has been started.
1354 *
1355 * Side Effects:
1356 * A new Job node is created and added to the list of running
1357 * jobs. PMake is forked and a child shell created.
1358 *
1359 * NB: I'm fairly sure that this code is never called with JOB_SPECIAL set
1360 * JOB_IGNDOTS is never set (dsl)
1361 * Also the return value is ignored by everyone.
1362 *-----------------------------------------------------------------------
1363 */
1364 static int
1365 JobStart(GNode *gn, int flags)
1366 {
1367 Job *job; /* new job descriptor */
1368 char *argv[10]; /* Argument vector to shell */
1369 Boolean cmdsOK; /* true if the nodes commands were all right */
1370 Boolean noExec; /* Set true if we decide not to run the job */
1371 int tfd; /* File descriptor to the temp file */
1372
1373 for (job = job_table; job < job_table_end; job++) {
1374 if (job->job_state == JOB_ST_FREE)
1375 break;
1376 }
1377 if (job >= job_table_end)
1378 Punt("JobStart no job slots vacant");
1379
1380 memset(job, 0, sizeof *job);
1381 job->job_state = JOB_ST_SETUP;
1382 if (gn->type & OP_SPECIAL)
1383 flags |= JOB_SPECIAL;
1384
1385 job->node = gn;
1386 job->tailCmds = NULL;
1387
1388 /*
1389 * Set the initial value of the flags for this job based on the global
1390 * ones and the node's attributes... Any flags supplied by the caller
1391 * are also added to the field.
1392 */
1393 job->flags = 0;
1394 if (Targ_Ignore(gn)) {
1395 job->flags |= JOB_IGNERR;
1396 }
1397 if (Targ_Silent(gn)) {
1398 job->flags |= JOB_SILENT;
1399 }
1400 job->flags |= flags;
1401
1402 /*
1403 * Check the commands now so any attributes from .DEFAULT have a chance
1404 * to migrate to the node
1405 */
1406 cmdsOK = Job_CheckCommands(gn, Error);
1407
1408 job->inPollfd = NULL;
1409 /*
1410 * If the -n flag wasn't given, we open up OUR (not the child's)
1411 * temporary file to stuff commands in it. The thing is rd/wr so we don't
1412 * need to reopen it to feed it to the shell. If the -n flag *was* given,
1413 * we just set the file to be stdout. Cute, huh?
1414 */
1415 if (((gn->type & OP_MAKE) && !(noRecursiveExecute)) ||
1416 (!noExecute && !touchFlag)) {
1417 /*
1418 * tfile is the name of a file into which all shell commands are
1419 * put. It is removed before the child shell is executed, unless
1420 * DEBUG(SCRIPT) is set.
1421 */
1422 char *tfile;
1423 sigset_t mask;
1424 /*
1425 * We're serious here, but if the commands were bogus, we're
1426 * also dead...
1427 */
1428 if (!cmdsOK) {
1429 PrintOnError(gn, NULL); /* provide some clue */
1430 DieHorribly();
1431 }
1432
1433 JobSigLock(&mask);
1434 tfd = mkTempFile(TMPPAT, &tfile);
1435 if (!DEBUG(SCRIPT))
1436 (void)eunlink(tfile);
1437 JobSigUnlock(&mask);
1438
1439 job->cmdFILE = fdopen(tfd, "w+");
1440 if (job->cmdFILE == NULL) {
1441 Punt("Could not fdopen %s", tfile);
1442 }
1443 (void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
1444 /*
1445 * Send the commands to the command file, flush all its buffers then
1446 * rewind and remove the thing.
1447 */
1448 noExec = FALSE;
1449
1450 #ifdef USE_META
1451 if (useMeta) {
1452 meta_job_start(job, gn);
1453 if (Targ_Silent(gn)) { /* might have changed */
1454 job->flags |= JOB_SILENT;
1455 }
1456 }
1457 #endif
1458 /*
1459 * We can do all the commands at once. hooray for sanity
1460 */
1461 numCommands = 0;
1462 Lst_ForEachUntil(gn->commands, JobPrintCommand, job);
1463
1464 /*
1465 * If we didn't print out any commands to the shell script,
1466 * there's not much point in executing the shell, is there?
1467 */
1468 if (numCommands == 0) {
1469 noExec = TRUE;
1470 }
1471
1472 free(tfile);
1473 } else if (NoExecute(gn)) {
1474 /*
1475 * Not executing anything -- just print all the commands to stdout
1476 * in one fell swoop. This will still set up job->tailCmds correctly.
1477 */
1478 if (lastNode != gn) {
1479 MESSAGE(stdout, gn);
1480 lastNode = gn;
1481 }
1482 job->cmdFILE = stdout;
1483 /*
1484 * Only print the commands if they're ok, but don't die if they're
1485 * not -- just let the user know they're bad and keep going. It
1486 * doesn't do any harm in this case and may do some good.
1487 */
1488 if (cmdsOK) {
1489 Lst_ForEachUntil(gn->commands, JobPrintCommand, job);
1490 }
1491 /*
1492 * Don't execute the shell, thank you.
1493 */
1494 noExec = TRUE;
1495 } else {
1496 /*
1497 * Just touch the target and note that no shell should be executed.
1498 * Set cmdFILE to stdout to make life easier. Check the commands, too,
1499 * but don't die if they're no good -- it does no harm to keep working
1500 * up the graph.
1501 */
1502 job->cmdFILE = stdout;
1503 Job_Touch(gn, job->flags&JOB_SILENT);
1504 noExec = TRUE;
1505 }
1506 /* Just in case it isn't already... */
1507 (void)fflush(job->cmdFILE);
1508
1509 /*
1510 * If we're not supposed to execute a shell, don't.
1511 */
1512 if (noExec) {
1513 if (!(job->flags & JOB_SPECIAL))
1514 Job_TokenReturn();
1515 /*
1516 * Unlink and close the command file if we opened one
1517 */
1518 if (job->cmdFILE != stdout) {
1519 if (job->cmdFILE != NULL) {
1520 (void)fclose(job->cmdFILE);
1521 job->cmdFILE = NULL;
1522 }
1523 }
1524
1525 /*
1526 * We only want to work our way up the graph if we aren't here because
1527 * the commands for the job were no good.
1528 */
1529 if (cmdsOK && aborting == 0) {
1530 JobSaveCommands(job);
1531 job->node->made = MADE;
1532 Make_Update(job->node);
1533 }
1534 job->job_state = JOB_ST_FREE;
1535 return cmdsOK ? JOB_FINISHED : JOB_ERROR;
1536 }
1537
1538 /*
1539 * Set up the control arguments to the shell. This is based on the flags
1540 * set earlier for this job.
1541 */
1542 JobMakeArgv(job, argv);
1543
1544 /* Create the pipe by which we'll get the shell's output. */
1545 JobCreatePipe(job, 3);
1546
1547 JobExec(job, argv);
1548 return JOB_RUNNING;
1549 }
1550
1551 static char *
1552 JobOutput(Job *job, char *cp, char *endp)
1553 {
1554 char *ecp;
1555
1556 if (commandShell->noPrint && commandShell->noPrint[0] != '\0') {
1557 while ((ecp = strstr(cp, commandShell->noPrint)) != NULL) {
1558 if (cp != ecp) {
1559 *ecp = '\0';
1560 /*
1561 * The only way there wouldn't be a newline after
1562 * this line is if it were the last in the buffer.
1563 * however, since the non-printable comes after it,
1564 * there must be a newline, so we don't print one.
1565 */
1566 (void)fprintf(stdout, "%s", cp);
1567 (void)fflush(stdout);
1568 }
1569 cp = ecp + commandShell->noPLen;
1570 if (cp != endp) {
1571 /*
1572 * Still more to print, look again after skipping
1573 * the whitespace following the non-printable
1574 * command....
1575 */
1576 cp++;
1577 while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1578 cp++;
1579 }
1580 } else {
1581 return cp;
1582 }
1583 }
1584 }
1585 return cp;
1586 }
1587
1588 /*-
1589 *-----------------------------------------------------------------------
1590 * JobDoOutput --
1591 * This function is called at different times depending on
1592 * whether the user has specified that output is to be collected
1593 * via pipes or temporary files. In the former case, we are called
1594 * whenever there is something to read on the pipe. We collect more
1595 * output from the given job and store it in the job's outBuf. If
1596 * this makes up a line, we print it tagged by the job's identifier,
1597 * as necessary.
1598 * If output has been collected in a temporary file, we open the
1599 * file and read it line by line, transferring it to our own
1600 * output channel until the file is empty. At which point we
1601 * remove the temporary file.
1602 * In both cases, however, we keep our figurative eye out for the
1603 * 'noPrint' line for the shell from which the output came. If
1604 * we recognize a line, we don't print it. If the command is not
1605 * alone on the line (the character after it is not \0 or \n), we
1606 * do print whatever follows it.
1607 *
1608 * Input:
1609 * job the job whose output needs printing
1610 * finish TRUE if this is the last time we'll be called
1611 * for this job
1612 *
1613 * Results:
1614 * None
1615 *
1616 * Side Effects:
1617 * curPos may be shifted as may the contents of outBuf.
1618 *-----------------------------------------------------------------------
1619 */
1620 STATIC void
1621 JobDoOutput(Job *job, Boolean finish)
1622 {
1623 Boolean gotNL = FALSE; /* true if got a newline */
1624 Boolean fbuf; /* true if our buffer filled up */
1625 size_t nr; /* number of bytes read */
1626 size_t i; /* auxiliary index into outBuf */
1627 size_t max; /* limit for i (end of current data) */
1628 ssize_t nRead; /* (Temporary) number of bytes read */
1629
1630 /*
1631 * Read as many bytes as will fit in the buffer.
1632 */
1633 end_loop:
1634 gotNL = FALSE;
1635 fbuf = FALSE;
1636
1637 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1638 JOB_BUFSIZE - job->curPos);
1639 if (nRead < 0) {
1640 if (errno == EAGAIN)
1641 return;
1642 if (DEBUG(JOB)) {
1643 perror("JobDoOutput(piperead)");
1644 }
1645 nr = 0;
1646 } else {
1647 nr = (size_t)nRead;
1648 }
1649
1650 /*
1651 * If we hit the end-of-file (the job is dead), we must flush its
1652 * remaining output, so pretend we read a newline if there's any
1653 * output remaining in the buffer.
1654 * Also clear the 'finish' flag so we stop looping.
1655 */
1656 if ((nr == 0) && (job->curPos != 0)) {
1657 job->outBuf[job->curPos] = '\n';
1658 nr = 1;
1659 finish = FALSE;
1660 } else if (nr == 0) {
1661 finish = FALSE;
1662 }
1663
1664 /*
1665 * Look for the last newline in the bytes we just got. If there is
1666 * one, break out of the loop with 'i' as its index and gotNL set
1667 * TRUE.
1668 */
1669 max = job->curPos + nr;
1670 for (i = job->curPos + nr - 1; i >= job->curPos && i != (size_t)-1; i--) {
1671 if (job->outBuf[i] == '\n') {
1672 gotNL = TRUE;
1673 break;
1674 } else if (job->outBuf[i] == '\0') {
1675 /*
1676 * Why?
1677 */
1678 job->outBuf[i] = ' ';
1679 }
1680 }
1681
1682 if (!gotNL) {
1683 job->curPos += nr;
1684 if (job->curPos == JOB_BUFSIZE) {
1685 /*
1686 * If we've run out of buffer space, we have no choice
1687 * but to print the stuff. sigh.
1688 */
1689 fbuf = TRUE;
1690 i = job->curPos;
1691 }
1692 }
1693 if (gotNL || fbuf) {
1694 /*
1695 * Need to send the output to the screen. Null terminate it
1696 * first, overwriting the newline character if there was one.
1697 * So long as the line isn't one we should filter (according
1698 * to the shell description), we print the line, preceded
1699 * by a target banner if this target isn't the same as the
1700 * one for which we last printed something.
1701 * The rest of the data in the buffer are then shifted down
1702 * to the start of the buffer and curPos is set accordingly.
1703 */
1704 job->outBuf[i] = '\0';
1705 if (i >= job->curPos) {
1706 char *cp;
1707
1708 cp = JobOutput(job, job->outBuf, &job->outBuf[i]);
1709
1710 /*
1711 * There's still more in that thar buffer. This time, though,
1712 * we know there's no newline at the end, so we add one of
1713 * our own free will.
1714 */
1715 if (*cp != '\0') {
1716 if (!beSilent && job->node != lastNode) {
1717 MESSAGE(stdout, job->node);
1718 lastNode = job->node;
1719 }
1720 #ifdef USE_META
1721 if (useMeta) {
1722 meta_job_output(job, cp, gotNL ? "\n" : "");
1723 }
1724 #endif
1725 (void)fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
1726 (void)fflush(stdout);
1727 }
1728 }
1729 /*
1730 * max is the last offset still in the buffer. Move any remaining
1731 * characters to the start of the buffer and update the end marker
1732 * curPos.
1733 */
1734 if (i < max) {
1735 (void)memmove(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
1736 job->curPos = max - (i + 1);
1737 } else {
1738 assert(i == max);
1739 job->curPos = 0;
1740 }
1741 }
1742 if (finish) {
1743 /*
1744 * If the finish flag is true, we must loop until we hit
1745 * end-of-file on the pipe. This is guaranteed to happen
1746 * eventually since the other end of the pipe is now closed
1747 * (we closed it explicitly and the child has exited). When
1748 * we do get an EOF, finish will be set FALSE and we'll fall
1749 * through and out.
1750 */
1751 goto end_loop;
1752 }
1753 }
1754
1755 static void
1756 JobRun(GNode *targ)
1757 {
1758 #if 0
1759 /*
1760 * Unfortunately it is too complicated to run .BEGIN, .END, and
1761 * .INTERRUPT job in the parallel job module. As of 2020-09-25,
1762 * unit-tests/deptgt-end-jobs.mk hangs in an endless loop.
1763 *
1764 * Running these jobs in compat mode also guarantees that these
1765 * jobs do not overlap with other unrelated jobs.
1766 */
1767 List *lst = Lst_New();
1768 Lst_Append(lst, targ);
1769 (void)Make_Run(lst);
1770 Lst_Destroy(lst, NULL);
1771 JobStart(targ, JOB_SPECIAL);
1772 while (jobTokensRunning) {
1773 Job_CatchOutput();
1774 }
1775 #else
1776 Compat_Make(targ, targ);
1777 if (targ->made == ERROR) {
1778 PrintOnError(targ, "\n\nStop.");
1779 exit(1);
1780 }
1781 #endif
1782 }
1783
1784 /* Handle the exit of a child. Called from Make_Make.
1785 *
1786 * The job descriptor is removed from the list of children.
1787 *
1788 * Notes:
1789 * We do waits, blocking or not, according to the wisdom of our
1790 * caller, until there are no more children to report. For each
1791 * job, call JobFinish to finish things off.
1792 */
1793 void
1794 Job_CatchChildren(void)
1795 {
1796 int pid; /* pid of dead child */
1797 int status; /* Exit/termination status */
1798
1799 /*
1800 * Don't even bother if we know there's no one around.
1801 */
1802 if (jobTokensRunning == 0)
1803 return;
1804
1805 while ((pid = waitpid((pid_t) -1, &status, WNOHANG | WUNTRACED)) > 0) {
1806 DEBUG2(JOB, "Process %d exited/stopped status %x.\n", pid, status);
1807 JobReapChild(pid, status, TRUE);
1808 }
1809 }
1810
1811 /*
1812 * It is possible that wait[pid]() was called from elsewhere,
1813 * this lets us reap jobs regardless.
1814 */
1815 void
1816 JobReapChild(pid_t pid, int status, Boolean isJobs)
1817 {
1818 Job *job; /* job descriptor for dead child */
1819
1820 /*
1821 * Don't even bother if we know there's no one around.
1822 */
1823 if (jobTokensRunning == 0)
1824 return;
1825
1826 job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
1827 if (job == NULL) {
1828 if (isJobs) {
1829 if (!lurking_children)
1830 Error("Child (%d) status %x not in table?", pid, status);
1831 }
1832 return; /* not ours */
1833 }
1834 if (WIFSTOPPED(status)) {
1835 DEBUG2(JOB, "Process %d (%s) stopped.\n", job->pid, job->node->name);
1836 if (!make_suspended) {
1837 switch (WSTOPSIG(status)) {
1838 case SIGTSTP:
1839 (void)printf("*** [%s] Suspended\n", job->node->name);
1840 break;
1841 case SIGSTOP:
1842 (void)printf("*** [%s] Stopped\n", job->node->name);
1843 break;
1844 default:
1845 (void)printf("*** [%s] Stopped -- signal %d\n",
1846 job->node->name, WSTOPSIG(status));
1847 }
1848 job->job_suspended = 1;
1849 }
1850 (void)fflush(stdout);
1851 return;
1852 }
1853
1854 job->job_state = JOB_ST_FINISHED;
1855 job->exit_status = status;
1856
1857 JobFinish(job, status);
1858 }
1859
1860 /* Catch the output from our children, if we're using pipes do so. Otherwise
1861 * just block time until we get a signal(most likely a SIGCHLD) since there's
1862 * no point in just spinning when there's nothing to do and the reaping of a
1863 * child can wait for a while. */
1864 void
1865 Job_CatchOutput(void)
1866 {
1867 int nready;
1868 Job *job;
1869 unsigned int i;
1870
1871 (void)fflush(stdout);
1872
1873 /* The first fd in the list is the job token pipe */
1874 do {
1875 nready = poll(fds + 1 - wantToken, nfds - 1 + wantToken, POLL_MSEC);
1876 } while (nready < 0 && errno == EINTR);
1877
1878 if (nready < 0)
1879 Punt("poll: %s", strerror(errno));
1880
1881 if (nready > 0 && readyfd(&childExitJob)) {
1882 char token = 0;
1883 ssize_t count;
1884 count = read(childExitJob.inPipe, &token, 1);
1885 switch (count) {
1886 case 0:
1887 Punt("unexpected eof on token pipe");
1888 case -1:
1889 Punt("token pipe read: %s", strerror(errno));
1890 case 1:
1891 if (token == DO_JOB_RESUME[0])
1892 /* Complete relay requested from our SIGCONT handler */
1893 JobRestartJobs();
1894 break;
1895 default:
1896 abort();
1897 }
1898 --nready;
1899 }
1900
1901 Job_CatchChildren();
1902 if (nready == 0)
1903 return;
1904
1905 for (i = npseudojobs * nfds_per_job(); i < nfds; i++) {
1906 if (!fds[i].revents)
1907 continue;
1908 job = jobfds[i];
1909 if (job->job_state == JOB_ST_RUNNING)
1910 JobDoOutput(job, FALSE);
1911 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
1912 /*
1913 * With meta mode, we may have activity on the job's filemon
1914 * descriptor too, which at the moment is any pollfd other than
1915 * job->inPollfd.
1916 */
1917 if (useMeta && job->inPollfd != &fds[i]) {
1918 if (meta_job_event(job) <= 0) {
1919 fds[i].events = 0; /* never mind */
1920 }
1921 }
1922 #endif
1923 if (--nready == 0)
1924 return;
1925 }
1926 }
1927
1928 /* Start the creation of a target. Basically a front-end for JobStart used by
1929 * the Make module. */
1930 void
1931 Job_Make(GNode *gn)
1932 {
1933 (void)JobStart(gn, 0);
1934 }
1935
1936 void
1937 Shell_Init(void)
1938 {
1939 if (shellPath == NULL) {
1940 /*
1941 * We are using the default shell, which may be an absolute
1942 * path if DEFSHELL_CUSTOM is defined.
1943 */
1944 shellName = commandShell->name;
1945 #ifdef DEFSHELL_CUSTOM
1946 if (*shellName == '/') {
1947 shellPath = shellName;
1948 shellName = strrchr(shellPath, '/');
1949 shellName++;
1950 } else
1951 #endif
1952 shellPath = str_concat3(_PATH_DEFSHELLDIR, "/", shellName);
1953 }
1954 Var_Set_with_flags(".SHELL", shellPath, VAR_CMD, VAR_SET_READONLY);
1955 if (commandShell->exit == NULL) {
1956 commandShell->exit = "";
1957 }
1958 if (commandShell->echo == NULL) {
1959 commandShell->echo = "";
1960 }
1961 if (commandShell->hasErrCtl && commandShell->exit[0] != '\0') {
1962 if (shellErrFlag &&
1963 strcmp(commandShell->exit, &shellErrFlag[1]) != 0) {
1964 free(shellErrFlag);
1965 shellErrFlag = NULL;
1966 }
1967 if (!shellErrFlag) {
1968 size_t n = strlen(commandShell->exit) + 2;
1969
1970 shellErrFlag = bmake_malloc(n);
1971 if (shellErrFlag) {
1972 snprintf(shellErrFlag, n, "-%s", commandShell->exit);
1973 }
1974 }
1975 } else if (shellErrFlag) {
1976 free(shellErrFlag);
1977 shellErrFlag = NULL;
1978 }
1979 }
1980
1981 /* Return the string literal that is used in the current command shell
1982 * to produce a newline character. */
1983 const char *
1984 Shell_GetNewline(void)
1985 {
1986 return commandShell->newline;
1987 }
1988
1989 void
1990 Job_SetPrefix(void)
1991 {
1992 if (targPrefix) {
1993 free(targPrefix);
1994 } else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
1995 Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL);
1996 }
1997
1998 (void)Var_Subst("${" MAKE_JOB_PREFIX "}",
1999 VAR_GLOBAL, VARE_WANTRES, &targPrefix);
2000 /* TODO: handle errors */
2001 }
2002
2003 /* Initialize the process module. */
2004 void
2005 Job_Init(void)
2006 {
2007 Job_SetPrefix();
2008 /* Allocate space for all the job info */
2009 job_table = bmake_malloc((size_t)maxJobs * sizeof *job_table);
2010 memset(job_table, 0, (size_t)maxJobs * sizeof *job_table);
2011 job_table_end = job_table + maxJobs;
2012 wantToken = 0;
2013
2014 aborting = 0;
2015 errors = 0;
2016
2017 lastNode = NULL;
2018
2019 /*
2020 * There is a non-zero chance that we already have children.
2021 * eg after 'make -f- <<EOF'
2022 * Since their termination causes a 'Child (pid) not in table' message,
2023 * Collect the status of any that are already dead, and suppress the
2024 * error message if there are any undead ones.
2025 */
2026 for (;;) {
2027 int rval, status;
2028 rval = waitpid((pid_t) -1, &status, WNOHANG);
2029 if (rval > 0)
2030 continue;
2031 if (rval == 0)
2032 lurking_children = 1;
2033 break;
2034 }
2035
2036 Shell_Init();
2037
2038 JobCreatePipe(&childExitJob, 3);
2039
2040 /* Preallocate enough for the maximum number of jobs. */
2041 fds = bmake_malloc(sizeof(*fds) *
2042 (npseudojobs + (size_t)maxJobs) * nfds_per_job());
2043 jobfds = bmake_malloc(sizeof(*jobfds) *
2044 (npseudojobs + (size_t)maxJobs) * nfds_per_job());
2045
2046 /* These are permanent entries and take slots 0 and 1 */
2047 watchfd(&tokenWaitJob);
2048 watchfd(&childExitJob);
2049
2050 sigemptyset(&caught_signals);
2051 /*
2052 * Install a SIGCHLD handler.
2053 */
2054 (void)bmake_signal(SIGCHLD, JobChildSig);
2055 sigaddset(&caught_signals, SIGCHLD);
2056
2057 #define ADDSIG(s,h) \
2058 if (bmake_signal(s, SIG_IGN) != SIG_IGN) { \
2059 sigaddset(&caught_signals, s); \
2060 (void)bmake_signal(s, h); \
2061 }
2062
2063 /*
2064 * Catch the four signals that POSIX specifies if they aren't ignored.
2065 * JobPassSig will take care of calling JobInterrupt if appropriate.
2066 */
2067 ADDSIG(SIGINT, JobPassSig_int)
2068 ADDSIG(SIGHUP, JobPassSig_term)
2069 ADDSIG(SIGTERM, JobPassSig_term)
2070 ADDSIG(SIGQUIT, JobPassSig_term)
2071
2072 /*
2073 * There are additional signals that need to be caught and passed if
2074 * either the export system wants to be told directly of signals or if
2075 * we're giving each job its own process group (since then it won't get
2076 * signals from the terminal driver as we own the terminal)
2077 */
2078 ADDSIG(SIGTSTP, JobPassSig_suspend)
2079 ADDSIG(SIGTTOU, JobPassSig_suspend)
2080 ADDSIG(SIGTTIN, JobPassSig_suspend)
2081 ADDSIG(SIGWINCH, JobCondPassSig)
2082 ADDSIG(SIGCONT, JobContinueSig)
2083 #undef ADDSIG
2084
2085 (void)Job_RunTarget(".BEGIN", NULL);
2086 /* Create the .END node now, even though no code in the unit tests
2087 * depends on it. See also Targ_GetEndNode in Compat_Run. */
2088 (void)Targ_GetEndNode();
2089 }
2090
2091 static void JobSigReset(void)
2092 {
2093 #define DELSIG(s) \
2094 if (sigismember(&caught_signals, s)) { \
2095 (void)bmake_signal(s, SIG_DFL); \
2096 }
2097
2098 DELSIG(SIGINT)
2099 DELSIG(SIGHUP)
2100 DELSIG(SIGQUIT)
2101 DELSIG(SIGTERM)
2102 DELSIG(SIGTSTP)
2103 DELSIG(SIGTTOU)
2104 DELSIG(SIGTTIN)
2105 DELSIG(SIGWINCH)
2106 DELSIG(SIGCONT)
2107 #undef DELSIG
2108 (void)bmake_signal(SIGCHLD, SIG_DFL);
2109 }
2110
2111 /* Find a shell in 'shells' given its name, or return NULL. */
2112 static Shell *
2113 JobMatchShell(const char *name)
2114 {
2115 Shell *sh;
2116
2117 for (sh = shells; sh->name != NULL; sh++) {
2118 if (strcmp(name, sh->name) == 0)
2119 return sh;
2120 }
2121 return NULL;
2122 }
2123
2124 /*-
2125 *-----------------------------------------------------------------------
2126 * Job_ParseShell --
2127 * Parse a shell specification and set up commandShell, shellPath
2128 * and shellName appropriately.
2129 *
2130 * Input:
2131 * line The shell spec
2132 *
2133 * Results:
2134 * FALSE if the specification was incorrect.
2135 *
2136 * Side Effects:
2137 * commandShell points to a Shell structure (either predefined or
2138 * created from the shell spec), shellPath is the full path of the
2139 * shell described by commandShell, while shellName is just the
2140 * final component of shellPath.
2141 *
2142 * Notes:
2143 * A shell specification consists of a .SHELL target, with dependency
2144 * operator, followed by a series of blank-separated words. Double
2145 * quotes can be used to use blanks in words. A backslash escapes
2146 * anything (most notably a double-quote and a space) and
2147 * provides the functionality it does in C. Each word consists of
2148 * keyword and value separated by an equal sign. There should be no
2149 * unnecessary spaces in the word. The keywords are as follows:
2150 * name Name of shell.
2151 * path Location of shell.
2152 * quiet Command to turn off echoing.
2153 * echo Command to turn echoing on
2154 * filter Result of turning off echoing that shouldn't be
2155 * printed.
2156 * echoFlag Flag to turn echoing on at the start
2157 * errFlag Flag to turn error checking on at the start
2158 * hasErrCtl True if shell has error checking control
2159 * newline String literal to represent a newline char
2160 * check Command to turn on error checking if hasErrCtl
2161 * is TRUE or template of command to echo a command
2162 * for which error checking is off if hasErrCtl is
2163 * FALSE.
2164 * ignore Command to turn off error checking if hasErrCtl
2165 * is TRUE or template of command to execute a
2166 * command so as to ignore any errors it returns if
2167 * hasErrCtl is FALSE.
2168 *
2169 *-----------------------------------------------------------------------
2170 */
2171 Boolean
2172 Job_ParseShell(char *line)
2173 {
2174 Words wordsList;
2175 char **words;
2176 char **argv;
2177 size_t argc;
2178 char *path;
2179 Shell newShell;
2180 Boolean fullSpec = FALSE;
2181 Shell *sh;
2182
2183 pp_skip_whitespace(&line);
2184
2185 free(shellArgv);
2186
2187 memset(&newShell, 0, sizeof(newShell));
2188
2189 /*
2190 * Parse the specification by keyword
2191 */
2192 wordsList = Str_Words(line, TRUE);
2193 words = wordsList.words;
2194 argc = wordsList.len;
2195 path = wordsList.freeIt;
2196 if (words == NULL) {
2197 Error("Unterminated quoted string [%s]", line);
2198 return FALSE;
2199 }
2200 shellArgv = path;
2201
2202 for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2203 char *arg = *argv;
2204 if (strncmp(arg, "path=", 5) == 0) {
2205 path = arg + 5;
2206 } else if (strncmp(arg, "name=", 5) == 0) {
2207 newShell.name = arg + 5;
2208 } else {
2209 if (strncmp(arg, "quiet=", 6) == 0) {
2210 newShell.echoOff = arg + 6;
2211 } else if (strncmp(arg, "echo=", 5) == 0) {
2212 newShell.echoOn = arg + 5;
2213 } else if (strncmp(arg, "filter=", 7) == 0) {
2214 newShell.noPrint = arg + 7;
2215 newShell.noPLen = strlen(newShell.noPrint);
2216 } else if (strncmp(arg, "echoFlag=", 9) == 0) {
2217 newShell.echo = arg + 9;
2218 } else if (strncmp(arg, "errFlag=", 8) == 0) {
2219 newShell.exit = arg + 8;
2220 } else if (strncmp(arg, "hasErrCtl=", 10) == 0) {
2221 char c = arg[10];
2222 newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2223 (c != 'T') && (c != 't'));
2224 } else if (strncmp(arg, "newline=", 8) == 0) {
2225 newShell.newline = arg + 8;
2226 } else if (strncmp(arg, "check=", 6) == 0) {
2227 newShell.errCheck = arg + 6;
2228 } else if (strncmp(arg, "ignore=", 7) == 0) {
2229 newShell.ignErr = arg + 7;
2230 } else if (strncmp(arg, "errout=", 7) == 0) {
2231 newShell.errOut = arg + 7;
2232 } else if (strncmp(arg, "comment=", 8) == 0) {
2233 newShell.commentChar = arg[8];
2234 } else {
2235 Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"", arg);
2236 free(words);
2237 return FALSE;
2238 }
2239 fullSpec = TRUE;
2240 }
2241 }
2242
2243 if (path == NULL) {
2244 /*
2245 * If no path was given, the user wants one of the pre-defined shells,
2246 * yes? So we find the one s/he wants with the help of JobMatchShell
2247 * and set things up the right way. shellPath will be set up by
2248 * Shell_Init.
2249 */
2250 if (newShell.name == NULL) {
2251 Parse_Error(PARSE_FATAL, "Neither path nor name specified");
2252 free(words);
2253 return FALSE;
2254 } else {
2255 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2256 Parse_Error(PARSE_WARNING, "%s: No matching shell",
2257 newShell.name);
2258 free(words);
2259 return FALSE;
2260 }
2261 commandShell = sh;
2262 shellName = newShell.name;
2263 if (shellPath) {
2264 /* Shell_Init has already been called! Do it again. */
2265 free(UNCONST(shellPath));
2266 shellPath = NULL;
2267 Shell_Init();
2268 }
2269 }
2270 } else {
2271 /*
2272 * The user provided a path. If s/he gave nothing else (fullSpec is
2273 * FALSE), try and find a matching shell in the ones we know of.
2274 * Else we just take the specification at its word and copy it
2275 * to a new location. In either case, we need to record the
2276 * path the user gave for the shell.
2277 */
2278 shellPath = path;
2279 path = strrchr(path, '/');
2280 if (path == NULL) {
2281 path = UNCONST(shellPath);
2282 } else {
2283 path++;
2284 }
2285 if (newShell.name != NULL) {
2286 shellName = newShell.name;
2287 } else {
2288 shellName = path;
2289 }
2290 if (!fullSpec) {
2291 if ((sh = JobMatchShell(shellName)) == NULL) {
2292 Parse_Error(PARSE_WARNING, "%s: No matching shell",
2293 shellName);
2294 free(words);
2295 return FALSE;
2296 }
2297 commandShell = sh;
2298 } else {
2299 commandShell = bmake_malloc(sizeof(Shell));
2300 *commandShell = newShell;
2301 }
2302 /* this will take care of shellErrFlag */
2303 Shell_Init();
2304 }
2305
2306 if (commandShell->echoOn && commandShell->echoOff) {
2307 commandShell->hasEchoCtl = TRUE;
2308 }
2309
2310 if (!commandShell->hasErrCtl) {
2311 if (commandShell->errCheck == NULL) {
2312 commandShell->errCheck = "";
2313 }
2314 if (commandShell->ignErr == NULL) {
2315 commandShell->ignErr = "%s\n";
2316 }
2317 }
2318
2319 /*
2320 * Do not free up the words themselves, since they might be in use by the
2321 * shell specification.
2322 */
2323 free(words);
2324 return TRUE;
2325 }
2326
2327 /* Handle the receipt of an interrupt.
2328 *
2329 * All children are killed. Another job will be started if the .INTERRUPT
2330 * target is defined.
2331 *
2332 * Input:
2333 * runINTERRUPT Non-zero if commands for the .INTERRUPT target
2334 * should be executed
2335 * signo signal received
2336 */
2337 static void
2338 JobInterrupt(int runINTERRUPT, int signo)
2339 {
2340 Job *job; /* job descriptor in that element */
2341 GNode *interrupt; /* the node describing the .INTERRUPT target */
2342 sigset_t mask;
2343 GNode *gn;
2344
2345 aborting = ABORT_INTERRUPT;
2346
2347 JobSigLock(&mask);
2348
2349 for (job = job_table; job < job_table_end; job++) {
2350 if (job->job_state != JOB_ST_RUNNING)
2351 continue;
2352
2353 gn = job->node;
2354
2355 JobDeleteTarget(gn);
2356 if (job->pid) {
2357 DEBUG2(JOB, "JobInterrupt passing signal %d to child %d.\n",
2358 signo, job->pid);
2359 KILLPG(job->pid, signo);
2360 }
2361 }
2362
2363 JobSigUnlock(&mask);
2364
2365 if (runINTERRUPT && !touchFlag) {
2366 interrupt = Targ_FindNode(".INTERRUPT");
2367 if (interrupt != NULL) {
2368 ignoreErrors = FALSE;
2369 JobRun(interrupt);
2370 }
2371 }
2372 Trace_Log(MAKEINTR, 0);
2373 exit(signo);
2374 }
2375
2376 /* Do the final processing, i.e. run the commands attached to the .END target.
2377 *
2378 * Return the number of errors reported. */
2379 int
2380 Job_Finish(void)
2381 {
2382 GNode *endNode = Targ_GetEndNode();
2383 if (!Lst_IsEmpty(endNode->commands) || !Lst_IsEmpty(endNode->children)) {
2384 if (errors) {
2385 Error("Errors reported so .END ignored");
2386 } else {
2387 JobRun(endNode);
2388 }
2389 }
2390 return errors;
2391 }
2392
2393 /* Clean up any memory used by the jobs module. */
2394 void
2395 Job_End(void)
2396 {
2397 #ifdef CLEANUP
2398 free(shellArgv);
2399 #endif
2400 }
2401
2402 /* Waits for all running jobs to finish and returns.
2403 * Sets 'aborting' to ABORT_WAIT to prevent other jobs from starting. */
2404 void
2405 Job_Wait(void)
2406 {
2407 aborting = ABORT_WAIT;
2408 while (jobTokensRunning != 0) {
2409 Job_CatchOutput();
2410 }
2411 aborting = 0;
2412 }
2413
2414 /* Abort all currently running jobs without handling output or anything.
2415 * This function is to be called only in the event of a major error.
2416 * Most definitely NOT to be called from JobInterrupt.
2417 *
2418 * All children are killed, not just the firstborn. */
2419 void
2420 Job_AbortAll(void)
2421 {
2422 Job *job; /* the job descriptor in that element */
2423 int foo;
2424
2425 aborting = ABORT_ERROR;
2426
2427 if (jobTokensRunning) {
2428 for (job = job_table; job < job_table_end; job++) {
2429 if (job->job_state != JOB_ST_RUNNING)
2430 continue;
2431 /*
2432 * kill the child process with increasingly drastic signals to make
2433 * darn sure it's dead.
2434 */
2435 KILLPG(job->pid, SIGINT);
2436 KILLPG(job->pid, SIGKILL);
2437 }
2438 }
2439
2440 /*
2441 * Catch as many children as want to report in at first, then give up
2442 */
2443 while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
2444 continue;
2445 }
2446
2447 /* Tries to restart stopped jobs if there are slots available.
2448 * Called in process context in response to a SIGCONT. */
2449 static void
2450 JobRestartJobs(void)
2451 {
2452 Job *job;
2453
2454 for (job = job_table; job < job_table_end; job++) {
2455 if (job->job_state == JOB_ST_RUNNING &&
2456 (make_suspended || job->job_suspended)) {
2457 DEBUG1(JOB, "Restarting stopped job pid %d.\n", job->pid);
2458 if (job->job_suspended) {
2459 (void)printf("*** [%s] Continued\n", job->node->name);
2460 (void)fflush(stdout);
2461 }
2462 job->job_suspended = 0;
2463 if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
2464 debug_printf("Failed to send SIGCONT to %d\n", job->pid);
2465 }
2466 }
2467 if (job->job_state == JOB_ST_FINISHED)
2468 /* Job exit deferred after calling waitpid() in a signal handler */
2469 JobFinish(job, job->exit_status);
2470 }
2471 make_suspended = 0;
2472 }
2473
2474 static void
2475 watchfd(Job *job)
2476 {
2477 if (job->inPollfd != NULL)
2478 Punt("Watching watched job");
2479
2480 fds[nfds].fd = job->inPipe;
2481 fds[nfds].events = POLLIN;
2482 jobfds[nfds] = job;
2483 job->inPollfd = &fds[nfds];
2484 nfds++;
2485 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2486 if (useMeta) {
2487 fds[nfds].fd = meta_job_fd(job);
2488 fds[nfds].events = fds[nfds].fd == -1 ? 0 : POLLIN;
2489 jobfds[nfds] = job;
2490 nfds++;
2491 }
2492 #endif
2493 }
2494
2495 static void
2496 clearfd(Job *job)
2497 {
2498 size_t i;
2499 if (job->inPollfd == NULL)
2500 Punt("Unwatching unwatched job");
2501 i = (size_t)(job->inPollfd - fds);
2502 nfds--;
2503 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2504 if (useMeta) {
2505 /*
2506 * Sanity check: there should be two fds per job, so the job's
2507 * pollfd number should be even.
2508 */
2509 assert(nfds_per_job() == 2);
2510 if (i % 2)
2511 Punt("odd-numbered fd with meta");
2512 nfds--;
2513 }
2514 #endif
2515 /*
2516 * Move last job in table into hole made by dead job.
2517 */
2518 if (nfds != i) {
2519 fds[i] = fds[nfds];
2520 jobfds[i] = jobfds[nfds];
2521 jobfds[i]->inPollfd = &fds[i];
2522 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2523 if (useMeta) {
2524 fds[i + 1] = fds[nfds + 1];
2525 jobfds[i + 1] = jobfds[nfds + 1];
2526 }
2527 #endif
2528 }
2529 job->inPollfd = NULL;
2530 }
2531
2532 static int
2533 readyfd(Job *job)
2534 {
2535 if (job->inPollfd == NULL)
2536 Punt("Polling unwatched job");
2537 return (job->inPollfd->revents & POLLIN) != 0;
2538 }
2539
2540 /* Put a token (back) into the job pipe.
2541 * This allows a make process to start a build job. */
2542 static void
2543 JobTokenAdd(void)
2544 {
2545 char tok = JOB_TOKENS[aborting], tok1;
2546
2547 /* If we are depositing an error token flush everything else */
2548 while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2549 continue;
2550
2551 DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
2552 getpid(), aborting, JOB_TOKENS[aborting]);
2553 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2554 continue;
2555 }
2556
2557 /* Prep the job token pipe in the root make process. */
2558 void
2559 Job_ServerStart(int max_tokens, int jp_0, int jp_1)
2560 {
2561 int i;
2562 char jobarg[64];
2563
2564 if (jp_0 >= 0 && jp_1 >= 0) {
2565 /* Pipe passed in from parent */
2566 tokenWaitJob.inPipe = jp_0;
2567 tokenWaitJob.outPipe = jp_1;
2568 (void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
2569 (void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
2570 return;
2571 }
2572
2573 JobCreatePipe(&tokenWaitJob, 15);
2574
2575 snprintf(jobarg, sizeof(jobarg), "%d,%d",
2576 tokenWaitJob.inPipe, tokenWaitJob.outPipe);
2577
2578 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
2579 Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
2580
2581 /*
2582 * Preload the job pipe with one token per job, save the one
2583 * "extra" token for the primary job.
2584 *
2585 * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
2586 * larger than the write buffer size of the pipe, we will
2587 * deadlock here.
2588 */
2589 for (i = 1; i < max_tokens; i++)
2590 JobTokenAdd();
2591 }
2592
2593 /* Return a withdrawn token to the pool. */
2594 void
2595 Job_TokenReturn(void)
2596 {
2597 jobTokensRunning--;
2598 if (jobTokensRunning < 0)
2599 Punt("token botch");
2600 if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
2601 JobTokenAdd();
2602 }
2603
2604 /* Attempt to withdraw a token from the pool.
2605 *
2606 * If pool is empty, set wantToken so that we wake up when a token is
2607 * released.
2608 *
2609 * Returns TRUE if a token was withdrawn, and FALSE if the pool is currently
2610 * empty. */
2611 Boolean
2612 Job_TokenWithdraw(void)
2613 {
2614 char tok, tok1;
2615 ssize_t count;
2616
2617 wantToken = 0;
2618 DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
2619 getpid(), aborting, jobTokensRunning);
2620
2621 if (aborting || (jobTokensRunning >= maxJobs))
2622 return FALSE;
2623
2624 count = read(tokenWaitJob.inPipe, &tok, 1);
2625 if (count == 0)
2626 Fatal("eof on job pipe!");
2627 if (count < 0 && jobTokensRunning != 0) {
2628 if (errno != EAGAIN) {
2629 Fatal("job pipe read: %s", strerror(errno));
2630 }
2631 DEBUG1(JOB, "(%d) blocked for token\n", getpid());
2632 return FALSE;
2633 }
2634
2635 if (count == 1 && tok != '+') {
2636 /* make being abvorted - remove any other job tokens */
2637 DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
2638 while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2639 continue;
2640 /* And put the stopper back */
2641 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2642 continue;
2643 if (dieQuietly(NULL, 1))
2644 exit(2);
2645 Fatal("A failure has been detected in another branch of the parallel make");
2646 }
2647
2648 if (count == 1 && jobTokensRunning == 0)
2649 /* We didn't want the token really */
2650 while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2651 continue;
2652
2653 jobTokensRunning++;
2654 DEBUG1(JOB, "(%d) withdrew token\n", getpid());
2655 return TRUE;
2656 }
2657
2658 /* Run the named target if found. If a filename is specified, then set that
2659 * to the sources.
2660 *
2661 * Exits if the target fails. */
2662 Boolean
2663 Job_RunTarget(const char *target, const char *fname) {
2664 GNode *gn = Targ_FindNode(target);
2665 if (gn == NULL)
2666 return FALSE;
2667
2668 if (fname)
2669 Var_Set(ALLSRC, fname, gn);
2670
2671 JobRun(gn);
2672 if (gn->made == ERROR) {
2673 PrintOnError(gn, "\n\nStop.");
2674 exit(1);
2675 }
2676 return TRUE;
2677 }
2678
2679 #ifdef USE_SELECT
2680 int
2681 emul_poll(struct pollfd *fd, int nfd, int timeout)
2682 {
2683 fd_set rfds, wfds;
2684 int i, maxfd, nselect, npoll;
2685 struct timeval tv, *tvp;
2686 long usecs;
2687
2688 FD_ZERO(&rfds);
2689 FD_ZERO(&wfds);
2690
2691 maxfd = -1;
2692 for (i = 0; i < nfd; i++) {
2693 fd[i].revents = 0;
2694
2695 if (fd[i].events & POLLIN)
2696 FD_SET(fd[i].fd, &rfds);
2697
2698 if (fd[i].events & POLLOUT)
2699 FD_SET(fd[i].fd, &wfds);
2700
2701 if (fd[i].fd > maxfd)
2702 maxfd = fd[i].fd;
2703 }
2704
2705 if (maxfd >= FD_SETSIZE) {
2706 Punt("Ran out of fd_set slots; "
2707 "recompile with a larger FD_SETSIZE.");
2708 }
2709
2710 if (timeout < 0) {
2711 tvp = NULL;
2712 } else {
2713 usecs = timeout * 1000;
2714 tv.tv_sec = usecs / 1000000;
2715 tv.tv_usec = usecs % 1000000;
2716 tvp = &tv;
2717 }
2718
2719 nselect = select(maxfd + 1, &rfds, &wfds, 0, tvp);
2720
2721 if (nselect <= 0)
2722 return nselect;
2723
2724 npoll = 0;
2725 for (i = 0; i < nfd; i++) {
2726 if (FD_ISSET(fd[i].fd, &rfds))
2727 fd[i].revents |= POLLIN;
2728
2729 if (FD_ISSET(fd[i].fd, &wfds))
2730 fd[i].revents |= POLLOUT;
2731
2732 if (fd[i].revents)
2733 npoll++;
2734 }
2735
2736 return npoll;
2737 }
2738 #endif /* USE_SELECT */
2739