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