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