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