job.c revision 1.492 1 1.492 rillig /* $NetBSD: job.c,v 1.492 2025/04/12 13:00:21 rillig Exp $ */
2 1.10 christos
3 1.1 cgd /*
4 1.1 cgd * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5 1.82 agc * All rights reserved.
6 1.82 agc *
7 1.82 agc * This code is derived from software contributed to Berkeley by
8 1.82 agc * Adam de Boor.
9 1.82 agc *
10 1.82 agc * Redistribution and use in source and binary forms, with or without
11 1.82 agc * modification, are permitted provided that the following conditions
12 1.82 agc * are met:
13 1.82 agc * 1. Redistributions of source code must retain the above copyright
14 1.82 agc * notice, this list of conditions and the following disclaimer.
15 1.82 agc * 2. Redistributions in binary form must reproduce the above copyright
16 1.82 agc * notice, this list of conditions and the following disclaimer in the
17 1.82 agc * documentation and/or other materials provided with the distribution.
18 1.82 agc * 3. Neither the name of the University nor the names of its contributors
19 1.82 agc * may be used to endorse or promote products derived from this software
20 1.82 agc * without specific prior written permission.
21 1.82 agc *
22 1.82 agc * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 1.82 agc * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 1.82 agc * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 1.82 agc * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 1.82 agc * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 1.82 agc * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 1.82 agc * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 1.82 agc * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 1.82 agc * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 1.82 agc * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 1.82 agc * SUCH DAMAGE.
33 1.82 agc */
34 1.82 agc
35 1.82 agc /*
36 1.1 cgd * Copyright (c) 1988, 1989 by Adam de Boor
37 1.1 cgd * Copyright (c) 1989 by Berkeley Softworks
38 1.1 cgd * All rights reserved.
39 1.1 cgd *
40 1.1 cgd * This code is derived from software contributed to Berkeley by
41 1.1 cgd * Adam de Boor.
42 1.1 cgd *
43 1.1 cgd * Redistribution and use in source and binary forms, with or without
44 1.1 cgd * modification, are permitted provided that the following conditions
45 1.1 cgd * are met:
46 1.1 cgd * 1. Redistributions of source code must retain the above copyright
47 1.1 cgd * notice, this list of conditions and the following disclaimer.
48 1.1 cgd * 2. Redistributions in binary form must reproduce the above copyright
49 1.1 cgd * notice, this list of conditions and the following disclaimer in the
50 1.1 cgd * documentation and/or other materials provided with the distribution.
51 1.1 cgd * 3. All advertising materials mentioning features or use of this software
52 1.1 cgd * must display the following acknowledgement:
53 1.1 cgd * This product includes software developed by the University of
54 1.1 cgd * California, Berkeley and its contributors.
55 1.1 cgd * 4. Neither the name of the University nor the names of its contributors
56 1.1 cgd * may be used to endorse or promote products derived from this software
57 1.1 cgd * without specific prior written permission.
58 1.1 cgd *
59 1.1 cgd * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 1.1 cgd * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 1.1 cgd * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 1.1 cgd * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 1.1 cgd * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 1.1 cgd * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 1.1 cgd * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 1.1 cgd * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 1.1 cgd * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 1.1 cgd * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 1.1 cgd * SUCH DAMAGE.
70 1.1 cgd */
71 1.1 cgd
72 1.398 rillig /*
73 1.461 rillig * Create child processes and collect their output.
74 1.1 cgd *
75 1.1 cgd * Interface:
76 1.278 rillig * Job_Init Called to initialize this module. In addition,
77 1.461 rillig * the .BEGIN target is made, including all of its
78 1.407 rillig * dependencies before this function returns.
79 1.278 rillig * Hence, the makefiles must have been parsed
80 1.278 rillig * before this function is called.
81 1.278 rillig *
82 1.278 rillig * Job_End Clean up any memory used.
83 1.278 rillig *
84 1.246 rillig * Job_Make Start the creation of the given target.
85 1.1 cgd *
86 1.246 rillig * Job_CatchChildren
87 1.246 rillig * Check for and handle the termination of any
88 1.246 rillig * children. This must be called reasonably
89 1.246 rillig * frequently to keep the whole make going at
90 1.246 rillig * a decent clip, since job table entries aren't
91 1.246 rillig * removed until their process is caught this way.
92 1.246 rillig *
93 1.246 rillig * Job_CatchOutput
94 1.246 rillig * Print any output our children have produced.
95 1.246 rillig * Should also be called fairly frequently to
96 1.246 rillig * keep the user informed of what's going on.
97 1.246 rillig * If no output is waiting, it will block for
98 1.246 rillig * a time given by the SEL_* constants, below,
99 1.246 rillig * or until output is ready.
100 1.246 rillig *
101 1.407 rillig * Job_ParseShell Given a special dependency line with target '.SHELL',
102 1.407 rillig * define the shell that is used for the creation
103 1.407 rillig * commands in jobs mode.
104 1.246 rillig *
105 1.487 rillig * Job_Finish Make the .END target. Should only be called when the
106 1.246 rillig * job table is empty.
107 1.246 rillig *
108 1.407 rillig * Job_AbortAll Abort all currently running jobs. Do not handle
109 1.407 rillig * output or do anything for the jobs, just kill them.
110 1.407 rillig * Should only be called in an emergency.
111 1.246 rillig *
112 1.246 rillig * Job_CheckCommands
113 1.246 rillig * Verify that the commands for a target are
114 1.246 rillig * ok. Provide them if necessary and possible.
115 1.1 cgd *
116 1.246 rillig * Job_Touch Update a target without really updating it.
117 1.1 cgd *
118 1.246 rillig * Job_Wait Wait for all currently-running jobs to finish.
119 1.1 cgd */
120 1.1 cgd
121 1.5 cgd #include <sys/types.h>
122 1.1 cgd #include <sys/stat.h>
123 1.1 cgd #include <sys/file.h>
124 1.1 cgd #include <sys/time.h>
125 1.1 cgd #include <sys/wait.h>
126 1.72 wiz
127 1.72 wiz #include <errno.h>
128 1.35 christos #ifndef USE_SELECT
129 1.35 christos #include <poll.h>
130 1.35 christos #endif
131 1.72 wiz #include <signal.h>
132 1.72 wiz #include <utime.h>
133 1.72 wiz
134 1.5 cgd #include "make.h"
135 1.5 cgd #include "dir.h"
136 1.1 cgd #include "job.h"
137 1.1 cgd #include "pathnames.h"
138 1.40 sommerfe #include "trace.h"
139 1.232 rillig
140 1.232 rillig /* "@(#)job.c 8.2 (Berkeley) 3/19/94" */
141 1.492 rillig MAKE_RCSID("$NetBSD: job.c,v 1.492 2025/04/12 13:00:21 rillig Exp $");
142 1.1 cgd
143 1.341 rillig /*
144 1.341 rillig * A shell defines how the commands are run. All commands for a target are
145 1.275 rillig * written into a single file, which is then given to the shell to execute
146 1.275 rillig * the commands from it. The commands are written to the file using a few
147 1.275 rillig * templates for echo control and error control.
148 1.275 rillig *
149 1.275 rillig * The name of the shell is the basename for the predefined shells, such as
150 1.275 rillig * "sh", "csh", "bash". For custom shells, it is the full pathname, and its
151 1.275 rillig * basename is used to select the type of shell; the longest match wins.
152 1.275 rillig * So /usr/pkg/bin/bash has type sh, /usr/local/bin/tcsh has type csh.
153 1.275 rillig *
154 1.275 rillig * The echoing of command lines is controlled using hasEchoCtl, echoOff,
155 1.275 rillig * echoOn, noPrint and noPrintLen. When echoOff is executed by the shell, it
156 1.275 rillig * still outputs something, but this something is not interesting, therefore
157 1.275 rillig * it is filtered out using noPrint and noPrintLen.
158 1.275 rillig *
159 1.275 rillig * The error checking for individual commands is controlled using hasErrCtl,
160 1.364 rillig * errOn, errOff and runChkTmpl.
161 1.275 rillig *
162 1.407 rillig * In case a shell doesn't have error control, echoTmpl is a printf template
163 1.407 rillig * for echoing the command, should echoing be on; runIgnTmpl is another
164 1.407 rillig * printf template for executing the command while ignoring the return
165 1.364 rillig * status. Finally runChkTmpl is a printf template for running the command and
166 1.275 rillig * causing the shell to exit on error. If any of these strings are empty when
167 1.421 rillig * hasErrCtl is false, the command will be executed anyway as is, and if it
168 1.319 rillig * causes an error, so be it. Any templates set up to echo the command will
169 1.407 rillig * escape any '$ ` \ "' characters in the command string to avoid unwanted
170 1.407 rillig * shell code injection, the escaped command is safe to use in double quotes.
171 1.275 rillig *
172 1.275 rillig * The command-line flags "echo" and "exit" also control the behavior. The
173 1.275 rillig * "echo" flag causes the shell to start echoing commands right away. The
174 1.275 rillig * "exit" flag causes the shell to exit when an error is detected in one of
175 1.275 rillig * the commands.
176 1.266 rillig */
177 1.266 rillig typedef struct Shell {
178 1.272 rillig
179 1.341 rillig /*
180 1.341 rillig * The name of the shell. For Bourne and C shells, this is used only
181 1.341 rillig * to find the shell description when used as the single source of a
182 1.341 rillig * .SHELL target. For user-defined shells, this is the full path of
183 1.341 rillig * the shell.
184 1.341 rillig */
185 1.341 rillig const char *name;
186 1.341 rillig
187 1.421 rillig bool hasEchoCtl; /* whether both echoOff and echoOn are there */
188 1.365 rillig const char *echoOff; /* command to turn echoing off */
189 1.365 rillig const char *echoOn; /* command to turn echoing back on */
190 1.375 rillig const char *noPrint; /* text to skip when printing output from the
191 1.272 rillig * shell. This is usually the same as echoOff */
192 1.341 rillig size_t noPrintLen; /* length of noPrint command */
193 1.272 rillig
194 1.421 rillig bool hasErrCtl; /* whether error checking can be controlled
195 1.375 rillig * for individual commands */
196 1.359 rillig const char *errOn; /* command to turn on error checking */
197 1.359 rillig const char *errOff; /* command to turn off error checking */
198 1.364 rillig
199 1.364 rillig const char *echoTmpl; /* template to echo a command */
200 1.443 rillig const char *runIgnTmpl; /* template to run a command without error
201 1.443 rillig * checking */
202 1.443 rillig const char *runChkTmpl; /* template to run a command with error
203 1.443 rillig * checking */
204 1.266 rillig
205 1.443 rillig /*
206 1.443 rillig * A string literal that results in a newline character when it
207 1.443 rillig * occurs outside of any 'quote' or "quote" characters.
208 1.443 rillig */
209 1.341 rillig const char *newline;
210 1.341 rillig char commentChar; /* character used by shell for comment lines */
211 1.341 rillig
212 1.366 rillig const char *echoFlag; /* shell flag to echo commands */
213 1.375 rillig const char *errFlag; /* shell flag to exit on error */
214 1.266 rillig } Shell;
215 1.266 rillig
216 1.360 rillig typedef struct CommandFlags {
217 1.407 rillig /* Whether to echo the command before or instead of running it. */
218 1.421 rillig bool echo;
219 1.348 rillig
220 1.360 rillig /* Run the command even in -n or -N mode. */
221 1.421 rillig bool always;
222 1.349 rillig
223 1.349 rillig /*
224 1.429 rillig * true if we turned error checking off before writing the command to
225 1.429 rillig * the commands file and need to turn it back on
226 1.349 rillig */
227 1.421 rillig bool ignerr;
228 1.360 rillig } CommandFlags;
229 1.347 rillig
230 1.1 cgd /*
231 1.371 rillig * Write shell commands to a file.
232 1.371 rillig *
233 1.371 rillig * TODO: keep track of whether commands are echoed.
234 1.371 rillig * TODO: keep track of whether error checking is active.
235 1.371 rillig */
236 1.371 rillig typedef struct ShellWriter {
237 1.371 rillig FILE *f;
238 1.374 rillig
239 1.374 rillig /* we've sent 'set -x' */
240 1.421 rillig bool xtraced;
241 1.374 rillig
242 1.371 rillig } ShellWriter;
243 1.371 rillig
244 1.461 rillig /* error handling variables */
245 1.331 rillig static int job_errors = 0; /* number of errors reported */
246 1.427 rillig static enum { /* Why is the make aborting? */
247 1.341 rillig ABORT_NONE,
248 1.427 rillig ABORT_ERROR, /* Aborted because of an error */
249 1.427 rillig ABORT_INTERRUPT, /* Aborted because it was interrupted */
250 1.341 rillig ABORT_WAIT /* Waiting for jobs to finish */
251 1.427 rillig } aborting = ABORT_NONE;
252 1.341 rillig #define JOB_TOKENS "+EI+" /* Token to requeue for each abort state */
253 1.1 cgd
254 1.461 rillig /* Tracks the number of tokens currently "out" to build jobs. */
255 1.103 dsl int jobTokensRunning = 0;
256 1.103 dsl
257 1.1 cgd /*
258 1.1 cgd * Descriptions for various shells.
259 1.121 apb *
260 1.133 apb * The build environment may set DEFSHELL_INDEX to one of
261 1.133 apb * DEFSHELL_INDEX_SH, DEFSHELL_INDEX_KSH, or DEFSHELL_INDEX_CSH, to
262 1.243 rillig * select one of the predefined shells as the default shell.
263 1.133 apb *
264 1.133 apb * Alternatively, the build environment may set DEFSHELL_CUSTOM to the
265 1.133 apb * name or the full path of a sh-compatible shell, which will be used as
266 1.133 apb * the default shell.
267 1.133 apb *
268 1.133 apb * ".SHELL" lines in Makefiles can choose the default shell from the
269 1.289 rillig * set defined here, or add additional shells.
270 1.133 apb */
271 1.133 apb
272 1.133 apb #ifdef DEFSHELL_CUSTOM
273 1.133 apb #define DEFSHELL_INDEX_CUSTOM 0
274 1.133 apb #define DEFSHELL_INDEX_SH 1
275 1.133 apb #define DEFSHELL_INDEX_KSH 2
276 1.133 apb #define DEFSHELL_INDEX_CSH 3
277 1.461 rillig #else
278 1.133 apb #define DEFSHELL_INDEX_SH 0
279 1.133 apb #define DEFSHELL_INDEX_KSH 1
280 1.133 apb #define DEFSHELL_INDEX_CSH 2
281 1.461 rillig #endif
282 1.133 apb
283 1.133 apb #ifndef DEFSHELL_INDEX
284 1.133 apb #define DEFSHELL_INDEX 0 /* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */
285 1.461 rillig #endif
286 1.133 apb
287 1.341 rillig static Shell shells[] = {
288 1.133 apb #ifdef DEFSHELL_CUSTOM
289 1.1 cgd /*
290 1.121 apb * An sh-compatible shell with a non-standard name.
291 1.121 apb *
292 1.121 apb * Keep this in sync with the "sh" description below, but avoid
293 1.121 apb * non-portable features that might not be supplied by all
294 1.121 apb * sh-compatible shells.
295 1.1 cgd */
296 1.341 rillig {
297 1.341 rillig DEFSHELL_CUSTOM, /* .name */
298 1.421 rillig false, /* .hasEchoCtl */
299 1.341 rillig "", /* .echoOff */
300 1.341 rillig "", /* .echoOn */
301 1.341 rillig "", /* .noPrint */
302 1.341 rillig 0, /* .noPrintLen */
303 1.421 rillig false, /* .hasErrCtl */
304 1.358 rillig "", /* .errOn */
305 1.359 rillig "", /* .errOff */
306 1.364 rillig "echo \"%s\"\n", /* .echoTmpl */
307 1.364 rillig "%s\n", /* .runIgnTmpl */
308 1.364 rillig "{ %s \n} || exit $?\n", /* .runChkTmpl */
309 1.341 rillig "'\n'", /* .newline */
310 1.341 rillig '#', /* .commentChar */
311 1.375 rillig "", /* .echoFlag */
312 1.375 rillig "", /* .errFlag */
313 1.341 rillig },
314 1.133 apb #endif /* DEFSHELL_CUSTOM */
315 1.1 cgd /*
316 1.1 cgd * SH description. Echo control is also possible and, under
317 1.1 cgd * sun UNIX anyway, one can even control error checking.
318 1.1 cgd */
319 1.341 rillig {
320 1.341 rillig "sh", /* .name */
321 1.421 rillig false, /* .hasEchoCtl */
322 1.341 rillig "", /* .echoOff */
323 1.341 rillig "", /* .echoOn */
324 1.341 rillig "", /* .noPrint */
325 1.341 rillig 0, /* .noPrintLen */
326 1.421 rillig false, /* .hasErrCtl */
327 1.358 rillig "", /* .errOn */
328 1.359 rillig "", /* .errOff */
329 1.364 rillig "echo \"%s\"\n", /* .echoTmpl */
330 1.364 rillig "%s\n", /* .runIgnTmpl */
331 1.364 rillig "{ %s \n} || exit $?\n", /* .runChkTmpl */
332 1.341 rillig "'\n'", /* .newline */
333 1.341 rillig '#', /* .commentChar*/
334 1.121 apb #if defined(MAKE_NATIVE) && defined(__NetBSD__)
335 1.375 rillig /* XXX: -q is not really echoFlag, it's more like noEchoInSysFlag. */
336 1.375 rillig "q", /* .echoFlag */
337 1.27 christos #else
338 1.375 rillig "", /* .echoFlag */
339 1.27 christos #endif
340 1.375 rillig "", /* .errFlag */
341 1.341 rillig },
342 1.1 cgd /*
343 1.201 rillig * KSH description.
344 1.81 sjg */
345 1.341 rillig {
346 1.341 rillig "ksh", /* .name */
347 1.421 rillig true, /* .hasEchoCtl */
348 1.341 rillig "set +v", /* .echoOff */
349 1.341 rillig "set -v", /* .echoOn */
350 1.341 rillig "set +v", /* .noPrint */
351 1.341 rillig 6, /* .noPrintLen */
352 1.421 rillig false, /* .hasErrCtl */
353 1.358 rillig "", /* .errOn */
354 1.359 rillig "", /* .errOff */
355 1.364 rillig "echo \"%s\"\n", /* .echoTmpl */
356 1.364 rillig "%s\n", /* .runIgnTmpl */
357 1.364 rillig "{ %s \n} || exit $?\n", /* .runChkTmpl */
358 1.341 rillig "'\n'", /* .newline */
359 1.341 rillig '#', /* .commentChar */
360 1.375 rillig "v", /* .echoFlag */
361 1.375 rillig "", /* .errFlag */
362 1.341 rillig },
363 1.81 sjg /*
364 1.121 apb * CSH description. The csh can do echo control by playing
365 1.121 apb * with the setting of the 'echo' shell variable. Sadly,
366 1.121 apb * however, it is unable to do error control nicely.
367 1.121 apb */
368 1.341 rillig {
369 1.341 rillig "csh", /* .name */
370 1.421 rillig true, /* .hasEchoCtl */
371 1.341 rillig "unset verbose", /* .echoOff */
372 1.341 rillig "set verbose", /* .echoOn */
373 1.341 rillig "unset verbose", /* .noPrint */
374 1.341 rillig 13, /* .noPrintLen */
375 1.421 rillig false, /* .hasErrCtl */
376 1.358 rillig "", /* .errOn */
377 1.359 rillig "", /* .errOff */
378 1.364 rillig "echo \"%s\"\n", /* .echoTmpl */
379 1.364 rillig "csh -c \"%s || exit 0\"\n", /* .runIgnTmpl */
380 1.364 rillig "", /* .runChkTmpl */
381 1.341 rillig "'\\\n'", /* .newline */
382 1.341 rillig '#', /* .commentChar */
383 1.375 rillig "v", /* .echoFlag */
384 1.375 rillig "e", /* .errFlag */
385 1.341 rillig }
386 1.1 cgd };
387 1.243 rillig
388 1.391 rillig /*
389 1.391 rillig * This is the shell to which we pass all commands in the Makefile.
390 1.391 rillig * It is set by the Job_ParseShell function.
391 1.391 rillig */
392 1.355 rillig static Shell *shell = &shells[DEFSHELL_INDEX];
393 1.478 rillig char *shellPath; /* full pathname of executable image */
394 1.243 rillig const char *shellName = NULL; /* last component of shellPath */
395 1.174 sjg char *shellErrFlag = NULL;
396 1.407 rillig static char *shell_freeIt = NULL; /* Allocated memory for custom .SHELL */
397 1.1 cgd
398 1.1 cgd
399 1.285 rillig static Job *job_table; /* The structures that describe them */
400 1.285 rillig static Job *job_table_end; /* job_table + maxJobs */
401 1.492 rillig static bool wantToken;
402 1.421 rillig static bool lurking_children = false;
403 1.421 rillig static bool make_suspended = false; /* Whether we've seen a SIGTSTP (etc) */
404 1.40 sommerfe
405 1.35 christos /*
406 1.35 christos * Set of descriptors of pipes connected to
407 1.35 christos * the output channels of children
408 1.35 christos */
409 1.35 christos static struct pollfd *fds = NULL;
410 1.408 rillig static Job **jobByFdIndex = NULL;
411 1.408 rillig static nfds_t fdsLen = 0;
412 1.72 wiz static void watchfd(Job *);
413 1.72 wiz static void clearfd(Job *);
414 1.1 cgd
415 1.443 rillig static char *targPrefix = NULL; /* To identify a job change in the output. */
416 1.40 sommerfe static Job tokenWaitJob; /* token wait pseudo-job */
417 1.12 christos
418 1.73 gson static Job childExitJob; /* child exit pseudo-job */
419 1.341 rillig #define CHILD_EXIT "."
420 1.341 rillig #define DO_JOB_RESUME "R"
421 1.73 gson
422 1.341 rillig enum {
423 1.341 rillig npseudojobs = 2 /* number of pseudo-jobs */
424 1.341 rillig };
425 1.196 riastrad
426 1.104 dsl static sigset_t caught_signals; /* Set of signals we handle */
427 1.406 sjg static volatile sig_atomic_t caught_sigchld;
428 1.1 cgd
429 1.424 rillig static void CollectOutput(Job *, bool);
430 1.421 rillig static void JobInterrupt(bool, int) MAKE_ATTR_DEAD;
431 1.72 wiz static void JobRestartJobs(void);
432 1.69 pk static void JobSigReset(void);
433 1.69 pk
434 1.339 rillig static void
435 1.340 rillig SwitchOutputTo(GNode *gn)
436 1.339 rillig {
437 1.340 rillig /* The node for which output was most recently produced. */
438 1.340 rillig static GNode *lastNode = NULL;
439 1.340 rillig
440 1.340 rillig if (gn == lastNode)
441 1.340 rillig return;
442 1.340 rillig lastNode = gn;
443 1.340 rillig
444 1.339 rillig if (opts.maxJobs != 1 && targPrefix != NULL && targPrefix[0] != '\0')
445 1.339 rillig (void)fprintf(stdout, "%s %s ---\n", targPrefix, gn->name);
446 1.339 rillig }
447 1.339 rillig
448 1.196 riastrad static unsigned
449 1.196 riastrad nfds_per_job(void)
450 1.196 riastrad {
451 1.197 sjg #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
452 1.341 rillig if (useMeta)
453 1.341 rillig return 2;
454 1.196 riastrad #endif
455 1.341 rillig return 1;
456 1.196 riastrad }
457 1.196 riastrad
458 1.354 rillig void
459 1.356 rillig Job_FlagsToString(const Job *job, char *buf, size_t bufsize)
460 1.354 rillig {
461 1.374 rillig snprintf(buf, bufsize, "%c%c%c",
462 1.356 rillig job->ignerr ? 'i' : '-',
463 1.357 rillig !job->echo ? 's' : '-',
464 1.374 rillig job->special ? 'S' : '-');
465 1.354 rillig }
466 1.354 rillig
467 1.114 dsl static void
468 1.428 rillig DumpJobs(const char *where)
469 1.114 dsl {
470 1.341 rillig Job *job;
471 1.374 rillig char flags[4];
472 1.114 dsl
473 1.341 rillig debug_printf("job table @ %s\n", where);
474 1.341 rillig for (job = job_table; job < job_table_end; job++) {
475 1.356 rillig Job_FlagsToString(job, flags, sizeof flags);
476 1.354 rillig debug_printf("job %d, status %d, flags %s, pid %d\n",
477 1.354 rillig (int)(job - job_table), job->status, flags, job->pid);
478 1.341 rillig }
479 1.114 dsl }
480 1.69 pk
481 1.69 pk /*
482 1.188 dholland * Delete the target of a failed, interrupted, or otherwise
483 1.188 dholland * unsuccessful job unless inhibited by .PRECIOUS.
484 1.188 dholland */
485 1.188 dholland static void
486 1.188 dholland JobDeleteTarget(GNode *gn)
487 1.188 dholland {
488 1.341 rillig const char *file;
489 1.341 rillig
490 1.341 rillig if (gn->type & OP_JOIN)
491 1.341 rillig return;
492 1.341 rillig if (gn->type & OP_PHONY)
493 1.341 rillig return;
494 1.447 rillig if (GNode_IsPrecious(gn))
495 1.341 rillig return;
496 1.341 rillig if (opts.noExecute)
497 1.341 rillig return;
498 1.287 rillig
499 1.341 rillig file = GNode_Path(gn);
500 1.456 rillig if (unlink_file(file) == 0)
501 1.341 rillig Error("*** %s removed", file);
502 1.188 dholland }
503 1.188 dholland
504 1.188 dholland /*
505 1.69 pk * JobSigLock/JobSigUnlock
506 1.69 pk *
507 1.69 pk * Signal lock routines to get exclusive access. Currently used to
508 1.69 pk * protect `jobs' and `stoppedJobs' list manipulations.
509 1.69 pk */
510 1.388 rillig static void
511 1.388 rillig JobSigLock(sigset_t *omaskp)
512 1.69 pk {
513 1.69 pk if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) {
514 1.69 pk Punt("JobSigLock: sigprocmask: %s", strerror(errno));
515 1.104 dsl sigemptyset(omaskp);
516 1.69 pk }
517 1.69 pk }
518 1.69 pk
519 1.388 rillig static void
520 1.388 rillig JobSigUnlock(sigset_t *omaskp)
521 1.69 pk {
522 1.96 christos (void)sigprocmask(SIG_SETMASK, omaskp, NULL);
523 1.69 pk }
524 1.1 cgd
525 1.122 dsl static void
526 1.122 dsl JobCreatePipe(Job *job, int minfd)
527 1.122 dsl {
528 1.341 rillig int i, fd, flags;
529 1.341 rillig int pipe_fds[2];
530 1.122 dsl
531 1.341 rillig if (pipe(pipe_fds) == -1)
532 1.341 rillig Punt("Cannot create pipe: %s", strerror(errno));
533 1.122 dsl
534 1.341 rillig for (i = 0; i < 2; i++) {
535 1.461 rillig /* Avoid using low-numbered fds */
536 1.341 rillig fd = fcntl(pipe_fds[i], F_DUPFD, minfd);
537 1.341 rillig if (fd != -1) {
538 1.341 rillig close(pipe_fds[i]);
539 1.341 rillig pipe_fds[i] = fd;
540 1.341 rillig }
541 1.247 rillig }
542 1.201 rillig
543 1.341 rillig job->inPipe = pipe_fds[0];
544 1.341 rillig job->outPipe = pipe_fds[1];
545 1.249 rillig
546 1.341 rillig if (fcntl(job->inPipe, F_SETFD, FD_CLOEXEC) == -1)
547 1.341 rillig Punt("Cannot set close-on-exec: %s", strerror(errno));
548 1.341 rillig if (fcntl(job->outPipe, F_SETFD, FD_CLOEXEC) == -1)
549 1.341 rillig Punt("Cannot set close-on-exec: %s", strerror(errno));
550 1.341 rillig
551 1.341 rillig /*
552 1.341 rillig * We mark the input side of the pipe non-blocking; we poll(2) the
553 1.341 rillig * pipe when we're waiting for a job token, but we might lose the
554 1.341 rillig * race for the token when a new one becomes available, so the read
555 1.341 rillig * from the pipe should not block.
556 1.341 rillig */
557 1.341 rillig flags = fcntl(job->inPipe, F_GETFL, 0);
558 1.341 rillig if (flags == -1)
559 1.341 rillig Punt("Cannot get flags: %s", strerror(errno));
560 1.341 rillig flags |= O_NONBLOCK;
561 1.341 rillig if (fcntl(job->inPipe, F_SETFL, flags) == -1)
562 1.341 rillig Punt("Cannot set flags: %s", strerror(errno));
563 1.122 dsl }
564 1.122 dsl
565 1.243 rillig /* Pass the signal to each running job. */
566 1.114 dsl static void
567 1.114 dsl JobCondPassSig(int signo)
568 1.1 cgd {
569 1.341 rillig Job *job;
570 1.106 dsl
571 1.341 rillig DEBUG1(JOB, "JobCondPassSig(%d) called.\n", signo);
572 1.116 dsl
573 1.341 rillig for (job = job_table; job < job_table_end; job++) {
574 1.341 rillig if (job->status != JOB_ST_RUNNING)
575 1.341 rillig continue;
576 1.341 rillig DEBUG2(JOB, "JobCondPassSig passing signal %d to child %d.\n",
577 1.341 rillig signo, job->pid);
578 1.341 rillig KILLPG(job->pid, signo);
579 1.341 rillig }
580 1.1 cgd }
581 1.1 cgd
582 1.341 rillig /*
583 1.341 rillig * SIGCHLD handler.
584 1.37 sommerfe *
585 1.341 rillig * Sends a token on the child exit pipe to wake us up from select()/poll().
586 1.341 rillig */
587 1.37 sommerfe static void
588 1.162 joerg JobChildSig(int signo MAKE_ATTR_UNUSED)
589 1.37 sommerfe {
590 1.405 sjg caught_sigchld = 1;
591 1.341 rillig while (write(childExitJob.outPipe, CHILD_EXIT, 1) == -1 &&
592 1.341 rillig errno == EAGAIN)
593 1.341 rillig continue;
594 1.37 sommerfe }
595 1.37 sommerfe
596 1.37 sommerfe
597 1.243 rillig /* Resume all stopped jobs. */
598 1.47 sommerfe static void
599 1.162 joerg JobContinueSig(int signo MAKE_ATTR_UNUSED)
600 1.47 sommerfe {
601 1.341 rillig /*
602 1.341 rillig * Defer sending SIGCONT to our stopped children until we return
603 1.341 rillig * from the signal handler.
604 1.341 rillig */
605 1.341 rillig while (write(childExitJob.outPipe, DO_JOB_RESUME, 1) == -1 &&
606 1.341 rillig errno == EAGAIN)
607 1.341 rillig continue;
608 1.47 sommerfe }
609 1.37 sommerfe
610 1.341 rillig /*
611 1.341 rillig * Pass a signal on to all jobs, then resend to ourselves.
612 1.341 rillig * We die by the same signal.
613 1.341 rillig */
614 1.162 joerg MAKE_ATTR_DEAD static void
615 1.116 dsl JobPassSig_int(int signo)
616 1.116 dsl {
617 1.341 rillig /* Run .INTERRUPT target then exit */
618 1.421 rillig JobInterrupt(true, signo);
619 1.116 dsl }
620 1.116 dsl
621 1.341 rillig /*
622 1.341 rillig * Pass a signal on to all jobs, then resend to ourselves.
623 1.341 rillig * We die by the same signal.
624 1.341 rillig */
625 1.162 joerg MAKE_ATTR_DEAD static void
626 1.116 dsl JobPassSig_term(int signo)
627 1.116 dsl {
628 1.341 rillig /* Dont run .INTERRUPT target then exit */
629 1.421 rillig JobInterrupt(false, signo);
630 1.116 dsl }
631 1.116 dsl
632 1.116 dsl static void
633 1.116 dsl JobPassSig_suspend(int signo)
634 1.1 cgd {
635 1.341 rillig sigset_t nmask, omask;
636 1.341 rillig struct sigaction act;
637 1.118 dsl
638 1.341 rillig /* Suppress job started/continued messages */
639 1.421 rillig make_suspended = true;
640 1.16 christos
641 1.341 rillig /* Pass the signal onto every job */
642 1.341 rillig JobCondPassSig(signo);
643 1.1 cgd
644 1.341 rillig /*
645 1.341 rillig * Send ourselves the signal now we've given the message to everyone
646 1.341 rillig * else. Note we block everything else possible while we're getting
647 1.341 rillig * the signal. This ensures that all our jobs get continued when we
648 1.341 rillig * wake up before we take any other signal.
649 1.341 rillig */
650 1.341 rillig sigfillset(&nmask);
651 1.341 rillig sigdelset(&nmask, signo);
652 1.341 rillig (void)sigprocmask(SIG_SETMASK, &nmask, &omask);
653 1.341 rillig
654 1.341 rillig act.sa_handler = SIG_DFL;
655 1.341 rillig sigemptyset(&act.sa_mask);
656 1.341 rillig act.sa_flags = 0;
657 1.341 rillig (void)sigaction(signo, &act, NULL);
658 1.13 christos
659 1.487 rillig DEBUG1(JOB, "JobPassSig_suspend passing signal %d to self.\n", signo);
660 1.1 cgd
661 1.341 rillig (void)kill(getpid(), signo);
662 1.115 dsl
663 1.341 rillig /*
664 1.341 rillig * We've been continued.
665 1.341 rillig *
666 1.461 rillig * A whole host of signals is going to happen!
667 1.341 rillig * SIGCHLD for any processes that actually suspended themselves.
668 1.461 rillig * SIGCHLD for any processes that exited while we were asleep.
669 1.461 rillig * The SIGCONT that actually caused us to wake up.
670 1.341 rillig *
671 1.341 rillig * Since we defer passing the SIGCONT on to our children until
672 1.341 rillig * the main processing loop, we can be sure that all the SIGCHLD
673 1.341 rillig * events will have happened by then - and that the waitpid() will
674 1.341 rillig * collect the child 'suspended' events.
675 1.341 rillig * For correct sequencing we just need to ensure we process the
676 1.341 rillig * waitpid() before passing on the SIGCONT.
677 1.341 rillig *
678 1.341 rillig * In any case nothing else is needed here.
679 1.341 rillig */
680 1.1 cgd
681 1.341 rillig /* Restore handler and signal mask */
682 1.341 rillig act.sa_handler = JobPassSig_suspend;
683 1.341 rillig (void)sigaction(signo, &act, NULL);
684 1.341 rillig (void)sigprocmask(SIG_SETMASK, &omask, NULL);
685 1.1 cgd }
686 1.1 cgd
687 1.114 dsl static Job *
688 1.421 rillig JobFindPid(int pid, JobStatus status, bool isJobs)
689 1.1 cgd {
690 1.341 rillig Job *job;
691 1.114 dsl
692 1.341 rillig for (job = job_table; job < job_table_end; job++) {
693 1.341 rillig if (job->status == status && job->pid == pid)
694 1.341 rillig return job;
695 1.341 rillig }
696 1.341 rillig if (DEBUG(JOB) && isJobs)
697 1.428 rillig DumpJobs("no pid");
698 1.341 rillig return NULL;
699 1.12 christos }
700 1.12 christos
701 1.298 rillig /* Parse leading '@', '-' and '+', which control the exact execution mode. */
702 1.298 rillig static void
703 1.383 rillig ParseCommandFlags(char **pp, CommandFlags *out_cmdFlags)
704 1.341 rillig {
705 1.341 rillig char *p = *pp;
706 1.421 rillig out_cmdFlags->echo = true;
707 1.421 rillig out_cmdFlags->ignerr = false;
708 1.421 rillig out_cmdFlags->always = false;
709 1.341 rillig
710 1.341 rillig for (;;) {
711 1.341 rillig if (*p == '@')
712 1.360 rillig out_cmdFlags->echo = DEBUG(LOUD);
713 1.341 rillig else if (*p == '-')
714 1.421 rillig out_cmdFlags->ignerr = true;
715 1.341 rillig else if (*p == '+')
716 1.421 rillig out_cmdFlags->always = true;
717 1.457 christos else if (!ch_isspace(*p))
718 1.461 rillig /* Ignore whitespace for compatibility with GNU make */
719 1.341 rillig break;
720 1.341 rillig p++;
721 1.341 rillig }
722 1.298 rillig
723 1.341 rillig pp_skip_whitespace(&p);
724 1.298 rillig
725 1.341 rillig *pp = p;
726 1.298 rillig }
727 1.298 rillig
728 1.299 rillig /* Escape a string for a double-quoted string literal in sh, csh and ksh. */
729 1.299 rillig static char *
730 1.299 rillig EscapeShellDblQuot(const char *cmd)
731 1.299 rillig {
732 1.341 rillig size_t i, j;
733 1.299 rillig
734 1.341 rillig /* Worst that could happen is every char needs escaping. */
735 1.341 rillig char *esc = bmake_malloc(strlen(cmd) * 2 + 1);
736 1.341 rillig for (i = 0, j = 0; cmd[i] != '\0'; i++, j++) {
737 1.341 rillig if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' ||
738 1.341 rillig cmd[i] == '"')
739 1.341 rillig esc[j++] = '\\';
740 1.341 rillig esc[j] = cmd[i];
741 1.341 rillig }
742 1.341 rillig esc[j] = '\0';
743 1.299 rillig
744 1.341 rillig return esc;
745 1.299 rillig }
746 1.299 rillig
747 1.318 rillig static void
748 1.429 rillig ShellWriter_WriteFmt(ShellWriter *wr, const char *fmt, const char *arg)
749 1.318 rillig {
750 1.343 rillig DEBUG1(JOB, fmt, arg);
751 1.318 rillig
752 1.371 rillig (void)fprintf(wr->f, fmt, arg);
753 1.436 sjg if (wr->f == stdout)
754 1.436 sjg (void)fflush(wr->f);
755 1.371 rillig }
756 1.371 rillig
757 1.371 rillig static void
758 1.429 rillig ShellWriter_WriteLine(ShellWriter *wr, const char *line)
759 1.318 rillig {
760 1.429 rillig ShellWriter_WriteFmt(wr, "%s\n", line);
761 1.318 rillig }
762 1.318 rillig
763 1.373 rillig static void
764 1.373 rillig ShellWriter_EchoOff(ShellWriter *wr)
765 1.373 rillig {
766 1.373 rillig if (shell->hasEchoCtl)
767 1.429 rillig ShellWriter_WriteLine(wr, shell->echoOff);
768 1.373 rillig }
769 1.373 rillig
770 1.373 rillig static void
771 1.373 rillig ShellWriter_EchoCmd(ShellWriter *wr, const char *escCmd)
772 1.373 rillig {
773 1.429 rillig ShellWriter_WriteFmt(wr, shell->echoTmpl, escCmd);
774 1.373 rillig }
775 1.373 rillig
776 1.373 rillig static void
777 1.373 rillig ShellWriter_EchoOn(ShellWriter *wr)
778 1.373 rillig {
779 1.373 rillig if (shell->hasEchoCtl)
780 1.429 rillig ShellWriter_WriteLine(wr, shell->echoOn);
781 1.373 rillig }
782 1.373 rillig
783 1.374 rillig static void
784 1.374 rillig ShellWriter_TraceOn(ShellWriter *wr)
785 1.374 rillig {
786 1.374 rillig if (!wr->xtraced) {
787 1.429 rillig ShellWriter_WriteLine(wr, "set -x");
788 1.421 rillig wr->xtraced = true;
789 1.374 rillig }
790 1.374 rillig }
791 1.374 rillig
792 1.346 rillig static void
793 1.421 rillig ShellWriter_ErrOff(ShellWriter *wr, bool echo)
794 1.346 rillig {
795 1.382 rillig if (echo)
796 1.373 rillig ShellWriter_EchoOff(wr);
797 1.429 rillig ShellWriter_WriteLine(wr, shell->errOff);
798 1.382 rillig if (echo)
799 1.382 rillig ShellWriter_EchoOn(wr);
800 1.382 rillig }
801 1.382 rillig
802 1.382 rillig static void
803 1.421 rillig ShellWriter_ErrOn(ShellWriter *wr, bool echo)
804 1.382 rillig {
805 1.382 rillig if (echo)
806 1.382 rillig ShellWriter_EchoOff(wr);
807 1.429 rillig ShellWriter_WriteLine(wr, shell->errOn);
808 1.382 rillig if (echo)
809 1.373 rillig ShellWriter_EchoOn(wr);
810 1.346 rillig }
811 1.346 rillig
812 1.346 rillig /*
813 1.384 rillig * The shell has no built-in error control, so emulate error control by
814 1.384 rillig * enclosing each shell command in a template like "{ %s \n } || exit $?"
815 1.384 rillig * (configurable per shell).
816 1.346 rillig */
817 1.346 rillig static void
818 1.429 rillig JobWriteSpecialsEchoCtl(Job *job, ShellWriter *wr, CommandFlags *inout_cmdFlags,
819 1.360 rillig const char *escCmd, const char **inout_cmdTemplate)
820 1.346 rillig {
821 1.452 rillig /* XXX: Why is the whole job modified at this point? */
822 1.421 rillig job->ignerr = true;
823 1.346 rillig
824 1.360 rillig if (job->echo && inout_cmdFlags->echo) {
825 1.373 rillig ShellWriter_EchoOff(wr);
826 1.373 rillig ShellWriter_EchoCmd(wr, escCmd);
827 1.384 rillig
828 1.384 rillig /*
829 1.384 rillig * Leave echoing off so the user doesn't see the commands
830 1.384 rillig * for toggling the error checking.
831 1.384 rillig */
832 1.421 rillig inout_cmdFlags->echo = false;
833 1.346 rillig }
834 1.364 rillig *inout_cmdTemplate = shell->runIgnTmpl;
835 1.346 rillig
836 1.346 rillig /*
837 1.364 rillig * The template runIgnTmpl already takes care of ignoring errors,
838 1.364 rillig * so pretend error checking is still on.
839 1.364 rillig * XXX: What effects does this have, and why is it necessary?
840 1.346 rillig */
841 1.421 rillig inout_cmdFlags->ignerr = false;
842 1.346 rillig }
843 1.346 rillig
844 1.345 rillig static void
845 1.429 rillig JobWriteSpecials(Job *job, ShellWriter *wr, const char *escCmd, bool run,
846 1.370 rillig CommandFlags *inout_cmdFlags, const char **inout_cmdTemplate)
847 1.345 rillig {
848 1.462 rillig if (!run)
849 1.421 rillig inout_cmdFlags->ignerr = false;
850 1.462 rillig else if (shell->hasErrCtl)
851 1.373 rillig ShellWriter_ErrOff(wr, job->echo && inout_cmdFlags->echo);
852 1.364 rillig else if (shell->runIgnTmpl != NULL && shell->runIgnTmpl[0] != '\0') {
853 1.429 rillig JobWriteSpecialsEchoCtl(job, wr, inout_cmdFlags, escCmd,
854 1.349 rillig inout_cmdTemplate);
855 1.346 rillig } else
856 1.421 rillig inout_cmdFlags->ignerr = false;
857 1.345 rillig }
858 1.345 rillig
859 1.338 rillig /*
860 1.429 rillig * Write a shell command to the job's commands file, to be run later.
861 1.72 wiz *
862 1.358 rillig * If the command starts with '@' and neither the -s nor the -n flag was
863 1.429 rillig * given to make, stick a shell-specific echoOff command in the script.
864 1.358 rillig *
865 1.358 rillig * If the command starts with '-' and the shell has no error control (none
866 1.429 rillig * of the predefined shells has that), ignore errors for the entire job.
867 1.358 rillig *
868 1.429 rillig * XXX: Why ignore errors for the entire job? This is even documented in the
869 1.429 rillig * manual page, but without any rationale since there is no known rationale.
870 1.429 rillig *
871 1.429 rillig * XXX: The manual page says the '-' "affects the entire job", but that's not
872 1.429 rillig * accurate. The '-' does not affect the commands before the '-'.
873 1.429 rillig *
874 1.429 rillig * If the command is just "...", skip all further commands of this job. These
875 1.429 rillig * commands are attached to the .END node instead and will be run by
876 1.429 rillig * Job_Finish after all other targets have been made.
877 1.1 cgd */
878 1.270 rillig static void
879 1.429 rillig JobWriteCommand(Job *job, ShellWriter *wr, StringListNode *ln, const char *ucmd)
880 1.1 cgd {
881 1.421 rillig bool run;
882 1.347 rillig
883 1.360 rillig CommandFlags cmdFlags;
884 1.429 rillig /* Template for writing a command to the shell file */
885 1.341 rillig const char *cmdTemplate;
886 1.363 rillig char *xcmd; /* The expanded command */
887 1.363 rillig char *xcmdStart;
888 1.363 rillig char *escCmd; /* xcmd escaped to be used in double quotes */
889 1.1 cgd
890 1.351 rillig run = GNode_ShouldExecute(job->node);
891 1.298 rillig
892 1.476 rillig xcmd = Var_SubstInTarget(ucmd, job->node);
893 1.341 rillig /* TODO: handle errors */
894 1.363 rillig xcmdStart = xcmd;
895 1.1 cgd
896 1.341 rillig cmdTemplate = "%s\n";
897 1.83 jmc
898 1.383 rillig ParseCommandFlags(&xcmd, &cmdFlags);
899 1.83 jmc
900 1.351 rillig /* The '+' command flag overrides the -n or -N options. */
901 1.360 rillig if (cmdFlags.always && !run) {
902 1.341 rillig /*
903 1.341 rillig * We're not actually executing anything...
904 1.341 rillig * but this one needs to be - use compat mode just for it.
905 1.341 rillig */
906 1.441 rillig (void)Compat_RunCommand(ucmd, job->node, ln);
907 1.363 rillig free(xcmdStart);
908 1.341 rillig return;
909 1.1 cgd }
910 1.1 cgd
911 1.341 rillig /*
912 1.363 rillig * If the shell doesn't have error control, the alternate echoing
913 1.363 rillig * will be done (to avoid showing additional error checking code)
914 1.363 rillig * and this needs some characters escaped.
915 1.341 rillig */
916 1.363 rillig escCmd = shell->hasErrCtl ? NULL : EscapeShellDblQuot(xcmd);
917 1.341 rillig
918 1.360 rillig if (!cmdFlags.echo) {
919 1.463 rillig if (job->echo && run && shell->hasEchoCtl)
920 1.373 rillig ShellWriter_EchoOff(wr);
921 1.463 rillig else if (shell->hasErrCtl)
922 1.463 rillig cmdFlags.echo = true;
923 1.341 rillig }
924 1.341 rillig
925 1.360 rillig if (cmdFlags.ignerr) {
926 1.429 rillig JobWriteSpecials(job, wr, escCmd, run, &cmdFlags, &cmdTemplate);
927 1.341 rillig } else {
928 1.341 rillig
929 1.1 cgd /*
930 1.341 rillig * If errors are being checked and the shell doesn't have
931 1.364 rillig * error control but does supply an runChkTmpl template, then
932 1.341 rillig * set up commands to run through it.
933 1.341 rillig */
934 1.341 rillig
935 1.396 rillig if (!shell->hasErrCtl && shell->runChkTmpl != NULL &&
936 1.364 rillig shell->runChkTmpl[0] != '\0') {
937 1.360 rillig if (job->echo && cmdFlags.echo) {
938 1.373 rillig ShellWriter_EchoOff(wr);
939 1.373 rillig ShellWriter_EchoCmd(wr, escCmd);
940 1.421 rillig cmdFlags.echo = false;
941 1.341 rillig }
942 1.341 rillig /*
943 1.367 rillig * If it's a comment line or blank, avoid the possible
944 1.381 rillig * syntax error generated by "{\n} || exit $?".
945 1.341 rillig */
946 1.367 rillig cmdTemplate = escCmd[0] == shell->commentChar ||
947 1.367 rillig escCmd[0] == '\0'
948 1.367 rillig ? shell->runIgnTmpl
949 1.367 rillig : shell->runChkTmpl;
950 1.421 rillig cmdFlags.ignerr = false;
951 1.341 rillig }
952 1.1 cgd }
953 1.83 jmc
954 1.374 rillig if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0)
955 1.374 rillig ShellWriter_TraceOn(wr);
956 1.16 christos
957 1.429 rillig ShellWriter_WriteFmt(wr, cmdTemplate, xcmd);
958 1.363 rillig free(xcmdStart);
959 1.341 rillig free(escCmd);
960 1.382 rillig
961 1.382 rillig if (cmdFlags.ignerr)
962 1.382 rillig ShellWriter_ErrOn(wr, cmdFlags.echo && job->echo);
963 1.382 rillig
964 1.373 rillig if (!cmdFlags.echo)
965 1.373 rillig ShellWriter_EchoOn(wr);
966 1.269 rillig }
967 1.269 rillig
968 1.341 rillig /*
969 1.429 rillig * Write all commands to the shell file that is later executed.
970 1.270 rillig *
971 1.429 rillig * The special command "..." stops writing and saves the remaining commands
972 1.409 rillig * to be executed later, when the target '.END' is made.
973 1.362 rillig *
974 1.362 rillig * Return whether at least one command was written to the shell file.
975 1.341 rillig */
976 1.421 rillig static bool
977 1.429 rillig JobWriteCommands(Job *job)
978 1.269 rillig {
979 1.341 rillig StringListNode *ln;
980 1.421 rillig bool seen = false;
981 1.422 rillig ShellWriter wr;
982 1.422 rillig
983 1.422 rillig wr.f = job->cmdFILE;
984 1.422 rillig wr.xtraced = false;
985 1.341 rillig
986 1.341 rillig for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
987 1.341 rillig const char *cmd = ln->datum;
988 1.269 rillig
989 1.341 rillig if (strcmp(cmd, "...") == 0) {
990 1.341 rillig job->node->type |= OP_SAVE_CMDS;
991 1.341 rillig job->tailCmds = ln->next;
992 1.341 rillig break;
993 1.341 rillig }
994 1.270 rillig
995 1.429 rillig JobWriteCommand(job, &wr, ln, ln->datum);
996 1.421 rillig seen = true;
997 1.314 rillig }
998 1.362 rillig
999 1.362 rillig return seen;
1000 1.1 cgd }
1001 1.1 cgd
1002 1.403 rillig /*
1003 1.403 rillig * Save the delayed commands (those after '...'), to be executed later in
1004 1.403 rillig * the '.END' node, when everything else is done.
1005 1.403 rillig */
1006 1.236 rillig static void
1007 1.236 rillig JobSaveCommands(Job *job)
1008 1.1 cgd {
1009 1.341 rillig StringListNode *ln;
1010 1.236 rillig
1011 1.341 rillig for (ln = job->tailCmds; ln != NULL; ln = ln->next) {
1012 1.341 rillig const char *cmd = ln->datum;
1013 1.341 rillig char *expanded_cmd;
1014 1.403 rillig /*
1015 1.403 rillig * XXX: This Var_Subst is only intended to expand the dynamic
1016 1.341 rillig * variables such as .TARGET, .IMPSRC. It is not intended to
1017 1.403 rillig * expand the other variables as well; see deptgt-end.mk.
1018 1.403 rillig */
1019 1.476 rillig expanded_cmd = Var_SubstInTarget(cmd, job->node);
1020 1.341 rillig /* TODO: handle errors */
1021 1.341 rillig Lst_Append(&Targ_GetEndNode()->commands, expanded_cmd);
1022 1.473 rillig Parse_RegisterCommand(expanded_cmd);
1023 1.341 rillig }
1024 1.12 christos }
1025 1.12 christos
1026 1.12 christos
1027 1.243 rillig /* Called to close both input and output pipes when a job is finished. */
1028 1.12 christos static void
1029 1.320 rillig JobClosePipes(Job *job)
1030 1.12 christos {
1031 1.341 rillig clearfd(job);
1032 1.341 rillig (void)close(job->outPipe);
1033 1.341 rillig job->outPipe = -1;
1034 1.341 rillig
1035 1.424 rillig CollectOutput(job, true);
1036 1.341 rillig (void)close(job->inPipe);
1037 1.341 rillig job->inPipe = -1;
1038 1.1 cgd }
1039 1.1 cgd
1040 1.378 rillig static void
1041 1.430 christos DebugFailedJob(const Job *job)
1042 1.430 christos {
1043 1.432 rillig const StringListNode *ln;
1044 1.430 christos
1045 1.430 christos if (!DEBUG(ERROR))
1046 1.430 christos return;
1047 1.430 christos
1048 1.437 rillig debug_printf("\n");
1049 1.437 rillig debug_printf("*** Failed target: %s\n", job->node->name);
1050 1.469 rillig debug_printf("*** In directory: %s\n", curdir);
1051 1.437 rillig debug_printf("*** Failed commands:\n");
1052 1.437 rillig for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
1053 1.439 rillig const char *cmd = ln->datum;
1054 1.439 rillig debug_printf("\t%s\n", cmd);
1055 1.437 rillig
1056 1.439 rillig if (strchr(cmd, '$') != NULL) {
1057 1.475 rillig char *xcmd = Var_Subst(cmd, job->node, VARE_EVAL);
1058 1.439 rillig debug_printf("\t=> %s\n", xcmd);
1059 1.439 rillig free(xcmd);
1060 1.437 rillig }
1061 1.437 rillig }
1062 1.430 christos }
1063 1.430 christos
1064 1.430 christos static void
1065 1.379 rillig JobFinishDoneExitedError(Job *job, int *inout_status)
1066 1.378 rillig {
1067 1.379 rillig SwitchOutputTo(job->node);
1068 1.378 rillig #ifdef USE_META
1069 1.379 rillig if (useMeta) {
1070 1.379 rillig meta_job_error(job, job->node,
1071 1.379 rillig job->ignerr, WEXITSTATUS(*inout_status));
1072 1.379 rillig }
1073 1.378 rillig #endif
1074 1.379 rillig if (!shouldDieQuietly(job->node, -1)) {
1075 1.430 christos DebugFailedJob(job);
1076 1.379 rillig (void)printf("*** [%s] Error code %d%s\n",
1077 1.379 rillig job->node->name, WEXITSTATUS(*inout_status),
1078 1.379 rillig job->ignerr ? " (ignored)" : "");
1079 1.379 rillig }
1080 1.379 rillig
1081 1.379 rillig if (job->ignerr)
1082 1.379 rillig *inout_status = 0;
1083 1.379 rillig else {
1084 1.379 rillig if (deleteOnError)
1085 1.379 rillig JobDeleteTarget(job->node);
1086 1.449 rillig PrintOnError(job->node, "\n");
1087 1.379 rillig }
1088 1.379 rillig }
1089 1.379 rillig
1090 1.379 rillig static void
1091 1.379 rillig JobFinishDoneExited(Job *job, int *inout_status)
1092 1.379 rillig {
1093 1.379 rillig DEBUG2(JOB, "Process %d [%s] exited.\n", job->pid, job->node->name);
1094 1.379 rillig
1095 1.379 rillig if (WEXITSTATUS(*inout_status) != 0)
1096 1.379 rillig JobFinishDoneExitedError(job, inout_status);
1097 1.379 rillig else if (DEBUG(JOB)) {
1098 1.378 rillig SwitchOutputTo(job->node);
1099 1.379 rillig (void)printf("*** [%s] Completed successfully\n",
1100 1.379 rillig job->node->name);
1101 1.378 rillig }
1102 1.379 rillig }
1103 1.379 rillig
1104 1.379 rillig static void
1105 1.379 rillig JobFinishDoneSignaled(Job *job, int status)
1106 1.379 rillig {
1107 1.379 rillig SwitchOutputTo(job->node);
1108 1.430 christos DebugFailedJob(job);
1109 1.379 rillig (void)printf("*** [%s] Signal %d\n", job->node->name, WTERMSIG(status));
1110 1.379 rillig if (deleteOnError)
1111 1.379 rillig JobDeleteTarget(job->node);
1112 1.379 rillig }
1113 1.379 rillig
1114 1.379 rillig static void
1115 1.379 rillig JobFinishDone(Job *job, int *inout_status)
1116 1.379 rillig {
1117 1.379 rillig if (WIFEXITED(*inout_status))
1118 1.379 rillig JobFinishDoneExited(job, inout_status);
1119 1.379 rillig else
1120 1.379 rillig JobFinishDoneSignaled(job, *inout_status);
1121 1.378 rillig
1122 1.378 rillig (void)fflush(stdout);
1123 1.378 rillig }
1124 1.378 rillig
1125 1.341 rillig /*
1126 1.341 rillig * Do final processing for the given job including updating parent nodes and
1127 1.320 rillig * starting new jobs as available/necessary.
1128 1.320 rillig *
1129 1.320 rillig * Deferred commands for the job are placed on the .END node.
1130 1.320 rillig *
1131 1.331 rillig * If there was a serious error (job_errors != 0; not an ignored one), no more
1132 1.320 rillig * jobs will be started.
1133 1.1 cgd *
1134 1.72 wiz * Input:
1135 1.72 wiz * job job to finish
1136 1.72 wiz * status sub-why job went away
1137 1.1 cgd */
1138 1.5 cgd static void
1139 1.116 dsl JobFinish(Job *job, int status)
1140 1.1 cgd {
1141 1.421 rillig bool done, return_job_token;
1142 1.1 cgd
1143 1.341 rillig DEBUG3(JOB, "JobFinish: %d [%s], status %d\n",
1144 1.341 rillig job->pid, job->node->name, status);
1145 1.116 dsl
1146 1.341 rillig if ((WIFEXITED(status) &&
1147 1.356 rillig ((WEXITSTATUS(status) != 0 && !job->ignerr))) ||
1148 1.341 rillig WIFSIGNALED(status)) {
1149 1.377 rillig /* Finished because of an error. */
1150 1.377 rillig
1151 1.341 rillig JobClosePipes(job);
1152 1.341 rillig if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1153 1.436 sjg if (fclose(job->cmdFILE) != 0)
1154 1.436 sjg Punt("Cannot write shell script for '%s': %s",
1155 1.436 sjg job->node->name, strerror(errno));
1156 1.341 rillig job->cmdFILE = NULL;
1157 1.341 rillig }
1158 1.421 rillig done = true;
1159 1.377 rillig
1160 1.341 rillig } else if (WIFEXITED(status)) {
1161 1.341 rillig /*
1162 1.341 rillig * Deal with ignored errors in -B mode. We need to print a
1163 1.341 rillig * message telling of the ignored error as well as to run
1164 1.341 rillig * the next command.
1165 1.341 rillig */
1166 1.341 rillig done = WEXITSTATUS(status) != 0;
1167 1.377 rillig
1168 1.341 rillig JobClosePipes(job);
1169 1.377 rillig
1170 1.341 rillig } else {
1171 1.377 rillig /* No need to close things down or anything. */
1172 1.421 rillig done = false;
1173 1.1 cgd }
1174 1.16 christos
1175 1.378 rillig if (done)
1176 1.378 rillig JobFinishDone(job, &status);
1177 1.16 christos
1178 1.156 sjg #ifdef USE_META
1179 1.341 rillig if (useMeta) {
1180 1.341 rillig int meta_status = meta_job_finish(job);
1181 1.341 rillig if (meta_status != 0 && status == 0)
1182 1.341 rillig status = meta_status;
1183 1.341 rillig }
1184 1.156 sjg #endif
1185 1.201 rillig
1186 1.421 rillig return_job_token = false;
1187 1.102 dsl
1188 1.341 rillig Trace_Log(JOBEND, job);
1189 1.356 rillig if (!job->special) {
1190 1.341 rillig if (status != 0 ||
1191 1.341 rillig (aborting == ABORT_ERROR) || aborting == ABORT_INTERRUPT)
1192 1.421 rillig return_job_token = true;
1193 1.341 rillig }
1194 1.1 cgd
1195 1.341 rillig if (aborting != ABORT_ERROR && aborting != ABORT_INTERRUPT &&
1196 1.341 rillig (status == 0)) {
1197 1.341 rillig /*
1198 1.341 rillig * As long as we aren't aborting and the job didn't return a
1199 1.341 rillig * non-zero status that we shouldn't ignore, we call
1200 1.341 rillig * Make_Update to update the parents.
1201 1.341 rillig */
1202 1.341 rillig JobSaveCommands(job);
1203 1.341 rillig job->node->made = MADE;
1204 1.356 rillig if (!job->special)
1205 1.421 rillig return_job_token = true;
1206 1.341 rillig Make_Update(job->node);
1207 1.341 rillig job->status = JOB_ST_FREE;
1208 1.341 rillig } else if (status != 0) {
1209 1.341 rillig job_errors++;
1210 1.341 rillig job->status = JOB_ST_FREE;
1211 1.341 rillig }
1212 1.341 rillig
1213 1.341 rillig if (job_errors > 0 && !opts.keepgoing && aborting != ABORT_INTERRUPT) {
1214 1.341 rillig /* Prevent more jobs from getting started. */
1215 1.341 rillig aborting = ABORT_ERROR;
1216 1.341 rillig }
1217 1.1 cgd
1218 1.341 rillig if (return_job_token)
1219 1.341 rillig Job_TokenReturn();
1220 1.16 christos
1221 1.487 rillig if (aborting == ABORT_ERROR && jobTokensRunning == 0) {
1222 1.487 rillig if (shouldDieQuietly(NULL, -1)) {
1223 1.491 rillig Job_Wait();
1224 1.487 rillig exit(2);
1225 1.487 rillig }
1226 1.487 rillig Fatal("%d error%s", job_errors, job_errors == 1 ? "" : "s");
1227 1.487 rillig }
1228 1.321 rillig }
1229 1.321 rillig
1230 1.321 rillig static void
1231 1.321 rillig TouchRegular(GNode *gn)
1232 1.321 rillig {
1233 1.341 rillig const char *file = GNode_Path(gn);
1234 1.422 rillig struct utimbuf times;
1235 1.341 rillig int fd;
1236 1.341 rillig char c;
1237 1.341 rillig
1238 1.422 rillig times.actime = now;
1239 1.422 rillig times.modtime = now;
1240 1.341 rillig if (utime(file, ×) >= 0)
1241 1.341 rillig return;
1242 1.321 rillig
1243 1.341 rillig fd = open(file, O_RDWR | O_CREAT, 0666);
1244 1.341 rillig if (fd < 0) {
1245 1.341 rillig (void)fprintf(stderr, "*** couldn't touch %s: %s\n",
1246 1.341 rillig file, strerror(errno));
1247 1.341 rillig (void)fflush(stderr);
1248 1.341 rillig return; /* XXX: What about propagating the error? */
1249 1.341 rillig }
1250 1.341 rillig
1251 1.443 rillig /*
1252 1.443 rillig * Last resort: update the file's time stamps in the traditional way.
1253 1.341 rillig * XXX: This doesn't work for empty files, which are sometimes used
1254 1.443 rillig * as marker files.
1255 1.443 rillig */
1256 1.341 rillig if (read(fd, &c, 1) == 1) {
1257 1.341 rillig (void)lseek(fd, 0, SEEK_SET);
1258 1.341 rillig while (write(fd, &c, 1) == -1 && errno == EAGAIN)
1259 1.341 rillig continue;
1260 1.341 rillig }
1261 1.341 rillig (void)close(fd); /* XXX: What about propagating the error? */
1262 1.1 cgd }
1263 1.1 cgd
1264 1.391 rillig /*
1265 1.484 rillig * Touch the given target. Called by Job_Make when the -t flag was given.
1266 1.1 cgd *
1267 1.243 rillig * The modification date of the file is changed.
1268 1.391 rillig * If the file did not exist, it is created.
1269 1.391 rillig */
1270 1.1 cgd void
1271 1.421 rillig Job_Touch(GNode *gn, bool echo)
1272 1.1 cgd {
1273 1.341 rillig if (gn->type &
1274 1.341 rillig (OP_JOIN | OP_USE | OP_USEBEFORE | OP_EXEC | OP_OPTIONAL |
1275 1.341 rillig OP_SPECIAL | OP_PHONY)) {
1276 1.341 rillig /*
1277 1.341 rillig * These are "virtual" targets and should not really be
1278 1.341 rillig * created.
1279 1.341 rillig */
1280 1.341 rillig return;
1281 1.341 rillig }
1282 1.16 christos
1283 1.357 rillig if (echo || !GNode_ShouldExecute(gn)) {
1284 1.341 rillig (void)fprintf(stdout, "touch %s\n", gn->name);
1285 1.341 rillig (void)fflush(stdout);
1286 1.341 rillig }
1287 1.1 cgd
1288 1.341 rillig if (!GNode_ShouldExecute(gn))
1289 1.341 rillig return;
1290 1.1 cgd
1291 1.380 rillig if (gn->type & OP_ARCHV)
1292 1.341 rillig Arch_Touch(gn);
1293 1.380 rillig else if (gn->type & OP_LIB)
1294 1.341 rillig Arch_TouchLib(gn);
1295 1.380 rillig else
1296 1.380 rillig TouchRegular(gn);
1297 1.1 cgd }
1298 1.1 cgd
1299 1.391 rillig /*
1300 1.391 rillig * Make sure the given node has all the commands it needs.
1301 1.243 rillig *
1302 1.243 rillig * The node will have commands from the .DEFAULT rule added to it if it
1303 1.243 rillig * needs them.
1304 1.1 cgd *
1305 1.72 wiz * Input:
1306 1.72 wiz * gn The target whose commands need verifying
1307 1.72 wiz * abortProc Function to abort with message
1308 1.72 wiz *
1309 1.1 cgd * Results:
1310 1.421 rillig * true if the commands list is/was ok.
1311 1.1 cgd */
1312 1.421 rillig bool
1313 1.77 christos Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
1314 1.1 cgd {
1315 1.341 rillig if (GNode_IsTarget(gn))
1316 1.421 rillig return true;
1317 1.341 rillig if (!Lst_IsEmpty(&gn->commands))
1318 1.421 rillig return true;
1319 1.341 rillig if ((gn->type & OP_LIB) && !Lst_IsEmpty(&gn->children))
1320 1.421 rillig return true;
1321 1.280 rillig
1322 1.281 rillig /*
1323 1.341 rillig * No commands. Look for .DEFAULT rule from which we might infer
1324 1.341 rillig * commands.
1325 1.281 rillig */
1326 1.341 rillig if (defaultNode != NULL && !Lst_IsEmpty(&defaultNode->commands) &&
1327 1.341 rillig !(gn->type & OP_SPECIAL)) {
1328 1.341 rillig /*
1329 1.341 rillig * The traditional Make only looks for a .DEFAULT if the node
1330 1.341 rillig * was never the target of an operator, so that's what we do
1331 1.341 rillig * too.
1332 1.341 rillig *
1333 1.341 rillig * The .DEFAULT node acts like a transformation rule, in that
1334 1.341 rillig * gn also inherits any attributes or sources attached to
1335 1.341 rillig * .DEFAULT itself.
1336 1.341 rillig */
1337 1.341 rillig Make_HandleUse(defaultNode, gn);
1338 1.417 rillig Var_Set(gn, IMPSRC, GNode_VarTarget(gn));
1339 1.421 rillig return true;
1340 1.341 rillig }
1341 1.341 rillig
1342 1.421 rillig Dir_UpdateMTime(gn, false);
1343 1.341 rillig if (gn->mtime != 0 || (gn->type & OP_SPECIAL))
1344 1.421 rillig return true;
1345 1.281 rillig
1346 1.341 rillig /*
1347 1.341 rillig * The node wasn't the target of an operator. We have no .DEFAULT
1348 1.341 rillig * rule to go on and the target doesn't already exist. There's
1349 1.341 rillig * nothing more we can do for this branch. If the -k flag wasn't
1350 1.341 rillig * given, we stop in our tracks, otherwise we just don't update
1351 1.341 rillig * this node's parents so they never get examined.
1352 1.341 rillig */
1353 1.282 rillig
1354 1.440 rillig if (gn->flags.fromDepend) {
1355 1.341 rillig if (!Job_RunTarget(".STALE", gn->fname))
1356 1.341 rillig fprintf(stdout,
1357 1.490 rillig "%s: %s:%u: ignoring stale %s for %s\n",
1358 1.341 rillig progname, gn->fname, gn->lineno, makeDependfile,
1359 1.341 rillig gn->name);
1360 1.421 rillig return true;
1361 1.341 rillig }
1362 1.282 rillig
1363 1.341 rillig if (gn->type & OP_OPTIONAL) {
1364 1.341 rillig (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
1365 1.341 rillig progname, gn->name, "ignored");
1366 1.341 rillig (void)fflush(stdout);
1367 1.421 rillig return true;
1368 1.341 rillig }
1369 1.282 rillig
1370 1.341 rillig if (opts.keepgoing) {
1371 1.341 rillig (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
1372 1.341 rillig progname, gn->name, "continuing");
1373 1.341 rillig (void)fflush(stdout);
1374 1.421 rillig return false;
1375 1.341 rillig }
1376 1.282 rillig
1377 1.464 sjg abortProc("don't know how to make %s. Stop", gn->name);
1378 1.421 rillig return false;
1379 1.1 cgd }
1380 1.1 cgd
1381 1.391 rillig /*
1382 1.391 rillig * Execute the shell for the given job.
1383 1.1 cgd *
1384 1.391 rillig * See Job_CatchOutput for handling the output of the shell.
1385 1.391 rillig */
1386 1.1 cgd static void
1387 1.72 wiz JobExec(Job *job, char **argv)
1388 1.1 cgd {
1389 1.341 rillig int cpid; /* ID of new child */
1390 1.341 rillig sigset_t mask;
1391 1.16 christos
1392 1.341 rillig if (DEBUG(JOB)) {
1393 1.341 rillig int i;
1394 1.16 christos
1395 1.341 rillig debug_printf("Running %s\n", job->node->name);
1396 1.341 rillig debug_printf("\tCommand: ");
1397 1.341 rillig for (i = 0; argv[i] != NULL; i++) {
1398 1.341 rillig debug_printf("%s ", argv[i]);
1399 1.341 rillig }
1400 1.341 rillig debug_printf("\n");
1401 1.1 cgd }
1402 1.16 christos
1403 1.341 rillig /*
1404 1.461 rillig * Some jobs produce no output, and it's disconcerting to have
1405 1.341 rillig * no feedback of their running (since they produce no output, the
1406 1.341 rillig * banner with their name in it never appears). This is an attempt to
1407 1.341 rillig * provide that feedback, even if nothing follows it.
1408 1.341 rillig */
1409 1.357 rillig if (job->echo)
1410 1.341 rillig SwitchOutputTo(job->node);
1411 1.16 christos
1412 1.341 rillig /* No interruptions until this job is on the `jobs' list */
1413 1.341 rillig JobSigLock(&mask);
1414 1.69 pk
1415 1.341 rillig /* Pre-emptively mark job running, pid still zero though */
1416 1.341 rillig job->status = JOB_ST_RUNNING;
1417 1.116 dsl
1418 1.466 sjg Var_ReexportVars(job->node);
1419 1.390 rillig
1420 1.485 rillig cpid = FORK_FUNCTION();
1421 1.341 rillig if (cpid == -1)
1422 1.485 rillig Punt("Cannot fork: %s", strerror(errno));
1423 1.341 rillig
1424 1.341 rillig if (cpid == 0) {
1425 1.341 rillig /* Child */
1426 1.341 rillig sigset_t tmask;
1427 1.1 cgd
1428 1.155 sjg #ifdef USE_META
1429 1.448 rillig if (useMeta)
1430 1.341 rillig meta_job_child(job);
1431 1.155 sjg #endif
1432 1.341 rillig /*
1433 1.341 rillig * Reset all signal handlers; this is necessary because we
1434 1.341 rillig * also need to unblock signals before we exec(2).
1435 1.341 rillig */
1436 1.341 rillig JobSigReset();
1437 1.69 pk
1438 1.341 rillig /* Now unblock signals */
1439 1.341 rillig sigemptyset(&tmask);
1440 1.341 rillig JobSigUnlock(&tmask);
1441 1.69 pk
1442 1.341 rillig /*
1443 1.341 rillig * Must duplicate the input stream down to the child's input
1444 1.341 rillig * and reset it to the beginning (again). Since the stream
1445 1.341 rillig * was marked close-on-exec, we must clear that bit in the
1446 1.341 rillig * new input.
1447 1.341 rillig */
1448 1.474 rillig if (dup2(fileno(job->cmdFILE), STDIN_FILENO) == -1)
1449 1.341 rillig execDie("dup2", "job->cmdFILE");
1450 1.474 rillig if (fcntl(STDIN_FILENO, F_SETFD, 0) == -1)
1451 1.341 rillig execDie("fcntl clear close-on-exec", "stdin");
1452 1.474 rillig if (lseek(STDIN_FILENO, 0, SEEK_SET) == -1)
1453 1.341 rillig execDie("lseek to 0", "stdin");
1454 1.341 rillig
1455 1.341 rillig if (job->node->type & (OP_MAKE | OP_SUBMAKE)) {
1456 1.461 rillig /* Pass job token pipe to submakes. */
1457 1.341 rillig if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1)
1458 1.341 rillig execDie("clear close-on-exec",
1459 1.341 rillig "tokenWaitJob.inPipe");
1460 1.341 rillig if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1)
1461 1.341 rillig execDie("clear close-on-exec",
1462 1.341 rillig "tokenWaitJob.outPipe");
1463 1.341 rillig }
1464 1.16 christos
1465 1.341 rillig /*
1466 1.341 rillig * Set up the child's output to be routed through the pipe
1467 1.341 rillig * we've created for it.
1468 1.341 rillig */
1469 1.474 rillig if (dup2(job->outPipe, STDOUT_FILENO) == -1)
1470 1.341 rillig execDie("dup2", "job->outPipe");
1471 1.201 rillig
1472 1.341 rillig /*
1473 1.341 rillig * The output channels are marked close on exec. This bit
1474 1.474 rillig * was duplicated by dup2 (on some systems), so we have
1475 1.341 rillig * to clear it before routing the shell's error output to
1476 1.341 rillig * the same place as its standard output.
1477 1.341 rillig */
1478 1.474 rillig if (fcntl(STDOUT_FILENO, F_SETFD, 0) == -1)
1479 1.341 rillig execDie("clear close-on-exec", "stdout");
1480 1.474 rillig if (dup2(STDOUT_FILENO, STDERR_FILENO) == -1)
1481 1.341 rillig execDie("dup2", "1, 2");
1482 1.264 rillig
1483 1.341 rillig /*
1484 1.341 rillig * We want to switch the child into a different process
1485 1.341 rillig * family so we can kill it and all its descendants in
1486 1.341 rillig * one fell swoop, by killing its process family, but not
1487 1.341 rillig * commit suicide.
1488 1.341 rillig */
1489 1.170 christos #if defined(MAKE_NATIVE) || defined(HAVE_SETPGID)
1490 1.412 rillig # if defined(SYSV)
1491 1.341 rillig /* XXX: dsl - I'm sure this should be setpgrp()... */
1492 1.341 rillig (void)setsid();
1493 1.412 rillig # else
1494 1.341 rillig (void)setpgid(0, getpid());
1495 1.412 rillig # endif
1496 1.170 christos #endif
1497 1.1 cgd
1498 1.341 rillig (void)execv(shellPath, argv);
1499 1.341 rillig execDie("exec", shellPath);
1500 1.341 rillig }
1501 1.116 dsl
1502 1.341 rillig /* Parent, continuing after the child exec */
1503 1.341 rillig job->pid = cpid;
1504 1.1 cgd
1505 1.341 rillig Trace_Log(JOBSTART, job);
1506 1.40 sommerfe
1507 1.196 riastrad #ifdef USE_META
1508 1.448 rillig if (useMeta)
1509 1.341 rillig meta_job_parent(job, cpid);
1510 1.196 riastrad #endif
1511 1.196 riastrad
1512 1.341 rillig /*
1513 1.341 rillig * Set the current position in the buffer to the beginning
1514 1.341 rillig * and mark another stream to watch in the outputs mask
1515 1.341 rillig */
1516 1.341 rillig job->curPos = 0;
1517 1.16 christos
1518 1.341 rillig watchfd(job);
1519 1.1 cgd
1520 1.341 rillig if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1521 1.436 sjg if (fclose(job->cmdFILE) != 0)
1522 1.436 sjg Punt("Cannot write shell script for '%s': %s",
1523 1.436 sjg job->node->name, strerror(errno));
1524 1.341 rillig job->cmdFILE = NULL;
1525 1.341 rillig }
1526 1.1 cgd
1527 1.409 rillig /* Now that the job is actually running, add it to the table. */
1528 1.341 rillig if (DEBUG(JOB)) {
1529 1.341 rillig debug_printf("JobExec(%s): pid %d added to jobs table\n",
1530 1.341 rillig job->node->name, job->pid);
1531 1.428 rillig DumpJobs("job started");
1532 1.341 rillig }
1533 1.341 rillig JobSigUnlock(&mask);
1534 1.1 cgd }
1535 1.1 cgd
1536 1.228 rillig /* Create the argv needed to execute the shell for a given job. */
1537 1.1 cgd static void
1538 1.72 wiz JobMakeArgv(Job *job, char **argv)
1539 1.1 cgd {
1540 1.341 rillig int argc;
1541 1.341 rillig static char args[10]; /* For merged arguments */
1542 1.16 christos
1543 1.341 rillig argv[0] = UNCONST(shellName);
1544 1.341 rillig argc = 1;
1545 1.1 cgd
1546 1.375 rillig if ((shell->errFlag != NULL && shell->errFlag[0] != '-') ||
1547 1.366 rillig (shell->echoFlag != NULL && shell->echoFlag[0] != '-')) {
1548 1.341 rillig /*
1549 1.341 rillig * At least one of the flags doesn't have a minus before it,
1550 1.341 rillig * so merge them together. Have to do this because the Bourne
1551 1.341 rillig * shell thinks its second argument is a file to source.
1552 1.341 rillig * Grrrr. Note the ten-character limitation on the combined
1553 1.341 rillig * arguments.
1554 1.341 rillig *
1555 1.341 rillig * TODO: Research until when the above comments were
1556 1.341 rillig * practically relevant.
1557 1.341 rillig */
1558 1.341 rillig (void)snprintf(args, sizeof args, "-%s%s",
1559 1.356 rillig (job->ignerr ? "" :
1560 1.375 rillig (shell->errFlag != NULL ? shell->errFlag : "")),
1561 1.357 rillig (!job->echo ? "" :
1562 1.366 rillig (shell->echoFlag != NULL ? shell->echoFlag : "")));
1563 1.341 rillig
1564 1.397 rillig if (args[1] != '\0') {
1565 1.341 rillig argv[argc] = args;
1566 1.341 rillig argc++;
1567 1.341 rillig }
1568 1.341 rillig } else {
1569 1.396 rillig if (!job->ignerr && shell->errFlag != NULL) {
1570 1.375 rillig argv[argc] = UNCONST(shell->errFlag);
1571 1.341 rillig argc++;
1572 1.341 rillig }
1573 1.396 rillig if (job->echo && shell->echoFlag != NULL) {
1574 1.366 rillig argv[argc] = UNCONST(shell->echoFlag);
1575 1.341 rillig argc++;
1576 1.341 rillig }
1577 1.1 cgd }
1578 1.341 rillig argv[argc] = NULL;
1579 1.1 cgd }
1580 1.1 cgd
1581 1.361 rillig static void
1582 1.434 rillig JobWriteShellCommands(Job *job, GNode *gn, bool *out_run)
1583 1.361 rillig {
1584 1.361 rillig /*
1585 1.361 rillig * tfile is the name of a file into which all shell commands
1586 1.361 rillig * are put. It is removed before the child shell is executed,
1587 1.361 rillig * unless DEBUG(SCRIPT) is set.
1588 1.361 rillig */
1589 1.419 sjg char tfile[MAXPATHLEN];
1590 1.361 rillig int tfd; /* File descriptor to the temp file */
1591 1.361 rillig
1592 1.419 sjg tfd = Job_TempFile(TMPPAT, tfile, sizeof tfile);
1593 1.361 rillig
1594 1.361 rillig job->cmdFILE = fdopen(tfd, "w+");
1595 1.361 rillig if (job->cmdFILE == NULL)
1596 1.361 rillig Punt("Could not fdopen %s", tfile);
1597 1.361 rillig
1598 1.361 rillig (void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
1599 1.361 rillig
1600 1.361 rillig #ifdef USE_META
1601 1.361 rillig if (useMeta) {
1602 1.361 rillig meta_job_start(job, gn);
1603 1.443 rillig if (gn->type & OP_SILENT) /* might have changed */
1604 1.421 rillig job->echo = false;
1605 1.361 rillig }
1606 1.361 rillig #endif
1607 1.362 rillig
1608 1.429 rillig *out_run = JobWriteCommands(job);
1609 1.361 rillig }
1610 1.361 rillig
1611 1.484 rillig void
1612 1.484 rillig Job_Make(GNode *gn)
1613 1.1 cgd {
1614 1.341 rillig Job *job; /* new job descriptor */
1615 1.341 rillig char *argv[10]; /* Argument vector to shell */
1616 1.421 rillig bool cmdsOK; /* true if the nodes commands were all right */
1617 1.421 rillig bool run;
1618 1.341 rillig
1619 1.341 rillig for (job = job_table; job < job_table_end; job++) {
1620 1.341 rillig if (job->status == JOB_ST_FREE)
1621 1.341 rillig break;
1622 1.341 rillig }
1623 1.341 rillig if (job >= job_table_end)
1624 1.484 rillig Punt("Job_Make no job slots vacant");
1625 1.122 dsl
1626 1.341 rillig memset(job, 0, sizeof *job);
1627 1.341 rillig job->node = gn;
1628 1.341 rillig job->tailCmds = NULL;
1629 1.341 rillig job->status = JOB_ST_SET_UP;
1630 1.1 cgd
1631 1.484 rillig job->special = (gn->type & OP_SPECIAL) != OP_NONE;
1632 1.369 rillig job->ignerr = opts.ignoreErrors || gn->type & OP_IGNORE;
1633 1.445 rillig job->echo = !(opts.silent || gn->type & OP_SILENT);
1634 1.16 christos
1635 1.1 cgd /*
1636 1.341 rillig * Check the commands now so any attributes from .DEFAULT have a
1637 1.341 rillig * chance to migrate to the node.
1638 1.34 christos */
1639 1.341 rillig cmdsOK = Job_CheckCommands(gn, Error);
1640 1.341 rillig
1641 1.341 rillig job->inPollfd = NULL;
1642 1.403 rillig
1643 1.399 rillig if (Lst_IsEmpty(&gn->commands)) {
1644 1.399 rillig job->cmdFILE = stdout;
1645 1.421 rillig run = false;
1646 1.435 rillig
1647 1.435 rillig /*
1648 1.435 rillig * We're serious here, but if the commands were bogus, we're
1649 1.435 rillig * also dead...
1650 1.435 rillig */
1651 1.435 rillig if (!cmdsOK) {
1652 1.449 rillig PrintOnError(gn, "\n"); /* provide some clue */
1653 1.435 rillig DieHorribly();
1654 1.435 rillig }
1655 1.399 rillig } else if (((gn->type & OP_MAKE) && !opts.noRecursiveExecute) ||
1656 1.445 rillig (!opts.noExecute && !opts.touch)) {
1657 1.401 rillig /*
1658 1.403 rillig * The above condition looks very similar to
1659 1.418 rillig * GNode_ShouldExecute but is subtly different. It prevents
1660 1.418 rillig * that .MAKE targets are touched since these are usually
1661 1.418 rillig * virtual targets.
1662 1.401 rillig */
1663 1.402 rillig
1664 1.481 rillig int parseErrorsBefore;
1665 1.481 rillig
1666 1.434 rillig /*
1667 1.434 rillig * We're serious here, but if the commands were bogus, we're
1668 1.434 rillig * also dead...
1669 1.434 rillig */
1670 1.434 rillig if (!cmdsOK) {
1671 1.449 rillig PrintOnError(gn, "\n"); /* provide some clue */
1672 1.434 rillig DieHorribly();
1673 1.434 rillig }
1674 1.434 rillig
1675 1.481 rillig parseErrorsBefore = parseErrors;
1676 1.434 rillig JobWriteShellCommands(job, gn, &run);
1677 1.481 rillig if (parseErrors != parseErrorsBefore)
1678 1.481 rillig run = false;
1679 1.401 rillig (void)fflush(job->cmdFILE);
1680 1.341 rillig } else if (!GNode_ShouldExecute(gn)) {
1681 1.341 rillig /*
1682 1.429 rillig * Just write all the commands to stdout in one fell swoop.
1683 1.418 rillig * This still sets up job->tailCmds correctly.
1684 1.341 rillig */
1685 1.341 rillig SwitchOutputTo(gn);
1686 1.341 rillig job->cmdFILE = stdout;
1687 1.341 rillig if (cmdsOK)
1688 1.429 rillig JobWriteCommands(job);
1689 1.421 rillig run = false;
1690 1.401 rillig (void)fflush(job->cmdFILE);
1691 1.341 rillig } else {
1692 1.357 rillig Job_Touch(gn, job->echo);
1693 1.421 rillig run = false;
1694 1.341 rillig }
1695 1.341 rillig
1696 1.341 rillig /* If we're not supposed to execute a shell, don't. */
1697 1.353 rillig if (!run) {
1698 1.356 rillig if (!job->special)
1699 1.341 rillig Job_TokenReturn();
1700 1.341 rillig /* Unlink and close the command file if we opened one */
1701 1.341 rillig if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
1702 1.341 rillig (void)fclose(job->cmdFILE);
1703 1.341 rillig job->cmdFILE = NULL;
1704 1.341 rillig }
1705 1.1 cgd
1706 1.341 rillig /*
1707 1.341 rillig * We only want to work our way up the graph if we aren't
1708 1.341 rillig * here because the commands for the job were no good.
1709 1.341 rillig */
1710 1.341 rillig if (cmdsOK && aborting == ABORT_NONE) {
1711 1.341 rillig JobSaveCommands(job);
1712 1.341 rillig job->node->made = MADE;
1713 1.341 rillig Make_Update(job->node);
1714 1.341 rillig }
1715 1.341 rillig job->status = JOB_ST_FREE;
1716 1.484 rillig return;
1717 1.1 cgd }
1718 1.1 cgd
1719 1.1 cgd /*
1720 1.341 rillig * Set up the control arguments to the shell. This is based on the
1721 1.341 rillig * flags set earlier for this job.
1722 1.1 cgd */
1723 1.341 rillig JobMakeArgv(job, argv);
1724 1.1 cgd
1725 1.341 rillig /* Create the pipe by which we'll get the shell's output. */
1726 1.341 rillig JobCreatePipe(job, 3);
1727 1.1 cgd
1728 1.341 rillig JobExec(job, argv);
1729 1.1 cgd }
1730 1.1 cgd
1731 1.341 rillig /*
1732 1.426 rillig * If the shell has an output filter (which only csh and ksh have by default),
1733 1.426 rillig * print the output of the child process, skipping the noPrint text of the
1734 1.426 rillig * shell.
1735 1.426 rillig *
1736 1.426 rillig * Return the part of the output that the calling function needs to output by
1737 1.426 rillig * itself.
1738 1.341 rillig */
1739 1.16 christos static char *
1740 1.470 rillig PrintFilteredOutput(char *p, const char *endp) /* XXX: p should be const */
1741 1.12 christos {
1742 1.460 rillig char *ep; /* XXX: should be const */
1743 1.12 christos
1744 1.355 rillig if (shell->noPrint == NULL || shell->noPrint[0] == '\0')
1745 1.460 rillig return p;
1746 1.324 rillig
1747 1.392 rillig /*
1748 1.392 rillig * XXX: What happens if shell->noPrint occurs on the boundary of
1749 1.392 rillig * the buffer? To work correctly in all cases, this should rather
1750 1.392 rillig * be a proper stream filter instead of doing string matching on
1751 1.392 rillig * selected chunks of the output.
1752 1.392 rillig */
1753 1.460 rillig while ((ep = strstr(p, shell->noPrint)) != NULL) {
1754 1.460 rillig if (ep != p) {
1755 1.460 rillig *ep = '\0'; /* XXX: avoid writing to the buffer */
1756 1.341 rillig /*
1757 1.341 rillig * The only way there wouldn't be a newline after
1758 1.341 rillig * this line is if it were the last in the buffer.
1759 1.392 rillig * however, since the noPrint output comes after it,
1760 1.341 rillig * there must be a newline, so we don't print one.
1761 1.341 rillig */
1762 1.392 rillig /* XXX: What about null bytes in the output? */
1763 1.460 rillig (void)fprintf(stdout, "%s", p);
1764 1.341 rillig (void)fflush(stdout);
1765 1.341 rillig }
1766 1.460 rillig p = ep + shell->noPrintLen;
1767 1.460 rillig if (p == endp)
1768 1.392 rillig break;
1769 1.460 rillig p++; /* skip over the (XXX: assumed) newline */
1770 1.460 rillig pp_skip_whitespace(&p);
1771 1.12 christos }
1772 1.460 rillig return p;
1773 1.12 christos }
1774 1.12 christos
1775 1.325 rillig /*
1776 1.325 rillig * This function is called whenever there is something to read on the pipe.
1777 1.325 rillig * We collect more output from the given job and store it in the job's
1778 1.325 rillig * outBuf. If this makes up a line, we print it tagged by the job's
1779 1.325 rillig * identifier, as necessary.
1780 1.325 rillig *
1781 1.325 rillig * In the output of the shell, the 'noPrint' lines are removed. If the
1782 1.325 rillig * command is not alone on the line (the character after it is not \0 or
1783 1.325 rillig * \n), we do print whatever follows it.
1784 1.1 cgd *
1785 1.72 wiz * Input:
1786 1.72 wiz * job the job whose output needs printing
1787 1.421 rillig * finish true if this is the last time we'll be called
1788 1.72 wiz * for this job
1789 1.1 cgd */
1790 1.285 rillig static void
1791 1.424 rillig CollectOutput(Job *job, bool finish)
1792 1.1 cgd {
1793 1.421 rillig bool gotNL; /* true if got a newline */
1794 1.421 rillig bool fbuf; /* true if our buffer filled up */
1795 1.341 rillig size_t nr; /* number of bytes read */
1796 1.341 rillig size_t i; /* auxiliary index into outBuf */
1797 1.341 rillig size_t max; /* limit for i (end of current data) */
1798 1.341 rillig ssize_t nRead; /* (Temporary) number of bytes read */
1799 1.1 cgd
1800 1.341 rillig /* Read as many bytes as will fit in the buffer. */
1801 1.325 rillig again:
1802 1.421 rillig gotNL = false;
1803 1.421 rillig fbuf = false;
1804 1.16 christos
1805 1.341 rillig nRead = read(job->inPipe, &job->outBuf[job->curPos],
1806 1.341 rillig JOB_BUFSIZE - job->curPos);
1807 1.341 rillig if (nRead < 0) {
1808 1.341 rillig if (errno == EAGAIN)
1809 1.341 rillig return;
1810 1.455 rillig if (DEBUG(JOB))
1811 1.424 rillig perror("CollectOutput(piperead)");
1812 1.341 rillig nr = 0;
1813 1.455 rillig } else
1814 1.341 rillig nr = (size_t)nRead;
1815 1.455 rillig
1816 1.455 rillig if (nr == 0)
1817 1.455 rillig finish = false; /* stop looping */
1818 1.1 cgd
1819 1.341 rillig /*
1820 1.341 rillig * If we hit the end-of-file (the job is dead), we must flush its
1821 1.341 rillig * remaining output, so pretend we read a newline if there's any
1822 1.341 rillig * output remaining in the buffer.
1823 1.341 rillig */
1824 1.341 rillig if (nr == 0 && job->curPos != 0) {
1825 1.341 rillig job->outBuf[job->curPos] = '\n';
1826 1.341 rillig nr = 1;
1827 1.341 rillig }
1828 1.16 christos
1829 1.341 rillig max = job->curPos + nr;
1830 1.454 rillig for (i = job->curPos; i < max; i++)
1831 1.454 rillig if (job->outBuf[i] == '\0')
1832 1.454 rillig job->outBuf[i] = ' ';
1833 1.455 rillig
1834 1.455 rillig /* Look for the last newline in the bytes we just got. */
1835 1.341 rillig for (i = job->curPos + nr - 1;
1836 1.341 rillig i >= job->curPos && i != (size_t)-1; i--) {
1837 1.341 rillig if (job->outBuf[i] == '\n') {
1838 1.421 rillig gotNL = true;
1839 1.341 rillig break;
1840 1.341 rillig }
1841 1.1 cgd }
1842 1.16 christos
1843 1.341 rillig if (!gotNL) {
1844 1.341 rillig job->curPos += nr;
1845 1.341 rillig if (job->curPos == JOB_BUFSIZE) {
1846 1.341 rillig /*
1847 1.341 rillig * If we've run out of buffer space, we have no choice
1848 1.341 rillig * but to print the stuff. sigh.
1849 1.341 rillig */
1850 1.421 rillig fbuf = true;
1851 1.341 rillig i = job->curPos;
1852 1.341 rillig }
1853 1.120 dsl }
1854 1.341 rillig if (gotNL || fbuf) {
1855 1.341 rillig /*
1856 1.341 rillig * Need to send the output to the screen. Null terminate it
1857 1.341 rillig * first, overwriting the newline character if there was one.
1858 1.341 rillig * So long as the line isn't one we should filter (according
1859 1.341 rillig * to the shell description), we print the line, preceded
1860 1.341 rillig * by a target banner if this target isn't the same as the
1861 1.341 rillig * one for which we last printed something.
1862 1.341 rillig * The rest of the data in the buffer are then shifted down
1863 1.341 rillig * to the start of the buffer and curPos is set accordingly.
1864 1.341 rillig */
1865 1.341 rillig job->outBuf[i] = '\0';
1866 1.341 rillig if (i >= job->curPos) {
1867 1.460 rillig char *p;
1868 1.341 rillig
1869 1.425 rillig /*
1870 1.425 rillig * FIXME: SwitchOutputTo should be here, according to
1871 1.425 rillig * the comment above. But since PrintOutput does not
1872 1.425 rillig * do anything in the default shell, this bug has gone
1873 1.425 rillig * unnoticed until now.
1874 1.425 rillig */
1875 1.460 rillig p = PrintFilteredOutput(job->outBuf, &job->outBuf[i]);
1876 1.341 rillig
1877 1.341 rillig /*
1878 1.426 rillig * There's still more in the output buffer. This time,
1879 1.341 rillig * though, we know there's no newline at the end, so
1880 1.341 rillig * we add one of our own free will.
1881 1.341 rillig */
1882 1.460 rillig if (*p != '\0') {
1883 1.445 rillig if (!opts.silent)
1884 1.341 rillig SwitchOutputTo(job->node);
1885 1.155 sjg #ifdef USE_META
1886 1.341 rillig if (useMeta) {
1887 1.460 rillig meta_job_output(job, p,
1888 1.341 rillig gotNL ? "\n" : "");
1889 1.341 rillig }
1890 1.341 rillig #endif
1891 1.460 rillig (void)fprintf(stdout, "%s%s", p,
1892 1.341 rillig gotNL ? "\n" : "");
1893 1.341 rillig (void)fflush(stdout);
1894 1.341 rillig }
1895 1.341 rillig }
1896 1.341 rillig /*
1897 1.341 rillig * max is the last offset still in the buffer. Move any
1898 1.341 rillig * remaining characters to the start of the buffer and
1899 1.341 rillig * update the end marker curPos.
1900 1.341 rillig */
1901 1.341 rillig if (i < max) {
1902 1.341 rillig (void)memmove(job->outBuf, &job->outBuf[i + 1],
1903 1.341 rillig max - (i + 1));
1904 1.341 rillig job->curPos = max - (i + 1);
1905 1.341 rillig } else {
1906 1.341 rillig assert(i == max);
1907 1.341 rillig job->curPos = 0;
1908 1.155 sjg }
1909 1.120 dsl }
1910 1.341 rillig if (finish) {
1911 1.341 rillig /*
1912 1.341 rillig * If the finish flag is true, we must loop until we hit
1913 1.341 rillig * end-of-file on the pipe. This is guaranteed to happen
1914 1.341 rillig * eventually since the other end of the pipe is now closed
1915 1.341 rillig * (we closed it explicitly and the child has exited). When
1916 1.421 rillig * we do get an EOF, finish will be set false and we'll fall
1917 1.341 rillig * through and out.
1918 1.341 rillig */
1919 1.341 rillig goto again;
1920 1.180 joerg }
1921 1.1 cgd }
1922 1.1 cgd
1923 1.91 christos static void
1924 1.91 christos JobRun(GNode *targ)
1925 1.91 christos {
1926 1.483 rillig /* Don't let these special jobs overlap with other unrelated jobs. */
1927 1.341 rillig Compat_Make(targ, targ);
1928 1.482 rillig if (GNode_IsError(targ)) {
1929 1.449 rillig PrintOnError(targ, "\n\nStop.\n");
1930 1.341 rillig exit(1);
1931 1.341 rillig }
1932 1.91 christos }
1933 1.91 christos
1934 1.1 cgd void
1935 1.120 dsl Job_CatchChildren(void)
1936 1.1 cgd {
1937 1.487 rillig int pid;
1938 1.487 rillig int status;
1939 1.1 cgd
1940 1.341 rillig if (jobTokensRunning == 0)
1941 1.341 rillig return;
1942 1.405 sjg if (caught_sigchld == 0)
1943 1.405 sjg return;
1944 1.405 sjg caught_sigchld = 0;
1945 1.405 sjg
1946 1.341 rillig while ((pid = waitpid((pid_t)-1, &status, WNOHANG | WUNTRACED)) > 0) {
1947 1.341 rillig DEBUG2(JOB, "Process %d exited/stopped status %x.\n",
1948 1.341 rillig pid, status);
1949 1.421 rillig JobReapChild(pid, status, true);
1950 1.341 rillig }
1951 1.153 sjg }
1952 1.153 sjg
1953 1.153 sjg /*
1954 1.153 sjg * It is possible that wait[pid]() was called from elsewhere,
1955 1.153 sjg * this lets us reap jobs regardless.
1956 1.153 sjg */
1957 1.153 sjg void
1958 1.421 rillig JobReapChild(pid_t pid, int status, bool isJobs)
1959 1.153 sjg {
1960 1.487 rillig Job *job;
1961 1.153 sjg
1962 1.341 rillig if (jobTokensRunning == 0)
1963 1.341 rillig return;
1964 1.16 christos
1965 1.341 rillig job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
1966 1.341 rillig if (job == NULL) {
1967 1.487 rillig if (isJobs && !lurking_children)
1968 1.487 rillig Error("Child (%d) status %x not in table?",
1969 1.487 rillig pid, status);
1970 1.487 rillig return;
1971 1.116 dsl }
1972 1.487 rillig
1973 1.341 rillig if (WIFSTOPPED(status)) {
1974 1.341 rillig DEBUG2(JOB, "Process %d (%s) stopped.\n",
1975 1.341 rillig job->pid, job->node->name);
1976 1.341 rillig if (!make_suspended) {
1977 1.341 rillig switch (WSTOPSIG(status)) {
1978 1.341 rillig case SIGTSTP:
1979 1.341 rillig (void)printf("*** [%s] Suspended\n",
1980 1.341 rillig job->node->name);
1981 1.341 rillig break;
1982 1.341 rillig case SIGSTOP:
1983 1.341 rillig (void)printf("*** [%s] Stopped\n",
1984 1.341 rillig job->node->name);
1985 1.341 rillig break;
1986 1.341 rillig default:
1987 1.341 rillig (void)printf("*** [%s] Stopped -- signal %d\n",
1988 1.341 rillig job->node->name, WSTOPSIG(status));
1989 1.341 rillig }
1990 1.421 rillig job->suspended = true;
1991 1.341 rillig }
1992 1.341 rillig (void)fflush(stdout);
1993 1.341 rillig return;
1994 1.1 cgd }
1995 1.1 cgd
1996 1.341 rillig job->status = JOB_ST_FINISHED;
1997 1.341 rillig job->exit_status = status;
1998 1.467 sjg if (WIFEXITED(status))
1999 1.467 sjg job->node->exit_status = WEXITSTATUS(status);
2000 1.116 dsl
2001 1.341 rillig JobFinish(job, status);
2002 1.1 cgd }
2003 1.1 cgd
2004 1.1 cgd void
2005 1.72 wiz Job_CatchOutput(void)
2006 1.1 cgd {
2007 1.341 rillig int nready;
2008 1.341 rillig Job *job;
2009 1.341 rillig unsigned int i;
2010 1.169 christos
2011 1.341 rillig (void)fflush(stdout);
2012 1.120 dsl
2013 1.341 rillig do {
2014 1.492 rillig /* Maybe skip the job token pipe. */
2015 1.492 rillig nfds_t skip = wantToken ? 0 : 1;
2016 1.492 rillig nready = poll(fds + skip, fdsLen - skip, POLL_MSEC);
2017 1.341 rillig } while (nready < 0 && errno == EINTR);
2018 1.341 rillig
2019 1.341 rillig if (nready < 0)
2020 1.341 rillig Punt("poll: %s", strerror(errno));
2021 1.341 rillig
2022 1.492 rillig if (nready > 0 && childExitJob.inPollfd->revents & POLLIN) {
2023 1.492 rillig char token;
2024 1.487 rillig ssize_t count = read(childExitJob.inPipe, &token, 1);
2025 1.409 rillig if (count == 1) {
2026 1.341 rillig if (token == DO_JOB_RESUME[0])
2027 1.341 rillig /*
2028 1.341 rillig * Complete relay requested from our SIGCONT
2029 1.487 rillig * handler.
2030 1.341 rillig */
2031 1.341 rillig JobRestartJobs();
2032 1.409 rillig } else if (count == 0)
2033 1.409 rillig Punt("unexpected eof on token pipe");
2034 1.409 rillig else
2035 1.409 rillig Punt("token pipe read: %s", strerror(errno));
2036 1.341 rillig nready--;
2037 1.169 christos }
2038 1.120 dsl
2039 1.341 rillig Job_CatchChildren();
2040 1.341 rillig if (nready == 0)
2041 1.341 rillig return;
2042 1.341 rillig
2043 1.408 rillig for (i = npseudojobs * nfds_per_job(); i < fdsLen; i++) {
2044 1.396 rillig if (fds[i].revents == 0)
2045 1.341 rillig continue;
2046 1.408 rillig job = jobByFdIndex[i];
2047 1.341 rillig if (job->status == JOB_ST_RUNNING)
2048 1.424 rillig CollectOutput(job, false);
2049 1.197 sjg #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2050 1.341 rillig /*
2051 1.341 rillig * With meta mode, we may have activity on the job's filemon
2052 1.341 rillig * descriptor too, which at the moment is any pollfd other
2053 1.341 rillig * than job->inPollfd.
2054 1.341 rillig */
2055 1.341 rillig if (useMeta && job->inPollfd != &fds[i]) {
2056 1.448 rillig if (meta_job_event(job) <= 0)
2057 1.443 rillig fds[i].events = 0; /* never mind */
2058 1.341 rillig }
2059 1.341 rillig #endif
2060 1.341 rillig if (--nready == 0)
2061 1.341 rillig return;
2062 1.196 riastrad }
2063 1.1 cgd }
2064 1.1 cgd
2065 1.344 rillig static void
2066 1.344 rillig InitShellNameAndPath(void)
2067 1.344 rillig {
2068 1.355 rillig shellName = shell->name;
2069 1.344 rillig
2070 1.344 rillig #ifdef DEFSHELL_CUSTOM
2071 1.344 rillig if (shellName[0] == '/') {
2072 1.477 rillig shellPath = bmake_strdup(shellName);
2073 1.387 rillig shellName = str_basename(shellPath);
2074 1.344 rillig return;
2075 1.344 rillig }
2076 1.344 rillig #endif
2077 1.344 rillig
2078 1.344 rillig shellPath = str_concat3(_PATH_DEFSHELLDIR, "/", shellName);
2079 1.344 rillig }
2080 1.344 rillig
2081 1.81 sjg void
2082 1.120 dsl Shell_Init(void)
2083 1.81 sjg {
2084 1.344 rillig if (shellPath == NULL)
2085 1.344 rillig InitShellNameAndPath();
2086 1.344 rillig
2087 1.471 sjg Var_SetWithFlags(SCOPE_CMDLINE, ".SHELL", shellPath,
2088 1.471 sjg VAR_SET_INTERNAL|VAR_SET_READONLY);
2089 1.375 rillig if (shell->errFlag == NULL)
2090 1.375 rillig shell->errFlag = "";
2091 1.366 rillig if (shell->echoFlag == NULL)
2092 1.366 rillig shell->echoFlag = "";
2093 1.375 rillig if (shell->hasErrCtl && shell->errFlag[0] != '\0') {
2094 1.396 rillig if (shellErrFlag != NULL &&
2095 1.375 rillig strcmp(shell->errFlag, &shellErrFlag[1]) != 0) {
2096 1.341 rillig free(shellErrFlag);
2097 1.341 rillig shellErrFlag = NULL;
2098 1.341 rillig }
2099 1.446 rillig if (shellErrFlag == NULL)
2100 1.446 rillig shellErrFlag = str_concat2("-", shell->errFlag);
2101 1.341 rillig } else if (shellErrFlag != NULL) {
2102 1.341 rillig free(shellErrFlag);
2103 1.341 rillig shellErrFlag = NULL;
2104 1.341 rillig }
2105 1.81 sjg }
2106 1.81 sjg
2107 1.487 rillig /* Return the shell string literal that results in a newline character. */
2108 1.112 rillig const char *
2109 1.112 rillig Shell_GetNewline(void)
2110 1.112 rillig {
2111 1.355 rillig return shell->newline;
2112 1.112 rillig }
2113 1.112 rillig
2114 1.125 sjg void
2115 1.125 sjg Job_SetPrefix(void)
2116 1.125 sjg {
2117 1.463 rillig if (targPrefix != NULL)
2118 1.341 rillig free(targPrefix);
2119 1.463 rillig else if (!Var_Exists(SCOPE_GLOBAL, ".MAKE.JOB.PREFIX"))
2120 1.459 rillig Global_Set(".MAKE.JOB.PREFIX", "---");
2121 1.128 dsl
2122 1.459 rillig targPrefix = Var_Subst("${.MAKE.JOB.PREFIX}",
2123 1.475 rillig SCOPE_GLOBAL, VARE_EVAL);
2124 1.341 rillig /* TODO: handle errors */
2125 1.125 sjg }
2126 1.125 sjg
2127 1.342 rillig static void
2128 1.342 rillig AddSig(int sig, SignalProc handler)
2129 1.342 rillig {
2130 1.342 rillig if (bmake_signal(sig, SIG_IGN) != SIG_IGN) {
2131 1.342 rillig sigaddset(&caught_signals, sig);
2132 1.342 rillig (void)bmake_signal(sig, handler);
2133 1.342 rillig }
2134 1.342 rillig }
2135 1.342 rillig
2136 1.1 cgd void
2137 1.111 dsl Job_Init(void)
2138 1.1 cgd {
2139 1.341 rillig Job_SetPrefix();
2140 1.487 rillig
2141 1.341 rillig job_table = bmake_malloc((size_t)opts.maxJobs * sizeof *job_table);
2142 1.341 rillig memset(job_table, 0, (size_t)opts.maxJobs * sizeof *job_table);
2143 1.341 rillig job_table_end = job_table + opts.maxJobs;
2144 1.492 rillig wantToken = false;
2145 1.405 sjg caught_sigchld = 0;
2146 1.341 rillig
2147 1.341 rillig aborting = ABORT_NONE;
2148 1.341 rillig job_errors = 0;
2149 1.341 rillig
2150 1.341 rillig /*
2151 1.487 rillig * There is a non-zero chance that we already have children,
2152 1.487 rillig * e.g. after 'make -f- <<EOF'.
2153 1.341 rillig * Since their termination causes a 'Child (pid) not in table'
2154 1.341 rillig * message, Collect the status of any that are already dead, and
2155 1.341 rillig * suppress the error message if there are any undead ones.
2156 1.341 rillig */
2157 1.341 rillig for (;;) {
2158 1.341 rillig int rval, status;
2159 1.341 rillig rval = waitpid((pid_t)-1, &status, WNOHANG);
2160 1.341 rillig if (rval > 0)
2161 1.341 rillig continue;
2162 1.341 rillig if (rval == 0)
2163 1.421 rillig lurking_children = true;
2164 1.341 rillig break;
2165 1.341 rillig }
2166 1.1 cgd
2167 1.341 rillig Shell_Init();
2168 1.1 cgd
2169 1.341 rillig JobCreatePipe(&childExitJob, 3);
2170 1.117 dsl
2171 1.408 rillig {
2172 1.408 rillig size_t nfds = (npseudojobs + (size_t)opts.maxJobs) *
2173 1.408 rillig nfds_per_job();
2174 1.408 rillig fds = bmake_malloc(sizeof *fds * nfds);
2175 1.408 rillig jobByFdIndex = bmake_malloc(sizeof *jobByFdIndex * nfds);
2176 1.408 rillig }
2177 1.1 cgd
2178 1.341 rillig /* These are permanent entries and take slots 0 and 1 */
2179 1.341 rillig watchfd(&tokenWaitJob);
2180 1.341 rillig watchfd(&childExitJob);
2181 1.73 gson
2182 1.341 rillig sigemptyset(&caught_signals);
2183 1.341 rillig (void)bmake_signal(SIGCHLD, JobChildSig);
2184 1.341 rillig sigaddset(&caught_signals, SIGCHLD);
2185 1.122 dsl
2186 1.487 rillig /* Handle the signals specified by POSIX. */
2187 1.342 rillig AddSig(SIGINT, JobPassSig_int);
2188 1.342 rillig AddSig(SIGHUP, JobPassSig_term);
2189 1.342 rillig AddSig(SIGTERM, JobPassSig_term);
2190 1.342 rillig AddSig(SIGQUIT, JobPassSig_term);
2191 1.69 pk
2192 1.341 rillig /*
2193 1.487 rillig * These signals need to be passed to the jobs, as each job has its
2194 1.487 rillig * own process group and thus the terminal driver doesn't forward the
2195 1.487 rillig * signals itself.
2196 1.341 rillig */
2197 1.342 rillig AddSig(SIGTSTP, JobPassSig_suspend);
2198 1.342 rillig AddSig(SIGTTOU, JobPassSig_suspend);
2199 1.342 rillig AddSig(SIGTTIN, JobPassSig_suspend);
2200 1.342 rillig AddSig(SIGWINCH, JobCondPassSig);
2201 1.342 rillig AddSig(SIGCONT, JobContinueSig);
2202 1.16 christos
2203 1.341 rillig (void)Job_RunTarget(".BEGIN", NULL);
2204 1.487 rillig /* Create the .END node, see Targ_GetEndNode in Compat_MakeAll. */
2205 1.341 rillig (void)Targ_GetEndNode();
2206 1.1 cgd }
2207 1.1 cgd
2208 1.342 rillig static void
2209 1.342 rillig DelSig(int sig)
2210 1.342 rillig {
2211 1.397 rillig if (sigismember(&caught_signals, sig) != 0)
2212 1.342 rillig (void)bmake_signal(sig, SIG_DFL);
2213 1.342 rillig }
2214 1.342 rillig
2215 1.388 rillig static void
2216 1.388 rillig JobSigReset(void)
2217 1.69 pk {
2218 1.342 rillig DelSig(SIGINT);
2219 1.342 rillig DelSig(SIGHUP);
2220 1.342 rillig DelSig(SIGQUIT);
2221 1.342 rillig DelSig(SIGTERM);
2222 1.342 rillig DelSig(SIGTSTP);
2223 1.342 rillig DelSig(SIGTTOU);
2224 1.342 rillig DelSig(SIGTTIN);
2225 1.342 rillig DelSig(SIGWINCH);
2226 1.342 rillig DelSig(SIGCONT);
2227 1.341 rillig (void)bmake_signal(SIGCHLD, SIG_DFL);
2228 1.69 pk }
2229 1.69 pk
2230 1.1 cgd static Shell *
2231 1.301 rillig FindShellByName(const char *name)
2232 1.1 cgd {
2233 1.341 rillig Shell *sh = shells;
2234 1.341 rillig const Shell *shellsEnd = sh + sizeof shells / sizeof shells[0];
2235 1.1 cgd
2236 1.341 rillig for (sh = shells; sh < shellsEnd; sh++) {
2237 1.341 rillig if (strcmp(name, sh->name) == 0)
2238 1.341 rillig return sh;
2239 1.341 rillig }
2240 1.341 rillig return NULL;
2241 1.1 cgd }
2242 1.1 cgd
2243 1.338 rillig /*
2244 1.355 rillig * Parse a shell specification and set up 'shell', shellPath and
2245 1.338 rillig * shellName appropriately.
2246 1.1 cgd *
2247 1.72 wiz * Input:
2248 1.72 wiz * line The shell spec
2249 1.72 wiz *
2250 1.1 cgd * Results:
2251 1.487 rillig * Returns false if the specification was incorrect.
2252 1.487 rillig * If successful, 'shell' is usable, shellPath is the full path of the
2253 1.487 rillig * shell described by 'shell', and shellName is the final component of
2254 1.487 rillig * shellPath.
2255 1.1 cgd *
2256 1.1 cgd * Notes:
2257 1.487 rillig * A shell specification has the form ".SHELL: keyword=value...". Double
2258 1.487 rillig * quotes can be used to enclose blanks in words. A backslash escapes
2259 1.1 cgd * anything (most notably a double-quote and a space) and
2260 1.487 rillig * provides the usual escape sequences from C. There should be no
2261 1.487 rillig * unnecessary spaces in the word. The keywords are:
2262 1.246 rillig * name Name of shell.
2263 1.246 rillig * path Location of shell.
2264 1.246 rillig * quiet Command to turn off echoing.
2265 1.246 rillig * echo Command to turn echoing on
2266 1.487 rillig * filter The output from the shell command that turns off
2267 1.487 rillig * echoing, to be filtered from the final output.
2268 1.487 rillig * echoFlag Flag to turn echoing on at the start.
2269 1.487 rillig * errFlag Flag to turn error checking on at the start.
2270 1.487 rillig * hasErrCtl True if the shell has error checking control.
2271 1.487 rillig * newline String literal to represent a newline character.
2272 1.487 rillig * check If hasErrCtl is true: The command to turn on error
2273 1.487 rillig * checking. If hasErrCtl is false: The template for a
2274 1.487 rillig * shell command that echoes a command for which error
2275 1.487 rillig * checking is off.
2276 1.487 rillig * ignore If hasErrCtl is true: The command to turn off error
2277 1.487 rillig * checking. If hasErrCtl is false: The template for a
2278 1.487 rillig * shell command that executes a command so as to ignore
2279 1.487 rillig * any errors it returns.
2280 1.1 cgd */
2281 1.421 rillig bool
2282 1.72 wiz Job_ParseShell(char *line)
2283 1.1 cgd {
2284 1.341 rillig Words wordsList;
2285 1.341 rillig char **words;
2286 1.341 rillig char **argv;
2287 1.341 rillig size_t argc;
2288 1.341 rillig char *path;
2289 1.341 rillig Shell newShell;
2290 1.421 rillig bool fullSpec = false;
2291 1.341 rillig Shell *sh;
2292 1.341 rillig
2293 1.386 rillig /* XXX: don't use line as an iterator variable */
2294 1.341 rillig pp_skip_whitespace(&line);
2295 1.341 rillig
2296 1.407 rillig free(shell_freeIt);
2297 1.341 rillig
2298 1.341 rillig memset(&newShell, 0, sizeof newShell);
2299 1.341 rillig
2300 1.421 rillig wordsList = Str_Words(line, true);
2301 1.341 rillig words = wordsList.words;
2302 1.341 rillig argc = wordsList.len;
2303 1.341 rillig path = wordsList.freeIt;
2304 1.341 rillig if (words == NULL) {
2305 1.341 rillig Error("Unterminated quoted string [%s]", line);
2306 1.421 rillig return false;
2307 1.244 rillig }
2308 1.407 rillig shell_freeIt = path;
2309 1.1 cgd
2310 1.341 rillig for (path = NULL, argv = words; argc != 0; argc--, argv++) {
2311 1.341 rillig char *arg = *argv;
2312 1.341 rillig if (strncmp(arg, "path=", 5) == 0) {
2313 1.341 rillig path = arg + 5;
2314 1.341 rillig } else if (strncmp(arg, "name=", 5) == 0) {
2315 1.341 rillig newShell.name = arg + 5;
2316 1.341 rillig } else {
2317 1.341 rillig if (strncmp(arg, "quiet=", 6) == 0) {
2318 1.341 rillig newShell.echoOff = arg + 6;
2319 1.341 rillig } else if (strncmp(arg, "echo=", 5) == 0) {
2320 1.341 rillig newShell.echoOn = arg + 5;
2321 1.341 rillig } else if (strncmp(arg, "filter=", 7) == 0) {
2322 1.341 rillig newShell.noPrint = arg + 7;
2323 1.341 rillig newShell.noPrintLen = strlen(newShell.noPrint);
2324 1.341 rillig } else if (strncmp(arg, "echoFlag=", 9) == 0) {
2325 1.366 rillig newShell.echoFlag = arg + 9;
2326 1.341 rillig } else if (strncmp(arg, "errFlag=", 8) == 0) {
2327 1.375 rillig newShell.errFlag = arg + 8;
2328 1.341 rillig } else if (strncmp(arg, "hasErrCtl=", 10) == 0) {
2329 1.341 rillig char c = arg[10];
2330 1.341 rillig newShell.hasErrCtl = c == 'Y' || c == 'y' ||
2331 1.341 rillig c == 'T' || c == 't';
2332 1.341 rillig } else if (strncmp(arg, "newline=", 8) == 0) {
2333 1.341 rillig newShell.newline = arg + 8;
2334 1.341 rillig } else if (strncmp(arg, "check=", 6) == 0) {
2335 1.443 rillig /*
2336 1.443 rillig * Before 2020-12-10, these two variables had
2337 1.443 rillig * been a single variable.
2338 1.443 rillig */
2339 1.358 rillig newShell.errOn = arg + 6;
2340 1.364 rillig newShell.echoTmpl = arg + 6;
2341 1.341 rillig } else if (strncmp(arg, "ignore=", 7) == 0) {
2342 1.443 rillig /*
2343 1.443 rillig * Before 2020-12-10, these two variables had
2344 1.443 rillig * been a single variable.
2345 1.443 rillig */
2346 1.359 rillig newShell.errOff = arg + 7;
2347 1.364 rillig newShell.runIgnTmpl = arg + 7;
2348 1.341 rillig } else if (strncmp(arg, "errout=", 7) == 0) {
2349 1.364 rillig newShell.runChkTmpl = arg + 7;
2350 1.341 rillig } else if (strncmp(arg, "comment=", 8) == 0) {
2351 1.341 rillig newShell.commentChar = arg[8];
2352 1.341 rillig } else {
2353 1.341 rillig Parse_Error(PARSE_FATAL,
2354 1.341 rillig "Unknown keyword \"%s\"", arg);
2355 1.341 rillig free(words);
2356 1.421 rillig return false;
2357 1.341 rillig }
2358 1.421 rillig fullSpec = true;
2359 1.341 rillig }
2360 1.1 cgd }
2361 1.341 rillig
2362 1.12 christos if (path == NULL) {
2363 1.341 rillig if (newShell.name == NULL) {
2364 1.341 rillig Parse_Error(PARSE_FATAL,
2365 1.341 rillig "Neither path nor name specified");
2366 1.341 rillig free(words);
2367 1.421 rillig return false;
2368 1.341 rillig } else {
2369 1.341 rillig if ((sh = FindShellByName(newShell.name)) == NULL) {
2370 1.341 rillig Parse_Error(PARSE_WARNING,
2371 1.341 rillig "%s: No matching shell", newShell.name);
2372 1.341 rillig free(words);
2373 1.421 rillig return false;
2374 1.341 rillig }
2375 1.355 rillig shell = sh;
2376 1.341 rillig shellName = newShell.name;
2377 1.341 rillig if (shellPath != NULL) {
2378 1.478 rillig free(shellPath);
2379 1.341 rillig shellPath = NULL;
2380 1.341 rillig Shell_Init();
2381 1.341 rillig }
2382 1.341 rillig }
2383 1.1 cgd } else {
2384 1.478 rillig free(shellPath);
2385 1.477 rillig shellPath = bmake_strdup(path);
2386 1.465 rillig shellName = newShell.name != NULL ? newShell.name
2387 1.465 rillig : str_basename(path);
2388 1.341 rillig if (!fullSpec) {
2389 1.341 rillig if ((sh = FindShellByName(shellName)) == NULL) {
2390 1.341 rillig Parse_Error(PARSE_WARNING,
2391 1.341 rillig "%s: No matching shell", shellName);
2392 1.341 rillig free(words);
2393 1.421 rillig return false;
2394 1.341 rillig }
2395 1.355 rillig shell = sh;
2396 1.341 rillig } else {
2397 1.355 rillig shell = bmake_malloc(sizeof *shell);
2398 1.355 rillig *shell = newShell;
2399 1.341 rillig }
2400 1.487 rillig /* This will take care of shellErrFlag. */
2401 1.341 rillig Shell_Init();
2402 1.1 cgd }
2403 1.341 rillig
2404 1.396 rillig if (shell->echoOn != NULL && shell->echoOff != NULL)
2405 1.421 rillig shell->hasEchoCtl = true;
2406 1.1 cgd
2407 1.355 rillig if (!shell->hasErrCtl) {
2408 1.364 rillig if (shell->echoTmpl == NULL)
2409 1.364 rillig shell->echoTmpl = "";
2410 1.364 rillig if (shell->runIgnTmpl == NULL)
2411 1.364 rillig shell->runIgnTmpl = "%s\n";
2412 1.1 cgd }
2413 1.16 christos
2414 1.341 rillig /*
2415 1.487 rillig * Do not free up the words themselves, since they may be in use
2416 1.341 rillig * by the shell specification.
2417 1.341 rillig */
2418 1.341 rillig free(words);
2419 1.421 rillig return true;
2420 1.1 cgd }
2421 1.1 cgd
2422 1.341 rillig /*
2423 1.487 rillig * After receiving an interrupt signal, terminate all child processes and if
2424 1.487 rillig * necessary make the .INTERRUPT target.
2425 1.1 cgd */
2426 1.1 cgd static void
2427 1.421 rillig JobInterrupt(bool runINTERRUPT, int signo)
2428 1.69 pk {
2429 1.487 rillig Job *job;
2430 1.487 rillig GNode *interrupt;
2431 1.341 rillig sigset_t mask;
2432 1.341 rillig
2433 1.341 rillig aborting = ABORT_INTERRUPT;
2434 1.341 rillig
2435 1.341 rillig JobSigLock(&mask);
2436 1.341 rillig
2437 1.341 rillig for (job = job_table; job < job_table_end; job++) {
2438 1.486 rillig if (job->status == JOB_ST_RUNNING && job->pid != 0) {
2439 1.341 rillig DEBUG2(JOB,
2440 1.341 rillig "JobInterrupt passing signal %d to child %d.\n",
2441 1.341 rillig signo, job->pid);
2442 1.341 rillig KILLPG(job->pid, signo);
2443 1.341 rillig }
2444 1.12 christos }
2445 1.12 christos
2446 1.486 rillig for (job = job_table; job < job_table_end; job++) {
2447 1.486 rillig if (job->status == JOB_ST_RUNNING && job->pid != 0) {
2448 1.486 rillig int status;
2449 1.486 rillig (void)waitpid(job->pid, &status, 0);
2450 1.486 rillig JobDeleteTarget(job->node);
2451 1.486 rillig }
2452 1.486 rillig }
2453 1.486 rillig
2454 1.341 rillig JobSigUnlock(&mask);
2455 1.69 pk
2456 1.445 rillig if (runINTERRUPT && !opts.touch) {
2457 1.341 rillig interrupt = Targ_FindNode(".INTERRUPT");
2458 1.341 rillig if (interrupt != NULL) {
2459 1.421 rillig opts.ignoreErrors = false;
2460 1.341 rillig JobRun(interrupt);
2461 1.341 rillig }
2462 1.1 cgd }
2463 1.341 rillig Trace_Log(MAKEINTR, NULL);
2464 1.368 rillig exit(signo); /* XXX: why signo? */
2465 1.1 cgd }
2466 1.1 cgd
2467 1.487 rillig /* Make the .END target, returning the number of job-related errors. */
2468 1.1 cgd int
2469 1.72 wiz Job_Finish(void)
2470 1.1 cgd {
2471 1.341 rillig GNode *endNode = Targ_GetEndNode();
2472 1.341 rillig if (!Lst_IsEmpty(&endNode->commands) ||
2473 1.341 rillig !Lst_IsEmpty(&endNode->children)) {
2474 1.463 rillig if (job_errors != 0)
2475 1.341 rillig Error("Errors reported so .END ignored");
2476 1.463 rillig else
2477 1.341 rillig JobRun(endNode);
2478 1.1 cgd }
2479 1.341 rillig return job_errors;
2480 1.22 christos }
2481 1.22 christos
2482 1.480 rillig #ifdef CLEANUP
2483 1.22 christos void
2484 1.72 wiz Job_End(void)
2485 1.22 christos {
2486 1.407 rillig free(shell_freeIt);
2487 1.480 rillig }
2488 1.30 mycroft #endif
2489 1.1 cgd
2490 1.487 rillig /* Waits for all running jobs to finish. */
2491 1.1 cgd void
2492 1.72 wiz Job_Wait(void)
2493 1.1 cgd {
2494 1.487 rillig aborting = ABORT_WAIT; /* Prevent other jobs from starting. */
2495 1.341 rillig while (jobTokensRunning != 0) {
2496 1.341 rillig Job_CatchOutput();
2497 1.341 rillig }
2498 1.341 rillig aborting = ABORT_NONE;
2499 1.1 cgd }
2500 1.1 cgd
2501 1.341 rillig /*
2502 1.341 rillig * Abort all currently running jobs without handling output or anything.
2503 1.243 rillig * This function is to be called only in the event of a major error.
2504 1.243 rillig * Most definitely NOT to be called from JobInterrupt.
2505 1.341 rillig */
2506 1.1 cgd void
2507 1.72 wiz Job_AbortAll(void)
2508 1.1 cgd {
2509 1.487 rillig Job *job;
2510 1.487 rillig int status;
2511 1.16 christos
2512 1.341 rillig aborting = ABORT_ERROR;
2513 1.16 christos
2514 1.341 rillig if (jobTokensRunning != 0) {
2515 1.341 rillig for (job = job_table; job < job_table_end; job++) {
2516 1.341 rillig if (job->status != JOB_ST_RUNNING)
2517 1.341 rillig continue;
2518 1.341 rillig KILLPG(job->pid, SIGINT);
2519 1.341 rillig KILLPG(job->pid, SIGKILL);
2520 1.341 rillig }
2521 1.1 cgd }
2522 1.16 christos
2523 1.489 rillig while (waitpid((pid_t)-1, &status, WNOHANG) > 0)
2524 1.341 rillig continue;
2525 1.12 christos }
2526 1.12 christos
2527 1.341 rillig /*
2528 1.341 rillig * Tries to restart stopped jobs if there are slots available.
2529 1.487 rillig * Called in response to a SIGCONT.
2530 1.341 rillig */
2531 1.12 christos static void
2532 1.72 wiz JobRestartJobs(void)
2533 1.12 christos {
2534 1.341 rillig Job *job;
2535 1.69 pk
2536 1.341 rillig for (job = job_table; job < job_table_end; job++) {
2537 1.341 rillig if (job->status == JOB_ST_RUNNING &&
2538 1.341 rillig (make_suspended || job->suspended)) {
2539 1.341 rillig DEBUG1(JOB, "Restarting stopped job pid %d.\n",
2540 1.341 rillig job->pid);
2541 1.341 rillig if (job->suspended) {
2542 1.341 rillig (void)printf("*** [%s] Continued\n",
2543 1.341 rillig job->node->name);
2544 1.341 rillig (void)fflush(stdout);
2545 1.341 rillig }
2546 1.421 rillig job->suspended = false;
2547 1.341 rillig if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
2548 1.341 rillig debug_printf("Failed to send SIGCONT to %d\n",
2549 1.341 rillig job->pid);
2550 1.341 rillig }
2551 1.341 rillig }
2552 1.341 rillig if (job->status == JOB_ST_FINISHED) {
2553 1.341 rillig /*
2554 1.341 rillig * Job exit deferred after calling waitpid() in a
2555 1.341 rillig * signal handler
2556 1.341 rillig */
2557 1.341 rillig JobFinish(job, job->exit_status);
2558 1.341 rillig }
2559 1.341 rillig }
2560 1.421 rillig make_suspended = false;
2561 1.1 cgd }
2562 1.35 christos
2563 1.35 christos static void
2564 1.72 wiz watchfd(Job *job)
2565 1.35 christos {
2566 1.341 rillig if (job->inPollfd != NULL)
2567 1.341 rillig Punt("Watching watched job");
2568 1.35 christos
2569 1.408 rillig fds[fdsLen].fd = job->inPipe;
2570 1.408 rillig fds[fdsLen].events = POLLIN;
2571 1.408 rillig jobByFdIndex[fdsLen] = job;
2572 1.408 rillig job->inPollfd = &fds[fdsLen];
2573 1.408 rillig fdsLen++;
2574 1.341 rillig #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2575 1.341 rillig if (useMeta) {
2576 1.408 rillig fds[fdsLen].fd = meta_job_fd(job);
2577 1.408 rillig fds[fdsLen].events = fds[fdsLen].fd == -1 ? 0 : POLLIN;
2578 1.408 rillig jobByFdIndex[fdsLen] = job;
2579 1.408 rillig fdsLen++;
2580 1.341 rillig }
2581 1.196 riastrad #endif
2582 1.35 christos }
2583 1.35 christos
2584 1.35 christos static void
2585 1.72 wiz clearfd(Job *job)
2586 1.35 christos {
2587 1.341 rillig size_t i;
2588 1.341 rillig if (job->inPollfd == NULL)
2589 1.341 rillig Punt("Unwatching unwatched job");
2590 1.341 rillig i = (size_t)(job->inPollfd - fds);
2591 1.408 rillig fdsLen--;
2592 1.197 sjg #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2593 1.341 rillig if (useMeta) {
2594 1.341 rillig assert(nfds_per_job() == 2);
2595 1.397 rillig if (i % 2 != 0)
2596 1.341 rillig Punt("odd-numbered fd with meta");
2597 1.408 rillig fdsLen--;
2598 1.341 rillig }
2599 1.341 rillig #endif
2600 1.461 rillig /* Move last job in table into hole made by dead job. */
2601 1.408 rillig if (fdsLen != i) {
2602 1.408 rillig fds[i] = fds[fdsLen];
2603 1.408 rillig jobByFdIndex[i] = jobByFdIndex[fdsLen];
2604 1.408 rillig jobByFdIndex[i]->inPollfd = &fds[i];
2605 1.341 rillig #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
2606 1.341 rillig if (useMeta) {
2607 1.408 rillig fds[i + 1] = fds[fdsLen + 1];
2608 1.408 rillig jobByFdIndex[i + 1] = jobByFdIndex[fdsLen + 1];
2609 1.341 rillig }
2610 1.196 riastrad #endif
2611 1.196 riastrad }
2612 1.341 rillig job->inPollfd = NULL;
2613 1.35 christos }
2614 1.35 christos
2615 1.391 rillig /*
2616 1.391 rillig * Put a token (back) into the job pipe.
2617 1.391 rillig * This allows a make process to start a build job.
2618 1.391 rillig */
2619 1.40 sommerfe static void
2620 1.72 wiz JobTokenAdd(void)
2621 1.40 sommerfe {
2622 1.341 rillig char tok = JOB_TOKENS[aborting], tok1;
2623 1.101 dsl
2624 1.487 rillig /* If we are depositing an error token, flush everything else. */
2625 1.341 rillig while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2626 1.341 rillig continue;
2627 1.341 rillig
2628 1.341 rillig DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
2629 1.341 rillig getpid(), aborting, JOB_TOKENS[aborting]);
2630 1.341 rillig while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
2631 1.341 rillig continue;
2632 1.40 sommerfe }
2633 1.40 sommerfe
2634 1.419 sjg int
2635 1.419 sjg Job_TempFile(const char *pattern, char *tfile, size_t tfile_sz)
2636 1.419 sjg {
2637 1.419 sjg int fd;
2638 1.419 sjg sigset_t mask;
2639 1.419 sjg
2640 1.419 sjg JobSigLock(&mask);
2641 1.419 sjg fd = mkTempFile(pattern, tfile, tfile_sz);
2642 1.420 sjg if (tfile != NULL && !DEBUG(SCRIPT))
2643 1.442 rillig unlink(tfile);
2644 1.419 sjg JobSigUnlock(&mask);
2645 1.419 sjg
2646 1.419 sjg return fd;
2647 1.419 sjg }
2648 1.419 sjg
2649 1.487 rillig /* Prepare the job token pipe in the root make process. */
2650 1.72 wiz void
2651 1.122 dsl Job_ServerStart(int max_tokens, int jp_0, int jp_1)
2652 1.40 sommerfe {
2653 1.341 rillig int i;
2654 1.341 rillig char jobarg[64];
2655 1.201 rillig
2656 1.341 rillig if (jp_0 >= 0 && jp_1 >= 0) {
2657 1.341 rillig tokenWaitJob.inPipe = jp_0;
2658 1.341 rillig tokenWaitJob.outPipe = jp_1;
2659 1.341 rillig (void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
2660 1.341 rillig (void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
2661 1.341 rillig return;
2662 1.341 rillig }
2663 1.100 dsl
2664 1.341 rillig JobCreatePipe(&tokenWaitJob, 15);
2665 1.40 sommerfe
2666 1.341 rillig snprintf(jobarg, sizeof jobarg, "%d,%d",
2667 1.122 dsl tokenWaitJob.inPipe, tokenWaitJob.outPipe);
2668 1.40 sommerfe
2669 1.415 rillig Global_Append(MAKEFLAGS, "-J");
2670 1.415 rillig Global_Append(MAKEFLAGS, jobarg);
2671 1.101 dsl
2672 1.341 rillig /*
2673 1.341 rillig * Preload the job pipe with one token per job, save the one
2674 1.341 rillig * "extra" token for the primary job.
2675 1.341 rillig *
2676 1.341 rillig * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
2677 1.341 rillig * larger than the write buffer size of the pipe, we will
2678 1.341 rillig * deadlock here.
2679 1.341 rillig */
2680 1.341 rillig for (i = 1; i < max_tokens; i++)
2681 1.341 rillig JobTokenAdd();
2682 1.40 sommerfe }
2683 1.40 sommerfe
2684 1.243 rillig /* Return a withdrawn token to the pool. */
2685 1.40 sommerfe void
2686 1.72 wiz Job_TokenReturn(void)
2687 1.40 sommerfe {
2688 1.341 rillig jobTokensRunning--;
2689 1.341 rillig if (jobTokensRunning < 0)
2690 1.341 rillig Punt("token botch");
2691 1.396 rillig if (jobTokensRunning != 0 || JOB_TOKENS[aborting] != '+')
2692 1.341 rillig JobTokenAdd();
2693 1.40 sommerfe }
2694 1.40 sommerfe
2695 1.341 rillig /*
2696 1.341 rillig * Attempt to withdraw a token from the pool.
2697 1.40 sommerfe *
2698 1.487 rillig * If the pool is empty, set wantToken so that we wake up when a token is
2699 1.243 rillig * released.
2700 1.40 sommerfe *
2701 1.421 rillig * Returns true if a token was withdrawn, and false if the pool is currently
2702 1.341 rillig * empty.
2703 1.341 rillig */
2704 1.421 rillig bool
2705 1.72 wiz Job_TokenWithdraw(void)
2706 1.40 sommerfe {
2707 1.341 rillig char tok, tok1;
2708 1.341 rillig ssize_t count;
2709 1.40 sommerfe
2710 1.492 rillig wantToken = false;
2711 1.341 rillig DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
2712 1.341 rillig getpid(), aborting, jobTokensRunning);
2713 1.60 enami
2714 1.341 rillig if (aborting != ABORT_NONE || (jobTokensRunning >= opts.maxJobs))
2715 1.421 rillig return false;
2716 1.40 sommerfe
2717 1.341 rillig count = read(tokenWaitJob.inPipe, &tok, 1);
2718 1.341 rillig if (count == 0)
2719 1.341 rillig Fatal("eof on job pipe!");
2720 1.341 rillig if (count < 0 && jobTokensRunning != 0) {
2721 1.463 rillig if (errno != EAGAIN)
2722 1.341 rillig Fatal("job pipe read: %s", strerror(errno));
2723 1.341 rillig DEBUG1(JOB, "(%d) blocked for token\n", getpid());
2724 1.492 rillig wantToken = true;
2725 1.421 rillig return false;
2726 1.40 sommerfe }
2727 1.102 dsl
2728 1.341 rillig if (count == 1 && tok != '+') {
2729 1.341 rillig /* make being aborted - remove any other job tokens */
2730 1.341 rillig DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
2731 1.341 rillig while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
2732 1.341 rillig continue;
2733 1.341 rillig /* And put the stopper back */
2734 1.341 rillig while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
2735 1.341 rillig errno == EAGAIN)
2736 1.341 rillig continue;
2737 1.487 rillig if (shouldDieQuietly(NULL, 1)) {
2738 1.488 rillig Job_Wait();
2739 1.487 rillig exit(6);
2740 1.487 rillig }
2741 1.341 rillig Fatal("A failure has been detected "
2742 1.341 rillig "in another branch of the parallel make");
2743 1.341 rillig }
2744 1.341 rillig
2745 1.341 rillig if (count == 1 && jobTokensRunning == 0)
2746 1.341 rillig /* We didn't want the token really */
2747 1.341 rillig while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
2748 1.341 rillig errno == EAGAIN)
2749 1.341 rillig continue;
2750 1.102 dsl
2751 1.341 rillig jobTokensRunning++;
2752 1.341 rillig DEBUG1(JOB, "(%d) withdrew token\n", getpid());
2753 1.421 rillig return true;
2754 1.41 sommerfe }
2755 1.41 sommerfe
2756 1.487 rillig /* Make the named target if found, exit if the target fails. */
2757 1.421 rillig bool
2758 1.341 rillig Job_RunTarget(const char *target, const char *fname)
2759 1.341 rillig {
2760 1.341 rillig GNode *gn = Targ_FindNode(target);
2761 1.341 rillig if (gn == NULL)
2762 1.421 rillig return false;
2763 1.172 christos
2764 1.341 rillig if (fname != NULL)
2765 1.417 rillig Var_Set(gn, ALLSRC, fname);
2766 1.172 christos
2767 1.341 rillig JobRun(gn);
2768 1.421 rillig return true;
2769 1.172 christos }
2770 1.172 christos
2771 1.73 gson #ifdef USE_SELECT
2772 1.73 gson int
2773 1.73 gson emul_poll(struct pollfd *fd, int nfd, int timeout)
2774 1.73 gson {
2775 1.341 rillig fd_set rfds, wfds;
2776 1.341 rillig int i, maxfd, nselect, npoll;
2777 1.341 rillig struct timeval tv, *tvp;
2778 1.341 rillig long usecs;
2779 1.73 gson
2780 1.341 rillig FD_ZERO(&rfds);
2781 1.341 rillig FD_ZERO(&wfds);
2782 1.73 gson
2783 1.341 rillig maxfd = -1;
2784 1.341 rillig for (i = 0; i < nfd; i++) {
2785 1.341 rillig fd[i].revents = 0;
2786 1.73 gson
2787 1.341 rillig if (fd[i].events & POLLIN)
2788 1.341 rillig FD_SET(fd[i].fd, &rfds);
2789 1.341 rillig
2790 1.341 rillig if (fd[i].events & POLLOUT)
2791 1.341 rillig FD_SET(fd[i].fd, &wfds);
2792 1.341 rillig
2793 1.341 rillig if (fd[i].fd > maxfd)
2794 1.341 rillig maxfd = fd[i].fd;
2795 1.341 rillig }
2796 1.201 rillig
2797 1.341 rillig if (maxfd >= FD_SETSIZE) {
2798 1.341 rillig Punt("Ran out of fd_set slots; "
2799 1.341 rillig "recompile with a larger FD_SETSIZE.");
2800 1.341 rillig }
2801 1.73 gson
2802 1.341 rillig if (timeout < 0) {
2803 1.341 rillig tvp = NULL;
2804 1.341 rillig } else {
2805 1.341 rillig usecs = timeout * 1000;
2806 1.341 rillig tv.tv_sec = usecs / 1000000;
2807 1.341 rillig tv.tv_usec = usecs % 1000000;
2808 1.341 rillig tvp = &tv;
2809 1.341 rillig }
2810 1.73 gson
2811 1.341 rillig nselect = select(maxfd + 1, &rfds, &wfds, NULL, tvp);
2812 1.73 gson
2813 1.341 rillig if (nselect <= 0)
2814 1.341 rillig return nselect;
2815 1.73 gson
2816 1.341 rillig npoll = 0;
2817 1.341 rillig for (i = 0; i < nfd; i++) {
2818 1.341 rillig if (FD_ISSET(fd[i].fd, &rfds))
2819 1.341 rillig fd[i].revents |= POLLIN;
2820 1.73 gson
2821 1.341 rillig if (FD_ISSET(fd[i].fd, &wfds))
2822 1.341 rillig fd[i].revents |= POLLOUT;
2823 1.73 gson
2824 1.341 rillig if (fd[i].revents)
2825 1.341 rillig npoll++;
2826 1.341 rillig }
2827 1.73 gson
2828 1.341 rillig return npoll;
2829 1.73 gson }
2830 1.443 rillig #endif /* USE_SELECT */
2831