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