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