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