Fri Jan 29 23:45:35 2021 UTC ()
make(1): explain seemingly redundant condition in jobs mode


(rillig)
diff -r1.401 -r1.402 src/usr.bin/make/job.c

cvs diff -r1.401 -r1.402 src/usr.bin/make/job.c (switch to unified diff)

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