Merge branch 'vendor/DHCPCD'
[dragonfly.git] / contrib / bmake / compat.c
blobcd88884736f14ceea4b2b8de68615d3a80b777ec
1 /* $NetBSD: compat.c,v 1.113 2020/07/03 08:13:23 rillig Exp $ */
3 /*
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5 * All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
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.
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.
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
41 * Adam de Boor.
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.
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.
72 #ifndef MAKE_NATIVE
73 static char rcsid[] = "$NetBSD: compat.c,v 1.113 2020/07/03 08:13:23 rillig Exp $";
74 #else
75 #include <sys/cdefs.h>
76 #ifndef lint
77 #if 0
78 static char sccsid[] = "@(#)compat.c 8.2 (Berkeley) 3/19/94";
79 #else
80 __RCSID("$NetBSD: compat.c,v 1.113 2020/07/03 08:13:23 rillig Exp $");
81 #endif
82 #endif /* not lint */
83 #endif
85 /*-
86 * compat.c --
87 * The routines in this file implement the full-compatibility
88 * mode of PMake. Most of the special functionality of PMake
89 * is available in this mode. Things not supported:
90 * - different shells.
91 * - friendly variable substitution.
93 * Interface:
94 * Compat_Run Initialize things for this module and recreate
95 * thems as need creatin'
98 #ifdef HAVE_CONFIG_H
99 # include "config.h"
100 #endif
101 #include <sys/types.h>
102 #include <sys/stat.h>
103 #include "wait.h"
105 #include <ctype.h>
106 #include <errno.h>
107 #include <signal.h>
108 #include <stdio.h>
110 #include "make.h"
111 #include "hash.h"
112 #include "dir.h"
113 #include "job.h"
114 #include "metachar.h"
115 #include "pathnames.h"
118 static GNode *curTarg = NULL;
119 static GNode *ENDNode;
120 static void CompatInterrupt(int);
121 static pid_t compatChild;
122 static int compatSigno;
125 * CompatDeleteTarget -- delete a failed, interrupted, or otherwise
126 * duffed target if not inhibited by .PRECIOUS.
128 static void
129 CompatDeleteTarget(GNode *gn)
131 if ((gn != NULL) && !Targ_Precious (gn)) {
132 char *p1;
133 char *file = Var_Value(TARGET, gn, &p1);
135 if (!noExecute && eunlink(file) != -1) {
136 Error("*** %s removed", file);
139 free(p1);
144 *-----------------------------------------------------------------------
145 * CompatInterrupt --
146 * Interrupt the creation of the current target and remove it if
147 * it ain't precious.
149 * Results:
150 * None.
152 * Side Effects:
153 * The target is removed and the process exits. If .INTERRUPT exists,
154 * its commands are run first WITH INTERRUPTS IGNORED..
156 * XXX: is .PRECIOUS supposed to inhibit .INTERRUPT? I doubt it, but I've
157 * left the logic alone for now. - dholland 20160826
159 *-----------------------------------------------------------------------
161 static void
162 CompatInterrupt(int signo)
164 GNode *gn;
166 CompatDeleteTarget(curTarg);
168 if ((curTarg != NULL) && !Targ_Precious (curTarg)) {
170 * Run .INTERRUPT only if hit with interrupt signal
172 if (signo == SIGINT) {
173 gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
174 if (gn != NULL) {
175 Compat_Make(gn, gn);
179 if (signo == SIGQUIT)
180 _exit(signo);
182 * If there is a child running, pass the signal on
183 * we will exist after it has exited.
185 compatSigno = signo;
186 if (compatChild > 0) {
187 KILLPG(compatChild, signo);
188 } else {
189 bmake_signal(signo, SIG_DFL);
190 kill(myPid, signo);
195 *-----------------------------------------------------------------------
196 * CompatRunCommand --
197 * Execute the next command for a target. If the command returns an
198 * error, the node's made field is set to ERROR and creation stops.
200 * Input:
201 * cmdp Command to execute
202 * gnp Node from which the command came
204 * Results:
205 * 0 if the command succeeded, 1 if an error occurred.
207 * Side Effects:
208 * The node's 'made' field may be set to ERROR.
210 *-----------------------------------------------------------------------
213 CompatRunCommand(void *cmdp, void *gnp)
215 char *cmdStart; /* Start of expanded command */
216 char *cp, *bp;
217 Boolean silent, /* Don't print command */
218 doIt; /* Execute even if -n */
219 volatile Boolean errCheck; /* Check errors */
220 WAIT_T reason; /* Reason for child's death */
221 int status; /* Description of child's death */
222 pid_t cpid; /* Child actually found */
223 pid_t retstat; /* Result of wait */
224 LstNode cmdNode; /* Node where current command is located */
225 const char ** volatile av; /* Argument vector for thing to exec */
226 char ** volatile mav;/* Copy of the argument vector for freeing */
227 int argc; /* Number of arguments in av or 0 if not
228 * dynamically allocated */
229 Boolean local; /* TRUE if command should be executed
230 * locally */
231 Boolean useShell; /* TRUE if command should be executed
232 * using a shell */
233 char * volatile cmd = (char *)cmdp;
234 GNode *gn = (GNode *)gnp;
236 silent = gn->type & OP_SILENT;
237 errCheck = !(gn->type & OP_IGNORE);
238 doIt = FALSE;
240 cmdNode = Lst_Member(gn->commands, cmd);
241 cmdStart = Var_Subst(NULL, cmd, gn, VARF_WANTRES);
244 * brk_string will return an argv with a NULL in av[0], thus causing
245 * execvp to choke and die horribly. Besides, how can we execute a null
246 * command? In any case, we warn the user that the command expanded to
247 * nothing (is this the right thing to do?).
250 if (*cmdStart == '\0') {
251 free(cmdStart);
252 return 0;
254 cmd = cmdStart;
255 Lst_Replace(cmdNode, cmdStart);
257 if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
258 (void)Lst_AtEnd(ENDNode->commands, cmdStart);
259 return 0;
261 if (strcmp(cmdStart, "...") == 0) {
262 gn->type |= OP_SAVE_CMDS;
263 return 0;
266 while ((*cmd == '@') || (*cmd == '-') || (*cmd == '+')) {
267 switch (*cmd) {
268 case '@':
269 silent = DEBUG(LOUD) ? FALSE : TRUE;
270 break;
271 case '-':
272 errCheck = FALSE;
273 break;
274 case '+':
275 doIt = TRUE;
276 if (!shellName) /* we came here from jobs */
277 Shell_Init();
278 break;
280 cmd++;
283 while (isspace((unsigned char)*cmd))
284 cmd++;
287 * If we did not end up with a command, just skip it.
289 if (!*cmd)
290 return 0;
292 #if !defined(MAKE_NATIVE)
294 * In a non-native build, the host environment might be weird enough
295 * that it's necessary to go through a shell to get the correct
296 * behaviour. Or perhaps the shell has been replaced with something
297 * that does extra logging, and that should not be bypassed.
299 useShell = TRUE;
300 #else
302 * Search for meta characters in the command. If there are no meta
303 * characters, there's no need to execute a shell to execute the
304 * command.
306 * Additionally variable assignments and empty commands
307 * go to the shell. Therefore treat '=' and ':' like shell
308 * meta characters as documented in make(1).
311 useShell = needshell(cmd, FALSE);
312 #endif
315 * Print the command before echoing if we're not supposed to be quiet for
316 * this one. We also print the command if -n given.
318 if (!silent || NoExecute(gn)) {
319 printf("%s\n", cmd);
320 fflush(stdout);
324 * If we're not supposed to execute any commands, this is as far as
325 * we go...
327 if (!doIt && NoExecute(gn)) {
328 return 0;
330 if (DEBUG(JOB))
331 fprintf(debug_file, "Execute: '%s'\n", cmd);
333 again:
334 if (useShell) {
336 * We need to pass the command off to the shell, typically
337 * because the command contains a "meta" character.
339 static const char *shargv[5];
340 int shargc;
342 shargc = 0;
343 shargv[shargc++] = shellPath;
345 * The following work for any of the builtin shell specs.
347 if (errCheck && shellErrFlag) {
348 shargv[shargc++] = shellErrFlag;
350 if (DEBUG(SHELL))
351 shargv[shargc++] = "-xc";
352 else
353 shargv[shargc++] = "-c";
354 shargv[shargc++] = cmd;
355 shargv[shargc++] = NULL;
356 av = shargv;
357 argc = 0;
358 bp = NULL;
359 mav = NULL;
360 } else {
362 * No meta-characters, so no need to exec a shell. Break the command
363 * into words to form an argument vector we can execute.
365 mav = brk_string(cmd, &argc, TRUE, &bp);
366 if (mav == NULL) {
367 useShell = 1;
368 goto again;
370 av = (void *)mav;
373 local = TRUE;
375 #ifdef USE_META
376 if (useMeta) {
377 meta_compat_start();
379 #endif
382 * Fork and execute the single command. If the fork fails, we abort.
384 compatChild = cpid = vFork();
385 if (cpid < 0) {
386 Fatal("Could not fork");
388 if (cpid == 0) {
389 Var_ExportVars();
390 #ifdef USE_META
391 if (useMeta) {
392 meta_compat_child();
394 #endif
395 if (local)
396 (void)execvp(av[0], (char *const *)UNCONST(av));
397 else
398 (void)execv(av[0], (char *const *)UNCONST(av));
399 execError("exec", av[0]);
400 _exit(1);
403 free(mav);
404 free(bp);
406 Lst_Replace(cmdNode, NULL);
408 #ifdef USE_META
409 if (useMeta) {
410 meta_compat_parent(cpid);
412 #endif
415 * The child is off and running. Now all we can do is wait...
417 while (1) {
419 while ((retstat = wait(&reason)) != cpid) {
420 if (retstat > 0)
421 JobReapChild(retstat, reason, FALSE); /* not ours? */
422 if (retstat == -1 && errno != EINTR) {
423 break;
427 if (retstat > -1) {
428 if (WIFSTOPPED(reason)) {
429 status = WSTOPSIG(reason); /* stopped */
430 } else if (WIFEXITED(reason)) {
431 status = WEXITSTATUS(reason); /* exited */
432 #if defined(USE_META) && defined(USE_FILEMON_ONCE)
433 if (useMeta) {
434 meta_cmd_finish(NULL);
436 #endif
437 if (status != 0) {
438 if (DEBUG(ERROR)) {
439 fprintf(debug_file, "\n*** Failed target: %s\n*** Failed command: ",
440 gn->name);
441 for (cp = cmd; *cp; ) {
442 if (isspace((unsigned char)*cp)) {
443 fprintf(debug_file, " ");
444 while (isspace((unsigned char)*cp))
445 cp++;
446 } else {
447 fprintf(debug_file, "%c", *cp);
448 cp++;
451 fprintf(debug_file, "\n");
453 printf("*** Error code %d", status);
455 } else {
456 status = WTERMSIG(reason); /* signaled */
457 printf("*** Signal %d", status);
461 if (!WIFEXITED(reason) || (status != 0)) {
462 if (errCheck) {
463 #ifdef USE_META
464 if (useMeta) {
465 meta_job_error(NULL, gn, 0, status);
467 #endif
468 gn->made = ERROR;
469 if (keepgoing) {
471 * Abort the current target, but let others
472 * continue.
474 printf(" (continuing)\n");
475 } else {
476 printf("\n");
478 if (deleteOnError) {
479 CompatDeleteTarget(gn);
481 } else {
483 * Continue executing commands for this target.
484 * If we return 0, this will happen...
486 printf(" (ignored)\n");
487 status = 0;
490 break;
491 } else {
492 Fatal("error in wait: %d: %s", retstat, strerror(errno));
493 /*NOTREACHED*/
496 free(cmdStart);
497 compatChild = 0;
498 if (compatSigno) {
499 bmake_signal(compatSigno, SIG_DFL);
500 kill(myPid, compatSigno);
503 return status;
507 *-----------------------------------------------------------------------
508 * Compat_Make --
509 * Make a target.
511 * Input:
512 * gnp The node to make
513 * pgnp Parent to abort if necessary
515 * Results:
518 * Side Effects:
519 * If an error is detected and not being ignored, the process exits.
521 *-----------------------------------------------------------------------
524 Compat_Make(void *gnp, void *pgnp)
526 GNode *gn = (GNode *)gnp;
527 GNode *pgn = (GNode *)pgnp;
529 if (!shellName) /* we came here from jobs */
530 Shell_Init();
531 if (gn->made == UNMADE && (gn == pgn || (pgn->type & OP_MADE) == 0)) {
533 * First mark ourselves to be made, then apply whatever transformations
534 * the suffix module thinks are necessary. Once that's done, we can
535 * descend and make all our children. If any of them has an error
536 * but the -k flag was given, our 'make' field will be set FALSE again.
537 * This is our signal to not attempt to do anything but abort our
538 * parent as well.
540 gn->flags |= REMAKE;
541 gn->made = BEINGMADE;
542 if ((gn->type & OP_MADE) == 0)
543 Suff_FindDeps(gn);
544 Lst_ForEach(gn->children, Compat_Make, gn);
545 if ((gn->flags & REMAKE) == 0) {
546 gn->made = ABORTED;
547 pgn->flags &= ~REMAKE;
548 goto cohorts;
551 if (Lst_Member(gn->iParents, pgn) != NULL) {
552 char *p1;
553 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
554 free(p1);
558 * All the children were made ok. Now cmgn->mtime contains the
559 * modification time of the newest child, we need to find out if we
560 * exist and when we were modified last. The criteria for datedness
561 * are defined by the Make_OODate function.
563 if (DEBUG(MAKE)) {
564 fprintf(debug_file, "Examining %s...", gn->name);
566 if (! Make_OODate(gn)) {
567 gn->made = UPTODATE;
568 if (DEBUG(MAKE)) {
569 fprintf(debug_file, "up-to-date.\n");
571 goto cohorts;
572 } else if (DEBUG(MAKE)) {
573 fprintf(debug_file, "out-of-date.\n");
577 * If the user is just seeing if something is out-of-date, exit now
578 * to tell him/her "yes".
580 if (queryFlag) {
581 exit(1);
585 * We need to be re-made. We also have to make sure we've got a $?
586 * variable. To be nice, we also define the $> variable using
587 * Make_DoAllVar().
589 Make_DoAllVar(gn);
592 * Alter our type to tell if errors should be ignored or things
593 * should not be printed so CompatRunCommand knows what to do.
595 if (Targ_Ignore(gn)) {
596 gn->type |= OP_IGNORE;
598 if (Targ_Silent(gn)) {
599 gn->type |= OP_SILENT;
602 if (Job_CheckCommands(gn, Fatal)) {
604 * Our commands are ok, but we still have to worry about the -t
605 * flag...
607 if (!touchFlag || (gn->type & OP_MAKE)) {
608 curTarg = gn;
609 #ifdef USE_META
610 if (useMeta && !NoExecute(gn)) {
611 meta_job_start(NULL, gn);
613 #endif
614 Lst_ForEach(gn->commands, CompatRunCommand, gn);
615 curTarg = NULL;
616 } else {
617 Job_Touch(gn, gn->type & OP_SILENT);
619 } else {
620 gn->made = ERROR;
622 #ifdef USE_META
623 if (useMeta && !NoExecute(gn)) {
624 if (meta_job_finish(NULL) != 0)
625 gn->made = ERROR;
627 #endif
629 if (gn->made != ERROR) {
631 * If the node was made successfully, mark it so, update
632 * its modification time and timestamp all its parents. Note
633 * that for .ZEROTIME targets, the timestamping isn't done.
634 * This is to keep its state from affecting that of its parent.
636 gn->made = MADE;
637 pgn->flags |= Make_Recheck(gn) == 0 ? FORCE : 0;
638 if (!(gn->type & OP_EXEC)) {
639 pgn->flags |= CHILDMADE;
640 Make_TimeStamp(pgn, gn);
642 } else if (keepgoing) {
643 pgn->flags &= ~REMAKE;
644 } else {
645 PrintOnError(gn, "\nStop.");
646 exit(1);
648 } else if (gn->made == ERROR) {
650 * Already had an error when making this beastie. Tell the parent
651 * to abort.
653 pgn->flags &= ~REMAKE;
654 } else {
655 if (Lst_Member(gn->iParents, pgn) != NULL) {
656 char *p1;
657 Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn);
658 free(p1);
660 switch(gn->made) {
661 case BEINGMADE:
662 Error("Graph cycles through %s", gn->name);
663 gn->made = ERROR;
664 pgn->flags &= ~REMAKE;
665 break;
666 case MADE:
667 if ((gn->type & OP_EXEC) == 0) {
668 pgn->flags |= CHILDMADE;
669 Make_TimeStamp(pgn, gn);
671 break;
672 case UPTODATE:
673 if ((gn->type & OP_EXEC) == 0) {
674 Make_TimeStamp(pgn, gn);
676 break;
677 default:
678 break;
682 cohorts:
683 Lst_ForEach(gn->cohorts, Compat_Make, pgnp);
684 return 0;
688 *-----------------------------------------------------------------------
689 * Compat_Run --
690 * Initialize this mode and start making.
692 * Input:
693 * targs List of target nodes to re-create
695 * Results:
696 * None.
698 * Side Effects:
699 * Guess what?
701 *-----------------------------------------------------------------------
703 void
704 Compat_Run(Lst targs)
706 GNode *gn = NULL;/* Current root target */
707 int errors; /* Number of targets not remade due to errors */
709 if (!shellName)
710 Shell_Init();
712 if (bmake_signal(SIGINT, SIG_IGN) != SIG_IGN) {
713 bmake_signal(SIGINT, CompatInterrupt);
715 if (bmake_signal(SIGTERM, SIG_IGN) != SIG_IGN) {
716 bmake_signal(SIGTERM, CompatInterrupt);
718 if (bmake_signal(SIGHUP, SIG_IGN) != SIG_IGN) {
719 bmake_signal(SIGHUP, CompatInterrupt);
721 if (bmake_signal(SIGQUIT, SIG_IGN) != SIG_IGN) {
722 bmake_signal(SIGQUIT, CompatInterrupt);
725 ENDNode = Targ_FindNode(".END", TARG_CREATE);
726 ENDNode->type = OP_SPECIAL;
728 * If the user has defined a .BEGIN target, execute the commands attached
729 * to it.
731 if (!queryFlag) {
732 gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
733 if (gn != NULL) {
734 Compat_Make(gn, gn);
735 if (gn->made == ERROR) {
736 PrintOnError(gn, "\nStop.");
737 exit(1);
743 * Expand .USE nodes right now, because they can modify the structure
744 * of the tree.
746 Make_ExpandUse(targs);
749 * For each entry in the list of targets to create, call Compat_Make on
750 * it to create the thing. Compat_Make will leave the 'made' field of gn
751 * in one of several states:
752 * UPTODATE gn was already up-to-date
753 * MADE gn was recreated successfully
754 * ERROR An error occurred while gn was being created
755 * ABORTED gn was not remade because one of its inferiors
756 * could not be made due to errors.
758 errors = 0;
759 while (!Lst_IsEmpty (targs)) {
760 gn = (GNode *)Lst_DeQueue(targs);
761 Compat_Make(gn, gn);
763 if (gn->made == UPTODATE) {
764 printf("`%s' is up to date.\n", gn->name);
765 } else if (gn->made == ABORTED) {
766 printf("`%s' not remade because of errors.\n", gn->name);
767 errors += 1;
772 * If the user has defined a .END target, run its commands.
774 if (errors == 0) {
775 Compat_Make(ENDNode, ENDNode);
776 if (gn->made == ERROR) {
777 PrintOnError(gn, "\nStop.");
778 exit(1);