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