1 /*        $NetBSD: make.c,v 1.268 2025/04/23 19:36:59 rillig Exp $    */
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *        The Regents of the University of California.  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) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *        This product includes software developed by the University of
53  *        California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 /*
72  * Examination of targets and their suitability for creation.
73  *
74  * Interface:
75  *        Make_Run  Initialize things for the module. Returns true if
76  *                            work was (or would have been) done.
77  *
78  *        Make_Update         After a target is made, update all its parents.
79  *                            Perform various bookkeeping chores like the updating
80  *                            of the youngestChild field of the parent, filling
81  *                            of the IMPSRC variable, etc. Place the parent on the
82  *                            toBeMade queue if it should be.
83  *
84  *        GNode_UpdateYoungestChild
85  *                            Update the node's youngestChild field based on the
86  *                            child's modification time.
87  *
88  *        GNode_SetLocalVars
89  *                            Set up the various local variables for a
90  *                            target, including the .ALLSRC variable, making
91  *                            sure that any variable that needs to exist
92  *                            at the very least has the empty value.
93  *
94  *        GNode_IsOODate      Determine if a target is out-of-date.
95  *
96  *        Make_HandleUse      See if a child is a .USE node for a parent
97  *                            and perform the .USE actions if so.
98  *
99  *        Make_ExpandUse      Expand .USE nodes
100  */
101 
102 #include "make.h"
103 #include "dir.h"
104 #include "job.h"
105 #ifdef USE_META
106 # include "meta.h"
107 #endif
108 
109 /*        "@(#)make.c         8.1 (Berkeley) 6/6/93"        */
110 MAKE_RCSID("$NetBSD: make.c,v 1.268 2025/04/23 19:36:59 rillig Exp $");
111 
112 /* Sequence # to detect recursion. */
113 static unsigned checked_seqno = 1;
114 
115 /*
116  * The current fringe of the graph.
117  * These are nodes which await examination by MakeOODate.
118  * It is added to by Make_Update and subtracted from by MakeStartJobs
119  */
120 static GNodeList toBeMade = LST_INIT;
121 
122 
123 void
debug_printf(const char * fmt,...)124 debug_printf(const char *fmt, ...)
125 {
126           va_list ap;
127 
128           va_start(ap, fmt);
129           vfprintf(opts.debug_file, fmt, ap);
130           va_end(ap);
131 }
132 
133 static char *
GNodeType_ToString(GNodeType type)134 GNodeType_ToString(GNodeType type)
135 {
136           Buffer buf;
137 
138           Buf_Init(&buf);
139 #define ADD(flag) Buf_AddFlag(&buf, (type & (flag)) != OP_NONE, #flag)
140           ADD(OP_DEPENDS);
141           ADD(OP_FORCE);
142           ADD(OP_DOUBLEDEP);
143           ADD(OP_OPTIONAL);
144           ADD(OP_USE);
145           ADD(OP_EXEC);
146           ADD(OP_IGNORE);
147           ADD(OP_PRECIOUS);
148           ADD(OP_SILENT);
149           ADD(OP_MAKE);
150           ADD(OP_JOIN);
151           ADD(OP_MADE);
152           ADD(OP_SPECIAL);
153           ADD(OP_USEBEFORE);
154           ADD(OP_INVISIBLE);
155           ADD(OP_NOTMAIN);
156           ADD(OP_PHONY);
157           ADD(OP_NOPATH);
158           ADD(OP_WAIT);
159           ADD(OP_NOMETA);
160           ADD(OP_META);
161           ADD(OP_NOMETA_CMP);
162           ADD(OP_SUBMAKE);
163           ADD(OP_TRANSFORM);
164           ADD(OP_MEMBER);
165           ADD(OP_LIB);
166           ADD(OP_ARCHV);
167           ADD(OP_HAS_COMMANDS);
168           ADD(OP_SAVE_CMDS);
169           ADD(OP_DEPS_FOUND);
170           ADD(OP_MARK);
171 #undef ADD
172           if (buf.len == 0)
173                     Buf_AddStr(&buf, "none");
174           return Buf_DoneData(&buf);
175 }
176 
177 static char *
GNodeFlags_ToString(GNodeFlags flags)178 GNodeFlags_ToString(GNodeFlags flags)
179 {
180           Buffer buf;
181 
182           Buf_Init(&buf);
183           Buf_AddFlag(&buf, flags.remake, "REMAKE");
184           Buf_AddFlag(&buf, flags.childMade, "CHILDMADE");
185           Buf_AddFlag(&buf, flags.force, "FORCE");
186           Buf_AddFlag(&buf, flags.doneWait, "DONE_WAIT");
187           Buf_AddFlag(&buf, flags.doneOrder, "DONE_ORDER");
188           Buf_AddFlag(&buf, flags.fromDepend, "FROM_DEPEND");
189           Buf_AddFlag(&buf, flags.doneAllsrc, "DONE_ALLSRC");
190           Buf_AddFlag(&buf, flags.cycle, "CYCLE");
191           Buf_AddFlag(&buf, flags.doneCycle, "DONECYCLE");
192           if (buf.len == 0)
193                     Buf_AddStr(&buf, "none");
194           return Buf_DoneData(&buf);
195 }
196 
197 void
GNode_FprintDetails(FILE * f,const char * prefix,const GNode * gn,const char * suffix)198 GNode_FprintDetails(FILE *f, const char *prefix, const GNode *gn,
199                         const char *suffix)
200 {
201           char *type = GNodeType_ToString(gn->type);
202           char *flags = GNodeFlags_ToString(gn->flags);
203 
204           fprintf(f, "%s%s, type %s, flags %s%s",
205               prefix, GNodeMade_Name(gn->made), type, flags, suffix);
206           free(type);
207           free(flags);
208 }
209 
210 bool
GNode_ShouldExecute(GNode * gn)211 GNode_ShouldExecute(GNode *gn)
212 {
213           return !((gn->type & OP_MAKE)
214               ? opts.noRecursiveExecute
215               : opts.noExecute);
216 }
217 
218 /* Update the youngest child of the node, according to the given child. */
219 void
GNode_UpdateYoungestChild(GNode * gn,GNode * cgn)220 GNode_UpdateYoungestChild(GNode *gn, GNode *cgn)
221 {
222           if (gn->youngestChild == NULL || cgn->mtime > gn->youngestChild->mtime)
223                     gn->youngestChild = cgn;
224 }
225 
226 static bool
IsOODateRegular(GNode * gn)227 IsOODateRegular(GNode *gn)
228 {
229           /* These rules are inherited from the original Make. */
230 
231           if (gn->youngestChild != NULL) {
232                     if (gn->mtime < gn->youngestChild->mtime) {
233                               DEBUG1(MAKE, "modified before source \"%s\"...",
234                                   GNode_Path(gn->youngestChild));
235                               return true;
236                     }
237                     return false;
238           }
239 
240           if (gn->mtime == 0 && !(gn->type & OP_OPTIONAL)) {
241                     DEBUG0(MAKE, "nonexistent and no sources...");
242                     return true;
243           }
244 
245           if (gn->type & OP_DOUBLEDEP) {
246                     DEBUG0(MAKE, ":: operator and no sources...");
247                     return true;
248           }
249 
250           return false;
251 }
252 
253 /*
254  * See if the node is out of date with respect to its sources.
255  *
256  * Used by Make_Run when deciding which nodes to place on the
257  * toBeMade queue initially and by Make_Update to screen out .USE and
258  * .EXEC nodes. In the latter case, however, any other sort of node
259  * must be considered out-of-date since at least one of its children
260  * will have been recreated.
261  *
262  * The mtime field of the node and the youngestChild field of its parents
263  * may be changed.
264  */
265 bool
GNode_IsOODate(GNode * gn)266 GNode_IsOODate(GNode *gn)
267 {
268           bool oodate;
269 
270           /*
271            * Certain types of targets needn't even be sought as their datedness
272            * doesn't depend on their modification time...
273            */
274           if (!(gn->type & (OP_JOIN | OP_USE | OP_USEBEFORE | OP_EXEC))) {
275                     Dir_UpdateMTime(gn, true);
276                     if (DEBUG(MAKE)) {
277                               if (gn->mtime != 0)
278                                         debug_printf("modified %s...",
279                                             Targ_FmtTime(gn->mtime));
280                               else
281                                         debug_printf("nonexistent...");
282                     }
283           }
284 
285           /*
286            * A target is remade in one of the following circumstances:
287            *
288            *        its modification time is smaller than that of its youngest
289            *        child and it would actually be run (has commands or is not
290            *        GNode_IsTarget)
291            *
292            *        it's the object of a force operator
293            *
294            *        it has no children, was on the lhs of an operator and doesn't
295            *        exist already.
296            *
297            * Libraries are only considered out-of-date if the archive module
298            * says they are.
299            *
300            * These weird rules are brought to you by Backward-Compatibility
301            * and the strange people who wrote 'Make'.
302            */
303           if (gn->type & (OP_USE | OP_USEBEFORE)) {
304                     /*
305                      * If the node is a USE node it is *never* out of date
306                      * no matter *what*.
307                      */
308                     DEBUG0(MAKE, ".USE node...");
309                     oodate = false;
310           } else if ((gn->type & OP_LIB) && (gn->mtime == 0 || Arch_IsLib(gn))) {
311                     DEBUG0(MAKE, "library...");
312 
313                     /*
314                      * always out of date if no children and :: target
315                      * or nonexistent.
316                      */
317                     oodate = (gn->mtime == 0 || Arch_LibOODate(gn) ||
318                                 (gn->youngestChild == NULL &&
319                                  (gn->type & OP_DOUBLEDEP)));
320           } else if (gn->type & OP_JOIN) {
321                     /*
322                      * A target with the .JOIN attribute is only considered
323                      * out-of-date if any of its children was out-of-date.
324                      */
325                     DEBUG0(MAKE, ".JOIN node...");
326                     DEBUG1(MAKE, "source %smade...",
327                         gn->flags.childMade ? "" : "not ");
328                     oodate = gn->flags.childMade;
329           } else if (gn->type & (OP_FORCE | OP_EXEC | OP_PHONY)) {
330                     /*
331                      * A node which is the object of the force (!) operator or
332                      * which has the .EXEC attribute is always considered
333                      * out-of-date.
334                      */
335                     if (DEBUG(MAKE)) {
336                               if (gn->type & OP_FORCE)
337                                         debug_printf("! operator...");
338                               else if (gn->type & OP_PHONY)
339                                         debug_printf(".PHONY node...");
340                               else
341                                         debug_printf(".EXEC node...");
342                     }
343                     oodate = true;
344           } else if (IsOODateRegular(gn)) {
345                     oodate = true;
346           } else {
347                     /*
348                      * When a nonexistent child with no sources
349                      * (such as a typically used FORCE source) has been made and
350                      * the target of the child (usually a directory) has the same
351                      * timestamp as the timestamp just given to the nonexistent
352                      * child after it was considered made.
353                      */
354                     if (DEBUG(MAKE)) {
355                               if (gn->flags.force)
356                                         debug_printf("non existing child...");
357                     }
358                     oodate = gn->flags.force;
359           }
360 
361 #ifdef USE_META
362           if (useMeta)
363                     oodate = meta_oodate(gn, oodate);
364 #endif
365 
366           /*
367            * If the target isn't out-of-date, the parents need to know its
368            * modification time. Note that targets that appear to be out-of-date
369            * but aren't, because they have no commands and are GNode_IsTarget,
370            * have their mtime stay below their children's mtime to keep parents
371            * from thinking they're out-of-date.
372            */
373           if (!oodate) {
374                     GNodeListNode *ln;
375                     for (ln = gn->parents.first; ln != NULL; ln = ln->next)
376                               GNode_UpdateYoungestChild(ln->datum, gn);
377           }
378 
379           return oodate;
380 }
381 
382 static void
PretendAllChildrenAreMade(GNode * pgn)383 PretendAllChildrenAreMade(GNode *pgn)
384 {
385           GNodeListNode *ln;
386 
387           for (ln = pgn->children.first; ln != NULL; ln = ln->next) {
388                     GNode *cgn = ln->datum;
389 
390                     /* This may also update cgn->path. */
391                     Dir_UpdateMTime(cgn, false);
392                     GNode_UpdateYoungestChild(pgn, cgn);
393                     pgn->unmade--;
394           }
395 }
396 
397 /*
398  * Called by Make_Run and SuffApplyTransform on the downward pass to handle
399  * .USE and transformation nodes, by copying the child node's commands, type
400  * flags and children to the parent node.
401  *
402  * A .USE node is much like an explicit transformation rule, except its
403  * commands are always added to the target node, even if the target already
404  * has commands.
405  *
406  * Input:
407  *        cgn                 The source node, which is either a .USE/.USEBEFORE
408  *                            node or a transformation node (OP_TRANSFORM).
409  *        pgn                 The target node
410  */
411 void
Make_HandleUse(GNode * cgn,GNode * pgn)412 Make_HandleUse(GNode *cgn, GNode *pgn)
413 {
414           GNodeListNode *ln;  /* An element in the children list */
415 
416 #ifdef DEBUG_SRC
417           if (!(cgn->type & (OP_USE | OP_USEBEFORE | OP_TRANSFORM))) {
418                     debug_printf("Make_HandleUse: called for plain node %s\n",
419                         cgn->name);
420                     /* XXX: debug mode should not affect control flow */
421                     return;
422           }
423 #endif
424 
425           if ((cgn->type & (OP_USE | OP_USEBEFORE)) ||
426               Lst_IsEmpty(&pgn->commands)) {
427                     if (cgn->type & OP_USEBEFORE) {
428                               /* .USEBEFORE */
429                               Lst_PrependAll(&pgn->commands, &cgn->commands);
430                     } else {
431                               /* .USE, or target has no commands */
432                               Lst_AppendAll(&pgn->commands, &cgn->commands);
433                     }
434           }
435 
436           for (ln = cgn->children.first; ln != NULL; ln = ln->next) {
437                     GNode *gn = ln->datum;
438 
439                     /*
440                      * Expand variables in the .USE node's name
441                      * and save the unexpanded form.
442                      * We don't need to do this for commands.
443                      * They get expanded properly when we execute.
444                      */
445                     if (gn->uname == NULL)
446                               gn->uname = gn->name;
447                     else
448                               free(gn->name);
449                     gn->name = Var_Subst(gn->uname, pgn, VARE_EVAL);
450                     /* TODO: handle errors */
451                     if (gn->uname != NULL && strcmp(gn->name, gn->uname) != 0) {
452                               /* See if we have a target for this node. */
453                               GNode *tgn = Targ_FindNode(gn->name);
454                               if (tgn != NULL)
455                                         gn = tgn;
456                     }
457 
458                     Lst_Append(&pgn->children, gn);
459                     Lst_Append(&gn->parents, pgn);
460                     pgn->unmade++;
461           }
462 
463           pgn->type |=
464               cgn->type & (unsigned)~(OP_OPMASK | OP_USE | OP_USEBEFORE | OP_TRANSFORM);
465 }
466 
467 /*
468  * Used by Make_Run on the downward pass to handle .USE nodes. Should be
469  * called before the children are enqueued to be looked at by MakeAddChild.
470  *
471  * For a .USE child, the commands, type flags and children are copied to the
472  * parent node, and since the relation to the .USE node is then no longer
473  * needed, that relation is removed.
474  *
475  * Input:
476  *        cgn                 the child, which may be a .USE node
477  *        pgn                 the current parent
478  */
479 static void
MakeHandleUse(GNode * cgn,GNode * pgn,GNodeListNode * ln)480 MakeHandleUse(GNode *cgn, GNode *pgn, GNodeListNode *ln)
481 {
482           bool unmarked;
483 
484           unmarked = !(cgn->type & OP_MARK);
485           cgn->type |= OP_MARK;
486 
487           if (!(cgn->type & (OP_USE | OP_USEBEFORE)))
488                     return;
489 
490           if (unmarked)
491                     Make_HandleUse(cgn, pgn);
492 
493           /*
494            * This child node is now "made", so we decrement the count of
495            * unmade children in the parent... We also remove the child
496            * from the parent's list to accurately reflect the number of decent
497            * children the parent has. This is used by Make_Run to decide
498            * whether to queue the parent or examine its children...
499            */
500           Lst_Remove(&pgn->children, ln);
501           pgn->unmade--;
502 }
503 
504 static void
HandleUseNodes(GNode * gn)505 HandleUseNodes(GNode *gn)
506 {
507           GNodeListNode *ln, *nln;
508           for (ln = gn->children.first; ln != NULL; ln = nln) {
509                     nln = ln->next;
510                     MakeHandleUse(ln->datum, gn, ln);
511           }
512 }
513 
514 
515 /*
516  * Check the modification time of a gnode, and update it if necessary.
517  * Return 0 if the gnode does not exist, or its filesystem time if it does.
518  */
519 time_t
Make_Recheck(GNode * gn)520 Make_Recheck(GNode *gn)
521 {
522           time_t mtime;
523 
524           Dir_UpdateMTime(gn, true);
525           mtime = gn->mtime;
526 
527 #ifndef RECHECK
528           /*
529            * We can't re-stat the thing, but we can at least take care of rules
530            * where a target depends on a source that actually creates the
531            * target, but only if it has changed, e.g.
532            *
533            * parse.h : parse.o
534            *
535            * parse.o : parse.y
536            *                  yacc -d parse.y
537            *                  cc -c y.tab.c
538            *                  mv y.tab.o parse.o
539            *                  cmp -s y.tab.h parse.h || mv y.tab.h parse.h
540            *
541            * In this case, if the definitions produced by yacc haven't changed
542            * from before, parse.h won't have been updated and gn->mtime will
543            * reflect the current modification time for parse.h. This is
544            * something of a kludge, I admit, but it's a useful one.
545            *
546            * XXX: People like to use a rule like "FRC:" to force things that
547            * depend on FRC to be made, so we have to check for gn->children
548            * being empty as well.
549            */
550           if (!Lst_IsEmpty(gn->commands) || Lst_IsEmpty(gn->children))
551                     gn->mtime = now;
552 #else
553           /*
554            * This is what Make does and it's actually a good thing, as it
555            * allows rules like
556            *
557            *        cmp -s y.tab.h parse.h || cp y.tab.h parse.h
558            *
559            * to function as intended. Unfortunately, thanks to the stateless
560            * nature of NFS (by which I mean the loose coupling of two clients
561            * using the same file from a common server), there are times when
562            * the modification time of a file created on a remote machine
563            * will not be modified before the local stat() implied by the
564            * Dir_UpdateMTime occurs, thus leading us to believe that the file
565            * is unchanged, wreaking havoc with files that depend on this one.
566            *
567            * I have decided it is better to make too much than to make too
568            * little, so this stuff is commented out unless you're sure it's ok.
569            * -- ardeb 1/12/88
570            */
571           /*
572            * Christos, 4/9/92: If we are saving commands, pretend that
573            * the target is made now. Otherwise archives with '...' rules
574            * don't work!
575            */
576           if (!GNode_ShouldExecute(gn) || (gn->type & OP_SAVE_CMDS) ||
577               (mtime == 0 && !(gn->type & OP_WAIT))) {
578                     DEBUG2(MAKE, " recheck(%s): update time from %s to now\n",
579                         gn->name,
580                         gn->mtime == 0 ? "nonexistent" : Targ_FmtTime(gn->mtime));
581                     gn->mtime = now;
582           } else {
583                     DEBUG2(MAKE, " recheck(%s): current update time: %s\n",
584                         gn->name, Targ_FmtTime(gn->mtime));
585           }
586 #endif
587 
588           /*
589            * XXX: The returned mtime may differ from gn->mtime. Intentionally?
590            */
591           return mtime;
592 }
593 
594 /*
595  * Set the .PREFIX and .IMPSRC variables for all the implied parents
596  * of this node.
597  */
598 static void
UpdateImplicitParentsVars(GNode * cgn,const char * cname)599 UpdateImplicitParentsVars(GNode *cgn, const char *cname)
600 {
601           GNodeListNode *ln;
602           const char *cpref = GNode_VarPrefix(cgn);
603 
604           for (ln = cgn->implicitParents.first; ln != NULL; ln = ln->next) {
605                     GNode *pgn = ln->datum;
606                     if (pgn->flags.remake) {
607                               Var_Set(pgn, IMPSRC, cname);
608                               if (cpref != NULL)
609                                         Var_Set(pgn, PREFIX, cpref);
610                     }
611           }
612 }
613 
614 /* See if a .ORDER rule stops us from building this node. */
615 static bool
IsWaitingForOrder(GNode * gn)616 IsWaitingForOrder(GNode *gn)
617 {
618           GNodeListNode *ln;
619 
620           for (ln = gn->order_pred.first; ln != NULL; ln = ln->next) {
621                     GNode *ogn = ln->datum;
622 
623                     if (GNode_IsDone(ogn) || !ogn->flags.remake)
624                               continue;
625 
626                     DEBUG2(MAKE,
627                         "IsWaitingForOrder: Waiting for .ORDER node \"%s%s\"\n",
628                         ogn->name, ogn->cohort_num);
629                     return true;
630           }
631           return false;
632 }
633 
634 static bool MakeBuildChild(GNode *, GNodeListNode *);
635 
636 static void
ScheduleOrderSuccessors(GNode * gn)637 ScheduleOrderSuccessors(GNode *gn)
638 {
639           GNodeListNode *toBeMadeNext = toBeMade.first;
640           GNodeListNode *ln;
641 
642           for (ln = gn->order_succ.first; ln != NULL; ln = ln->next) {
643                     GNode *succ = ln->datum;
644 
645                     if (succ->made == DEFERRED &&
646                         !MakeBuildChild(succ, toBeMadeNext))
647                               succ->flags.doneOrder = true;
648           }
649 }
650 
651 /*
652  * Perform update on the parents of a node. Used by JobFinish once
653  * a node has been dealt with and by MakeStartJobs if it finds an
654  * up-to-date node.
655  *
656  * The unmade field of pgn is decremented and pgn may be placed on
657  * the toBeMade queue if this field becomes 0.
658  *
659  * If the child was made, the parent's flag CHILDMADE field will be
660  * set true.
661  *
662  * If the child is not up-to-date and still does not exist,
663  * set the FORCE flag on the parents.
664  *
665  * If the child wasn't made, the youngestChild field of the parent will be
666  * altered if the child's mtime is big enough.
667  *
668  * Finally, if the child is the implied source for the parent, the
669  * parent's IMPSRC variable is set appropriately.
670  */
671 void
Make_Update(GNode * cgn)672 Make_Update(GNode *cgn)
673 {
674           const char *cname;  /* the child's name */
675           time_t mtime = -1;
676           GNodeList *parents;
677           GNodeListNode *ln;
678           GNode *centurion;
679 
680           /* It is save to re-examine any nodes again */
681           checked_seqno++;
682 
683           cname = GNode_VarTarget(cgn);
684 
685           DEBUG2(MAKE, "Make_Update: %s%s\n", cgn->name, cgn->cohort_num);
686 
687           /*
688            * If the child was actually made, see what its modification time is
689            * now -- some rules won't actually update the file. If the file
690            * still doesn't exist, make its mtime now.
691            */
692           if (cgn->made != UPTODATE)
693                     mtime = Make_Recheck(cgn);
694 
695           /*
696            * If this is a `::' node, we must consult its first instance
697            * which is where all parents are linked.
698            */
699           if ((centurion = cgn->centurion) != NULL) {
700                     if (!Lst_IsEmpty(&cgn->parents))
701                               Punt("%s%s: cohort has parents", cgn->name,
702                                   cgn->cohort_num);
703                     centurion->unmade_cohorts--;
704                     if (centurion->unmade_cohorts < 0)
705                               Error("Graph cycles through centurion %s",
706                                   centurion->name);
707           } else {
708                     centurion = cgn;
709           }
710           parents = &centurion->parents;
711 
712           /* If this was a .ORDER node, schedule the RHS */
713           ScheduleOrderSuccessors(centurion);
714 
715           /* Now mark all the parents as having one less unmade child */
716           for (ln = parents->first; ln != NULL; ln = ln->next) {
717                     GNode *pgn = ln->datum;
718 
719                     if (DEBUG(MAKE)) {
720                               debug_printf("inspect parent %s%s: ", pgn->name,
721                                   pgn->cohort_num);
722                               GNode_FprintDetails(opts.debug_file, "", pgn, "");
723                               debug_printf(", unmade %d ", pgn->unmade - 1);
724                     }
725 
726                     if (!pgn->flags.remake) {
727                               /* This parent isn't needed */
728                               DEBUG0(MAKE, "- not needed\n");
729                               continue;
730                     }
731                     if (mtime == 0 && !(cgn->type & OP_WAIT))
732                               pgn->flags.force = true;
733 
734                     /*
735                      * If the parent has the .MADE attribute, its timestamp got
736                      * updated to that of its newest child, and its unmade
737                      * child count got set to zero in Make_ExpandUse().
738                      * However other things might cause us to build one of its
739                      * children - and so we mustn't do any processing here when
740                      * the child build finishes.
741                      */
742                     if (pgn->type & OP_MADE) {
743                               DEBUG0(MAKE, "- .MADE\n");
744                               continue;
745                     }
746 
747                     if (!(cgn->type & (OP_EXEC | OP_USE | OP_USEBEFORE))) {
748                               if (cgn->made == MADE)
749                                         pgn->flags.childMade = true;
750                               GNode_UpdateYoungestChild(pgn, cgn);
751                     }
752 
753                     /*
754                      * A parent must wait for the completion of all instances
755                      * of a `::' dependency.
756                      */
757                     if (centurion->unmade_cohorts != 0 ||
758                         !GNode_IsDone(centurion)) {
759                               DEBUG2(MAKE,
760                                   "- centurion made %d, %d unmade cohorts\n",
761                                   centurion->made, centurion->unmade_cohorts);
762                               continue;
763                     }
764 
765                     /* One more child of this parent is now made */
766                     pgn->unmade--;
767                     if (pgn->unmade < 0) {
768                               if (DEBUG(MAKE)) {
769                                         debug_printf("Graph cycles through %s%s\n",
770                                             pgn->name, pgn->cohort_num);
771                                         Targ_PrintGraph(2);
772                               }
773                               Error("Graph cycles through %s%s", pgn->name,
774                                   pgn->cohort_num);
775                     }
776 
777                     /*
778                      * We must always rescan the parents of .WAIT and .ORDER
779                      * nodes.
780                      */
781                     if (pgn->unmade != 0 && !(centurion->type & OP_WAIT)
782                         && !centurion->flags.doneOrder) {
783                               DEBUG0(MAKE, "- unmade children\n");
784                               continue;
785                     }
786                     if (pgn->made != DEFERRED) {
787                               /*
788                                * Either this parent is on a different branch of
789                                * the tree, or it on the RHS of a .WAIT directive
790                                * or it is already on the toBeMade list.
791                                */
792                               DEBUG0(MAKE, "- not deferred\n");
793                               continue;
794                     }
795 
796                     if (IsWaitingForOrder(pgn))
797                               continue;
798 
799                     if (DEBUG(MAKE)) {
800                               debug_printf("- %s%s made, schedule %s%s (made %d)\n",
801                                   cgn->name, cgn->cohort_num,
802                                   pgn->name, pgn->cohort_num, pgn->made);
803                               Targ_PrintNode(pgn, 2);
804                     }
805                     /* Ok, we can schedule the parent again */
806                     pgn->made = REQUESTED;
807                     Lst_Enqueue(&toBeMade, pgn);
808           }
809 
810           UpdateImplicitParentsVars(cgn, cname);
811 }
812 
813 static void
UnmarkChildren(GNode * gn)814 UnmarkChildren(GNode *gn)
815 {
816           GNodeListNode *ln;
817 
818           for (ln = gn->children.first; ln != NULL; ln = ln->next) {
819                     GNode *child = ln->datum;
820                     child->type &= (unsigned)~OP_MARK;
821           }
822 }
823 
824 /*
825  * Add a child's name to the ALLSRC and OODATE variables of the given
826  * node, but only if it has not been given the .EXEC, .USE or .INVISIBLE
827  * attributes. .EXEC and .USE children are very rarely going to be files,
828  * so...
829  *
830  * If the child is a .JOIN node, its ALLSRC is propagated to the parent.
831  *
832  * A child is added to the OODATE variable if its modification time is
833  * later than that of its parent, as defined by Make, except if the
834  * parent is a .JOIN node. In that case, it is only added to the OODATE
835  * variable if it was actually made (since .JOIN nodes don't have
836  * modification times, the comparison is rather unfair...)..
837  *
838  * Input:
839  *        cgn                 The child to add
840  *        pgn                 The parent to whose ALLSRC variable it should
841  *                            be added
842  */
843 static void
MakeAddAllSrc(GNode * cgn,GNode * pgn)844 MakeAddAllSrc(GNode *cgn, GNode *pgn)
845 {
846           const char *child, *allsrc;
847 
848           if (cgn->type & OP_MARK)
849                     return;
850           cgn->type |= OP_MARK;
851 
852           if (cgn->type & (OP_EXEC | OP_USE | OP_USEBEFORE | OP_INVISIBLE))
853                     return;
854 
855           if (cgn->type & OP_ARCHV)
856                     child = GNode_VarMember(cgn);
857           else
858                     child = GNode_Path(cgn);
859 
860           if (cgn->type & OP_JOIN)
861                     allsrc = GNode_VarAllsrc(cgn);
862           else
863                     allsrc = child;
864 
865           if (allsrc != NULL)
866                     Var_Append(pgn, ALLSRC, allsrc);
867 
868           if (pgn->type & OP_JOIN) {
869                     if (cgn->made == MADE)
870                               Var_Append(pgn, OODATE, child);
871 
872           } else if ((pgn->mtime < cgn->mtime) ||
873                        (cgn->mtime >= now && cgn->made == MADE)) {
874                     /*
875                      * It goes in the OODATE variable if the parent is
876                      * younger than the child or if the child has been
877                      * modified more recently than the start of the make.
878                      * This is to keep pmake from getting confused if
879                      * something else updates the parent after the make
880                      * starts (shouldn't happen, I know, but sometimes it
881                      * does). In such a case, if we've updated the child,
882                      * the parent is likely to have a modification time
883                      * later than that of the child and anything that
884                      * relies on the OODATE variable will be hosed.
885                      *
886                      * XXX: This will cause all made children to go in
887                      * the OODATE variable, even if they're not touched,
888                      * if RECHECK isn't defined, since cgn->mtime is set
889                      * to now in Make_Update. According to some people,
890                      * this is good...
891                      */
892                     Var_Append(pgn, OODATE, child);
893           }
894 }
895 
896 /*
897  * Set up the ALLSRC and OODATE variables. Sad to say, it must be
898  * done separately, rather than while traversing the graph. This is
899  * because Make defined OODATE to contain all sources whose modification
900  * times were later than that of the target, *not* those sources that
901  * were out-of-date. Since in both compatibility and native modes,
902  * the modification time of the parent isn't found until the child
903  * has been dealt with, we have to wait until now to fill in the
904  * variable. As for ALLSRC, the ordering is important and not
905  * guaranteed when in native mode, so it must be set here, too.
906  *
907  * If the node is a .JOIN node, its TARGET variable will be set to
908  * match its ALLSRC variable.
909  */
910 void
GNode_SetLocalVars(GNode * gn)911 GNode_SetLocalVars(GNode *gn)
912 {
913           GNodeListNode *ln;
914 
915           if (gn->flags.doneAllsrc)
916                     return;
917 
918           UnmarkChildren(gn);
919           for (ln = gn->children.first; ln != NULL; ln = ln->next)
920                     MakeAddAllSrc(ln->datum, gn);
921 
922           if (!Var_Exists(gn, OODATE))
923                     Var_Set(gn, OODATE, "");
924           if (!Var_Exists(gn, ALLSRC))
925                     Var_Set(gn, ALLSRC, "");
926 
927           if (gn->type & OP_JOIN)
928                     Var_Set(gn, TARGET, GNode_VarAllsrc(gn));
929           gn->flags.doneAllsrc = true;
930 }
931 
932 static void
ScheduleRandomly(GNode * gn)933 ScheduleRandomly(GNode *gn)
934 {
935           GNodeListNode *ln;
936           size_t i, n;
937 
938           n = 0;
939           for (ln = toBeMade.first; ln != NULL; ln = ln->next)
940                     n++;
941           i = n > 0 ? (size_t)random() % (n + 1) : 0;
942 
943           if (i == 0) {
944                     Lst_Append(&toBeMade, gn);
945                     return;
946           }
947           i--;
948 
949           for (ln = toBeMade.first; i > 0; ln = ln->next)
950                     i--;
951           Lst_InsertBefore(&toBeMade, ln, gn);
952 }
953 
954 static bool
MakeBuildChild(GNode * cn,GNodeListNode * toBeMadeNext)955 MakeBuildChild(GNode *cn, GNodeListNode *toBeMadeNext)
956 {
957 
958           if (DEBUG(MAKE)) {
959                     debug_printf("MakeBuildChild: inspect %s%s, ",
960                         cn->name, cn->cohort_num);
961                     GNode_FprintDetails(opts.debug_file, "", cn, "\n");
962           }
963           if (GNode_IsReady(cn))
964                     return false;
965 
966           /* If this node is on the RHS of a .ORDER, check LHSs. */
967           if (IsWaitingForOrder(cn)) {
968                     /*
969                      * Can't build this (or anything else in this child list) yet
970                      */
971                     cn->made = DEFERRED;
972                     return false;       /* but keep looking */
973           }
974 
975           DEBUG2(MAKE, "MakeBuildChild: schedule %s%s\n",
976               cn->name, cn->cohort_num);
977 
978           cn->made = REQUESTED;
979           if (opts.randomizeTargets && !(cn->type & OP_WAIT))
980                     ScheduleRandomly(cn);
981           else if (toBeMadeNext == NULL)
982                     Lst_Append(&toBeMade, cn);
983           else
984                     Lst_InsertBefore(&toBeMade, toBeMadeNext, cn);
985 
986           if (cn->unmade_cohorts != 0) {
987                     ListNode *ln;
988 
989                     for (ln = cn->cohorts.first; ln != NULL; ln = ln->next)
990                               if (MakeBuildChild(ln->datum, toBeMadeNext))
991                                         break;
992           }
993 
994           /*
995            * If this node is a .WAIT node with unmade children
996            * then don't add the next sibling.
997            */
998           return cn->type & OP_WAIT && cn->unmade > 0;
999 }
1000 
1001 static void
MakeChildren(GNode * gn)1002 MakeChildren(GNode *gn)
1003 {
1004           GNodeListNode *toBeMadeNext = toBeMade.first;
1005           GNodeListNode *ln;
1006 
1007           for (ln = gn->children.first; ln != NULL; ln = ln->next)
1008                     if (MakeBuildChild(ln->datum, toBeMadeNext))
1009                               break;
1010 }
1011 
1012 /*
1013  * Start as many jobs as possible, taking them from the toBeMade queue.
1014  *
1015  * If the -q option was given, no job will be started,
1016  * but as soon as an out-of-date target is found, this function
1017  * returns true. In all other cases, this function returns false.
1018  */
1019 static bool
MakeStartJobs(void)1020 MakeStartJobs(void)
1021 {
1022           GNode *gn;
1023           bool have_token = false;
1024 
1025           while (!Lst_IsEmpty(&toBeMade)) {
1026                     /*
1027                      * Get token now to avoid cycling job-list when we only
1028                      * have 1 token
1029                      */
1030                     if (!have_token && !TokenPool_Take())
1031                               break;
1032                     have_token = true;
1033 
1034                     gn = Lst_Dequeue(&toBeMade);
1035                     DEBUG2(MAKE, "Examining %s%s...\n", gn->name, gn->cohort_num);
1036 
1037                     if (gn->made != REQUESTED) {
1038                               debug_printf("internal error: made = %s\n",
1039                                   GNodeMade_Name(gn->made));
1040                               Targ_PrintNode(gn, 2);
1041                               Targ_PrintNodes(&toBeMade, 2);
1042                               Targ_PrintGraph(3);
1043                               abort();
1044                     }
1045 
1046                     if (gn->checked_seqno == checked_seqno) {
1047                               /*
1048                                * We've already looked at this node since a job
1049                                * finished...
1050                                */
1051                               DEBUG2(MAKE, "already checked %s%s\n", gn->name,
1052                                   gn->cohort_num);
1053                               gn->made = DEFERRED;
1054                               continue;
1055                     }
1056                     gn->checked_seqno = checked_seqno;
1057 
1058                     if (gn->unmade != 0) {
1059                               /*
1060                                * We can't build this yet, add all unmade children
1061                                * to toBeMade, just before the current first element.
1062                                */
1063                               gn->made = DEFERRED;
1064 
1065                               MakeChildren(gn);
1066 
1067                               /* and drop this node on the floor */
1068                               DEBUG2(MAKE, "dropped %s%s\n", gn->name,
1069                                   gn->cohort_num);
1070                               continue;
1071                     }
1072 
1073                     gn->made = BEINGMADE;
1074                     if (GNode_IsOODate(gn)) {
1075                               DEBUG0(MAKE, "out-of-date\n");
1076                               if (opts.query)
1077                                         return strcmp(gn->name, ".MAIN") != 0;
1078                               GNode_SetLocalVars(gn);
1079                               Job_Make(gn);
1080                               have_token = false;
1081                     } else {
1082                               DEBUG0(MAKE, "up-to-date\n");
1083                               gn->made = UPTODATE;
1084                               if (gn->type & OP_JOIN) {
1085                                         /*
1086                                          * Even for an up-to-date .JOIN node, we
1087                                          * need it to have its local variables so
1088                                          * references to it get the correct value
1089                                          * for .TARGET when building up the local
1090                                          * variables of its parent(s)...
1091                                          */
1092                                         GNode_SetLocalVars(gn);
1093                               }
1094                               Make_Update(gn);
1095                     }
1096           }
1097 
1098           if (have_token)
1099                     TokenPool_Return();
1100 
1101           return false;
1102 }
1103 
1104 /* Print the status of a .ORDER node. */
1105 static void
MakePrintStatusOrderNode(GNode * ogn,GNode * gn)1106 MakePrintStatusOrderNode(GNode *ogn, GNode *gn)
1107 {
1108           if (!GNode_IsWaitingFor(ogn))
1109                     return;
1110 
1111           printf("    `%s%s' has .ORDER dependency on %s%s ",
1112               gn->name, gn->cohort_num, ogn->name, ogn->cohort_num);
1113           GNode_FprintDetails(stdout, "(", ogn, ")\n");
1114 
1115           if (DEBUG(MAKE) && opts.debug_file != stdout) {
1116                     debug_printf("    `%s%s' has .ORDER dependency on %s%s ",
1117                         gn->name, gn->cohort_num, ogn->name, ogn->cohort_num);
1118                     GNode_FprintDetails(opts.debug_file, "(", ogn, ")\n");
1119           }
1120 }
1121 
1122 static void
MakePrintStatusOrder(GNode * gn)1123 MakePrintStatusOrder(GNode *gn)
1124 {
1125           GNodeListNode *ln;
1126           for (ln = gn->order_pred.first; ln != NULL; ln = ln->next)
1127                     MakePrintStatusOrderNode(ln->datum, gn);
1128 }
1129 
1130 static void MakePrintStatusList(GNodeList *, int *);
1131 
1132 /*
1133  * Print the status of a top-level node, viz. it being up-to-date already
1134  * or not created due to an error in a lower level.
1135  */
1136 static bool
MakePrintStatus(GNode * gn,int * errors)1137 MakePrintStatus(GNode *gn, int *errors)
1138 {
1139           if (gn->flags.doneCycle) {
1140                     /*
1141                      * We've completely processed this node before, don't do
1142                      * it again.
1143                      */
1144                     return false;
1145           }
1146 
1147           if (gn->unmade == 0) {
1148                     gn->flags.doneCycle = true;
1149                     switch (gn->made) {
1150                     case UPTODATE:
1151                               printf("`%s%s' is up to date.\n", gn->name,
1152                                   gn->cohort_num);
1153                               break;
1154                     case MADE:
1155                               break;
1156                     case UNMADE:
1157                     case DEFERRED:
1158                     case REQUESTED:
1159                     case BEINGMADE:
1160                               (*errors)++;
1161                               printf("`%s%s' was not built", gn->name,
1162                                   gn->cohort_num);
1163                               GNode_FprintDetails(stdout, " (", gn, ")!\n");
1164                               if (DEBUG(MAKE) && opts.debug_file != stdout) {
1165                                         debug_printf("`%s%s' was not built", gn->name,
1166                                             gn->cohort_num);
1167                                         GNode_FprintDetails(opts.debug_file, " (", gn,
1168                                             ")!\n");
1169                               }
1170                               /* Most likely problem is actually caused by .ORDER */
1171                               MakePrintStatusOrder(gn);
1172                               break;
1173                     default:
1174                               /* Errors - already counted */
1175                               printf("`%s%s' not remade because of errors.\n",
1176                                   gn->name, gn->cohort_num);
1177                               if (DEBUG(MAKE) && opts.debug_file != stdout)
1178                                         debug_printf(
1179                                             "`%s%s' not remade because of errors.\n",
1180                                             gn->name, gn->cohort_num);
1181                               break;
1182                     }
1183                     return false;
1184           }
1185 
1186           DEBUG3(MAKE, "MakePrintStatus: %s%s has %d unmade children\n",
1187               gn->name, gn->cohort_num, gn->unmade);
1188           /*
1189            * If printing cycles and came to one that has unmade children,
1190            * print out the cycle by recursing on its children.
1191            */
1192           if (!gn->flags.cycle) {
1193                     /* First time we've seen this node, check all children */
1194                     gn->flags.cycle = true;
1195                     MakePrintStatusList(&gn->children, errors);
1196                     /* Mark that this node needn't be processed again */
1197                     gn->flags.doneCycle = true;
1198                     return false;
1199           }
1200 
1201           /* Only output the error once per node */
1202           gn->flags.doneCycle = true;
1203           Error("Graph cycles through `%s%s'", gn->name, gn->cohort_num);
1204           if ((*errors)++ > 100)
1205                     /* Abandon the whole error report */
1206                     return true;
1207 
1208           /* Reporting for our children will give the rest of the loop */
1209           MakePrintStatusList(&gn->children, errors);
1210           return false;
1211 }
1212 
1213 static void
MakePrintStatusList(GNodeList * gnodes,int * errors)1214 MakePrintStatusList(GNodeList *gnodes, int *errors)
1215 {
1216           GNodeListNode *ln;
1217 
1218           for (ln = gnodes->first; ln != NULL; ln = ln->next)
1219                     if (MakePrintStatus(ln->datum, errors))
1220                               break;
1221 }
1222 
1223 static void
ExamineLater(GNodeList * examine,GNodeList * toBeExamined)1224 ExamineLater(GNodeList *examine, GNodeList *toBeExamined)
1225 {
1226           GNodeListNode *ln;
1227 
1228           for (ln = toBeExamined->first; ln != NULL; ln = ln->next) {
1229                     GNode *gn = ln->datum;
1230 
1231                     if (gn->flags.remake)
1232                               continue;
1233                     if (gn->type & (OP_USE | OP_USEBEFORE))
1234                               continue;
1235 
1236                     DEBUG2(MAKE, "ExamineLater: need to examine \"%s%s\"\n",
1237                         gn->name, gn->cohort_num);
1238                     Lst_Enqueue(examine, gn);
1239           }
1240 }
1241 
1242 /*
1243  * Expand .USE nodes and create a new targets list.
1244  *
1245  * Input:
1246  *        targs               the initial list of targets
1247  */
1248 void
Make_ExpandUse(GNodeList * targs)1249 Make_ExpandUse(GNodeList *targs)
1250 {
1251           GNodeList examine = LST_INIT; /* Queue of targets to examine */
1252           Lst_AppendAll(&examine, targs);
1253 
1254           /*
1255            * Make an initial downward pass over the graph, marking nodes to
1256            * be made as we go down.
1257            *
1258            * We call Suff_FindDeps to find where a node is and to get some
1259            * children for it if it has none and also has no commands. If the
1260            * node is a leaf, we stick it on the toBeMade queue to be looked
1261            * at in a minute, otherwise we add its children to our queue and
1262            * go on about our business.
1263            */
1264           while (!Lst_IsEmpty(&examine)) {
1265                     GNode *gn = Lst_Dequeue(&examine);
1266 
1267                     if (gn->flags.remake)
1268                               /* We've looked at this one already */
1269                               continue;
1270                     gn->flags.remake = true;
1271                     DEBUG2(MAKE, "Make_ExpandUse: examine %s%s\n",
1272                         gn->name, gn->cohort_num);
1273 
1274                     if (gn->type & OP_DOUBLEDEP)
1275                               Lst_PrependAll(&examine, &gn->cohorts);
1276 
1277                     /*
1278                      * Apply any .USE rules before looking for implicit
1279                      * dependencies to make sure everything has commands that
1280                      * should.
1281                      *
1282                      * Make sure that the TARGET is set, so that we can make
1283                      * expansions.
1284                      */
1285                     if (gn->type & OP_ARCHV) {
1286                               char *eoa = strchr(gn->name, '(');
1287                               char *eon = strchr(gn->name, ')');
1288                               if (eoa == NULL || eon == NULL)
1289                                         continue;
1290                               *eoa = '\0';
1291                               *eon = '\0';
1292                               Var_Set(gn, MEMBER, eoa + 1);
1293                               Var_Set(gn, ARCHIVE, gn->name);
1294                               *eoa = '(';
1295                               *eon = ')';
1296                     }
1297 
1298                     Dir_UpdateMTime(gn, false);
1299                     Var_Set(gn, TARGET, GNode_Path(gn));
1300                     UnmarkChildren(gn);
1301                     HandleUseNodes(gn);
1302 
1303                     if (!(gn->type & OP_MADE))
1304                               Suff_FindDeps(gn);
1305                     else {
1306                               PretendAllChildrenAreMade(gn);
1307                               if (gn->unmade != 0) {
1308                                         printf(
1309                                             "Warning: "
1310                                             "%s%s still has %d unmade children\n",
1311                                             gn->name, gn->cohort_num, gn->unmade);
1312                               }
1313                     }
1314 
1315                     if (gn->unmade != 0)
1316                               ExamineLater(&examine, &gn->children);
1317           }
1318 
1319           Lst_Done(&examine);
1320 }
1321 
1322 /* Make the .WAIT node depend on the previous children */
1323 static void
add_wait_dependency(GNodeListNode * owln,GNode * wn)1324 add_wait_dependency(GNodeListNode *owln, GNode *wn)
1325 {
1326           GNodeListNode *cln;
1327           GNode *cn;
1328 
1329           for (cln = owln; (cn = cln->datum) != wn; cln = cln->next) {
1330                     DEBUG3(MAKE, ".WAIT: add dependency %s%s -> %s\n",
1331                         cn->name, cn->cohort_num, wn->name);
1332 
1333                     /*
1334                      * XXX: This pattern should be factored out, it repeats often
1335                      */
1336                     Lst_Append(&wn->children, cn);
1337                     wn->unmade++;
1338                     Lst_Append(&cn->parents, wn);
1339           }
1340 }
1341 
1342 /* Convert .WAIT nodes into dependencies. */
1343 static void
Make_ProcessWait(GNodeList * targs)1344 Make_ProcessWait(GNodeList *targs)
1345 {
1346           GNode *pgn;                   /* 'parent' node we are examining */
1347           GNodeListNode *owln;          /* Previous .WAIT node */
1348           GNodeList examine;  /* List of targets to examine */
1349 
1350           /*
1351            * We need all the nodes to have a common parent in order for the
1352            * .WAIT and .ORDER scheduling to work.
1353            * Perhaps this should be done earlier...
1354            */
1355 
1356           pgn = GNode_New(".MAIN");
1357           pgn->flags.remake = true;
1358           pgn->type = OP_PHONY | OP_DEPENDS;
1359           /* Get it displayed in the diag dumps */
1360           Lst_Prepend(Targ_List(), pgn);
1361 
1362           {
1363                     GNodeListNode *ln;
1364                     for (ln = targs->first; ln != NULL; ln = ln->next) {
1365                               GNode *cgn = ln->datum;
1366 
1367                               Lst_Append(&pgn->children, cgn);
1368                               Lst_Append(&cgn->parents, pgn);
1369                               pgn->unmade++;
1370                     }
1371           }
1372 
1373           /* Start building with the 'dummy' .MAIN' node */
1374           MakeBuildChild(pgn, NULL);
1375 
1376           Lst_Init(&examine);
1377           Lst_Append(&examine, pgn);
1378 
1379           while (!Lst_IsEmpty(&examine)) {
1380                     GNodeListNode *ln;
1381 
1382                     pgn = Lst_Dequeue(&examine);
1383 
1384                     /* We only want to process each child-list once */
1385                     if (pgn->flags.doneWait)
1386                               continue;
1387                     pgn->flags.doneWait = true;
1388                     DEBUG1(MAKE, "Make_ProcessWait: examine %s\n", pgn->name);
1389 
1390                     if (pgn->type & OP_DOUBLEDEP)
1391                               Lst_PrependAll(&examine, &pgn->cohorts);
1392 
1393                     owln = pgn->children.first;
1394                     for (ln = pgn->children.first; ln != NULL; ln = ln->next) {
1395                               GNode *cgn = ln->datum;
1396                               if (cgn->type & OP_WAIT) {
1397                                         add_wait_dependency(owln, cgn);
1398                                         owln = ln;
1399                               } else {
1400                                         Lst_Append(&examine, cgn);
1401                               }
1402                     }
1403           }
1404 
1405           Lst_Done(&examine);
1406 }
1407 
1408 /*
1409  * Initialize the nodes to remake and the list of nodes which are ready to
1410  * be made by doing a breadth-first traversal of the graph starting from the
1411  * nodes in the given list. Once this traversal is finished, all the 'leaves'
1412  * of the graph are in the toBeMade queue.
1413  *
1414  * Using this queue and the Job module, work back up the graph, calling on
1415  * MakeStartJobs to keep the job table as full as possible.
1416  *
1417  * Input:
1418  *        targs               the initial list of targets
1419  *
1420  * Results:
1421  *        True if work was done, false otherwise.
1422  *
1423  * Side Effects:
1424  *        The make field of all nodes involved in the creation of the given
1425  *        targets is set to 1. The toBeMade list is set to contain all the
1426  *        'leaves' of these subgraphs.
1427  */
1428 bool
Make_Run(GNodeList * targs)1429 Make_Run(GNodeList *targs)
1430 {
1431           int errors;                   /* Number of errors the Job module reports */
1432 
1433           /* Start trying to make the current targets... */
1434           Lst_Init(&toBeMade);
1435 
1436           Make_ExpandUse(targs);
1437           Make_ProcessWait(targs);
1438 
1439           if (DEBUG(MAKE)) {
1440                     debug_printf("#***# full graph\n");
1441                     Targ_PrintGraph(1);
1442           }
1443 
1444           if (opts.query) {
1445                     /*
1446                      * We wouldn't do any work unless we could start some jobs
1447                      * in the next loop... (we won't actually start any, of
1448                      * course, this is just to see if any of the targets was out
1449                      * of date)
1450                      */
1451                     return MakeStartJobs();
1452           }
1453           /*
1454            * Initialization. At the moment, no jobs are running and until some
1455            * get started, nothing will happen since the remaining upward
1456            * traversal of the graph is performed by the routines in job.c upon
1457            * the finishing of a job. So we fill the Job table as much as we can
1458            * before going into our loop.
1459            */
1460           (void)MakeStartJobs();
1461 
1462           /*
1463            * Main Loop: The idea here is that the ending of jobs will take
1464            * care of the maintenance of data structures and the waiting for
1465            * output will cause us to be idle most of the time while our
1466            * children run as much as possible. Because the job table is kept
1467            * as full as possible, the only time when it will be empty is when
1468            * all the jobs which need running have been run, so that is the end
1469            * condition of this loop. Note that the Job module will exit if
1470            * there were any errors unless the keepgoing flag was given.
1471            */
1472           while (!Lst_IsEmpty(&toBeMade) || jobTokensRunning > 0) {
1473                     Job_CatchOutput();
1474                     (void)MakeStartJobs();
1475           }
1476 
1477           errors = Job_Finish();
1478 
1479           /*
1480            * Print the final status of each target. E.g. if it wasn't made
1481            * because some inferior reported an error.
1482            */
1483           DEBUG1(MAKE, "done: errors %d\n", errors);
1484           if (errors == 0) {
1485                     MakePrintStatusList(targs, &errors);
1486                     if (DEBUG(MAKE)) {
1487                               debug_printf("done: errors %d\n", errors);
1488                               if (errors > 0)
1489                                         Targ_PrintGraph(4);
1490                     }
1491           }
1492           return errors > 0;
1493 }
1494