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