compat.c revision 1.183 1 /* $NetBSD: compat.c,v 1.183 2020/11/15 22:31:03 rillig Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 /*
36 * Copyright (c) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
39 *
40 * This code is derived from software contributed to Berkeley by
41 * Adam de Boor.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
58 *
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
70 */
71
72 /*-
73 * compat.c --
74 * The routines in this file implement the full-compatibility
75 * mode of PMake. Most of the special functionality of PMake
76 * is available in this mode. Things not supported:
77 * - different shells.
78 * - friendly variable substitution.
79 *
80 * Interface:
81 * Compat_Run Initialize things for this module and recreate
82 * thems as need creatin'
83 */
84
85 #include <sys/types.h>
86 #include <sys/stat.h>
87 #include <sys/wait.h>
88
89 #include <errno.h>
90 #include <signal.h>
91
92 #include "make.h"
93 #include "dir.h"
94 #include "job.h"
95 #include "metachar.h"
96 #include "pathnames.h"
97
98 /* "@(#)compat.c 8.2 (Berkeley) 3/19/94" */
99 MAKE_RCSID("$NetBSD: compat.c,v 1.183 2020/11/15 22:31:03 rillig Exp $");
100
101 static GNode *curTarg = NULL;
102 static pid_t compatChild;
103 static int compatSigno;
104
105 /*
106 * CompatDeleteTarget -- delete the file of a failed, interrupted, or
107 * otherwise duffed target if not inhibited by .PRECIOUS.
108 */
109 static void
110 CompatDeleteTarget(GNode *gn)
111 {
112 if (gn != NULL && !Targ_Precious(gn)) {
113 const char *file = GNode_VarTarget(gn);
114
115 if (!opts.noExecute && eunlink(file) != -1) {
116 Error("*** %s removed", file);
117 }
118 }
119 }
120
121 /* Interrupt the creation of the current target and remove it if it ain't
122 * precious. Then exit.
123 *
124 * If .INTERRUPT exists, its commands are run first WITH INTERRUPTS IGNORED.
125 *
126 * XXX: is .PRECIOUS supposed to inhibit .INTERRUPT? I doubt it, but I've
127 * left the logic alone for now. - dholland 20160826
128 */
129 static void
130 CompatInterrupt(int signo)
131 {
132 CompatDeleteTarget(curTarg);
133
134 if (curTarg != NULL && !Targ_Precious(curTarg)) {
135 /*
136 * Run .INTERRUPT only if hit with interrupt signal
137 */
138 if (signo == SIGINT) {
139 GNode *gn = Targ_FindNode(".INTERRUPT");
140 if (gn != NULL) {
141 Compat_Make(gn, gn);
142 }
143 }
144 }
145
146 if (signo == SIGQUIT)
147 _exit(signo);
148
149 /*
150 * If there is a child running, pass the signal on.
151 * We will exist after it has exited.
152 */
153 compatSigno = signo;
154 if (compatChild > 0) {
155 KILLPG(compatChild, signo);
156 } else {
157 bmake_signal(signo, SIG_DFL);
158 kill(myPid, signo);
159 }
160 }
161
162 /* Execute the next command for a target. If the command returns an error,
163 * the node's made field is set to ERROR and creation stops.
164 *
165 * Input:
166 * cmdp Command to execute
167 * gnp Node from which the command came
168 *
169 * Results:
170 * 0 if the command succeeded, 1 if an error occurred.
171 */
172 int
173 Compat_RunCommand(const char *cmdp, GNode *gn)
174 {
175 char *cmdStart; /* Start of expanded command */
176 char *bp;
177 Boolean silent; /* Don't print command */
178 Boolean doIt; /* Execute even if -n */
179 volatile Boolean errCheck; /* Check errors */
180 int reason; /* Reason for child's death */
181 int status; /* Description of child's death */
182 pid_t cpid; /* Child actually found */
183 pid_t retstat; /* Result of wait */
184 StringListNode *cmdNode; /* Node where current command is located */
185 const char **volatile av; /* Argument vector for thing to exec */
186 char **volatile mav; /* Copy of the argument vector for freeing */
187 Boolean useShell; /* TRUE if command should be executed
188 * using a shell */
189 const char *volatile cmd = cmdp;
190
191 silent = (gn->type & OP_SILENT) != 0;
192 errCheck = !(gn->type & OP_IGNORE);
193 doIt = FALSE;
194
195 /* Luckily the commands don't end up in a string pool, otherwise
196 * this comparison could match too early, in a dependency using "..."
197 * for delayed commands, run in parallel mode, using the same shell
198 * command line more than once; see JobPrintCommand.
199 * TODO: write a unit-test to protect against this potential bug. */
200 cmdNode = Lst_FindDatum(gn->commands, cmd);
201 (void)Var_Subst(cmd, gn, VARE_WANTRES, &cmdStart);
202 /* TODO: handle errors */
203
204 if (cmdStart[0] == '\0') {
205 free(cmdStart);
206 return 0;
207 }
208 cmd = cmdStart;
209 LstNode_Set(cmdNode, cmdStart);
210
211 if (gn->type & OP_SAVE_CMDS) {
212 GNode *endNode = Targ_GetEndNode();
213 if (gn != endNode) {
214 Lst_Append(endNode->commands, cmdStart);
215 return 0;
216 }
217 }
218 if (strcmp(cmdStart, "...") == 0) {
219 gn->type |= OP_SAVE_CMDS;
220 return 0;
221 }
222
223 for (;;) {
224 if (*cmd == '@')
225 silent = !DEBUG(LOUD);
226 else if (*cmd == '-')
227 errCheck = FALSE;
228 else if (*cmd == '+') {
229 doIt = TRUE;
230 if (!shellName) /* we came here from jobs */
231 Shell_Init();
232 } else
233 break;
234 cmd++;
235 }
236
237 while (ch_isspace(*cmd))
238 cmd++;
239
240 /*
241 * If we did not end up with a command, just skip it.
242 */
243 if (cmd[0] == '\0')
244 return 0;
245
246 #if !defined(MAKE_NATIVE)
247 /*
248 * In a non-native build, the host environment might be weird enough
249 * that it's necessary to go through a shell to get the correct
250 * behaviour. Or perhaps the shell has been replaced with something
251 * that does extra logging, and that should not be bypassed.
252 */
253 useShell = TRUE;
254 #else
255 /*
256 * Search for meta characters in the command. If there are no meta
257 * characters, there's no need to execute a shell to execute the
258 * command.
259 *
260 * Additionally variable assignments and empty commands
261 * go to the shell. Therefore treat '=' and ':' like shell
262 * meta characters as documented in make(1).
263 */
264
265 useShell = needshell(cmd);
266 #endif
267
268 /*
269 * Print the command before echoing if we're not supposed to be quiet for
270 * this one. We also print the command if -n given.
271 */
272 if (!silent || !GNode_ShouldExecute(gn)) {
273 printf("%s\n", cmd);
274 fflush(stdout);
275 }
276
277 /*
278 * If we're not supposed to execute any commands, this is as far as
279 * we go...
280 */
281 if (!doIt && !GNode_ShouldExecute(gn))
282 return 0;
283
284 DEBUG1(JOB, "Execute: '%s'\n", cmd);
285
286 if (useShell) {
287 /*
288 * We need to pass the command off to the shell, typically
289 * because the command contains a "meta" character.
290 */
291 static const char *shargv[5];
292
293 /* The following work for any of the builtin shell specs. */
294 int shargc = 0;
295 shargv[shargc++] = shellPath;
296 if (errCheck && shellErrFlag)
297 shargv[shargc++] = shellErrFlag;
298 shargv[shargc++] = DEBUG(SHELL) ? "-xc" : "-c";
299 shargv[shargc++] = cmd;
300 shargv[shargc] = NULL;
301 av = shargv;
302 bp = NULL;
303 mav = NULL;
304 } else {
305 /*
306 * No meta-characters, so no need to exec a shell. Break the command
307 * into words to form an argument vector we can execute.
308 */
309 Words words = Str_Words(cmd, FALSE);
310 mav = words.words;
311 bp = words.freeIt;
312 av = (void *)mav;
313 }
314
315 #ifdef USE_META
316 if (useMeta) {
317 meta_compat_start();
318 }
319 #endif
320
321 /*
322 * Fork and execute the single command. If the fork fails, we abort.
323 */
324 compatChild = cpid = vFork();
325 if (cpid < 0) {
326 Fatal("Could not fork");
327 }
328 if (cpid == 0) {
329 Var_ExportVars();
330 #ifdef USE_META
331 if (useMeta) {
332 meta_compat_child();
333 }
334 #endif
335 (void)execvp(av[0], (char *const *)UNCONST(av));
336 execDie("exec", av[0]);
337 }
338
339 free(mav);
340 free(bp);
341
342 /* XXX: Memory management looks suspicious here. */
343 /* XXX: Setting a list item to NULL is unexpected. */
344 LstNode_SetNull(cmdNode);
345
346 #ifdef USE_META
347 if (useMeta) {
348 meta_compat_parent(cpid);
349 }
350 #endif
351
352 /*
353 * The child is off and running. Now all we can do is wait...
354 */
355 while ((retstat = wait(&reason)) != cpid) {
356 if (retstat > 0)
357 JobReapChild(retstat, reason, FALSE); /* not ours? */
358 if (retstat == -1 && errno != EINTR) {
359 break;
360 }
361 }
362
363 if (retstat < 0)
364 Fatal("error in wait: %d: %s", retstat, strerror(errno));
365
366 if (WIFSTOPPED(reason)) {
367 status = WSTOPSIG(reason); /* stopped */
368 } else if (WIFEXITED(reason)) {
369 status = WEXITSTATUS(reason); /* exited */
370 #if defined(USE_META) && defined(USE_FILEMON_ONCE)
371 if (useMeta) {
372 meta_cmd_finish(NULL);
373 }
374 #endif
375 if (status != 0) {
376 if (DEBUG(ERROR)) {
377 const char *p = cmd;
378 debug_printf("\n*** Failed target: %s\n*** Failed command: ",
379 gn->name);
380
381 /* Replace runs of whitespace with a single space, to reduce
382 * the amount of whitespace for multi-line command lines. */
383 while (*p != '\0') {
384 if (ch_isspace(*p)) {
385 debug_printf(" ");
386 cpp_skip_whitespace(&p);
387 } else {
388 debug_printf("%c", *p);
389 p++;
390 }
391 }
392 debug_printf("\n");
393 }
394 printf("*** Error code %d", status);
395 }
396 } else {
397 status = WTERMSIG(reason); /* signaled */
398 printf("*** Signal %d", status);
399 }
400
401
402 if (!WIFEXITED(reason) || status != 0) {
403 if (errCheck) {
404 #ifdef USE_META
405 if (useMeta) {
406 meta_job_error(NULL, gn, 0, status);
407 }
408 #endif
409 gn->made = ERROR;
410 if (opts.keepgoing) {
411 /* Abort the current target, but let others continue. */
412 printf(" (continuing)\n");
413 } else {
414 printf("\n");
415 }
416 if (deleteOnError)
417 CompatDeleteTarget(gn);
418 } else {
419 /*
420 * Continue executing commands for this target.
421 * If we return 0, this will happen...
422 */
423 printf(" (ignored)\n");
424 status = 0;
425 }
426 }
427
428 free(cmdStart);
429 compatChild = 0;
430 if (compatSigno) {
431 bmake_signal(compatSigno, SIG_DFL);
432 kill(myPid, compatSigno);
433 }
434
435 return status;
436 }
437
438 static void
439 RunCommands(GNode *gn)
440 {
441 StringListNode *ln;
442 for (ln = gn->commands->first; ln != NULL; ln = ln->next) {
443 const char *cmd = ln->datum;
444 if (Compat_RunCommand(cmd, gn) != 0)
445 break;
446 }
447 }
448
449 static void
450 MakeNodes(GNodeList *gnodes, GNode *pgn)
451 {
452 GNodeListNode *ln;
453 for (ln = gnodes->first; ln != NULL; ln = ln->next) {
454 GNode *cohort = ln->datum;
455 Compat_Make(cohort, pgn);
456 }
457 }
458
459 /* Make a target.
460 *
461 * If an error is detected and not being ignored, the process exits.
462 *
463 * Input:
464 * gn The node to make
465 * pgn Parent to abort if necessary
466 */
467 void
468 Compat_Make(GNode *gn, GNode *pgn)
469 {
470 if (shellName == NULL) /* we came here from jobs */
471 Shell_Init();
472
473 if (gn->made == UNMADE && (gn == pgn || !(pgn->type & OP_MADE))) {
474 /*
475 * First mark ourselves to be made, then apply whatever transformations
476 * the suffix module thinks are necessary. Once that's done, we can
477 * descend and make all our children. If any of them has an error
478 * but the -k flag was given, our 'make' field will be set to FALSE
479 * again. This is our signal to not attempt to do anything but abort
480 * our parent as well.
481 */
482 gn->flags |= REMAKE;
483 gn->made = BEINGMADE;
484 if (!(gn->type & OP_MADE))
485 Suff_FindDeps(gn);
486 MakeNodes(gn->children, gn);
487 if (!(gn->flags & REMAKE)) {
488 gn->made = ABORTED;
489 pgn->flags &= ~(unsigned)REMAKE;
490 goto cohorts;
491 }
492
493 if (Lst_FindDatum(gn->implicitParents, pgn) != NULL)
494 Var_Set(IMPSRC, GNode_VarTarget(gn), pgn);
495
496 /*
497 * All the children were made ok. Now youngestChild->mtime contains the
498 * modification time of the newest child, we need to find out if we
499 * exist and when we were modified last. The criteria for datedness
500 * are defined by GNode_IsOODate.
501 */
502 DEBUG1(MAKE, "Examining %s...", gn->name);
503 if (!GNode_IsOODate(gn)) {
504 gn->made = UPTODATE;
505 DEBUG0(MAKE, "up-to-date.\n");
506 goto cohorts;
507 } else
508 DEBUG0(MAKE, "out-of-date.\n");
509
510 /*
511 * If the user is just seeing if something is out-of-date, exit now
512 * to tell him/her "yes".
513 */
514 if (opts.queryFlag)
515 exit(1);
516
517 /*
518 * We need to be re-made. We also have to make sure we've got a $?
519 * variable. To be nice, we also define the $> variable using
520 * Make_DoAllVar().
521 */
522 Make_DoAllVar(gn);
523
524 /*
525 * Alter our type to tell if errors should be ignored or things
526 * should not be printed so CompatRunCommand knows what to do.
527 */
528 if (Targ_Ignore(gn))
529 gn->type |= OP_IGNORE;
530 if (Targ_Silent(gn))
531 gn->type |= OP_SILENT;
532
533 if (Job_CheckCommands(gn, Fatal)) {
534 /*
535 * Our commands are ok, but we still have to worry about the -t
536 * flag...
537 */
538 if (!opts.touchFlag || (gn->type & OP_MAKE)) {
539 curTarg = gn;
540 #ifdef USE_META
541 if (useMeta && GNode_ShouldExecute(gn)) {
542 meta_job_start(NULL, gn);
543 }
544 #endif
545 RunCommands(gn);
546 curTarg = NULL;
547 } else {
548 Job_Touch(gn, (gn->type & OP_SILENT) != 0);
549 }
550 } else {
551 gn->made = ERROR;
552 }
553 #ifdef USE_META
554 if (useMeta && GNode_ShouldExecute(gn)) {
555 if (meta_job_finish(NULL) != 0)
556 gn->made = ERROR;
557 }
558 #endif
559
560 if (gn->made != ERROR) {
561 /*
562 * If the node was made successfully, mark it so, update
563 * its modification time and timestamp all its parents.
564 * This is to keep its state from affecting that of its parent.
565 */
566 gn->made = MADE;
567 if (Make_Recheck(gn) == 0)
568 pgn->flags |= FORCE;
569 if (!(gn->type & OP_EXEC)) {
570 pgn->flags |= CHILDMADE;
571 GNode_UpdateYoungestChild(pgn, gn);
572 }
573 } else if (opts.keepgoing) {
574 pgn->flags &= ~(unsigned)REMAKE;
575 } else {
576 PrintOnError(gn, "\nStop.");
577 exit(1);
578 }
579 } else if (gn->made == ERROR) {
580 /* Already had an error when making this. Tell the parent to abort. */
581 pgn->flags &= ~(unsigned)REMAKE;
582 } else {
583 if (Lst_FindDatum(gn->implicitParents, pgn) != NULL) {
584 const char *target = GNode_VarTarget(gn);
585 Var_Set(IMPSRC, target != NULL ? target : "", pgn);
586 }
587 switch(gn->made) {
588 case BEINGMADE:
589 Error("Graph cycles through %s", gn->name);
590 gn->made = ERROR;
591 pgn->flags &= ~(unsigned)REMAKE;
592 break;
593 case MADE:
594 if (!(gn->type & OP_EXEC)) {
595 pgn->flags |= CHILDMADE;
596 GNode_UpdateYoungestChild(pgn, gn);
597 }
598 break;
599 case UPTODATE:
600 if (!(gn->type & OP_EXEC))
601 GNode_UpdateYoungestChild(pgn, gn);
602 break;
603 default:
604 break;
605 }
606 }
607
608 cohorts:
609 MakeNodes(gn->cohorts, pgn);
610 }
611
612 /* Initialize this module and start making.
613 *
614 * Input:
615 * targs The target nodes to re-create
616 */
617 void
618 Compat_Run(GNodeList *targs)
619 {
620 GNode *gn = NULL; /* Current root target */
621 int errors; /* Number of targets not remade due to errors */
622
623 if (!shellName)
624 Shell_Init();
625
626 if (bmake_signal(SIGINT, SIG_IGN) != SIG_IGN)
627 bmake_signal(SIGINT, CompatInterrupt);
628 if (bmake_signal(SIGTERM, SIG_IGN) != SIG_IGN)
629 bmake_signal(SIGTERM, CompatInterrupt);
630 if (bmake_signal(SIGHUP, SIG_IGN) != SIG_IGN)
631 bmake_signal(SIGHUP, CompatInterrupt);
632 if (bmake_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
633 bmake_signal(SIGQUIT, CompatInterrupt);
634
635 /* Create the .END node now, to keep the (debug) output of the
636 * counter.mk test the same as before 2020-09-23. This implementation
637 * detail probably doesn't matter though. */
638 (void)Targ_GetEndNode();
639 /*
640 * If the user has defined a .BEGIN target, execute the commands attached
641 * to it.
642 */
643 if (!opts.queryFlag) {
644 gn = Targ_FindNode(".BEGIN");
645 if (gn != NULL) {
646 Compat_Make(gn, gn);
647 if (gn->made == ERROR) {
648 PrintOnError(gn, "\nStop.");
649 exit(1);
650 }
651 }
652 }
653
654 /*
655 * Expand .USE nodes right now, because they can modify the structure
656 * of the tree.
657 */
658 Make_ExpandUse(targs);
659
660 /*
661 * For each entry in the list of targets to create, call Compat_Make on
662 * it to create the thing. Compat_Make will leave the 'made' field of gn
663 * in one of several states:
664 * UPTODATE gn was already up-to-date
665 * MADE gn was recreated successfully
666 * ERROR An error occurred while gn was being created
667 * ABORTED gn was not remade because one of its inferiors
668 * could not be made due to errors.
669 */
670 errors = 0;
671 while (!Lst_IsEmpty(targs)) {
672 gn = Lst_Dequeue(targs);
673 Compat_Make(gn, gn);
674
675 if (gn->made == UPTODATE) {
676 printf("`%s' is up to date.\n", gn->name);
677 } else if (gn->made == ABORTED) {
678 printf("`%s' not remade because of errors.\n", gn->name);
679 errors++;
680 }
681 }
682
683 /*
684 * If the user has defined a .END target, run its commands.
685 */
686 if (errors == 0) {
687 GNode *endNode = Targ_GetEndNode();
688 Compat_Make(endNode, endNode);
689 /* XXX: Did you mean endNode->made instead of gn->made? */
690 if (gn->made == ERROR) {
691 PrintOnError(gn, "\nStop.");
692 exit(1);
693 }
694 }
695 }
696