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