suff.c revision 1.380 1 /* $NetBSD: suff.c,v 1.380 2024/06/02 15:31:26 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.380 2024/06/02 15:31:26 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 if (suff->include)
860 SearchPath_AddAll(includesPath,
861 suff->searchPath);
862 if (suff->library)
863 SearchPath_AddAll(libsPath, suff->searchPath);
864 SearchPath_AddAll(suff->searchPath, &dirSearchPath);
865 } else {
866 SearchPath_Free(suff->searchPath);
867 suff->searchPath = Dir_CopyDirSearchPath();
868 }
869 }
870
871 flags = SearchPath_ToFlags(includesPath, "-I");
872 Global_Set(".INCLUDES", flags);
873 free(flags);
874
875 flags = SearchPath_ToFlags(libsPath, "-L");
876 Global_Set(".LIBS", flags);
877 free(flags);
878
879 SearchPath_Free(includesPath);
880 SearchPath_Free(libsPath);
881 }
882
883 /*
884 * Add the given suffix as a type of file which gets included.
885 * Called when a '.INCLUDES: .h' line is parsed.
886 * To have an effect, the suffix must already exist.
887 * This affects the magic variable '.INCLUDES'.
888 */
889 void
890 Suff_AddInclude(const char *suffName)
891 {
892 Suffix *suff = FindSuffixByName(suffName);
893 if (suff != NULL)
894 suff->include = true;
895 }
896
897 /*
898 * Add the given suffix as a type of file which is a library.
899 * Called when a '.LIBS: .a' line is parsed.
900 * To have an effect, the suffix must already exist.
901 * This affects the magic variable '.LIBS'.
902 */
903 void
904 Suff_AddLib(const char *suffName)
905 {
906 Suffix *suff = FindSuffixByName(suffName);
907 if (suff != NULL)
908 suff->library = true;
909 }
910
911 /********** Implicit Source Search Functions *********/
912
913 static void
914 CandidateSearcher_Init(CandidateSearcher *cs)
915 {
916 Lst_Init(&cs->list);
917 }
918
919 static void
920 CandidateSearcher_Done(CandidateSearcher *cs)
921 {
922 Lst_Done(&cs->list);
923 }
924
925 static void
926 CandidateSearcher_Add(CandidateSearcher *cs, Candidate *cand)
927 {
928 /* TODO: filter duplicates */
929 Lst_Append(&cs->list, cand);
930 }
931
932 static void
933 CandidateSearcher_AddIfNew(CandidateSearcher *cs, Candidate *cand)
934 {
935 /* TODO: filter duplicates */
936 if (Lst_FindDatum(&cs->list, cand) == NULL)
937 Lst_Append(&cs->list, cand);
938 }
939
940 static void
941 CandidateSearcher_MoveAll(CandidateSearcher *cs, CandidateList *list)
942 {
943 /* TODO: filter duplicates */
944 Lst_MoveAll(&cs->list, list);
945 }
946
947
948 #ifdef DEBUG_SRC
949 static void
950 CandidateList_PrintAddrs(CandidateList *list)
951 {
952 CandidateListNode *ln;
953
954 for (ln = list->first; ln != NULL; ln = ln->next) {
955 Candidate *cand = ln->datum;
956 debug_printf(" %p:%s", cand, cand->file);
957 }
958 debug_printf("\n");
959 }
960 #endif
961
962 static Candidate *
963 Candidate_New(char *name, char *prefix, Suffix *suff, Candidate *parent,
964 GNode *gn)
965 {
966 Candidate *cand = bmake_malloc(sizeof *cand);
967
968 cand->file = name;
969 cand->prefix = prefix;
970 cand->suff = Suffix_Ref(suff);
971 cand->parent = parent;
972 cand->node = gn;
973 cand->numChildren = 0;
974 #ifdef DEBUG_SRC
975 Lst_Init(&cand->childrenList);
976 #endif
977
978 return cand;
979 }
980
981 /* Add a new candidate to the list. */
982 /*ARGSUSED*/
983 static void
984 CandidateList_Add(CandidateList *list, char *srcName, Candidate *targ,
985 Suffix *suff, const char *debug_tag MAKE_ATTR_UNUSED)
986 {
987 Candidate *cand = Candidate_New(srcName, targ->prefix, suff, targ,
988 NULL);
989 targ->numChildren++;
990 Lst_Append(list, cand);
991
992 #ifdef DEBUG_SRC
993 Lst_Append(&targ->childrenList, cand);
994 debug_printf("%s add suff %p:%s candidate %p:%s to list %p:",
995 debug_tag, targ, targ->file, cand, cand->file, list);
996 CandidateList_PrintAddrs(list);
997 #endif
998 }
999
1000 /*
1001 * Add all candidates to the list that can be formed by applying a suffix to
1002 * the candidate.
1003 */
1004 static void
1005 CandidateList_AddCandidatesFor(CandidateList *list, Candidate *cand)
1006 {
1007 SuffixListNode *ln;
1008 for (ln = cand->suff->children.first; ln != NULL; ln = ln->next) {
1009 Suffix *suff = ln->datum;
1010
1011 if (suff->isNull && suff->name[0] != '\0') {
1012 /*
1013 * If the suffix has been marked as the NULL suffix,
1014 * also create a candidate for a file with no suffix
1015 * attached.
1016 */
1017 CandidateList_Add(list, bmake_strdup(cand->prefix),
1018 cand, suff, "1");
1019 }
1020
1021 CandidateList_Add(list, str_concat2(cand->prefix, suff->name),
1022 cand, suff, "2");
1023 }
1024 }
1025
1026 /*
1027 * Free the first candidate in the list that is not referenced anymore.
1028 * Return whether a candidate was removed.
1029 */
1030 static bool
1031 RemoveCandidate(CandidateList *srcs)
1032 {
1033 CandidateListNode *ln;
1034
1035 #ifdef DEBUG_SRC
1036 debug_printf("cleaning list %p:", srcs);
1037 CandidateList_PrintAddrs(srcs);
1038 #endif
1039
1040 for (ln = srcs->first; ln != NULL; ln = ln->next) {
1041 Candidate *src = ln->datum;
1042
1043 if (src->numChildren == 0) {
1044 if (src->parent == NULL)
1045 free(src->prefix);
1046 else {
1047 #ifdef DEBUG_SRC
1048 /* XXX: Lst_RemoveDatum */
1049 CandidateListNode *ln2;
1050 ln2 = Lst_FindDatum(&src->parent->childrenList,
1051 src);
1052 if (ln2 != NULL)
1053 Lst_Remove(&src->parent->childrenList,
1054 ln2);
1055 #endif
1056 src->parent->numChildren--;
1057 }
1058 #ifdef DEBUG_SRC
1059 debug_printf("free: list %p src %p:%s children %d\n",
1060 srcs, src, src->file, src->numChildren);
1061 Lst_Done(&src->childrenList);
1062 #endif
1063 Lst_Remove(srcs, ln);
1064 free(src->file);
1065 free(src);
1066 return true;
1067 }
1068 #ifdef DEBUG_SRC
1069 else {
1070 debug_printf("keep: list %p src %p:%s children %d:",
1071 srcs, src, src->file, src->numChildren);
1072 CandidateList_PrintAddrs(&src->childrenList);
1073 }
1074 #endif
1075 }
1076
1077 return false;
1078 }
1079
1080 /* Find the first existing file/target in srcs. */
1081 static Candidate *
1082 FindThem(CandidateList *srcs, CandidateSearcher *cs)
1083 {
1084 HashSet seen;
1085
1086 HashSet_Init(&seen);
1087
1088 while (!Lst_IsEmpty(srcs)) {
1089 Candidate *src = Lst_Dequeue(srcs);
1090
1091 #ifdef DEBUG_SRC
1092 debug_printf("remove from list %p src %p:%s\n",
1093 srcs, src, src->file);
1094 #endif
1095 DEBUG1(SUFF, "\ttrying %s...", src->file);
1096
1097 /*
1098 * A file is considered to exist if either a node exists in the
1099 * graph for it or the file actually exists.
1100 */
1101 if (Targ_FindNode(src->file) != NULL) {
1102 found:
1103 HashSet_Done(&seen);
1104 DEBUG0(SUFF, "got it\n");
1105 return src;
1106 }
1107
1108 {
1109 char *file = Dir_FindFile(src->file,
1110 src->suff->searchPath);
1111 if (file != NULL) {
1112 free(file);
1113 goto found;
1114 }
1115 }
1116
1117 DEBUG0(SUFF, "not there\n");
1118
1119 if (HashSet_Add(&seen, src->file))
1120 CandidateList_AddCandidatesFor(srcs, src);
1121 else {
1122 DEBUG1(SUFF, "FindThem: skipping duplicate \"%s\"\n",
1123 src->file);
1124 }
1125
1126 CandidateSearcher_Add(cs, src);
1127 }
1128
1129 HashSet_Done(&seen);
1130 return NULL;
1131 }
1132
1133 /*
1134 * See if any of the children of the candidate's GNode is one from which the
1135 * target can be transformed. If there is one, a candidate is put together
1136 * for it and returned.
1137 */
1138 static Candidate *
1139 FindCmds(Candidate *targ, CandidateSearcher *cs)
1140 {
1141 GNodeListNode *gln;
1142 GNode *tgn; /* Target GNode */
1143 GNode *sgn; /* Source GNode */
1144 size_t prefLen; /* The length of the defined prefix */
1145 Suffix *suff; /* Suffix of the matching candidate */
1146 Candidate *ret; /* Return value */
1147
1148 tgn = targ->node;
1149 prefLen = strlen(targ->prefix);
1150
1151 for (gln = tgn->children.first; gln != NULL; gln = gln->next) {
1152 const char *base;
1153
1154 sgn = gln->datum;
1155
1156 if (sgn->type & OP_OPTIONAL && Lst_IsEmpty(&tgn->commands)) {
1157 /*
1158 * We haven't looked to see if .OPTIONAL files exist
1159 * yet, so don't use one as the implicit source.
1160 * This allows us to use .OPTIONAL in .depend files so
1161 * make won't complain "don't know how to make xxx.h"
1162 * when a dependent file has been moved/deleted.
1163 */
1164 continue;
1165 }
1166
1167 base = str_basename(sgn->name);
1168 if (strncmp(base, targ->prefix, prefLen) != 0)
1169 continue;
1170 /*
1171 * The node matches the prefix, see if it has a known suffix.
1172 */
1173 suff = FindSuffixByName(base + prefLen);
1174 if (suff == NULL)
1175 continue;
1176
1177 /*
1178 * It even has a known suffix, see if there's a transformation
1179 * defined between the node's suffix and the target's suffix.
1180 *
1181 * XXX: Handle multi-stage transformations here, too.
1182 */
1183
1184 if (Lst_FindDatum(&suff->parents, targ->suff) != NULL)
1185 break;
1186 }
1187
1188 if (gln == NULL)
1189 return NULL;
1190
1191 ret = Candidate_New(bmake_strdup(sgn->name), targ->prefix, suff, targ,
1192 sgn);
1193 targ->numChildren++;
1194 #ifdef DEBUG_SRC
1195 debug_printf("3 add targ %p:%s ret %p:%s\n",
1196 targ, targ->file, ret, ret->file);
1197 Lst_Append(&targ->childrenList, ret);
1198 #endif
1199 CandidateSearcher_Add(cs, ret);
1200 DEBUG1(SUFF, "\tusing existing source %s\n", sgn->name);
1201 return ret;
1202 }
1203
1204 static void
1205 ExpandWildcards(GNodeListNode *cln, GNode *pgn)
1206 {
1207 GNode *cgn = cln->datum;
1208 StringList expansions;
1209
1210 if (!Dir_HasWildcards(cgn->name))
1211 return;
1212
1213 /* Expand the word along the chosen path. */
1214 Lst_Init(&expansions);
1215 SearchPath_Expand(Suff_FindPath(cgn), cgn->name, &expansions);
1216
1217 while (!Lst_IsEmpty(&expansions)) {
1218 GNode *gn;
1219 /*
1220 * Fetch next expansion off the list and find its GNode
1221 */
1222 char *name = Lst_Dequeue(&expansions);
1223
1224 DEBUG1(SUFF, "%s...", name);
1225 gn = Targ_GetNode(name);
1226 free(name);
1227
1228 /* Insert gn before the original child. */
1229 Lst_InsertBefore(&pgn->children, cln, gn);
1230 Lst_Append(&gn->parents, pgn);
1231 pgn->unmade++;
1232 }
1233
1234 Lst_Done(&expansions);
1235
1236 DEBUG0(SUFF, "\n");
1237
1238 /*
1239 * Now that the source is expanded, remove it from the list of
1240 * children, to keep it from being processed.
1241 */
1242 pgn->unmade--;
1243 Lst_Remove(&pgn->children, cln);
1244 Lst_Remove(&cgn->parents, Lst_FindDatum(&cgn->parents, pgn));
1245 }
1246
1247 /*
1248 * Break the result into a vector of strings whose nodes we can find, then
1249 * add those nodes to the members list.
1250 *
1251 * Unfortunately, we can't use Str_Words because it doesn't understand about
1252 * expressions with spaces in them.
1253 */
1254 static void
1255 ExpandChildrenRegular(char *p, GNode *pgn, GNodeList *members)
1256 {
1257 char *start;
1258
1259 pp_skip_hspace(&p);
1260 start = p;
1261 while (*p != '\0') {
1262 if (*p == ' ' || *p == '\t') {
1263 GNode *gn;
1264 /*
1265 * White-space -- terminate element, find the node,
1266 * add it, skip any further spaces.
1267 */
1268 *p++ = '\0';
1269 gn = Targ_GetNode(start);
1270 Lst_Append(members, gn);
1271 pp_skip_hspace(&p);
1272 /* Continue at the next non-space. */
1273 start = p;
1274 } else if (*p == '$') {
1275 /* Skip over the expression. */
1276 const char *nested_p = p;
1277 FStr junk = Var_Parse(&nested_p, pgn, VARE_PARSE);
1278 /* TODO: handle errors */
1279 if (junk.str == var_Error) {
1280 Parse_Error(PARSE_FATAL,
1281 "Malformed expression at \"%s\"", p);
1282 p++;
1283 } else {
1284 p += nested_p - p;
1285 }
1286
1287 FStr_Done(&junk);
1288 } else if (p[0] == '\\' && p[1] != '\0') {
1289 /* Escaped something -- skip over it. */
1290 /*
1291 * XXX: In other places, escaping at this syntactical
1292 * position is done by a '$', not a '\'. The '\' is
1293 * only used in variable modifiers.
1294 */
1295 p += 2;
1296 } else {
1297 p++;
1298 }
1299 }
1300
1301 if (p != start) {
1302 /*
1303 * Stuff left over -- add it to the list too
1304 */
1305 GNode *gn = Targ_GetNode(start);
1306 Lst_Append(members, gn);
1307 }
1308 }
1309
1310 /*
1311 * Expand the names of any children of a given node that contain
1312 * expressions or file wildcards into actual targets.
1313 *
1314 * The expanded node is removed from the parent's list of children, and the
1315 * parent's unmade counter is decremented, but other nodes may be added.
1316 *
1317 * Input:
1318 * cln Child to examine
1319 * pgn Parent node being processed
1320 */
1321 static void
1322 ExpandChildren(GNodeListNode *cln, GNode *pgn)
1323 {
1324 GNode *cgn = cln->datum;
1325 char *expanded;
1326
1327 if (!Lst_IsEmpty(&cgn->order_pred) || !Lst_IsEmpty(&cgn->order_succ))
1328 /* It is all too hard to process the result of .ORDER */
1329 return;
1330
1331 if (cgn->type & OP_WAIT)
1332 /* Ignore these (& OP_PHONY ?) */
1333 return;
1334
1335 /*
1336 * First do variable expansion -- this takes precedence over wildcard
1337 * expansion. If the result contains wildcards, they'll be gotten to
1338 * later since the resulting words are tacked on to the end of the
1339 * children list.
1340 */
1341 if (strchr(cgn->name, '$') == NULL) {
1342 ExpandWildcards(cln, pgn);
1343 return;
1344 }
1345
1346 DEBUG1(SUFF, "Expanding \"%s\"...", cgn->name);
1347 expanded = Var_Subst(cgn->name, pgn, VARE_EVAL_DEFINED);
1348 /* TODO: handle errors */
1349
1350 {
1351 GNodeList members = LST_INIT;
1352
1353 if (cgn->type & OP_ARCHV) {
1354 /*
1355 * Node was an 'archive(member)' target, so
1356 * call on the Arch module to find the nodes for us,
1357 * expanding variables in the parent's scope.
1358 */
1359 char *ap = expanded;
1360 (void)Arch_ParseArchive(&ap, &members, pgn);
1361 } else {
1362 ExpandChildrenRegular(expanded, pgn, &members);
1363 }
1364
1365 /* Add all members to the parent node. */
1366 while (!Lst_IsEmpty(&members)) {
1367 GNode *gn = Lst_Dequeue(&members);
1368
1369 DEBUG1(SUFF, "%s...", gn->name);
1370 Lst_InsertBefore(&pgn->children, cln, gn);
1371 Lst_Append(&gn->parents, pgn);
1372 pgn->unmade++;
1373 ExpandWildcards(cln->prev, pgn);
1374 }
1375 Lst_Done(&members);
1376
1377 free(expanded);
1378 }
1379
1380 DEBUG0(SUFF, "\n");
1381
1382 /*
1383 * The source is expanded now, so remove it from the list of children,
1384 * to keep it from being processed.
1385 */
1386 pgn->unmade--;
1387 Lst_Remove(&pgn->children, cln);
1388 Lst_Remove(&cgn->parents, Lst_FindDatum(&cgn->parents, pgn));
1389 }
1390
1391 static void
1392 ExpandAllChildren(GNode *gn)
1393 {
1394 GNodeListNode *ln, *nln;
1395
1396 for (ln = gn->children.first; ln != NULL; ln = nln) {
1397 nln = ln->next;
1398 ExpandChildren(ln, gn);
1399 }
1400 }
1401
1402 /*
1403 * Find a path along which to search or expand the node.
1404 *
1405 * If the node has a known suffix, use that path,
1406 * otherwise use the default system search path.
1407 */
1408 SearchPath *
1409 Suff_FindPath(GNode *gn)
1410 {
1411 Suffix *suff = gn->suffix;
1412
1413 if (suff == NULL) {
1414 char *name = gn->name;
1415 size_t nameLen = strlen(gn->name);
1416 SuffixListNode *ln;
1417 for (ln = sufflist.first; ln != NULL; ln = ln->next)
1418 if (Suffix_IsSuffix(ln->datum, nameLen, name + nameLen))
1419 break;
1420
1421 DEBUG1(SUFF, "Wildcard expanding \"%s\"...", gn->name);
1422 if (ln != NULL)
1423 suff = ln->datum;
1424 /*
1425 * XXX: Here we can save the suffix so we don't have to do
1426 * this again.
1427 */
1428 }
1429
1430 if (suff != NULL) {
1431 DEBUG1(SUFF, "suffix is \"%s\"...\n", suff->name);
1432 return suff->searchPath;
1433 } else {
1434 DEBUG0(SUFF, "\n");
1435 return &dirSearchPath; /* Use default search path */
1436 }
1437 }
1438
1439 /*
1440 * Apply a transformation rule, given the source and target nodes and
1441 * suffixes.
1442 *
1443 * The source and target are linked and the commands from the transformation
1444 * are added to the target node's commands list. The target also inherits all
1445 * the sources for the transformation rule.
1446 *
1447 * Results:
1448 * true if successful, false if not.
1449 */
1450 static bool
1451 ApplyTransform(GNode *tgn, GNode *sgn, Suffix *tsuff, Suffix *ssuff)
1452 {
1453 GNodeListNode *ln;
1454 char *tname; /* Name of transformation rule */
1455 GNode *gn; /* Node for the transformation rule */
1456
1457 /* Form the proper links between the target and source. */
1458 Lst_Append(&tgn->children, sgn);
1459 Lst_Append(&sgn->parents, tgn);
1460 tgn->unmade++;
1461
1462 /* Locate the transformation rule itself. */
1463 tname = str_concat2(ssuff->name, tsuff->name);
1464 gn = FindTransformByName(tname);
1465 free(tname);
1466
1467 /* This can happen when linking an OP_MEMBER and OP_ARCHV node. */
1468 if (gn == NULL)
1469 return false;
1470
1471 DEBUG3(SUFF, "\tapplying %s -> %s to \"%s\"\n",
1472 ssuff->name, tsuff->name, tgn->name);
1473
1474 /* Record last child; Make_HandleUse may add child nodes. */
1475 ln = tgn->children.last;
1476
1477 /* Apply the rule. */
1478 Make_HandleUse(gn, tgn);
1479
1480 /* Deal with wildcards and expressions in any acquired sources. */
1481 ln = ln != NULL ? ln->next : NULL;
1482 while (ln != NULL) {
1483 GNodeListNode *nln = ln->next;
1484 ExpandChildren(ln, tgn);
1485 ln = nln;
1486 }
1487
1488 /*
1489 * Keep track of another parent to which this node is transformed so
1490 * the .IMPSRC variable can be set correctly for the parent.
1491 */
1492 Lst_Append(&sgn->implicitParents, tgn);
1493
1494 return true;
1495 }
1496
1497 /*
1498 * Member has a known suffix, so look for a transformation rule from
1499 * it to a possible suffix of the archive.
1500 *
1501 * Rather than searching through the entire list, we just look at
1502 * suffixes to which the member's suffix may be transformed.
1503 */
1504 static void
1505 ExpandMember(GNode *gn, const char *eoarch, GNode *mem, Suffix *memSuff)
1506 {
1507 SuffixListNode *ln;
1508 size_t nameLen = (size_t)(eoarch - gn->name);
1509
1510 /* Use first matching suffix... */
1511 for (ln = memSuff->parents.first; ln != NULL; ln = ln->next)
1512 if (Suffix_IsSuffix(ln->datum, nameLen, eoarch))
1513 break;
1514
1515 if (ln != NULL) {
1516 Suffix *suff = ln->datum;
1517 if (!ApplyTransform(gn, mem, suff, memSuff)) {
1518 DEBUG2(SUFF, "\tNo transformation from %s -> %s\n",
1519 memSuff->name, suff->name);
1520 }
1521 }
1522 }
1523
1524 static void FindDeps(GNode *, CandidateSearcher *);
1525
1526 /*
1527 * Locate dependencies for an OP_ARCHV node.
1528 *
1529 * Side Effects:
1530 * Same as Suff_FindDeps
1531 */
1532 static void
1533 FindDepsArchive(GNode *gn, CandidateSearcher *cs)
1534 {
1535 char *eoarch; /* End of archive portion */
1536 char *eoname; /* End of member portion */
1537 GNode *mem; /* Node for member */
1538 Suffix *memSuff;
1539 const char *name; /* Start of member's name */
1540
1541 /*
1542 * The node is an 'archive(member)' pair, so we must find a
1543 * suffix for both of them.
1544 */
1545 eoarch = strchr(gn->name, '(');
1546 eoname = strchr(eoarch, ')');
1547
1548 /*
1549 * Caller guarantees the format `libname(member)', via
1550 * Arch_ParseArchive.
1551 */
1552 assert(eoarch != NULL);
1553 assert(eoname != NULL);
1554
1555 *eoname = '\0'; /* Nuke parentheses during suffix search */
1556 *eoarch = '\0'; /* So a suffix can be found */
1557
1558 name = eoarch + 1;
1559
1560 /*
1561 * To simplify things, call Suff_FindDeps recursively on the member
1562 * now, so we can simply compare the member's .PREFIX and .TARGET
1563 * variables to locate its suffix. This allows us to figure out the
1564 * suffix to use for the archive without having to do a quadratic
1565 * search over the suffix list, backtracking for each one.
1566 */
1567 mem = Targ_GetNode(name);
1568 FindDeps(mem, cs);
1569
1570 /* Create the link between the two nodes right off. */
1571 Lst_Append(&gn->children, mem);
1572 Lst_Append(&mem->parents, gn);
1573 gn->unmade++;
1574
1575 /* Copy in the variables from the member node to this one. */
1576 Var_Set(gn, PREFIX, GNode_VarPrefix(mem));
1577 Var_Set(gn, TARGET, GNode_VarTarget(mem));
1578
1579 memSuff = mem->suffix;
1580 if (memSuff == NULL) { /* Didn't know what it was. */
1581 DEBUG0(SUFF, "using null suffix\n");
1582 memSuff = nullSuff;
1583 }
1584
1585
1586 /* Set the other two local variables required for this target. */
1587 Var_Set(gn, MEMBER, name);
1588 Var_Set(gn, ARCHIVE, gn->name);
1589 /* Set $@ for compatibility with other makes. */
1590 Var_Set(gn, TARGET, gn->name);
1591
1592 /*
1593 * Now we've got the important local variables set, expand any sources
1594 * that still contain variables or wildcards in their names.
1595 */
1596 ExpandAllChildren(gn);
1597
1598 if (memSuff != NULL)
1599 ExpandMember(gn, eoarch, mem, memSuff);
1600
1601 /*
1602 * Replace the opening and closing parens now we've no need of the
1603 * separate pieces.
1604 */
1605 *eoarch = '(';
1606 *eoname = ')';
1607
1608 /*
1609 * Pretend gn appeared to the left of a dependency operator so the
1610 * user needn't provide a transformation from the member to the
1611 * archive.
1612 */
1613 if (!GNode_IsTarget(gn))
1614 gn->type |= OP_DEPENDS;
1615
1616 /*
1617 * Flag the member as such so we remember to look in the archive for
1618 * its modification time. The OP_JOIN | OP_MADE is needed because
1619 * this target should never get made.
1620 */
1621 mem->type |= OP_MEMBER | OP_JOIN | OP_MADE;
1622 }
1623
1624 /*
1625 * If the node is a library, it is the arch module's job to find it
1626 * and set the TARGET variable accordingly. We merely provide the
1627 * search path, assuming all libraries end in ".a" (if the suffix
1628 * hasn't been defined, there's nothing we can do for it, so we just
1629 * set the TARGET variable to the node's name in order to give it a
1630 * value).
1631 */
1632 static void
1633 FindDepsLib(GNode *gn)
1634 {
1635 Suffix *suff = FindSuffixByName(LIBSUFF);
1636 if (suff != NULL) {
1637 Suffix_Reassign(&gn->suffix, suff);
1638 Arch_FindLib(gn, suff->searchPath);
1639 } else {
1640 Suffix_Unassign(&gn->suffix);
1641 Var_Set(gn, TARGET, gn->name);
1642 }
1643
1644 /*
1645 * Because a library (-lfoo) target doesn't follow the standard
1646 * filesystem conventions, we don't set the regular variables for
1647 * the thing. .PREFIX is simply made empty.
1648 */
1649 Var_Set(gn, PREFIX, "");
1650 }
1651
1652 static void
1653 FindDepsRegularKnown(const char *name, size_t nameLen, GNode *gn,
1654 CandidateList *srcs, CandidateList *targs)
1655 {
1656 SuffixListNode *ln;
1657 Candidate *targ;
1658 char *pref;
1659
1660 for (ln = sufflist.first; ln != NULL; ln = ln->next) {
1661 Suffix *suff = ln->datum;
1662 if (!Suffix_IsSuffix(suff, nameLen, name + nameLen))
1663 continue;
1664
1665 pref = bmake_strldup(name, (size_t)(nameLen - suff->nameLen));
1666 targ = Candidate_New(bmake_strdup(gn->name), pref, suff, NULL,
1667 gn);
1668
1669 CandidateList_AddCandidatesFor(srcs, targ);
1670
1671 /* Record the target so we can nuke it. */
1672 Lst_Append(targs, targ);
1673 }
1674 }
1675
1676 static void
1677 FindDepsRegularUnknown(GNode *gn, const char *sopref,
1678 CandidateList *srcs, CandidateList *targs)
1679 {
1680 Candidate *targ;
1681
1682 if (!Lst_IsEmpty(targs) || nullSuff == NULL)
1683 return;
1684
1685 DEBUG1(SUFF, "\tNo known suffix on %s. Using .NULL suffix\n", gn->name);
1686
1687 targ = Candidate_New(bmake_strdup(gn->name), bmake_strdup(sopref),
1688 nullSuff, NULL, gn);
1689
1690 /*
1691 * Only use the default suffix rules if we don't have commands
1692 * defined for this gnode; traditional make programs used to not
1693 * define suffix rules if the gnode had children but we don't do
1694 * this anymore.
1695 */
1696 if (Lst_IsEmpty(&gn->commands))
1697 CandidateList_AddCandidatesFor(srcs, targ);
1698 else {
1699 DEBUG0(SUFF, "not ");
1700 }
1701
1702 DEBUG0(SUFF, "adding suffix rules\n");
1703
1704 Lst_Append(targs, targ);
1705 }
1706
1707 /*
1708 * Deal with finding the thing on the default search path. We always do
1709 * that, not only if the node is only a source (not on the lhs of a
1710 * dependency operator or [XXX] it has neither children or commands) as
1711 * the old pmake did.
1712 */
1713 static void
1714 FindDepsRegularPath(GNode *gn, Candidate *targ)
1715 {
1716 if (gn->type & (OP_PHONY | OP_NOPATH))
1717 return;
1718
1719 free(gn->path);
1720 gn->path = Dir_FindFile(gn->name,
1721 targ == NULL ? &dirSearchPath : targ->suff->searchPath);
1722 if (gn->path == NULL)
1723 return;
1724
1725 Var_Set(gn, TARGET, gn->path);
1726
1727 if (targ != NULL) {
1728 /*
1729 * Suffix known for the thing -- trim the suffix off
1730 * the path to form the proper .PREFIX variable.
1731 */
1732 size_t savep = strlen(gn->path) - targ->suff->nameLen;
1733 char savec;
1734
1735 Suffix_Reassign(&gn->suffix, targ->suff);
1736
1737 savec = gn->path[savep];
1738 gn->path[savep] = '\0';
1739
1740 Var_Set(gn, PREFIX, str_basename(gn->path));
1741
1742 gn->path[savep] = savec;
1743 } else {
1744 /*
1745 * The .PREFIX gets the full path if the target has no
1746 * known suffix.
1747 */
1748 Suffix_Unassign(&gn->suffix);
1749 Var_Set(gn, PREFIX, str_basename(gn->path));
1750 }
1751 }
1752
1753 /*
1754 * Locate implicit dependencies for regular targets.
1755 *
1756 * Input:
1757 * gn Node for which to find sources
1758 *
1759 * Side Effects:
1760 * Same as Suff_FindDeps
1761 */
1762 static void
1763 FindDepsRegular(GNode *gn, CandidateSearcher *cs)
1764 {
1765 /* List of sources at which to look */
1766 CandidateList srcs = LST_INIT;
1767 /*
1768 * List of targets to which things can be transformed.
1769 * They all have the same file, but different suff and prefix fields.
1770 */
1771 CandidateList targs = LST_INIT;
1772 Candidate *bottom; /* Start of found transformation path */
1773 Candidate *src;
1774 Candidate *targ;
1775
1776 const char *name = gn->name;
1777 size_t nameLen = strlen(name);
1778
1779 #ifdef DEBUG_SRC
1780 DEBUG1(SUFF, "FindDepsRegular \"%s\"\n", gn->name);
1781 #endif
1782
1783 /*
1784 * We're caught in a catch-22 here. On the one hand, we want to use
1785 * any transformation implied by the target's sources, but we can't
1786 * examine the sources until we've expanded any variables/wildcards
1787 * they may hold, and we can't do that until we've set up the
1788 * target's local variables and we can't do that until we know what
1789 * the proper suffix for the target is (in case there are two
1790 * suffixes one of which is a suffix of the other) and we can't know
1791 * that until we've found its implied source, which we may not want
1792 * to use if there's an existing source that implies a different
1793 * transformation.
1794 *
1795 * In an attempt to get around this, which may not work all the time,
1796 * but should work most of the time, we look for implied sources
1797 * first, checking transformations to all possible suffixes of the
1798 * target, use what we find to set the target's local variables,
1799 * expand the children, then look for any overriding transformations
1800 * they imply. Should we find one, we discard the one we found before.
1801 */
1802 bottom = NULL;
1803 targ = NULL;
1804
1805 if (!(gn->type & OP_PHONY)) {
1806
1807 FindDepsRegularKnown(name, nameLen, gn, &srcs, &targs);
1808
1809 /* Handle target of unknown suffix... */
1810 FindDepsRegularUnknown(gn, name, &srcs, &targs);
1811
1812 /*
1813 * Using the list of possible sources built up from the target
1814 * suffix(es), try and find an existing file/target that
1815 * matches.
1816 */
1817 bottom = FindThem(&srcs, cs);
1818
1819 if (bottom == NULL) {
1820 /*
1821 * No known transformations -- use the first suffix
1822 * found for setting the local variables.
1823 */
1824 if (targs.first != NULL)
1825 targ = targs.first->datum;
1826 else
1827 targ = NULL;
1828 } else {
1829 /*
1830 * Work up the transformation path to find the suffix
1831 * of the target to which the transformation was made.
1832 */
1833 for (targ = bottom;
1834 targ->parent != NULL; targ = targ->parent)
1835 continue;
1836 }
1837 }
1838
1839 Var_Set(gn, TARGET, GNode_Path(gn));
1840 Var_Set(gn, PREFIX, targ != NULL ? targ->prefix : gn->name);
1841
1842 /*
1843 * Now we've got the important local variables set, expand any sources
1844 * that still contain variables or wildcards in their names.
1845 */
1846 {
1847 GNodeListNode *ln, *nln;
1848 for (ln = gn->children.first; ln != NULL; ln = nln) {
1849 nln = ln->next;
1850 ExpandChildren(ln, gn);
1851 }
1852 }
1853
1854 if (targ == NULL) {
1855 DEBUG1(SUFF, "\tNo valid suffix on %s\n", gn->name);
1856
1857 sfnd_abort:
1858 FindDepsRegularPath(gn, targ);
1859 goto sfnd_return;
1860 }
1861
1862 /*
1863 * If the suffix indicates that the target is a library, mark that in
1864 * the node's type field.
1865 */
1866 if (targ->suff->library)
1867 gn->type |= OP_LIB;
1868
1869 /*
1870 * Check for overriding transformation rule implied by sources
1871 */
1872 if (!Lst_IsEmpty(&gn->children)) {
1873 src = FindCmds(targ, cs);
1874
1875 if (src != NULL) {
1876 /*
1877 * Free up all the candidates in the transformation
1878 * path, up to but not including the parent node.
1879 */
1880 while (bottom != NULL && bottom->parent != NULL) {
1881 CandidateSearcher_AddIfNew(cs, bottom);
1882 bottom = bottom->parent;
1883 }
1884 bottom = src;
1885 }
1886 }
1887
1888 if (bottom == NULL) {
1889 /* No idea from where it can come -- return now. */
1890 goto sfnd_abort;
1891 }
1892
1893 /*
1894 * We now have a list of candidates headed by 'bottom' and linked via
1895 * their 'parent' pointers. What we do next is create links between
1896 * source and target nodes (which may or may not have been created)
1897 * and set the necessary local variables in each target.
1898 *
1899 * The commands for each target are set from the commands of the
1900 * transformation rule used to get from the src suffix to the targ
1901 * suffix. Note that this causes the commands list of the original
1902 * node, gn, to be replaced with the commands of the final
1903 * transformation rule.
1904 */
1905 if (bottom->node == NULL)
1906 bottom->node = Targ_GetNode(bottom->file);
1907
1908 for (src = bottom; src->parent != NULL; src = src->parent) {
1909 targ = src->parent;
1910
1911 Suffix_Reassign(&src->node->suffix, src->suff);
1912
1913 if (targ->node == NULL)
1914 targ->node = Targ_GetNode(targ->file);
1915
1916 ApplyTransform(targ->node, src->node, targ->suff, src->suff);
1917
1918 if (targ->node != gn) {
1919 /*
1920 * Finish off the dependency-search process for any
1921 * nodes between bottom and gn (no point in questing
1922 * around the filesystem for their implicit source
1923 * when it's already known). Note that the node
1924 * can't have any sources that need expanding, since
1925 * SuffFindThem will stop on an existing node, so all
1926 * we need to do is set the standard variables.
1927 */
1928 targ->node->type |= OP_DEPS_FOUND;
1929 Var_Set(targ->node, PREFIX, targ->prefix);
1930 Var_Set(targ->node, TARGET, targ->node->name);
1931 }
1932 }
1933
1934 Suffix_Reassign(&gn->suffix, src->suff);
1935
1936 /*
1937 * Nuke the transformation path and the candidates left over in the
1938 * two lists.
1939 */
1940 sfnd_return:
1941 if (bottom != NULL)
1942 CandidateSearcher_AddIfNew(cs, bottom);
1943
1944 while (RemoveCandidate(&srcs) || RemoveCandidate(&targs))
1945 continue;
1946
1947 CandidateSearcher_MoveAll(cs, &srcs);
1948 CandidateSearcher_MoveAll(cs, &targs);
1949 }
1950
1951 static void
1952 CandidateSearcher_CleanUp(CandidateSearcher *cs)
1953 {
1954 while (RemoveCandidate(&cs->list))
1955 continue;
1956 assert(Lst_IsEmpty(&cs->list));
1957 }
1958
1959
1960 /*
1961 * Find implicit sources for the target.
1962 *
1963 * Nodes are added to the graph as children of the passed-in node. The nodes
1964 * are marked to have their IMPSRC variable filled in. The PREFIX variable
1965 * is set for the given node and all its implied children.
1966 *
1967 * The path found by this target is the shortest path in the transformation
1968 * graph, which may pass through nonexistent targets, to an existing target.
1969 * The search continues on all paths from the root suffix until a file is
1970 * found. I.e. if there's a path .o -> .c -> .l -> .l,v from the root and the
1971 * .l,v file exists but the .c and .l files don't, the search will branch out
1972 * in all directions from .o and again from all the nodes on the next level
1973 * until the .l,v node is encountered.
1974 */
1975 void
1976 Suff_FindDeps(GNode *gn)
1977 {
1978 CandidateSearcher cs;
1979
1980 CandidateSearcher_Init(&cs);
1981
1982 FindDeps(gn, &cs);
1983
1984 CandidateSearcher_CleanUp(&cs);
1985 CandidateSearcher_Done(&cs);
1986 }
1987
1988 static void
1989 FindDeps(GNode *gn, CandidateSearcher *cs)
1990 {
1991 if (gn->type & OP_DEPS_FOUND)
1992 return;
1993 gn->type |= OP_DEPS_FOUND;
1994
1995 /* Make sure we have these set, may get revised below. */
1996 Var_Set(gn, TARGET, GNode_Path(gn));
1997 Var_Set(gn, PREFIX, gn->name);
1998
1999 DEBUG1(SUFF, "SuffFindDeps \"%s\"\n", gn->name);
2000
2001 if (gn->type & OP_ARCHV)
2002 FindDepsArchive(gn, cs);
2003 else if (gn->type & OP_LIB)
2004 FindDepsLib(gn);
2005 else
2006 FindDepsRegular(gn, cs);
2007 }
2008
2009 /*
2010 * Define which suffix is the null suffix.
2011 *
2012 * Need to handle the changing of the null suffix gracefully so the old
2013 * transformation rules don't just go away.
2014 */
2015 void
2016 Suff_SetNull(const char *name)
2017 {
2018 Suffix *suff = FindSuffixByName(name);
2019 if (suff == NULL) {
2020 Parse_Error(PARSE_WARNING,
2021 "Desired null suffix %s not defined",
2022 name);
2023 return;
2024 }
2025
2026 if (nullSuff != NULL)
2027 nullSuff->isNull = false;
2028 suff->isNull = true;
2029 /* XXX: Here's where the transformation mangling would take place. */
2030 nullSuff = suff;
2031 }
2032
2033 /* Initialize the suffixes module. */
2034 void
2035 Suff_Init(void)
2036 {
2037 /*
2038 * Create null suffix for single-suffix rules (POSIX). The thing
2039 * doesn't actually go on the suffix list or everyone will think
2040 * that's its suffix.
2041 */
2042 Suff_ClearSuffixes();
2043 }
2044
2045 /* Clean up the suffixes module. */
2046 void
2047 Suff_End(void)
2048 {
2049 #ifdef CLEANUP
2050 SuffixListNode *ln;
2051
2052 for (ln = sufflist.first; ln != NULL; ln = ln->next)
2053 Suffix_Free(ln->datum);
2054 Lst_Done(&sufflist);
2055 for (ln = suffClean.first; ln != NULL; ln = ln->next)
2056 Suffix_Free(ln->datum);
2057 Lst_Done(&suffClean);
2058 if (nullSuff != NULL)
2059 Suffix_Free(nullSuff);
2060 Lst_Done(&transforms);
2061 #endif
2062 }
2063
2064
2065 static void
2066 PrintSuffNames(const char *prefix, const SuffixList *suffs)
2067 {
2068 SuffixListNode *ln;
2069
2070 debug_printf("#\t%s: ", prefix);
2071 for (ln = suffs->first; ln != NULL; ln = ln->next) {
2072 const Suffix *suff = ln->datum;
2073 debug_printf("%s ", suff->name);
2074 }
2075 debug_printf("\n");
2076 }
2077
2078 static void
2079 Suffix_Print(const Suffix *suff)
2080 {
2081 Buffer buf;
2082
2083 Buf_Init(&buf);
2084 Buf_AddFlag(&buf, suff->include, "SUFF_INCLUDE");
2085 Buf_AddFlag(&buf, suff->library, "SUFF_LIBRARY");
2086 Buf_AddFlag(&buf, suff->isNull, "SUFF_NULL");
2087
2088 debug_printf("# \"%s\" (num %d, ref %d)",
2089 suff->name, suff->sNum, suff->refCount);
2090 if (buf.len > 0)
2091 debug_printf(" (%s)", buf.data);
2092 debug_printf("\n");
2093
2094 Buf_Done(&buf);
2095
2096 PrintSuffNames("To", &suff->parents);
2097 PrintSuffNames("From", &suff->children);
2098
2099 debug_printf("#\tSearch Path: ");
2100 SearchPath_Print(suff->searchPath);
2101 debug_printf("\n");
2102 }
2103
2104 static void
2105 PrintTransformation(GNode *t)
2106 {
2107 debug_printf("%-16s:", t->name);
2108 Targ_PrintType(t->type);
2109 debug_printf("\n");
2110 Targ_PrintCmds(t);
2111 debug_printf("\n");
2112 }
2113
2114 void
2115 Suff_PrintAll(void)
2116 {
2117 debug_printf("#*** Suffixes:\n");
2118 {
2119 SuffixListNode *ln;
2120 for (ln = sufflist.first; ln != NULL; ln = ln->next)
2121 Suffix_Print(ln->datum);
2122 }
2123
2124 debug_printf("#*** Transformations:\n");
2125 {
2126 GNodeListNode *ln;
2127 for (ln = transforms.first; ln != NULL; ln = ln->next)
2128 PrintTransformation(ln->datum);
2129 }
2130 }
2131
2132 char *
2133 Suff_NamesStr(void)
2134 {
2135 Buffer buf;
2136 SuffixListNode *ln;
2137 Suffix *suff;
2138
2139 Buf_Init(&buf);
2140 for (ln = sufflist.first; ln != NULL; ln = ln->next) {
2141 suff = ln->datum;
2142 if (ln != sufflist.first)
2143 Buf_AddByte(&buf, ' ');
2144 Buf_AddStr(&buf, suff->name);
2145 }
2146 return Buf_DoneData(&buf);
2147 }
2148