xref: /netbsd-src/usr.bin/make/make.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: make.c,v 1.55 2004/07/01 20:38:09 jmc 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.55 2004/07/01 20:38:09 jmc 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.55 2004/07/01 20:38:09 jmc 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 cmtime 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 cmtime 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 and return the new list of
116  *				targets.
117  */
118 
119 #include    "make.h"
120 #include    "hash.h"
121 #include    "dir.h"
122 #include    "job.h"
123 
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 static int  	numNodes;   	/* Number of nodes to be processed. If this
130 				 * is non-zero when Job_Empty() returns
131 				 * TRUE, there's a cycle in the graph */
132 
133 static int MakeAddChild(ClientData, ClientData);
134 static int MakeFindChild(ClientData, ClientData);
135 static int MakeUnmark(ClientData, ClientData);
136 static int MakeAddAllSrc(ClientData, ClientData);
137 static int MakeTimeStamp(ClientData, ClientData);
138 static int MakeHandleUse(ClientData, ClientData);
139 static Boolean MakeStartJobs(void);
140 static int MakePrintStatus(ClientData, ClientData);
141 /*-
142  *-----------------------------------------------------------------------
143  * Make_TimeStamp --
144  *	Set the cmtime field of a parent node based on the mtime stamp in its
145  *	child. Called from MakeOODate via Lst_ForEach.
146  *
147  * Input:
148  *	pgn		the current parent
149  *	cgn		the child we've just examined
150  *
151  * Results:
152  *	Always returns 0.
153  *
154  * Side Effects:
155  *	The cmtime of the parent node will be changed if the mtime
156  *	field of the child is greater than it.
157  *-----------------------------------------------------------------------
158  */
159 int
160 Make_TimeStamp(GNode *pgn, GNode *cgn)
161 {
162     if (cgn->mtime > pgn->cmtime) {
163 	pgn->cmtime = cgn->mtime;
164     }
165     return (0);
166 }
167 
168 /*
169  * Input:
170  *	pgn		the current parent
171  *	cgn		the child we've just examined
172  *
173  */
174 static int
175 MakeTimeStamp(ClientData pgn, ClientData cgn)
176 {
177     return Make_TimeStamp((GNode *) pgn, (GNode *) cgn);
178 }
179 
180 /*-
181  *-----------------------------------------------------------------------
182  * Make_OODate --
183  *	See if a given node is out of date with respect to its sources.
184  *	Used by Make_Run when deciding which nodes to place on the
185  *	toBeMade queue initially and by Make_Update to screen out USE and
186  *	EXEC nodes. In the latter case, however, any other sort of node
187  *	must be considered out-of-date since at least one of its children
188  *	will have been recreated.
189  *
190  * Input:
191  *	gn		the node to check
192  *
193  * Results:
194  *	TRUE if the node is out of date. FALSE otherwise.
195  *
196  * Side Effects:
197  *	The mtime field of the node and the cmtime field of its parents
198  *	will/may be changed.
199  *-----------------------------------------------------------------------
200  */
201 Boolean
202 Make_OODate(GNode *gn)
203 {
204     Boolean         oodate;
205 
206     /*
207      * Certain types of targets needn't even be sought as their datedness
208      * doesn't depend on their modification time...
209      */
210     if ((gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC)) == 0) {
211 	(void) Dir_MTime (gn);
212 	if (DEBUG(MAKE)) {
213 	    if (gn->mtime != 0) {
214 		printf ("modified %s...", Targ_FmtTime(gn->mtime));
215 	    } else {
216 		printf ("non-existent...");
217 	    }
218 	}
219     }
220 
221     /*
222      * A target is remade in one of the following circumstances:
223      *	its modification time is smaller than that of its youngest child
224      *	    and it would actually be run (has commands or type OP_NOP)
225      *	it's the object of a force operator
226      *	it has no children, was on the lhs of an operator and doesn't exist
227      *	    already.
228      *
229      * Libraries are only considered out-of-date if the archive module says
230      * they are.
231      *
232      * These weird rules are brought to you by Backward-Compatibility and
233      * the strange people who wrote 'Make'.
234      */
235     if (gn->type & (OP_USE|OP_USEBEFORE)) {
236 	/*
237 	 * If the node is a USE node it is *never* out of date
238 	 * no matter *what*.
239 	 */
240 	if (DEBUG(MAKE)) {
241 	    printf(".USE node...");
242 	}
243 	oodate = FALSE;
244     } else if ((gn->type & OP_LIB) &&
245 	       ((gn->mtime==0) || Arch_IsLib(gn))) {
246 	if (DEBUG(MAKE)) {
247 	    printf("library...");
248 	}
249 
250 	/*
251 	 * always out of date if no children and :: target
252 	 * or non-existent.
253 	 */
254 	oodate = (gn->mtime == 0 || Arch_LibOODate (gn) ||
255 		  (gn->cmtime == 0 && (gn->type & OP_DOUBLEDEP)));
256     } else if (gn->type & OP_JOIN) {
257 	/*
258 	 * A target with the .JOIN attribute is only considered
259 	 * out-of-date if any of its children was out-of-date.
260 	 */
261 	if (DEBUG(MAKE)) {
262 	    printf(".JOIN node...");
263 	}
264 	if (DEBUG(MAKE)) {
265 	    printf("source %smade...", gn->flags & CHILDMADE ? "" : "not ");
266 	}
267 	oodate = (gn->flags & CHILDMADE) ? TRUE : FALSE;
268     } else if (gn->type & (OP_FORCE|OP_EXEC|OP_PHONY)) {
269 	/*
270 	 * A node which is the object of the force (!) operator or which has
271 	 * the .EXEC attribute is always considered out-of-date.
272 	 */
273 	if (DEBUG(MAKE)) {
274 	    if (gn->type & OP_FORCE) {
275 		printf("! operator...");
276 	    } else if (gn->type & OP_PHONY) {
277 		printf(".PHONY node...");
278 	    } else {
279 		printf(".EXEC node...");
280 	    }
281 	}
282 	oodate = TRUE;
283     } else if (gn->mtime < gn->cmtime ||
284 	       (gn->cmtime == 0 &&
285 		((gn->mtime == 0 && !(gn->type & OP_OPTIONAL))
286 		  || gn->type & OP_DOUBLEDEP)))
287     {
288 	/*
289 	 * A node whose modification time is less than that of its
290 	 * youngest child or that has no children (cmtime == 0) and
291 	 * either doesn't exist (mtime == 0) and it isn't optional
292 	 * or was the object of a * :: operator is out-of-date.
293 	 * Why? Because that's the way Make does it.
294 	 */
295 	if (DEBUG(MAKE)) {
296 	    if (gn->mtime < gn->cmtime) {
297 		printf("modified before source...");
298 	    } else if (gn->mtime == 0) {
299 		printf("non-existent and no sources...");
300 	    } else {
301 		printf(":: operator and no sources...");
302 	    }
303 	}
304 	oodate = TRUE;
305     } else {
306 	/*
307 	 * When a non-existing child with no sources
308 	 * (such as a typically used FORCE source) has been made and
309 	 * the target of the child (usually a directory) has the same
310 	 * timestamp as the timestamp just given to the non-existing child
311 	 * after it was considered made.
312 	 */
313 	if (DEBUG(MAKE)) {
314 	    if (gn->flags & FORCE)
315 		printf("non existing child...");
316 	}
317 	oodate = (gn->flags & FORCE) ? TRUE : FALSE;
318     }
319 
320     /*
321      * If the target isn't out-of-date, the parents need to know its
322      * modification time. Note that targets that appear to be out-of-date
323      * but aren't, because they have no commands and aren't of type OP_NOP,
324      * have their mtime stay below their children's mtime to keep parents from
325      * thinking they're out-of-date.
326      */
327     if (!oodate) {
328 	Lst_ForEach (gn->parents, MakeTimeStamp, (ClientData)gn);
329     }
330 
331     return (oodate);
332 }
333 
334 /*-
335  *-----------------------------------------------------------------------
336  * MakeAddChild  --
337  *	Function used by Make_Run to add a child to the list l.
338  *	It will only add the child if its make field is FALSE.
339  *
340  * Input:
341  *	gnp		the node to add
342  *	lp		the list to which to add it
343  *
344  * Results:
345  *	Always returns 0
346  *
347  * Side Effects:
348  *	The given list is extended
349  *-----------------------------------------------------------------------
350  */
351 static int
352 MakeAddChild(ClientData gnp, ClientData lp)
353 {
354     GNode          *gn = (GNode *) gnp;
355     Lst            l = (Lst) lp;
356 
357     if ((gn->flags & REMAKE) == 0 && !(gn->type & (OP_USE|OP_USEBEFORE))) {
358 	(void)Lst_EnQueue (l, (ClientData)gn);
359     }
360     return (0);
361 }
362 
363 /*-
364  *-----------------------------------------------------------------------
365  * MakeFindChild  --
366  *	Function used by Make_Run to find the pathname of a child
367  *	that was already made.
368  *
369  * Input:
370  *	gnp		the node to find
371  *
372  * Results:
373  *	Always returns 0
374  *
375  * Side Effects:
376  *	The path and mtime of the node and the cmtime of the parent are
377  *	updated; the unmade children count of the parent is decremented.
378  *-----------------------------------------------------------------------
379  */
380 static int
381 MakeFindChild(ClientData gnp, ClientData pgnp)
382 {
383     GNode          *gn = (GNode *) gnp;
384     GNode          *pgn = (GNode *) pgnp;
385 
386     (void) Dir_MTime(gn);
387     Make_TimeStamp(pgn, gn);
388     pgn->unmade--;
389 
390     return (0);
391 }
392 
393 /*-
394  *-----------------------------------------------------------------------
395  * Make_HandleUse --
396  *	Function called by Make_Run and SuffApplyTransform on the downward
397  *	pass to handle .USE and transformation nodes. It implements the
398  *	.USE and transformation functionality by copying the node's commands,
399  *	type flags and children to the parent node.
400  *
401  *	A .USE node is much like an explicit transformation rule, except
402  *	its commands are always added to the target node, even if the
403  *	target already has commands.
404  *
405  * Input:
406  *	cgn		The .USE node
407  *	pgn		The target of the .USE node
408  *
409  * Results:
410  *	none
411  *
412  * Side Effects:
413  *	Children and commands may be added to the parent and the parent's
414  *	type may be changed.
415  *
416  *-----------------------------------------------------------------------
417  */
418 void
419 Make_HandleUse(GNode *cgn, GNode *pgn)
420 {
421     LstNode	ln; 	/* An element in the children list */
422 
423 #ifdef DEBUG_SRC
424     if ((cgn->type & (OP_USE|OP_USEBEFORE|OP_TRANSFORM)) == 0) {
425 	printf("Make_HandleUse: called for plain node %s\n", cgn->name);
426 	return;
427     }
428 #endif
429 
430     if ((cgn->type & (OP_USE|OP_USEBEFORE)) || Lst_IsEmpty(pgn->commands)) {
431 	    if (cgn->type & OP_USEBEFORE) {
432 		/*
433 		 * .USEBEFORE --
434 		 *	prepend the child's commands to the parent.
435 		 */
436 		Lst cmds = pgn->commands;
437 		pgn->commands = Lst_Duplicate (cgn->commands, NOCOPY);
438 		(void) Lst_Concat (pgn->commands, cmds, LST_CONCNEW);
439 		Lst_Destroy (cmds, NOFREE);
440 	    } else {
441 		/*
442 		 * .USE or target has no commands --
443 		 *	append the child's commands to the parent.
444 		 */
445 		(void) Lst_Concat (pgn->commands, cgn->commands, LST_CONCNEW);
446 	    }
447     }
448 
449     if (Lst_Open (cgn->children) == SUCCESS) {
450 	while ((ln = Lst_Next (cgn->children)) != NILLNODE) {
451 	    GNode *tgn, *gn = (GNode *)Lst_Datum (ln);
452 
453 	    /*
454 	     * Expand variables in the .USE node's name
455 	     * and save the unexpanded form.
456 	     * We don't need to do this for commands.
457 	     * They get expanded properly when we execute.
458 	     */
459 	    if (gn->uname == NULL) {
460 		gn->uname = gn->name;
461 	    } else {
462 		if (gn->name)
463 		    free(gn->name);
464 	    }
465 	    gn->name = Var_Subst(NULL, gn->uname, pgn, FALSE);
466 	    if (gn->name && gn->uname && strcmp(gn->name, gn->uname) != 0) {
467 		/* See if we have a target for this node. */
468 		tgn = Targ_FindNode(gn->name, TARG_NOCREATE);
469 		if (tgn != NILGNODE)
470 		    gn = tgn;
471 	    }
472 
473 	    (void) Lst_AtEnd (pgn->children, gn);
474 	    (void) Lst_AtEnd (gn->parents, pgn);
475 	    pgn->unmade += 1;
476 	}
477 	Lst_Close (cgn->children);
478     }
479 
480     pgn->type |= cgn->type & ~(OP_OPMASK|OP_USE|OP_USEBEFORE|OP_TRANSFORM);
481 }
482 
483 /*-
484  *-----------------------------------------------------------------------
485  * MakeHandleUse --
486  *	Callback function for Lst_ForEach, used by Make_Run on the downward
487  *	pass to handle .USE nodes. Should be called before the children
488  *	are enqueued to be looked at by MakeAddChild.
489  *	This function calls Make_HandleUse to copy the .USE node's commands,
490  *	type flags and children to the parent node.
491  *
492  * Input:
493  *	cgnp		the child we've just examined
494  *	pgnp		the current parent
495  *
496  * Results:
497  *	returns 0.
498  *
499  * Side Effects:
500  *	After expansion, .USE child nodes are removed from the parent
501  *
502  *-----------------------------------------------------------------------
503  */
504 static int
505 MakeHandleUse(ClientData cgnp, ClientData pgnp)
506 {
507     GNode	*cgn = (GNode *) cgnp;
508     GNode	*pgn = (GNode *) pgnp;
509     LstNode	ln; 	/* An element in the children list */
510     int		unmarked;
511 
512     unmarked = ((cgn->type & OP_MARK) == 0);
513     cgn->type |= OP_MARK;
514 
515     if ((cgn->type & (OP_USE|OP_USEBEFORE)) == 0)
516 	return (0);
517 
518     if (unmarked)
519 	Make_HandleUse(cgn, pgn);
520 
521     /*
522      * This child node is now "made", so we decrement the count of
523      * unmade children in the parent... We also remove the child
524      * from the parent's list to accurately reflect the number of decent
525      * children the parent has. This is used by Make_Run to decide
526      * whether to queue the parent or examine its children...
527      */
528     if ((ln = Lst_Member (pgn->children, (ClientData) cgn)) != NILLNODE) {
529 	Lst_Remove(pgn->children, ln);
530 	pgn->unmade--;
531     }
532     return (0);
533 }
534 
535 
536 /*-
537  *-----------------------------------------------------------------------
538  * Make_Recheck --
539  *	Check the modification time of a gnode, and update it as described
540  *	in the comments below.
541  *
542  * Results:
543  *	returns 0 if the gnode does not exist, or it's filesystem
544  *	time if it does.
545  *
546  * Side Effects:
547  *	the gnode's modification time and path name are affected.
548  *
549  *-----------------------------------------------------------------------
550  */
551 time_t
552 Make_Recheck(GNode *gn)
553 {
554     time_t mtime = Dir_MTime(gn);
555 
556 #ifndef RECHECK
557     /*
558      * We can't re-stat the thing, but we can at least take care of rules
559      * where a target depends on a source that actually creates the
560      * target, but only if it has changed, e.g.
561      *
562      * parse.h : parse.o
563      *
564      * parse.o : parse.y
565      *  	yacc -d parse.y
566      *  	cc -c y.tab.c
567      *  	mv y.tab.o parse.o
568      *  	cmp -s y.tab.h parse.h || mv y.tab.h parse.h
569      *
570      * In this case, if the definitions produced by yacc haven't changed
571      * from before, parse.h won't have been updated and gn->mtime will
572      * reflect the current modification time for parse.h. This is
573      * something of a kludge, I admit, but it's a useful one..
574      * XXX: People like to use a rule like
575      *
576      * FRC:
577      *
578      * To force things that depend on FRC to be made, so we have to
579      * check for gn->children being empty as well...
580      */
581     if (!Lst_IsEmpty(gn->commands) || Lst_IsEmpty(gn->children)) {
582 	gn->mtime = now;
583     }
584 #else
585     /*
586      * This is what Make does and it's actually a good thing, as it
587      * allows rules like
588      *
589      *	cmp -s y.tab.h parse.h || cp y.tab.h parse.h
590      *
591      * to function as intended. Unfortunately, thanks to the stateless
592      * nature of NFS (by which I mean the loose coupling of two clients
593      * using the same file from a common server), there are times
594      * when the modification time of a file created on a remote
595      * machine will not be modified before the local stat() implied by
596      * the Dir_MTime occurs, thus leading us to believe that the file
597      * is unchanged, wreaking havoc with files that depend on this one.
598      *
599      * I have decided it is better to make too much than to make too
600      * little, so this stuff is commented out unless you're sure it's ok.
601      * -- ardeb 1/12/88
602      */
603     /*
604      * Christos, 4/9/92: If we are  saving commands pretend that
605      * the target is made now. Otherwise archives with ... rules
606      * don't work!
607      */
608     if (NoExecute(gn) ||
609 	(gn->type & OP_SAVE_CMDS) || mtime == 0) {
610 	if (DEBUG(MAKE)) {
611 	    printf(" recheck(%s): update time to now: %s\n",
612 		   gn->name, Targ_FmtTime(gn->mtime));
613 	}
614 	gn->mtime = now;
615     }
616     else {
617 	if (DEBUG(MAKE)) {
618 	    printf(" recheck(%s): current update time: %s\n",
619 		   gn->name, Targ_FmtTime(gn->mtime));
620 	}
621     }
622 #endif
623     return mtime;
624 }
625 
626 /*-
627  *-----------------------------------------------------------------------
628  * Make_Update  --
629  *	Perform update on the parents of a node. Used by JobFinish once
630  *	a node has been dealt with and by MakeStartJobs if it finds an
631  *	up-to-date node.
632  *
633  * Input:
634  *	cgn		the child node
635  *
636  * Results:
637  *	Always returns 0
638  *
639  * Side Effects:
640  *	The unmade field of pgn is decremented and pgn may be placed on
641  *	the toBeMade queue if this field becomes 0.
642  *
643  * 	If the child was made, the parent's flag CHILDMADE field will be
644  *	set true and its cmtime set to now.
645  *
646  *	If the child is not up-to-date and still does not exist,
647  *	set the FORCE flag on the parents.
648  *
649  *	If the child wasn't made, the cmtime field of the parent will be
650  *	altered if the child's mtime is big enough.
651  *
652  *	Finally, if the child is the implied source for the parent, the
653  *	parent's IMPSRC variable is set appropriately.
654  *
655  *-----------------------------------------------------------------------
656  */
657 void
658 Make_Update(GNode *cgn)
659 {
660     GNode 	*pgn;	/* the parent node */
661     char  	*cname;	/* the child's name */
662     LstNode	ln; 	/* Element in parents and iParents lists */
663     time_t	mtime = -1;
664     char	*p1;
665     Lst		parents;
666     GNode	*centurion;
667 
668     cname = Var_Value (TARGET, cgn, &p1);
669     if (p1)
670 	free(p1);
671 
672     /*
673      * If the child was actually made, see what its modification time is
674      * now -- some rules won't actually update the file. If the file still
675      * doesn't exist, make its mtime now.
676      */
677     if (cgn->made != UPTODATE) {
678 	mtime = Make_Recheck(cgn);
679     }
680 
681     /*
682      * If this is a `::' node, we must consult its first instance
683      * which is where all parents are linked.
684      */
685     if ((centurion = cgn->centurion) != NULL) {
686 	if (!Lst_IsEmpty(cgn->parents))
687 		Punt("%s: cohort has parents", cgn->name);
688 	centurion->unmade_cohorts -= 1;
689 	if (centurion->unmade_cohorts < 0)
690 	    Error ("Graph cycles through centurion %s", centurion->name);
691 	parents = centurion->parents;
692     } else {
693 	centurion = cgn;
694 	parents = cgn->parents;
695     }
696     if (Lst_Open (parents) == SUCCESS) {
697 	while ((ln = Lst_Next (parents)) != NILLNODE) {
698 	    pgn = (GNode *)Lst_Datum (ln);
699 	    if (mtime == 0)
700 		pgn->flags |= FORCE;
701 	    /*
702 	     * If the parent has the .MADE attribute, it has already
703 	     * been queued on the `toBeMade' list in Make_ExpandUse()
704 	     * and its unmade children counter is zero.
705 	     */
706 	    if ((pgn->flags & REMAKE) == 0 || (pgn->type & OP_MADE) != 0)
707 		continue;
708 
709 	    if ( ! (cgn->type & (OP_EXEC|OP_USE|OP_USEBEFORE))) {
710 		if (cgn->made == MADE)
711 		    pgn->flags |= CHILDMADE;
712 		(void)Make_TimeStamp (pgn, cgn);
713 	    }
714 
715 	    /*
716 	     * A parent must wait for the completion of all instances
717 	     * of a `::' dependency.
718 	     */
719 	    if (centurion->unmade_cohorts != 0 || centurion->made == UNMADE)
720 		continue;
721 
722 	    /* One more child of this parent is now made */
723 	    pgn->unmade -= 1;
724 	    if (pgn->unmade == 0) {
725 		/*
726 		 * Queue the node up -- any unmade predecessors will
727 		 * be dealt with in MakeStartJobs.
728 		 */
729 		(void)Lst_EnQueue (toBeMade, (ClientData)pgn);
730 	    } else if (pgn->unmade < 0) {
731 		Error ("Graph cycles through %s", pgn->name);
732 	    }
733 	}
734 	Lst_Close (parents);
735     }
736     /*
737      * Deal with successor nodes. If any is marked for making and has an unmade
738      * count of 0, has not been made and isn't in the examination queue,
739      * it means we need to place it in the queue as it restrained itself
740      * before.
741      */
742     for (ln = Lst_First(centurion->successors); ln != NILLNODE;
743 	 ln = Lst_Succ(ln)) {
744 	GNode	*succ = (GNode *)Lst_Datum(ln);
745 
746 	if ((succ->flags & REMAKE) != 0 && succ->unmade == 0 &&
747 	    succ->made == UNMADE &&
748 	    Lst_Member(toBeMade, (ClientData)succ) == NILLNODE)
749 	{
750 	    (void)Lst_EnQueue(toBeMade, (ClientData)succ);
751 	}
752     }
753 
754     /*
755      * Set the .PREFIX and .IMPSRC variables for all the implied parents
756      * of this node.
757      */
758     if (Lst_Open (cgn->iParents) == SUCCESS) {
759 	char	*cpref = Var_Value(PREFIX, cgn, &p1);
760 
761 	while ((ln = Lst_Next (cgn->iParents)) != NILLNODE) {
762 	    pgn = (GNode *)Lst_Datum (ln);
763 	    if (pgn->flags & REMAKE) {
764 		Var_Set (IMPSRC, cname, pgn, 0);
765 		if (cpref != NULL)
766 		    Var_Set (PREFIX, cpref, pgn, 0);
767 	    }
768 	}
769 	if (p1)
770 	    free(p1);
771 	Lst_Close (cgn->iParents);
772     }
773 }
774 
775 /*-
776  *-----------------------------------------------------------------------
777  * MakeAddAllSrc --
778  *	Add a child's name to the ALLSRC and OODATE variables of the given
779  *	node. Called from Make_DoAllVar via Lst_ForEach. A child is added only
780  *	if it has not been given the .EXEC, .USE or .INVISIBLE attributes.
781  *	.EXEC and .USE children are very rarely going to be files, so...
782  *	If the child is a .JOIN node, its ALLSRC is propagated to the parent.
783  *
784  *	A child is added to the OODATE variable if its modification time is
785  *	later than that of its parent, as defined by Make, except if the
786  *	parent is a .JOIN node. In that case, it is only added to the OODATE
787  *	variable if it was actually made (since .JOIN nodes don't have
788  *	modification times, the comparison is rather unfair...)..
789  *
790  * Results:
791  *	Always returns 0
792  *
793  * Side Effects:
794  *	The ALLSRC variable for the given node is extended.
795  *-----------------------------------------------------------------------
796  */
797 static int
798 MakeUnmark(ClientData cgnp, ClientData pgnp __unused)
799 {
800     GNode	*cgn = (GNode *) cgnp;
801 
802     cgn->type &= ~OP_MARK;
803     return (0);
804 }
805 
806 /*
807  * Input:
808  *	cgnp		The child to add
809  *	pgnp		The parent to whose ALLSRC variable it should
810  *			be added
811  *
812  */
813 static int
814 MakeAddAllSrc(ClientData cgnp, ClientData pgnp)
815 {
816     GNode	*cgn = (GNode *) cgnp;
817     GNode	*pgn = (GNode *) pgnp;
818 
819     if (cgn->type & OP_MARK)
820 	return (0);
821     cgn->type |= OP_MARK;
822 
823     if ((cgn->type & (OP_EXEC|OP_USE|OP_USEBEFORE|OP_INVISIBLE)) == 0) {
824 	char *child, *allsrc;
825 	char *p1 = NULL, *p2 = NULL;
826 
827 	if (cgn->type & OP_ARCHV)
828 	    child = Var_Value (MEMBER, cgn, &p1);
829 	else
830 	    child = cgn->path ? cgn->path : cgn->name;
831 	if (cgn->type & OP_JOIN) {
832 	    allsrc = Var_Value (ALLSRC, cgn, &p2);
833 	} else {
834 	    allsrc = child;
835 	}
836 	if (allsrc != NULL)
837 		Var_Append (ALLSRC, allsrc, pgn);
838 	if (p2)
839 	    free(p2);
840 	if (pgn->type & OP_JOIN) {
841 	    if (cgn->made == MADE) {
842 		Var_Append(OODATE, child, pgn);
843 	    }
844 	} else if ((pgn->mtime < cgn->mtime) ||
845 		   (cgn->mtime >= now && cgn->made == MADE))
846 	{
847 	    /*
848 	     * It goes in the OODATE variable if the parent is younger than the
849 	     * child or if the child has been modified more recently than
850 	     * the start of the make. This is to keep pmake from getting
851 	     * confused if something else updates the parent after the
852 	     * make starts (shouldn't happen, I know, but sometimes it
853 	     * does). In such a case, if we've updated the kid, the parent
854 	     * is likely to have a modification time later than that of
855 	     * the kid and anything that relies on the OODATE variable will
856 	     * be hosed.
857 	     *
858 	     * XXX: This will cause all made children to go in the OODATE
859 	     * variable, even if they're not touched, if RECHECK isn't defined,
860 	     * since cgn->mtime is set to now in Make_Update. According to
861 	     * some people, this is good...
862 	     */
863 	    Var_Append(OODATE, child, pgn);
864 	}
865 	if (p1)
866 	    free(p1);
867     }
868     return (0);
869 }
870 
871 /*-
872  *-----------------------------------------------------------------------
873  * Make_DoAllVar --
874  *	Set up the ALLSRC and OODATE variables. Sad to say, it must be
875  *	done separately, rather than while traversing the graph. This is
876  *	because Make defined OODATE to contain all sources whose modification
877  *	times were later than that of the target, *not* those sources that
878  *	were out-of-date. Since in both compatibility and native modes,
879  *	the modification time of the parent isn't found until the child
880  *	has been dealt with, we have to wait until now to fill in the
881  *	variable. As for ALLSRC, the ordering is important and not
882  *	guaranteed when in native mode, so it must be set here, too.
883  *
884  * Results:
885  *	None
886  *
887  * Side Effects:
888  *	The ALLSRC and OODATE variables of the given node is filled in.
889  *	If the node is a .JOIN node, its TARGET variable will be set to
890  * 	match its ALLSRC variable.
891  *-----------------------------------------------------------------------
892  */
893 void
894 Make_DoAllVar(GNode *gn)
895 {
896     Lst_ForEach (gn->children, MakeUnmark, (ClientData) gn);
897     Lst_ForEach (gn->children, MakeAddAllSrc, (ClientData) gn);
898 
899     if (!Var_Exists (OODATE, gn)) {
900 	Var_Set (OODATE, "", gn, 0);
901     }
902     if (!Var_Exists (ALLSRC, gn)) {
903 	Var_Set (ALLSRC, "", gn, 0);
904     }
905 
906     if (gn->type & OP_JOIN) {
907 	char *p1;
908 	Var_Set (TARGET, Var_Value (ALLSRC, gn, &p1), gn, 0);
909 	if (p1)
910 	    free(p1);
911     }
912 }
913 
914 /*-
915  *-----------------------------------------------------------------------
916  * MakeStartJobs --
917  *	Start as many jobs as possible.
918  *
919  * Results:
920  *	If the query flag was given to pmake, no job will be started,
921  *	but as soon as an out-of-date target is found, this function
922  *	returns TRUE. At all other times, this function returns FALSE.
923  *
924  * Side Effects:
925  *	Nodes are removed from the toBeMade queue and job table slots
926  *	are filled.
927  *
928  *-----------------------------------------------------------------------
929  */
930 static Boolean
931 MakeStartJobs(void)
932 {
933     GNode	*gn;
934 
935     while (!Lst_IsEmpty (toBeMade)) {
936 	gn = (GNode *) Lst_DeQueue (toBeMade);
937 	if (DEBUG(MAKE)) {
938 	    printf ("Examining %s...", gn->name);
939 	}
940 	/*
941 	 * Make sure any and all predecessors that are going to be made,
942 	 * have been.
943 	 */
944 	if (!Lst_IsEmpty(gn->preds)) {
945 	    LstNode ln;
946 
947 	    for (ln = Lst_First(gn->preds); ln != NILLNODE; ln = Lst_Succ(ln)){
948 		GNode	*pgn = (GNode *)Lst_Datum(ln);
949 
950 		if ((pgn->flags & REMAKE) &&
951 		    (pgn->made == UNMADE || pgn->unmade_cohorts != 0)) {
952 		    if (DEBUG(MAKE)) {
953 			printf("predecessor %s not made yet.\n", pgn->name);
954 		    }
955 		    break;
956 		}
957 	    }
958 	    /*
959 	     * If ln isn't nil, there's a predecessor as yet unmade, so we
960 	     * just drop this node on the floor. When the node in question
961 	     * has been made, it will notice this node as being ready to
962 	     * make but as yet unmade and will place the node on the queue.
963 	     */
964 	    if (ln != NILLNODE) {
965 		continue;
966 	    }
967 	}
968 
969 	if (!Job_TokenWithdraw()) {
970 	    Lst_AtFront(toBeMade, gn);
971 	    break;
972 	}
973 
974 	numNodes--;
975 	if (Make_OODate (gn)) {
976 	    if (DEBUG(MAKE)) {
977 		printf ("out-of-date\n");
978 	    }
979 	    if (queryFlag) {
980 		return (TRUE);
981 	    }
982 	    Make_DoAllVar (gn);
983 	    Job_Make (gn);
984 	} else {
985 	    if (DEBUG(MAKE)) {
986 		printf ("up-to-date\n");
987 	    }
988 	    gn->made = UPTODATE;
989 	    if (gn->type & OP_JOIN) {
990 		/*
991 		 * Even for an up-to-date .JOIN node, we need it to have its
992 		 * context variables so references to it get the correct
993 		 * value for .TARGET when building up the context variables
994 		 * of its parent(s)...
995 		 */
996 		Make_DoAllVar (gn);
997 	    }
998 	    Job_TokenReturn();
999 	    Make_Update (gn);
1000 	}
1001     }
1002     return (FALSE);
1003 }
1004 
1005 /*-
1006  *-----------------------------------------------------------------------
1007  * MakePrintStatus --
1008  *	Print the status of a top-level node, viz. it being up-to-date
1009  *	already or not created due to an error in a lower level.
1010  *	Callback function for Make_Run via Lst_ForEach.
1011  *
1012  * Input:
1013  *	gnp		Node to examine
1014  *	cyclep		True if gn->unmade being non-zero implies a
1015  *			cycle in the graph, not an error in an
1016  *			inferior.
1017  *
1018  * Results:
1019  *	Always returns 0.
1020  *
1021  * Side Effects:
1022  *	A message may be printed.
1023  *
1024  *-----------------------------------------------------------------------
1025  */
1026 static int
1027 MakePrintStatus(ClientData gnp, ClientData cyclep)
1028 {
1029     GNode   	*gn = (GNode *) gnp;
1030     Boolean 	cycle = *(Boolean *) cyclep;
1031     if (gn->made == UPTODATE) {
1032 	printf ("`%s' is up to date.\n", gn->name);
1033     } else if (gn->unmade != 0) {
1034 	if (cycle) {
1035 	    Boolean t = TRUE;
1036 	    /*
1037 	     * If printing cycles and came to one that has unmade children,
1038 	     * print out the cycle by recursing on its children. Note a
1039 	     * cycle like:
1040 	     *	a : b
1041 	     *	b : c
1042 	     *	c : b
1043 	     * will cause this to erroneously complain about a being in
1044 	     * the cycle, but this is a good approximation.
1045 	     */
1046 	    if (gn->made == CYCLE) {
1047 		Error("Graph cycles through `%s'", gn->name);
1048 		gn->made = ENDCYCLE;
1049 		Lst_ForEach(gn->children, MakePrintStatus, (ClientData) &t);
1050 		gn->made = UNMADE;
1051 	    } else if (gn->made != ENDCYCLE) {
1052 		gn->made = CYCLE;
1053 		Lst_ForEach(gn->children, MakePrintStatus, (ClientData) &t);
1054 	    }
1055 	} else {
1056 	    printf ("`%s' not remade because of errors.\n", gn->name);
1057 	}
1058     }
1059     return (0);
1060 }
1061 
1062 
1063 /*-
1064  *-----------------------------------------------------------------------
1065  * Make_ExpandUse --
1066  *	Expand .USE nodes and create a new targets list
1067  *
1068  * Input:
1069  *	targs		the initial list of targets
1070  *
1071  * Results:
1072  *	The new list of targets.
1073  *
1074  * Side Effects:
1075  *	numNodes is set to the number of elements in the list of targets.
1076  *-----------------------------------------------------------------------
1077  */
1078 Lst
1079 Make_ExpandUse(Lst targs)
1080 {
1081     GNode  *gn;		/* a temporary pointer */
1082     Lst    examine; 	/* List of targets to examine */
1083     Lst    ntargs;	/* List of new targets to be made */
1084 
1085     ntargs = Lst_Init (FALSE);
1086 
1087     examine = Lst_Duplicate(targs, NOCOPY);
1088     numNodes = 0;
1089 
1090     /*
1091      * Make an initial downward pass over the graph, marking nodes to be made
1092      * as we go down. We call Suff_FindDeps to find where a node is and
1093      * to get some children for it if it has none and also has no commands.
1094      * If the node is a leaf, we stick it on the toBeMade queue to
1095      * be looked at in a minute, otherwise we add its children to our queue
1096      * and go on about our business.
1097      */
1098     while (!Lst_IsEmpty (examine)) {
1099 	gn = (GNode *) Lst_DeQueue (examine);
1100 
1101 	if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts)) {
1102 	    Lst new;
1103 	    new = Lst_Duplicate (gn->cohorts, NOCOPY);
1104 	    Lst_Concat (new, examine, LST_CONCLINK);
1105 	    examine = new;
1106 	}
1107 
1108 	if ((gn->flags & REMAKE) == 0) {
1109 	    gn->flags |= REMAKE;
1110 	    numNodes++;
1111 
1112 	    /*
1113 	     * Apply any .USE rules before looking for implicit dependencies
1114 	     * to make sure everything has commands that should...
1115 	     * Make sure that the TARGET is set, so that we can make
1116 	     * expansions.
1117 	     */
1118 	    if (gn->type & OP_ARCHV) {
1119 		char *eoa, *eon;
1120 		eoa = strchr(gn->name, '(');
1121 		eon = strchr(gn->name, ')');
1122 		if (eoa == NULL || eon == NULL)
1123 		    continue;
1124 		*eoa = '\0';
1125 		*eon = '\0';
1126 		Var_Set (MEMBER, eoa + 1, gn, 0);
1127 		Var_Set (ARCHIVE, gn->name, gn, 0);
1128 		*eoa = '(';
1129 		*eon = ')';
1130 	    }
1131 
1132 	    (void)Dir_MTime(gn);
1133 	    Var_Set (TARGET, gn->path ? gn->path : gn->name, gn, 0);
1134 	    Lst_ForEach (gn->children, MakeUnmark, (ClientData)gn);
1135 	    Lst_ForEach (gn->children, MakeHandleUse, (ClientData)gn);
1136 
1137 	    if ((gn->type & OP_MADE) == 0)
1138 		Suff_FindDeps (gn);
1139 	    else {
1140 		/* Pretend we made all this node's children */
1141 		Lst_ForEach (gn->children, MakeFindChild, (ClientData)gn);
1142 		if (gn->unmade != 0)
1143 			printf("Warning: %s still has %d unmade children\n",
1144 				gn->name, gn->unmade);
1145 	    }
1146 
1147 	    if (gn->unmade != 0) {
1148 		Lst_ForEach (gn->children, MakeAddChild, (ClientData)examine);
1149 	    } else {
1150 		(void)Lst_EnQueue (ntargs, (ClientData)gn);
1151 	    }
1152 	}
1153     }
1154 
1155     Lst_Destroy (examine, NOFREE);
1156     return ntargs;
1157 }
1158 
1159 /*-
1160  *-----------------------------------------------------------------------
1161  * Make_Run --
1162  *	Initialize the nodes to remake and the list of nodes which are
1163  *	ready to be made by doing a breadth-first traversal of the graph
1164  *	starting from the nodes in the given list. Once this traversal
1165  *	is finished, all the 'leaves' of the graph are in the toBeMade
1166  *	queue.
1167  *	Using this queue and the Job module, work back up the graph,
1168  *	calling on MakeStartJobs to keep the job table as full as
1169  *	possible.
1170  *
1171  * Input:
1172  *	targs		the initial list of targets
1173  *
1174  * Results:
1175  *	TRUE if work was done. FALSE otherwise.
1176  *
1177  * Side Effects:
1178  *	The make field of all nodes involved in the creation of the given
1179  *	targets is set to 1. The toBeMade list is set to contain all the
1180  *	'leaves' of these subgraphs.
1181  *-----------------------------------------------------------------------
1182  */
1183 Boolean
1184 Make_Run(Lst targs)
1185 {
1186     int	    	    errors; 	/* Number of errors the Job module reports */
1187 
1188     toBeMade = Make_ExpandUse (targs);
1189 
1190     if (queryFlag) {
1191 	/*
1192 	 * We wouldn't do any work unless we could start some jobs in the
1193 	 * next loop... (we won't actually start any, of course, this is just
1194 	 * to see if any of the targets was out of date)
1195 	 */
1196 	return (MakeStartJobs());
1197     } else {
1198 	/*
1199 	 * Initialization. At the moment, no jobs are running and until some
1200 	 * get started, nothing will happen since the remaining upward
1201 	 * traversal of the graph is performed by the routines in job.c upon
1202 	 * the finishing of a job. So we fill the Job table as much as we can
1203 	 * before going into our loop.
1204 	 */
1205 	(void) MakeStartJobs();
1206     }
1207 
1208     /*
1209      * Main Loop: The idea here is that the ending of jobs will take
1210      * care of the maintenance of data structures and the waiting for output
1211      * will cause us to be idle most of the time while our children run as
1212      * much as possible. Because the job table is kept as full as possible,
1213      * the only time when it will be empty is when all the jobs which need
1214      * running have been run, so that is the end condition of this loop.
1215      * Note that the Job module will exit if there were any errors unless the
1216      * keepgoing flag was given.
1217      */
1218     while (!Lst_IsEmpty(toBeMade) || !Job_Empty ()) {
1219 	Job_CatchOutput ();
1220 	Job_CatchChildren (!usePipes);
1221 	(void)MakeStartJobs();
1222     }
1223 
1224     errors = Job_Finish();
1225 
1226     /*
1227      * Print the final status of each target. E.g. if it wasn't made
1228      * because some inferior reported an error.
1229      */
1230     errors = ((errors == 0) && (numNodes != 0));
1231     Lst_ForEach(targs, MakePrintStatus, (ClientData) &errors);
1232 
1233     return (TRUE);
1234 }
1235