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