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