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