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