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