dir.c revision 1.224 1 /* $NetBSD: dir.c,v 1.224 2020/11/28 22:13:56 rillig Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5 * 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) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
39 *
40 * This code is derived from software contributed to Berkeley by
41 * Adam de Boor.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
58 *
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
70 */
71
72 /* Directory searching using wildcards and/or normal names.
73 * Used both for source wildcarding in the makefile and for finding
74 * implicit sources.
75 *
76 * The interface for this module is:
77 * Dir_Init Initialize the module.
78 *
79 * Dir_InitCur Set the cur CachedDir.
80 *
81 * Dir_InitDot Set the dot CachedDir.
82 *
83 * Dir_End Clean up the module.
84 *
85 * Dir_SetPATH Set ${.PATH} to reflect state of dirSearchPath.
86 *
87 * Dir_HasWildcards
88 * Returns TRUE if the name given it needs to
89 * be wildcard-expanded.
90 *
91 * Dir_Expand Given a pattern and a path, return a Lst of names
92 * which match the pattern on the search path.
93 *
94 * Dir_FindFile Searches for a file on a given search path.
95 * If it exists, the entire path is returned.
96 * Otherwise NULL is returned.
97 *
98 * Dir_FindHereOrAbove
99 * Search for a path in the current directory and
100 * then all the directories above it in turn until
101 * the path is found or we reach the root ("/").
102 *
103 * Dir_UpdateMTime
104 * Update the modification time and path of a node with
105 * data from the file corresponding to the node.
106 *
107 * Dir_AddDir Add a directory to a search path.
108 *
109 * SearchPath_ToFlags
110 * Given a search path and a command flag, create
111 * a string with each of the directories in the path
112 * preceded by the command flag and all of them
113 * separated by a space.
114 *
115 * Dir_Destroy Destroy an element of a search path. Frees up all
116 * things that can be freed for the element as long
117 * as the element is no longer referenced by any other
118 * search path.
119 *
120 * SearchPath_Clear
121 * Resets a search path to the empty list.
122 *
123 * For debugging:
124 * Dir_PrintDirectories
125 * Print stats about the directory cache.
126 */
127
128 #include <sys/types.h>
129 #include <sys/stat.h>
130
131 #include <dirent.h>
132 #include <errno.h>
133
134 #include "make.h"
135 #include "dir.h"
136 #include "job.h"
137
138 /* "@(#)dir.c 8.2 (Berkeley) 1/2/94" */
139 MAKE_RCSID("$NetBSD: dir.c,v 1.224 2020/11/28 22:13:56 rillig Exp $");
140
141 #define DIR_DEBUG0(text) DEBUG0(DIR, text)
142 #define DIR_DEBUG1(fmt, arg1) DEBUG1(DIR, fmt, arg1)
143 #define DIR_DEBUG2(fmt, arg1, arg2) DEBUG2(DIR, fmt, arg1, arg2)
144
145 /* A search path is a list of CachedDir structures. A CachedDir has in it the
146 * name of the directory and the names of all the files in the directory.
147 * This is used to cut down on the number of system calls necessary to find
148 * implicit dependents and their like. Since these searches are made before
149 * any actions are taken, we need not worry about the directory changing due
150 * to creation commands. If this hampers the style of some makefiles, they
151 * must be changed.
152 *
153 * All previously-read directories are kept in openDirs, which is checked
154 * first before a directory is opened.
155 *
156 * The need for the caching of whole directories is brought about by the
157 * multi-level transformation code in suff.c, which tends to search for far
158 * more files than regular make does. In the initial implementation, the
159 * amount of time spent performing "stat" calls was truly astronomical.
160 * The problem with caching at the start is, of course, that pmake doesn't
161 * then detect changes to these directories during the course of the make.
162 * Three possibilities suggest themselves:
163 *
164 * 1) just use stat to test for a file's existence. As mentioned above,
165 * this is very inefficient due to the number of checks engendered by
166 * the multi-level transformation code.
167 *
168 * 2) use readdir() and company to search the directories, keeping them
169 * open between checks. I have tried this and while it didn't slow down
170 * the process too much, it could severely affect the amount of
171 * parallelism available as each directory open would take another file
172 * descriptor out of play for handling I/O for another job. Given that
173 * it is only recently (as of 1993 or earlier) that UNIX OS's have taken
174 * to allowing more than 20 or 32 file descriptors for a process, this
175 * doesn't seem acceptable to me.
176 *
177 * 3) record the mtime of the directory in the CachedDir structure and
178 * verify the directory hasn't changed since the contents were cached.
179 * This will catch the creation or deletion of files, but not the
180 * updating of files. However, since it is the creation and deletion
181 * that is the problem, this could be a good thing to do. Unfortunately,
182 * if the directory (say ".") were fairly large and changed fairly
183 * frequently, the constant reloading could seriously degrade
184 * performance. It might be good in such cases to keep track of the
185 * number of reloadings and if the number goes over a (small) limit,
186 * resort to using stat in its place.
187 *
188 * An additional thing to consider is that pmake is used primarily to create
189 * C programs and until recently (as of 1993 or earlier) pcc-based compilers
190 * refused to allow you to specify where the resulting object file should be
191 * placed. This forced all objects to be created in the current directory.
192 * This isn't meant as a full excuse, just an explanation of some of the
193 * reasons for the caching used here.
194 *
195 * One more note: the location of a target's file is only performed on the
196 * downward traversal of the graph and then only for terminal nodes in the
197 * graph. This could be construed as wrong in some cases, but prevents
198 * inadvertent modification of files when the "installed" directory for a
199 * file is provided in the search path.
200 *
201 * Another data structure maintained by this module is an mtime cache used
202 * when the searching of cached directories fails to find a file. In the past,
203 * Dir_FindFile would simply perform an access() call in such a case to
204 * determine if the file could be found using just the name given. When this
205 * hit, however, all that was gained was the knowledge that the file existed.
206 * Given that an access() is essentially a stat() without the copyout() call,
207 * and that the same filesystem overhead would have to be incurred in
208 * Dir_MTime, it made sense to replace the access() with a stat() and record
209 * the mtime in a cache for when Dir_UpdateMTime was actually called.
210 */
211
212 typedef List CachedDirList;
213 typedef ListNode CachedDirListNode;
214
215 typedef ListNode SearchPathNode;
216
217 SearchPath *dirSearchPath; /* main search path */
218
219 /* A list of cached directories, with fast lookup by directory name. */
220 typedef struct OpenDirs {
221 CachedDirList *list;
222 HashTable /* of CachedDirListNode */ table;
223 } OpenDirs;
224
225 static void
226 OpenDirs_Init(OpenDirs *odirs)
227 {
228 odirs->list = Lst_New();
229 HashTable_Init(&odirs->table);
230 }
231
232 #ifdef CLEANUP
233 static void
234 OpenDirs_Done(OpenDirs *odirs)
235 {
236 CachedDirListNode *ln = odirs->list->first;
237 while (ln != NULL) {
238 CachedDirListNode *next = ln->next;
239 CachedDir *dir = ln->datum;
240 Dir_Destroy(dir); /* removes the dir from odirs->list */
241 ln = next;
242 }
243 Lst_Free(odirs->list);
244 HashTable_Done(&odirs->table);
245 }
246 #endif
247
248 static CachedDir *
249 OpenDirs_Find(OpenDirs *odirs, const char *name)
250 {
251 CachedDirListNode *ln = HashTable_FindValue(&odirs->table, name);
252 return ln != NULL ? ln->datum : NULL;
253 }
254
255 static void
256 OpenDirs_Add(OpenDirs *odirs, CachedDir *cdir)
257 {
258 if (HashTable_FindEntry(&odirs->table, cdir->name) != NULL)
259 return;
260 Lst_Append(odirs->list, cdir);
261 HashTable_Set(&odirs->table, cdir->name, odirs->list->last);
262 }
263
264 static void
265 OpenDirs_Remove(OpenDirs *odirs, const char *name)
266 {
267 HashEntry *he = HashTable_FindEntry(&odirs->table, name);
268 CachedDirListNode *ln;
269 if (he == NULL)
270 return;
271 ln = HashEntry_Get(he);
272 HashTable_DeleteEntry(&odirs->table, he);
273 Lst_Remove(odirs->list, ln);
274 }
275
276 static OpenDirs openDirs; /* all cached directories */
277
278 /*
279 * Variables for gathering statistics on the efficiency of the caching
280 * mechanism.
281 */
282 static int hits; /* Found in directory cache */
283 static int misses; /* Sad, but not evil misses */
284 static int nearmisses; /* Found under search path */
285 static int bigmisses; /* Sought by itself */
286
287 static CachedDir *dot; /* contents of current directory */
288 static CachedDir *cur; /* contents of current directory, if not dot */
289 static CachedDir *dotLast; /* a fake path entry indicating we need to
290 * look for . last */
291
292 /* Results of doing a last-resort stat in Dir_FindFile -- if we have to go to
293 * the system to find the file, we might as well have its mtime on record.
294 *
295 * XXX: If this is done way early, there's a chance other rules will have
296 * already updated the file, in which case we'll update it again. Generally,
297 * there won't be two rules to update a single file, so this should be ok,
298 * but... */
299 static HashTable mtimes;
300
301 static HashTable lmtimes; /* same as mtimes but for lstat */
302
303 typedef enum CachedStatsFlags {
304 CST_NONE = 0,
305 CST_LSTAT = 1 << 0, /* call lstat(2) instead of stat(2) */
306 CST_UPDATE = 1 << 1 /* ignore existing cached entry */
307 } CachedStatsFlags;
308
309 /* Returns 0 and the result of stat(2) or lstat(2) in *out_cst,
310 * or -1 on error. */
311 static int
312 cached_stats(const char *pathname, struct cached_stat *out_cst,
313 CachedStatsFlags flags)
314 {
315 HashTable *tbl = flags & CST_LSTAT ? &lmtimes : &mtimes;
316 struct stat sys_st;
317 struct cached_stat *cst;
318 int rc;
319
320 if (pathname == NULL || pathname[0] == '\0')
321 return -1; /* This can happen in meta mode. */
322
323 cst = HashTable_FindValue(tbl, pathname);
324 if (cst != NULL && !(flags & CST_UPDATE)) {
325 *out_cst = *cst;
326 DIR_DEBUG2("Using cached time %s for %s\n",
327 Targ_FmtTime(cst->cst_mtime), pathname);
328 return 0;
329 }
330
331 rc = (flags & CST_LSTAT ? lstat : stat)(pathname, &sys_st);
332 if (rc == -1)
333 return -1; /* don't cache negative lookups */
334
335 if (sys_st.st_mtime == 0)
336 sys_st.st_mtime = 1; /* avoid confusion with missing file */
337
338 if (cst == NULL) {
339 cst = bmake_malloc(sizeof *cst);
340 HashTable_Set(tbl, pathname, cst);
341 }
342
343 cst->cst_mtime = sys_st.st_mtime;
344 cst->cst_mode = sys_st.st_mode;
345
346 *out_cst = *cst;
347 DIR_DEBUG2(" Caching %s for %s\n",
348 Targ_FmtTime(sys_st.st_mtime), pathname);
349
350 return 0;
351 }
352
353 int
354 cached_stat(const char *pathname, struct cached_stat *cst)
355 {
356 return cached_stats(pathname, cst, CST_NONE);
357 }
358
359 int
360 cached_lstat(const char *pathname, struct cached_stat *cst)
361 {
362 return cached_stats(pathname, cst, CST_LSTAT);
363 }
364
365 /* Initialize the directories module. */
366 void
367 Dir_Init(void)
368 {
369 dirSearchPath = Lst_New();
370 OpenDirs_Init(&openDirs);
371 HashTable_Init(&mtimes);
372 HashTable_Init(&lmtimes);
373 }
374
375 void
376 Dir_InitDir(const char *cdname)
377 {
378 Dir_InitCur(cdname);
379
380 dotLast = bmake_malloc(sizeof *dotLast);
381 dotLast->refCount = 1;
382 dotLast->hits = 0;
383 dotLast->name = bmake_strdup(".DOTLAST");
384 HashSet_Init(&dotLast->files);
385 }
386
387 /*
388 * Called by Dir_InitDir and whenever .CURDIR is assigned to.
389 */
390 void
391 Dir_InitCur(const char *cdname)
392 {
393 CachedDir *dir;
394
395 if (cdname == NULL)
396 return;
397
398 /*
399 * Our build directory is not the same as our source directory.
400 * Keep this one around too.
401 */
402 dir = Dir_AddDir(NULL, cdname);
403 if (dir == NULL)
404 return;
405
406 /* XXX: Reference counting is wrong here.
407 * If this function is called repeatedly with the same directory name,
408 * its reference count increases each time even though the number of
409 * actual references stays the same. */
410
411 dir->refCount++;
412 if (cur != NULL && cur != dir) {
413 /*
414 * We've been here before, clean up.
415 */
416 cur->refCount--;
417 Dir_Destroy(cur);
418 }
419 cur = dir;
420 }
421
422 /* (Re)initialize "dot" (current/object directory) path hash.
423 * Some directories may be opened. */
424 void
425 Dir_InitDot(void)
426 {
427 if (dot != NULL) {
428 /* Remove old entry from openDirs, but do not destroy. */
429 OpenDirs_Remove(&openDirs, dot->name);
430 }
431
432 dot = Dir_AddDir(NULL, ".");
433
434 if (dot == NULL) {
435 Error("Cannot open `.' (%s)", strerror(errno));
436 exit(1);
437 }
438
439 /*
440 * We always need to have dot around, so we increment its reference
441 * count to make sure it's not destroyed.
442 */
443 dot->refCount++;
444 Dir_SetPATH(); /* initialize */
445 }
446
447 /* Clean up the directories module. */
448 void
449 Dir_End(void)
450 {
451 #ifdef CLEANUP
452 if (cur != NULL) {
453 cur->refCount--;
454 Dir_Destroy(cur);
455 }
456 dot->refCount--;
457 dotLast->refCount--;
458 Dir_Destroy(dotLast);
459 Dir_Destroy(dot);
460 SearchPath_Clear(dirSearchPath);
461 Lst_Free(dirSearchPath);
462 OpenDirs_Done(&openDirs);
463 HashTable_Done(&mtimes);
464 #endif
465 }
466
467 /*
468 * We want ${.PATH} to indicate the order in which we will actually
469 * search, so we rebuild it after any .PATH: target.
470 * This is the simplest way to deal with the effect of .DOTLAST.
471 */
472 void
473 Dir_SetPATH(void)
474 {
475 CachedDirListNode *ln;
476 Boolean hasLastDot = FALSE; /* true if we should search dot last */
477
478 Var_Delete(".PATH", VAR_GLOBAL);
479
480 if ((ln = dirSearchPath->first) != NULL) {
481 CachedDir *dir = ln->datum;
482 if (dir == dotLast) {
483 hasLastDot = TRUE;
484 Var_Append(".PATH", dotLast->name, VAR_GLOBAL);
485 }
486 }
487
488 if (!hasLastDot) {
489 if (dot != NULL)
490 Var_Append(".PATH", dot->name, VAR_GLOBAL);
491 if (cur != NULL)
492 Var_Append(".PATH", cur->name, VAR_GLOBAL);
493 }
494
495 for (ln = dirSearchPath->first; ln != NULL; ln = ln->next) {
496 CachedDir *dir = ln->datum;
497 if (dir == dotLast)
498 continue;
499 if (dir == dot && hasLastDot)
500 continue;
501 Var_Append(".PATH", dir->name, VAR_GLOBAL);
502 }
503
504 if (hasLastDot) {
505 if (dot != NULL)
506 Var_Append(".PATH", dot->name, VAR_GLOBAL);
507 if (cur != NULL)
508 Var_Append(".PATH", cur->name, VAR_GLOBAL);
509 }
510 }
511
512 /* See if the given name has any wildcard characters in it and all braces and
513 * brackets are properly balanced.
514 *
515 * XXX: This code is not 100% correct ([^]] fails etc.). I really don't think
516 * that make(1) should be expanding patterns, because then you have to set a
517 * mechanism for escaping the expansion!
518 *
519 * Return TRUE if the word should be expanded, FALSE otherwise.
520 */
521 Boolean
522 Dir_HasWildcards(const char *name)
523 {
524 const char *p;
525 Boolean wild = FALSE;
526 int braces = 0, brackets = 0;
527
528 for (p = name; *p != '\0'; p++) {
529 switch (*p) {
530 case '{':
531 braces++;
532 wild = TRUE;
533 break;
534 case '}':
535 braces--;
536 break;
537 case '[':
538 brackets++;
539 wild = TRUE;
540 break;
541 case ']':
542 brackets--;
543 break;
544 case '?':
545 case '*':
546 wild = TRUE;
547 break;
548 default:
549 break;
550 }
551 }
552 return wild && brackets == 0 && braces == 0;
553 }
554
555 /* See if any files match the pattern and add their names to the 'expansions'
556 * list if they do.
557 *
558 * This is incomplete -- wildcards are only expanded in the final path
559 * component, but not in directories like src/lib*c/file*.c, but it
560 * will do for now (now being 1993 until at least 2020). To expand these,
561 * use the ':sh' variable modifier such as in ${:!echo src/lib*c/file*.c!}.
562 *
563 * Input:
564 * pattern Pattern to look for
565 * dir Directory to search
566 * expansion Place to store the results
567 */
568 static void
569 DirMatchFiles(const char *pattern, CachedDir *dir, StringList *expansions)
570 {
571 const char *dirName = dir->name;
572 Boolean isDot = dirName[0] == '.' && dirName[1] == '\0';
573 HashIter hi;
574
575 /*
576 * XXX: Iterating over all hash entries is inefficient. If the
577 * pattern is a plain string without any wildcards, a direct lookup
578 * is faster.
579 */
580
581 HashIter_InitSet(&hi, &dir->files);
582 while (HashIter_Next(&hi) != NULL) {
583 const char *base = hi.entry->key;
584
585 if (!Str_Match(base, pattern))
586 continue;
587
588 /*
589 * Follow the UNIX convention that dot files are only found
590 * if the pattern begins with a dot. The pattern '.*' does
591 * not match '.' or '..' since these are not included in the
592 * directory cache.
593 *
594 * This means that the pattern '[a-z.]*' does not find
595 * '.file', which is consistent with bash, NetBSD sh and csh.
596 */
597 if (base[0] == '.' && pattern[0] != '.')
598 continue;
599
600 {
601 char *fullName = isDot
602 ? bmake_strdup(base)
603 : str_concat3(dirName, "/", base);
604 Lst_Append(expansions, fullName);
605 }
606 }
607 }
608
609 /* Find the next closing brace in the string, taking nested braces into
610 * account. */
611 static const char *
612 closing_brace(const char *p)
613 {
614 int nest = 0;
615 while (*p != '\0') {
616 if (*p == '}' && nest == 0)
617 break;
618 if (*p == '{')
619 nest++;
620 if (*p == '}')
621 nest--;
622 p++;
623 }
624 return p;
625 }
626
627 /* Find the next closing brace or comma in the string, taking nested braces
628 * into account. */
629 static const char *
630 separator_comma(const char *p)
631 {
632 int nest = 0;
633 while (*p != '\0') {
634 if ((*p == '}' || *p == ',') && nest == 0)
635 break;
636 if (*p == '{')
637 nest++;
638 if (*p == '}')
639 nest--;
640 p++;
641 }
642 return p;
643 }
644
645 static Boolean
646 contains_wildcard(const char *p)
647 {
648 for (; *p != '\0'; p++) {
649 switch (*p) {
650 case '*':
651 case '?':
652 case '{':
653 case '[':
654 return TRUE;
655 }
656 }
657 return FALSE;
658 }
659
660 static char *
661 concat3(const char *a, size_t a_len, const char *b, size_t b_len,
662 const char *c, size_t c_len)
663 {
664 size_t s_len = a_len + b_len + c_len;
665 char *s = bmake_malloc(s_len + 1);
666 memcpy(s, a, a_len);
667 memcpy(s + a_len, b, b_len);
668 memcpy(s + a_len + b_len, c, c_len);
669 s[s_len] = '\0';
670 return s;
671 }
672
673 /* Expand curly braces like the C shell. Brace expansion by itself is purely
674 * textual, the expansions are not looked up in the file system. But if an
675 * expanded word contains wildcard characters, it is expanded further,
676 * matching only the actually existing files.
677 *
678 * Example: "{a{b,c}}" expands to "ab" and "ac".
679 * Example: "{a}" expands to "a".
680 * Example: "{a,*.c}" expands to "a" and all "*.c" files that exist.
681 *
682 * Input:
683 * word Entire word to expand
684 * brace First curly brace in it
685 * path Search path to use
686 * expansions Place to store the expansions
687 */
688 static void
689 DirExpandCurly(const char *word, const char *brace, SearchPath *path,
690 StringList *expansions)
691 {
692 const char *prefix, *middle, *piece, *middle_end, *suffix;
693 size_t prefix_len, suffix_len;
694
695 /* Split the word into prefix '{' middle '}' suffix. */
696
697 middle = brace + 1;
698 middle_end = closing_brace(middle);
699 if (*middle_end == '\0') {
700 Error("Unterminated {} clause \"%s\"", middle);
701 return;
702 }
703
704 prefix = word;
705 prefix_len = (size_t)(brace - prefix);
706 suffix = middle_end + 1;
707 suffix_len = strlen(suffix);
708
709 /* Split the middle into pieces, separated by commas. */
710
711 piece = middle;
712 while (piece < middle_end + 1) {
713 const char *piece_end = separator_comma(piece);
714 size_t piece_len = (size_t)(piece_end - piece);
715
716 char *file = concat3(prefix, prefix_len, piece, piece_len,
717 suffix, suffix_len);
718
719 if (contains_wildcard(file)) {
720 Dir_Expand(file, path, expansions);
721 free(file);
722 } else {
723 Lst_Append(expansions, file);
724 }
725
726 /* skip over the comma or closing brace */
727 piece = piece_end + 1;
728 }
729 }
730
731
732 /* Expand the word in each of the directories from the path. */
733 static void
734 DirExpandPath(const char *word, SearchPath *path, StringList *expansions)
735 {
736 SearchPathNode *ln;
737 for (ln = path->first; ln != NULL; ln = ln->next) {
738 CachedDir *dir = ln->datum;
739 DirMatchFiles(word, dir, expansions);
740 }
741 }
742
743 static void
744 PrintExpansions(StringList *expansions)
745 {
746 const char *sep = "";
747 StringListNode *ln;
748 for (ln = expansions->first; ln != NULL; ln = ln->next) {
749 const char *word = ln->datum;
750 debug_printf("%s%s", sep, word);
751 sep = " ";
752 }
753 debug_printf("\n");
754 }
755
756 /* Expand the given word into a list of words by globbing it, looking in the
757 * directories on the given search path.
758 *
759 * Input:
760 * word the word to expand
761 * path the directories in which to find the files
762 * expansions the list on which to place the results
763 */
764 void
765 Dir_Expand(const char *word, SearchPath *path, StringList *expansions)
766 {
767 const char *cp;
768
769 assert(path != NULL);
770 assert(expansions != NULL);
771
772 DIR_DEBUG1("Expanding \"%s\"... ", word);
773
774 cp = strchr(word, '{');
775 if (cp != NULL) {
776 DirExpandCurly(word, cp, path, expansions);
777 goto done;
778 }
779
780 /* At this point, the word does not contain '{'. */
781
782 cp = strchr(word, '/');
783 if (cp == NULL) {
784 /* The word has no directory component. */
785 /* First the files in dot. */
786 DirMatchFiles(word, dot, expansions);
787
788 /* Then the files in every other directory on the path. */
789 DirExpandPath(word, path, expansions);
790 goto done;
791 }
792
793 /* At this point, the word has a directory component. */
794
795 /* Find the first wildcard in the word. */
796 for (cp = word; *cp != '\0'; cp++)
797 if (*cp == '?' || *cp == '[' || *cp == '*')
798 break;
799
800 if (*cp == '\0') {
801 /*
802 * No directory component and no wildcard at all -- this
803 * should never happen as in such a simple case there is no
804 * need to expand anything.
805 */
806 DirExpandPath(word, path, expansions);
807 goto done;
808 }
809
810 /* Back up to the start of the component containing the wildcard. */
811 /* XXX: This handles '///' and '/' differently. */
812 while (cp > word && *cp != '/')
813 cp--;
814
815 if (cp == word) {
816 /* The first component contains the wildcard. */
817 /* Start the search from the local directory */
818 DirExpandPath(word, path, expansions);
819 goto done;
820 }
821
822 {
823 char *prefix = bmake_strsedup(word, cp + 1);
824 /*
825 * The wildcard isn't in the first component.
826 * Find all the components up to the one with the wildcard.
827 */
828 /*
829 * XXX: Check the "the directory is added to the path" part.
830 * It is probably surprising that the directory before a
831 * wildcard gets added to the path.
832 */
833 /*
834 * XXX: Only the first match of the prefix in the path is
835 * taken, any others are ignored. The expectation may be
836 * that the pattern is expanded in the whole path.
837 */
838 char *dirpath = Dir_FindFile(prefix, path);
839 free(prefix);
840
841 /*
842 * dirpath is null if can't find the leading component
843 * XXX: Dir_FindFile won't find internal components.
844 * i.e. if the path contains ../Etc/Object and we're
845 * looking for Etc, it won't be found. Ah well.
846 * Probably not important.
847 * XXX: Check whether the above comment is still true.
848 */
849 if (dirpath != NULL) {
850 SearchPath *partPath;
851
852 char *end = &dirpath[strlen(dirpath) - 1];
853 /* XXX: What about multiple trailing slashes? */
854 if (*end == '/')
855 *end = '\0';
856
857 partPath = Lst_New();
858 (void)Dir_AddDir(partPath, dirpath);
859 DirExpandPath(cp + 1, partPath, expansions);
860 Lst_Free(partPath);
861 }
862 }
863
864 done:
865 if (DEBUG(DIR))
866 PrintExpansions(expansions);
867 }
868
869 /* Find if the file with the given name exists in the given path.
870 * Return the freshly allocated path to the file, or NULL. */
871 static char *
872 DirLookup(CachedDir *dir, const char *base)
873 {
874 char *file; /* the current filename to check */
875
876 DIR_DEBUG1(" %s ...\n", dir->name);
877
878 if (!HashSet_Contains(&dir->files, base))
879 return NULL;
880
881 file = str_concat3(dir->name, "/", base);
882 DIR_DEBUG1(" returning %s\n", file);
883 dir->hits++;
884 hits++;
885 return file;
886 }
887
888
889 /* Find if the file with the given name exists in the given directory.
890 * Return the freshly allocated path to the file, or NULL. */
891 static char *
892 DirLookupSubdir(CachedDir *dir, const char *name)
893 {
894 struct cached_stat cst;
895 char *file = dir == dot ? bmake_strdup(name)
896 : str_concat3(dir->name, "/", name);
897
898 DIR_DEBUG1("checking %s ...\n", file);
899
900 if (cached_stat(file, &cst) == 0) {
901 nearmisses++;
902 return file;
903 }
904 free(file);
905 return NULL;
906 }
907
908 /* Find if the file with the given name exists in the given path.
909 * Return the freshly allocated path to the file, the empty string, or NULL.
910 * Returning the empty string means that the search should be terminated.
911 */
912 static char *
913 DirLookupAbs(CachedDir *dir, const char *name, const char *cp)
914 {
915 const char *dnp; /* pointer into dir->name */
916 const char *np; /* pointer into name */
917
918 DIR_DEBUG1(" %s ...\n", dir->name);
919
920 /*
921 * If the file has a leading path component and that component
922 * exactly matches the entire name of the current search
923 * directory, we can attempt another cache lookup. And if we don't
924 * have a hit, we can safely assume the file does not exist at all.
925 */
926 for (dnp = dir->name, np = name;
927 *dnp != '\0' && *dnp == *np; dnp++, np++)
928 continue;
929 if (*dnp != '\0' || np != cp - 1)
930 return NULL;
931
932 if (!HashSet_Contains(&dir->files, cp)) {
933 DIR_DEBUG0(" must be here but isn't -- returning\n");
934 return bmake_strdup(""); /* to terminate the search */
935 }
936
937 dir->hits++;
938 hits++;
939 DIR_DEBUG1(" returning %s\n", name);
940 return bmake_strdup(name);
941 }
942
943 /* Find the file given on "." or curdir.
944 * Return the freshly allocated path to the file, or NULL. */
945 static char *
946 DirFindDot(const char *name, const char *base)
947 {
948
949 if (HashSet_Contains(&dot->files, base)) {
950 DIR_DEBUG0(" in '.'\n");
951 hits++;
952 dot->hits++;
953 return bmake_strdup(name);
954 }
955
956 if (cur != NULL && HashSet_Contains(&cur->files, base)) {
957 DIR_DEBUG1(" in ${.CURDIR} = %s\n", cur->name);
958 hits++;
959 cur->hits++;
960 return str_concat3(cur->name, "/", base);
961 }
962
963 return NULL;
964 }
965
966 /* Find the file with the given name along the given search path.
967 *
968 * If the file is found in a directory that is not on the path
969 * already (either 'name' is absolute or it is a relative path
970 * [ dir1/.../dirn/file ] which exists below one of the directories
971 * already on the search path), its directory is added to the end
972 * of the path, on the assumption that there will be more files in
973 * that directory later on. Sometimes this is true. Sometimes not.
974 *
975 * Input:
976 * name the file to find
977 * path the directories to search, or NULL
978 *
979 * Results:
980 * The freshly allocated path to the file, or NULL.
981 */
982 char *
983 Dir_FindFile(const char *name, SearchPath *path)
984 {
985 char *file; /* the current filename to check */
986 const char *base; /* Terminal name of file */
987 Boolean hasLastDot = FALSE; /* true if we should search dot last */
988 Boolean hasSlash; /* true if 'name' contains a / */
989 struct cached_stat cst; /* Buffer for stat, if necessary */
990 const char *trailing_dot = ".";
991
992 /*
993 * Find the final component of the name and note whether it has a
994 * slash in it (the name, I mean)
995 */
996 base = strrchr(name, '/');
997 if (base != NULL) {
998 hasSlash = TRUE;
999 base++;
1000 } else {
1001 hasSlash = FALSE;
1002 base = name;
1003 }
1004
1005 DIR_DEBUG1("Searching for %s ...", name);
1006
1007 if (path == NULL) {
1008 DIR_DEBUG0("couldn't open path, file not found\n");
1009 misses++;
1010 return NULL;
1011 }
1012
1013 if (path->first != NULL) {
1014 CachedDir *dir = path->first->datum;
1015 if (dir == dotLast) {
1016 hasLastDot = TRUE;
1017 DIR_DEBUG0("[dot last]...");
1018 }
1019 }
1020 DIR_DEBUG0("\n");
1021
1022 /*
1023 * If there's no leading directory components or if the leading
1024 * directory component is exactly `./', consult the cached contents
1025 * of each of the directories on the search path.
1026 */
1027 if (!hasSlash || (base - name == 2 && *name == '.')) {
1028 SearchPathNode *ln;
1029
1030 /*
1031 * We look through all the directories on the path seeking one
1032 * which contains the final component of the given name. If
1033 * such a beast is found, we concatenate the directory name
1034 * and the final component and return the resulting string.
1035 * If we don't find any such thing, we go on to phase two.
1036 *
1037 * No matter what, we always look for the file in the current
1038 * directory before anywhere else (unless we found the magic
1039 * DOTLAST path, in which case we search it last) and we *do
1040 * not* add the ./ to it if it exists.
1041 * This is so there are no conflicts between what the user
1042 * specifies (fish.c) and what pmake finds (./fish.c).
1043 */
1044 if (!hasLastDot && (file = DirFindDot(name, base)) != NULL)
1045 return file;
1046
1047 for (ln = path->first; ln != NULL; ln = ln->next) {
1048 CachedDir *dir = ln->datum;
1049 if (dir == dotLast)
1050 continue;
1051 if ((file = DirLookup(dir, base)) != NULL)
1052 return file;
1053 }
1054
1055 if (hasLastDot && (file = DirFindDot(name, base)) != NULL)
1056 return file;
1057 }
1058
1059 /*
1060 * We didn't find the file on any directory in the search path.
1061 * If the name doesn't contain a slash, that means it doesn't exist.
1062 * If it *does* contain a slash, however, there is still hope: it
1063 * could be in a subdirectory of one of the members of the search
1064 * path. (eg. /usr/include and sys/types.h. The above search would
1065 * fail to turn up types.h in /usr/include, but it *is* in
1066 * /usr/include/sys/types.h).
1067 * [ This no longer applies: If we find such a beast, we assume there
1068 * will be more (what else can we assume?) and add all but the last
1069 * component of the resulting name onto the search path (at the
1070 * end).]
1071 * This phase is only performed if the file is *not* absolute.
1072 */
1073 if (!hasSlash) {
1074 DIR_DEBUG0(" failed.\n");
1075 misses++;
1076 return NULL;
1077 }
1078
1079 if (*base == '\0') {
1080 /* we were given a trailing "/" */
1081 base = trailing_dot;
1082 }
1083
1084 if (name[0] != '/') {
1085 SearchPathNode *ln;
1086 Boolean checkedDot = FALSE;
1087
1088 DIR_DEBUG0(" Trying subdirectories...\n");
1089
1090 if (!hasLastDot) {
1091 if (dot != NULL) {
1092 checkedDot = TRUE;
1093 if ((file = DirLookupSubdir(dot, name)) != NULL)
1094 return file;
1095 }
1096 if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
1097 return file;
1098 }
1099
1100 for (ln = path->first; ln != NULL; ln = ln->next) {
1101 CachedDir *dir = ln->datum;
1102 if (dir == dotLast)
1103 continue;
1104 if (dir == dot) {
1105 if (checkedDot)
1106 continue;
1107 checkedDot = TRUE;
1108 }
1109 if ((file = DirLookupSubdir(dir, name)) != NULL)
1110 return file;
1111 }
1112
1113 if (hasLastDot) {
1114 if (dot && !checkedDot) {
1115 checkedDot = TRUE;
1116 if ((file = DirLookupSubdir(dot, name)) != NULL)
1117 return file;
1118 }
1119 if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
1120 return file;
1121 }
1122
1123 if (checkedDot) {
1124 /*
1125 * Already checked by the given name, since . was in
1126 * the path, so no point in proceeding.
1127 */
1128 DIR_DEBUG0(" Checked . already, returning NULL\n");
1129 return NULL;
1130 }
1131
1132 } else { /* name[0] == '/' */
1133 SearchPathNode *ln;
1134
1135 /*
1136 * For absolute names, compare directory path prefix against
1137 * the the directory path of each member on the search path
1138 * for an exact match. If we have an exact match on any member
1139 * of the search path, use the cached contents of that member
1140 * to lookup the final file component. If that lookup fails we
1141 * can safely assume that the file does not exist at all.
1142 * This is signified by DirLookupAbs() returning an empty
1143 * string.
1144 */
1145 DIR_DEBUG0(" Trying exact path matches...\n");
1146
1147 if (!hasLastDot && cur &&
1148 ((file = DirLookupAbs(cur, name, base)) != NULL)) {
1149 if (file[0] == '\0') {
1150 free(file);
1151 return NULL;
1152 }
1153 return file;
1154 }
1155
1156 for (ln = path->first; ln != NULL; ln = ln->next) {
1157 CachedDir *dir = ln->datum;
1158 if (dir == dotLast)
1159 continue;
1160 if ((file = DirLookupAbs(dir, name, base)) != NULL) {
1161 if (file[0] == '\0') {
1162 free(file);
1163 return NULL;
1164 }
1165 return file;
1166 }
1167 }
1168
1169 if (hasLastDot && cur &&
1170 ((file = DirLookupAbs(cur, name, base)) != NULL)) {
1171 if (file[0] == '\0') {
1172 free(file);
1173 return NULL;
1174 }
1175 return file;
1176 }
1177 }
1178
1179 /*
1180 * Didn't find it that way, either. Sigh. Phase 3. Add its directory
1181 * onto the search path in any case, just in case, then look for the
1182 * thing in the hash table. If we find it, grand. We return a new
1183 * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
1184 * Note that if the directory holding the file doesn't exist, this
1185 * will do an extra search of the final directory on the path. Unless
1186 * something weird happens, this search won't succeed and life will
1187 * be groovy.
1188 *
1189 * Sigh. We cannot add the directory onto the search path because
1190 * of this amusing case:
1191 * $(INSTALLDIR)/$(FILE): $(FILE)
1192 *
1193 * $(FILE) exists in $(INSTALLDIR) but not in the current one.
1194 * When searching for $(FILE), we will find it in $(INSTALLDIR)
1195 * b/c we added it here. This is not good...
1196 */
1197 #if 0
1198 {
1199 CachedDir *dir;
1200 char *prefix;
1201
1202 if (base == trailing_dot) {
1203 base = strrchr(name, '/');
1204 base++;
1205 }
1206 prefix = bmake_strsedup(name, base - 1);
1207 (void)Dir_AddDir(path, prefix);
1208 free(prefix);
1209
1210 bigmisses++;
1211 if (path->last == NULL)
1212 return NULL;
1213
1214 dir = path->last->datum;
1215 if (HashSet_Contains(&dir->files, base))
1216 return bmake_strdup(name);
1217 return NULL;
1218 }
1219 #else
1220 DIR_DEBUG1(" Looking for \"%s\" ...\n", name);
1221
1222 bigmisses++;
1223 if (cached_stat(name, &cst) == 0) {
1224 return bmake_strdup(name);
1225 }
1226
1227 DIR_DEBUG0(" failed. Returning NULL\n");
1228 return NULL;
1229 #endif
1230 }
1231
1232
1233 /* Search for a path starting at a given directory and then working our way
1234 * up towards the root.
1235 *
1236 * Input:
1237 * here starting directory
1238 * search_path the relative path we are looking for
1239 *
1240 * Results:
1241 * The found path, or NULL.
1242 */
1243 char *
1244 Dir_FindHereOrAbove(const char *here, const char *search_path)
1245 {
1246 struct cached_stat cst;
1247 char *dirbase, *dirbase_end;
1248 char *try, *try_end;
1249
1250 /* copy out our starting point */
1251 dirbase = bmake_strdup(here);
1252 dirbase_end = dirbase + strlen(dirbase);
1253
1254 /* loop until we determine a result */
1255 for (;;) {
1256
1257 /* try and stat(2) it ... */
1258 try = str_concat3(dirbase, "/", search_path);
1259 if (cached_stat(try, &cst) != -1) {
1260 /*
1261 * success! if we found a file, chop off
1262 * the filename so we return a directory.
1263 */
1264 if ((cst.cst_mode & S_IFMT) != S_IFDIR) {
1265 try_end = try + strlen(try);
1266 while (try_end > try && *try_end != '/')
1267 try_end--;
1268 if (try_end > try)
1269 *try_end = '\0'; /* chop! */
1270 }
1271
1272 free(dirbase);
1273 return try;
1274 }
1275 free(try);
1276
1277 /*
1278 * nope, we didn't find it. if we used up dirbase we've
1279 * reached the root and failed.
1280 */
1281 if (dirbase_end == dirbase)
1282 break; /* failed! */
1283
1284 /*
1285 * truncate dirbase from the end to move up a dir
1286 */
1287 while (dirbase_end > dirbase && *dirbase_end != '/')
1288 dirbase_end--;
1289 *dirbase_end = '\0'; /* chop! */
1290 }
1291
1292 free(dirbase);
1293 return NULL;
1294 }
1295
1296 /*
1297 * This is an implied source, and it may have moved,
1298 * see if we can find it via the current .PATH
1299 */
1300 static char *
1301 ResolveMovedDepends(GNode *gn)
1302 {
1303 char *fullName;
1304
1305 char *base = strrchr(gn->name, '/');
1306 if (base == NULL)
1307 return NULL;
1308 base++;
1309
1310 fullName = Dir_FindFile(base, Suff_FindPath(gn));
1311 if (fullName == NULL)
1312 return NULL;
1313
1314 /*
1315 * Put the found file in gn->path so that we give that to the compiler.
1316 */
1317 /*
1318 * XXX: Better just reset gn->path to NULL; updating it is already done
1319 * by Dir_UpdateMTime.
1320 */
1321 gn->path = bmake_strdup(fullName);
1322 if (!Job_RunTarget(".STALE", gn->fname))
1323 fprintf(stdout, /* XXX: Why stdout? */
1324 "%s: %s, %d: ignoring stale %s for %s, found %s\n",
1325 progname, gn->fname, gn->lineno,
1326 makeDependfile, gn->name, fullName);
1327
1328 return fullName;
1329 }
1330
1331 static char *
1332 ResolveFullName(GNode *gn)
1333 {
1334 char *fullName;
1335
1336 fullName = gn->path;
1337 if (fullName == NULL && !(gn->type & OP_NOPATH)) {
1338
1339 fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
1340
1341 if (fullName == NULL && gn->flags & FROM_DEPEND &&
1342 !Lst_IsEmpty(&gn->implicitParents))
1343 fullName = ResolveMovedDepends(gn);
1344
1345 DIR_DEBUG2("Found '%s' as '%s'\n",
1346 gn->name, fullName ? fullName : "(not found)");
1347 }
1348
1349 if (fullName == NULL)
1350 fullName = bmake_strdup(gn->name);
1351
1352 /* XXX: Is every piece of memory freed as it should? */
1353
1354 return fullName;
1355 }
1356
1357 /* Search gn along dirSearchPath and store its modification time in gn->mtime.
1358 * If no file is found, store 0 instead.
1359 *
1360 * The found file is stored in gn->path, unless the node already had a path. */
1361 void
1362 Dir_UpdateMTime(GNode *gn, Boolean recheck)
1363 {
1364 char *fullName;
1365 struct cached_stat cst;
1366
1367 if (gn->type & OP_ARCHV) {
1368 Arch_UpdateMTime(gn);
1369 return;
1370 }
1371
1372 if (gn->type & OP_PHONY) {
1373 gn->mtime = 0;
1374 return;
1375 }
1376
1377 fullName = ResolveFullName(gn);
1378
1379 if (cached_stats(fullName, &cst, recheck ? CST_UPDATE : CST_NONE) < 0) {
1380 if (gn->type & OP_MEMBER) {
1381 if (fullName != gn->path)
1382 free(fullName);
1383 Arch_UpdateMemberMTime(gn);
1384 return;
1385 }
1386
1387 cst.cst_mtime = 0;
1388 }
1389
1390 if (fullName != NULL && gn->path == NULL)
1391 gn->path = fullName;
1392 /* XXX: else free(fullName)? */
1393
1394 gn->mtime = cst.cst_mtime;
1395 }
1396
1397 /* Read the list of filenames in the directory and store the result
1398 * in openDirs.
1399 *
1400 * If a path is given, append the directory to that path.
1401 *
1402 * Input:
1403 * path The path to which the directory should be
1404 * added, or NULL to only add the directory to openDirs
1405 * name The name of the directory to add.
1406 * The name is not normalized in any way.
1407 */
1408 CachedDir *
1409 Dir_AddDir(SearchPath *path, const char *name)
1410 /*
1411 * XXX: Maybe return const CachedDir, as a hint that the return value must
1412 * not be freed since it is owned by openDirs.
1413 */
1414 {
1415 CachedDir *dir = NULL; /* the added directory */
1416 DIR *d;
1417 struct dirent *dp;
1418
1419 if (path != NULL && strcmp(name, ".DOTLAST") == 0) {
1420 SearchPathNode *ln;
1421
1422 /* XXX: Linear search gets slow with thousands of entries. */
1423 for (ln = path->first; ln != NULL; ln = ln->next) {
1424 CachedDir *pathDir = ln->datum;
1425 if (strcmp(pathDir->name, name) == 0)
1426 return pathDir;
1427 }
1428
1429 dotLast->refCount++;
1430 Lst_Prepend(path, dotLast);
1431 }
1432
1433 if (path != NULL)
1434 dir = OpenDirs_Find(&openDirs, name);
1435 if (dir != NULL) {
1436 if (Lst_FindDatum(path, dir) == NULL) {
1437 dir->refCount++;
1438 Lst_Append(path, dir);
1439 }
1440 return dir;
1441 }
1442
1443 DIR_DEBUG1("Caching %s ...", name);
1444
1445 if ((d = opendir(name)) != NULL) {
1446 dir = bmake_malloc(sizeof *dir);
1447 dir->name = bmake_strdup(name);
1448 dir->hits = 0;
1449 dir->refCount = 1;
1450 HashSet_Init(&dir->files);
1451
1452 while ((dp = readdir(d)) != NULL) {
1453 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
1454 /*
1455 * The sun directory library doesn't check for a 0 inode
1456 * (0-inode slots just take up space), so we have to do
1457 * it ourselves.
1458 */
1459 if (dp->d_fileno == 0)
1460 continue;
1461 #endif /* sun && d_ino */
1462 (void)HashSet_Add(&dir->files, dp->d_name);
1463 }
1464 (void)closedir(d);
1465 OpenDirs_Add(&openDirs, dir);
1466 if (path != NULL)
1467 Lst_Append(path, dir);
1468 }
1469 DIR_DEBUG0("done\n");
1470 return dir;
1471 }
1472
1473 /* Return a copy of dirSearchPath, incrementing the reference counts for
1474 * the contained directories. */
1475 SearchPath *
1476 Dir_CopyDirSearchPath(void)
1477 {
1478 SearchPath *path = Lst_New();
1479 SearchPathNode *ln;
1480 for (ln = dirSearchPath->first; ln != NULL; ln = ln->next) {
1481 CachedDir *dir = ln->datum;
1482 dir->refCount++;
1483 Lst_Append(path, dir);
1484 }
1485 return path;
1486 }
1487
1488 /*-
1489 *-----------------------------------------------------------------------
1490 * SearchPath_ToFlags --
1491 * Make a string by taking all the directories in the given search
1492 * path and preceding them by the given flag. Used by the suffix
1493 * module to create variables for compilers based on suffix search
1494 * paths.
1495 *
1496 * Input:
1497 * flag flag which should precede each directory
1498 * path list of directories
1499 *
1500 * Results:
1501 * The string mentioned above. Note that there is no space between
1502 * the given flag and each directory. The empty string is returned if
1503 * Things don't go well.
1504 *
1505 * Side Effects:
1506 * None
1507 *-----------------------------------------------------------------------
1508 */
1509 char *
1510 SearchPath_ToFlags(const char *flag, SearchPath *path)
1511 {
1512 Buffer buf;
1513 SearchPathNode *ln;
1514
1515 Buf_Init(&buf);
1516
1517 if (path != NULL) {
1518 for (ln = path->first; ln != NULL; ln = ln->next) {
1519 CachedDir *dir = ln->datum;
1520 Buf_AddStr(&buf, " ");
1521 Buf_AddStr(&buf, flag);
1522 Buf_AddStr(&buf, dir->name);
1523 }
1524 }
1525
1526 return Buf_Destroy(&buf, FALSE);
1527 }
1528
1529 /* Nuke a directory descriptor, if possible. Callback procedure for the
1530 * suffixes module when destroying a search path.
1531 *
1532 * Input:
1533 * dirp The directory descriptor to nuke
1534 */
1535 void
1536 Dir_Destroy(void *dirp)
1537 {
1538 CachedDir *dir = dirp;
1539 dir->refCount--;
1540
1541 if (dir->refCount == 0) {
1542 OpenDirs_Remove(&openDirs, dir->name);
1543
1544 HashSet_Done(&dir->files);
1545 free(dir->name);
1546 free(dir);
1547 }
1548 }
1549
1550 /* Clear out all elements from the given search path.
1551 * The path is set to the empty list but is not destroyed. */
1552 void
1553 SearchPath_Clear(SearchPath *path)
1554 {
1555 while (!Lst_IsEmpty(path)) {
1556 CachedDir *dir = Lst_Dequeue(path);
1557 Dir_Destroy(dir);
1558 }
1559 }
1560
1561
1562 /* Concatenate two paths, adding the second to the end of the first,
1563 * skipping duplicates. */
1564 void
1565 SearchPath_AddAll(SearchPath *dst, SearchPath *src)
1566 {
1567 SearchPathNode *ln;
1568
1569 for (ln = src->first; ln != NULL; ln = ln->next) {
1570 CachedDir *dir = ln->datum;
1571 if (Lst_FindDatum(dst, dir) == NULL) {
1572 dir->refCount++;
1573 Lst_Append(dst, dir);
1574 }
1575 }
1576 }
1577
1578 static int
1579 percentage(int num, int den)
1580 {
1581 return den != 0 ? num * 100 / den : 0;
1582 }
1583
1584 /********** DEBUG INFO **********/
1585 void
1586 Dir_PrintDirectories(void)
1587 {
1588 CachedDirListNode *ln;
1589
1590 debug_printf("#*** Directory Cache:\n");
1591 debug_printf(
1592 "# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
1593 hits, misses, nearmisses, bigmisses,
1594 percentage(hits, hits + bigmisses + nearmisses));
1595 debug_printf("# %-20s referenced\thits\n", "directory");
1596
1597 for (ln = openDirs.list->first; ln != NULL; ln = ln->next) {
1598 CachedDir *dir = ln->datum;
1599 debug_printf("# %-20s %10d\t%4d\n",
1600 dir->name, dir->refCount, dir->hits);
1601 }
1602 }
1603
1604 void
1605 SearchPath_Print(SearchPath *path)
1606 {
1607 SearchPathNode *node;
1608 for (node = path->first; node != NULL; node = node->next) {
1609 const CachedDir *dir = node->datum;
1610 debug_printf("%s ", dir->name);
1611 }
1612 }
1613