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