xref: /netbsd-src/usr.bin/make/suff.c (revision 4d342c046e3288fb5a1edcd33cfec48c41c80664)
1 /*	$NetBSD: suff.c,v 1.156 2020/09/13 18:27:39 rillig Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * Copyright (c) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *	This product includes software developed by the University of
53  *	California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 /*-
72  * suff.c --
73  *	Functions to maintain suffix lists and find implicit dependents
74  *	using suffix transformation rules
75  *
76  * Interface:
77  *	Suff_Init 	    	Initialize all things to do with suffixes.
78  *
79  *	Suff_End 	    	Cleanup the module
80  *
81  *	Suff_DoPaths	    	This function is used to make life easier
82  *	    	  	    	when searching for a file according to its
83  *	    	  	    	suffix. It takes the global search path,
84  *	    	  	    	as defined using the .PATH: target, and appends
85  *	    	  	    	its directories to the path of each of the
86  *	    	  	    	defined suffixes, as specified using
87  *	    	  	    	.PATH<suffix>: targets. In addition, all
88  *	    	  	    	directories given for suffixes labeled as
89  *	    	  	    	include files or libraries, using the .INCLUDES
90  *	    	  	    	or .LIBS targets, are played with using
91  *	    	  	    	Dir_MakeFlags to create the .INCLUDES and
92  *	    	  	    	.LIBS global variables.
93  *
94  *	Suff_ClearSuffixes  	Clear out all the suffixes and defined
95  *	    	  	    	transformations.
96  *
97  *	Suff_IsTransform    	Return TRUE if the passed string is the lhs
98  *	    	  	    	of a transformation rule.
99  *
100  *	Suff_AddSuffix	    	Add the passed string as another known suffix.
101  *
102  *	Suff_GetPath	    	Return the search path for the given suffix.
103  *
104  *	Suff_AddInclude	    	Mark the given suffix as denoting an include
105  *	    	  	    	file.
106  *
107  *	Suff_AddLib	    	Mark the given suffix as denoting a library.
108  *
109  *	Suff_AddTransform   	Add another transformation to the suffix
110  *	    	  	    	graph. Returns  GNode suitable for framing, I
111  *	    	  	    	mean, tacking commands, attributes, etc. on.
112  *
113  *	Suff_SetNull	    	Define the suffix to consider the suffix of
114  *	    	  	    	any file that doesn't have a known one.
115  *
116  *	Suff_FindDeps	    	Find implicit sources for and the location of
117  *	    	  	    	a target based on its suffix. Returns the
118  *	    	  	    	bottom-most node added to the graph or NULL
119  *	    	  	    	if the target had no implicit sources.
120  *
121  *	Suff_FindPath	    	Return the appropriate path to search in
122  *				order to find the node.
123  */
124 
125 #include	  "make.h"
126 #include	  "dir.h"
127 
128 /*	"@(#)suff.c	8.4 (Berkeley) 3/21/94"	*/
129 MAKE_RCSID("$NetBSD: suff.c,v 1.156 2020/09/13 18:27:39 rillig Exp $");
130 
131 #define SUFF_DEBUG0(fmt) \
132     if (!DEBUG(SUFF)) (void) 0; else fprintf(debug_file, fmt)
133 
134 #define SUFF_DEBUG1(fmt, arg1) \
135     if (!DEBUG(SUFF)) (void) 0; else fprintf(debug_file, fmt, arg1)
136 
137 #define SUFF_DEBUG2(fmt, arg1, arg2) \
138     if (!DEBUG(SUFF)) (void) 0; else fprintf(debug_file, fmt, arg1, arg2)
139 
140 #define SUFF_DEBUG3(fmt, arg1, arg2, arg3) \
141     if (!DEBUG(SUFF)) (void) 0; else fprintf(debug_file, fmt, arg1, arg2, arg3)
142 
143 static Lst       sufflist;	/* Lst of suffixes */
144 #ifdef CLEANUP
145 static Lst	 suffClean;	/* Lst of suffixes to be cleaned */
146 #endif
147 static Lst	 srclist;	/* Lst of sources */
148 static Lst       transforms;	/* Lst of transformation rules */
149 
150 static int        sNum = 0;	/* Counter for assigning suffix numbers */
151 
152 typedef enum {
153     SUFF_INCLUDE	= 0x01,	/* One which is #include'd */
154     SUFF_LIBRARY	= 0x02,	/* One which contains a library */
155     SUFF_NULL		= 0x04	/* The empty suffix */
156     /* XXX: Why is SUFF_NULL needed? Wouldn't nameLen == 0 mean the same? */
157 } SuffFlags;
158 
159 ENUM_FLAGS_RTTI_3(SuffFlags,
160 		  SUFF_INCLUDE, SUFF_LIBRARY, SUFF_NULL);
161 
162 /*
163  * Structure describing an individual suffix.
164  */
165 typedef struct Suff {
166     char         *name;	    	/* The suffix itself, such as ".c" */
167     int		 nameLen;	/* Length of the name, to avoid strlen calls */
168     SuffFlags	 flags;      	/* Type of suffix */
169     Lst    	 searchPath;	/* The path along which files of this suffix
170 				 * may be found */
171     int          sNum;	      	/* The suffix number */
172     int		 refCount;	/* Reference count of list membership */
173     Lst          parents;	/* Suffixes we have a transformation to */
174     Lst          children;	/* Suffixes we have a transformation from */
175     Lst		 ref;		/* List of lists this suffix is referenced */
176 } Suff;
177 
178 /*
179  * Structure used in the search for implied sources.
180  */
181 typedef struct _Src {
182     char            *file;	/* The file to look for */
183     char    	    *pref;  	/* Prefix from which file was formed */
184     Suff            *suff;	/* The suffix on the file */
185     struct _Src     *parent;	/* The Src for which this is a source */
186     GNode           *node;	/* The node describing the file */
187     int	    	    children;	/* Count of existing children (so we don't free
188 				 * this thing too early or never nuke it) */
189 #ifdef DEBUG_SRC
190     Lst		    cp;		/* Debug; children list */
191 #endif
192 } Src;
193 
194 /*
195  * A structure for passing more than one argument to the Lst-library-invoked
196  * function...
197  */
198 typedef struct {
199     Lst            l;
200     Src            *s;
201 } LstSrc;
202 
203 typedef struct {
204     GNode	  **gnp;
205     Suff	   *s;
206     Boolean	    r;
207 } GNodeSuff;
208 
209 static Suff 	    *suffNull;	/* The NULL suffix for this run */
210 static Suff 	    *emptySuff;	/* The empty suffix required for POSIX
211 				 * single-suffix transformation rules */
212 
213 
214 static void SuffUnRef(void *, void *);
215 static void SuffFree(void *);
216 static void SuffInsert(Lst, Suff *);
217 static void SuffRemove(Lst, Suff *);
218 static Boolean SuffParseTransform(char *, Suff **, Suff **);
219 static int SuffRebuildGraph(void *, void *);
220 static int SuffScanTargets(void *, void *);
221 static int SuffAddSrc(void *, void *);
222 static void SuffAddLevel(Lst, Src *);
223 static void SuffExpandChildren(LstNode, GNode *);
224 static void SuffExpandWildcards(LstNode, GNode *);
225 static Boolean SuffApplyTransform(GNode *, GNode *, Suff *, Suff *);
226 static void SuffFindDeps(GNode *, Lst);
227 static void SuffFindArchiveDeps(GNode *, Lst);
228 static void SuffFindNormalDeps(GNode *, Lst);
229 static int SuffPrintName(void *, void *);
230 static int SuffPrintSuff(void *, void *);
231 static int SuffPrintTrans(void *, void *);
232 
233 	/*************** Lst Predicates ****************/
234 /*-
235  *-----------------------------------------------------------------------
236  * SuffStrIsPrefix  --
237  *	See if pref is a prefix of str.
238  *
239  * Input:
240  *	pref		possible prefix
241  *	str		string to check
242  *
243  * Results:
244  *	NULL if it ain't, pointer to character in str after prefix if so
245  *
246  * Side Effects:
247  *	None
248  *-----------------------------------------------------------------------
249  */
250 static const char *
251 SuffStrIsPrefix(const char *pref, const char *str)
252 {
253     while (*str && *pref == *str) {
254 	pref++;
255 	str++;
256     }
257 
258     return *pref ? NULL : str;
259 }
260 
261 typedef struct {
262     char	*ename;		/* The end of the name */
263     int		 len;		/* Length of the name */
264 } SuffSuffGetSuffixArgs;
265 
266 /* See if suff is a suffix of str. str->ename should point to THE END
267  * of the string to check. (THE END == the null byte)
268  *
269  * Input:
270  *	s		possible suffix
271  *	str		string to examine
272  *
273  * Results:
274  *	NULL if it ain't, pointer to character in str before suffix if
275  *	it is.
276  */
277 static char *
278 SuffSuffGetSuffix(const Suff *s, const SuffSuffGetSuffixArgs *str)
279 {
280     char  *p1;	    	/* Pointer into suffix name */
281     char  *p2;	    	/* Pointer into string being examined */
282 
283     if (str->len < s->nameLen)
284 	return NULL;		/* this string is shorter than the suffix */
285 
286     p1 = s->name + s->nameLen;
287     p2 = str->ename;
288 
289     while (p1 >= s->name && *p1 == *p2) {
290 	p1--;
291 	p2--;
292     }
293 
294     return p1 == s->name - 1 ? p2 : NULL;
295 }
296 
297 /* Predicate form of SuffSuffGetSuffix, for Lst_Find. */
298 static Boolean
299 SuffSuffIsSuffix(const void *s, const void *sd)
300 {
301     return SuffSuffGetSuffix(s, sd) != NULL;
302 }
303 
304 /* See if the suffix has the desired name. */
305 static Boolean
306 SuffSuffHasName(const void *s, const void *desiredName)
307 {
308     return strcmp(((const Suff *)s)->name, desiredName) == 0;
309 }
310 
311 /* See if the suffix name is a prefix of the string. Care must be taken when
312  * using this to search for transformations and what-not, since there could
313  * well be two suffixes, one of which is a prefix of the other... */
314 static Boolean
315 SuffSuffIsPrefix(const void *s, const void *str)
316 {
317     return SuffStrIsPrefix(((const Suff *)s)->name, str) != NULL;
318 }
319 
320 /* See if the graph node has the desired name. */
321 static Boolean
322 SuffGNHasName(const void *gn, const void *desiredName)
323 {
324     return strcmp(((const GNode *)gn)->name, desiredName) == 0;
325 }
326 
327 	    /*********** Maintenance Functions ************/
328 
329 static void
330 SuffUnRef(void *lp, void *sp)
331 {
332     Lst l = (Lst) lp;
333 
334     LstNode ln = Lst_FindDatum(l, sp);
335     if (ln != NULL) {
336 	Lst_Remove(l, ln);
337 	((Suff *)sp)->refCount--;
338     }
339 }
340 
341 /* Free up all memory associated with the given suffix structure. */
342 static void
343 SuffFree(void *sp)
344 {
345     Suff *s = (Suff *)sp;
346 
347     if (s == suffNull)
348 	suffNull = NULL;
349 
350     if (s == emptySuff)
351 	emptySuff = NULL;
352 
353 #ifdef notdef
354     /* We don't delete suffixes in order, so we cannot use this */
355     if (s->refCount)
356 	Punt("Internal error deleting suffix `%s' with refcount = %d", s->name,
357 	    s->refCount);
358 #endif
359 
360     Lst_Free(s->ref);
361     Lst_Free(s->children);
362     Lst_Free(s->parents);
363     Lst_Destroy(s->searchPath, Dir_Destroy);
364 
365     free(s->name);
366     free(s);
367 }
368 
369 /* Remove the suffix from the list, and free if it is otherwise unused. */
370 static void
371 SuffRemove(Lst l, Suff *s)
372 {
373     SuffUnRef(l, s);
374     if (s->refCount == 0) {
375 	SuffUnRef(sufflist, s);
376 	SuffFree(s);
377     }
378 }
379 
380 /* Insert the suffix into the list keeping the list ordered by suffix numbers.
381  *
382  * Input:
383  *	l		the list where in s should be inserted
384  *	s		the suffix to insert
385  */
386 static void
387 SuffInsert(Lst l, Suff *s)
388 {
389     LstNode 	  ln;		/* current element in l we're examining */
390     Suff          *s2 = NULL;	/* the suffix descriptor in this element */
391 
392     Lst_Open(l);
393     while ((ln = Lst_Next(l)) != NULL) {
394 	s2 = LstNode_Datum(ln);
395 	if (s2->sNum >= s->sNum) {
396 	    break;
397 	}
398     }
399     Lst_Close(l);
400 
401     SUFF_DEBUG2("inserting %s(%d)...", s->name, s->sNum);
402 
403     if (ln == NULL) {
404 	SUFF_DEBUG0("at end of list\n");
405 	Lst_Append(l, s);
406 	s->refCount++;
407 	Lst_Append(s->ref, l);
408     } else if (s2->sNum != s->sNum) {
409 	SUFF_DEBUG2("before %s(%d)\n", s2->name, s2->sNum);
410 	Lst_InsertBefore(l, ln, s);
411 	s->refCount++;
412 	Lst_Append(s->ref, l);
413     } else {
414 	SUFF_DEBUG0("already there\n");
415     }
416 }
417 
418 static Suff *
419 SuffNew(const char *name)
420 {
421     Suff *s = bmake_malloc(sizeof(Suff));
422 
423     s->name =   	bmake_strdup(name);
424     s->nameLen = 	strlen(s->name);
425     s->searchPath = Lst_Init();
426     s->children = 	Lst_Init();
427     s->parents = 	Lst_Init();
428     s->ref = 	Lst_Init();
429     s->sNum =   	sNum++;
430     s->flags =  	0;
431     s->refCount =	1;
432 
433     return s;
434 }
435 
436 /* This is gross. Nuke the list of suffixes but keep all transformation
437  * rules around. The transformation graph is destroyed in this process, but
438  * we leave the list of rules so when a new graph is formed the rules will
439  * remain. This function is called from the parse module when a .SUFFIXES:\n
440  * line is encountered. */
441 void
442 Suff_ClearSuffixes(void)
443 {
444 #ifdef CLEANUP
445     Lst_MoveAll(suffClean, sufflist);
446 #endif
447     sufflist = Lst_Init();
448     sNum = 0;
449     if (suffNull)
450 	SuffFree(suffNull);
451     emptySuff = suffNull = SuffNew("");
452 
453     Dir_Concat(suffNull->searchPath, dirSearchPath);
454     suffNull->flags =  	    SUFF_NULL;
455 }
456 
457 /* Parse a transformation string to find its two component suffixes.
458  *
459  * Input:
460  *	str		String being parsed
461  *	out_src		Place to store source of trans.
462  *	out_targ	Place to store target of trans.
463  *
464  * Results:
465  *	TRUE if the string is a valid transformation, FALSE otherwise.
466  */
467 static Boolean
468 SuffParseTransform(char *str, Suff **out_src, Suff **out_targ)
469 {
470     LstNode		srcLn;	    /* element in suffix list of trans source*/
471     Suff		*src;	    /* Source of transformation */
472     LstNode		targLn;	    /* element in suffix list of trans target*/
473     char		*str2;	    /* Extra pointer (maybe target suffix) */
474     LstNode 	    	singleLn;   /* element in suffix list of any suffix
475 				     * that exactly matches str */
476     Suff    	    	*single = NULL;/* Source of possible transformation to
477 				     * null suffix */
478 
479     srcLn = NULL;
480     singleLn = NULL;
481 
482     /*
483      * Loop looking first for a suffix that matches the start of the
484      * string and then for one that exactly matches the rest of it. If
485      * we can find two that meet these criteria, we've successfully
486      * parsed the string.
487      */
488     for (;;) {
489 	if (srcLn == NULL) {
490 	    srcLn = Lst_Find(sufflist, SuffSuffIsPrefix, str);
491 	} else {
492 	    srcLn = Lst_FindFrom(sufflist, LstNode_Next(srcLn),
493 				  SuffSuffIsPrefix, str);
494 	}
495 	if (srcLn == NULL) {
496 	    /*
497 	     * Ran out of source suffixes -- no such rule
498 	     */
499 	    if (singleLn != NULL) {
500 		/*
501 		 * Not so fast Mr. Smith! There was a suffix that encompassed
502 		 * the entire string, so we assume it was a transformation
503 		 * to the null suffix (thank you POSIX). We still prefer to
504 		 * find a double rule over a singleton, hence we leave this
505 		 * check until the end.
506 		 *
507 		 * XXX: Use emptySuff over suffNull?
508 		 */
509 		*out_src = single;
510 		*out_targ = suffNull;
511 		return TRUE;
512 	    }
513 	    return FALSE;
514 	}
515 	src = LstNode_Datum(srcLn);
516 	str2 = str + src->nameLen;
517 	if (*str2 == '\0') {
518 	    single = src;
519 	    singleLn = srcLn;
520 	} else {
521 	    targLn = Lst_Find(sufflist, SuffSuffHasName, str2);
522 	    if (targLn != NULL) {
523 		*out_src = src;
524 		*out_targ = LstNode_Datum(targLn);
525 		return TRUE;
526 	    }
527 	}
528     }
529 }
530 
531 /* Return TRUE if the given string is a transformation rule, that is, a
532  * concatenation of two known suffixes. */
533 Boolean
534 Suff_IsTransform(char *str)
535 {
536     Suff    	  *src, *targ;
537 
538     return SuffParseTransform(str, &src, &targ);
539 }
540 
541 /* Add the transformation rule described by the line to the list of rules
542  * and place the transformation itself in the graph.
543  *
544  * The node is placed on the end of the transforms Lst and links are made
545  * between the two suffixes mentioned in the target name.
546 
547  * Input:
548  *	line		name of transformation to add
549  *
550  * Results:
551  *	The node created for the transformation in the transforms list
552  */
553 GNode *
554 Suff_AddTransform(char *line)
555 {
556     GNode         *gn;		/* GNode of transformation rule */
557     Suff          *s,		/* source suffix */
558 		  *t;		/* target suffix */
559     LstNode 	  ln;	    	/* Node for existing transformation */
560     Boolean ok;
561 
562     ln = Lst_Find(transforms, SuffGNHasName, line);
563     if (ln == NULL) {
564 	/*
565 	 * Make a new graph node for the transformation. It will be filled in
566 	 * by the Parse module.
567 	 */
568 	gn = Targ_NewGN(line);
569 	Lst_Append(transforms, gn);
570     } else {
571 	/*
572 	 * New specification for transformation rule. Just nuke the old list
573 	 * of commands so they can be filled in again... We don't actually
574 	 * free the commands themselves, because a given command can be
575 	 * attached to several different transformations.
576 	 */
577 	gn = LstNode_Datum(ln);
578 	Lst_Free(gn->commands);
579 	Lst_Free(gn->children);
580 	gn->commands = Lst_Init();
581 	gn->children = Lst_Init();
582     }
583 
584     gn->type = OP_TRANSFORM;
585 
586     ok = SuffParseTransform(line, &s, &t);
587     assert(ok);
588     (void)ok;
589 
590     /*
591      * link the two together in the proper relationship and order
592      */
593     SUFF_DEBUG2("defining transformation from `%s' to `%s'\n",
594 		s->name, t->name);
595     SuffInsert(t->children, s);
596     SuffInsert(s->parents, t);
597 
598     return gn;
599 }
600 
601 /* Handle the finish of a transformation definition, removing the
602  * transformation from the graph if it has neither commands nor sources.
603  * This is a callback procedure for the Parse module via Lst_ForEach.
604  *
605  * If the node has no commands or children, the children and parents lists
606  * of the affected suffixes are altered.
607  *
608  * Input:
609  *	gn		Node for transformation
610  */
611 void
612 Suff_EndTransform(GNode *gn)
613 {
614     if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(gn->cohorts))
615 	gn = LstNode_Datum(Lst_Last(gn->cohorts));
616     if ((gn->type & OP_TRANSFORM) && Lst_IsEmpty(gn->commands) &&
617 	Lst_IsEmpty(gn->children))
618     {
619 	Suff	*s, *t;
620 
621 	/*
622 	 * SuffParseTransform() may fail for special rules which are not
623 	 * actual transformation rules. (e.g. .DEFAULT)
624 	 */
625 	if (SuffParseTransform(gn->name, &s, &t)) {
626 	    Lst	 p;
627 
628 	    SUFF_DEBUG2("deleting transformation from `%s' to `%s'\n",
629 			s->name, t->name);
630 
631 	    /*
632 	     * Store s->parents because s could be deleted in SuffRemove
633 	     */
634 	    p = s->parents;
635 
636 	    /*
637 	     * Remove the source from the target's children list. We check for a
638 	     * nil return to handle a beanhead saying something like
639 	     *  .c.o .c.o:
640 	     *
641 	     * We'll be called twice when the next target is seen, but .c and .o
642 	     * are only linked once...
643 	     */
644 	    SuffRemove(t->children, s);
645 
646 	    /*
647 	     * Remove the target from the source's parents list
648 	     */
649 	    SuffRemove(p, t);
650 	}
651     } else if (gn->type & OP_TRANSFORM) {
652 	SUFF_DEBUG1("transformation %s complete\n", gn->name);
653     }
654 }
655 
656 /* Called from Suff_AddSuffix via Lst_ForEach to search through the list of
657  * existing transformation rules and rebuild the transformation graph when
658  * it has been destroyed by Suff_ClearSuffixes. If the given rule is a
659  * transformation involving this suffix and another, existing suffix, the
660  * proper relationship is established between the two.
661  *
662  * The appropriate links will be made between this suffix and others if
663  * transformation rules exist for it.
664  *
665  * Input:
666  *	transformp	Transformation to test
667  *	sp		Suffix to rebuild
668  *
669  * Results:
670  *	0, so that Lst_ForEach continues
671  */
672 static int
673 SuffRebuildGraph(void *transformp, void *sp)
674 {
675     GNode   	*transform = (GNode *)transformp;
676     Suff    	*s = (Suff *)sp;
677     char 	*cp;
678     LstNode	ln;
679     Suff  	*s2;
680     SuffSuffGetSuffixArgs sd;
681 
682     /*
683      * First see if it is a transformation from this suffix.
684      */
685     cp = UNCONST(SuffStrIsPrefix(s->name, transform->name));
686     if (cp != NULL) {
687 	ln = Lst_Find(sufflist, SuffSuffHasName, cp);
688 	if (ln != NULL) {
689 	    /*
690 	     * Found target. Link in and return, since it can't be anything
691 	     * else.
692 	     */
693 	    s2 = LstNode_Datum(ln);
694 	    SuffInsert(s2->children, s);
695 	    SuffInsert(s->parents, s2);
696 	    return 0;
697 	}
698     }
699 
700     /*
701      * Not from, maybe to?
702      */
703     sd.len = strlen(transform->name);
704     sd.ename = transform->name + sd.len;
705     cp = SuffSuffGetSuffix(s, &sd);
706     if (cp != NULL) {
707 	/*
708 	 * Null-terminate the source suffix in order to find it.
709 	 */
710 	cp[1] = '\0';
711 	ln = Lst_Find(sufflist, SuffSuffHasName, transform->name);
712 	/*
713 	 * Replace the start of the target suffix
714 	 */
715 	cp[1] = s->name[0];
716 	if (ln != NULL) {
717 	    /*
718 	     * Found it -- establish the proper relationship
719 	     */
720 	    s2 = LstNode_Datum(ln);
721 	    SuffInsert(s->children, s2);
722 	    SuffInsert(s2->parents, s);
723 	}
724     }
725     return 0;
726 }
727 
728 /* Called from Suff_AddSuffix via Lst_ForEach to search through the list of
729  * existing targets and find if any of the existing targets can be turned
730  * into a transformation rule.
731  *
732  * If such a target is found and the target is the current main target, the
733  * main target is set to NULL and the next target examined (if that exists)
734  * becomes the main target.
735  *
736  * Results:
737  *	1 if a new main target has been selected, 0 otherwise.
738  */
739 static int
740 SuffScanTargets(void *targetp, void *gsp)
741 {
742     GNode   	*target = (GNode *)targetp;
743     GNodeSuff	*gs = (GNodeSuff *)gsp;
744     Suff	*s, *t;
745     char 	*ptr;
746 
747     if (*gs->gnp == NULL && gs->r && (target->type & OP_NOTARGET) == 0) {
748 	*gs->gnp = target;
749 	Targ_SetMain(target);
750 	return 1;
751     }
752 
753     if (target->type == OP_TRANSFORM)
754 	return 0;
755 
756     if ((ptr = strstr(target->name, gs->s->name)) == NULL ||
757 	ptr == target->name)
758 	return 0;
759 
760     if (SuffParseTransform(target->name, &s, &t)) {
761 	if (*gs->gnp == target) {
762 	    gs->r = TRUE;
763 	    *gs->gnp = NULL;
764 	    Targ_SetMain(NULL);
765 	}
766 	Lst_Free(target->children);
767 	target->children = Lst_Init();
768 	target->type = OP_TRANSFORM;
769 	/*
770 	 * link the two together in the proper relationship and order
771 	 */
772 	SUFF_DEBUG2("defining transformation from `%s' to `%s'\n",
773 		    s->name, t->name);
774 	SuffInsert(t->children, s);
775 	SuffInsert(s->parents, t);
776     }
777     return 0;
778 }
779 
780 /* Add the suffix to the end of the list of known suffixes.
781  * Should we restructure the suffix graph? Make doesn't...
782  *
783  * A GNode is created for the suffix and a Suff structure is created and
784  * added to the suffixes list unless the suffix was already known.
785  * The mainNode passed can be modified if a target mutated into a
786  * transform and that target happened to be the main target.
787  *
788  * Input:
789  *	name		the name of the suffix to add
790  */
791 void
792 Suff_AddSuffix(const char *name, GNode **gnp)
793 {
794     Suff          *s;	    /* new suffix descriptor */
795     LstNode 	  ln;
796     GNodeSuff	  gs;
797 
798     ln = Lst_Find(sufflist, SuffSuffHasName, name);
799     if (ln == NULL) {
800 	s = SuffNew(name);
801 
802 	Lst_Append(sufflist, s);
803 	/*
804 	 * We also look at our existing targets list to see if adding
805 	 * this suffix will make one of our current targets mutate into
806 	 * a suffix rule. This is ugly, but other makes treat all targets
807 	 * that start with a . as suffix rules.
808 	 */
809 	gs.gnp = gnp;
810 	gs.s  = s;
811 	gs.r  = FALSE;
812 	Lst_ForEach(Targ_List(), SuffScanTargets, &gs);
813 	/*
814 	 * Look for any existing transformations from or to this suffix.
815 	 * XXX: Only do this after a Suff_ClearSuffixes?
816 	 */
817 	Lst_ForEach(transforms, SuffRebuildGraph, s);
818     }
819 }
820 
821 /* Return the search path for the given suffix, or NULL. */
822 Lst
823 Suff_GetPath(char *sname)
824 {
825     LstNode   	  ln;
826     Suff    	  *s;
827 
828     ln = Lst_Find(sufflist, SuffSuffHasName, sname);
829     if (ln == NULL) {
830 	return NULL;
831     } else {
832 	s = LstNode_Datum(ln);
833 	return s->searchPath;
834     }
835 }
836 
837 /* Extend the search paths for all suffixes to include the default search
838  * path.
839  *
840  * The searchPath field of all the suffixes is extended by the directories
841  * in dirSearchPath. If paths were specified for the ".h" suffix, the
842  * directories are stuffed into a global variable called ".INCLUDES" with
843  * each directory preceded by a -I. The same is done for the ".a" suffix,
844  * except the variable is called ".LIBS" and the flag is -L.
845  */
846 void
847 Suff_DoPaths(void)
848 {
849     Suff	   	*s;
850     LstNode  		ln;
851     char		*ptr;
852     Lst	    	    	inIncludes; /* Cumulative .INCLUDES path */
853     Lst	    	    	inLibs;	    /* Cumulative .LIBS path */
854 
855 
856     inIncludes = Lst_Init();
857     inLibs = Lst_Init();
858 
859     Lst_Open(sufflist);
860     while ((ln = Lst_Next(sufflist)) != NULL) {
861 	s = LstNode_Datum(ln);
862 	if (!Lst_IsEmpty(s->searchPath)) {
863 #ifdef INCLUDES
864 	    if (s->flags & SUFF_INCLUDE) {
865 		Dir_Concat(inIncludes, s->searchPath);
866 	    }
867 #endif
868 #ifdef LIBRARIES
869 	    if (s->flags & SUFF_LIBRARY) {
870 		Dir_Concat(inLibs, s->searchPath);
871 	    }
872 #endif
873 	    Dir_Concat(s->searchPath, dirSearchPath);
874 	} else {
875 	    Lst_Destroy(s->searchPath, Dir_Destroy);
876 	    s->searchPath = Lst_Copy(dirSearchPath, Dir_CopyDir);
877 	}
878     }
879     Lst_Close(sufflist);
880 
881     Var_Set(".INCLUDES", ptr = Dir_MakeFlags("-I", inIncludes), VAR_GLOBAL);
882     free(ptr);
883     Var_Set(".LIBS", ptr = Dir_MakeFlags("-L", inLibs), VAR_GLOBAL);
884     free(ptr);
885 
886     Lst_Destroy(inIncludes, Dir_Destroy);
887     Lst_Destroy(inLibs, Dir_Destroy);
888 }
889 
890 /* Add the given suffix as a type of file which gets included.
891  * Called from the parse module when a .INCLUDES line is parsed.
892  * The suffix must have already been defined.
893  * The SUFF_INCLUDE bit is set in the suffix's flags field.
894  *
895  * Input:
896  *	sname		Name of the suffix to mark
897  */
898 void
899 Suff_AddInclude(char *sname)
900 {
901     LstNode	  ln;
902     Suff	  *s;
903 
904     ln = Lst_Find(sufflist, SuffSuffHasName, sname);
905     if (ln != NULL) {
906 	s = LstNode_Datum(ln);
907 	s->flags |= SUFF_INCLUDE;
908     }
909 }
910 
911 /* Add the given suffix as a type of file which is a library.
912  * Called from the parse module when parsing a .LIBS line.
913  * The suffix must have been defined via .SUFFIXES before this is called.
914  * The SUFF_LIBRARY bit is set in the suffix's flags field.
915  *
916  * Input:
917  *	sname		Name of the suffix to mark
918  */
919 void
920 Suff_AddLib(const char *sname)
921 {
922     LstNode	  ln;
923     Suff	  *s;
924 
925     ln = Lst_Find(sufflist, SuffSuffHasName, sname);
926     if (ln != NULL) {
927 	s = LstNode_Datum(ln);
928 	s->flags |= SUFF_LIBRARY;
929     }
930 }
931 
932 	  /********** Implicit Source Search Functions *********/
933 
934 #ifdef DEBUG_SRC
935 static int
936 PrintAddr(void *a, void *b MAKE_ATTR_UNUSED)
937 {
938     printf("%lx ", (unsigned long) a);
939     return 0;
940 }
941 #endif
942 
943 /* Add a suffix as a Src structure to the given list with its parent
944  * being the given Src structure. If the suffix is the null suffix,
945  * the prefix is used unaltered as the file name in the Src structure.
946  *
947  * Input:
948  *	sp		suffix for which to create a Src structure
949  *	lsp		list and parent for the new Src
950  *
951  * Results:
952  *	0, so that Lst_ForEach continues
953  */
954 static int
955 SuffAddSrc(void *sp, void *lsp)
956 {
957     Suff	*s = (Suff *)sp;
958     LstSrc      *ls = (LstSrc *)lsp;
959     Src         *s2;	    /* new Src structure */
960     Src    	*targ; 	    /* Target structure */
961 
962     targ = ls->s;
963 
964     if ((s->flags & SUFF_NULL) && s->name[0] != '\0') {
965 	/*
966 	 * If the suffix has been marked as the NULL suffix, also create a Src
967 	 * structure for a file with no suffix attached. Two birds, and all
968 	 * that...
969 	 */
970 	s2 = bmake_malloc(sizeof(Src));
971 	s2->file =  	bmake_strdup(targ->pref);
972 	s2->pref =  	targ->pref;
973 	s2->parent = 	targ;
974 	s2->node =  	NULL;
975 	s2->suff =  	s;
976 	s->refCount++;
977 	s2->children =	0;
978 	targ->children += 1;
979 	Lst_Append(ls->l, s2);
980 #ifdef DEBUG_SRC
981 	s2->cp = Lst_Init();
982 	Lst_Append(targ->cp, s2);
983 	fprintf(debug_file, "1 add %p %p to %p:", targ, s2, ls->l);
984 	Lst_ForEach(ls->l, PrintAddr, NULL);
985 	fprintf(debug_file, "\n");
986 #endif
987     }
988     s2 = bmake_malloc(sizeof(Src));
989     s2->file = 	    str_concat2(targ->pref, s->name);
990     s2->pref =	    targ->pref;
991     s2->parent =    targ;
992     s2->node = 	    NULL;
993     s2->suff = 	    s;
994     s->refCount++;
995     s2->children =  0;
996     targ->children += 1;
997     Lst_Append(ls->l, s2);
998 #ifdef DEBUG_SRC
999     s2->cp = Lst_Init();
1000     Lst_Append(targ->cp, s2);
1001     fprintf(debug_file, "2 add %p %p to %p:", targ, s2, ls->l);
1002     Lst_ForEach(ls->l, PrintAddr, NULL);
1003     fprintf(debug_file, "\n");
1004 #endif
1005 
1006     return 0;
1007 }
1008 
1009 /* Add all the children of targ as Src structures to the given list.
1010  *
1011  * Input:
1012  *	l		list to which to add the new level
1013  *	targ		Src structure to use as the parent
1014  */
1015 static void
1016 SuffAddLevel(Lst l, Src *targ)
1017 {
1018     LstSrc         ls;
1019 
1020     ls.s = targ;
1021     ls.l = l;
1022 
1023     Lst_ForEach(targ->suff->children, SuffAddSrc, &ls);
1024 }
1025 
1026 /* Free the first Src in the list that doesn't have a reference count.
1027  * Return whether a Src was removed. */
1028 static Boolean
1029 SuffRemoveSrc(Lst l)
1030 {
1031     LstNode ln;
1032     Src *s;
1033 
1034     Lst_Open(l);
1035 
1036 #ifdef DEBUG_SRC
1037     fprintf(debug_file, "cleaning %lx: ", (unsigned long) l);
1038     Lst_ForEach(l, PrintAddr, NULL);
1039     fprintf(debug_file, "\n");
1040 #endif
1041 
1042     while ((ln = Lst_Next(l)) != NULL) {
1043 	s = LstNode_Datum(ln);
1044 	if (s->children == 0) {
1045 	    free(s->file);
1046 	    if (!s->parent)
1047 		free(s->pref);
1048 	    else {
1049 #ifdef DEBUG_SRC
1050 		LstNode ln2 = Lst_FindDatum(s->parent->cp, s);
1051 		if (ln2 != NULL)
1052 		    Lst_Remove(s->parent->cp, ln2);
1053 #endif
1054 		--s->parent->children;
1055 	    }
1056 #ifdef DEBUG_SRC
1057 	    fprintf(debug_file, "free: [l=%p] p=%p %d\n", l, s, s->children);
1058 	    Lst_Free(s->cp);
1059 #endif
1060 	    Lst_Remove(l, ln);
1061 	    free(s);
1062 	    Lst_Close(l);
1063 	    return TRUE;
1064 	}
1065 #ifdef DEBUG_SRC
1066 	else {
1067 	    fprintf(debug_file, "keep: [l=%p] p=%p %d: ", l, s, s->children);
1068 	    Lst_ForEach(s->cp, PrintAddr, NULL);
1069 	    fprintf(debug_file, "\n");
1070 	}
1071 #endif
1072     }
1073 
1074     Lst_Close(l);
1075 
1076     return FALSE;
1077 }
1078 
1079 /* Find the first existing file/target in the list srcs.
1080  *
1081  * Input:
1082  *	srcs		list of Src structures to search through
1083  *
1084  * Results:
1085  *	The lowest structure in the chain of transformations, or NULL.
1086  */
1087 static Src *
1088 SuffFindThem(Lst srcs, Lst slst)
1089 {
1090     Src            *s;		/* current Src */
1091     Src		   *rs;		/* returned Src */
1092     char	   *ptr;
1093 
1094     rs = NULL;
1095 
1096     while (!Lst_IsEmpty(srcs)) {
1097 	s = Lst_Dequeue(srcs);
1098 
1099 	SUFF_DEBUG1("\ttrying %s...", s->file);
1100 
1101 	/*
1102 	 * A file is considered to exist if either a node exists in the
1103 	 * graph for it or the file actually exists.
1104 	 */
1105 	if (Targ_FindNode(s->file, TARG_NOCREATE) != NULL) {
1106 #ifdef DEBUG_SRC
1107 	    fprintf(debug_file, "remove %p from %p\n", s, srcs);
1108 #endif
1109 	    rs = s;
1110 	    break;
1111 	}
1112 
1113 	if ((ptr = Dir_FindFile(s->file, s->suff->searchPath)) != NULL) {
1114 	    rs = s;
1115 #ifdef DEBUG_SRC
1116 	    fprintf(debug_file, "remove %p from %p\n", s, srcs);
1117 #endif
1118 	    free(ptr);
1119 	    break;
1120 	}
1121 
1122 	SUFF_DEBUG0("not there\n");
1123 
1124 	SuffAddLevel(srcs, s);
1125 	Lst_Append(slst, s);
1126     }
1127 
1128     if (rs) {
1129 	SUFF_DEBUG0("got it\n");
1130     }
1131     return rs;
1132 }
1133 
1134 /* See if any of the children of the target in the Src structure is one from
1135  * which the target can be transformed. If there is one, a Src structure is
1136  * put together for it and returned.
1137  *
1138  * Input:
1139  *	targ		Src to play with
1140  *
1141  * Results:
1142  *	The Src of the "winning" child, or NULL.
1143  */
1144 static Src *
1145 SuffFindCmds(Src *targ, Lst slst)
1146 {
1147     LstNode 	  	ln; 	/* General-purpose list node */
1148     GNode		*t, 	/* Target GNode */
1149 			*s; 	/* Source GNode */
1150     int	    	  	prefLen;/* The length of the defined prefix */
1151     Suff    	  	*suff;	/* Suffix on matching beastie */
1152     Src	    	  	*ret;	/* Return value */
1153     char    	  	*cp;
1154 
1155     t = targ->node;
1156     Lst_Open(t->children);
1157     prefLen = strlen(targ->pref);
1158 
1159     for (;;) {
1160 	ln = Lst_Next(t->children);
1161 	if (ln == NULL) {
1162 	    Lst_Close(t->children);
1163 	    return NULL;
1164 	}
1165 	s = LstNode_Datum(ln);
1166 
1167 	if (s->type & OP_OPTIONAL && Lst_IsEmpty(t->commands)) {
1168 	    /*
1169 	     * We haven't looked to see if .OPTIONAL files exist yet, so
1170 	     * don't use one as the implicit source.
1171 	     * This allows us to use .OPTIONAL in .depend files so make won't
1172 	     * complain "don't know how to make xxx.h' when a dependent file
1173 	     * has been moved/deleted.
1174 	     */
1175 	    continue;
1176 	}
1177 
1178 	cp = strrchr(s->name, '/');
1179 	if (cp == NULL) {
1180 	    cp = s->name;
1181 	} else {
1182 	    cp++;
1183 	}
1184 	if (strncmp(cp, targ->pref, prefLen) != 0)
1185 	    continue;
1186 	/*
1187 	 * The node matches the prefix ok, see if it has a known
1188 	 * suffix.
1189 	 */
1190 	ln = Lst_Find(sufflist, SuffSuffHasName, &cp[prefLen]);
1191 	if (ln == NULL)
1192 	    continue;
1193 	/*
1194 	 * It even has a known suffix, see if there's a transformation
1195 	 * defined between the node's suffix and the target's suffix.
1196 	 *
1197 	 * XXX: Handle multi-stage transformations here, too.
1198 	 */
1199 	suff = LstNode_Datum(ln);
1200 
1201 	/* XXX: Can targ->suff be NULL here? */
1202 	if (targ->suff != NULL &&
1203 	    Lst_FindDatum(suff->parents, targ->suff) != NULL)
1204 	    break;
1205     }
1206 
1207     /*
1208      * Hot Damn! Create a new Src structure to describe
1209      * this transformation (making sure to duplicate the
1210      * source node's name so Suff_FindDeps can free it
1211      * again (ick)), and return the new structure.
1212      */
1213     ret = bmake_malloc(sizeof(Src));
1214     ret->file = bmake_strdup(s->name);
1215     ret->pref = targ->pref;
1216     ret->suff = suff;
1217     suff->refCount++;
1218     ret->parent = targ;
1219     ret->node = s;
1220     ret->children = 0;
1221     targ->children += 1;
1222 #ifdef DEBUG_SRC
1223     ret->cp = Lst_Init();
1224     fprintf(debug_file, "3 add %p %p\n", targ, ret);
1225     Lst_Append(targ->cp, ret);
1226 #endif
1227     Lst_Append(slst, ret);
1228     SUFF_DEBUG1("\tusing existing source %s\n", s->name);
1229     Lst_Close(t->children);
1230     return ret;
1231 }
1232 
1233 /* Expand the names of any children of a given node that contain variable
1234  * expressions or file wildcards into actual targets.
1235  *
1236  * The expanded node is removed from the parent's list of children, and the
1237  * parent's unmade counter is decremented, but other nodes may be added.
1238  *
1239  * Input:
1240  *	cln		Child to examine
1241  *	pgn		Parent node being processed
1242  */
1243 static void
1244 SuffExpandChildren(LstNode cln, GNode *pgn)
1245 {
1246     GNode   	*cgn = LstNode_Datum(cln);
1247     GNode	*gn;	    /* New source 8) */
1248     char	*cp;	    /* Expanded value */
1249 
1250     if (!Lst_IsEmpty(cgn->order_pred) || !Lst_IsEmpty(cgn->order_succ))
1251 	/* It is all too hard to process the result of .ORDER */
1252 	return;
1253 
1254     if (cgn->type & OP_WAIT)
1255 	/* Ignore these (& OP_PHONY ?) */
1256 	return;
1257 
1258     /*
1259      * First do variable expansion -- this takes precedence over
1260      * wildcard expansion. If the result contains wildcards, they'll be gotten
1261      * to later since the resulting words are tacked on to the end of
1262      * the children list.
1263      */
1264     if (strchr(cgn->name, '$') == NULL) {
1265 	SuffExpandWildcards(cln, pgn);
1266 	return;
1267     }
1268 
1269     SUFF_DEBUG1("Expanding \"%s\"...", cgn->name);
1270     cp = Var_Subst(cgn->name, pgn, VARE_UNDEFERR|VARE_WANTRES);
1271 
1272     {
1273 	Lst	    members = Lst_Init();
1274 
1275 	if (cgn->type & OP_ARCHV) {
1276 	    /*
1277 	     * Node was an archive(member) target, so we want to call
1278 	     * on the Arch module to find the nodes for us, expanding
1279 	     * variables in the parent's context.
1280 	     */
1281 	    char	*sacrifice = cp;
1282 
1283 	    (void)Arch_ParseArchive(&sacrifice, members, pgn);
1284 	} else {
1285 	    /*
1286 	     * Break the result into a vector of strings whose nodes
1287 	     * we can find, then add those nodes to the members list.
1288 	     * Unfortunately, we can't use brk_string b/c it
1289 	     * doesn't understand about variable specifications with
1290 	     * spaces in them...
1291 	     */
1292 	    char	    *start;
1293 	    char	    *initcp = cp;   /* For freeing... */
1294 
1295 	    for (start = cp; *start == ' ' || *start == '\t'; start++)
1296 		continue;
1297 	    cp = start;
1298 	    while (*cp != '\0') {
1299 		if (*cp == ' ' || *cp == '\t') {
1300 		    /*
1301 		     * White-space -- terminate element, find the node,
1302 		     * add it, skip any further spaces.
1303 		     */
1304 		    *cp++ = '\0';
1305 		    gn = Targ_FindNode(start, TARG_CREATE);
1306 		    Lst_Append(members, gn);
1307 		    while (*cp == ' ' || *cp == '\t') {
1308 			cp++;
1309 		    }
1310 		    start = cp;		/* Continue at the next non-space. */
1311 		} else if (*cp == '$') {
1312 		    /*
1313 		     * Start of a variable spec -- contact variable module
1314 		     * to find the end so we can skip over it.
1315 		     */
1316 		    const char *nested_p = cp;
1317 		    const char	*junk;
1318 		    void	*freeIt;
1319 
1320 		    /* XXX: Why VARE_WANTRES when the result is not used? */
1321 		    (void)Var_Parse(&nested_p, pgn,
1322 				    VARE_UNDEFERR|VARE_WANTRES,
1323 				    &junk, &freeIt);
1324 		    /* TODO: handle errors */
1325 		    if (junk == var_Error) {
1326 			Parse_Error(PARSE_FATAL,
1327 				    "Malformed variable expression at \"%s\"",
1328 				    cp);
1329 			cp++;
1330 		    } else {
1331 			cp += nested_p - cp;
1332 		    }
1333 
1334 		    free(freeIt);
1335 		} else if (*cp == '\\' && cp[1] != '\0') {
1336 		    /*
1337 		     * Escaped something -- skip over it
1338 		     */
1339 		    /* XXX: In other places, escaping at this syntactical
1340 		     * position is done by a '$', not a '\'.  The '\' is only
1341 		     * used in variable modifiers. */
1342 		    cp += 2;
1343 		} else {
1344 		    cp++;
1345 		}
1346 	    }
1347 
1348 	    if (cp != start) {
1349 		/*
1350 		 * Stuff left over -- add it to the list too
1351 		 */
1352 		gn = Targ_FindNode(start, TARG_CREATE);
1353 		Lst_Append(members, gn);
1354 	    }
1355 	    /*
1356 	     * Point cp back at the beginning again so the variable value
1357 	     * can be freed.
1358 	     */
1359 	    cp = initcp;
1360 	}
1361 
1362 	/*
1363 	 * Add all elements of the members list to the parent node.
1364 	 */
1365 	while(!Lst_IsEmpty(members)) {
1366 	    gn = Lst_Dequeue(members);
1367 
1368 	    SUFF_DEBUG1("%s...", gn->name);
1369 	    /* Add gn to the parents child list before the original child */
1370 	    Lst_InsertBefore(pgn->children, cln, gn);
1371 	    Lst_Append(gn->parents, pgn);
1372 	    pgn->unmade++;
1373 	    /* Expand wildcards on new node */
1374 	    SuffExpandWildcards(LstNode_Prev(cln), pgn);
1375 	}
1376 	Lst_Free(members);
1377 
1378 	/*
1379 	 * Free the result
1380 	 */
1381 	free(cp);
1382     }
1383 
1384     SUFF_DEBUG0("\n");
1385 
1386     /*
1387      * Now the source is expanded, remove it from the list of children to
1388      * keep it from being processed.
1389      */
1390     pgn->unmade--;
1391     Lst_Remove(pgn->children, cln);
1392     Lst_Remove(cgn->parents, Lst_FindDatum(cgn->parents, pgn));
1393 }
1394 
1395 static void
1396 SuffExpandWildcards(LstNode cln, GNode *pgn)
1397 {
1398     GNode   	*cgn = LstNode_Datum(cln);
1399     GNode	*gn;	    /* New source 8) */
1400     char	*cp;	    /* Expanded value */
1401     Lst 	explist;    /* List of expansions */
1402 
1403     if (!Dir_HasWildcards(cgn->name))
1404 	return;
1405 
1406     /*
1407      * Expand the word along the chosen path
1408      */
1409     explist = Lst_Init();
1410     Dir_Expand(cgn->name, Suff_FindPath(cgn), explist);
1411 
1412     while (!Lst_IsEmpty(explist)) {
1413 	/*
1414 	 * Fetch next expansion off the list and find its GNode
1415 	 */
1416 	cp = Lst_Dequeue(explist);
1417 
1418 	SUFF_DEBUG1("%s...", cp);
1419 	gn = Targ_FindNode(cp, TARG_CREATE);
1420 
1421 	/* Add gn to the parents child list before the original child */
1422 	Lst_InsertBefore(pgn->children, cln, gn);
1423 	Lst_Append(gn->parents, pgn);
1424 	pgn->unmade++;
1425     }
1426 
1427     Lst_Free(explist);
1428 
1429     SUFF_DEBUG0("\n");
1430 
1431     /*
1432      * Now the source is expanded, remove it from the list of children to
1433      * keep it from being processed.
1434      */
1435     pgn->unmade--;
1436     Lst_Remove(pgn->children, cln);
1437     Lst_Remove(cgn->parents, Lst_FindDatum(cgn->parents, pgn));
1438 }
1439 
1440 /* Find a path along which to expand the node.
1441  *
1442  * If the word has a known suffix, use that path.
1443  * If it has no known suffix, use the default system search path.
1444  *
1445  * Input:
1446  *	gn		Node being examined
1447  *
1448  * Results:
1449  *	The appropriate path to search for the GNode.
1450  */
1451 Lst
1452 Suff_FindPath(GNode* gn)
1453 {
1454     Suff *suff = gn->suffix;
1455 
1456     if (suff == NULL) {
1457 	SuffSuffGetSuffixArgs sd;   /* Search string data */
1458 	LstNode ln;
1459 	sd.len = strlen(gn->name);
1460 	sd.ename = gn->name + sd.len;
1461 	ln = Lst_Find(sufflist, SuffSuffIsSuffix, &sd);
1462 
1463 	SUFF_DEBUG1("Wildcard expanding \"%s\"...", gn->name);
1464 	if (ln != NULL)
1465 	    suff = LstNode_Datum(ln);
1466 	/* XXX: Here we can save the suffix so we don't have to do this again */
1467     }
1468 
1469     if (suff != NULL) {
1470 	SUFF_DEBUG1("suffix is \"%s\"...", suff->name);
1471 	return suff->searchPath;
1472     } else {
1473 	/*
1474 	 * Use default search path
1475 	 */
1476 	return dirSearchPath;
1477     }
1478 }
1479 
1480 /* Apply a transformation rule, given the source and target nodes and
1481  * suffixes.
1482  *
1483  * Input:
1484  *	tGn		Target node
1485  *	sGn		Source node
1486  *	t		Target suffix
1487  *	s		Source suffix
1488  *
1489  * Results:
1490  *	TRUE if successful, FALSE if not.
1491  *
1492  * Side Effects:
1493  *	The source and target are linked and the commands from the
1494  *	transformation are added to the target node's commands list.
1495  *	All attributes but OP_DEPMASK and OP_TRANSFORM are applied
1496  *	to the target. The target also inherits all the sources for
1497  *	the transformation rule.
1498  */
1499 static Boolean
1500 SuffApplyTransform(GNode *tGn, GNode *sGn, Suff *t, Suff *s)
1501 {
1502     LstNode 	ln, nln;    /* General node */
1503     char    	*tname;	    /* Name of transformation rule */
1504     GNode   	*gn;	    /* Node for same */
1505 
1506     /*
1507      * Form the proper links between the target and source.
1508      */
1509     Lst_Append(tGn->children, sGn);
1510     Lst_Append(sGn->parents, tGn);
1511     tGn->unmade += 1;
1512 
1513     /*
1514      * Locate the transformation rule itself
1515      */
1516     tname = str_concat2(s->name, t->name);
1517     ln = Lst_Find(transforms, SuffGNHasName, tname);
1518     free(tname);
1519 
1520     if (ln == NULL) {
1521 	/*
1522 	 * Not really such a transformation rule (can happen when we're
1523 	 * called to link an OP_MEMBER and OP_ARCHV node), so return
1524 	 * FALSE.
1525 	 */
1526 	return FALSE;
1527     }
1528 
1529     gn = LstNode_Datum(ln);
1530 
1531     SUFF_DEBUG3("\tapplying %s -> %s to \"%s\"\n", s->name, t->name, tGn->name);
1532 
1533     /*
1534      * Record last child for expansion purposes
1535      */
1536     ln = Lst_Last(tGn->children);
1537 
1538     /*
1539      * Pass the buck to Make_HandleUse to apply the rule
1540      */
1541     (void)Make_HandleUse(gn, tGn);
1542 
1543     /*
1544      * Deal with wildcards and variables in any acquired sources
1545      */
1546     for (ln = ln != NULL ? LstNode_Next(ln) : NULL; ln != NULL; ln = nln) {
1547 	nln = LstNode_Next(ln);
1548 	SuffExpandChildren(ln, tGn);
1549     }
1550 
1551     /*
1552      * Keep track of another parent to which this beast is transformed so
1553      * the .IMPSRC variable can be set correctly for the parent.
1554      */
1555     Lst_Append(sGn->implicitParents, tGn);
1556 
1557     return TRUE;
1558 }
1559 
1560 
1561 /* Locate dependencies for an OP_ARCHV node.
1562  *
1563  * Input:
1564  *	gn		Node for which to locate dependencies
1565  *
1566  * Side Effects:
1567  *	Same as Suff_FindDeps
1568  */
1569 static void
1570 SuffFindArchiveDeps(GNode *gn, Lst slst)
1571 {
1572     char    	*eoarch;    /* End of archive portion */
1573     char    	*eoname;    /* End of member portion */
1574     GNode   	*mem;	    /* Node for member */
1575     LstNode 	ln, nln;    /* Next suffix node to check */
1576     Suff    	*ms;	    /* Suffix descriptor for member */
1577     char    	*name;	    /* Start of member's name */
1578 
1579     /*
1580      * The node is an archive(member) pair. so we must find a
1581      * suffix for both of them.
1582      */
1583     eoarch = strchr(gn->name, '(');
1584     eoname = strchr(eoarch, ')');
1585 
1586     /*
1587      * Caller guarantees the format `libname(member)', via
1588      * Arch_ParseArchive.
1589      */
1590     assert(eoarch != NULL);
1591     assert(eoname != NULL);
1592 
1593     *eoname = '\0';	  /* Nuke parentheses during suffix search */
1594     *eoarch = '\0';	  /* So a suffix can be found */
1595 
1596     name = eoarch + 1;
1597 
1598     /*
1599      * To simplify things, call Suff_FindDeps recursively on the member now,
1600      * so we can simply compare the member's .PREFIX and .TARGET variables
1601      * to locate its suffix. This allows us to figure out the suffix to
1602      * use for the archive without having to do a quadratic search over the
1603      * suffix list, backtracking for each one...
1604      */
1605     mem = Targ_FindNode(name, TARG_CREATE);
1606     SuffFindDeps(mem, slst);
1607 
1608     /*
1609      * Create the link between the two nodes right off
1610      */
1611     Lst_Append(gn->children, mem);
1612     Lst_Append(mem->parents, gn);
1613     gn->unmade += 1;
1614 
1615     /*
1616      * Copy in the variables from the member node to this one.
1617      */
1618     {
1619 	char *freeIt;
1620 	Var_Set(PREFIX, Var_Value(PREFIX, mem, &freeIt), gn);
1621 	bmake_free(freeIt);
1622 	Var_Set(TARGET, Var_Value(TARGET, mem, &freeIt), gn);
1623 	bmake_free(freeIt);
1624     }
1625 
1626     ms = mem->suffix;
1627     if (ms == NULL) {
1628 	/*
1629 	 * Didn't know what it was -- use .NULL suffix if not in make mode
1630 	 */
1631 	SUFF_DEBUG0("using null suffix\n");
1632 	ms = suffNull;
1633     }
1634 
1635 
1636     /*
1637      * Set the other two local variables required for this target.
1638      */
1639     Var_Set(MEMBER, name, gn);
1640     Var_Set(ARCHIVE, gn->name, gn);
1641 
1642     /*
1643      * Set $@ for compatibility with other makes
1644      */
1645     Var_Set(TARGET, gn->name, gn);
1646 
1647     /*
1648      * Now we've got the important local variables set, expand any sources
1649      * that still contain variables or wildcards in their names.
1650      */
1651     for (ln = Lst_First(gn->children); ln != NULL; ln = nln) {
1652 	nln = LstNode_Next(ln);
1653 	SuffExpandChildren(ln, gn);
1654     }
1655 
1656     if (ms != NULL) {
1657 	/*
1658 	 * Member has a known suffix, so look for a transformation rule from
1659 	 * it to a possible suffix of the archive. Rather than searching
1660 	 * through the entire list, we just look at suffixes to which the
1661 	 * member's suffix may be transformed...
1662 	 */
1663 	SuffSuffGetSuffixArgs sd;	/* Search string data */
1664 
1665 	/*
1666 	 * Use first matching suffix...
1667 	 */
1668 	sd.len = eoarch - gn->name;
1669 	sd.ename = eoarch;
1670 	ln = Lst_Find(ms->parents, SuffSuffIsSuffix, &sd);
1671 
1672 	if (ln != NULL) {
1673 	    /*
1674 	     * Got one -- apply it
1675 	     */
1676 	    Suff *suff = LstNode_Datum(ln);
1677 	    if (!SuffApplyTransform(gn, mem, suff, ms)) {
1678 		SUFF_DEBUG2("\tNo transformation from %s -> %s\n",
1679 			    ms->name, suff->name);
1680 	    }
1681 	}
1682     }
1683 
1684     /*
1685      * Replace the opening and closing parens now we've no need of the separate
1686      * pieces.
1687      */
1688     *eoarch = '('; *eoname = ')';
1689 
1690     /*
1691      * Pretend gn appeared to the left of a dependency operator so
1692      * the user needn't provide a transformation from the member to the
1693      * archive.
1694      */
1695     if (OP_NOP(gn->type)) {
1696 	gn->type |= OP_DEPENDS;
1697     }
1698 
1699     /*
1700      * Flag the member as such so we remember to look in the archive for
1701      * its modification time. The OP_JOIN | OP_MADE is needed because this
1702      * target should never get made.
1703      */
1704     mem->type |= OP_MEMBER | OP_JOIN | OP_MADE;
1705 }
1706 
1707 /* Locate implicit dependencies for regular targets.
1708  *
1709  * Input:
1710  *	gn		Node for which to find sources
1711  *
1712  * Side Effects:
1713  *	Same as Suff_FindDeps
1714  */
1715 static void
1716 SuffFindNormalDeps(GNode *gn, Lst slst)
1717 {
1718     char    	*eoname;    /* End of name */
1719     char    	*sopref;    /* Start of prefix */
1720     LstNode 	ln, nln;    /* Next suffix node to check */
1721     Lst	    	srcs;	    /* List of sources at which to look */
1722     Lst	    	targs;	    /* List of targets to which things can be
1723 			     * transformed. They all have the same file,
1724 			     * but different suff and pref fields */
1725     Src	    	*bottom;    /* Start of found transformation path */
1726     Src 	*src;	    /* General Src pointer */
1727     char    	*pref;	    /* Prefix to use */
1728     Src	    	*targ;	    /* General Src target pointer */
1729     SuffSuffGetSuffixArgs sd; /* Search string data */
1730 
1731 
1732     sd.len = strlen(gn->name);
1733     sd.ename = eoname = gn->name + sd.len;
1734 
1735     sopref = gn->name;
1736 
1737     /*
1738      * Begin at the beginning...
1739      */
1740     ln = Lst_First(sufflist);
1741     srcs = Lst_Init();
1742     targs = Lst_Init();
1743 
1744     /*
1745      * We're caught in a catch-22 here. On the one hand, we want to use any
1746      * transformation implied by the target's sources, but we can't examine
1747      * the sources until we've expanded any variables/wildcards they may hold,
1748      * and we can't do that until we've set up the target's local variables
1749      * and we can't do that until we know what the proper suffix for the
1750      * target is (in case there are two suffixes one of which is a suffix of
1751      * the other) and we can't know that until we've found its implied
1752      * source, which we may not want to use if there's an existing source
1753      * that implies a different transformation.
1754      *
1755      * In an attempt to get around this, which may not work all the time,
1756      * but should work most of the time, we look for implied sources first,
1757      * checking transformations to all possible suffixes of the target,
1758      * use what we find to set the target's local variables, expand the
1759      * children, then look for any overriding transformations they imply.
1760      * Should we find one, we discard the one we found before.
1761      */
1762     bottom = NULL;
1763     targ = NULL;
1764 
1765     if (!(gn->type & OP_PHONY)) {
1766 
1767 	while (ln != NULL) {
1768 	    /*
1769 	     * Look for next possible suffix...
1770 	     */
1771 	    ln = Lst_FindFrom(sufflist, ln, SuffSuffIsSuffix, &sd);
1772 
1773 	    if (ln != NULL) {
1774 		const char *eopref;
1775 
1776 		/*
1777 		 * Allocate a Src structure to which things can be transformed
1778 		 */
1779 		targ = bmake_malloc(sizeof(Src));
1780 		targ->file = bmake_strdup(gn->name);
1781 		targ->suff = LstNode_Datum(ln);
1782 		targ->suff->refCount++;
1783 		targ->node = gn;
1784 		targ->parent = NULL;
1785 		targ->children = 0;
1786 #ifdef DEBUG_SRC
1787 		targ->cp = Lst_Init();
1788 #endif
1789 
1790 		eopref = eoname - targ->suff->nameLen;
1791 		targ->pref = bmake_strsedup(sopref, eopref);
1792 
1793 		/*
1794 		 * Add nodes from which the target can be made
1795 		 */
1796 		SuffAddLevel(srcs, targ);
1797 
1798 		/*
1799 		 * Record the target so we can nuke it
1800 		 */
1801 		Lst_Append(targs, targ);
1802 
1803 		/*
1804 		 * Search from this suffix's successor...
1805 		 */
1806 		ln = LstNode_Next(ln);
1807 	    }
1808 	}
1809 
1810 	/*
1811 	 * Handle target of unknown suffix...
1812 	 */
1813 	if (Lst_IsEmpty(targs) && suffNull != NULL) {
1814 	    SUFF_DEBUG1("\tNo known suffix on %s. Using .NULL suffix\n",
1815 			gn->name);
1816 
1817 	    targ = bmake_malloc(sizeof(Src));
1818 	    targ->file = bmake_strdup(gn->name);
1819 	    targ->suff = suffNull;
1820 	    targ->suff->refCount++;
1821 	    targ->node = gn;
1822 	    targ->parent = NULL;
1823 	    targ->children = 0;
1824 	    targ->pref = bmake_strdup(sopref);
1825 #ifdef DEBUG_SRC
1826 	    targ->cp = Lst_Init();
1827 #endif
1828 
1829 	    /*
1830 	     * Only use the default suffix rules if we don't have commands
1831 	     * defined for this gnode; traditional make programs used to
1832 	     * not define suffix rules if the gnode had children but we
1833 	     * don't do this anymore.
1834 	     */
1835 	    if (Lst_IsEmpty(gn->commands))
1836 		SuffAddLevel(srcs, targ);
1837 	    else {
1838 		SUFF_DEBUG0("not ");
1839 	    }
1840 
1841 	    SUFF_DEBUG0("adding suffix rules\n");
1842 
1843 	    Lst_Append(targs, targ);
1844 	}
1845 
1846 	/*
1847 	 * Using the list of possible sources built up from the target
1848 	 * suffix(es), try and find an existing file/target that matches.
1849 	 */
1850 	bottom = SuffFindThem(srcs, slst);
1851 
1852 	if (bottom == NULL) {
1853 	    /*
1854 	     * No known transformations -- use the first suffix found
1855 	     * for setting the local variables.
1856 	     */
1857 	    if (!Lst_IsEmpty(targs)) {
1858 		targ = LstNode_Datum(Lst_First(targs));
1859 	    } else {
1860 		targ = NULL;
1861 	    }
1862 	} else {
1863 	    /*
1864 	     * Work up the transformation path to find the suffix of the
1865 	     * target to which the transformation was made.
1866 	     */
1867 	    for (targ = bottom; targ->parent != NULL; targ = targ->parent)
1868 		continue;
1869 	}
1870     }
1871 
1872     Var_Set(TARGET, gn->path ? gn->path : gn->name, gn);
1873 
1874     pref = (targ != NULL) ? targ->pref : gn->name;
1875     Var_Set(PREFIX, pref, gn);
1876 
1877     /*
1878      * Now we've got the important local variables set, expand any sources
1879      * that still contain variables or wildcards in their names.
1880      */
1881     for (ln = Lst_First(gn->children); ln != NULL; ln = nln) {
1882 	nln = LstNode_Next(ln);
1883 	SuffExpandChildren(ln, gn);
1884     }
1885 
1886     if (targ == NULL) {
1887 	SUFF_DEBUG1("\tNo valid suffix on %s\n", gn->name);
1888 
1889 sfnd_abort:
1890 	/*
1891 	 * Deal with finding the thing on the default search path. We
1892 	 * always do that, not only if the node is only a source (not
1893 	 * on the lhs of a dependency operator or [XXX] it has neither
1894 	 * children or commands) as the old pmake did.
1895 	 */
1896 	if ((gn->type & (OP_PHONY|OP_NOPATH)) == 0) {
1897 	    free(gn->path);
1898 	    gn->path = Dir_FindFile(gn->name,
1899 				    (targ == NULL ? dirSearchPath :
1900 				     targ->suff->searchPath));
1901 	    if (gn->path != NULL) {
1902 		char *ptr;
1903 		Var_Set(TARGET, gn->path, gn);
1904 
1905 		if (targ != NULL) {
1906 		    /*
1907 		     * Suffix known for the thing -- trim the suffix off
1908 		     * the path to form the proper .PREFIX variable.
1909 		     */
1910 		    int     savep = strlen(gn->path) - targ->suff->nameLen;
1911 		    char    savec;
1912 
1913 		    if (gn->suffix)
1914 			gn->suffix->refCount--;
1915 		    gn->suffix = targ->suff;
1916 		    gn->suffix->refCount++;
1917 
1918 		    savec = gn->path[savep];
1919 		    gn->path[savep] = '\0';
1920 
1921 		    if ((ptr = strrchr(gn->path, '/')) != NULL)
1922 			ptr++;
1923 		    else
1924 			ptr = gn->path;
1925 
1926 		    Var_Set(PREFIX, ptr, gn);
1927 
1928 		    gn->path[savep] = savec;
1929 		} else {
1930 		    /*
1931 		     * The .PREFIX gets the full path if the target has
1932 		     * no known suffix.
1933 		     */
1934 		    if (gn->suffix)
1935 			gn->suffix->refCount--;
1936 		    gn->suffix = NULL;
1937 
1938 		    if ((ptr = strrchr(gn->path, '/')) != NULL)
1939 			ptr++;
1940 		    else
1941 			ptr = gn->path;
1942 
1943 		    Var_Set(PREFIX, ptr, gn);
1944 		}
1945 	    }
1946 	}
1947 
1948 	goto sfnd_return;
1949     }
1950 
1951     /*
1952      * If the suffix indicates that the target is a library, mark that in
1953      * the node's type field.
1954      */
1955     if (targ->suff->flags & SUFF_LIBRARY) {
1956 	gn->type |= OP_LIB;
1957     }
1958 
1959     /*
1960      * Check for overriding transformation rule implied by sources
1961      */
1962     if (!Lst_IsEmpty(gn->children)) {
1963 	src = SuffFindCmds(targ, slst);
1964 
1965 	if (src != NULL) {
1966 	    /*
1967 	     * Free up all the Src structures in the transformation path
1968 	     * up to, but not including, the parent node.
1969 	     */
1970 	    while (bottom && bottom->parent != NULL) {
1971 		if (Lst_FindDatum(slst, bottom) == NULL) {
1972 		    Lst_Append(slst, bottom);
1973 		}
1974 		bottom = bottom->parent;
1975 	    }
1976 	    bottom = src;
1977 	}
1978     }
1979 
1980     if (bottom == NULL) {
1981 	/*
1982 	 * No idea from where it can come -- return now.
1983 	 */
1984 	goto sfnd_abort;
1985     }
1986 
1987     /*
1988      * We now have a list of Src structures headed by 'bottom' and linked via
1989      * their 'parent' pointers. What we do next is create links between
1990      * source and target nodes (which may or may not have been created)
1991      * and set the necessary local variables in each target. The
1992      * commands for each target are set from the commands of the
1993      * transformation rule used to get from the src suffix to the targ
1994      * suffix. Note that this causes the commands list of the original
1995      * node, gn, to be replaced by the commands of the final
1996      * transformation rule. Also, the unmade field of gn is incremented.
1997      * Etc.
1998      */
1999     if (bottom->node == NULL) {
2000 	bottom->node = Targ_FindNode(bottom->file, TARG_CREATE);
2001     }
2002 
2003     for (src = bottom; src->parent != NULL; src = src->parent) {
2004 	targ = src->parent;
2005 
2006 	if (src->node->suffix)
2007 	    src->node->suffix->refCount--;
2008 	src->node->suffix = src->suff;
2009 	src->node->suffix->refCount++;
2010 
2011 	if (targ->node == NULL) {
2012 	    targ->node = Targ_FindNode(targ->file, TARG_CREATE);
2013 	}
2014 
2015 	SuffApplyTransform(targ->node, src->node,
2016 			   targ->suff, src->suff);
2017 
2018 	if (targ->node != gn) {
2019 	    /*
2020 	     * Finish off the dependency-search process for any nodes
2021 	     * between bottom and gn (no point in questing around the
2022 	     * filesystem for their implicit source when it's already
2023 	     * known). Note that the node can't have any sources that
2024 	     * need expanding, since SuffFindThem will stop on an existing
2025 	     * node, so all we need to do is set the standard and System V
2026 	     * variables.
2027 	     */
2028 	    targ->node->type |= OP_DEPS_FOUND;
2029 
2030 	    Var_Set(PREFIX, targ->pref, targ->node);
2031 
2032 	    Var_Set(TARGET, targ->node->name, targ->node);
2033 	}
2034     }
2035 
2036     if (gn->suffix)
2037 	gn->suffix->refCount--;
2038     gn->suffix = src->suff;
2039     gn->suffix->refCount++;
2040 
2041     /*
2042      * Nuke the transformation path and the Src structures left over in the
2043      * two lists.
2044      */
2045 sfnd_return:
2046     if (bottom)
2047 	if (Lst_FindDatum(slst, bottom) == NULL)
2048 	    Lst_Append(slst, bottom);
2049 
2050     while (SuffRemoveSrc(srcs) || SuffRemoveSrc(targs))
2051 	continue;
2052 
2053     Lst_MoveAll(slst, srcs);
2054     Lst_MoveAll(slst, targs);
2055 }
2056 
2057 
2058 /* Find implicit sources for the target described by the graph node.
2059  *
2060  * Nodes are added to the graph below the passed-in node. The nodes are
2061  * marked to have their IMPSRC variable filled in. The PREFIX variable is set
2062  * for the given node and all its implied children.
2063  *
2064  * The path found by this target is the shortest path in the transformation
2065  * graph, which may pass through non-existent targets, to an existing target.
2066  * The search continues on all paths from the root suffix until a file is
2067  * found. I.e. if there's a path .o -> .c -> .l -> .l,v from the root and the
2068  * .l,v file exists but the .c and .l files don't, the search will branch out
2069  * in all directions from .o and again from all the nodes on the next level
2070  * until the .l,v node is encountered.
2071  */
2072 void
2073 Suff_FindDeps(GNode *gn)
2074 {
2075 
2076     SuffFindDeps(gn, srclist);
2077     while (SuffRemoveSrc(srclist))
2078 	continue;
2079 }
2080 
2081 static void
2082 SuffFindDeps(GNode *gn, Lst slst)
2083 {
2084     if (gn->type & OP_DEPS_FOUND)
2085 	return;
2086     gn->type |= OP_DEPS_FOUND;
2087 
2088     /*
2089      * Make sure we have these set, may get revised below.
2090      */
2091     Var_Set(TARGET, gn->path ? gn->path : gn->name, gn);
2092     Var_Set(PREFIX, gn->name, gn);
2093 
2094     SUFF_DEBUG1("SuffFindDeps (%s)\n", gn->name);
2095 
2096     if (gn->type & OP_ARCHV) {
2097 	SuffFindArchiveDeps(gn, slst);
2098     } else if (gn->type & OP_LIB) {
2099 	/*
2100 	 * If the node is a library, it is the arch module's job to find it
2101 	 * and set the TARGET variable accordingly. We merely provide the
2102 	 * search path, assuming all libraries end in ".a" (if the suffix
2103 	 * hasn't been defined, there's nothing we can do for it, so we just
2104 	 * set the TARGET variable to the node's name in order to give it a
2105 	 * value).
2106 	 */
2107 	LstNode	ln;
2108 	Suff	*s;
2109 
2110 	ln = Lst_Find(sufflist, SuffSuffHasName, LIBSUFF);
2111 	if (gn->suffix)
2112 	    gn->suffix->refCount--;
2113 	if (ln != NULL) {
2114 	    gn->suffix = s = LstNode_Datum(ln);
2115 	    gn->suffix->refCount++;
2116 	    Arch_FindLib(gn, s->searchPath);
2117 	} else {
2118 	    gn->suffix = NULL;
2119 	    Var_Set(TARGET, gn->name, gn);
2120 	}
2121 	/*
2122 	 * Because a library (-lfoo) target doesn't follow the standard
2123 	 * filesystem conventions, we don't set the regular variables for
2124 	 * the thing. .PREFIX is simply made empty...
2125 	 */
2126 	Var_Set(PREFIX, "", gn);
2127     } else {
2128 	SuffFindNormalDeps(gn, slst);
2129     }
2130 }
2131 
2132 /* Define which suffix is the null suffix.
2133  *
2134  * Need to handle the changing of the null suffix gracefully so the old
2135  * transformation rules don't just go away.
2136  *
2137  * Input:
2138  *	name		Name of null suffix
2139  */
2140 void
2141 Suff_SetNull(char *name)
2142 {
2143     Suff    *s;
2144     LstNode ln;
2145 
2146     ln = Lst_Find(sufflist, SuffSuffHasName, name);
2147     if (ln != NULL) {
2148 	s = LstNode_Datum(ln);
2149 	if (suffNull != NULL) {
2150 	    suffNull->flags &= ~SUFF_NULL;
2151 	}
2152 	s->flags |= SUFF_NULL;
2153 	/*
2154 	 * XXX: Here's where the transformation mangling would take place
2155 	 */
2156 	suffNull = s;
2157     } else {
2158 	Parse_Error(PARSE_WARNING, "Desired null suffix %s not defined.",
2159 		     name);
2160     }
2161 }
2162 
2163 /* Initialize the suffixes module. */
2164 void
2165 Suff_Init(void)
2166 {
2167 #ifdef CLEANUP
2168     suffClean = Lst_Init();
2169     sufflist = Lst_Init();
2170 #endif
2171     srclist = Lst_Init();
2172     transforms = Lst_Init();
2173 
2174     /*
2175      * Create null suffix for single-suffix rules (POSIX). The thing doesn't
2176      * actually go on the suffix list or everyone will think that's its
2177      * suffix.
2178      */
2179     Suff_ClearSuffixes();
2180 }
2181 
2182 
2183 /* Clean up the suffixes module. */
2184 void
2185 Suff_End(void)
2186 {
2187 #ifdef CLEANUP
2188     Lst_Destroy(sufflist, SuffFree);
2189     Lst_Destroy(suffClean, SuffFree);
2190     if (suffNull)
2191 	SuffFree(suffNull);
2192     Lst_Free(srclist);
2193     Lst_Free(transforms);
2194 #endif
2195 }
2196 
2197 
2198 /********************* DEBUGGING FUNCTIONS **********************/
2199 
2200 static int SuffPrintName(void *s, void *dummy MAKE_ATTR_UNUSED)
2201 {
2202 
2203     fprintf(debug_file, "%s ", ((Suff *)s)->name);
2204     return 0;
2205 }
2206 
2207 static int
2208 SuffPrintSuff(void *sp, void *dummy MAKE_ATTR_UNUSED)
2209 {
2210     Suff    *s = (Suff *)sp;
2211 
2212     fprintf(debug_file, "# `%s' [%d] ", s->name, s->refCount);
2213 
2214     if (s->flags != 0) {
2215 	char flags_buf[SuffFlags_ToStringSize];
2216 
2217 	fprintf(debug_file, " (%s)",
2218 		Enum_FlagsToString(flags_buf, sizeof flags_buf,
2219 				   s->flags, SuffFlags_ToStringSpecs));
2220     }
2221     fputc('\n', debug_file);
2222     fprintf(debug_file, "#\tTo: ");
2223     Lst_ForEach(s->parents, SuffPrintName, NULL);
2224     fputc('\n', debug_file);
2225     fprintf(debug_file, "#\tFrom: ");
2226     Lst_ForEach(s->children, SuffPrintName, NULL);
2227     fputc('\n', debug_file);
2228     fprintf(debug_file, "#\tSearch Path: ");
2229     Dir_PrintPath(s->searchPath);
2230     fputc('\n', debug_file);
2231     return 0;
2232 }
2233 
2234 static int
2235 SuffPrintTrans(void *tp, void *dummy MAKE_ATTR_UNUSED)
2236 {
2237     GNode   *t = (GNode *)tp;
2238 
2239     fprintf(debug_file, "%-16s:", t->name);
2240     Targ_PrintType(t->type);
2241     fputc('\n', debug_file);
2242     Targ_PrintCmds(t);
2243     fputc('\n', debug_file);
2244     return 0;
2245 }
2246 
2247 void
2248 Suff_PrintAll(void)
2249 {
2250     fprintf(debug_file, "#*** Suffixes:\n");
2251     Lst_ForEach(sufflist, SuffPrintSuff, NULL);
2252 
2253     fprintf(debug_file, "#*** Transformations:\n");
2254     Lst_ForEach(transforms, SuffPrintTrans, NULL);
2255 }
2256