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