1 /* $NetBSD: compat.c,v 1.244 2023/01/17 21:35:19 christos Exp $ */
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
36 * Copyright (c) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
40 * This code is derived from software contributed to Berkeley by
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
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.
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
73 * This file implements the full-compatibility mode of make, which makes the
74 * targets without parallelism and without a custom shell.
77 * Compat_MakeAll Initialize this module and make the given targets.
83 #include <sys/types.h>
94 #include "pathnames.h"
96 /* "@(#)compat.c 8.2 (Berkeley) 3/19/94" */
97 MAKE_RCSID("$NetBSD: compat.c,v 1.244 2023/01/17 21:35:19 christos Exp $");
99 static GNode *curTarg = NULL;
100 static pid_t compatChild;
101 static int compatSigno;
104 * Delete the file of a failed, interrupted, or otherwise duffed target,
105 * unless inhibited by .PRECIOUS.
108 CompatDeleteTarget(GNode *gn)
110 if (gn != NULL && !GNode_IsPrecious(gn)) {
111 const char *file = GNode_VarTarget(gn);
113 if (!opts.noExecute && unlink_file(file) == 0) {
114 Error("*** %s removed", file);
120 * Interrupt the creation of the current target and remove it if it ain't
121 * precious. Then exit.
123 * If .INTERRUPT exists, its commands are run first WITH INTERRUPTS IGNORED.
125 * XXX: is .PRECIOUS supposed to inhibit .INTERRUPT? I doubt it, but I've
126 * left the logic alone for now. - dholland 20160826
129 CompatInterrupt(int signo)
131 CompatDeleteTarget(curTarg);
133 if (curTarg != NULL && !GNode_IsPrecious(curTarg)) {
135 * Run .INTERRUPT only if hit with interrupt signal
137 if (signo == SIGINT) {
138 GNode *gn = Targ_FindNode(".INTERRUPT");
145 if (signo == SIGQUIT)
149 * If there is a child running, pass the signal on.
150 * We will exist after it has exited.
153 if (compatChild > 0) {
154 KILLPG(compatChild, signo);
156 bmake_signal(signo, SIG_DFL);
162 DebugFailedTarget(const char *cmd, const GNode *gn)
165 debug_printf("\n*** Failed target: %s\n*** Failed command: ",
169 * Replace runs of whitespace with a single space, to reduce the
170 * amount of whitespace for multi-line command lines.
173 if (ch_isspace(*p)) {
175 cpp_skip_whitespace(&p);
177 debug_printf("%c", *p);
185 UseShell(const char *cmd MAKE_ATTR_UNUSED)
187 #if defined(FORCE_USE_SHELL) || !defined(MAKE_NATIVE)
189 * In a non-native build, the host environment might be weird enough
190 * that it's necessary to go through a shell to get the correct
191 * behaviour. Or perhaps the shell has been replaced with something
192 * that does extra logging, and that should not be bypassed.
197 * Search for meta characters in the command. If there are no meta
198 * characters, there's no need to execute a shell to execute the
201 * Additionally variable assignments and empty commands
202 * go to the shell. Therefore treat '=' and ':' like shell
203 * meta characters as documented in make(1).
206 return needshell(cmd);
211 * Execute the next command for a target. If the command returns an error,
212 * the node's made field is set to ERROR and creation stops.
215 * cmdp Command to execute
216 * gn Node from which the command came
217 * ln List node that contains the command
220 * true if the command succeeded.
223 Compat_RunCommand(const char *cmdp, GNode *gn, StringListNode *ln)
225 char *cmdStart; /* Start of expanded command */
227 bool silent; /* Don't print command */
228 bool doIt; /* Execute even if -n */
229 volatile bool errCheck; /* Check errors */
230 WAIT_T reason; /* Reason for child's death */
231 WAIT_T status; /* Description of child's death */
232 pid_t cpid; /* Child actually found */
233 pid_t retstat; /* Result of wait */
234 const char **volatile av; /* Argument vector for thing to exec */
235 char **volatile mav; /* Copy of the argument vector for freeing */
236 bool useShell; /* True if command should be executed using a
238 const char *volatile cmd = cmdp;
240 silent = (gn->type & OP_SILENT) != OP_NONE;
241 errCheck = !(gn->type & OP_IGNORE);
244 (void)Var_Subst(cmd, gn, VARE_WANTRES, &cmdStart);
245 /* TODO: handle errors */
247 if (cmdStart[0] == '\0') {
252 LstNode_Set(ln, cmdStart);
254 if (gn->type & OP_SAVE_CMDS) {
255 GNode *endNode = Targ_GetEndNode();
258 * Append the expanded command, to prevent the
259 * local variables from being interpreted in the
260 * scope of the .END node.
262 * A probably unintended side effect of this is that
263 * the expanded command will be expanded again in the
264 * .END node. Therefore, a literal '$' in these
265 * commands must be written as '$$$$' instead of the
268 Lst_Append(&endNode->commands, cmdStart);
272 if (strcmp(cmdStart, "...") == 0) {
273 gn->type |= OP_SAVE_CMDS;
279 silent = !DEBUG(LOUD);
280 else if (*cmd == '-')
282 else if (*cmd == '+') {
284 if (shellName == NULL) /* we came here from jobs */
286 } else if (!ch_isspace(*cmd))
287 /* Ignore whitespace for compatibility with gnu make */
292 while (ch_isspace(*cmd))
296 * If we did not end up with a command, just skip it.
301 useShell = UseShell(cmd);
303 * Print the command before echoing if we're not supposed to be quiet
304 * for this one. We also print the command if -n given.
306 if (!silent || !GNode_ShouldExecute(gn)) {
312 * If we're not supposed to execute any commands, this is as far as
315 if (!doIt && !GNode_ShouldExecute(gn))
318 DEBUG1(JOB, "Execute: '%s'\n", cmd);
322 * We need to pass the command off to the shell, typically
323 * because the command contains a "meta" character.
325 static const char *shargv[5];
327 /* The following work for any of the builtin shell specs. */
329 shargv[shargc++] = shellPath;
330 if (errCheck && shellErrFlag != NULL)
331 shargv[shargc++] = shellErrFlag;
332 shargv[shargc++] = DEBUG(SHELL) ? "-xc" : "-c";
333 shargv[shargc++] = cmd;
334 shargv[shargc] = NULL;
340 * No meta-characters, so no need to exec a shell. Break the
341 * command into words to form an argument vector we can
344 Words words = Str_Words(cmd, false);
357 compatChild = cpid = vfork();
359 Fatal("Could not fork");
366 (void)execvp(av[0], (char *const *)UNCONST(av));
367 execDie("exec", av[0]);
373 /* XXX: Memory management looks suspicious here. */
374 /* XXX: Setting a list item to NULL is unexpected. */
379 meta_compat_parent(cpid);
383 * The child is off and running. Now all we can do is wait...
385 while ((retstat = wait(&reason)) != cpid) {
387 JobReapChild(retstat, reason, false); /* not ours? */
388 if (retstat == -1 && errno != EINTR) {
394 Fatal("error in wait: %d: %s", retstat, strerror(errno));
396 if (WIFSTOPPED(reason)) {
397 status = WSTOPSIG(reason); /* stopped */
398 } else if (WIFEXITED(reason)) {
399 status = WEXITSTATUS(reason); /* exited */
400 #if defined(USE_META) && defined(USE_FILEMON_ONCE)
402 meta_cmd_finish(NULL);
406 DebugFailedTarget(cmd, gn);
407 printf("*** Error code %d", status);
410 status = WTERMSIG(reason); /* signaled */
411 printf("*** Signal %d", status);
415 if (!WIFEXITED(reason) || status != 0) {
419 meta_job_error(NULL, gn, false, status);
422 if (opts.keepgoing) {
424 * Abort the current target,
425 * but let others continue.
427 printf(" (continuing)\n");
432 CompatDeleteTarget(gn);
435 * Continue executing commands for this target.
436 * If we return 0, this will happen...
438 printf(" (ignored)\n");
445 if (compatSigno != 0) {
446 bmake_signal(compatSigno, SIG_DFL);
447 kill(myPid, compatSigno);
454 RunCommands(GNode *gn)
458 for (ln = gn->commands.first; ln != NULL; ln = ln->next) {
459 const char *cmd = ln->datum;
460 if (!Compat_RunCommand(cmd, gn, ln))
466 MakeInRandomOrder(GNode **gnodes, GNode **end, GNode *pgn)
471 for (r = (size_t)(end - gnodes); r >= 2; r--) {
472 /* Biased, but irrelevant in practice. */
473 size_t i = (size_t)random() % r;
474 GNode *t = gnodes[r - 1];
475 gnodes[r - 1] = gnodes[i];
479 for (it = gnodes; it != end; it++)
480 Compat_Make(*it, pgn);
484 MakeWaitGroupsInRandomOrder(GNodeList *gnodes, GNode *pgn)
491 Vector_Init(&vec, sizeof(GNode *));
492 for (ln = gnodes->first; ln != NULL; ln = ln->next)
493 *(GNode **)Vector_Push(&vec) = ln->datum;
498 for (i = 0; i < n; i++) {
499 if (nodes[i]->type & OP_WAIT) {
500 MakeInRandomOrder(nodes + start, nodes + i, pgn);
501 Compat_Make(nodes[i], pgn);
505 MakeInRandomOrder(nodes + start, nodes + i, pgn);
511 MakeNodes(GNodeList *gnodes, GNode *pgn)
515 if (Lst_IsEmpty(gnodes))
517 if (opts.randomizeTargets) {
518 MakeWaitGroupsInRandomOrder(gnodes, pgn);
522 for (ln = gnodes->first; ln != NULL; ln = ln->next) {
523 GNode *cgn = ln->datum;
524 Compat_Make(cgn, pgn);
529 MakeUnmade(GNode *gn, GNode *pgn)
532 assert(gn->made == UNMADE);
535 * First mark ourselves to be made, then apply whatever transformations
536 * the suffix module thinks are necessary. Once that's done, we can
537 * descend and make all our children. If any of them has an error
538 * but the -k flag was given, our 'make' field will be set to false
539 * again. This is our signal to not attempt to do anything but abort
540 * our parent as well.
542 gn->flags.remake = true;
543 gn->made = BEINGMADE;
545 if (!(gn->type & OP_MADE))
548 MakeNodes(&gn->children, gn);
550 if (!gn->flags.remake) {
552 pgn->flags.remake = false;
556 if (Lst_FindDatum(&gn->implicitParents, pgn) != NULL)
557 Var_Set(pgn, IMPSRC, GNode_VarTarget(gn));
560 * All the children were made ok. Now youngestChild->mtime contains the
561 * modification time of the newest child, we need to find out if we
562 * exist and when we were modified last. The criteria for datedness
563 * are defined by GNode_IsOODate.
565 DEBUG1(MAKE, "Examining %s...", gn->name);
566 if (!GNode_IsOODate(gn)) {
568 DEBUG0(MAKE, "up-to-date.\n");
573 * If the user is just seeing if something is out-of-date, exit now
574 * to tell him/her "yes".
576 DEBUG0(MAKE, "out-of-date.\n");
577 if (opts.query && gn != Targ_GetEndNode())
581 * We need to be re-made.
582 * Ensure that $? (.OODATE) and $> (.ALLSRC) are both set.
584 GNode_SetLocalVars(gn);
587 * Alter our type to tell if errors should be ignored or things
588 * should not be printed so Compat_RunCommand knows what to do.
590 if (opts.ignoreErrors)
591 gn->type |= OP_IGNORE;
593 gn->type |= OP_SILENT;
595 if (Job_CheckCommands(gn, Fatal)) {
597 * Our commands are ok, but we still have to worry about
600 if (!opts.touch || (gn->type & OP_MAKE)) {
603 if (useMeta && GNode_ShouldExecute(gn))
604 meta_job_start(NULL, gn);
609 Job_Touch(gn, (gn->type & OP_SILENT) != OP_NONE);
615 if (useMeta && GNode_ShouldExecute(gn)) {
616 if (meta_job_finish(NULL) != 0)
621 if (gn->made != ERROR) {
623 * If the node was made successfully, mark it so, update
624 * its modification time and timestamp all its parents.
625 * This is to keep its state from affecting that of its parent.
628 if (Make_Recheck(gn) == 0)
629 pgn->flags.force = true;
630 if (!(gn->type & OP_EXEC)) {
631 pgn->flags.childMade = true;
632 GNode_UpdateYoungestChild(pgn, gn);
634 } else if (opts.keepgoing) {
635 pgn->flags.remake = false;
637 PrintOnError(gn, "\nStop.\n");
644 MakeOther(GNode *gn, GNode *pgn)
647 if (Lst_FindDatum(&gn->implicitParents, pgn) != NULL) {
648 const char *target = GNode_VarTarget(gn);
649 Var_Set(pgn, IMPSRC, target != NULL ? target : "");
654 Error("Graph cycles through %s", gn->name);
656 pgn->flags.remake = false;
659 if (!(gn->type & OP_EXEC)) {
660 pgn->flags.childMade = true;
661 GNode_UpdateYoungestChild(pgn, gn);
665 if (!(gn->type & OP_EXEC))
666 GNode_UpdateYoungestChild(pgn, gn);
676 * If an error is detected and not being ignored, the process exits.
679 * gn The node to make
680 * pgn Parent to abort if necessary
684 * UPTODATE gn was already up-to-date.
685 * MADE gn was recreated successfully.
686 * ERROR An error occurred while gn was being created,
687 * either due to missing commands or in -k mode.
688 * ABORTED gn was not remade because one of its
689 * dependencies could not be made due to errors.
692 Compat_Make(GNode *gn, GNode *pgn)
694 if (shellName == NULL) /* we came here from jobs */
697 if (gn->made == UNMADE && (gn == pgn || !(pgn->type & OP_MADE))) {
698 if (!MakeUnmade(gn, pgn))
701 /* XXX: Replace with GNode_IsError(gn) */
702 } else if (gn->made == ERROR) {
704 * Already had an error when making this.
705 * Tell the parent to abort.
707 pgn->flags.remake = false;
713 MakeNodes(&gn->cohorts, pgn);
719 GNode *gn = Targ_FindNode(".BEGIN");
724 if (GNode_IsError(gn)) {
725 PrintOnError(gn, "\nStop.\n");
733 if (bmake_signal(SIGINT, SIG_IGN) != SIG_IGN)
734 bmake_signal(SIGINT, CompatInterrupt);
735 if (bmake_signal(SIGTERM, SIG_IGN) != SIG_IGN)
736 bmake_signal(SIGTERM, CompatInterrupt);
737 if (bmake_signal(SIGHUP, SIG_IGN) != SIG_IGN)
738 bmake_signal(SIGHUP, CompatInterrupt);
739 if (bmake_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
740 bmake_signal(SIGQUIT, CompatInterrupt);
744 Compat_MakeAll(GNodeList *targs)
746 GNode *errorNode = NULL;
748 if (shellName == NULL)
754 * Create the .END node now, to keep the (debug) output of the
755 * counter.mk test the same as before 2020-09-23. This
756 * implementation detail probably doesn't matter though.
758 (void)Targ_GetEndNode();
764 * Expand .USE nodes right now, because they can modify the structure
767 Make_ExpandUse(targs);
769 while (!Lst_IsEmpty(targs)) {
770 GNode *gn = Lst_Dequeue(targs);
773 if (gn->made == UPTODATE) {
774 printf("`%s' is up to date.\n", gn->name);
775 } else if (gn->made == ABORTED) {
776 printf("`%s' not remade because of errors.\n",
779 if (GNode_IsError(gn) && errorNode == NULL)
783 /* If the user has defined a .END target, run its commands. */
784 if (errorNode == NULL) {
785 GNode *endNode = Targ_GetEndNode();
786 Compat_Make(endNode, endNode);
787 if (GNode_IsError(endNode))
791 if (errorNode != NULL) {
794 else if (DEBUG(GRAPH3))
796 PrintOnError(errorNode, "\nStop.\n");