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