suff.c revision 1.376 1 /* $NetBSD: suff.c,v 1.376 2023/12/30 15:00:56 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.376 2023/12/30 15:00:56 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\"",
1285 p);
1286 p++;
1287 } else {
1288 p += nested_p - p;
1289 }
1290
1291 FStr_Done(&junk);
1292 } else if (p[0] == '\\' && p[1] != '\0') {
1293 /* Escaped something -- skip over it. */
1294 /*
1295 * XXX: In other places, escaping at this syntactical
1296 * position is done by a '$', not a '\'. The '\' is
1297 * only used in variable modifiers.
1298 */
1299 p += 2;
1300 } else {
1301 p++;
1302 }
1303 }
1304
1305 if (p != start) {
1306 /*
1307 * Stuff left over -- add it to the list too
1308 */
1309 GNode *gn = Targ_GetNode(start);
1310 Lst_Append(members, gn);
1311 }
1312 }
1313
1314 /*
1315 * Expand the names of any children of a given node that contain
1316 * expressions or file wildcards into actual targets.
1317 *
1318 * The expanded node is removed from the parent's list of children, and the
1319 * parent's unmade counter is decremented, but other nodes may be added.
1320 *
1321 * Input:
1322 * cln Child to examine
1323 * pgn Parent node being processed
1324 */
1325 static void
1326 ExpandChildren(GNodeListNode *cln, GNode *pgn)
1327 {
1328 GNode *cgn = cln->datum;
1329 char *expanded;
1330
1331 if (!Lst_IsEmpty(&cgn->order_pred) || !Lst_IsEmpty(&cgn->order_succ))
1332 /* It is all too hard to process the result of .ORDER */
1333 return;
1334
1335 if (cgn->type & OP_WAIT)
1336 /* Ignore these (& OP_PHONY ?) */
1337 return;
1338
1339 /*
1340 * First do variable expansion -- this takes precedence over wildcard
1341 * expansion. If the result contains wildcards, they'll be gotten to
1342 * later since the resulting words are tacked on to the end of the
1343 * children list.
1344 */
1345 if (strchr(cgn->name, '$') == NULL) {
1346 ExpandWildcards(cln, pgn);
1347 return;
1348 }
1349
1350 DEBUG1(SUFF, "Expanding \"%s\"...", cgn->name);
1351 expanded = Var_Subst(cgn->name, pgn, VARE_UNDEFERR);
1352 /* TODO: handle errors */
1353
1354 {
1355 GNodeList members = LST_INIT;
1356
1357 if (cgn->type & OP_ARCHV) {
1358 /*
1359 * Node was an 'archive(member)' target, so
1360 * call on the Arch module to find the nodes for us,
1361 * expanding variables in the parent's scope.
1362 */
1363 char *ap = expanded;
1364 (void)Arch_ParseArchive(&ap, &members, pgn);
1365 } else {
1366 ExpandChildrenRegular(expanded, pgn, &members);
1367 }
1368
1369 /* Add all members to the parent node. */
1370 while (!Lst_IsEmpty(&members)) {
1371 GNode *gn = Lst_Dequeue(&members);
1372
1373 DEBUG1(SUFF, "%s...", gn->name);
1374 Lst_InsertBefore(&pgn->children, cln, gn);
1375 Lst_Append(&gn->parents, pgn);
1376 pgn->unmade++;
1377 ExpandWildcards(cln->prev, pgn);
1378 }
1379 Lst_Done(&members);
1380
1381 free(expanded);
1382 }
1383
1384 DEBUG0(SUFF, "\n");
1385
1386 /*
1387 * The source is expanded now, so remove it from the list of children,
1388 * to keep it from being processed.
1389 */
1390 pgn->unmade--;
1391 Lst_Remove(&pgn->children, cln);
1392 Lst_Remove(&cgn->parents, Lst_FindDatum(&cgn->parents, pgn));
1393 }
1394
1395 static void
1396 ExpandAllChildren(GNode *gn)
1397 {
1398 GNodeListNode *ln, *nln;
1399
1400 for (ln = gn->children.first; ln != NULL; ln = nln) {
1401 nln = ln->next;
1402 ExpandChildren(ln, gn);
1403 }
1404 }
1405
1406 /*
1407 * Find a path along which to search or expand the node.
1408 *
1409 * If the node has a known suffix, use that path,
1410 * otherwise use the default system search path.
1411 */
1412 SearchPath *
1413 Suff_FindPath(GNode *gn)
1414 {
1415 Suffix *suff = gn->suffix;
1416
1417 if (suff == NULL) {
1418 char *name = gn->name;
1419 size_t nameLen = strlen(gn->name);
1420 SuffixListNode *ln;
1421 for (ln = sufflist.first; ln != NULL; ln = ln->next)
1422 if (Suffix_IsSuffix(ln->datum, nameLen, name + nameLen))
1423 break;
1424
1425 DEBUG1(SUFF, "Wildcard expanding \"%s\"...", gn->name);
1426 if (ln != NULL)
1427 suff = ln->datum;
1428 /*
1429 * XXX: Here we can save the suffix so we don't have to do
1430 * this again.
1431 */
1432 }
1433
1434 if (suff != NULL) {
1435 DEBUG1(SUFF, "suffix is \"%s\"...\n", suff->name);
1436 return suff->searchPath;
1437 } else {
1438 DEBUG0(SUFF, "\n");
1439 return &dirSearchPath; /* Use default search path */
1440 }
1441 }
1442
1443 /*
1444 * Apply a transformation rule, given the source and target nodes and
1445 * suffixes.
1446 *
1447 * The source and target are linked and the commands from the transformation
1448 * are added to the target node's commands list. The target also inherits all
1449 * the sources for the transformation rule.
1450 *
1451 * Results:
1452 * true if successful, false if not.
1453 */
1454 static bool
1455 ApplyTransform(GNode *tgn, GNode *sgn, Suffix *tsuff, Suffix *ssuff)
1456 {
1457 GNodeListNode *ln;
1458 char *tname; /* Name of transformation rule */
1459 GNode *gn; /* Node for the transformation rule */
1460
1461 /* Form the proper links between the target and source. */
1462 Lst_Append(&tgn->children, sgn);
1463 Lst_Append(&sgn->parents, tgn);
1464 tgn->unmade++;
1465
1466 /* Locate the transformation rule itself. */
1467 tname = str_concat2(ssuff->name, tsuff->name);
1468 gn = FindTransformByName(tname);
1469 free(tname);
1470
1471 /* This can happen when linking an OP_MEMBER and OP_ARCHV node. */
1472 if (gn == NULL)
1473 return false;
1474
1475 DEBUG3(SUFF, "\tapplying %s -> %s to \"%s\"\n",
1476 ssuff->name, tsuff->name, tgn->name);
1477
1478 /* Record last child; Make_HandleUse may add child nodes. */
1479 ln = tgn->children.last;
1480
1481 /* Apply the rule. */
1482 Make_HandleUse(gn, tgn);
1483
1484 /* Deal with wildcards and expressions in any acquired sources. */
1485 ln = ln != NULL ? ln->next : NULL;
1486 while (ln != NULL) {
1487 GNodeListNode *nln = ln->next;
1488 ExpandChildren(ln, tgn);
1489 ln = nln;
1490 }
1491
1492 /*
1493 * Keep track of another parent to which this node is transformed so
1494 * the .IMPSRC variable can be set correctly for the parent.
1495 */
1496 Lst_Append(&sgn->implicitParents, tgn);
1497
1498 return true;
1499 }
1500
1501 /*
1502 * Member has a known suffix, so look for a transformation rule from
1503 * it to a possible suffix of the archive.
1504 *
1505 * Rather than searching through the entire list, we just look at
1506 * suffixes to which the member's suffix may be transformed.
1507 */
1508 static void
1509 ExpandMember(GNode *gn, const char *eoarch, GNode *mem, Suffix *memSuff)
1510 {
1511 SuffixListNode *ln;
1512 size_t nameLen = (size_t)(eoarch - gn->name);
1513
1514 /* Use first matching suffix... */
1515 for (ln = memSuff->parents.first; ln != NULL; ln = ln->next)
1516 if (Suffix_IsSuffix(ln->datum, nameLen, eoarch))
1517 break;
1518
1519 if (ln != NULL) {
1520 Suffix *suff = ln->datum;
1521 if (!ApplyTransform(gn, mem, suff, memSuff)) {
1522 DEBUG2(SUFF, "\tNo transformation from %s -> %s\n",
1523 memSuff->name, suff->name);
1524 }
1525 }
1526 }
1527
1528 static void FindDeps(GNode *, CandidateSearcher *);
1529
1530 /*
1531 * Locate dependencies for an OP_ARCHV node.
1532 *
1533 * Side Effects:
1534 * Same as Suff_FindDeps
1535 */
1536 static void
1537 FindDepsArchive(GNode *gn, CandidateSearcher *cs)
1538 {
1539 char *eoarch; /* End of archive portion */
1540 char *eoname; /* End of member portion */
1541 GNode *mem; /* Node for member */
1542 Suffix *memSuff;
1543 const char *name; /* Start of member's name */
1544
1545 /*
1546 * The node is an 'archive(member)' pair, so we must find a
1547 * suffix for both of them.
1548 */
1549 eoarch = strchr(gn->name, '(');
1550 eoname = strchr(eoarch, ')');
1551
1552 /*
1553 * Caller guarantees the format `libname(member)', via
1554 * Arch_ParseArchive.
1555 */
1556 assert(eoarch != NULL);
1557 assert(eoname != NULL);
1558
1559 *eoname = '\0'; /* Nuke parentheses during suffix search */
1560 *eoarch = '\0'; /* So a suffix can be found */
1561
1562 name = eoarch + 1;
1563
1564 /*
1565 * To simplify things, call Suff_FindDeps recursively on the member
1566 * now, so we can simply compare the member's .PREFIX and .TARGET
1567 * variables to locate its suffix. This allows us to figure out the
1568 * suffix to use for the archive without having to do a quadratic
1569 * search over the suffix list, backtracking for each one.
1570 */
1571 mem = Targ_GetNode(name);
1572 FindDeps(mem, cs);
1573
1574 /* Create the link between the two nodes right off. */
1575 Lst_Append(&gn->children, mem);
1576 Lst_Append(&mem->parents, gn);
1577 gn->unmade++;
1578
1579 /* Copy in the variables from the member node to this one. */
1580 Var_Set(gn, PREFIX, GNode_VarPrefix(mem));
1581 Var_Set(gn, TARGET, GNode_VarTarget(mem));
1582
1583 memSuff = mem->suffix;
1584 if (memSuff == NULL) { /* Didn't know what it was. */
1585 DEBUG0(SUFF, "using null suffix\n");
1586 memSuff = nullSuff;
1587 }
1588
1589
1590 /* Set the other two local variables required for this target. */
1591 Var_Set(gn, MEMBER, name);
1592 Var_Set(gn, ARCHIVE, gn->name);
1593 /* Set $@ for compatibility with other makes. */
1594 Var_Set(gn, TARGET, gn->name);
1595
1596 /*
1597 * Now we've got the important local variables set, expand any sources
1598 * that still contain variables or wildcards in their names.
1599 */
1600 ExpandAllChildren(gn);
1601
1602 if (memSuff != NULL)
1603 ExpandMember(gn, eoarch, mem, memSuff);
1604
1605 /*
1606 * Replace the opening and closing parens now we've no need of the
1607 * separate pieces.
1608 */
1609 *eoarch = '(';
1610 *eoname = ')';
1611
1612 /*
1613 * Pretend gn appeared to the left of a dependency operator so the
1614 * user needn't provide a transformation from the member to the
1615 * archive.
1616 */
1617 if (!GNode_IsTarget(gn))
1618 gn->type |= OP_DEPENDS;
1619
1620 /*
1621 * Flag the member as such so we remember to look in the archive for
1622 * its modification time. The OP_JOIN | OP_MADE is needed because
1623 * this target should never get made.
1624 */
1625 mem->type |= OP_MEMBER | OP_JOIN | OP_MADE;
1626 }
1627
1628 /*
1629 * If the node is a library, it is the arch module's job to find it
1630 * and set the TARGET variable accordingly. We merely provide the
1631 * search path, assuming all libraries end in ".a" (if the suffix
1632 * hasn't been defined, there's nothing we can do for it, so we just
1633 * set the TARGET variable to the node's name in order to give it a
1634 * value).
1635 */
1636 static void
1637 FindDepsLib(GNode *gn)
1638 {
1639 Suffix *suff = FindSuffixByName(LIBSUFF);
1640 if (suff != NULL) {
1641 Suffix_Reassign(&gn->suffix, suff);
1642 Arch_FindLib(gn, suff->searchPath);
1643 } else {
1644 Suffix_Unassign(&gn->suffix);
1645 Var_Set(gn, TARGET, gn->name);
1646 }
1647
1648 /*
1649 * Because a library (-lfoo) target doesn't follow the standard
1650 * filesystem conventions, we don't set the regular variables for
1651 * the thing. .PREFIX is simply made empty.
1652 */
1653 Var_Set(gn, PREFIX, "");
1654 }
1655
1656 static void
1657 FindDepsRegularKnown(const char *name, size_t nameLen, GNode *gn,
1658 CandidateList *srcs, CandidateList *targs)
1659 {
1660 SuffixListNode *ln;
1661 Candidate *targ;
1662 char *pref;
1663
1664 for (ln = sufflist.first; ln != NULL; ln = ln->next) {
1665 Suffix *suff = ln->datum;
1666 if (!Suffix_IsSuffix(suff, nameLen, name + nameLen))
1667 continue;
1668
1669 pref = bmake_strldup(name, (size_t)(nameLen - suff->nameLen));
1670 targ = Candidate_New(bmake_strdup(gn->name), pref, suff, NULL,
1671 gn);
1672
1673 CandidateList_AddCandidatesFor(srcs, targ);
1674
1675 /* Record the target so we can nuke it. */
1676 Lst_Append(targs, targ);
1677 }
1678 }
1679
1680 static void
1681 FindDepsRegularUnknown(GNode *gn, const char *sopref,
1682 CandidateList *srcs, CandidateList *targs)
1683 {
1684 Candidate *targ;
1685
1686 if (!Lst_IsEmpty(targs) || nullSuff == NULL)
1687 return;
1688
1689 DEBUG1(SUFF, "\tNo known suffix on %s. Using .NULL suffix\n", gn->name);
1690
1691 targ = Candidate_New(bmake_strdup(gn->name), bmake_strdup(sopref),
1692 nullSuff, NULL, gn);
1693
1694 /*
1695 * Only use the default suffix rules if we don't have commands
1696 * defined for this gnode; traditional make programs used to not
1697 * define suffix rules if the gnode had children but we don't do
1698 * this anymore.
1699 */
1700 if (Lst_IsEmpty(&gn->commands))
1701 CandidateList_AddCandidatesFor(srcs, targ);
1702 else {
1703 DEBUG0(SUFF, "not ");
1704 }
1705
1706 DEBUG0(SUFF, "adding suffix rules\n");
1707
1708 Lst_Append(targs, targ);
1709 }
1710
1711 /*
1712 * Deal with finding the thing on the default search path. We always do
1713 * that, not only if the node is only a source (not on the lhs of a
1714 * dependency operator or [XXX] it has neither children or commands) as
1715 * the old pmake did.
1716 */
1717 static void
1718 FindDepsRegularPath(GNode *gn, Candidate *targ)
1719 {
1720 if (gn->type & (OP_PHONY | OP_NOPATH))
1721 return;
1722
1723 free(gn->path);
1724 gn->path = Dir_FindFile(gn->name,
1725 targ == NULL ? &dirSearchPath : targ->suff->searchPath);
1726 if (gn->path == NULL)
1727 return;
1728
1729 Var_Set(gn, TARGET, gn->path);
1730
1731 if (targ != NULL) {
1732 /*
1733 * Suffix known for the thing -- trim the suffix off
1734 * the path to form the proper .PREFIX variable.
1735 */
1736 size_t savep = strlen(gn->path) - targ->suff->nameLen;
1737 char savec;
1738
1739 Suffix_Reassign(&gn->suffix, targ->suff);
1740
1741 savec = gn->path[savep];
1742 gn->path[savep] = '\0';
1743
1744 Var_Set(gn, PREFIX, str_basename(gn->path));
1745
1746 gn->path[savep] = savec;
1747 } else {
1748 /*
1749 * The .PREFIX gets the full path if the target has no
1750 * known suffix.
1751 */
1752 Suffix_Unassign(&gn->suffix);
1753 Var_Set(gn, PREFIX, str_basename(gn->path));
1754 }
1755 }
1756
1757 /*
1758 * Locate implicit dependencies for regular targets.
1759 *
1760 * Input:
1761 * gn Node for which to find sources
1762 *
1763 * Side Effects:
1764 * Same as Suff_FindDeps
1765 */
1766 static void
1767 FindDepsRegular(GNode *gn, CandidateSearcher *cs)
1768 {
1769 /* List of sources at which to look */
1770 CandidateList srcs = LST_INIT;
1771 /*
1772 * List of targets to which things can be transformed.
1773 * They all have the same file, but different suff and prefix fields.
1774 */
1775 CandidateList targs = LST_INIT;
1776 Candidate *bottom; /* Start of found transformation path */
1777 Candidate *src;
1778 Candidate *targ;
1779
1780 const char *name = gn->name;
1781 size_t nameLen = strlen(name);
1782
1783 #ifdef DEBUG_SRC
1784 DEBUG1(SUFF, "FindDepsRegular \"%s\"\n", gn->name);
1785 #endif
1786
1787 /*
1788 * We're caught in a catch-22 here. On the one hand, we want to use
1789 * any transformation implied by the target's sources, but we can't
1790 * examine the sources until we've expanded any variables/wildcards
1791 * they may hold, and we can't do that until we've set up the
1792 * target's local variables and we can't do that until we know what
1793 * the proper suffix for the target is (in case there are two
1794 * suffixes one of which is a suffix of the other) and we can't know
1795 * that until we've found its implied source, which we may not want
1796 * to use if there's an existing source that implies a different
1797 * transformation.
1798 *
1799 * In an attempt to get around this, which may not work all the time,
1800 * but should work most of the time, we look for implied sources
1801 * first, checking transformations to all possible suffixes of the
1802 * target, use what we find to set the target's local variables,
1803 * expand the children, then look for any overriding transformations
1804 * they imply. Should we find one, we discard the one we found before.
1805 */
1806 bottom = NULL;
1807 targ = NULL;
1808
1809 if (!(gn->type & OP_PHONY)) {
1810
1811 FindDepsRegularKnown(name, nameLen, gn, &srcs, &targs);
1812
1813 /* Handle target of unknown suffix... */
1814 FindDepsRegularUnknown(gn, name, &srcs, &targs);
1815
1816 /*
1817 * Using the list of possible sources built up from the target
1818 * suffix(es), try and find an existing file/target that
1819 * matches.
1820 */
1821 bottom = FindThem(&srcs, cs);
1822
1823 if (bottom == NULL) {
1824 /*
1825 * No known transformations -- use the first suffix
1826 * found for setting the local variables.
1827 */
1828 if (targs.first != NULL)
1829 targ = targs.first->datum;
1830 else
1831 targ = NULL;
1832 } else {
1833 /*
1834 * Work up the transformation path to find the suffix
1835 * of the target to which the transformation was made.
1836 */
1837 for (targ = bottom;
1838 targ->parent != NULL; targ = targ->parent)
1839 continue;
1840 }
1841 }
1842
1843 Var_Set(gn, TARGET, GNode_Path(gn));
1844 Var_Set(gn, PREFIX, targ != NULL ? targ->prefix : gn->name);
1845
1846 /*
1847 * Now we've got the important local variables set, expand any sources
1848 * that still contain variables or wildcards in their names.
1849 */
1850 {
1851 GNodeListNode *ln, *nln;
1852 for (ln = gn->children.first; ln != NULL; ln = nln) {
1853 nln = ln->next;
1854 ExpandChildren(ln, gn);
1855 }
1856 }
1857
1858 if (targ == NULL) {
1859 DEBUG1(SUFF, "\tNo valid suffix on %s\n", gn->name);
1860
1861 sfnd_abort:
1862 FindDepsRegularPath(gn, targ);
1863 goto sfnd_return;
1864 }
1865
1866 /*
1867 * If the suffix indicates that the target is a library, mark that in
1868 * the node's type field.
1869 */
1870 if (targ->suff->library)
1871 gn->type |= OP_LIB;
1872
1873 /*
1874 * Check for overriding transformation rule implied by sources
1875 */
1876 if (!Lst_IsEmpty(&gn->children)) {
1877 src = FindCmds(targ, cs);
1878
1879 if (src != NULL) {
1880 /*
1881 * Free up all the candidates in the transformation
1882 * path, up to but not including the parent node.
1883 */
1884 while (bottom != NULL && bottom->parent != NULL) {
1885 CandidateSearcher_AddIfNew(cs, bottom);
1886 bottom = bottom->parent;
1887 }
1888 bottom = src;
1889 }
1890 }
1891
1892 if (bottom == NULL) {
1893 /* No idea from where it can come -- return now. */
1894 goto sfnd_abort;
1895 }
1896
1897 /*
1898 * We now have a list of candidates headed by 'bottom' and linked via
1899 * their 'parent' pointers. What we do next is create links between
1900 * source and target nodes (which may or may not have been created)
1901 * and set the necessary local variables in each target.
1902 *
1903 * The commands for each target are set from the commands of the
1904 * transformation rule used to get from the src suffix to the targ
1905 * suffix. Note that this causes the commands list of the original
1906 * node, gn, to be replaced with the commands of the final
1907 * transformation rule.
1908 */
1909 if (bottom->node == NULL)
1910 bottom->node = Targ_GetNode(bottom->file);
1911
1912 for (src = bottom; src->parent != NULL; src = src->parent) {
1913 targ = src->parent;
1914
1915 Suffix_Reassign(&src->node->suffix, src->suff);
1916
1917 if (targ->node == NULL)
1918 targ->node = Targ_GetNode(targ->file);
1919
1920 ApplyTransform(targ->node, src->node,
1921 targ->suff, src->suff);
1922
1923 if (targ->node != gn) {
1924 /*
1925 * Finish off the dependency-search process for any
1926 * nodes between bottom and gn (no point in questing
1927 * around the filesystem for their implicit source
1928 * when it's already known). Note that the node
1929 * can't have any sources that need expanding, since
1930 * SuffFindThem will stop on an existing node, so all
1931 * we need to do is set the standard variables.
1932 */
1933 targ->node->type |= OP_DEPS_FOUND;
1934 Var_Set(targ->node, PREFIX, targ->prefix);
1935 Var_Set(targ->node, TARGET, targ->node->name);
1936 }
1937 }
1938
1939 Suffix_Reassign(&gn->suffix, src->suff);
1940
1941 /*
1942 * Nuke the transformation path and the candidates left over in the
1943 * two lists.
1944 */
1945 sfnd_return:
1946 if (bottom != NULL)
1947 CandidateSearcher_AddIfNew(cs, bottom);
1948
1949 while (RemoveCandidate(&srcs) || RemoveCandidate(&targs))
1950 continue;
1951
1952 CandidateSearcher_MoveAll(cs, &srcs);
1953 CandidateSearcher_MoveAll(cs, &targs);
1954 }
1955
1956 static void
1957 CandidateSearcher_CleanUp(CandidateSearcher *cs)
1958 {
1959 while (RemoveCandidate(&cs->list))
1960 continue;
1961 assert(Lst_IsEmpty(&cs->list));
1962 }
1963
1964
1965 /*
1966 * Find implicit sources for the target.
1967 *
1968 * Nodes are added to the graph as children of the passed-in node. The nodes
1969 * are marked to have their IMPSRC variable filled in. The PREFIX variable
1970 * is set for the given node and all its implied children.
1971 *
1972 * The path found by this target is the shortest path in the transformation
1973 * graph, which may pass through nonexistent targets, to an existing target.
1974 * The search continues on all paths from the root suffix until a file is
1975 * found. I.e. if there's a path .o -> .c -> .l -> .l,v from the root and the
1976 * .l,v file exists but the .c and .l files don't, the search will branch out
1977 * in all directions from .o and again from all the nodes on the next level
1978 * until the .l,v node is encountered.
1979 */
1980 void
1981 Suff_FindDeps(GNode *gn)
1982 {
1983 CandidateSearcher cs;
1984
1985 CandidateSearcher_Init(&cs);
1986
1987 FindDeps(gn, &cs);
1988
1989 CandidateSearcher_CleanUp(&cs);
1990 CandidateSearcher_Done(&cs);
1991 }
1992
1993 static void
1994 FindDeps(GNode *gn, CandidateSearcher *cs)
1995 {
1996 if (gn->type & OP_DEPS_FOUND)
1997 return;
1998 gn->type |= OP_DEPS_FOUND;
1999
2000 /* Make sure we have these set, may get revised below. */
2001 Var_Set(gn, TARGET, GNode_Path(gn));
2002 Var_Set(gn, PREFIX, gn->name);
2003
2004 DEBUG1(SUFF, "SuffFindDeps \"%s\"\n", gn->name);
2005
2006 if (gn->type & OP_ARCHV)
2007 FindDepsArchive(gn, cs);
2008 else if (gn->type & OP_LIB)
2009 FindDepsLib(gn);
2010 else
2011 FindDepsRegular(gn, cs);
2012 }
2013
2014 /*
2015 * Define which suffix is the null suffix.
2016 *
2017 * Need to handle the changing of the null suffix gracefully so the old
2018 * transformation rules don't just go away.
2019 */
2020 void
2021 Suff_SetNull(const char *name)
2022 {
2023 Suffix *suff = FindSuffixByName(name);
2024 if (suff == NULL) {
2025 Parse_Error(PARSE_WARNING,
2026 "Desired null suffix %s not defined",
2027 name);
2028 return;
2029 }
2030
2031 if (nullSuff != NULL)
2032 nullSuff->isNull = false;
2033 suff->isNull = true;
2034 /* XXX: Here's where the transformation mangling would take place. */
2035 nullSuff = suff;
2036 }
2037
2038 /* Initialize the suffixes module. */
2039 void
2040 Suff_Init(void)
2041 {
2042 /*
2043 * Create null suffix for single-suffix rules (POSIX). The thing
2044 * doesn't actually go on the suffix list or everyone will think
2045 * that's its suffix.
2046 */
2047 Suff_ClearSuffixes();
2048 }
2049
2050 /* Clean up the suffixes module. */
2051 void
2052 Suff_End(void)
2053 {
2054 #ifdef CLEANUP
2055 SuffixListNode *ln;
2056
2057 for (ln = sufflist.first; ln != NULL; ln = ln->next)
2058 Suffix_Free(ln->datum);
2059 Lst_Done(&sufflist);
2060 for (ln = suffClean.first; ln != NULL; ln = ln->next)
2061 Suffix_Free(ln->datum);
2062 Lst_Done(&suffClean);
2063 if (nullSuff != NULL)
2064 Suffix_Free(nullSuff);
2065 Lst_Done(&transforms);
2066 #endif
2067 }
2068
2069
2070 static void
2071 PrintSuffNames(const char *prefix, const SuffixList *suffs)
2072 {
2073 SuffixListNode *ln;
2074
2075 debug_printf("#\t%s: ", prefix);
2076 for (ln = suffs->first; ln != NULL; ln = ln->next) {
2077 const Suffix *suff = ln->datum;
2078 debug_printf("%s ", suff->name);
2079 }
2080 debug_printf("\n");
2081 }
2082
2083 static void
2084 Suffix_Print(const Suffix *suff)
2085 {
2086 Buffer buf;
2087
2088 Buf_Init(&buf);
2089 Buf_AddFlag(&buf, suff->include, "SUFF_INCLUDE");
2090 Buf_AddFlag(&buf, suff->library, "SUFF_LIBRARY");
2091 Buf_AddFlag(&buf, suff->isNull, "SUFF_NULL");
2092
2093 debug_printf("# \"%s\" (num %d, ref %d)",
2094 suff->name, suff->sNum, suff->refCount);
2095 if (buf.len > 0)
2096 debug_printf(" (%s)", buf.data);
2097 debug_printf("\n");
2098
2099 Buf_Done(&buf);
2100
2101 PrintSuffNames("To", &suff->parents);
2102 PrintSuffNames("From", &suff->children);
2103
2104 debug_printf("#\tSearch Path: ");
2105 SearchPath_Print(suff->searchPath);
2106 debug_printf("\n");
2107 }
2108
2109 static void
2110 PrintTransformation(GNode *t)
2111 {
2112 debug_printf("%-16s:", t->name);
2113 Targ_PrintType(t->type);
2114 debug_printf("\n");
2115 Targ_PrintCmds(t);
2116 debug_printf("\n");
2117 }
2118
2119 void
2120 Suff_PrintAll(void)
2121 {
2122 debug_printf("#*** Suffixes:\n");
2123 {
2124 SuffixListNode *ln;
2125 for (ln = sufflist.first; ln != NULL; ln = ln->next)
2126 Suffix_Print(ln->datum);
2127 }
2128
2129 debug_printf("#*** Transformations:\n");
2130 {
2131 GNodeListNode *ln;
2132 for (ln = transforms.first; ln != NULL; ln = ln->next)
2133 PrintTransformation(ln->datum);
2134 }
2135 }
2136
2137 char *
2138 Suff_NamesStr(void)
2139 {
2140 Buffer buf;
2141 SuffixListNode *ln;
2142 Suffix *suff;
2143
2144 Buf_Init(&buf);
2145 for (ln = sufflist.first; ln != NULL; ln = ln->next) {
2146 suff = ln->datum;
2147 if (ln != sufflist.first)
2148 Buf_AddByte(&buf, ' ');
2149 Buf_AddStr(&buf, suff->name);
2150 }
2151 return Buf_DoneData(&buf);
2152 }
2153