xref: /dragonfly/contrib/bmake/compat.c (revision 9e7ae5a0527a977cab412aede3a532cfe2903bbb)
1 /*        $NetBSD: compat.c,v 1.241 2022/08/17 20:10:29 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  * This file implements the full-compatibility mode of make, which makes the
74  * targets without parallelism and without a custom shell.
75  *
76  * Interface:
77  *        Compat_MakeAll      Initialize this module and make the given targets.
78  */
79 
80 #ifdef HAVE_CONFIG_H
81 # include   "config.h"
82 #endif
83 #include <sys/types.h>
84 #include <sys/stat.h>
85 #include "wait.h"
86 
87 #include <errno.h>
88 #include <signal.h>
89 
90 #include "make.h"
91 #include "dir.h"
92 #include "job.h"
93 #include "metachar.h"
94 #include "pathnames.h"
95 
96 /*        "@(#)compat.c       8.2 (Berkeley) 3/19/94"       */
97 MAKE_RCSID("$NetBSD: compat.c,v 1.241 2022/08/17 20:10:29 rillig Exp $");
98 
99 static GNode *curTarg = NULL;
100 static pid_t compatChild;
101 static int compatSigno;
102 
103 /*
104  * CompatDeleteTarget -- delete the file of a failed, interrupted, or
105  * otherwise duffed target if not inhibited by .PRECIOUS.
106  */
107 static void
CompatDeleteTarget(GNode * gn)108 CompatDeleteTarget(GNode *gn)
109 {
110           if (gn != NULL && !GNode_IsPrecious(gn)) {
111                     const char *file = GNode_VarTarget(gn);
112 
113                     if (!opts.noExecute && unlink_file(file)) {
114                               Error("*** %s removed", file);
115                     }
116           }
117 }
118 
119 /*
120  * Interrupt the creation of the current target and remove it if it ain't
121  * precious. Then exit.
122  *
123  * If .INTERRUPT exists, its commands are run first WITH INTERRUPTS IGNORED.
124  *
125  * XXX: is .PRECIOUS supposed to inhibit .INTERRUPT? I doubt it, but I've
126  * left the logic alone for now. - dholland 20160826
127  */
128 static void
CompatInterrupt(int signo)129 CompatInterrupt(int signo)
130 {
131           CompatDeleteTarget(curTarg);
132 
133           if (curTarg != NULL && !GNode_IsPrecious(curTarg)) {
134                     /*
135                      * Run .INTERRUPT only if hit with interrupt signal
136                      */
137                     if (signo == SIGINT) {
138                               GNode *gn = Targ_FindNode(".INTERRUPT");
139                               if (gn != NULL) {
140                                         Compat_Make(gn, gn);
141                               }
142                     }
143           }
144 
145           if (signo == SIGQUIT)
146                     _exit(signo);
147 
148           /*
149            * If there is a child running, pass the signal on.
150            * We will exist after it has exited.
151            */
152           compatSigno = signo;
153           if (compatChild > 0) {
154                     KILLPG(compatChild, signo);
155           } else {
156                     bmake_signal(signo, SIG_DFL);
157                     kill(myPid, signo);
158           }
159 }
160 
161 static void
DebugFailedTarget(const char * cmd,const GNode * gn)162 DebugFailedTarget(const char *cmd, const GNode *gn)
163 {
164           const char *p = cmd;
165           debug_printf("\n*** Failed target:  %s\n*** Failed command: ",
166               gn->name);
167 
168           /*
169            * Replace runs of whitespace with a single space, to reduce the
170            * amount of whitespace for multi-line command lines.
171            */
172           while (*p != '\0') {
173                     if (ch_isspace(*p)) {
174                               debug_printf(" ");
175                               cpp_skip_whitespace(&p);
176                     } else {
177                               debug_printf("%c", *p);
178                               p++;
179                     }
180           }
181           debug_printf("\n");
182 }
183 
184 static bool
UseShell(const char * cmd MAKE_ATTR_UNUSED)185 UseShell(const char *cmd MAKE_ATTR_UNUSED)
186 {
187 #if defined(FORCE_USE_SHELL) || !defined(MAKE_NATIVE)
188           /*
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.
193            */
194           return true;
195 #else
196           /*
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
199            * command.
200            *
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).
204            */
205 
206           return needshell(cmd);
207 #endif
208 }
209 
210 /*
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.
213  *
214  * Input:
215  *        cmdp                Command to execute
216  *        gn                  Node from which the command came
217  *        ln                  List node that contains the command
218  *
219  * Results:
220  *        true if the command succeeded.
221  */
222 bool
Compat_RunCommand(const char * cmdp,GNode * gn,StringListNode * ln)223 Compat_RunCommand(const char *cmdp, GNode *gn, StringListNode *ln)
224 {
225           char *cmdStart;               /* Start of expanded command */
226           char *bp;
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
237                                          * shell */
238           const char *volatile cmd = cmdp;
239 
240           silent = (gn->type & OP_SILENT) != OP_NONE;
241           errCheck = !(gn->type & OP_IGNORE);
242           doIt = false;
243 
244           (void)Var_Subst(cmd, gn, VARE_WANTRES, &cmdStart);
245           /* TODO: handle errors */
246 
247           if (cmdStart[0] == '\0') {
248                     free(cmdStart);
249                     return true;
250           }
251           cmd = cmdStart;
252           LstNode_Set(ln, cmdStart);
253 
254           if (gn->type & OP_SAVE_CMDS) {
255                     GNode *endNode = Targ_GetEndNode();
256                     if (gn != endNode) {
257                               /*
258                                * Append the expanded command, to prevent the
259                                * local variables from being interpreted in the
260                                * scope of the .END node.
261                                *
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
266                                * usual '$$'.
267                                */
268                               Lst_Append(&endNode->commands, cmdStart);
269                               return true;
270                     }
271           }
272           if (strcmp(cmdStart, "...") == 0) {
273                     gn->type |= OP_SAVE_CMDS;
274                     return true;
275           }
276 
277           for (;;) {
278                     if (*cmd == '@')
279                               silent = !DEBUG(LOUD);
280                     else if (*cmd == '-')
281                               errCheck = false;
282                     else if (*cmd == '+') {
283                               doIt = true;
284                               if (shellName == NULL)        /* we came here from jobs */
285                                         Shell_Init();
286                     } else
287                               break;
288                     cmd++;
289           }
290 
291           while (ch_isspace(*cmd))
292                     cmd++;
293 
294           /*
295            * If we did not end up with a command, just skip it.
296            */
297           if (cmd[0] == '\0')
298                     return true;
299 
300           useShell = UseShell(cmd);
301           /*
302            * Print the command before echoing if we're not supposed to be quiet
303            * for this one. We also print the command if -n given.
304            */
305           if (!silent || !GNode_ShouldExecute(gn)) {
306                     printf("%s\n", cmd);
307                     fflush(stdout);
308           }
309 
310           /*
311            * If we're not supposed to execute any commands, this is as far as
312            * we go...
313            */
314           if (!doIt && !GNode_ShouldExecute(gn))
315                     return true;
316 
317           DEBUG1(JOB, "Execute: '%s'\n", cmd);
318 
319           if (useShell) {
320                     /*
321                      * We need to pass the command off to the shell, typically
322                      * because the command contains a "meta" character.
323                      */
324                     static const char *shargv[5];
325 
326                     /* The following work for any of the builtin shell specs. */
327                     int shargc = 0;
328                     shargv[shargc++] = shellPath;
329                     if (errCheck && shellErrFlag != NULL)
330                               shargv[shargc++] = shellErrFlag;
331                     shargv[shargc++] = DEBUG(SHELL) ? "-xc" : "-c";
332                     shargv[shargc++] = cmd;
333                     shargv[shargc] = NULL;
334                     av = shargv;
335                     bp = NULL;
336                     mav = NULL;
337           } else {
338                     /*
339                      * No meta-characters, so no need to exec a shell. Break the
340                      * command into words to form an argument vector we can
341                      * execute.
342                      */
343                     Words words = Str_Words(cmd, false);
344                     mav = words.words;
345                     bp = words.freeIt;
346                     av = (void *)mav;
347           }
348 
349 #ifdef USE_META
350           if (useMeta)
351                     meta_compat_start();
352 #endif
353 
354           Var_ReexportVars();
355 
356           compatChild = cpid = vfork();
357           if (cpid < 0)
358                     Fatal("Could not fork");
359 
360           if (cpid == 0) {
361 #ifdef USE_META
362                     if (useMeta)
363                               meta_compat_child();
364 #endif
365                     (void)execvp(av[0], (char *const *)UNCONST(av));
366                     execDie("exec", av[0]);
367           }
368 
369           free(mav);
370           free(bp);
371 
372           /* XXX: Memory management looks suspicious here. */
373           /* XXX: Setting a list item to NULL is unexpected. */
374           LstNode_SetNull(ln);
375 
376 #ifdef USE_META
377           if (useMeta)
378                     meta_compat_parent(cpid);
379 #endif
380 
381           /*
382            * The child is off and running. Now all we can do is wait...
383            */
384           while ((retstat = wait(&reason)) != cpid) {
385                     if (retstat > 0)
386                               JobReapChild(retstat, reason, false); /* not ours? */
387                     if (retstat == -1 && errno != EINTR) {
388                               break;
389                     }
390           }
391 
392           if (retstat < 0)
393                     Fatal("error in wait: %d: %s", retstat, strerror(errno));
394 
395           if (WIFSTOPPED(reason)) {
396                     status = WSTOPSIG(reason);    /* stopped */
397           } else if (WIFEXITED(reason)) {
398                     status = WEXITSTATUS(reason); /* exited */
399 #if defined(USE_META) && defined(USE_FILEMON_ONCE)
400                     if (useMeta)
401                               meta_cmd_finish(NULL);
402 #endif
403                     if (status != 0) {
404                               if (DEBUG(ERROR))
405                                         DebugFailedTarget(cmd, gn);
406                               printf("*** Error code %d", status);
407                     }
408           } else {
409                     status = WTERMSIG(reason);    /* signaled */
410                     printf("*** Signal %d", status);
411           }
412 
413 
414           if (!WIFEXITED(reason) || status != 0) {
415                     if (errCheck) {
416 #ifdef USE_META
417                               if (useMeta)
418                                         meta_job_error(NULL, gn, false, status);
419 #endif
420                               gn->made = ERROR;
421                               if (opts.keepgoing) {
422                                         /*
423                                          * Abort the current target,
424                                          * but let others continue.
425                                          */
426                                         printf(" (continuing)\n");
427                               } else {
428                                         printf("\n");
429                               }
430                               if (deleteOnError)
431                                         CompatDeleteTarget(gn);
432                     } else {
433                               /*
434                                * Continue executing commands for this target.
435                                * If we return 0, this will happen...
436                                */
437                               printf(" (ignored)\n");
438                               status = 0;
439                     }
440           }
441 
442           free(cmdStart);
443           compatChild = 0;
444           if (compatSigno != 0) {
445                     bmake_signal(compatSigno, SIG_DFL);
446                     kill(myPid, compatSigno);
447           }
448 
449           return status == 0;
450 }
451 
452 static void
RunCommands(GNode * gn)453 RunCommands(GNode *gn)
454 {
455           StringListNode *ln;
456 
457           for (ln = gn->commands.first; ln != NULL; ln = ln->next) {
458                     const char *cmd = ln->datum;
459                     if (!Compat_RunCommand(cmd, gn, ln))
460                               break;
461           }
462 }
463 
464 static void
MakeInRandomOrder(GNode ** gnodes,GNode ** end,GNode * pgn)465 MakeInRandomOrder(GNode **gnodes, GNode **end, GNode *pgn)
466 {
467           GNode **it;
468           size_t r;
469 
470           for (r = (size_t)(end - gnodes); r >= 2; r--) {
471                     /* Biased, but irrelevant in practice. */
472                     size_t i = (size_t)random() % r;
473                     GNode *t = gnodes[r - 1];
474                     gnodes[r - 1] = gnodes[i];
475                     gnodes[i] = t;
476           }
477 
478           for (it = gnodes; it != end; it++)
479                     Compat_Make(*it, pgn);
480 }
481 
482 static void
MakeWaitGroupsInRandomOrder(GNodeList * gnodes,GNode * pgn)483 MakeWaitGroupsInRandomOrder(GNodeList *gnodes, GNode *pgn)
484 {
485           Vector vec;
486           GNodeListNode *ln;
487           GNode **nodes;
488           size_t i, n, start;
489 
490           Vector_Init(&vec, sizeof(GNode *));
491           for (ln = gnodes->first; ln != NULL; ln = ln->next)
492                     *(GNode **)Vector_Push(&vec) = ln->datum;
493           nodes = vec.items;
494           n = vec.len;
495 
496           start = 0;
497           for (i = 0; i < n; i++) {
498                     if (nodes[i]->type & OP_WAIT) {
499                               MakeInRandomOrder(nodes + start, nodes + i, pgn);
500                               Compat_Make(nodes[i], pgn);
501                               start = i + 1;
502                     }
503           }
504           MakeInRandomOrder(nodes + start, nodes + i, pgn);
505 
506           Vector_Done(&vec);
507 }
508 
509 static void
MakeNodes(GNodeList * gnodes,GNode * pgn)510 MakeNodes(GNodeList *gnodes, GNode *pgn)
511 {
512           GNodeListNode *ln;
513 
514           if (Lst_IsEmpty(gnodes))
515                     return;
516           if (opts.randomizeTargets) {
517                     MakeWaitGroupsInRandomOrder(gnodes, pgn);
518                     return;
519           }
520 
521           for (ln = gnodes->first; ln != NULL; ln = ln->next) {
522                     GNode *cgn = ln->datum;
523                     Compat_Make(cgn, pgn);
524           }
525 }
526 
527 static bool
MakeUnmade(GNode * gn,GNode * pgn)528 MakeUnmade(GNode *gn, GNode *pgn)
529 {
530 
531           assert(gn->made == UNMADE);
532 
533           /*
534            * First mark ourselves to be made, then apply whatever transformations
535            * the suffix module thinks are necessary. Once that's done, we can
536            * descend and make all our children. If any of them has an error
537            * but the -k flag was given, our 'make' field will be set to false
538            * again. This is our signal to not attempt to do anything but abort
539            * our parent as well.
540            */
541           gn->flags.remake = true;
542           gn->made = BEINGMADE;
543 
544           if (!(gn->type & OP_MADE))
545                     Suff_FindDeps(gn);
546 
547           MakeNodes(&gn->children, gn);
548 
549           if (!gn->flags.remake) {
550                     gn->made = ABORTED;
551                     pgn->flags.remake = false;
552                     return false;
553           }
554 
555           if (Lst_FindDatum(&gn->implicitParents, pgn) != NULL)
556                     Var_Set(pgn, IMPSRC, GNode_VarTarget(gn));
557 
558           /*
559            * All the children were made ok. Now youngestChild->mtime contains the
560            * modification time of the newest child, we need to find out if we
561            * exist and when we were modified last. The criteria for datedness
562            * are defined by GNode_IsOODate.
563            */
564           DEBUG1(MAKE, "Examining %s...", gn->name);
565           if (!GNode_IsOODate(gn)) {
566                     gn->made = UPTODATE;
567                     DEBUG0(MAKE, "up-to-date.\n");
568                     return false;
569           }
570 
571           /*
572            * If the user is just seeing if something is out-of-date, exit now
573            * to tell him/her "yes".
574            */
575           DEBUG0(MAKE, "out-of-date.\n");
576           if (opts.query && gn != Targ_GetEndNode())
577                     exit(1);
578 
579           /*
580            * We need to be re-made.
581            * Ensure that $? (.OODATE) and $> (.ALLSRC) are both set.
582            */
583           GNode_SetLocalVars(gn);
584 
585           /*
586            * Alter our type to tell if errors should be ignored or things
587            * should not be printed so Compat_RunCommand knows what to do.
588            */
589           if (opts.ignoreErrors)
590                     gn->type |= OP_IGNORE;
591           if (opts.silent)
592                     gn->type |= OP_SILENT;
593 
594           if (Job_CheckCommands(gn, Fatal)) {
595                     /*
596                      * Our commands are ok, but we still have to worry about
597                      * the -t flag.
598                      */
599                     if (!opts.touch || (gn->type & OP_MAKE)) {
600                               curTarg = gn;
601 #ifdef USE_META
602                               if (useMeta && GNode_ShouldExecute(gn))
603                                         meta_job_start(NULL, gn);
604 #endif
605                               RunCommands(gn);
606                               curTarg = NULL;
607                     } else {
608                               Job_Touch(gn, (gn->type & OP_SILENT) != OP_NONE);
609                     }
610           } else {
611                     gn->made = ERROR;
612           }
613 #ifdef USE_META
614           if (useMeta && GNode_ShouldExecute(gn)) {
615                     if (meta_job_finish(NULL) != 0)
616                               gn->made = ERROR;
617           }
618 #endif
619 
620           if (gn->made != ERROR) {
621                     /*
622                      * If the node was made successfully, mark it so, update
623                      * its modification time and timestamp all its parents.
624                      * This is to keep its state from affecting that of its parent.
625                      */
626                     gn->made = MADE;
627                     if (Make_Recheck(gn) == 0)
628                               pgn->flags.force = true;
629                     if (!(gn->type & OP_EXEC)) {
630                               pgn->flags.childMade = true;
631                               GNode_UpdateYoungestChild(pgn, gn);
632                     }
633           } else if (opts.keepgoing) {
634                     pgn->flags.remake = false;
635           } else {
636                     PrintOnError(gn, "\nStop.\n");
637                     exit(1);
638           }
639           return true;
640 }
641 
642 static void
MakeOther(GNode * gn,GNode * pgn)643 MakeOther(GNode *gn, GNode *pgn)
644 {
645 
646           if (Lst_FindDatum(&gn->implicitParents, pgn) != NULL) {
647                     const char *target = GNode_VarTarget(gn);
648                     Var_Set(pgn, IMPSRC, target != NULL ? target : "");
649           }
650 
651           switch (gn->made) {
652           case BEINGMADE:
653                     Error("Graph cycles through %s", gn->name);
654                     gn->made = ERROR;
655                     pgn->flags.remake = false;
656                     break;
657           case MADE:
658                     if (!(gn->type & OP_EXEC)) {
659                               pgn->flags.childMade = true;
660                               GNode_UpdateYoungestChild(pgn, gn);
661                     }
662                     break;
663           case UPTODATE:
664                     if (!(gn->type & OP_EXEC))
665                               GNode_UpdateYoungestChild(pgn, gn);
666                     break;
667           default:
668                     break;
669           }
670 }
671 
672 /*
673  * Make a target.
674  *
675  * If an error is detected and not being ignored, the process exits.
676  *
677  * Input:
678  *        gn                  The node to make
679  *        pgn                 Parent to abort if necessary
680  *
681  * Output:
682  *        gn->made
683  *                  UPTODATE  gn was already up-to-date.
684  *                  MADE                gn was recreated successfully.
685  *                  ERROR               An error occurred while gn was being created,
686  *                                      either due to missing commands or in -k mode.
687  *                  ABORTED             gn was not remade because one of its
688  *                                      dependencies could not be made due to errors.
689  */
690 void
Compat_Make(GNode * gn,GNode * pgn)691 Compat_Make(GNode *gn, GNode *pgn)
692 {
693           if (shellName == NULL)        /* we came here from jobs */
694                     Shell_Init();
695 
696           if (gn->made == UNMADE && (gn == pgn || !(pgn->type & OP_MADE))) {
697                     if (!MakeUnmade(gn, pgn))
698                               goto cohorts;
699 
700                     /* XXX: Replace with GNode_IsError(gn) */
701           } else if (gn->made == ERROR) {
702                     /*
703                      * Already had an error when making this.
704                      * Tell the parent to abort.
705                      */
706                     pgn->flags.remake = false;
707           } else {
708                     MakeOther(gn, pgn);
709           }
710 
711 cohorts:
712           MakeNodes(&gn->cohorts, pgn);
713 }
714 
715 static void
MakeBeginNode(void)716 MakeBeginNode(void)
717 {
718           GNode *gn = Targ_FindNode(".BEGIN");
719           if (gn == NULL)
720                     return;
721 
722           Compat_Make(gn, gn);
723           if (GNode_IsError(gn)) {
724                     PrintOnError(gn, "\nStop.\n");
725                     exit(1);
726           }
727 }
728 
729 static void
InitSignals(void)730 InitSignals(void)
731 {
732           if (bmake_signal(SIGINT, SIG_IGN) != SIG_IGN)
733                     bmake_signal(SIGINT, CompatInterrupt);
734           if (bmake_signal(SIGTERM, SIG_IGN) != SIG_IGN)
735                     bmake_signal(SIGTERM, CompatInterrupt);
736           if (bmake_signal(SIGHUP, SIG_IGN) != SIG_IGN)
737                     bmake_signal(SIGHUP, CompatInterrupt);
738           if (bmake_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
739                     bmake_signal(SIGQUIT, CompatInterrupt);
740 }
741 
742 void
Compat_MakeAll(GNodeList * targs)743 Compat_MakeAll(GNodeList *targs)
744 {
745           GNode *errorNode = NULL;
746 
747           if (shellName == NULL)
748                     Shell_Init();
749 
750           InitSignals();
751 
752           /*
753            * Create the .END node now, to keep the (debug) output of the
754            * counter.mk test the same as before 2020-09-23.  This
755            * implementation detail probably doesn't matter though.
756            */
757           (void)Targ_GetEndNode();
758 
759           if (!opts.query)
760                     MakeBeginNode();
761 
762           /*
763            * Expand .USE nodes right now, because they can modify the structure
764            * of the tree.
765            */
766           Make_ExpandUse(targs);
767 
768           while (!Lst_IsEmpty(targs)) {
769                     GNode *gn = Lst_Dequeue(targs);
770                     Compat_Make(gn, gn);
771 
772                     if (gn->made == UPTODATE) {
773                               printf("`%s' is up to date.\n", gn->name);
774                     } else if (gn->made == ABORTED) {
775                               printf("`%s' not remade because of errors.\n",
776                                   gn->name);
777                     }
778                     if (GNode_IsError(gn) && errorNode == NULL)
779                               errorNode = gn;
780           }
781 
782           /* If the user has defined a .END target, run its commands. */
783           if (errorNode == NULL) {
784                     GNode *endNode = Targ_GetEndNode();
785                     Compat_Make(endNode, endNode);
786                     if (GNode_IsError(endNode))
787                               errorNode = endNode;
788           }
789 
790           if (errorNode != NULL) {
791                     if (DEBUG(GRAPH2))
792                               Targ_PrintGraph(2);
793                     else if (DEBUG(GRAPH3))
794                               Targ_PrintGraph(3);
795                     PrintOnError(errorNode, "\nStop.\n");
796                     exit(1);
797           }
798 }
799