job.c revision 1.85 1 /* $NetBSD: job.c,v 1.85 2004/05/07 08:12:15 sjg 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.85 2004/05/07 08:12:15 sjg 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.85 2004/05/07 08:12:15 sjg 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 RMT_WILL_WATCH
150 #ifndef USE_SELECT
151 #include <poll.h>
152 #endif
153 #endif
154 #include <signal.h>
155 #include <stdio.h>
156 #include <string.h>
157 #include <utime.h>
158
159 #include "make.h"
160 #include "hash.h"
161 #include "dir.h"
162 #include "job.h"
163 #include "pathnames.h"
164 #include "trace.h"
165 #ifdef REMOTE
166 #include "rmt.h"
167 # define STATIC
168 #else
169 # define STATIC static
170 #endif
171
172 /*
173 * error handling variables
174 */
175 static int errors = 0; /* number of errors reported */
176 static int aborting = 0; /* why is the make aborting? */
177 #define ABORT_ERROR 1 /* Because of an error */
178 #define ABORT_INTERRUPT 2 /* Because it was interrupted */
179 #define ABORT_WAIT 3 /* Waiting for jobs to finish */
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\"", "", '#',
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 (char *) 0,
254 FALSE, (char *) 0, (char *) 0, (char *) 0, 0,
255 FALSE, (char *) 0, (char *) 0, (char *) 0, 0,
256 (char *) 0, (char *) 0,
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 maxLocal; /* The most local ones we can have */
272 STATIC int nJobs; /* The number of children currently running */
273 STATIC int nLocal; /* The number of local children */
274 STATIC Lst jobs; /* The structures that describe them */
275 static Boolean wantToken; /* we want a token */
276
277 /*
278 * Set of descriptors of pipes connected to
279 * the output channels of children
280 */
281 #ifndef RMT_WILL_WATCH
282 static struct pollfd *fds = NULL;
283 static Job **jobfds = NULL;
284 static int nfds = 0;
285 static int maxfds = 0;
286 static void watchfd(Job *);
287 static void clearfd(Job *);
288 static int readyfd(Job *);
289 #define JBSTART 256
290 #define JBFACTOR 2
291 #endif
292
293 STATIC GNode *lastNode; /* The node for which output was most recently
294 * produced. */
295 STATIC const char *targFmt; /* Format string to use to head output from a
296 * job when it's not the most-recent job heard
297 * from */
298 static Job tokenWaitJob; /* token wait pseudo-job */
299 int job_pipe[2] = { -1, -1 }; /* job server pipes. */
300
301 static Job childExitJob; /* child exit pseudo-job */
302 int exit_pipe[2] = { -1, -1 }; /* child exit signal pipe. */
303
304 #ifdef REMOTE
305 # define TARG_FMT "--- %s at %s ---\n" /* Default format */
306 # define MESSAGE(fp, gn) \
307 (void) fprintf(fp, targFmt, gn->name, gn->rem.hname)
308 #else
309 # define TARG_FMT "--- %s ---\n" /* Default format */
310 # define MESSAGE(fp, gn) \
311 (void) fprintf(fp, targFmt, gn->name)
312 #endif
313
314 /*
315 * When JobStart attempts to run a job remotely but can't, and isn't allowed
316 * to run the job locally, or when Job_CatchChildren detects a job that has
317 * been migrated home, the job is placed on the stoppedJobs queue to be run
318 * when the next job finishes.
319 */
320 STATIC Lst stoppedJobs; /* Lst of Job structures describing
321 * jobs that were stopped due to concurrency
322 * limits or migration home */
323
324
325 sigset_t caught_signals; /* Set of signals we handle */
326 #if defined(USE_PGRP) && defined(SYSV)
327 # define KILL(pid, sig) kill(-(pid), (sig))
328 #else
329 # if defined(USE_PGRP)
330 # define KILL(pid, sig) killpg((pid), (sig))
331 # else
332 # define KILL(pid, sig) kill((pid), (sig))
333 # endif
334 #endif
335
336 /*
337 * Grmpf... There is no way to set bits of the wait structure
338 * anymore with the stupid W*() macros. I liked the union wait
339 * stuff much more. So, we devise our own macros... This is
340 * really ugly, use dramamine sparingly. You have been warned.
341 */
342 #ifndef W_STOPCODE
343 #define W_STOPCODE(sig) (((sig) << 8) | 0177)
344 #endif
345 #ifndef W_EXITCODE
346 #define W_EXITCODE(ret, sig) ((ret << 8) | (sig))
347 #endif
348
349 static int JobCondPassSig(ClientData, ClientData);
350 static void JobPassSig(int);
351 static void JobChildSig(int);
352 #ifdef USE_PGRP
353 static void JobContinueSig(int);
354 #endif
355 static int JobCmpPid(ClientData, ClientData);
356 static int JobPrintCommand(ClientData, ClientData);
357 static int JobSaveCommand(ClientData, ClientData);
358 static void JobClose(Job *);
359 #ifdef REMOTE
360 static int JobCmpRmtID(ClientData, ClientData);
361 # ifdef RMT_WILL_WATCH
362 static void JobLocalInput(int, Job *);
363 # endif
364 #else
365 static void JobFinish(Job *, int *);
366 static void JobExec(Job *, char **);
367 #endif
368 static void JobMakeArgv(Job *, char **);
369 static int JobRestart(Job *);
370 static int JobStart(GNode *, int, Job *);
371 static char *JobOutput(Job *, char *, char *, int);
372 static void JobDoOutput(Job *, Boolean);
373 static Shell *JobMatchShell(const char *);
374 static void JobInterrupt(int, int);
375 static void JobRestartJobs(void);
376 static void JobTokenAdd(void);
377 static void JobSigLock(sigset_t *);
378 static void JobSigUnlock(sigset_t *);
379 static void JobSigReset(void);
380
381
382
383 /*
384 * JobSigLock/JobSigUnlock
385 *
386 * Signal lock routines to get exclusive access. Currently used to
387 * protect `jobs' and `stoppedJobs' list manipulations.
388 */
389 static void JobSigLock(sigset_t *omaskp)
390 {
391 if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) {
392 Punt("JobSigLock: sigprocmask: %s", strerror(errno));
393 sigemptyset(omaskp);
394 }
395 }
396
397 static void JobSigUnlock(sigset_t *omaskp)
398 {
399 (void) sigprocmask(SIG_SETMASK, omaskp, NULL);
400 }
401
402 /*-
403 *-----------------------------------------------------------------------
404 * JobCondPassSig --
405 * Pass a signal to a job if the job is remote or if USE_PGRP
406 * is defined.
407 *
408 * Input:
409 * jobp Job to biff
410 * signop Signal to send it
411 *
412 * Results:
413 * === 0
414 *
415 * Side Effects:
416 * None, except the job may bite it.
417 *
418 *-----------------------------------------------------------------------
419 */
420 static int
421 JobCondPassSig(ClientData jobp, ClientData signop)
422 {
423 Job *job = (Job *) jobp;
424 int signo = *(int *) signop;
425 #ifdef RMT_WANTS_SIGNALS
426 if (job->flags & JOB_REMOTE) {
427 (void) Rmt_Signal(job, signo);
428 } else {
429 KILL(job->pid, signo);
430 }
431 #else
432 /*
433 * Assume that sending the signal to job->pid will signal any remote
434 * job as well.
435 */
436 if (DEBUG(JOB)) {
437 (void) fprintf(stdout,
438 "JobCondPassSig passing signal %d to child %d.\n",
439 signo, job->pid);
440 (void) fflush(stdout);
441 }
442 KILL(job->pid, signo);
443 #endif
444 return 0;
445 }
446
447 /*-
448 *-----------------------------------------------------------------------
449 * JobChldSig --
450 * SIGCHLD handler.
451 *
452 * Input:
453 * signo The signal number we've received
454 *
455 * Results:
456 * None.
457 *
458 * Side Effects:
459 * Sends a token on the child exit pipe to wake us up from
460 * select()/poll().
461 *
462 *-----------------------------------------------------------------------
463 */
464 static void
465 JobChildSig(int signo)
466 {
467 write(exit_pipe[1], ".", 1);
468 }
469
470
471 #ifdef USE_PGRP
472 /*-
473 *-----------------------------------------------------------------------
474 * JobContinueSig --
475 * Resume all stopped jobs.
476 *
477 * Input:
478 * signo The signal number we've received
479 *
480 * Results:
481 * None.
482 *
483 * Side Effects:
484 * Jobs start running again.
485 *
486 *-----------------------------------------------------------------------
487 */
488 static void
489 JobContinueSig(int signo)
490 {
491 JobRestartJobs();
492 }
493 #endif
494
495 /*-
496 *-----------------------------------------------------------------------
497 * JobPassSig --
498 * Pass a signal on to all remote jobs and to all local jobs if
499 * USE_PGRP is defined, then die ourselves.
500 *
501 * Input:
502 * signo The signal number we've received
503 *
504 * Results:
505 * None.
506 *
507 * Side Effects:
508 * We die by the same signal.
509 *
510 *-----------------------------------------------------------------------
511 */
512 static void
513 JobPassSig(int signo)
514 {
515 sigset_t nmask, omask;
516 struct sigaction act;
517 int sigcont;
518
519 if (DEBUG(JOB)) {
520 (void) fprintf(stdout, "JobPassSig(%d) called.\n", signo);
521 (void) fflush(stdout);
522 }
523 Lst_ForEach(jobs, JobCondPassSig, (ClientData) &signo);
524
525 /*
526 * Deal with proper cleanup based on the signal received. We only run
527 * the .INTERRUPT target if the signal was in fact an interrupt. The other
528 * three termination signals are more of a "get out *now*" command.
529 */
530 if (signo == SIGINT) {
531 JobInterrupt(TRUE, signo);
532 } else if ((signo == SIGHUP) || (signo == SIGTERM) || (signo == SIGQUIT)) {
533 JobInterrupt(FALSE, signo);
534 }
535
536 /*
537 * Leave gracefully if SIGQUIT, rather than core dumping.
538 */
539 if (signo == SIGQUIT) {
540 Finish(0);
541 }
542
543 if (signo == SIGTSTP) {
544 Job_CatchChildren(FALSE);
545 }
546 /*
547 * Send ourselves the signal now we've given the message to everyone else.
548 * Note we block everything else possible while we're getting the signal.
549 * This ensures that all our jobs get continued when we wake up before
550 * we take any other signal.
551 */
552 sigfillset(&nmask);
553 sigdelset(&nmask, signo);
554 (void) sigprocmask(SIG_SETMASK, &nmask, &omask);
555
556 act.sa_handler = SIG_DFL;
557 sigemptyset(&act.sa_mask);
558 act.sa_flags = 0;
559 (void) sigaction(signo, &act, NULL);
560
561 if (DEBUG(JOB)) {
562 (void) fprintf(stdout,
563 "JobPassSig passing signal %d to self.\n", signo);
564 (void) fflush(stdout);
565 }
566
567 (void) kill(getpid(), signo);
568 if (signo != SIGTSTP) {
569 sigcont = SIGCONT;
570 Lst_ForEach(jobs, JobCondPassSig, (ClientData) &sigcont);
571 }
572
573 /* Restore handler and signal mask */
574 act.sa_handler = JobPassSig;
575 (void) sigaction(signo, &act, NULL);
576 (void) sigprocmask(SIG_SETMASK, &omask, NULL);
577 }
578
579 /*-
580 *-----------------------------------------------------------------------
581 * JobCmpPid --
582 * Compare the pid of the job with the given pid and return 0 if they
583 * are equal. This function is called from Job_CatchChildren via
584 * Lst_Find to find the job descriptor of the finished job.
585 *
586 * Input:
587 * job job to examine
588 * pid process id desired
589 *
590 * Results:
591 * 0 if the pid's match
592 *
593 * Side Effects:
594 * None
595 *-----------------------------------------------------------------------
596 */
597 static int
598 JobCmpPid(ClientData job, ClientData pid)
599 {
600 return *(int *) pid - ((Job *) job)->pid;
601 }
602
603 #ifdef REMOTE
604 /*-
605 *-----------------------------------------------------------------------
606 * JobCmpRmtID --
607 * Compare the rmtID of the job with the given rmtID and return 0 if they
608 * are equal.
609 *
610 * Input:
611 * job job to examine
612 * rmtID remote id desired
613 *
614 * Results:
615 * 0 if the rmtID's match
616 *
617 * Side Effects:
618 * None.
619 *-----------------------------------------------------------------------
620 */
621 static int
622 JobCmpRmtID(ClientData job, ClientData rmtID)
623 {
624 return(*(int *) rmtID - ((Job *) job)->rmtID);
625 }
626 #endif
627
628 /*-
629 *-----------------------------------------------------------------------
630 * JobPrintCommand --
631 * Put out another command for the given job. If the command starts
632 * with an @ or a - we process it specially. In the former case,
633 * so long as the -s and -n flags weren't given to make, we stick
634 * a shell-specific echoOff command in the script. In the latter,
635 * we ignore errors for the entire job, unless the shell has error
636 * control.
637 * If the command is just "..." we take all future commands for this
638 * job to be commands to be executed once the entire graph has been
639 * made and return non-zero to signal that the end of the commands
640 * was reached. These commands are later attached to the postCommands
641 * node and executed by Job_End when all things are done.
642 * This function is called from JobStart via Lst_ForEach.
643 *
644 * Input:
645 * cmdp command string to print
646 * jobp job for which to print it
647 *
648 * Results:
649 * Always 0, unless the command was "..."
650 *
651 * Side Effects:
652 * If the command begins with a '-' and the shell has no error control,
653 * the JOB_IGNERR flag is set in the job descriptor.
654 * If the command is "..." and we're not ignoring such things,
655 * tailCmds is set to the successor node of the cmd.
656 * numCommands is incremented if the command is actually printed.
657 *-----------------------------------------------------------------------
658 */
659 static int
660 JobPrintCommand(ClientData cmdp, ClientData jobp)
661 {
662 Boolean noSpecials; /* true if we shouldn't worry about
663 * inserting special commands into
664 * the input stream. */
665 Boolean shutUp = FALSE; /* true if we put a no echo command
666 * into the command file */
667 Boolean errOff = FALSE; /* true if we turned error checking
668 * off before printing the command
669 * and need to turn it back on */
670 const char *cmdTemplate; /* Template to use when printing the
671 * command */
672 char *cmdStart; /* Start of expanded command */
673 char *escCmd = NULL; /* Command with quotes/backticks escaped */
674 char *cmd = (char *) cmdp;
675 Job *job = (Job *) jobp;
676 char *cp;
677 int i, j;
678
679 noSpecials = NoExecute(job->node);
680
681 if (strcmp(cmd, "...") == 0) {
682 job->node->type |= OP_SAVE_CMDS;
683 if ((job->flags & JOB_IGNDOTS) == 0) {
684 job->tailCmds = Lst_Succ(Lst_Member(job->node->commands,
685 (ClientData)cmd));
686 return 1;
687 }
688 return 0;
689 }
690
691 #define DBPRINTF(fmt, arg) if (DEBUG(JOB)) { \
692 (void) fprintf(stdout, fmt, arg); \
693 (void) fflush(stdout); \
694 } \
695 (void) fprintf(job->cmdFILE, fmt, arg); \
696 (void) fflush(job->cmdFILE);
697
698 numCommands += 1;
699
700 cmdStart = cmd = Var_Subst(NULL, cmd, job->node, FALSE);
701
702 cmdTemplate = "%s\n";
703
704 /*
705 * Check for leading @' and -'s to control echoing and error checking.
706 */
707 while (*cmd == '@' || *cmd == '-' || (*cmd == '+')) {
708 switch (*cmd) {
709 case '@':
710 shutUp = TRUE;
711 break;
712 case '-':
713 errOff = TRUE;
714 break;
715 case '+':
716 if (noSpecials) {
717 /*
718 * We're not actually executing anything...
719 * but this one needs to be - use compat mode just for it.
720 */
721 CompatRunCommand(cmdp, (ClientData)job->node);
722 return 0;
723 }
724 break;
725 }
726 cmd++;
727 }
728
729 while (isspace((unsigned char) *cmd))
730 cmd++;
731
732 /*
733 * If the shell doesn't have error control the alternate echo'ing will
734 * be done (to avoid showing additional error checking code)
735 * and this will need the characters '$ ` \ "' escaped
736 */
737
738 if (!commandShell->hasErrCtl) {
739 /* Worst that could happen is every char needs escaping. */
740 escCmd = (char *) emalloc((strlen(cmd) * 2) + 1);
741 for (i = 0, j= 0; cmd[i] != '\0'; i++, j++) {
742 if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' ||
743 cmd[i] == '"')
744 escCmd[j++] = '\\';
745 escCmd[j] = cmd[i];
746 }
747 escCmd[j] = 0;
748 }
749
750 if (shutUp) {
751 if (!(job->flags & JOB_SILENT) && !noSpecials &&
752 commandShell->hasEchoCtl) {
753 DBPRINTF("%s\n", commandShell->echoOff);
754 } else {
755 if (commandShell->hasErrCtl)
756 shutUp = FALSE;
757 }
758 }
759
760 if (errOff) {
761 if ( !(job->flags & JOB_IGNERR) && !noSpecials) {
762 if (commandShell->hasErrCtl) {
763 /*
764 * we don't want the error-control commands showing
765 * up either, so we turn off echoing while executing
766 * them. We could put another field in the shell
767 * structure to tell JobDoOutput to look for this
768 * string too, but why make it any more complex than
769 * it already is?
770 */
771 if (!(job->flags & JOB_SILENT) && !shutUp &&
772 commandShell->hasEchoCtl) {
773 DBPRINTF("%s\n", commandShell->echoOff);
774 DBPRINTF("%s\n", commandShell->ignErr);
775 DBPRINTF("%s\n", commandShell->echoOn);
776 } else {
777 DBPRINTF("%s\n", commandShell->ignErr);
778 }
779 } else if (commandShell->ignErr &&
780 (*commandShell->ignErr != '\0'))
781 {
782 /*
783 * The shell has no error control, so we need to be
784 * weird to get it to ignore any errors from the command.
785 * If echoing is turned on, we turn it off and use the
786 * errCheck template to echo the command. Leave echoing
787 * off so the user doesn't see the weirdness we go through
788 * to ignore errors. Set cmdTemplate to use the weirdness
789 * instead of the simple "%s\n" template.
790 */
791 if (!(job->flags & JOB_SILENT) && !shutUp) {
792 if (commandShell->hasEchoCtl) {
793 DBPRINTF("%s\n", commandShell->echoOff);
794 }
795 DBPRINTF(commandShell->errCheck, escCmd);
796 shutUp = TRUE;
797 } else {
798 if (!shutUp) {
799 DBPRINTF(commandShell->errCheck, escCmd);
800 }
801 }
802 cmdTemplate = commandShell->ignErr;
803 /*
804 * The error ignoration (hee hee) is already taken care
805 * of by the ignErr template, so pretend error checking
806 * is still on.
807 */
808 errOff = FALSE;
809 } else {
810 errOff = FALSE;
811 }
812 } else {
813 errOff = FALSE;
814 }
815 } else {
816
817 /*
818 * If errors are being checked and the shell doesn't have error control
819 * but does supply an errOut template, then setup commands to run
820 * through it.
821 */
822
823 if (!commandShell->hasErrCtl && commandShell->errOut &&
824 (*commandShell->errOut != '\0')) {
825 if (!(job->flags & JOB_SILENT) && !shutUp) {
826 if (commandShell->hasEchoCtl) {
827 DBPRINTF("%s\n", commandShell->echoOff);
828 }
829 DBPRINTF(commandShell->errCheck, escCmd);
830 shutUp = TRUE;
831 }
832 /* If it's a comment line, treat it like an ignored error */
833 if (escCmd[0] == commandShell->commentChar)
834 cmdTemplate = commandShell->ignErr;
835 else
836 cmdTemplate = commandShell->errOut;
837 errOff = FALSE;
838 }
839 }
840
841 if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 &&
842 (job->flags & JOB_TRACED) == 0) {
843 DBPRINTF("set -%s\n", "x");
844 job->flags |= JOB_TRACED;
845 }
846
847 if ((cp = Check_Cwd_Cmd(cmd)) != NULL) {
848 DBPRINTF("test -d %s && ", cp);
849 DBPRINTF("cd %s; ", cp);
850 }
851 DBPRINTF(cmdTemplate, cmd);
852 free(cmdStart);
853 if (escCmd)
854 free(escCmd);
855 if (errOff) {
856 /*
857 * If echoing is already off, there's no point in issuing the
858 * echoOff command. Otherwise we issue it and pretend it was on
859 * for the whole command...
860 */
861 if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){
862 DBPRINTF("%s\n", commandShell->echoOff);
863 shutUp = TRUE;
864 }
865 DBPRINTF("%s\n", commandShell->errCheck);
866 }
867 if (shutUp && commandShell->hasEchoCtl) {
868 DBPRINTF("%s\n", commandShell->echoOn);
869 }
870 return 0;
871 }
872
873 /*-
874 *-----------------------------------------------------------------------
875 * JobSaveCommand --
876 * Save a command to be executed when everything else is done.
877 * Callback function for JobFinish...
878 *
879 * Results:
880 * Always returns 0
881 *
882 * Side Effects:
883 * The command is tacked onto the end of postCommands's commands list.
884 *
885 *-----------------------------------------------------------------------
886 */
887 static int
888 JobSaveCommand(ClientData cmd, ClientData gn)
889 {
890 cmd = (ClientData) Var_Subst(NULL, (char *) cmd, (GNode *) gn, FALSE);
891 (void) Lst_AtEnd(postCommands->commands, cmd);
892 return(0);
893 }
894
895
896 /*-
897 *-----------------------------------------------------------------------
898 * JobClose --
899 * Called to close both input and output pipes when a job is finished.
900 *
901 * Results:
902 * Nada
903 *
904 * Side Effects:
905 * The file descriptors associated with the job are closed.
906 *
907 *-----------------------------------------------------------------------
908 */
909 static void
910 JobClose(Job *job)
911 {
912 if (usePipes && (job->flags & JOB_FIRST)) {
913 #ifdef RMT_WILL_WATCH
914 Rmt_Ignore(job->inPipe);
915 #else
916 clearfd(job);
917 #endif
918 if (job->outPipe != job->inPipe) {
919 (void) close(job->outPipe);
920 }
921 JobDoOutput(job, TRUE);
922 (void) close(job->inPipe);
923 } else {
924 (void) close(job->outFd);
925 JobDoOutput(job, TRUE);
926 }
927 }
928
929 /*-
930 *-----------------------------------------------------------------------
931 * JobFinish --
932 * Do final processing for the given job including updating
933 * parents and starting new jobs as available/necessary. Note
934 * that we pay no attention to the JOB_IGNERR flag here.
935 * This is because when we're called because of a noexecute flag
936 * or something, jstat.w_status is 0 and when called from
937 * Job_CatchChildren, the status is zeroed if it s/b ignored.
938 *
939 * Input:
940 * job job to finish
941 * status sub-why job went away
942 *
943 * Results:
944 * None
945 *
946 * Side Effects:
947 * Some nodes may be put on the toBeMade queue.
948 * Final commands for the job are placed on postCommands.
949 *
950 * If we got an error and are aborting (aborting == ABORT_ERROR) and
951 * the job list is now empty, we are done for the day.
952 * If we recognized an error (errors !=0), we set the aborting flag
953 * to ABORT_ERROR so no more jobs will be started.
954 *-----------------------------------------------------------------------
955 */
956 /*ARGSUSED*/
957 static void
958 JobFinish(Job *job, int *status)
959 {
960 Boolean done;
961
962 if ((WIFEXITED(*status) &&
963 (((WEXITSTATUS(*status) != 0) && !(job->flags & JOB_IGNERR)))) ||
964 WIFSIGNALED(*status))
965 {
966 /*
967 * If it exited non-zero and either we're doing things our
968 * way or we're not ignoring errors, the job is finished.
969 * Similarly, if the shell died because of a signal
970 * the job is also finished. In these
971 * cases, finish out the job's output before printing the exit
972 * status...
973 */
974 #ifdef REMOTE
975 KILL(job->pid, SIGCONT);
976 #endif
977 JobClose(job);
978 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
979 (void) fclose(job->cmdFILE);
980 job->cmdFILE = NULL;
981 }
982 done = TRUE;
983 #ifdef REMOTE
984 if (job->flags & JOB_REMOTE)
985 Rmt_Done(job->rmtID, job->node);
986 #endif
987 } else if (WIFEXITED(*status)) {
988 /*
989 * Deal with ignored errors in -B mode. We need to print a message
990 * telling of the ignored error as well as setting status.w_status
991 * to 0 so the next command gets run. To do this, we set done to be
992 * TRUE if in -B mode and the job exited non-zero.
993 */
994 done = WEXITSTATUS(*status) != 0;
995 /*
996 * Old comment said: "Note we don't
997 * want to close down any of the streams until we know we're at the
998 * end."
999 * But we do. Otherwise when are we going to print the rest of the
1000 * stuff?
1001 */
1002 JobClose(job);
1003 #ifdef REMOTE
1004 if (job->flags & JOB_REMOTE)
1005 Rmt_Done(job->rmtID, job->node);
1006 #endif /* REMOTE */
1007 } else {
1008 /*
1009 * No need to close things down or anything.
1010 */
1011 done = FALSE;
1012 }
1013
1014 if (done ||
1015 WIFSTOPPED(*status) ||
1016 (WIFSIGNALED(*status) && (WTERMSIG(*status) == SIGCONT)))
1017 {
1018 FILE *out;
1019
1020 if (compatMake && !usePipes && (job->flags & JOB_IGNERR)) {
1021 /*
1022 * If output is going to a file and this job is ignoring
1023 * errors, arrange to have the exit status sent to the
1024 * output file as well.
1025 */
1026 out = fdopen(job->outFd, "w");
1027 if (out == NULL)
1028 Punt("Cannot fdopen");
1029 } else {
1030 out = stdout;
1031 }
1032
1033 if (WIFEXITED(*status)) {
1034 if (DEBUG(JOB)) {
1035 (void) fprintf(stdout, "Process %d [%s] exited.\n",
1036 job->pid, job->node->name);
1037 (void) fflush(stdout);
1038 }
1039 if (WEXITSTATUS(*status) != 0) {
1040 if (usePipes && job->node != lastNode) {
1041 MESSAGE(out, job->node);
1042 lastNode = job->node;
1043 }
1044 (void) fprintf(out, "*** [%s] Error code %d%s\n",
1045 job->node->name,
1046 WEXITSTATUS(*status),
1047 (job->flags & JOB_IGNERR) ? "(ignored)" : "");
1048
1049 if (job->flags & JOB_IGNERR) {
1050 *status = 0;
1051 }
1052 } else if (DEBUG(JOB)) {
1053 if (usePipes && job->node != lastNode) {
1054 MESSAGE(out, job->node);
1055 lastNode = job->node;
1056 }
1057 (void) fprintf(out, "*** [%s] Completed successfully\n",
1058 job->node->name);
1059 }
1060 } else if (WIFSTOPPED(*status) && WSTOPSIG(*status) != SIGCONT) {
1061 if (DEBUG(JOB)) {
1062 (void) fprintf(stdout, "Process %d (%s) stopped.\n",
1063 job->pid, job->node->name);
1064 (void) fflush(stdout);
1065 }
1066 if (usePipes && job->node != lastNode) {
1067 MESSAGE(out, job->node);
1068 lastNode = job->node;
1069 }
1070 if (!(job->flags & JOB_REMIGRATE)) {
1071 switch (WSTOPSIG(*status)) {
1072 case SIGTSTP:
1073 (void) fprintf(out, "*** [%s] Suspended\n",
1074 job->node->name);
1075 break;
1076 case SIGSTOP:
1077 (void) fprintf(out, "*** [%s] Stopped\n",
1078 job->node->name);
1079 break;
1080 default:
1081 (void) fprintf(out, "*** [%s] Stopped -- signal %d\n",
1082 job->node->name, WSTOPSIG(*status));
1083 }
1084 }
1085 job->flags |= JOB_RESUME;
1086 (void)Lst_AtEnd(stoppedJobs, (ClientData)job);
1087 #ifdef REMOTE
1088 if (job->flags & JOB_REMIGRATE)
1089 JobRestart(job);
1090 #endif
1091 (void) fflush(out);
1092 return;
1093 } else if (WIFSTOPPED(*status) && WSTOPSIG(*status) == SIGCONT) {
1094 /*
1095 * If the beastie has continued, shift the Job from the stopped
1096 * list to the running one (or re-stop it if concurrency is
1097 * exceeded) and go and get another child.
1098 */
1099 if (job->flags & (JOB_RESUME|JOB_REMIGRATE|JOB_RESTART)) {
1100 if (usePipes && job->node != lastNode) {
1101 MESSAGE(out, job->node);
1102 lastNode = job->node;
1103 }
1104 (void) fprintf(out, "*** [%s] Continued\n", job->node->name);
1105 }
1106 if (!(job->flags & JOB_CONTINUING)) {
1107 if (DEBUG(JOB)) {
1108 (void) fprintf(stdout,
1109 "Warning: process %d [%s] was not continuing.\n",
1110 job->pid, job->node->name);
1111 (void) fflush(stdout);
1112 }
1113 #ifdef notdef
1114 /*
1115 * We don't really want to restart a job from scratch just
1116 * because it continued, especially not without killing the
1117 * continuing process! That's why this is ifdef'ed out.
1118 * FD - 9/17/90
1119 */
1120 JobRestart(job);
1121 #endif
1122 }
1123 job->flags &= ~JOB_CONTINUING;
1124 Lst_AtEnd(jobs, (ClientData)job);
1125 nJobs += 1;
1126 if (!(job->flags & JOB_REMOTE)) {
1127 if (DEBUG(JOB)) {
1128 (void) fprintf(stdout,
1129 "Process %d is continuing locally.\n",
1130 job->pid);
1131 (void) fflush(stdout);
1132 }
1133 nLocal += 1;
1134 }
1135 (void) fflush(out);
1136 return;
1137 } else {
1138 if (usePipes && job->node != lastNode) {
1139 MESSAGE(out, job->node);
1140 lastNode = job->node;
1141 }
1142 (void) fprintf(out, "*** [%s] Signal %d\n",
1143 job->node->name, WTERMSIG(*status));
1144 }
1145
1146 (void) fflush(out);
1147 }
1148
1149 /*
1150 * Now handle the -B-mode stuff. If the beast still isn't finished,
1151 * try and restart the job on the next command. If JobStart says it's
1152 * ok, it's ok. If there's an error, this puppy is done.
1153 */
1154 if (compatMake && (WIFEXITED(*status) &&
1155 !Lst_IsAtEnd(job->node->commands))) {
1156 switch (JobStart(job->node, job->flags & JOB_IGNDOTS, job)) {
1157 case JOB_RUNNING:
1158 done = FALSE;
1159 break;
1160 case JOB_ERROR:
1161 done = TRUE;
1162 *status = W_EXITCODE(1, 0);
1163 break;
1164 case JOB_FINISHED:
1165 /*
1166 * If we got back a JOB_FINISHED code, JobStart has already
1167 * called Make_Update and freed the job descriptor. We set
1168 * done to false here to avoid fake cycles and double frees.
1169 * JobStart needs to do the update so we can proceed up the
1170 * graph when given the -n flag..
1171 */
1172 done = FALSE;
1173 break;
1174 }
1175 } else {
1176 done = TRUE;
1177 }
1178
1179 if (done) {
1180 Trace_Log(JOBEND, job);
1181 if (!compatMake && !(job->flags & JOB_SPECIAL)) {
1182 if ((*status != 0) ||
1183 (aborting == ABORT_ERROR) ||
1184 (aborting == ABORT_INTERRUPT))
1185 Job_TokenReturn();
1186 }
1187
1188 }
1189
1190 if (done &&
1191 (aborting != ABORT_ERROR) &&
1192 (aborting != ABORT_INTERRUPT) &&
1193 (*status == 0))
1194 {
1195 /*
1196 * As long as we aren't aborting and the job didn't return a non-zero
1197 * status that we shouldn't ignore, we call Make_Update to update
1198 * the parents. In addition, any saved commands for the node are placed
1199 * on the .END target.
1200 */
1201 if (job->tailCmds != NILLNODE) {
1202 Lst_ForEachFrom(job->node->commands, job->tailCmds,
1203 JobSaveCommand,
1204 (ClientData)job->node);
1205 }
1206 job->node->made = MADE;
1207 if (!(job->flags & JOB_SPECIAL))
1208 Job_TokenReturn();
1209 Make_Update(job->node);
1210 free((Address)job);
1211 } else if (*status != 0) {
1212 errors += 1;
1213 free((Address)job);
1214 }
1215 JobRestartJobs();
1216
1217 /*
1218 * Set aborting if any error.
1219 */
1220 if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) {
1221 /*
1222 * If we found any errors in this batch of children and the -k flag
1223 * wasn't given, we set the aborting flag so no more jobs get
1224 * started.
1225 */
1226 aborting = ABORT_ERROR;
1227 }
1228
1229 if ((aborting == ABORT_ERROR) && Job_Empty()) {
1230 /*
1231 * If we are aborting and the job table is now empty, we finish.
1232 */
1233 Finish(errors);
1234 }
1235 }
1236
1237 /*-
1238 *-----------------------------------------------------------------------
1239 * Job_Touch --
1240 * Touch the given target. Called by JobStart when the -t flag was
1241 * given
1242 *
1243 * Input:
1244 * gn the node of the file to touch
1245 * silent TRUE if should not print message
1246 *
1247 * Results:
1248 * None
1249 *
1250 * Side Effects:
1251 * The data modification of the file is changed. In addition, if the
1252 * file did not exist, it is created.
1253 *-----------------------------------------------------------------------
1254 */
1255 void
1256 Job_Touch(GNode *gn, Boolean silent)
1257 {
1258 int streamID; /* ID of stream opened to do the touch */
1259 struct utimbuf times; /* Times for utime() call */
1260
1261 if (gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC|OP_OPTIONAL|OP_PHONY)) {
1262 /*
1263 * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets
1264 * and, as such, shouldn't really be created.
1265 */
1266 return;
1267 }
1268
1269 if (!silent || NoExecute(gn)) {
1270 (void) fprintf(stdout, "touch %s\n", gn->name);
1271 (void) fflush(stdout);
1272 }
1273
1274 if (NoExecute(gn)) {
1275 return;
1276 }
1277
1278 if (gn->type & OP_ARCHV) {
1279 Arch_Touch(gn);
1280 } else if (gn->type & OP_LIB) {
1281 Arch_TouchLib(gn);
1282 } else {
1283 char *file = gn->path ? gn->path : gn->name;
1284
1285 times.actime = times.modtime = now;
1286 if (utime(file, ×) < 0){
1287 streamID = open(file, O_RDWR | O_CREAT, 0666);
1288
1289 if (streamID >= 0) {
1290 char c;
1291
1292 /*
1293 * Read and write a byte to the file to change the
1294 * modification time, then close the file.
1295 */
1296 if (read(streamID, &c, 1) == 1) {
1297 (void) lseek(streamID, (off_t)0, SEEK_SET);
1298 (void) write(streamID, &c, 1);
1299 }
1300
1301 (void) close(streamID);
1302 } else {
1303 (void) fprintf(stdout, "*** couldn't touch %s: %s",
1304 file, strerror(errno));
1305 (void) fflush(stdout);
1306 }
1307 }
1308 }
1309 }
1310
1311 /*-
1312 *-----------------------------------------------------------------------
1313 * Job_CheckCommands --
1314 * Make sure the given node has all the commands it needs.
1315 *
1316 * Input:
1317 * gn The target whose commands need verifying
1318 * abortProc Function to abort with message
1319 *
1320 * Results:
1321 * TRUE if the commands list is/was ok.
1322 *
1323 * Side Effects:
1324 * The node will have commands from the .DEFAULT rule added to it
1325 * if it needs them.
1326 *-----------------------------------------------------------------------
1327 */
1328 Boolean
1329 Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1330 {
1331 if (OP_NOP(gn->type) && Lst_IsEmpty(gn->commands) &&
1332 ((gn->type & OP_LIB) == 0 || Lst_IsEmpty(gn->children))) {
1333 /*
1334 * No commands. Look for .DEFAULT rule from which we might infer
1335 * commands
1336 */
1337 if ((DEFAULT != NILGNODE) && !Lst_IsEmpty(DEFAULT->commands)) {
1338 char *p1;
1339 /*
1340 * Make only looks for a .DEFAULT if the node was never the
1341 * target of an operator, so that's what we do too. If
1342 * a .DEFAULT was given, we substitute its commands for gn's
1343 * commands and set the IMPSRC variable to be the target's name
1344 * The DEFAULT node acts like a transformation rule, in that
1345 * gn also inherits any attributes or sources attached to
1346 * .DEFAULT itself.
1347 */
1348 Make_HandleUse(DEFAULT, gn);
1349 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn, 0);
1350 if (p1)
1351 free(p1);
1352 } else if (Dir_MTime(gn) == 0) {
1353 /*
1354 * The node wasn't the target of an operator we have no .DEFAULT
1355 * rule to go on and the target doesn't already exist. There's
1356 * nothing more we can do for this branch. If the -k flag wasn't
1357 * given, we stop in our tracks, otherwise we just don't update
1358 * this node's parents so they never get examined.
1359 */
1360 static const char msg[] = ": don't know how to make";
1361
1362 if (gn->type & OP_OPTIONAL) {
1363 (void) fprintf(stdout, "%s%s %s(ignored)\n", progname,
1364 msg, gn->name);
1365 (void) fflush(stdout);
1366 } else if (keepgoing) {
1367 (void) fprintf(stdout, "%s%s %s(continuing)\n", progname,
1368 msg, gn->name);
1369 (void) fflush(stdout);
1370 return FALSE;
1371 } else {
1372 (*abortProc)("%s%s %s. Stop", progname, msg, gn->name);
1373 return FALSE;
1374 }
1375 }
1376 }
1377 return TRUE;
1378 }
1379 #ifdef RMT_WILL_WATCH
1380 /*-
1381 *-----------------------------------------------------------------------
1382 * JobLocalInput --
1383 * Handle a pipe becoming readable. Callback function for Rmt_Watch
1384 *
1385 * Input:
1386 * stream Stream that's ready (ignored)
1387 * job Job to which the stream belongs
1388 *
1389 * Results:
1390 * None
1391 *
1392 * Side Effects:
1393 * JobDoOutput is called.
1394 *
1395 *-----------------------------------------------------------------------
1396 */
1397 /*ARGSUSED*/
1398 static void
1399 JobLocalInput(int stream, Job *job)
1400 {
1401 JobDoOutput(job, FALSE);
1402 }
1403 #endif /* RMT_WILL_WATCH */
1404
1405 /*-
1406 *-----------------------------------------------------------------------
1407 * JobExec --
1408 * Execute the shell for the given job. Called from JobStart and
1409 * JobRestart.
1410 *
1411 * Input:
1412 * job Job to execute
1413 *
1414 * Results:
1415 * None.
1416 *
1417 * Side Effects:
1418 * A shell is executed, outputs is altered and the Job structure added
1419 * to the job table.
1420 *
1421 *-----------------------------------------------------------------------
1422 */
1423 static void
1424 JobExec(Job *job, char **argv)
1425 {
1426 int cpid; /* ID of new child */
1427 sigset_t mask;
1428
1429 job->flags &= ~JOB_TRACED;
1430
1431 if (DEBUG(JOB)) {
1432 int i;
1433
1434 (void) fprintf(stdout, "Running %s %sly\n", job->node->name,
1435 job->flags&JOB_REMOTE?"remote":"local");
1436 (void) fprintf(stdout, "\tCommand: ");
1437 for (i = 0; argv[i] != NULL; i++) {
1438 (void) fprintf(stdout, "%s ", argv[i]);
1439 }
1440 (void) fprintf(stdout, "\n");
1441 (void) fflush(stdout);
1442 }
1443
1444 /*
1445 * Some jobs produce no output and it's disconcerting to have
1446 * no feedback of their running (since they produce no output, the
1447 * banner with their name in it never appears). This is an attempt to
1448 * provide that feedback, even if nothing follows it.
1449 */
1450 if ((lastNode != job->node) && (job->flags & JOB_FIRST) &&
1451 !(job->flags & JOB_SILENT)) {
1452 MESSAGE(stdout, job->node);
1453 lastNode = job->node;
1454 }
1455
1456 #ifdef RMT_NO_EXEC
1457 if (job->flags & JOB_REMOTE) {
1458 goto jobExecFinish;
1459 }
1460 #endif /* RMT_NO_EXEC */
1461
1462 /* No interruptions until this job is on the `jobs' list */
1463 JobSigLock(&mask);
1464
1465 if ((cpid = vfork()) == -1) {
1466 Punt("Cannot vfork: %s", strerror(errno));
1467 } else if (cpid == 0) {
1468
1469 /*
1470 * Reset all signal handlers; this is necessary because we also
1471 * need to unblock signals before we exec(2).
1472 */
1473 JobSigReset();
1474
1475 /* Now unblock signals */
1476 sigemptyset(&mask);
1477 JobSigUnlock(&mask);
1478
1479 /*
1480 * Must duplicate the input stream down to the child's input and
1481 * reset it to the beginning (again). Since the stream was marked
1482 * close-on-exec, we must clear that bit in the new input.
1483 */
1484 if (dup2(FILENO(job->cmdFILE), 0) == -1) {
1485 execError("dup2", "job->cmdFILE");
1486 _exit(1);
1487 }
1488 (void) fcntl(0, F_SETFD, 0);
1489 (void) lseek(0, (off_t)0, SEEK_SET);
1490
1491 if (job->node->type & OP_MAKE) {
1492 /*
1493 * Pass job token pipe to submakes.
1494 */
1495 fcntl(job_pipe[0], F_SETFD, 0);
1496 fcntl(job_pipe[1], F_SETFD, 0);
1497 }
1498
1499 if (usePipes) {
1500 /*
1501 * Set up the child's output to be routed through the pipe
1502 * we've created for it.
1503 */
1504 if (dup2(job->outPipe, 1) == -1) {
1505 execError("dup2", "job->outPipe");
1506 _exit(1);
1507 }
1508 } else {
1509 /*
1510 * We're capturing output in a file, so we duplicate the
1511 * descriptor to the temporary file into the standard
1512 * output.
1513 */
1514 if (dup2(job->outFd, 1) == -1) {
1515 execError("dup2", "job->outFd");
1516 _exit(1);
1517 }
1518 }
1519 /*
1520 * The output channels are marked close on exec. This bit was
1521 * duplicated by the dup2 (on some systems), so we have to clear
1522 * it before routing the shell's error output to the same place as
1523 * its standard output.
1524 */
1525 (void) fcntl(1, F_SETFD, 0);
1526 if (dup2(1, 2) == -1) {
1527 execError("dup2", "1, 2");
1528 _exit(1);
1529 }
1530
1531 #ifdef USE_PGRP
1532 /*
1533 * We want to switch the child into a different process family so
1534 * we can kill it and all its descendants in one fell swoop,
1535 * by killing its process family, but not commit suicide.
1536 */
1537 # if defined(SYSV)
1538 (void) setsid();
1539 # else
1540 (void) setpgid(0, getpid());
1541 # endif
1542 #endif /* USE_PGRP */
1543
1544 #ifdef REMOTE
1545 if (job->flags & JOB_REMOTE) {
1546 Rmt_Exec(shellPath, argv, FALSE);
1547 } else
1548 #endif /* REMOTE */
1549 {
1550 (void) execv(shellPath, argv);
1551 execError("exec", shellPath);
1552 }
1553 _exit(1);
1554 } else {
1555 job->pid = cpid;
1556
1557 Trace_Log(JOBSTART, job);
1558
1559 if (usePipes && (job->flags & JOB_FIRST)) {
1560 /*
1561 * The first time a job is run for a node, we set the current
1562 * position in the buffer to the beginning and mark another
1563 * stream to watch in the outputs mask
1564 */
1565 job->curPos = 0;
1566
1567 #ifdef RMT_WILL_WATCH
1568 Rmt_Watch(job->inPipe, JobLocalInput, job);
1569 #else
1570 watchfd(job);
1571 #endif /* RMT_WILL_WATCH */
1572 }
1573
1574 if (job->flags & JOB_REMOTE) {
1575 #ifndef REMOTE
1576 job->rmtID = 0;
1577 #else
1578 job->rmtID = Rmt_LastID(job->pid);
1579 #endif /* REMOTE */
1580 } else {
1581 nLocal += 1;
1582 /*
1583 * XXX: Used to not happen if REMOTE. Why?
1584 */
1585 if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1586 (void) fclose(job->cmdFILE);
1587 job->cmdFILE = NULL;
1588 }
1589 }
1590 }
1591
1592 #ifdef RMT_NO_EXEC
1593 jobExecFinish:
1594 #endif
1595 /*
1596 * Now the job is actually running, add it to the table.
1597 */
1598 if (DEBUG(JOB)) {
1599 printf("JobExec(%s): pid %d added to jobs table\n",
1600 job->node->name, job->pid);
1601 }
1602 nJobs += 1;
1603 (void) Lst_AtEnd(jobs, (ClientData)job);
1604 JobSigUnlock(&mask);
1605 }
1606
1607 /*-
1608 *-----------------------------------------------------------------------
1609 * JobMakeArgv --
1610 * Create the argv needed to execute the shell for a given job.
1611 *
1612 *
1613 * Results:
1614 *
1615 * Side Effects:
1616 *
1617 *-----------------------------------------------------------------------
1618 */
1619 static void
1620 JobMakeArgv(Job *job, char **argv)
1621 {
1622 int argc;
1623 static char args[10]; /* For merged arguments */
1624
1625 argv[0] = UNCONST(shellName);
1626 argc = 1;
1627
1628 if ((commandShell->exit && (*commandShell->exit != '-')) ||
1629 (commandShell->echo && (*commandShell->echo != '-')))
1630 {
1631 /*
1632 * At least one of the flags doesn't have a minus before it, so
1633 * merge them together. Have to do this because the *(&(@*#*&#$#
1634 * Bourne shell thinks its second argument is a file to source.
1635 * Grrrr. Note the ten-character limitation on the combined arguments.
1636 */
1637 (void)snprintf(args, sizeof(args), "-%s%s",
1638 ((job->flags & JOB_IGNERR) ? "" :
1639 (commandShell->exit ? commandShell->exit : "")),
1640 ((job->flags & JOB_SILENT) ? "" :
1641 (commandShell->echo ? commandShell->echo : "")));
1642
1643 if (args[1]) {
1644 argv[argc] = args;
1645 argc++;
1646 }
1647 } else {
1648 if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
1649 argv[argc] = UNCONST(commandShell->exit);
1650 argc++;
1651 }
1652 if (!(job->flags & JOB_SILENT) && commandShell->echo) {
1653 argv[argc] = UNCONST(commandShell->echo);
1654 argc++;
1655 }
1656 }
1657 argv[argc] = NULL;
1658 }
1659
1660 /*-
1661 *-----------------------------------------------------------------------
1662 * JobRestart --
1663 * Restart a job that stopped for some reason.
1664 *
1665 * Input:
1666 * job Job to restart
1667 *
1668 * Results:
1669 * 1 if max number of running jobs has been reached, 0 otherwise.
1670 *
1671 *-----------------------------------------------------------------------
1672 */
1673 static int
1674 JobRestart(Job *job)
1675 {
1676 #ifdef REMOTE
1677 int host;
1678 #endif
1679
1680 if (job->flags & JOB_REMIGRATE) {
1681 if (
1682 #ifdef REMOTE
1683 verboseRemigrates ||
1684 #endif
1685 DEBUG(JOB)) {
1686 (void) fprintf(stdout, "*** remigrating %x(%s)\n",
1687 job->pid, job->node->name);
1688 (void) fflush(stdout);
1689 }
1690
1691 #ifdef REMOTE
1692 if (!Rmt_ReExport(job->pid, job->node, &host)) {
1693 if (verboseRemigrates || DEBUG(JOB)) {
1694 (void) fprintf(stdout, "*** couldn't migrate...\n");
1695 (void) fflush(stdout);
1696 }
1697 #endif
1698 if (nLocal != maxLocal) {
1699 /*
1700 * Job cannot be remigrated, but there's room on the local
1701 * machine, so resume the job and note that another
1702 * local job has started.
1703 */
1704 if (
1705 #ifdef REMOTE
1706 verboseRemigrates ||
1707 #endif
1708 DEBUG(JOB)) {
1709 (void) fprintf(stdout, "*** resuming on local machine\n");
1710 (void) fflush(stdout);
1711 }
1712 KILL(job->pid, SIGCONT);
1713 nLocal +=1;
1714 #ifdef REMOTE
1715 job->flags &= ~(JOB_REMIGRATE|JOB_RESUME|JOB_REMOTE);
1716 job->flags |= JOB_CONTINUING;
1717 #else
1718 job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
1719 #endif
1720 } else {
1721 /*
1722 * Job cannot be restarted. Mark the table as full and
1723 * place the job back on the list of stopped jobs.
1724 */
1725 if (
1726 #ifdef REMOTE
1727 verboseRemigrates ||
1728 #endif
1729 DEBUG(JOB)) {
1730 (void) fprintf(stdout, "*** holding\n");
1731 (void) fflush(stdout);
1732 }
1733 (void)Lst_AtFront(stoppedJobs, (ClientData)job);
1734 return 1;
1735 }
1736 #ifdef REMOTE
1737 } else {
1738 /*
1739 * Clear out the remigrate and resume flags. Set the continuing
1740 * flag so we know later on that the process isn't exiting just
1741 * because of a signal.
1742 */
1743 job->flags &= ~(JOB_REMIGRATE|JOB_RESUME);
1744 job->flags |= JOB_CONTINUING;
1745 job->rmtID = host;
1746 }
1747 #endif
1748
1749 (void)Lst_AtEnd(jobs, (ClientData)job);
1750 nJobs += 1;
1751 } else if (job->flags & JOB_RESTART) {
1752 /*
1753 * Set up the control arguments to the shell. This is based on the
1754 * flags set earlier for this job. If the JOB_IGNERR flag is clear,
1755 * the 'exit' flag of the commandShell is used to cause it to exit
1756 * upon receiving an error. If the JOB_SILENT flag is clear, the
1757 * 'echo' flag of the commandShell is used to get it to start echoing
1758 * as soon as it starts processing commands.
1759 */
1760 char *argv[10];
1761
1762 JobMakeArgv(job, argv);
1763
1764 if (DEBUG(JOB)) {
1765 (void) fprintf(stdout, "Restarting %s...", job->node->name);
1766 (void) fflush(stdout);
1767 }
1768 #ifdef REMOTE
1769 if ((job->node->type & OP_NOEXPORT) ||
1770 (nLocal < maxLocal && runLocalFirst)
1771 # ifdef RMT_NO_EXEC
1772 || !Rmt_Export(shellPath, argv, job)
1773 # else
1774 || !Rmt_Begin(shellPath, argv, job->node)
1775 # endif
1776 )
1777 #endif
1778 {
1779 if (((nLocal >= maxLocal) && !(job->flags & JOB_SPECIAL))) {
1780 /*
1781 * Can't be exported and not allowed to run locally -- put it
1782 * back on the hold queue and mark the table full
1783 */
1784 if (DEBUG(JOB)) {
1785 (void) fprintf(stdout, "holding\n");
1786 (void) fflush(stdout);
1787 }
1788 (void)Lst_AtFront(stoppedJobs, (ClientData)job);
1789 return 1;
1790 } else {
1791 /*
1792 * Job may be run locally.
1793 */
1794 if (DEBUG(JOB)) {
1795 (void) fprintf(stdout, "running locally\n");
1796 (void) fflush(stdout);
1797 }
1798 job->flags &= ~JOB_REMOTE;
1799 }
1800 }
1801 #ifdef REMOTE
1802 else {
1803 /*
1804 * Can be exported. Hooray!
1805 */
1806 if (DEBUG(JOB)) {
1807 (void) fprintf(stdout, "exporting\n");
1808 (void) fflush(stdout);
1809 }
1810 job->flags |= JOB_REMOTE;
1811 }
1812 #endif
1813 JobExec(job, argv);
1814 } else {
1815 /*
1816 * The job has stopped and needs to be restarted. Why it stopped,
1817 * we don't know...
1818 */
1819 if (DEBUG(JOB)) {
1820 (void) fprintf(stdout, "Resuming %s...", job->node->name);
1821 (void) fflush(stdout);
1822 }
1823 if ((nJobs != maxJobs) &&
1824 ((job->flags & JOB_REMOTE) ||
1825 (nLocal < maxLocal) ||
1826 ((maxLocal == 0) &&
1827 ((job->flags & JOB_SPECIAL)
1828 #ifdef REMOTE
1829 && (job->node->type & OP_NOEXPORT)
1830 #endif
1831 ))))
1832 {
1833 /*
1834 * If the job is remote, it's ok to resume it as long as the
1835 * maximum concurrency won't be exceeded. If it's local and
1836 * we haven't reached the local concurrency limit already (or the
1837 * job must be run locally and maxLocal is 0), it's also ok to
1838 * resume it.
1839 */
1840 Boolean error;
1841 int status;
1842
1843 #ifdef RMT_WANTS_SIGNALS
1844 if (job->flags & JOB_REMOTE) {
1845 error = !Rmt_Signal(job, SIGCONT);
1846 } else
1847 #endif /* RMT_WANTS_SIGNALS */
1848 error = (KILL(job->pid, SIGCONT) != 0);
1849
1850 if (!error) {
1851 /*
1852 * Make sure the user knows we've continued the beast and
1853 * actually put the thing in the job table.
1854 */
1855 job->flags |= JOB_CONTINUING;
1856 status = W_STOPCODE(SIGCONT);
1857 JobFinish(job, &status);
1858
1859 job->flags &= ~(JOB_RESUME|JOB_CONTINUING);
1860 if (DEBUG(JOB)) {
1861 (void) fprintf(stdout, "done\n");
1862 (void) fflush(stdout);
1863 }
1864 } else {
1865 Error("couldn't resume %s: %s",
1866 job->node->name, strerror(errno));
1867 status = W_EXITCODE(1, 0);
1868 JobFinish(job, &status);
1869 }
1870 } else {
1871 /*
1872 * Job cannot be restarted. Mark the table as full and
1873 * place the job back on the list of stopped jobs.
1874 */
1875 if (DEBUG(JOB)) {
1876 (void) fprintf(stdout, "table full\n");
1877 (void) fflush(stdout);
1878 }
1879 (void) Lst_AtFront(stoppedJobs, (ClientData)job);
1880 return 1;
1881 }
1882 }
1883 return 0;
1884 }
1885
1886 /*-
1887 *-----------------------------------------------------------------------
1888 * JobStart --
1889 * Start a target-creation process going for the target described
1890 * by the graph node gn.
1891 *
1892 * Input:
1893 * gn target to create
1894 * flags flags for the job to override normal ones.
1895 * e.g. JOB_SPECIAL or JOB_IGNDOTS
1896 * previous The previous Job structure for this node, if any.
1897 *
1898 * Results:
1899 * JOB_ERROR if there was an error in the commands, JOB_FINISHED
1900 * if there isn't actually anything left to do for the job and
1901 * JOB_RUNNING if the job has been started.
1902 *
1903 * Side Effects:
1904 * A new Job node is created and added to the list of running
1905 * jobs. PMake is forked and a child shell created.
1906 *-----------------------------------------------------------------------
1907 */
1908 static int
1909 JobStart(GNode *gn, int flags, Job *previous)
1910 {
1911 Job *job; /* new job descriptor */
1912 char *argv[10]; /* Argument vector to shell */
1913 Boolean cmdsOK; /* true if the nodes commands were all right */
1914 Boolean local; /* Set true if the job was run locally */
1915 Boolean noExec; /* Set true if we decide not to run the job */
1916 int tfd; /* File descriptor to the temp file */
1917
1918 if (previous != NULL) {
1919 previous->flags &= ~(JOB_FIRST|JOB_IGNERR|JOB_SILENT|JOB_REMOTE);
1920 job = previous;
1921 } else {
1922 job = (Job *) emalloc(sizeof(Job));
1923 if (job == NULL) {
1924 Punt("JobStart out of memory");
1925 }
1926 flags |= JOB_FIRST;
1927 }
1928
1929 job->node = gn;
1930 job->tailCmds = NILLNODE;
1931
1932 /*
1933 * Set the initial value of the flags for this job based on the global
1934 * ones and the node's attributes... Any flags supplied by the caller
1935 * are also added to the field.
1936 */
1937 job->flags = 0;
1938 if (Targ_Ignore(gn)) {
1939 job->flags |= JOB_IGNERR;
1940 }
1941 if (Targ_Silent(gn)) {
1942 job->flags |= JOB_SILENT;
1943 }
1944 job->flags |= flags;
1945
1946 /*
1947 * Check the commands now so any attributes from .DEFAULT have a chance
1948 * to migrate to the node
1949 */
1950 if (!compatMake && job->flags & JOB_FIRST) {
1951 cmdsOK = Job_CheckCommands(gn, Error);
1952 } else {
1953 cmdsOK = TRUE;
1954 }
1955
1956 #ifndef RMT_WILL_WATCH
1957 job->inPollfd = NULL;
1958 #endif
1959 /*
1960 * If the -n flag wasn't given, we open up OUR (not the child's)
1961 * temporary file to stuff commands in it. The thing is rd/wr so we don't
1962 * need to reopen it to feed it to the shell. If the -n flag *was* given,
1963 * we just set the file to be stdout. Cute, huh?
1964 */
1965 if (((gn->type & OP_MAKE) && !(noRecursiveExecute)) ||
1966 (!noExecute && !touchFlag)) {
1967 /*
1968 * tfile is the name of a file into which all shell commands are
1969 * put. It is used over by removing it before the child shell is
1970 * executed. The XXXXXX in the string are replaced by the pid of
1971 * the make process in a 6-character field with leading zeroes.
1972 */
1973 char tfile[sizeof(TMPPAT)];
1974 sigset_t mask;
1975 /*
1976 * We're serious here, but if the commands were bogus, we're
1977 * also dead...
1978 */
1979 if (!cmdsOK) {
1980 DieHorribly();
1981 }
1982
1983 JobSigLock(&mask);
1984 (void)strcpy(tfile, TMPPAT);
1985 if ((tfd = mkstemp(tfile)) == -1)
1986 Punt("Could not create temporary file %s", strerror(errno));
1987 (void) eunlink(tfile);
1988 JobSigUnlock(&mask);
1989
1990 job->cmdFILE = fdopen(tfd, "w+");
1991 if (job->cmdFILE == NULL) {
1992 Punt("Could not fdopen %s", tfile);
1993 }
1994 (void) fcntl(FILENO(job->cmdFILE), F_SETFD, 1);
1995 /*
1996 * Send the commands to the command file, flush all its buffers then
1997 * rewind and remove the thing.
1998 */
1999 noExec = FALSE;
2000
2001 /*
2002 * used to be backwards; replace when start doing multiple commands
2003 * per shell.
2004 */
2005 if (compatMake) {
2006 /*
2007 * Be compatible: If this is the first time for this node,
2008 * verify its commands are ok and open the commands list for
2009 * sequential access by later invocations of JobStart.
2010 * Once that is done, we take the next command off the list
2011 * and print it to the command file. If the command was an
2012 * ellipsis, note that there's nothing more to execute.
2013 */
2014 if ((job->flags&JOB_FIRST) && (Lst_Open(gn->commands) != SUCCESS)){
2015 cmdsOK = FALSE;
2016 } else {
2017 LstNode ln = Lst_Next(gn->commands);
2018
2019 if ((ln == NILLNODE) ||
2020 JobPrintCommand((ClientData) Lst_Datum(ln),
2021 (ClientData) job))
2022 {
2023 noExec = TRUE;
2024 Lst_Close(gn->commands);
2025 }
2026 if (noExec && !(job->flags & JOB_FIRST)) {
2027 /*
2028 * If we're not going to execute anything, the job
2029 * is done and we need to close down the various
2030 * file descriptors we've opened for output, then
2031 * call JobDoOutput to catch the final characters or
2032 * send the file to the screen... Note that the i/o streams
2033 * are only open if this isn't the first job.
2034 * Note also that this could not be done in
2035 * Job_CatchChildren b/c it wasn't clear if there were
2036 * more commands to execute or not...
2037 */
2038 JobClose(job);
2039 }
2040 }
2041 } else {
2042 /*
2043 * We can do all the commands at once. hooray for sanity
2044 */
2045 numCommands = 0;
2046 Lst_ForEach(gn->commands, JobPrintCommand, (ClientData)job);
2047
2048 /*
2049 * If we didn't print out any commands to the shell script,
2050 * there's not much point in executing the shell, is there?
2051 */
2052 if (numCommands == 0) {
2053 noExec = TRUE;
2054 }
2055 }
2056 } else if (NoExecute(gn)) {
2057 /*
2058 * Not executing anything -- just print all the commands to stdout
2059 * in one fell swoop. This will still set up job->tailCmds correctly.
2060 */
2061 if (lastNode != gn) {
2062 MESSAGE(stdout, gn);
2063 lastNode = gn;
2064 }
2065 job->cmdFILE = stdout;
2066 /*
2067 * Only print the commands if they're ok, but don't die if they're
2068 * not -- just let the user know they're bad and keep going. It
2069 * doesn't do any harm in this case and may do some good.
2070 */
2071 if (cmdsOK) {
2072 Lst_ForEach(gn->commands, JobPrintCommand, (ClientData)job);
2073 }
2074 /*
2075 * Don't execute the shell, thank you.
2076 */
2077 noExec = TRUE;
2078 } else {
2079 /*
2080 * Just touch the target and note that no shell should be executed.
2081 * Set cmdFILE to stdout to make life easier. Check the commands, too,
2082 * but don't die if they're no good -- it does no harm to keep working
2083 * up the graph.
2084 */
2085 job->cmdFILE = stdout;
2086 Job_Touch(gn, job->flags&JOB_SILENT);
2087 noExec = TRUE;
2088 }
2089
2090 /*
2091 * If we're not supposed to execute a shell, don't.
2092 */
2093 if (noExec) {
2094 /*
2095 * Unlink and close the command file if we opened one
2096 */
2097 if (job->cmdFILE != stdout) {
2098 if (job->cmdFILE != NULL) {
2099 (void) fclose(job->cmdFILE);
2100 job->cmdFILE = NULL;
2101 }
2102 } else {
2103 (void) fflush(stdout);
2104 }
2105
2106 /*
2107 * We only want to work our way up the graph if we aren't here because
2108 * the commands for the job were no good.
2109 */
2110 if (cmdsOK) {
2111 if (aborting == 0) {
2112 if (job->tailCmds != NILLNODE) {
2113 Lst_ForEachFrom(job->node->commands, job->tailCmds,
2114 JobSaveCommand,
2115 (ClientData)job->node);
2116 }
2117 if (!(job->flags & JOB_SPECIAL))
2118 Job_TokenReturn();
2119 job->node->made = MADE;
2120 Make_Update(job->node);
2121 }
2122 free((Address)job);
2123 return(JOB_FINISHED);
2124 } else {
2125 free((Address)job);
2126 return(JOB_ERROR);
2127 }
2128 } else {
2129 (void) fflush(job->cmdFILE);
2130 }
2131
2132 /*
2133 * Set up the control arguments to the shell. This is based on the flags
2134 * set earlier for this job.
2135 */
2136 JobMakeArgv(job, argv);
2137
2138 /*
2139 * If we're using pipes to catch output, create the pipe by which we'll
2140 * get the shell's output. If we're using files, print out that we're
2141 * starting a job and then set up its temporary-file name.
2142 */
2143 if (!compatMake || (job->flags & JOB_FIRST)) {
2144 if (usePipes) {
2145 int fd[2];
2146 if (pipe(fd) == -1)
2147 Punt("Cannot create pipe: %s", strerror(errno));
2148 job->inPipe = fd[0];
2149 job->outPipe = fd[1];
2150 (void) fcntl(job->inPipe, F_SETFD, 1);
2151 (void) fcntl(job->outPipe, F_SETFD, 1);
2152 } else {
2153 (void) fprintf(stdout, "Remaking `%s'\n", gn->name);
2154 (void) fflush(stdout);
2155 (void) strcpy(job->outFile, TMPPAT);
2156 job->outFd = mkstemp(job->outFile);
2157 (void) fcntl(job->outFd, F_SETFD, 1);
2158 }
2159 }
2160
2161 #ifdef REMOTE
2162 if (!(gn->type & OP_NOEXPORT) && !(runLocalFirst && nLocal < maxLocal)) {
2163 #ifdef RMT_NO_EXEC
2164 local = !Rmt_Export(shellPath, argv, job);
2165 #else
2166 local = !Rmt_Begin(shellPath, argv, job->node);
2167 #endif /* RMT_NO_EXEC */
2168 if (!local) {
2169 job->flags |= JOB_REMOTE;
2170 }
2171 } else
2172 #endif
2173 local = TRUE;
2174
2175 if (local && (((nLocal >= maxLocal) &&
2176 !(job->flags & JOB_SPECIAL) &&
2177 #ifdef REMOTE
2178 (!(gn->type & OP_NOEXPORT) || (maxLocal != 0))
2179 #else
2180 (maxLocal != 0)
2181 #endif
2182 )))
2183 {
2184 /*
2185 * The job can only be run locally, but we've hit the limit of
2186 * local concurrency, so put the job on hold until some other job
2187 * finishes. Note that the special jobs (.BEGIN, .INTERRUPT and .END)
2188 * may be run locally even when the local limit has been reached
2189 * (e.g. when maxLocal == 0), though they will be exported if at
2190 * all possible. In addition, any target marked with .NOEXPORT will
2191 * be run locally if maxLocal is 0.
2192 */
2193 job->flags |= JOB_RESTART;
2194 (void) Lst_AtEnd(stoppedJobs, (ClientData)job);
2195 } else {
2196 JobExec(job, argv);
2197 }
2198 return(JOB_RUNNING);
2199 }
2200
2201 static char *
2202 JobOutput(Job *job, char *cp, char *endp, int msg)
2203 {
2204 char *ecp;
2205
2206 if (commandShell->noPrint) {
2207 ecp = Str_FindSubstring(cp, commandShell->noPrint);
2208 while (ecp != NULL) {
2209 if (cp != ecp) {
2210 *ecp = '\0';
2211 if (msg && job->node != lastNode) {
2212 MESSAGE(stdout, job->node);
2213 lastNode = job->node;
2214 }
2215 /*
2216 * The only way there wouldn't be a newline after
2217 * this line is if it were the last in the buffer.
2218 * however, since the non-printable comes after it,
2219 * there must be a newline, so we don't print one.
2220 */
2221 (void) fprintf(stdout, "%s", cp);
2222 (void) fflush(stdout);
2223 }
2224 cp = ecp + commandShell->noPLen;
2225 if (cp != endp) {
2226 /*
2227 * Still more to print, look again after skipping
2228 * the whitespace following the non-printable
2229 * command....
2230 */
2231 cp++;
2232 while (*cp == ' ' || *cp == '\t' || *cp == '\n') {
2233 cp++;
2234 }
2235 ecp = Str_FindSubstring(cp, commandShell->noPrint);
2236 } else {
2237 return cp;
2238 }
2239 }
2240 }
2241 return cp;
2242 }
2243
2244 /*-
2245 *-----------------------------------------------------------------------
2246 * JobDoOutput --
2247 * This function is called at different times depending on
2248 * whether the user has specified that output is to be collected
2249 * via pipes or temporary files. In the former case, we are called
2250 * whenever there is something to read on the pipe. We collect more
2251 * output from the given job and store it in the job's outBuf. If
2252 * this makes up a line, we print it tagged by the job's identifier,
2253 * as necessary.
2254 * If output has been collected in a temporary file, we open the
2255 * file and read it line by line, transfering it to our own
2256 * output channel until the file is empty. At which point we
2257 * remove the temporary file.
2258 * In both cases, however, we keep our figurative eye out for the
2259 * 'noPrint' line for the shell from which the output came. If
2260 * we recognize a line, we don't print it. If the command is not
2261 * alone on the line (the character after it is not \0 or \n), we
2262 * do print whatever follows it.
2263 *
2264 * Input:
2265 * job the job whose output needs printing
2266 * finish TRUE if this is the last time we'll be called
2267 * for this job
2268 *
2269 * Results:
2270 * None
2271 *
2272 * Side Effects:
2273 * curPos may be shifted as may the contents of outBuf.
2274 *-----------------------------------------------------------------------
2275 */
2276 STATIC void
2277 JobDoOutput(Job *job, Boolean finish)
2278 {
2279 Boolean gotNL = FALSE; /* true if got a newline */
2280 Boolean fbuf; /* true if our buffer filled up */
2281 int nr; /* number of bytes read */
2282 int i; /* auxiliary index into outBuf */
2283 int max; /* limit for i (end of current data) */
2284 int nRead; /* (Temporary) number of bytes read */
2285
2286 FILE *oFILE; /* Stream pointer to shell's output file */
2287 char inLine[132];
2288
2289
2290 if (usePipes) {
2291 /*
2292 * Read as many bytes as will fit in the buffer.
2293 */
2294 end_loop:
2295 gotNL = FALSE;
2296 fbuf = FALSE;
2297
2298 nRead = read(job->inPipe, &job->outBuf[job->curPos],
2299 JOB_BUFSIZE - job->curPos);
2300 if (nRead < 0) {
2301 if (DEBUG(JOB)) {
2302 perror("JobDoOutput(piperead)");
2303 }
2304 nr = 0;
2305 } else {
2306 nr = nRead;
2307 }
2308
2309 /*
2310 * If we hit the end-of-file (the job is dead), we must flush its
2311 * remaining output, so pretend we read a newline if there's any
2312 * output remaining in the buffer.
2313 * Also clear the 'finish' flag so we stop looping.
2314 */
2315 if ((nr == 0) && (job->curPos != 0)) {
2316 job->outBuf[job->curPos] = '\n';
2317 nr = 1;
2318 finish = FALSE;
2319 } else if (nr == 0) {
2320 finish = FALSE;
2321 }
2322
2323 /*
2324 * Look for the last newline in the bytes we just got. If there is
2325 * one, break out of the loop with 'i' as its index and gotNL set
2326 * TRUE.
2327 */
2328 max = job->curPos + nr;
2329 for (i = job->curPos + nr - 1; i >= job->curPos; i--) {
2330 if (job->outBuf[i] == '\n') {
2331 gotNL = TRUE;
2332 break;
2333 } else if (job->outBuf[i] == '\0') {
2334 /*
2335 * Why?
2336 */
2337 job->outBuf[i] = ' ';
2338 }
2339 }
2340
2341 if (!gotNL) {
2342 job->curPos += nr;
2343 if (job->curPos == JOB_BUFSIZE) {
2344 /*
2345 * If we've run out of buffer space, we have no choice
2346 * but to print the stuff. sigh.
2347 */
2348 fbuf = TRUE;
2349 i = job->curPos;
2350 }
2351 }
2352 if (gotNL || fbuf) {
2353 /*
2354 * Need to send the output to the screen. Null terminate it
2355 * first, overwriting the newline character if there was one.
2356 * So long as the line isn't one we should filter (according
2357 * to the shell description), we print the line, preceded
2358 * by a target banner if this target isn't the same as the
2359 * one for which we last printed something.
2360 * The rest of the data in the buffer are then shifted down
2361 * to the start of the buffer and curPos is set accordingly.
2362 */
2363 job->outBuf[i] = '\0';
2364 if (i >= job->curPos) {
2365 char *cp;
2366
2367 cp = JobOutput(job, job->outBuf, &job->outBuf[i], FALSE);
2368
2369 /*
2370 * There's still more in that thar buffer. This time, though,
2371 * we know there's no newline at the end, so we add one of
2372 * our own free will.
2373 */
2374 if (*cp != '\0') {
2375 if (job->node != lastNode) {
2376 MESSAGE(stdout, job->node);
2377 lastNode = job->node;
2378 }
2379 (void) fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
2380 (void) fflush(stdout);
2381 }
2382 }
2383 if (i < max - 1) {
2384 /* shift the remaining characters down */
2385 (void) memcpy(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
2386 job->curPos = max - (i + 1);
2387
2388 } else {
2389 /*
2390 * We have written everything out, so we just start over
2391 * from the start of the buffer. No copying. No nothing.
2392 */
2393 job->curPos = 0;
2394 }
2395 }
2396 if (finish) {
2397 /*
2398 * If the finish flag is true, we must loop until we hit
2399 * end-of-file on the pipe. This is guaranteed to happen
2400 * eventually since the other end of the pipe is now closed
2401 * (we closed it explicitly and the child has exited). When
2402 * we do get an EOF, finish will be set FALSE and we'll fall
2403 * through and out.
2404 */
2405 goto end_loop;
2406 }
2407 } else {
2408 /*
2409 * We've been called to retrieve the output of the job from the
2410 * temporary file where it's been squirreled away. This consists of
2411 * opening the file, reading the output line by line, being sure not
2412 * to print the noPrint line for the shell we used, then close and
2413 * remove the temporary file. Very simple.
2414 *
2415 * Change to read in blocks and do FindSubString type things as for
2416 * pipes? That would allow for "@echo -n..."
2417 */
2418 oFILE = fopen(job->outFile, "r");
2419 if (oFILE != NULL) {
2420 (void) fprintf(stdout, "Results of making %s:\n", job->node->name);
2421 (void) fflush(stdout);
2422 while (fgets(inLine, sizeof(inLine), oFILE) != NULL) {
2423 char *cp, *endp, *oendp;
2424
2425 cp = inLine;
2426 oendp = endp = inLine + strlen(inLine);
2427 if (endp[-1] == '\n') {
2428 *--endp = '\0';
2429 }
2430 cp = JobOutput(job, inLine, endp, FALSE);
2431
2432 /*
2433 * There's still more in that thar buffer. This time, though,
2434 * we know there's no newline at the end, so we add one of
2435 * our own free will.
2436 */
2437 (void) fprintf(stdout, "%s", cp);
2438 (void) fflush(stdout);
2439 if (endp != oendp) {
2440 (void) fprintf(stdout, "\n");
2441 (void) fflush(stdout);
2442 }
2443 }
2444 (void) fclose(oFILE);
2445 (void) eunlink(job->outFile);
2446 } else {
2447 Punt("Cannot open `%s'", job->outFile);
2448 }
2449 }
2450 }
2451
2452 /*-
2453 *-----------------------------------------------------------------------
2454 * Job_CatchChildren --
2455 * Handle the exit of a child. Called from Make_Make.
2456 *
2457 * Input:
2458 * block TRUE if should block on the wait
2459 *
2460 * Results:
2461 * none.
2462 *
2463 * Side Effects:
2464 * The job descriptor is removed from the list of children.
2465 *
2466 * Notes:
2467 * We do waits, blocking or not, according to the wisdom of our
2468 * caller, until there are no more children to report. For each
2469 * job, call JobFinish to finish things off. This will take care of
2470 * putting jobs on the stoppedJobs queue.
2471 *
2472 *-----------------------------------------------------------------------
2473 */
2474 void
2475 Job_CatchChildren(Boolean block)
2476 {
2477 int pid; /* pid of dead child */
2478 Job *job; /* job descriptor for dead child */
2479 LstNode jnode; /* list element for finding job */
2480 int status; /* Exit/termination status */
2481
2482 /*
2483 * Don't even bother if we know there's no one around.
2484 */
2485 if (nLocal == 0) {
2486 return;
2487 }
2488
2489 while ((pid = waitpid((pid_t) -1, &status,
2490 (block?0:WNOHANG)|WUNTRACED)) > 0)
2491 {
2492 if (DEBUG(JOB)) {
2493 (void) fprintf(stdout, "Process %d exited or stopped %x.\n", pid,
2494 status);
2495 (void) fflush(stdout);
2496 }
2497
2498 jnode = Lst_Find(jobs, (ClientData)&pid, JobCmpPid);
2499 if (jnode == NILLNODE) {
2500 if (WIFSTOPPED(status) && (WSTOPSIG(status) == SIGCONT)) {
2501 jnode = Lst_Find(stoppedJobs, (ClientData) &pid, JobCmpPid);
2502 if (jnode == NILLNODE) {
2503 Error("Resumed child (%d) not in table", pid);
2504 continue;
2505 }
2506 job = (Job *)Lst_Datum(jnode);
2507 (void) Lst_Remove(stoppedJobs, jnode);
2508 } else {
2509 Error("Child (%d) not in table?", pid);
2510 continue;
2511 }
2512 } else {
2513 job = (Job *) Lst_Datum(jnode);
2514 (void) Lst_Remove(jobs, jnode);
2515 nJobs -= 1;
2516 #ifdef REMOTE
2517 if (!(job->flags & JOB_REMOTE)) {
2518 if (DEBUG(JOB)) {
2519 (void) fprintf(stdout,
2520 "Job queue has one fewer local process.\n");
2521 (void) fflush(stdout);
2522 }
2523 nLocal -= 1;
2524 }
2525 #else
2526 nLocal -= 1;
2527 #endif
2528 }
2529
2530 JobFinish(job, &status);
2531 }
2532 }
2533
2534 /*-
2535 *-----------------------------------------------------------------------
2536 * Job_CatchOutput --
2537 * Catch the output from our children, if we're using
2538 * pipes do so. Otherwise just block time until we get a
2539 * signal (most likely a SIGCHLD) since there's no point in
2540 * just spinning when there's nothing to do and the reaping
2541 * of a child can wait for a while.
2542 *
2543 * Results:
2544 * None
2545 *
2546 * Side Effects:
2547 * Output is read from pipes if we're piping.
2548 * -----------------------------------------------------------------------
2549 */
2550 void
2551 Job_CatchOutput(void)
2552 {
2553 int nready;
2554 LstNode ln;
2555 Job *job;
2556 #ifdef RMT_WILL_WATCH
2557 int pnJobs; /* Previous nJobs */
2558 #endif
2559
2560 (void) fflush(stdout);
2561 Job_TokenFlush();
2562 #ifdef RMT_WILL_WATCH
2563 pnJobs = nJobs;
2564
2565 /*
2566 * It is possible for us to be called with nJobs equal to 0. This happens
2567 * if all the jobs finish and a job that is stopped cannot be run
2568 * locally (eg if maxLocal is 0) and cannot be exported. The job will
2569 * be placed back on the stoppedJobs queue, Job_Empty() will return false,
2570 * Make_Run will call us again when there's nothing for which to wait.
2571 * nJobs never changes, so we loop forever. Hence the check. It could
2572 * be argued that we should sleep for a bit so as not to swamp the
2573 * exportation system with requests. Perhaps we should.
2574 *
2575 * NOTE: IT IS THE RESPONSIBILITY OF Rmt_Wait TO CALL Job_CatchChildren
2576 * IN A TIMELY FASHION TO CATCH ANY LOCALLY RUNNING JOBS THAT EXIT.
2577 * It may use the variable nLocal to determine if it needs to call
2578 * Job_CatchChildren (if nLocal is 0, there's nothing for which to
2579 * wait...)
2580 */
2581 while (nJobs != 0 && pnJobs == nJobs) {
2582 Rmt_Wait();
2583 }
2584 #else
2585 if (usePipes) {
2586 if ((nready = poll((wantToken ? fds : (fds + 1)),
2587 (wantToken ? nfds : (nfds - 1)), POLL_MSEC)) <= 0) {
2588 return;
2589 } else {
2590 sigset_t mask;
2591 JobSigLock(&mask);
2592 if (Lst_Open(jobs) == FAILURE) {
2593 Punt("Cannot open job table");
2594 }
2595
2596 if (readyfd(&childExitJob)) {
2597 char token;
2598 (void) read(childExitJob.inPipe, &token, 1);
2599 nready -= 1;
2600 }
2601
2602 while (nready && (ln = Lst_Next(jobs)) != NILLNODE) {
2603 job = (Job *) Lst_Datum(ln);
2604 if (readyfd(job)) {
2605 JobDoOutput(job, FALSE);
2606 nready -= 1;
2607 }
2608 }
2609 Lst_Close(jobs);
2610 JobSigUnlock(&mask);
2611 }
2612 }
2613 #endif /* RMT_WILL_WATCH */
2614 }
2615
2616 /*-
2617 *-----------------------------------------------------------------------
2618 * Job_Make --
2619 * Start the creation of a target. Basically a front-end for
2620 * JobStart used by the Make module.
2621 *
2622 * Results:
2623 * None.
2624 *
2625 * Side Effects:
2626 * Another job is started.
2627 *
2628 *-----------------------------------------------------------------------
2629 */
2630 void
2631 Job_Make(GNode *gn)
2632 {
2633 (void) JobStart(gn, 0, NULL);
2634 }
2635
2636 void
2637 Shell_Init()
2638 {
2639 if (shellPath == NULL) {
2640 /*
2641 * The user didn't specify a shell to use, so we are using the
2642 * default one... Both the absolute path and the last component
2643 * must be set. The last component is taken from the 'name' field
2644 * of the default shell description pointed-to by commandShell.
2645 * All default shells are located in _PATH_DEFSHELLDIR.
2646 */
2647 shellName = commandShell->name;
2648 shellPath = str_concat(_PATH_DEFSHELLDIR, shellName, STR_ADDSLASH);
2649 }
2650 if (commandShell->exit == NULL) {
2651 commandShell->exit = "";
2652 }
2653 if (commandShell->echo == NULL) {
2654 commandShell->echo = "";
2655 }
2656 }
2657
2658 /*-
2659 *-----------------------------------------------------------------------
2660 * Job_Init --
2661 * Initialize the process module
2662 *
2663 * Input:
2664 * maxproc the greatest number of jobs which may be running
2665 * at one time
2666 * maxlocal the greatest number of jobs which may be running
2667 * at once
2668 *
2669 * Results:
2670 * none
2671 *
2672 * Side Effects:
2673 * lists and counters are initialized
2674 *-----------------------------------------------------------------------
2675 */
2676 void
2677 Job_Init(int maxproc, int maxlocal)
2678 {
2679 GNode *begin; /* node for commands to do at the very start */
2680
2681 jobs = Lst_Init(FALSE);
2682 stoppedJobs = Lst_Init(FALSE);
2683 maxJobs = maxproc;
2684 maxLocal = maxlocal;
2685 nJobs = 0;
2686 nLocal = 0;
2687 wantToken = FALSE;
2688
2689 aborting = 0;
2690 errors = 0;
2691
2692 lastNode = NILGNODE;
2693
2694 if (maxJobs == 1
2695 #ifdef REMOTE
2696 || noMessages
2697 #endif
2698 ) {
2699 /*
2700 * If only one job can run at a time, there's no need for a banner,
2701 * is there?
2702 */
2703 targFmt = "";
2704 } else {
2705 targFmt = TARG_FMT;
2706 }
2707
2708 Shell_Init();
2709
2710 if (pipe(exit_pipe) < 0)
2711 Fatal("error in pipe: %s", strerror(errno));
2712 fcntl(exit_pipe[0], F_SETFD, 1);
2713 fcntl(exit_pipe[1], F_SETFD, 1);
2714
2715 childExitJob.inPipe = exit_pipe[0];
2716
2717 sigemptyset(&caught_signals);
2718 /*
2719 * Install a SIGCHLD handler.
2720 */
2721 (void)signal(SIGCHLD, JobChildSig);
2722 sigaddset(&caught_signals, SIGCHLD);
2723
2724 #define ADDSIG(s,h) \
2725 if (signal(s, SIG_IGN) != SIG_IGN) { \
2726 sigaddset(&caught_signals, s); \
2727 (void) signal(s, h); \
2728 }
2729
2730 /*
2731 * Catch the four signals that POSIX specifies if they aren't ignored.
2732 * JobPassSig will take care of calling JobInterrupt if appropriate.
2733 */
2734 ADDSIG(SIGINT, JobPassSig)
2735 ADDSIG(SIGHUP, JobPassSig)
2736 ADDSIG(SIGTERM, JobPassSig)
2737 ADDSIG(SIGQUIT, JobPassSig)
2738
2739 /*
2740 * There are additional signals that need to be caught and passed if
2741 * either the export system wants to be told directly of signals or if
2742 * we're giving each job its own process group (since then it won't get
2743 * signals from the terminal driver as we own the terminal)
2744 */
2745 #if defined(RMT_WANTS_SIGNALS) || defined(USE_PGRP)
2746 ADDSIG(SIGTSTP, JobPassSig)
2747 ADDSIG(SIGTTOU, JobPassSig)
2748 ADDSIG(SIGTTIN, JobPassSig)
2749 ADDSIG(SIGWINCH, JobPassSig)
2750 ADDSIG(SIGCONT, JobContinueSig)
2751 #endif
2752 #undef ADDSIG
2753
2754 begin = Targ_FindNode(".BEGIN", TARG_NOCREATE);
2755
2756 if (begin != NILGNODE) {
2757 JobStart(begin, JOB_SPECIAL, (Job *)0);
2758 while (nJobs) {
2759 Job_CatchOutput();
2760 #ifndef RMT_WILL_WATCH
2761 Job_CatchChildren(!usePipes);
2762 #endif /* RMT_WILL_WATCH */
2763 }
2764 }
2765 postCommands = Targ_FindNode(".END", TARG_CREATE);
2766 }
2767
2768 static void JobSigReset(void)
2769 {
2770 #define DELSIG(s) \
2771 if (sigismember(&caught_signals, s)) { \
2772 (void) signal(SIGINT, SIG_DFL); \
2773 }
2774
2775 DELSIG(SIGINT)
2776 DELSIG(SIGHUP)
2777 DELSIG(SIGQUIT)
2778 DELSIG(SIGTERM)
2779 #if defined(RMT_WANTS_SIGNALS) || defined(USE_PGRP)
2780 DELSIG(SIGTSTP)
2781 DELSIG(SIGTTOU)
2782 DELSIG(SIGTTIN)
2783 DELSIG(SIGWINCH)
2784 DELSIG(SIGCONT)
2785 #endif
2786 #undef DELSIG
2787 (void)signal(SIGCHLD, SIG_DFL);
2788 }
2789
2790 /*-
2791 *-----------------------------------------------------------------------
2792 * Job_Empty --
2793 * See if the job table is empty. Because the local concurrency may
2794 * be set to 0, it is possible for the job table to become empty,
2795 * while the list of stoppedJobs remains non-empty. In such a case,
2796 * we want to restart as many jobs as we can.
2797 *
2798 * Results:
2799 * TRUE if it is. FALSE if it ain't.
2800 *
2801 * Side Effects:
2802 * None.
2803 *
2804 * -----------------------------------------------------------------------
2805 */
2806 Boolean
2807 Job_Empty(void)
2808 {
2809 if (nJobs == 0) {
2810 if (!Lst_IsEmpty(stoppedJobs) && !aborting) {
2811 /*
2812 * The job table is obviously not full if it has no jobs in
2813 * it...Try and restart the stopped jobs.
2814 */
2815 JobRestartJobs();
2816 return(FALSE);
2817 } else {
2818 return(TRUE);
2819 }
2820 } else {
2821 return(FALSE);
2822 }
2823 }
2824
2825 /*-
2826 *-----------------------------------------------------------------------
2827 * JobMatchShell --
2828 * Find a shell in 'shells' given its name.
2829 *
2830 * Results:
2831 * A pointer to the Shell structure.
2832 *
2833 * Side Effects:
2834 * None.
2835 *
2836 *-----------------------------------------------------------------------
2837 */
2838 static Shell *
2839 JobMatchShell(const char *name)
2840 {
2841 Shell *sh;
2842
2843 for (sh = shells; sh->name != NULL; sh++) {
2844 if (strcmp(name, sh->name) == 0)
2845 return (sh);
2846 }
2847 return (NULL);
2848 }
2849
2850 /*-
2851 *-----------------------------------------------------------------------
2852 * Job_ParseShell --
2853 * Parse a shell specification and set up commandShell, shellPath
2854 * and shellName appropriately.
2855 *
2856 * Input:
2857 * line The shell spec
2858 *
2859 * Results:
2860 * FAILURE if the specification was incorrect.
2861 *
2862 * Side Effects:
2863 * commandShell points to a Shell structure (either predefined or
2864 * created from the shell spec), shellPath is the full path of the
2865 * shell described by commandShell, while shellName is just the
2866 * final component of shellPath.
2867 *
2868 * Notes:
2869 * A shell specification consists of a .SHELL target, with dependency
2870 * operator, followed by a series of blank-separated words. Double
2871 * quotes can be used to use blanks in words. A backslash escapes
2872 * anything (most notably a double-quote and a space) and
2873 * provides the functionality it does in C. Each word consists of
2874 * keyword and value separated by an equal sign. There should be no
2875 * unnecessary spaces in the word. The keywords are as follows:
2876 * name Name of shell.
2877 * path Location of shell.
2878 * quiet Command to turn off echoing.
2879 * echo Command to turn echoing on
2880 * filter Result of turning off echoing that shouldn't be
2881 * printed.
2882 * echoFlag Flag to turn echoing on at the start
2883 * errFlag Flag to turn error checking on at the start
2884 * hasErrCtl True if shell has error checking control
2885 * check Command to turn on error checking if hasErrCtl
2886 * is TRUE or template of command to echo a command
2887 * for which error checking is off if hasErrCtl is
2888 * FALSE.
2889 * ignore Command to turn off error checking if hasErrCtl
2890 * is TRUE or template of command to execute a
2891 * command so as to ignore any errors it returns if
2892 * hasErrCtl is FALSE.
2893 *
2894 *-----------------------------------------------------------------------
2895 */
2896 ReturnStatus
2897 Job_ParseShell(char *line)
2898 {
2899 char **words;
2900 char **argv;
2901 int argc;
2902 char *path;
2903 Shell newShell;
2904 Boolean fullSpec = FALSE;
2905 Shell *sh;
2906
2907 while (isspace((unsigned char)*line)) {
2908 line++;
2909 }
2910
2911 if (shellArgv)
2912 free(UNCONST(shellArgv));
2913
2914 memset((Address)&newShell, 0, sizeof(newShell));
2915
2916 /*
2917 * Parse the specification by keyword
2918 */
2919 words = brk_string(line, &argc, TRUE, &path);
2920 shellArgv = path;
2921
2922 for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2923 if (strncmp(*argv, "path=", 5) == 0) {
2924 path = &argv[0][5];
2925 } else if (strncmp(*argv, "name=", 5) == 0) {
2926 newShell.name = &argv[0][5];
2927 } else {
2928 if (strncmp(*argv, "quiet=", 6) == 0) {
2929 newShell.echoOff = &argv[0][6];
2930 } else if (strncmp(*argv, "echo=", 5) == 0) {
2931 newShell.echoOn = &argv[0][5];
2932 } else if (strncmp(*argv, "filter=", 7) == 0) {
2933 newShell.noPrint = &argv[0][7];
2934 newShell.noPLen = strlen(newShell.noPrint);
2935 } else if (strncmp(*argv, "echoFlag=", 9) == 0) {
2936 newShell.echo = &argv[0][9];
2937 } else if (strncmp(*argv, "errFlag=", 8) == 0) {
2938 newShell.exit = &argv[0][8];
2939 } else if (strncmp(*argv, "hasErrCtl=", 10) == 0) {
2940 char c = argv[0][10];
2941 newShell.hasErrCtl = !((c != 'Y') && (c != 'y') &&
2942 (c != 'T') && (c != 't'));
2943 } else if (strncmp(*argv, "check=", 6) == 0) {
2944 newShell.errCheck = &argv[0][6];
2945 } else if (strncmp(*argv, "ignore=", 7) == 0) {
2946 newShell.ignErr = &argv[0][7];
2947 } else if (strncmp(*argv, "errout=", 7) == 0) {
2948 newShell.errOut = &argv[0][7];
2949 } else if (strncmp(*argv, "comment=", 8) == 0) {
2950 newShell.commentChar = argv[0][8];
2951 } else {
2952 Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"",
2953 *argv);
2954 free(words);
2955 return(FAILURE);
2956 }
2957 fullSpec = TRUE;
2958 }
2959 }
2960
2961 if (path == NULL) {
2962 /*
2963 * If no path was given, the user wants one of the pre-defined shells,
2964 * yes? So we find the one s/he wants with the help of JobMatchShell
2965 * and set things up the right way. shellPath will be set up by
2966 * Job_Init.
2967 */
2968 if (newShell.name == NULL) {
2969 Parse_Error(PARSE_FATAL, "Neither path nor name specified");
2970 free(words);
2971 return(FAILURE);
2972 } else {
2973 if ((sh = JobMatchShell(newShell.name)) == NULL) {
2974 Parse_Error(PARSE_WARNING, "%s: No matching shell",
2975 newShell.name);
2976 free(words);
2977 return(FAILURE);
2978 }
2979 commandShell = sh;
2980 shellName = newShell.name;
2981 }
2982 } else {
2983 /*
2984 * The user provided a path. If s/he gave nothing else (fullSpec is
2985 * FALSE), try and find a matching shell in the ones we know of.
2986 * Else we just take the specification at its word and copy it
2987 * to a new location. In either case, we need to record the
2988 * path the user gave for the shell.
2989 */
2990 shellPath = path;
2991 path = strrchr(path, '/');
2992 if (path == NULL) {
2993 path = UNCONST(shellPath);
2994 } else {
2995 path += 1;
2996 }
2997 if (newShell.name != NULL) {
2998 shellName = newShell.name;
2999 } else {
3000 shellName = path;
3001 }
3002 if (!fullSpec) {
3003 if ((sh = JobMatchShell(shellName)) == NULL) {
3004 Parse_Error(PARSE_WARNING, "%s: No matching shell",
3005 shellName);
3006 free(words);
3007 return(FAILURE);
3008 }
3009 commandShell = sh;
3010 } else {
3011 commandShell = (Shell *) emalloc(sizeof(Shell));
3012 *commandShell = newShell;
3013 }
3014 }
3015
3016 if (commandShell->echoOn && commandShell->echoOff) {
3017 commandShell->hasEchoCtl = TRUE;
3018 }
3019
3020 if (!commandShell->hasErrCtl) {
3021 if (commandShell->errCheck == NULL) {
3022 commandShell->errCheck = "";
3023 }
3024 if (commandShell->ignErr == NULL) {
3025 commandShell->ignErr = "%s\n";
3026 }
3027 }
3028
3029 /*
3030 * Do not free up the words themselves, since they might be in use by the
3031 * shell specification.
3032 */
3033 free(words);
3034 return SUCCESS;
3035 }
3036
3037 /*-
3038 *-----------------------------------------------------------------------
3039 * JobInterrupt --
3040 * Handle the receipt of an interrupt.
3041 *
3042 * Input:
3043 * runINTERRUPT Non-zero if commands for the .INTERRUPT target
3044 * should be executed
3045 * signo signal received
3046 *
3047 * Results:
3048 * None
3049 *
3050 * Side Effects:
3051 * All children are killed. Another job will be started if the
3052 * .INTERRUPT target was given.
3053 *-----------------------------------------------------------------------
3054 */
3055 static void
3056 JobInterrupt(int runINTERRUPT, int signo)
3057 {
3058 LstNode ln; /* element in job table */
3059 Job *job; /* job descriptor in that element */
3060 GNode *interrupt; /* the node describing the .INTERRUPT target */
3061 sigset_t mask;
3062
3063 aborting = ABORT_INTERRUPT;
3064
3065 JobSigLock(&mask);
3066
3067 (void) Lst_Open(jobs);
3068 while ((ln = Lst_Next(jobs)) != NILLNODE) {
3069 GNode *gn;
3070
3071 job = (Job *) Lst_Datum(ln);
3072 gn = job->node;
3073
3074 if ((gn->type & (OP_JOIN|OP_PHONY)) == 0 && !Targ_Precious(gn)) {
3075 char *file = (gn->path == NULL ? gn->name : gn->path);
3076 if (!noExecute && eunlink(file) != -1) {
3077 Error("*** %s removed", file);
3078 }
3079 }
3080 #ifdef RMT_WANTS_SIGNALS
3081 if (job->flags & JOB_REMOTE) {
3082 /*
3083 * If job is remote, let the Rmt module do the killing.
3084 */
3085 if (!Rmt_Signal(job, signo)) {
3086 /*
3087 * If couldn't kill the thing, finish it out now with an
3088 * error code, since no exit report will come in likely.
3089 */
3090 int status;
3091
3092 status.w_status = 0;
3093 status.w_retcode = 1;
3094 JobFinish(job, &status);
3095 }
3096 } else if (job->pid) {
3097 KILL(job->pid, signo);
3098 }
3099 #else
3100 if (job->pid) {
3101 if (DEBUG(JOB)) {
3102 (void) fprintf(stdout,
3103 "JobInterrupt passing signal %d to child %d.\n",
3104 signo, job->pid);
3105 (void) fflush(stdout);
3106 }
3107 KILL(job->pid, signo);
3108 }
3109 #endif /* RMT_WANTS_SIGNALS */
3110 }
3111 Lst_Close(jobs);
3112
3113 #ifdef REMOTE
3114 (void)Lst_Open(stoppedJobs);
3115 while ((ln = Lst_Next(stoppedJobs)) != NILLNODE) {
3116 GNode *gn;
3117
3118 job = (Job *) Lst_Datum(ln);
3119 gn = job->node;
3120
3121 if (job->flags & JOB_RESTART) {
3122 if (DEBUG(JOB)) {
3123 (void) fprintf(stdout, "%s%s",
3124 "JobInterrupt skipping job on stopped queue",
3125 "-- it was waiting to be restarted.\n");
3126 (void) fflush(stdout);
3127 }
3128 continue;
3129 }
3130 if ((gn->type & (OP_JOIN|OP_PHONY)) == 0 && !Targ_Precious(gn)) {
3131 char *file = (gn->path == NULL ? gn->name : gn->path);
3132 if (eunlink(file) == 0) {
3133 Error("*** %s removed", file);
3134 }
3135 }
3136 /*
3137 * Resume the thing so it will take the signal.
3138 */
3139 if (DEBUG(JOB)) {
3140 (void) fprintf(stdout,
3141 "JobInterrupt passing CONT to stopped child %d.\n",
3142 job->pid);
3143 (void) fflush(stdout);
3144 }
3145 KILL(job->pid, SIGCONT);
3146 #ifdef RMT_WANTS_SIGNALS
3147 if (job->flags & JOB_REMOTE) {
3148 /*
3149 * If job is remote, let the Rmt module do the killing.
3150 */
3151 if (!Rmt_Signal(job, SIGINT)) {
3152 /*
3153 * If couldn't kill the thing, finish it out now with an
3154 * error code, since no exit report will come in likely.
3155 */
3156 int status;
3157 status.w_status = 0;
3158 status.w_retcode = 1;
3159 JobFinish(job, &status);
3160 }
3161 } else if (job->pid) {
3162 if (DEBUG(JOB)) {
3163 (void) fprintf(stdout,
3164 "JobInterrupt passing interrupt to stopped child %d.\n",
3165 job->pid);
3166 (void) fflush(stdout);
3167 }
3168 KILL(job->pid, SIGINT);
3169 }
3170 #endif /* RMT_WANTS_SIGNALS */
3171 }
3172 Lst_Close(stoppedJobs);
3173 #endif /* REMOTE */
3174
3175 JobSigUnlock(&mask);
3176
3177 if (runINTERRUPT && !touchFlag) {
3178 interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
3179 if (interrupt != NILGNODE) {
3180 ignoreErrors = FALSE;
3181
3182 JobStart(interrupt, JOB_IGNDOTS, (Job *)0);
3183 while (nJobs) {
3184 Job_CatchOutput();
3185 #ifndef RMT_WILL_WATCH
3186 Job_CatchChildren(!usePipes);
3187 #endif /* RMT_WILL_WATCH */
3188 }
3189 }
3190 }
3191 Trace_Log(MAKEINTR, 0);
3192 exit(signo);
3193 }
3194
3195 /*
3196 *-----------------------------------------------------------------------
3197 * Job_Finish --
3198 * Do final processing such as the running of the commands
3199 * attached to the .END target.
3200 *
3201 * Results:
3202 * Number of errors reported.
3203 *
3204 * Side Effects:
3205 * None.
3206 *-----------------------------------------------------------------------
3207 */
3208 int
3209 Job_Finish(void)
3210 {
3211 if (postCommands != NILGNODE && !Lst_IsEmpty(postCommands->commands)) {
3212 if (errors) {
3213 Error("Errors reported so .END ignored");
3214 } else {
3215 JobStart(postCommands, JOB_SPECIAL | JOB_IGNDOTS, NULL);
3216
3217 while (nJobs) {
3218 Job_CatchOutput();
3219 #ifndef RMT_WILL_WATCH
3220 Job_CatchChildren(!usePipes);
3221 #endif /* RMT_WILL_WATCH */
3222 }
3223 }
3224 }
3225 Job_TokenFlush();
3226 return(errors);
3227 }
3228
3229 /*-
3230 *-----------------------------------------------------------------------
3231 * Job_End --
3232 * Cleanup any memory used by the jobs module
3233 *
3234 * Results:
3235 * None.
3236 *
3237 * Side Effects:
3238 * Memory is freed
3239 *-----------------------------------------------------------------------
3240 */
3241 void
3242 Job_End(void)
3243 {
3244 #ifdef CLEANUP
3245 if (shellArgv)
3246 free(shellArgv);
3247 #endif
3248 }
3249
3250 /*-
3251 *-----------------------------------------------------------------------
3252 * Job_Wait --
3253 * Waits for all running jobs to finish and returns. Sets 'aborting'
3254 * to ABORT_WAIT to prevent other jobs from starting.
3255 *
3256 * Results:
3257 * None.
3258 *
3259 * Side Effects:
3260 * Currently running jobs finish.
3261 *
3262 *-----------------------------------------------------------------------
3263 */
3264 void
3265 Job_Wait(void)
3266 {
3267 aborting = ABORT_WAIT;
3268 while (nJobs != 0) {
3269 Job_CatchOutput();
3270 #ifndef RMT_WILL_WATCH
3271 Job_CatchChildren(!usePipes);
3272 #endif /* RMT_WILL_WATCH */
3273 }
3274 Job_TokenFlush();
3275 aborting = 0;
3276 }
3277
3278 /*-
3279 *-----------------------------------------------------------------------
3280 * Job_AbortAll --
3281 * Abort all currently running jobs without handling output or anything.
3282 * This function is to be called only in the event of a major
3283 * error. Most definitely NOT to be called from JobInterrupt.
3284 *
3285 * Results:
3286 * None
3287 *
3288 * Side Effects:
3289 * All children are killed, not just the firstborn
3290 *-----------------------------------------------------------------------
3291 */
3292 void
3293 Job_AbortAll(void)
3294 {
3295 LstNode ln; /* element in job table */
3296 Job *job; /* the job descriptor in that element */
3297 int foo;
3298 sigset_t mask;
3299
3300 aborting = ABORT_ERROR;
3301
3302 if (nJobs) {
3303
3304 JobSigLock(&mask);
3305 (void) Lst_Open(jobs);
3306 while ((ln = Lst_Next(jobs)) != NILLNODE) {
3307 job = (Job *) Lst_Datum(ln);
3308
3309 /*
3310 * kill the child process with increasingly drastic signals to make
3311 * darn sure it's dead.
3312 */
3313 #ifdef RMT_WANTS_SIGNALS
3314 if (job->flags & JOB_REMOTE) {
3315 Rmt_Signal(job, SIGINT);
3316 Rmt_Signal(job, SIGKILL);
3317 } else {
3318 KILL(job->pid, SIGINT);
3319 KILL(job->pid, SIGKILL);
3320 }
3321 #else
3322 KILL(job->pid, SIGINT);
3323 KILL(job->pid, SIGKILL);
3324 #endif /* RMT_WANTS_SIGNALS */
3325 }
3326 Lst_Close(jobs);
3327 JobSigUnlock(&mask);
3328 }
3329
3330 /*
3331 * Catch as many children as want to report in at first, then give up
3332 */
3333 while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
3334 continue;
3335 }
3336
3337 #ifdef REMOTE
3338 /*-
3339 *-----------------------------------------------------------------------
3340 * JobFlagForMigration --
3341 * Handle the eviction of a child. Called from RmtStatusChange.
3342 * Flags the child as remigratable and then suspends it.
3343 *
3344 * Input:
3345 * hostID ID of host we used, for matching children
3346 *
3347 * Results:
3348 * none.
3349 *
3350 * Side Effects:
3351 * The job descriptor is flagged for remigration.
3352 *
3353 *-----------------------------------------------------------------------
3354 */
3355 void
3356 JobFlagForMigration(int hostID)
3357 {
3358 Job *job; /* job descriptor for dead child */
3359 LstNode jnode; /* list element for finding job */
3360
3361 if (DEBUG(JOB)) {
3362 (void) fprintf(stdout, "JobFlagForMigration(%d) called.\n", hostID);
3363 (void) fflush(stdout);
3364 }
3365 jnode = Lst_Find(jobs, (ClientData)&hostID, JobCmpRmtID);
3366
3367 if (jnode == NILLNODE) {
3368 jnode = Lst_Find(stoppedJobs, (ClientData)hostID, JobCmpRmtID);
3369 if (jnode == NILLNODE) {
3370 if (DEBUG(JOB)) {
3371 Error("Evicting host(%d) not in table", hostID);
3372 }
3373 return;
3374 }
3375 }
3376 job = (Job *) Lst_Datum(jnode);
3377
3378 if (DEBUG(JOB)) {
3379 (void) fprintf(stdout,
3380 "JobFlagForMigration(%d) found job '%s'.\n", hostID,
3381 job->node->name);
3382 (void) fflush(stdout);
3383 }
3384
3385 KILL(job->pid, SIGSTOP);
3386
3387 job->flags |= JOB_REMIGRATE;
3388 }
3389
3390 #endif
3391
3392 /*-
3394 *-----------------------------------------------------------------------
3395 * JobRestartJobs --
3396 * Tries to restart stopped jobs if there are slots available.
3397 * Note that this tries to restart them regardless of pending errors.
3398 * It's not good to leave stopped jobs lying around!
3399 *
3400 * Results:
3401 * None.
3402 *
3403 * Side Effects:
3404 * Resumes(and possibly migrates) jobs.
3405 *
3406 *-----------------------------------------------------------------------
3407 */
3408 static void
3409 JobRestartJobs(void)
3410 {
3411 sigset_t mask;
3412
3413 JobSigLock(&mask);
3414 while (!Lst_IsEmpty(stoppedJobs)) {
3415 if (DEBUG(JOB)) {
3416 (void) fprintf(stdout, "Restarting a stopped job.\n");
3417 (void) fflush(stdout);
3418 }
3419 if (JobRestart((Job *)Lst_DeQueue(stoppedJobs)) != 0)
3420 break;
3421 }
3422 JobSigUnlock(&mask);
3423 }
3424
3425 #ifndef RMT_WILL_WATCH
3426 static void
3427 watchfd(Job *job)
3428 {
3429 int i;
3430 if (job->inPollfd != NULL)
3431 Punt("Watching watched job");
3432 if (fds == NULL) {
3433 maxfds = JBSTART;
3434 fds = emalloc(sizeof(struct pollfd) * maxfds);
3435 jobfds = emalloc(sizeof(Job **) * maxfds);
3436
3437 fds[0].fd = job_pipe[0];
3438 fds[0].events = POLLIN;
3439 jobfds[0] = &tokenWaitJob;
3440 tokenWaitJob.inPollfd = &fds[0];
3441 nfds++;
3442
3443 fds[1].fd = exit_pipe[0];
3444 fds[1].events = POLLIN;
3445 jobfds[1] = &childExitJob;
3446 childExitJob.inPollfd = &fds[1];
3447 nfds++;
3448 } else if (nfds == maxfds) {
3449 maxfds *= JBFACTOR;
3450 fds = erealloc(fds, sizeof(struct pollfd) * maxfds);
3451 jobfds = erealloc(jobfds, sizeof(Job **) * maxfds);
3452 for (i = 0; i < nfds; i++)
3453 jobfds[i]->inPollfd = &fds[i];
3454 }
3455
3456 fds[nfds].fd = job->inPipe;
3457 fds[nfds].events = POLLIN;
3458 jobfds[nfds] = job;
3459 job->inPollfd = &fds[nfds];
3460 nfds++;
3461 }
3462
3463 static void
3464 clearfd(Job *job)
3465 {
3466 int i;
3467 if (job->inPollfd == NULL)
3468 Punt("Unwatching unwatched job");
3469 i = job->inPollfd - fds;
3470 nfds--;
3471 /*
3472 * Move last job in table into hole made by dead job.
3473 */
3474 if (nfds != i) {
3475 fds[i] = fds[nfds];
3476 jobfds[i] = jobfds[nfds];
3477 jobfds[i]->inPollfd = &fds[i];
3478 }
3479 job->inPollfd = NULL;
3480 }
3481
3482 static int
3483 readyfd(Job *job)
3484 {
3485 if (job->inPollfd == NULL)
3486 Punt("Polling unwatched job");
3487 return (job->inPollfd->revents & POLLIN) != 0;
3488 }
3489 #endif
3490
3491 /*-
3492 *-----------------------------------------------------------------------
3493 * JobTokenAdd --
3494 * Put a token into the job pipe so that some make process can start
3495 * another job.
3496 *
3497 * Side Effects:
3498 * Allows more build jobs to be spawned somewhere.
3499 *
3500 *-----------------------------------------------------------------------
3501 */
3502
3503 static void
3504 JobTokenAdd(void)
3505 {
3506
3507 if (DEBUG(JOB))
3508 printf("deposit token\n");
3509 write(job_pipe[1], "+", 1);
3510 }
3511
3512 /*-
3513 *-----------------------------------------------------------------------
3514 * Job_ServerStartTokenAdd --
3515 * Prep the job token pipe in the root make process.
3516 *
3517 *-----------------------------------------------------------------------
3518 */
3519
3520 void
3521 Job_ServerStart(int maxproc)
3522 {
3523 int i, flags;
3524 char jobarg[64];
3525
3526 if (pipe(job_pipe) < 0)
3527 Fatal ("error in pipe: %s", strerror(errno));
3528
3529 /*
3530 * We mark the input side of the pipe non-blocking; we poll(2) the
3531 * pipe when we're waiting for a job token, but we might lose the
3532 * race for the token when a new one becomes available, so the read
3533 * from the pipe should not block.
3534 */
3535 flags = fcntl(job_pipe[0], F_GETFL, 0);
3536 flags |= O_NONBLOCK;
3537 fcntl(job_pipe[0], F_SETFL, flags);
3538
3539 /*
3540 * Mark job pipes as close-on-exec.
3541 * Note that we will clear this when executing submakes.
3542 */
3543 fcntl(job_pipe[0], F_SETFD, 1);
3544 fcntl(job_pipe[1], F_SETFD, 1);
3545
3546 snprintf(jobarg, sizeof(jobarg), "%d,%d", job_pipe[0], job_pipe[1]);
3547
3548 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
3549 Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
3550
3551 /*
3552 * Preload job_pipe with one token per job, save the one
3553 * "extra" token for the primary job.
3554 *
3555 * XXX should clip maxJobs against PIPE_BUF -- if maxJobs is
3556 * larger than the write buffer size of the pipe, we will
3557 * deadlock here.
3558 */
3559 for (i=1; i < maxproc; i++)
3560 JobTokenAdd();
3561 }
3562
3563 /*
3564 * this tracks the number of tokens currently "out" to build jobs.
3565 */
3566 int jobTokensRunning = 0;
3567 int jobTokensFree = 0;
3568 /*-
3569 *-----------------------------------------------------------------------
3570 * Job_TokenReturn --
3571 * Return a withdrawn token to the pool.
3572 *
3573 *-----------------------------------------------------------------------
3574 */
3575
3576 void
3577 Job_TokenReturn(void)
3578 {
3579 jobTokensRunning--;
3580 if (jobTokensRunning < 0)
3581 Punt("token botch");
3582 if (jobTokensRunning)
3583 jobTokensFree++;
3584 }
3585
3586 /*-
3587 *-----------------------------------------------------------------------
3588 * Job_TokenWithdraw --
3589 * Attempt to withdraw a token from the pool.
3590 *
3591 * Results:
3592 * Returns TRUE if a token was withdrawn, and FALSE if the pool
3593 * is currently empty.
3594 *
3595 * Side Effects:
3596 * If pool is empty, set wantToken so that we wake up
3597 * when a token is released.
3598 *
3599 *-----------------------------------------------------------------------
3600 */
3601
3602
3603 Boolean
3604 Job_TokenWithdraw(void)
3605 {
3606 char tok;
3607 int count;
3608
3609 wantToken = FALSE;
3610
3611 if (aborting)
3612 return FALSE;
3613
3614 if (jobTokensRunning == 0) {
3615 if (DEBUG(JOB))
3616 printf("first one's free\n");
3617 jobTokensRunning++;
3618 return TRUE;
3619 }
3620 if (jobTokensFree > 0) {
3621 jobTokensFree--;
3622 jobTokensRunning++;
3623 return TRUE;
3624 }
3625 count = read(job_pipe[0], &tok, 1);
3626 if (count == 0)
3627 Fatal("eof on job pipe!");
3628 else if (count < 0) {
3629 if (errno != EAGAIN) {
3630 Fatal("job pipe read: %s", strerror(errno));
3631 }
3632 if (DEBUG(JOB))
3633 printf("blocked for token\n");
3634 wantToken = TRUE;
3635 return FALSE;
3636 }
3637 jobTokensRunning++;
3638 if (DEBUG(JOB))
3639 printf("withdrew token\n");
3640 return TRUE;
3641 }
3642
3643 /*-
3644 *-----------------------------------------------------------------------
3645 * Job_TokenFlush --
3646 * Return free tokens to the pool.
3647 *
3648 *-----------------------------------------------------------------------
3649 */
3650
3651 void
3652 Job_TokenFlush(void)
3653 {
3654 if (compatMake) return;
3655
3656 while (jobTokensFree > 0) {
3657 JobTokenAdd();
3658 jobTokensFree--;
3659 }
3660 }
3661
3662 #ifdef USE_SELECT
3663 int
3664 emul_poll(struct pollfd *fd, int nfd, int timeout)
3665 {
3666 fd_set rfds, wfds;
3667 int i, maxfd, nselect, npoll;
3668 struct timeval tv, *tvp;
3669 long usecs;
3670
3671 FD_ZERO(&rfds);
3672 FD_ZERO(&wfds);
3673
3674 maxfd = -1;
3675 for (i = 0; i < nfd; i++) {
3676 fd[i].revents = 0;
3677
3678 if (fd[i].events & POLLIN)
3679 FD_SET(fd[i].fd, &rfds);
3680
3681 if (fd[i].events & POLLOUT)
3682 FD_SET(fd[i].fd, &wfds);
3683
3684 if (fd[i].fd > maxfd)
3685 maxfd = fd[i].fd;
3686 }
3687
3688 if (maxfd >= FD_SETSIZE) {
3689 Punt("Ran out of fd_set slots; "
3690 "recompile with a larger FD_SETSIZE.");
3691 }
3692
3693 if (timeout < 0) {
3694 tvp = NULL;
3695 } else {
3696 usecs = timeout * 1000;
3697 tv.tv_sec = usecs / 1000000;
3698 tv.tv_usec = usecs % 1000000;
3699 tvp = &tv;
3700 }
3701
3702 nselect = select(maxfd + 1, &rfds, &wfds, 0, tvp);
3703
3704 if (nselect <= 0)
3705 return nselect;
3706
3707 npoll = 0;
3708 for (i = 0; i < nfd; i++) {
3709 if (FD_ISSET(fd[i].fd, &rfds))
3710 fd[i].revents |= POLLIN;
3711
3712 if (FD_ISSET(fd[i].fd, &wfds))
3713 fd[i].revents |= POLLOUT;
3714
3715 if (fd[i].revents)
3716 npoll++;
3717 }
3718
3719 return npoll;
3720 }
3721 #endif /* USE_SELECT */
3722