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