job.c revision 1.109 1 /* $NetBSD: job.c,v 1.109 2006/03/13 20:35:09 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.109 2006/03/13 20:35:09 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.109 2006/03/13 20:35:09 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) {
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_SILENT)) {
1297 MESSAGE(stdout, job->node);
1298 lastNode = job->node;
1299 }
1300
1301 /* No interruptions until this job is on the `jobs' list */
1302 JobSigLock(&mask);
1303
1304 if ((cpid = vfork()) == -1) {
1305 Punt("Cannot vfork: %s", strerror(errno));
1306 } else if (cpid == 0) {
1307
1308 /*
1309 * Reset all signal handlers; this is necessary because we also
1310 * need to unblock signals before we exec(2).
1311 */
1312 JobSigReset();
1313
1314 /* Now unblock signals */
1315 sigemptyset(&mask);
1316 JobSigUnlock(&mask);
1317
1318 /*
1319 * Must duplicate the input stream down to the child's input and
1320 * reset it to the beginning (again). Since the stream was marked
1321 * close-on-exec, we must clear that bit in the new input.
1322 */
1323 if (dup2(FILENO(job->cmdFILE), 0) == -1) {
1324 execError("dup2", "job->cmdFILE");
1325 _exit(1);
1326 }
1327 (void)fcntl(0, F_SETFD, 0);
1328 (void)lseek(0, (off_t)0, SEEK_SET);
1329
1330 if (job->node->type & OP_MAKE) {
1331 /*
1332 * Pass job token pipe to submakes.
1333 */
1334 fcntl(job_pipe[0], F_SETFD, 0);
1335 fcntl(job_pipe[1], F_SETFD, 0);
1336 }
1337
1338 if (usePipes) {
1339 /*
1340 * Set up the child's output to be routed through the pipe
1341 * we've created for it.
1342 */
1343 if (dup2(job->outPipe, 1) == -1) {
1344 execError("dup2", "job->outPipe");
1345 _exit(1);
1346 }
1347 } else {
1348 /*
1349 * We're capturing output in a file, so we duplicate the
1350 * descriptor to the temporary file into the standard
1351 * output.
1352 */
1353 if (dup2(job->outFd, 1) == -1) {
1354 execError("dup2", "job->outFd");
1355 _exit(1);
1356 }
1357 }
1358 /*
1359 * The output channels are marked close on exec. This bit was
1360 * duplicated by the dup2(on some systems), so we have to clear
1361 * it before routing the shell's error output to the same place as
1362 * its standard output.
1363 */
1364 (void)fcntl(1, F_SETFD, 0);
1365 if (dup2(1, 2) == -1) {
1366 execError("dup2", "1, 2");
1367 _exit(1);
1368 }
1369
1370 #ifdef USE_PGRP
1371 /*
1372 * We want to switch the child into a different process family so
1373 * we can kill it and all its descendants in one fell swoop,
1374 * by killing its process family, but not commit suicide.
1375 */
1376 # if defined(SYSV)
1377 (void)setsid();
1378 # else
1379 (void)setpgid(0, getpid());
1380 # endif
1381 #endif /* USE_PGRP */
1382
1383 (void)execv(shellPath, argv);
1384 execError("exec", shellPath);
1385 _exit(1);
1386 } else {
1387 job->pid = cpid;
1388
1389 Trace_Log(JOBSTART, job);
1390
1391 if (usePipes) {
1392 /*
1393 * Set the current position in the buffer to the beginning
1394 * and mark another stream to watch in the outputs mask
1395 */
1396 job->curPos = 0;
1397
1398 watchfd(job);
1399 }
1400
1401 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1402 (void)fclose(job->cmdFILE);
1403 job->cmdFILE = NULL;
1404 }
1405 }
1406
1407 /*
1408 * Now the job is actually running, add it to the table.
1409 */
1410 if (DEBUG(JOB)) {
1411 printf("JobExec(%s): pid %d added to jobs table\n",
1412 job->node->name, job->pid);
1413 }
1414 nJobs += 1;
1415 (void)Lst_AtEnd(jobs, (ClientData)job);
1416 JobSigUnlock(&mask);
1417 }
1418
1419 /*-
1420 *-----------------------------------------------------------------------
1421 * JobMakeArgv --
1422 * Create the argv needed to execute the shell for a given job.
1423 *
1424 *
1425 * Results:
1426 *
1427 * Side Effects:
1428 *
1429 *-----------------------------------------------------------------------
1430 */
1431 static void
1432 JobMakeArgv(Job *job, char **argv)
1433 {
1434 int argc;
1435 static char args[10]; /* For merged arguments */
1436
1437 argv[0] = UNCONST(shellName);
1438 argc = 1;
1439
1440 if ((commandShell->exit && (*commandShell->exit != '-')) ||
1441 (commandShell->echo && (*commandShell->echo != '-')))
1442 {
1443 /*
1444 * At least one of the flags doesn't have a minus before it, so
1445 * merge them together. Have to do this because the *(&(@*#*&#$#
1446 * Bourne shell thinks its second argument is a file to source.
1447 * Grrrr. Note the ten-character limitation on the combined arguments.
1448 */
1449 (void)snprintf(args, sizeof(args), "-%s%s",
1450 ((job->flags & JOB_IGNERR) ? "" :
1451 (commandShell->exit ? commandShell->exit : "")),
1452 ((job->flags & JOB_SILENT) ? "" :
1453 (commandShell->echo ? commandShell->echo : "")));
1454
1455 if (args[1]) {
1456 argv[argc] = args;
1457 argc++;
1458 }
1459 } else {
1460 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1461 argv[argc] = UNCONST(commandShell->exit);
1462 argc++;
1463 }
1464 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1465 argv[argc] = UNCONST(commandShell->echo);
1466 argc++;
1467 }
1468 }
1469 argv[argc] = NULL;
1470 }
1471
1472 /*-
1473 *-----------------------------------------------------------------------
1474 * JobRestart --
1475 * Restart a job that stopped for some reason.
1476 *
1477 * Input:
1478 * job Job to restart
1479 *
1480 * Results:
1481 * 1 if max number of running jobs has been reached, 0 otherwise.
1482 *
1483 *-----------------------------------------------------------------------
1484 */
1485 static int
1486 JobRestart(Job *job)
1487 {
1488 Boolean error;
1489 int status;
1490
1491 /*
1492 * The job has stopped and needs to be restarted. Why it stopped,
1493 * we don't know...
1494 */
1495 if (DEBUG(JOB)) {
1496 (void)fprintf(stdout, "Resuming %s...", job->node->name);
1497 (void)fflush(stdout);
1498 }
1499
1500 error = (KILL(job->pid, SIGCONT) != 0);
1501
1502 if (!error) {
1503 /*
1504 * Make sure the user knows we've continued the beast and
1505 * actually put the thing in the job table.
1506 */
1507 job->flags |= JOB_CONTINUING;
1508 status = W_STOPCODE(SIGCONT);
1509 JobFinish(job, &status);
1510
1511 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1512 if (DEBUG(JOB)) {
1513 (void)fprintf(stdout, "done\n");
1514 (void)fflush(stdout);
1515 }
1516 } else {
1517 Error("couldn't resume %s: %s",
1518 job->node->name, strerror(errno));
1519 status = W_EXITCODE(1, 0);
1520 JobFinish(job, &status);
1521 }
1522 return 0;
1523 }
1524
1525 /*-
1526 *-----------------------------------------------------------------------
1527 * JobStart --
1528 * Start a target-creation process going for the target described
1529 * by the graph node gn.
1530 *
1531 * Input:
1532 * gn target to create
1533 * flags flags for the job to override normal ones.
1534 * e.g. JOB_SPECIAL or JOB_IGNDOTS
1535 * previous The previous Job structure for this node, if any.
1536 *
1537 * Results:
1538 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1539 * if there isn't actually anything left to do for the job and
1540 * JOB_RUNNING if the job has been started.
1541 *
1542 * Side Effects:
1543 * A new Job node is created and added to the list of running
1544 * jobs. PMake is forked and a child shell created.
1545 *-----------------------------------------------------------------------
1546 */
1547 static int
1548 JobStart(GNode *gn, int flags)
1549 {
1550 Job *job; /* new job descriptor */
1551 char *argv[10]; /* Argument vector to shell */
1552 Boolean cmdsOK; /* true if the nodes commands were all right */
1553 Boolean noExec; /* Set true if we decide not to run the job */
1554 int tfd; /* File descriptor to the temp file */
1555
1556 job = emalloc(sizeof(Job));
1557 if (job == NULL)
1558 Punt("JobStart out of memory");
1559 if (gn->type & OP_SPECIAL)
1560 flags |= JOB_SPECIAL;
1561
1562 job->node = gn;
1563 job->tailCmds = NILLNODE;
1564
1565 /*
1566 * Set the initial value of the flags for this job based on the global
1567 * ones and the node's attributes... Any flags supplied by the caller
1568 * are also added to the field.
1569 */
1570 job->flags = 0;
1571 if (Targ_Ignore(gn)) {
1572 job->flags |= JOB_IGNERR;
1573 }
1574 if (Targ_Silent(gn)) {
1575 job->flags |= JOB_SILENT;
1576 }
1577 job->flags |= flags;
1578
1579 /*
1580 * Check the commands now so any attributes from .DEFAULT have a chance
1581 * to migrate to the node
1582 */
1583 cmdsOK = Job_CheckCommands(gn, Error);
1584
1585 job->inPollfd = NULL;
1586 /*
1587 * If the -n flag wasn't given, we open up OUR (not the child's)
1588 * temporary file to stuff commands in it. The thing is rd/wr so we don't
1589 * need to reopen it to feed it to the shell. If the -n flag *was* given,
1590 * we just set the file to be stdout. Cute, huh?
1591 */
1592 if (((gn->type & OP_MAKE) && !(noRecursiveExecute)) ||
1593 (!noExecute && !touchFlag)) {
1594 /*
1595 * tfile is the name of a file into which all shell commands are
1596 * put. It is used over by removing it before the child shell is
1597 * executed. The XXXXXX in the string are replaced by the pid of
1598 * the make process in a 6-character field with leading zeroes.
1599 */
1600 char tfile[sizeof(TMPPAT)];
1601 sigset_t mask;
1602 /*
1603 * We're serious here, but if the commands were bogus, we're
1604 * also dead...
1605 */
1606 if (!cmdsOK) {
1607 DieHorribly();
1608 }
1609
1610 JobSigLock(&mask);
1611 (void)strcpy(tfile, TMPPAT);
1612 if ((tfd = mkstemp(tfile)) == -1)
1613 Punt("Could not create temporary file %s", strerror(errno));
1614 if (!DEBUG(SCRIPT))
1615 (void)eunlink(tfile);
1616 JobSigUnlock(&mask);
1617
1618 job->cmdFILE = fdopen(tfd, "w+");
1619 if (job->cmdFILE == NULL) {
1620 Punt("Could not fdopen %s", tfile);
1621 }
1622 (void)fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1623 /*
1624 * Send the commands to the command file, flush all its buffers then
1625 * rewind and remove the thing.
1626 */
1627 noExec = FALSE;
1628
1629 /*
1630 * We can do all the commands at once. hooray for sanity
1631 */
1632 numCommands = 0;
1633 Lst_ForEach(gn->commands, JobPrintCommand, (ClientData)job);
1634
1635 /*
1636 * If we didn't print out any commands to the shell script,
1637 * there's not much point in executing the shell, is there?
1638 */
1639 if (numCommands == 0) {
1640 noExec = TRUE;
1641 }
1642 } else if (NoExecute(gn)) {
1643 /*
1644 * Not executing anything -- just print all the commands to stdout
1645 * in one fell swoop. This will still set up job->tailCmds correctly.
1646 */
1647 if (lastNode != gn) {
1648 MESSAGE(stdout, gn);
1649 lastNode = gn;
1650 }
1651 job->cmdFILE = stdout;
1652 /*
1653 * Only print the commands if they're ok, but don't die if they're
1654 * not -- just let the user know they're bad and keep going. It
1655 * doesn't do any harm in this case and may do some good.
1656 */
1657 if (cmdsOK) {
1658 Lst_ForEach(gn->commands, JobPrintCommand, (ClientData)job);
1659 }
1660 /*
1661 * Don't execute the shell, thank you.
1662 */
1663 noExec = TRUE;
1664 } else {
1665 /*
1666 * Just touch the target and note that no shell should be executed.
1667 * Set cmdFILE to stdout to make life easier. Check the commands, too,
1668 * but don't die if they're no good -- it does no harm to keep working
1669 * up the graph.
1670 */
1671 job->cmdFILE = stdout;
1672 Job_Touch(gn, job->flags&JOB_SILENT);
1673 noExec = TRUE;
1674 }
1675
1676 /*
1677 * If we're not supposed to execute a shell, don't.
1678 */
1679 if (noExec) {
1680 /*
1681 * Unlink and close the command file if we opened one
1682 */
1683 if (job->cmdFILE != stdout) {
1684 if (job->cmdFILE != NULL) {
1685 (void)fclose(job->cmdFILE);
1686 job->cmdFILE = NULL;
1687 }
1688 } else {
1689 (void)fflush(stdout);
1690 }
1691
1692 /*
1693 * We only want to work our way up the graph if we aren't here because
1694 * the commands for the job were no good.
1695 */
1696 if (cmdsOK) {
1697 if (aborting == 0) {
1698 if (job->tailCmds != NILLNODE) {
1699 Lst_ForEachFrom(job->node->commands, job->tailCmds,
1700 JobSaveCommand,
1701 (ClientData)job->node);
1702 }
1703 if (!(job->flags & JOB_SPECIAL))
1704 Job_TokenReturn();
1705 job->node->made = MADE;
1706 Make_Update(job->node);
1707 }
1708 free(job);
1709 return(JOB_FINISHED);
1710 } else {
1711 free(job);
1712 return(JOB_ERROR);
1713 }
1714 } else {
1715 (void)fflush(job->cmdFILE);
1716 }
1717
1718 /*
1719 * Set up the control arguments to the shell. This is based on the flags
1720 * set earlier for this job.
1721 */
1722 JobMakeArgv(job, argv);
1723
1724 /*
1725 * If we're using pipes to catch output, create the pipe by which we'll
1726 * get the shell's output. If we're using files, print out that we're
1727 * starting a job and then set up its temporary-file name.
1728 */
1729 if (usePipes) {
1730 int fd[2];
1731 if (pipe(fd) == -1)
1732 Punt("Cannot create pipe: %s", strerror(errno));
1733 job->inPipe = fd[0];
1734 job->outPipe = fd[1];
1735 (void)fcntl(job->inPipe, F_SETFD, 1);
1736 (void)fcntl(job->outPipe, F_SETFD, 1);
1737 } else {
1738 (void)fprintf(stdout, "Remaking `%s'\n", gn->name);
1739 (void)fflush(stdout);
1740 (void)strcpy(job->outFile, TMPPAT);
1741 job->outFd = mkstemp(job->outFile);
1742 (void)fcntl(job->outFd, F_SETFD, 1);
1743 }
1744
1745 JobExec(job, argv);
1746 return(JOB_RUNNING);
1747 }
1748
1749 static char *
1750 JobOutput(Job *job, char *cp, char *endp, int msg)
1751 {
1752 char *ecp;
1753
1754 if (commandShell->noPrint) {
1755 ecp = Str_FindSubstring(cp, commandShell->noPrint);
1756 while (ecp != NULL) {
1757 if (cp != ecp) {
1758 *ecp = '\0';
1759 if (!beSilent && msg && job->node != lastNode) {
1760 MESSAGE(stdout, job->node);
1761 lastNode = job->node;
1762 }
1763 /*
1764 * The only way there wouldn't be a newline after
1765 * this line is if it were the last in the buffer.
1766 * however, since the non-printable comes after it,
1767 * there must be a newline, so we don't print one.
1768 */
1769 (void)fprintf(stdout, "%s", cp);
1770 (void)fflush(stdout);
1771 }
1772 cp = ecp + commandShell->noPLen;
1773 if (cp != endp) {
1774 /*
1775 * Still more to print, look again after skipping
1776 * the whitespace following the non-printable
1777 * command....
1778 */
1779 cp++;
1780 while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
1781 cp++;
1782 }
1783 ecp = Str_FindSubstring(cp, commandShell->noPrint);
1784 } else {
1785 return cp;
1786 }
1787 }
1788 }
1789 return cp;
1790 }
1791
1792 /*-
1793 *-----------------------------------------------------------------------
1794 * JobDoOutput --
1795 * This function is called at different times depending on
1796 * whether the user has specified that output is to be collected
1797 * via pipes or temporary files. In the former case, we are called
1798 * whenever there is something to read on the pipe. We collect more
1799 * output from the given job and store it in the job's outBuf. If
1800 * this makes up a line, we print it tagged by the job's identifier,
1801 * as necessary.
1802 * If output has been collected in a temporary file, we open the
1803 * file and read it line by line, transfering it to our own
1804 * output channel until the file is empty. At which point we
1805 * remove the temporary file.
1806 * In both cases, however, we keep our figurative eye out for the
1807 * 'noPrint' line for the shell from which the output came. If
1808 * we recognize a line, we don't print it. If the command is not
1809 * alone on the line (the character after it is not \0 or \n), we
1810 * do print whatever follows it.
1811 *
1812 * Input:
1813 * job the job whose output needs printing
1814 * finish TRUE if this is the last time we'll be called
1815 * for this job
1816 *
1817 * Results:
1818 * None
1819 *
1820 * Side Effects:
1821 * curPos may be shifted as may the contents of outBuf.
1822 *-----------------------------------------------------------------------
1823 */
1824 STATIC void
1825 JobDoOutput(Job *job, Boolean finish)
1826 {
1827 Boolean gotNL = FALSE; /* true if got a newline */
1828 Boolean fbuf; /* true if our buffer filled up */
1829 int nr; /* number of bytes read */
1830 int i; /* auxiliary index into outBuf */
1831 int max; /* limit for i (end of current data) */
1832 int nRead; /* (Temporary) number of bytes read */
1833
1834 FILE *oFILE; /* Stream pointer to shell's output file */
1835 char inLine[132];
1836
1837
1838 if (usePipes) {
1839 /*
1840 * Read as many bytes as will fit in the buffer.
1841 */
1842 end_loop:
1843 gotNL = FALSE;
1844 fbuf = FALSE;
1845
1846 nRead = read(job->inPipe, &job->outBuf[job->curPos],
1847 JOB_BUFSIZE - job->curPos);
1848 if (nRead < 0) {
1849 if (DEBUG(JOB)) {
1850 perror("JobDoOutput(piperead)");
1851 }
1852 nr = 0;
1853 } else {
1854 nr = nRead;
1855 }
1856
1857 /*
1858 * If we hit the end-of-file (the job is dead), we must flush its
1859 * remaining output, so pretend we read a newline if there's any
1860 * output remaining in the buffer.
1861 * Also clear the 'finish' flag so we stop looping.
1862 */
1863 if ((nr == 0) && (job->curPos != 0)) {
1864 job->outBuf[job->curPos] = '\n';
1865 nr = 1;
1866 finish = FALSE;
1867 } else if (nr == 0) {
1868 finish = FALSE;
1869 }
1870
1871 /*
1872 * Look for the last newline in the bytes we just got. If there is
1873 * one, break out of the loop with 'i' as its index and gotNL set
1874 * TRUE.
1875 */
1876 max = job->curPos + nr;
1877 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
1878 if (job->outBuf[i] == '\n') {
1879 gotNL = TRUE;
1880 break;
1881 } else if (job->outBuf[i] == '\0') {
1882 /*
1883 * Why?
1884 */
1885 job->outBuf[i] = ' ';
1886 }
1887 }
1888
1889 if (!gotNL) {
1890 job->curPos += nr;
1891 if (job->curPos == JOB_BUFSIZE) {
1892 /*
1893 * If we've run out of buffer space, we have no choice
1894 * but to print the stuff. sigh.
1895 */
1896 fbuf = TRUE;
1897 i = job->curPos;
1898 }
1899 }
1900 if (gotNL || fbuf) {
1901 /*
1902 * Need to send the output to the screen. Null terminate it
1903 * first, overwriting the newline character if there was one.
1904 * So long as the line isn't one we should filter (according
1905 * to the shell description), we print the line, preceded
1906 * by a target banner if this target isn't the same as the
1907 * one for which we last printed something.
1908 * The rest of the data in the buffer are then shifted down
1909 * to the start of the buffer and curPos is set accordingly.
1910 */
1911 job->outBuf[i] = '\0';
1912 if (i >= job->curPos) {
1913 char *cp;
1914
1915 cp = JobOutput(job, job->outBuf, &job->outBuf[i], FALSE);
1916
1917 /*
1918 * There's still more in that thar buffer. This time, though,
1919 * we know there's no newline at the end, so we add one of
1920 * our own free will.
1921 */
1922 if (*cp != '\0') {
1923 if (!beSilent && job->node != lastNode) {
1924 MESSAGE(stdout, job->node);
1925 lastNode = job->node;
1926 }
1927 (void)fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
1928 (void)fflush(stdout);
1929 }
1930 }
1931 if (i < max - 1) {
1932 /* shift the remaining characters down */
1933 (void)memcpy(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
1934 job->curPos = max - (i + 1);
1935
1936 } else {
1937 /*
1938 * We have written everything out, so we just start over
1939 * from the start of the buffer. No copying. No nothing.
1940 */
1941 job->curPos = 0;
1942 }
1943 }
1944 if (finish) {
1945 /*
1946 * If the finish flag is true, we must loop until we hit
1947 * end-of-file on the pipe. This is guaranteed to happen
1948 * eventually since the other end of the pipe is now closed
1949 * (we closed it explicitly and the child has exited). When
1950 * we do get an EOF, finish will be set FALSE and we'll fall
1951 * through and out.
1952 */
1953 goto end_loop;
1954 }
1955 } else {
1956 /*
1957 * We've been called to retrieve the output of the job from the
1958 * temporary file where it's been squirreled away. This consists of
1959 * opening the file, reading the output line by line, being sure not
1960 * to print the noPrint line for the shell we used, then close and
1961 * remove the temporary file. Very simple.
1962 *
1963 * Change to read in blocks and do FindSubString type things as for
1964 * pipes? That would allow for "@echo -n..."
1965 */
1966 oFILE = fopen(job->outFile, "r");
1967 if (oFILE != NULL) {
1968 (void)fprintf(stdout, "Results of making %s:\n", job->node->name);
1969 (void)fflush(stdout);
1970 while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
1971 char *cp, *endp, *oendp;
1972
1973 cp = inLine;
1974 oendp = endp = inLine + strlen(inLine);
1975 if (endp[-1] == '\n') {
1976 *--endp = '\0';
1977 }
1978 cp = JobOutput(job, inLine, endp, FALSE);
1979
1980 /*
1981 * There's still more in that thar buffer. This time, though,
1982 * we know there's no newline at the end, so we add one of
1983 * our own free will.
1984 */
1985 (void)fprintf(stdout, "%s", cp);
1986 (void)fflush(stdout);
1987 if (endp != oendp) {
1988 (void)fprintf(stdout, "\n");
1989 (void)fflush(stdout);
1990 }
1991 }
1992 (void)fclose(oFILE);
1993 (void)eunlink(job->outFile);
1994 } else {
1995 Punt("Cannot open `%s'", job->outFile);
1996 }
1997 }
1998 }
1999
2000 static void
2001 JobRun(GNode *targ)
2002 {
2003 #ifdef notyet
2004 /*
2005 * Unfortunately it is too complicated to run .BEGIN, .END,
2006 * and .INTERRUPT job in the parallel job module. This has
2007 * the nice side effect that it avoids a lot of other problems.
2008 */
2009 Lst lst = Lst_Init(FALSE);
2010 Lst_AtEnd(lst, targ);
2011 (void)Make_Run(lst);
2012 Lst_Destroy(lst, NOFREE);
2013 JobStart(targ, JOB_SPECIAL);
2014 while (nJobs) {
2015 Job_CatchOutput();
2016 Job_CatchChildren(!usePipes);
2017 }
2018 #else
2019 Compat_Make(targ, targ);
2020 if (targ->made == ERROR) {
2021 PrintOnError("\n\nStop.");
2022 exit(1);
2023 }
2024 #endif
2025 }
2026
2027 /*-
2028 *-----------------------------------------------------------------------
2029 * Job_CatchChildren --
2030 * Handle the exit of a child. Called from Make_Make.
2031 *
2032 * Input:
2033 * block TRUE if should block on the wait
2034 *
2035 * Results:
2036 * none.
2037 *
2038 * Side Effects:
2039 * The job descriptor is removed from the list of children.
2040 *
2041 * Notes:
2042 * We do waits, blocking or not, according to the wisdom of our
2043 * caller, until there are no more children to report. For each
2044 * job, call JobFinish to finish things off. This will take care of
2045 * putting jobs on the stoppedJobs queue.
2046 *
2047 *-----------------------------------------------------------------------
2048 */
2049 void
2050 Job_CatchChildren(Boolean block)
2051 {
2052 int pid; /* pid of dead child */
2053 Job *job; /* job descriptor for dead child */
2054 LstNode jnode; /* list element for finding job */
2055 int status; /* Exit/termination status */
2056
2057 /*
2058 * Don't even bother if we know there's no one around.
2059 */
2060 if (nJobs == 0) {
2061 return;
2062 }
2063
2064 while ((pid = waitpid((pid_t) -1, &status,
2065 (block?0:WNOHANG)|WUNTRACED)) > 0)
2066 {
2067 if (DEBUG(JOB)) {
2068 (void)fprintf(stdout, "Process %d exited or stopped %x.\n", pid,
2069 status);
2070 (void)fflush(stdout);
2071 }
2072
2073 jnode = Lst_Find(jobs, (ClientData)&pid, JobCmpPid);
2074 if (jnode == NILLNODE) {
2075 if (WIFSTOPPED(status) && (WSTOPSIG(status) == SIGCONT)) {
2076 jnode = Lst_Find(stoppedJobs, (ClientData) &pid, JobCmpPid);
2077 if (jnode == NILLNODE) {
2078 Error("Resumed child (%d) not in table", pid);
2079 continue;
2080 }
2081 job = (Job *)Lst_Datum(jnode);
2082 (void)Lst_Remove(stoppedJobs, jnode);
2083 } else {
2084 Error("Child (%d) not in table?", pid);
2085 continue;
2086 }
2087 } else {
2088 job = (Job *)Lst_Datum(jnode);
2089 (void)Lst_Remove(jobs, jnode);
2090 nJobs -= 1;
2091 }
2092
2093 JobFinish(job, &status);
2094 }
2095 }
2096
2097 /*-
2098 *-----------------------------------------------------------------------
2099 * Job_CatchOutput --
2100 * Catch the output from our children, if we're using
2101 * pipes do so. Otherwise just block time until we get a
2102 * signal(most likely a SIGCHLD) since there's no point in
2103 * just spinning when there's nothing to do and the reaping
2104 * of a child can wait for a while.
2105 *
2106 * Results:
2107 * None
2108 *
2109 * Side Effects:
2110 * Output is read from pipes if we're piping.
2111 * -----------------------------------------------------------------------
2112 */
2113 void
2114 Job_CatchOutput(void)
2115 {
2116 int nready;
2117 LstNode ln;
2118 Job *job;
2119
2120 (void)fflush(stdout);
2121 if (usePipes) {
2122 if ((nready = poll((wantToken ? fds : (fds + 1)),
2123 (wantToken ? nfds : (nfds - 1)), POLL_MSEC)) <= 0) {
2124 return;
2125 } else {
2126 sigset_t mask;
2127
2128 if (readyfd(&childExitJob)) {
2129 char token;
2130 (void)read(childExitJob.inPipe, &token, 1);
2131 nready -= 1;
2132 if (token == DO_JOB_RESUME[0])
2133 JobRestartJobs();
2134 }
2135
2136 JobSigLock(&mask);
2137 if (Lst_Open(jobs) == FAILURE) {
2138 Punt("Cannot open job table");
2139 }
2140
2141 while (nready && (ln = Lst_Next(jobs)) != NILLNODE) {
2142 job = (Job *)Lst_Datum(ln);
2143 if (readyfd(job)) {
2144 JobDoOutput(job, FALSE);
2145 nready -= 1;
2146 }
2147 }
2148 Lst_Close(jobs);
2149 JobSigUnlock(&mask);
2150 }
2151 }
2152 }
2153
2154 /*-
2155 *-----------------------------------------------------------------------
2156 * Job_Make --
2157 * Start the creation of a target. Basically a front-end for
2158 * JobStart used by the Make module.
2159 *
2160 * Results:
2161 * None.
2162 *
2163 * Side Effects:
2164 * Another job is started.
2165 *
2166 *-----------------------------------------------------------------------
2167 */
2168 void
2169 Job_Make(GNode *gn)
2170 {
2171 (void)JobStart(gn, 0);
2172 }
2173
2174 void
2175 Shell_Init()
2176 {
2177 if (shellPath == NULL) {
2178 /*
2179 * The user didn't specify a shell to use, so we are using the
2180 * default one... Both the absolute path and the last component
2181 * must be set. The last component is taken from the 'name' field
2182 * of the default shell description pointed-to by commandShell.
2183 * All default shells are located in _PATH_DEFSHELLDIR.
2184 */
2185 shellName = commandShell->name;
2186 shellPath = str_concat(_PATH_DEFSHELLDIR, shellName, STR_ADDSLASH);
2187 }
2188 if (commandShell->exit == NULL) {
2189 commandShell->exit = "";
2190 }
2191 if (commandShell->echo == NULL) {
2192 commandShell->echo = "";
2193 }
2194 }
2195
2196 /*-
2197 *-----------------------------------------------------------------------
2198 * Job_Init --
2199 * Initialize the process module
2200 *
2201 * Input:
2202 * maxproc the greatest number of jobs which may be running
2203 * at one time
2204 * maxlocal the greatest number of jobs which may be running
2205 * at once
2206 *
2207 * Results:
2208 * none
2209 *
2210 * Side Effects:
2211 * lists and counters are initialized
2212 *-----------------------------------------------------------------------
2213 */
2214 void
2215 Job_Init(int maxproc)
2216 {
2217 GNode *begin; /* node for commands to do at the very start */
2218
2219 jobs = Lst_Init(FALSE);
2220 stoppedJobs = Lst_Init(FALSE);
2221 maxJobs = maxproc;
2222 nJobs = 0;
2223 wantToken = FALSE;
2224
2225 aborting = 0;
2226 errors = 0;
2227
2228 lastNode = NILGNODE;
2229
2230 if (maxJobs == 1) {
2231 /*
2232 * If only one job can run at a time, there's no need for a banner,
2233 * is there?
2234 */
2235 targFmt = "";
2236 } else {
2237 targFmt = TARG_FMT;
2238 }
2239
2240 Shell_Init();
2241
2242 if (pipe(exit_pipe) < 0)
2243 Fatal("error in pipe: %s", strerror(errno));
2244 fcntl(exit_pipe[0], F_SETFD, 1);
2245 fcntl(exit_pipe[1], F_SETFD, 1);
2246
2247 childExitJob.inPipe = exit_pipe[0];
2248
2249 sigemptyset(&caught_signals);
2250 /*
2251 * Install a SIGCHLD handler.
2252 */
2253 (void)signal(SIGCHLD, JobChildSig);
2254 sigaddset(&caught_signals, SIGCHLD);
2255
2256 #define ADDSIG(s,h) \
2257 if (signal(s, SIG_IGN) != SIG_IGN) { \
2258 sigaddset(&caught_signals, s); \
2259 (void)signal(s, h); \
2260 }
2261
2262 /*
2263 * Catch the four signals that POSIX specifies if they aren't ignored.
2264 * JobPassSig will take care of calling JobInterrupt if appropriate.
2265 */
2266 ADDSIG(SIGINT, JobPassSig)
2267 ADDSIG(SIGHUP, JobPassSig)
2268 ADDSIG(SIGTERM, JobPassSig)
2269 ADDSIG(SIGQUIT, JobPassSig)
2270
2271 /*
2272 * There are additional signals that need to be caught and passed if
2273 * either the export system wants to be told directly of signals or if
2274 * we're giving each job its own process group (since then it won't get
2275 * signals from the terminal driver as we own the terminal)
2276 */
2277 #if defined(USE_PGRP)
2278 ADDSIG(SIGTSTP, JobPassSig)
2279 ADDSIG(SIGTTOU, JobPassSig)
2280 ADDSIG(SIGTTIN, JobPassSig)
2281 ADDSIG(SIGWINCH, JobPassSig)
2282 ADDSIG(SIGCONT, JobContinueSig)
2283 #endif
2284 #undef ADDSIG
2285
2286 begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2287
2288 if (begin != NILGNODE) {
2289 JobRun(begin);
2290 if (begin->made == ERROR) {
2291 PrintOnError("\n\nStop.");
2292 exit(1);
2293 }
2294 }
2295 postCommands = Targ_FindNode(".END", TARG_CREATE);
2296 }
2297
2298 static void JobSigReset(void)
2299 {
2300 #define DELSIG(s) \
2301 if (sigismember(&caught_signals, s)) { \
2302 (void)signal(s, SIG_DFL); \
2303 }
2304
2305 DELSIG(SIGINT)
2306 DELSIG(SIGHUP)
2307 DELSIG(SIGQUIT)
2308 DELSIG(SIGTERM)
2309 #if defined(USE_PGRP)
2310 DELSIG(SIGTSTP)
2311 DELSIG(SIGTTOU)
2312 DELSIG(SIGTTIN)
2313 DELSIG(SIGWINCH)
2314 DELSIG(SIGCONT)
2315 #endif
2316 #undef DELSIG
2317 (void)signal(SIGCHLD, SIG_DFL);
2318 }
2319
2320 /*-
2321 *-----------------------------------------------------------------------
2322 * Job_Empty --
2323 * See if the job table is empty. Because the local concurrency may
2324 * be set to 0, it is possible for the job table to become empty,
2325 * while the list of stoppedJobs remains non-empty. In such a case,
2326 * we want to restart as many jobs as we can.
2327 *
2328 * Results:
2329 * TRUE if it is. FALSE if it ain't.
2330 *
2331 * Side Effects:
2332 * None.
2333 *
2334 * -----------------------------------------------------------------------
2335 */
2336 Boolean
2337 Job_Empty(void)
2338 {
2339 if (nJobs != 0)
2340 return FALSE;
2341
2342 if (Lst_IsEmpty(stoppedJobs) || aborting)
2343 return TRUE;
2344
2345 /*
2346 * The job table is obviously not full if it has no jobs in
2347 * it...Try and restart the stopped jobs.
2348 */
2349 JobRestartJobs();
2350 return FALSE;
2351 }
2352
2353 /*-
2354 *-----------------------------------------------------------------------
2355 * JobMatchShell --
2356 * Find a shell in 'shells' given its name.
2357 *
2358 * Results:
2359 * A pointer to the Shell structure.
2360 *
2361 * Side Effects:
2362 * None.
2363 *
2364 *-----------------------------------------------------------------------
2365 */
2366 static Shell *
2367 JobMatchShell(const char *name)
2368 {
2369 Shell *sh;
2370
2371 for (sh = shells; sh->name != NULL; sh++) {
2372 if (strcmp(name, sh->name) == 0)
2373 return (sh);
2374 }
2375 return (NULL);
2376 }
2377
2378 /*-
2379 *-----------------------------------------------------------------------
2380 * Job_ParseShell --
2381 * Parse a shell specification and set up commandShell, shellPath
2382 * and shellName appropriately.
2383 *
2384 * Input:
2385 * line The shell spec
2386 *
2387 * Results:
2388 * FAILURE if the specification was incorrect.
2389 *
2390 * Side Effects:
2391 * commandShell points to a Shell structure (either predefined or
2392 * created from the shell spec), shellPath is the full path of the
2393 * shell described by commandShell, while shellName is just the
2394 * final component of shellPath.
2395 *
2396 * Notes:
2397 * A shell specification consists of a .SHELL target, with dependency
2398 * operator, followed by a series of blank-separated words. Double
2399 * quotes can be used to use blanks in words. A backslash escapes
2400 * anything (most notably a double-quote and a space) and
2401 * provides the functionality it does in C. Each word consists of
2402 * keyword and value separated by an equal sign. There should be no
2403 * unnecessary spaces in the word. The keywords are as follows:
2404 * name Name of shell.
2405 * path Location of shell.
2406 * quiet Command to turn off echoing.
2407 * echo Command to turn echoing on
2408 * filter Result of turning off echoing that shouldn't be
2409 * printed.
2410 * echoFlag Flag to turn echoing on at the start
2411 * errFlag Flag to turn error checking on at the start
2412 * hasErrCtl True if shell has error checking control
2413 * check Command to turn on error checking if hasErrCtl
2414 * is TRUE or template of command to echo a command
2415 * for which error checking is off if hasErrCtl is
2416 * FALSE.
2417 * ignore Command to turn off error checking if hasErrCtl
2418 * is TRUE or template of command to execute a
2419 * command so as to ignore any errors it returns if
2420 * hasErrCtl is FALSE.
2421 *
2422 *-----------------------------------------------------------------------
2423 */
2424 ReturnStatus
2425 Job_ParseShell(char *line)
2426 {
2427 char **words;
2428 char **argv;
2429 int argc;
2430 char *path;
2431 Shell newShell;
2432 Boolean fullSpec = FALSE;
2433 Shell *sh;
2434
2435 while (isspace((unsigned char)*line)) {
2436 line++;
2437 }
2438
2439 if (shellArgv)
2440 free(UNCONST(shellArgv));
2441
2442 memset(&newShell, 0, sizeof(newShell));
2443
2444 /*
2445 * Parse the specification by keyword
2446 */
2447 words = brk_string(line, &argc, TRUE, &path);
2448 shellArgv = path;
2449
2450 for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2451 if (strncmp(*argv, "path=", 5) == 0) {
2452 path = &argv[0][5];
2453 } else if (strncmp(*argv, "name=", 5) == 0) {
2454 newShell.name = &argv[0][5];
2455 } else {
2456 if (strncmp(*argv, "quiet=", 6) == 0) {
2457 newShell.echoOff = &argv[0][6];
2458 } else if (strncmp(*argv, "echo=", 5) == 0) {
2459 newShell.echoOn = &argv[0][5];
2460 } else if (strncmp(*argv, "filter=", 7) == 0) {
2461 newShell.noPrint = &argv[0][7];
2462 newShell.noPLen = strlen(newShell.noPrint);
2463 } else if (strncmp(*argv, "echoFlag=", 9) == 0) {
2464 newShell.echo = &argv[0][9];
2465 } else if (strncmp(*argv, "errFlag=", 8) == 0) {
2466 newShell.exit = &argv[0][8];
2467 } else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
2468 char c = argv[0][10];
2469 newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2470 (c != 'T') && (c != 't'));
2471 } else if (strncmp(*argv, "check=", 6) == 0) {
2472 newShell.errCheck = &argv[0][6];
2473 } else if (strncmp(*argv, "ignore=", 7) == 0) {
2474 newShell.ignErr = &argv[0][7];
2475 } else if (strncmp(*argv, "errout=", 7) == 0) {
2476 newShell.errOut = &argv[0][7];
2477 } else if (strncmp(*argv, "comment=", 8) == 0) {
2478 newShell.commentChar = argv[0][8];
2479 } else {
2480 Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"",
2481 *argv);
2482 free(words);
2483 return(FAILURE);
2484 }
2485 fullSpec = TRUE;
2486 }
2487 }
2488
2489 if (path == NULL) {
2490 /*
2491 * If no path was given, the user wants one of the pre-defined shells,
2492 * yes? So we find the one s/he wants with the help of JobMatchShell
2493 * and set things up the right way. shellPath will be set up by
2494 * Job_Init.
2495 */
2496 if (newShell.name == NULL) {
2497 Parse_Error(PARSE_FATAL, "Neither path nor name specified");
2498 free(words);
2499 return(FAILURE);
2500 } else {
2501 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2502 Parse_Error(PARSE_WARNING, "%s: No matching shell",
2503 newShell.name);
2504 free(words);
2505 return(FAILURE);
2506 }
2507 commandShell = sh;
2508 shellName = newShell.name;
2509 }
2510 } else {
2511 /*
2512 * The user provided a path. If s/he gave nothing else (fullSpec is
2513 * FALSE), try and find a matching shell in the ones we know of.
2514 * Else we just take the specification at its word and copy it
2515 * to a new location. In either case, we need to record the
2516 * path the user gave for the shell.
2517 */
2518 shellPath = path;
2519 path = strrchr(path, '/');
2520 if (path == NULL) {
2521 path = UNCONST(shellPath);
2522 } else {
2523 path += 1;
2524 }
2525 if (newShell.name != NULL) {
2526 shellName = newShell.name;
2527 } else {
2528 shellName = path;
2529 }
2530 if (!fullSpec) {
2531 if ((sh = JobMatchShell(shellName)) == NULL) {
2532 Parse_Error(PARSE_WARNING, "%s: No matching shell",
2533 shellName);
2534 free(words);
2535 return(FAILURE);
2536 }
2537 commandShell = sh;
2538 } else {
2539 commandShell = emalloc(sizeof(Shell));
2540 *commandShell = newShell;
2541 }
2542 }
2543
2544 if (commandShell->echoOn && commandShell->echoOff) {
2545 commandShell->hasEchoCtl = TRUE;
2546 }
2547
2548 if (!commandShell->hasErrCtl) {
2549 if (commandShell->errCheck == NULL) {
2550 commandShell->errCheck = "";
2551 }
2552 if (commandShell->ignErr == NULL) {
2553 commandShell->ignErr = "%s\n";
2554 }
2555 }
2556
2557 /*
2558 * Do not free up the words themselves, since they might be in use by the
2559 * shell specification.
2560 */
2561 free(words);
2562 return SUCCESS;
2563 }
2564
2565 /*-
2566 *-----------------------------------------------------------------------
2567 * JobInterrupt --
2568 * Handle the receipt of an interrupt.
2569 *
2570 * Input:
2571 * runINTERRUPT Non-zero if commands for the .INTERRUPT target
2572 * should be executed
2573 * signo signal received
2574 *
2575 * Results:
2576 * None
2577 *
2578 * Side Effects:
2579 * All children are killed. Another job will be started if the
2580 * .INTERRUPT target was given.
2581 *-----------------------------------------------------------------------
2582 */
2583 static void
2584 JobInterrupt(int runINTERRUPT, int signo)
2585 {
2586 LstNode ln; /* element in job table */
2587 Job *job; /* job descriptor in that element */
2588 GNode *interrupt; /* the node describing the .INTERRUPT target */
2589 sigset_t mask;
2590
2591 aborting = ABORT_INTERRUPT;
2592
2593 JobSigLock(&mask);
2594
2595 (void)Lst_Open(jobs);
2596 while ((ln = Lst_Next(jobs)) != NILLNODE) {
2597 GNode *gn;
2598
2599 job = (Job *)Lst_Datum(ln);
2600 gn = job->node;
2601
2602 if ((gn->type & (OP_JOIN|OP_PHONY)) == 0 && !Targ_Precious(gn)) {
2603 char *file = (gn->path == NULL ? gn->name : gn->path);
2604 if (!noExecute && eunlink(file) != -1) {
2605 Error("*** %s removed", file);
2606 }
2607 }
2608 if (job->pid) {
2609 if (DEBUG(JOB)) {
2610 (void)fprintf(stdout,
2611 "JobInterrupt passing signal %d to child %d.\n",
2612 signo, job->pid);
2613 (void)fflush(stdout);
2614 }
2615 KILL(job->pid, signo);
2616 }
2617 }
2618 Lst_Close(jobs);
2619
2620 JobSigUnlock(&mask);
2621
2622 if (runINTERRUPT && !touchFlag) {
2623 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
2624 if (interrupt != NILGNODE) {
2625 ignoreErrors = FALSE;
2626 JobRun(interrupt);
2627 }
2628 }
2629 Trace_Log(MAKEINTR, 0);
2630 exit(signo);
2631 }
2632
2633 /*
2634 *-----------------------------------------------------------------------
2635 * Job_Finish --
2636 * Do final processing such as the running of the commands
2637 * attached to the .END target.
2638 *
2639 * Results:
2640 * Number of errors reported.
2641 *
2642 * Side Effects:
2643 * None.
2644 *-----------------------------------------------------------------------
2645 */
2646 int
2647 Job_Finish(void)
2648 {
2649 if (postCommands != NILGNODE && !Lst_IsEmpty(postCommands->commands)) {
2650 if (errors) {
2651 Error("Errors reported so .END ignored");
2652 } else {
2653 JobRun(postCommands);
2654 }
2655 }
2656 return(errors);
2657 }
2658
2659 /*-
2660 *-----------------------------------------------------------------------
2661 * Job_End --
2662 * Cleanup any memory used by the jobs module
2663 *
2664 * Results:
2665 * None.
2666 *
2667 * Side Effects:
2668 * Memory is freed
2669 *-----------------------------------------------------------------------
2670 */
2671 void
2672 Job_End(void)
2673 {
2674 #ifdef CLEANUP
2675 if (shellArgv)
2676 free(shellArgv);
2677 #endif
2678 }
2679
2680 /*-
2681 *-----------------------------------------------------------------------
2682 * Job_Wait --
2683 * Waits for all running jobs to finish and returns. Sets 'aborting'
2684 * to ABORT_WAIT to prevent other jobs from starting.
2685 *
2686 * Results:
2687 * None.
2688 *
2689 * Side Effects:
2690 * Currently running jobs finish.
2691 *
2692 *-----------------------------------------------------------------------
2693 */
2694 void
2695 Job_Wait(void)
2696 {
2697 aborting = ABORT_WAIT;
2698 while (nJobs != 0) {
2699 Job_CatchOutput();
2700 Job_CatchChildren(!usePipes);
2701 }
2702 aborting = 0;
2703 }
2704
2705 /*-
2706 *-----------------------------------------------------------------------
2707 * Job_AbortAll --
2708 * Abort all currently running jobs without handling output or anything.
2709 * This function is to be called only in the event of a major
2710 * error. Most definitely NOT to be called from JobInterrupt.
2711 *
2712 * Results:
2713 * None
2714 *
2715 * Side Effects:
2716 * All children are killed, not just the firstborn
2717 *-----------------------------------------------------------------------
2718 */
2719 void
2720 Job_AbortAll(void)
2721 {
2722 LstNode ln; /* element in job table */
2723 Job *job; /* the job descriptor in that element */
2724 int foo;
2725 sigset_t mask;
2726
2727 aborting = ABORT_ERROR;
2728
2729 if (nJobs) {
2730
2731 JobSigLock(&mask);
2732 (void)Lst_Open(jobs);
2733 while ((ln = Lst_Next(jobs)) != NILLNODE) {
2734 job = (Job *)Lst_Datum(ln);
2735
2736 /*
2737 * kill the child process with increasingly drastic signals to make
2738 * darn sure it's dead.
2739 */
2740 KILL(job->pid, SIGINT);
2741 KILL(job->pid, SIGKILL);
2742 }
2743 Lst_Close(jobs);
2744 JobSigUnlock(&mask);
2745 }
2746
2747 /*
2748 * Catch as many children as want to report in at first, then give up
2749 */
2750 while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
2751 continue;
2752 }
2753
2754
2755 /*-
2757 *-----------------------------------------------------------------------
2758 * JobRestartJobs --
2759 * Tries to restart stopped jobs if there are slots available.
2760 * Note that this tries to restart them regardless of pending errors.
2761 * It's not good to leave stopped jobs lying around!
2762 *
2763 * Results:
2764 * None.
2765 *
2766 * Side Effects:
2767 * Resumes(and possibly migrates) jobs.
2768 *
2769 *-----------------------------------------------------------------------
2770 */
2771 static void
2772 JobRestartJobs(void)
2773 {
2774 sigset_t mask;
2775
2776 JobSigLock(&mask);
2777 while (!Lst_IsEmpty(stoppedJobs)) {
2778 if (DEBUG(JOB)) {
2779 (void)fprintf(stdout, "Restarting a stopped job.\n");
2780 (void)fflush(stdout);
2781 }
2782 if (JobRestart((Job *)Lst_DeQueue(stoppedJobs)) != 0)
2783 break;
2784 }
2785 JobSigUnlock(&mask);
2786 }
2787
2788 static void
2789 watchfd(Job *job)
2790 {
2791 int i;
2792 if (job->inPollfd != NULL)
2793 Punt("Watching watched job");
2794 if (fds == NULL) {
2795 maxfds = JBSTART;
2796 fds = emalloc(sizeof(struct pollfd) * maxfds);
2797 jobfds = emalloc(sizeof(Job **) * maxfds);
2798
2799 fds[0].fd = job_pipe[0];
2800 fds[0].events = POLLIN;
2801 jobfds[0] = &tokenWaitJob;
2802 tokenWaitJob.inPollfd = &fds[0];
2803 nfds++;
2804
2805 fds[1].fd = exit_pipe[0];
2806 fds[1].events = POLLIN;
2807 jobfds[1] = &childExitJob;
2808 childExitJob.inPollfd = &fds[1];
2809 nfds++;
2810 } else if (nfds == maxfds) {
2811 maxfds *= JBFACTOR;
2812 fds = erealloc(fds, sizeof(struct pollfd) * maxfds);
2813 jobfds = erealloc(jobfds, sizeof(Job **) * maxfds);
2814 for (i = 0; i < nfds; i++)
2815 jobfds[i]->inPollfd = &fds[i];
2816 }
2817
2818 fds[nfds].fd = job->inPipe;
2819 fds[nfds].events = POLLIN;
2820 jobfds[nfds] = job;
2821 job->inPollfd = &fds[nfds];
2822 nfds++;
2823 }
2824
2825 static void
2826 clearfd(Job *job)
2827 {
2828 int i;
2829 if (job->inPollfd == NULL)
2830 Punt("Unwatching unwatched job");
2831 i = job->inPollfd - fds;
2832 nfds--;
2833 /*
2834 * Move last job in table into hole made by dead job.
2835 */
2836 if (nfds != i) {
2837 fds[i] = fds[nfds];
2838 jobfds[i] = jobfds[nfds];
2839 jobfds[i]->inPollfd = &fds[i];
2840 }
2841 job->inPollfd = NULL;
2842 }
2843
2844 static int
2845 readyfd(Job *job)
2846 {
2847 if (job->inPollfd == NULL)
2848 Punt("Polling unwatched job");
2849 return (job->inPollfd->revents & POLLIN) != 0;
2850 }
2851
2852 /*-
2853 *-----------------------------------------------------------------------
2854 * JobTokenAdd --
2855 * Put a token into the job pipe so that some make process can start
2856 * another job.
2857 *
2858 * Side Effects:
2859 * Allows more build jobs to be spawned somewhere.
2860 *
2861 *-----------------------------------------------------------------------
2862 */
2863
2864 static void
2865 JobTokenAdd(void)
2866 {
2867 char tok = JOB_TOKENS[aborting], tok1;
2868
2869 /* If we are depositing an error token flush everything else */
2870 while (tok != '+' && read(job_pipe[0], &tok1, 1) == 1)
2871 continue;
2872
2873 if (DEBUG(JOB))
2874 printf("(%d) aborting %d, deposit token %c\n",
2875 getpid(), aborting, JOB_TOKENS[aborting]);
2876 write(job_pipe[1], &tok, 1);
2877 }
2878
2879 /*-
2880 *-----------------------------------------------------------------------
2881 * Job_ServerStartTokenAdd --
2882 * Prep the job token pipe in the root make process.
2883 *
2884 *-----------------------------------------------------------------------
2885 */
2886
2887 void
2888 Job_ServerStart(int maxproc)
2889 {
2890 int i, fd, flags;
2891 char jobarg[64];
2892
2893 if (pipe(job_pipe) < 0)
2894 Fatal("error in pipe: %s", strerror(errno));
2895
2896 for (i = 0; i < 2; i++) {
2897 /* Avoid using low numbered fds */
2898 fd = fcntl(job_pipe[i], F_DUPFD, 15);
2899 if (fd != -1) {
2900 close(job_pipe[i]);
2901 job_pipe[i] = fd;
2902 }
2903 }
2904
2905 /*
2906 * We mark the input side of the pipe non-blocking; we poll(2) the
2907 * pipe when we're waiting for a job token, but we might lose the
2908 * race for the token when a new one becomes available, so the read
2909 * from the pipe should not block.
2910 */
2911 flags = fcntl(job_pipe[0], F_GETFL, 0);
2912 flags |= O_NONBLOCK;
2913 fcntl(job_pipe[0], F_SETFL, flags);
2914
2915 /*
2916 * Mark job pipes as close-on-exec.
2917 * Note that we will clear this when executing submakes.
2918 */
2919 fcntl(job_pipe[0], F_SETFD, 1);
2920 fcntl(job_pipe[1], F_SETFD, 1);
2921
2922 snprintf(jobarg, sizeof(jobarg), "%d,%d", job_pipe[0], job_pipe[1]);
2923
2924 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
2925 Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
2926
2927 /*
2928 * Preload job_pipe with one token per job, save the one
2929 * "extra" token for the primary job.
2930 *
2931 * XXX should clip maxJobs against PIPE_BUF -- if maxJobs is
2932 * larger than the write buffer size of the pipe, we will
2933 * deadlock here.
2934 */
2935 for (i=1; i < maxproc; i++)
2936 JobTokenAdd();
2937 }
2938
2939 /*-
2940 *-----------------------------------------------------------------------
2941 * Job_TokenReturn --
2942 * Return a withdrawn token to the pool.
2943 *
2944 *-----------------------------------------------------------------------
2945 */
2946
2947 void
2948 Job_TokenReturn(void)
2949 {
2950 jobTokensRunning--;
2951 if (jobTokensRunning < 0)
2952 Punt("token botch");
2953 if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
2954 JobTokenAdd();
2955 }
2956
2957 /*-
2958 *-----------------------------------------------------------------------
2959 * Job_TokenWithdraw --
2960 * Attempt to withdraw a token from the pool.
2961 *
2962 * Results:
2963 * Returns TRUE if a token was withdrawn, and FALSE if the pool
2964 * is currently empty.
2965 *
2966 * Side Effects:
2967 * If pool is empty, set wantToken so that we wake up
2968 * when a token is released.
2969 *
2970 *-----------------------------------------------------------------------
2971 */
2972
2973
2974 Boolean
2975 Job_TokenWithdraw(void)
2976 {
2977 char tok, tok1;
2978 int count;
2979
2980 wantToken = FALSE;
2981 if (DEBUG(JOB))
2982 printf("Job_TokenWithdraw(%d): aborting %d, running %d\n",
2983 getpid(), aborting, jobTokensRunning);
2984
2985 if (aborting || (jobTokensRunning && not_parallel))
2986 return FALSE;
2987
2988 count = read(job_pipe[0], &tok, 1);
2989 if (count == 0)
2990 Fatal("eof on job pipe!");
2991 if (count < 0 && jobTokensRunning != 0) {
2992 if (errno != EAGAIN) {
2993 Fatal("job pipe read: %s", strerror(errno));
2994 }
2995 if (DEBUG(JOB))
2996 printf("(%d) blocked for token\n", getpid());
2997 wantToken = TRUE;
2998 return FALSE;
2999 }
3000
3001 if (count == 1 && tok != '+') {
3002 /* Remove any other job tokens */
3003 if (DEBUG(JOB))
3004 printf("(%d) aborted by token %c\n", getpid(), tok);
3005 while (read(job_pipe[0], &tok1, 1) == 1)
3006 continue;
3007 /* And put the stopper back */
3008 write(job_pipe[1], &tok, 1);
3009 Fatal("A failure has been detected in another branch of the parallel make");
3010 }
3011
3012 if (count == 1 && jobTokensRunning == 0)
3013 /* We didn't want the token really */
3014 write(job_pipe[1], &tok, 1);
3015
3016 jobTokensRunning++;
3017 if (DEBUG(JOB))
3018 printf("(%d) withdrew token\n", getpid());
3019 return TRUE;
3020 }
3021
3022 #ifdef USE_SELECT
3023 int
3024 emul_poll(struct pollfd *fd, int nfd, int timeout)
3025 {
3026 fd_set rfds, wfds;
3027 int i, maxfd, nselect, npoll;
3028 struct timeval tv, *tvp;
3029 long usecs;
3030
3031 FD_ZERO(&rfds);
3032 FD_ZERO(&wfds);
3033
3034 maxfd = -1;
3035 for (i = 0; i < nfd; i++) {
3036 fd[i].revents = 0;
3037
3038 if (fd[i].events & POLLIN)
3039 FD_SET(fd[i].fd, &rfds);
3040
3041 if (fd[i].events & POLLOUT)
3042 FD_SET(fd[i].fd, &wfds);
3043
3044 if (fd[i].fd > maxfd)
3045 maxfd = fd[i].fd;
3046 }
3047
3048 if (maxfd >= FD_SETSIZE) {
3049 Punt("Ran out of fd_set slots; "
3050 "recompile with a larger FD_SETSIZE.");
3051 }
3052
3053 if (timeout < 0) {
3054 tvp = NULL;
3055 } else {
3056 usecs = timeout * 1000;
3057 tv.tv_sec = usecs / 1000000;
3058 tv.tv_usec = usecs % 1000000;
3059 tvp = &tv;
3060 }
3061
3062 nselect = select(maxfd + 1, &rfds, &wfds, 0, tvp);
3063
3064 if (nselect <= 0)
3065 return nselect;
3066
3067 npoll = 0;
3068 for (i = 0; i < nfd; i++) {
3069 if (FD_ISSET(fd[i].fd, &rfds))
3070 fd[i].revents |= POLLIN;
3071
3072 if (FD_ISSET(fd[i].fd, &wfds))
3073 fd[i].revents |= POLLOUT;
3074
3075 if (fd[i].revents)
3076 npoll++;
3077 }
3078
3079 return npoll;
3080 }
3081 #endif /* USE_SELECT */
3082