dir.c revision 1.228 1 /* $NetBSD: dir.c,v 1.228 2020/11/29 01:40:26 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.228 2020/11/29 01:40:26 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 = LST_INIT; /* 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 Lst_Init(&odirs->list);
229 HashTable_Init(&odirs->table);
230 }
231
232 static void Dir_Destroy(CachedDir *);
233
234 #ifdef CLEANUP
235 static void
236 OpenDirs_Done(OpenDirs *odirs)
237 {
238 CachedDirListNode *ln = odirs->list.first;
239 while (ln != NULL) {
240 CachedDirListNode *next = ln->next;
241 CachedDir *dir = ln->datum;
242 Dir_Destroy(dir); /* removes the dir from odirs->list */
243 ln = next;
244 }
245 Lst_Done(&odirs->list);
246 HashTable_Done(&odirs->table);
247 }
248 #endif
249
250 static CachedDir *
251 OpenDirs_Find(OpenDirs *odirs, const char *name)
252 {
253 CachedDirListNode *ln = HashTable_FindValue(&odirs->table, name);
254 return ln != NULL ? ln->datum : NULL;
255 }
256
257 static void
258 OpenDirs_Add(OpenDirs *odirs, CachedDir *cdir)
259 {
260 if (HashTable_FindEntry(&odirs->table, cdir->name) != NULL)
261 return;
262 Lst_Append(&odirs->list, cdir);
263 HashTable_Set(&odirs->table, cdir->name, odirs->list.last);
264 }
265
266 static void
267 OpenDirs_Remove(OpenDirs *odirs, const char *name)
268 {
269 HashEntry *he = HashTable_FindEntry(&odirs->table, name);
270 CachedDirListNode *ln;
271 if (he == NULL)
272 return;
273 ln = HashEntry_Get(he);
274 HashTable_DeleteEntry(&odirs->table, he);
275 Lst_Remove(&odirs->list, ln);
276 }
277
278 static OpenDirs openDirs; /* all cached directories */
279
280 /*
281 * Variables for gathering statistics on the efficiency of the caching
282 * mechanism.
283 */
284 static int hits; /* Found in directory cache */
285 static int misses; /* Sad, but not evil misses */
286 static int nearmisses; /* Found under search path */
287 static int bigmisses; /* Sought by itself */
288
289 static CachedDir *dot; /* contents of current directory */
290 static CachedDir *cur; /* contents of current directory, if not dot */
291 static CachedDir *dotLast; /* a fake path entry indicating we need to
292 * look for . last */
293
294 /* Results of doing a last-resort stat in Dir_FindFile -- if we have to go to
295 * the system to find the file, we might as well have its mtime on record.
296 *
297 * XXX: If this is done way early, there's a chance other rules will have
298 * already updated the file, in which case we'll update it again. Generally,
299 * there won't be two rules to update a single file, so this should be ok,
300 * but... */
301 static HashTable mtimes;
302
303 static HashTable lmtimes; /* same as mtimes but for lstat */
304
305 typedef enum CachedStatsFlags {
306 CST_NONE = 0,
307 CST_LSTAT = 1 << 0, /* call lstat(2) instead of stat(2) */
308 CST_UPDATE = 1 << 1 /* ignore existing cached entry */
309 } CachedStatsFlags;
310
311 /* Returns 0 and the result of stat(2) or lstat(2) in *out_cst,
312 * or -1 on error. */
313 static int
314 cached_stats(const char *pathname, struct cached_stat *out_cst,
315 CachedStatsFlags flags)
316 {
317 HashTable *tbl = flags & CST_LSTAT ? &lmtimes : &mtimes;
318 struct stat sys_st;
319 struct cached_stat *cst;
320 int rc;
321
322 if (pathname == NULL || pathname[0] == '\0')
323 return -1; /* This can happen in meta mode. */
324
325 cst = HashTable_FindValue(tbl, pathname);
326 if (cst != NULL && !(flags & CST_UPDATE)) {
327 *out_cst = *cst;
328 DIR_DEBUG2("Using cached time %s for %s\n",
329 Targ_FmtTime(cst->cst_mtime), pathname);
330 return 0;
331 }
332
333 rc = (flags & CST_LSTAT ? lstat : stat)(pathname, &sys_st);
334 if (rc == -1)
335 return -1; /* don't cache negative lookups */
336
337 if (sys_st.st_mtime == 0)
338 sys_st.st_mtime = 1; /* avoid confusion with missing file */
339
340 if (cst == NULL) {
341 cst = bmake_malloc(sizeof *cst);
342 HashTable_Set(tbl, pathname, cst);
343 }
344
345 cst->cst_mtime = sys_st.st_mtime;
346 cst->cst_mode = sys_st.st_mode;
347
348 *out_cst = *cst;
349 DIR_DEBUG2(" Caching %s for %s\n",
350 Targ_FmtTime(sys_st.st_mtime), pathname);
351
352 return 0;
353 }
354
355 int
356 cached_stat(const char *pathname, struct cached_stat *cst)
357 {
358 return cached_stats(pathname, cst, CST_NONE);
359 }
360
361 int
362 cached_lstat(const char *pathname, struct cached_stat *cst)
363 {
364 return cached_stats(pathname, cst, CST_LSTAT);
365 }
366
367 /* Initialize the directories module. */
368 void
369 Dir_Init(void)
370 {
371 OpenDirs_Init(&openDirs);
372 HashTable_Init(&mtimes);
373 HashTable_Init(&lmtimes);
374 }
375
376 void
377 Dir_InitDir(const char *cdname)
378 {
379 Dir_InitCur(cdname);
380
381 dotLast = bmake_malloc(sizeof *dotLast);
382 dotLast->refCount = 1;
383 dotLast->hits = 0;
384 dotLast->name = bmake_strdup(".DOTLAST");
385 HashSet_Init(&dotLast->files);
386 }
387
388 /*
389 * Called by Dir_InitDir and whenever .CURDIR is assigned to.
390 */
391 void
392 Dir_InitCur(const char *cdname)
393 {
394 CachedDir *dir;
395
396 if (cdname == NULL)
397 return;
398
399 /*
400 * Our build directory is not the same as our source directory.
401 * Keep this one around too.
402 */
403 dir = Dir_AddDir(NULL, cdname);
404 if (dir == NULL)
405 return;
406
407 /* XXX: Reference counting is wrong here.
408 * If this function is called repeatedly with the same directory name,
409 * its reference count increases each time even though the number of
410 * actual references stays the same. */
411
412 dir->refCount++;
413 if (cur != NULL && cur != dir) {
414 /*
415 * We've been here before, clean up.
416 */
417 cur->refCount--;
418 Dir_Destroy(cur);
419 }
420 cur = dir;
421 }
422
423 /* (Re)initialize "dot" (current/object directory) path hash.
424 * Some directories may be opened. */
425 void
426 Dir_InitDot(void)
427 {
428 if (dot != NULL) {
429 /* Remove old entry from openDirs, but do not destroy. */
430 OpenDirs_Remove(&openDirs, dot->name);
431 }
432
433 dot = Dir_AddDir(NULL, ".");
434
435 if (dot == NULL) {
436 Error("Cannot open `.' (%s)", strerror(errno));
437 exit(1);
438 }
439
440 /*
441 * We always need to have dot around, so we increment its reference
442 * count to make sure it's not destroyed.
443 */
444 dot->refCount++;
445 Dir_SetPATH(); /* initialize */
446 }
447
448 /* Clean up the directories module. */
449 void
450 Dir_End(void)
451 {
452 #ifdef CLEANUP
453 if (cur != NULL) {
454 cur->refCount--;
455 Dir_Destroy(cur);
456 }
457 dot->refCount--;
458 dotLast->refCount--;
459 Dir_Destroy(dotLast);
460 Dir_Destroy(dot);
461 SearchPath_Clear(&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 = SearchPath_New();
858 (void)Dir_AddDir(partPath, dirpath);
859 DirExpandPath(cp + 1, partPath, expansions);
860 Lst_Free(partPath);
861 /* XXX: Should the dirs in partPath be freed here?
862 * It's not obvious whether to free them or not. */
863 }
864 }
865
866 done:
867 if (DEBUG(DIR))
868 PrintExpansions(expansions);
869 }
870
871 /* Find if the file with the given name exists in the given path.
872 * Return the freshly allocated path to the file, or NULL. */
873 static char *
874 DirLookup(CachedDir *dir, const char *base)
875 {
876 char *file; /* the current filename to check */
877
878 DIR_DEBUG1(" %s ...\n", dir->name);
879
880 if (!HashSet_Contains(&dir->files, base))
881 return NULL;
882
883 file = str_concat3(dir->name, "/", base);
884 DIR_DEBUG1(" returning %s\n", file);
885 dir->hits++;
886 hits++;
887 return file;
888 }
889
890
891 /* Find if the file with the given name exists in the given directory.
892 * Return the freshly allocated path to the file, or NULL. */
893 static char *
894 DirLookupSubdir(CachedDir *dir, const char *name)
895 {
896 struct cached_stat cst;
897 char *file = dir == dot ? bmake_strdup(name)
898 : str_concat3(dir->name, "/", name);
899
900 DIR_DEBUG1("checking %s ...\n", file);
901
902 if (cached_stat(file, &cst) == 0) {
903 nearmisses++;
904 return file;
905 }
906 free(file);
907 return NULL;
908 }
909
910 /* Find if the file with the given name exists in the given path.
911 * Return the freshly allocated path to the file, the empty string, or NULL.
912 * Returning the empty string means that the search should be terminated.
913 */
914 static char *
915 DirLookupAbs(CachedDir *dir, const char *name, const char *cp)
916 {
917 const char *dnp; /* pointer into dir->name */
918 const char *np; /* pointer into name */
919
920 DIR_DEBUG1(" %s ...\n", dir->name);
921
922 /*
923 * If the file has a leading path component and that component
924 * exactly matches the entire name of the current search
925 * directory, we can attempt another cache lookup. And if we don't
926 * have a hit, we can safely assume the file does not exist at all.
927 */
928 for (dnp = dir->name, np = name;
929 *dnp != '\0' && *dnp == *np; dnp++, np++)
930 continue;
931 if (*dnp != '\0' || np != cp - 1)
932 return NULL;
933
934 if (!HashSet_Contains(&dir->files, cp)) {
935 DIR_DEBUG0(" must be here but isn't -- returning\n");
936 return bmake_strdup(""); /* to terminate the search */
937 }
938
939 dir->hits++;
940 hits++;
941 DIR_DEBUG1(" returning %s\n", name);
942 return bmake_strdup(name);
943 }
944
945 /* Find the file given on "." or curdir.
946 * Return the freshly allocated path to the file, or NULL. */
947 static char *
948 DirFindDot(const char *name, const char *base)
949 {
950
951 if (HashSet_Contains(&dot->files, base)) {
952 DIR_DEBUG0(" in '.'\n");
953 hits++;
954 dot->hits++;
955 return bmake_strdup(name);
956 }
957
958 if (cur != NULL && HashSet_Contains(&cur->files, base)) {
959 DIR_DEBUG1(" in ${.CURDIR} = %s\n", cur->name);
960 hits++;
961 cur->hits++;
962 return str_concat3(cur->name, "/", base);
963 }
964
965 return NULL;
966 }
967
968 /* Find the file with the given name along the given search path.
969 *
970 * If the file is found in a directory that is not on the path
971 * already (either 'name' is absolute or it is a relative path
972 * [ dir1/.../dirn/file ] which exists below one of the directories
973 * already on the search path), its directory is added to the end
974 * of the path, on the assumption that there will be more files in
975 * that directory later on. Sometimes this is true. Sometimes not.
976 *
977 * Input:
978 * name the file to find
979 * path the directories to search, or NULL
980 *
981 * Results:
982 * The freshly allocated path to the file, or NULL.
983 */
984 char *
985 Dir_FindFile(const char *name, SearchPath *path)
986 {
987 char *file; /* the current filename to check */
988 const char *base; /* Terminal name of file */
989 Boolean hasLastDot = FALSE; /* true if we should search dot last */
990 Boolean hasSlash; /* true if 'name' contains a / */
991 struct cached_stat cst; /* Buffer for stat, if necessary */
992 const char *trailing_dot = ".";
993
994 /*
995 * Find the final component of the name and note whether it has a
996 * slash in it (the name, I mean)
997 */
998 base = strrchr(name, '/');
999 if (base != NULL) {
1000 hasSlash = TRUE;
1001 base++;
1002 } else {
1003 hasSlash = FALSE;
1004 base = name;
1005 }
1006
1007 DIR_DEBUG1("Searching for %s ...", name);
1008
1009 if (path == NULL) {
1010 DIR_DEBUG0("couldn't open path, file not found\n");
1011 misses++;
1012 return NULL;
1013 }
1014
1015 if (path->first != NULL) {
1016 CachedDir *dir = path->first->datum;
1017 if (dir == dotLast) {
1018 hasLastDot = TRUE;
1019 DIR_DEBUG0("[dot last]...");
1020 }
1021 }
1022 DIR_DEBUG0("\n");
1023
1024 /*
1025 * If there's no leading directory components or if the leading
1026 * directory component is exactly `./', consult the cached contents
1027 * of each of the directories on the search path.
1028 */
1029 if (!hasSlash || (base - name == 2 && *name == '.')) {
1030 SearchPathNode *ln;
1031
1032 /*
1033 * We look through all the directories on the path seeking one
1034 * which contains the final component of the given name. If
1035 * such a beast is found, we concatenate the directory name
1036 * and the final component and return the resulting string.
1037 * If we don't find any such thing, we go on to phase two.
1038 *
1039 * No matter what, we always look for the file in the current
1040 * directory before anywhere else (unless we found the magic
1041 * DOTLAST path, in which case we search it last) and we *do
1042 * not* add the ./ to it if it exists.
1043 * This is so there are no conflicts between what the user
1044 * specifies (fish.c) and what pmake finds (./fish.c).
1045 */
1046 if (!hasLastDot && (file = DirFindDot(name, base)) != NULL)
1047 return file;
1048
1049 for (ln = path->first; ln != NULL; ln = ln->next) {
1050 CachedDir *dir = ln->datum;
1051 if (dir == dotLast)
1052 continue;
1053 if ((file = DirLookup(dir, base)) != NULL)
1054 return file;
1055 }
1056
1057 if (hasLastDot && (file = DirFindDot(name, base)) != NULL)
1058 return file;
1059 }
1060
1061 /*
1062 * We didn't find the file on any directory in the search path.
1063 * If the name doesn't contain a slash, that means it doesn't exist.
1064 * If it *does* contain a slash, however, there is still hope: it
1065 * could be in a subdirectory of one of the members of the search
1066 * path. (eg. /usr/include and sys/types.h. The above search would
1067 * fail to turn up types.h in /usr/include, but it *is* in
1068 * /usr/include/sys/types.h).
1069 * [ This no longer applies: If we find such a beast, we assume there
1070 * will be more (what else can we assume?) and add all but the last
1071 * component of the resulting name onto the search path (at the
1072 * end).]
1073 * This phase is only performed if the file is *not* absolute.
1074 */
1075 if (!hasSlash) {
1076 DIR_DEBUG0(" failed.\n");
1077 misses++;
1078 return NULL;
1079 }
1080
1081 if (*base == '\0') {
1082 /* we were given a trailing "/" */
1083 base = trailing_dot;
1084 }
1085
1086 if (name[0] != '/') {
1087 SearchPathNode *ln;
1088 Boolean checkedDot = FALSE;
1089
1090 DIR_DEBUG0(" Trying subdirectories...\n");
1091
1092 if (!hasLastDot) {
1093 if (dot != NULL) {
1094 checkedDot = TRUE;
1095 if ((file = DirLookupSubdir(dot, name)) != NULL)
1096 return file;
1097 }
1098 if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
1099 return file;
1100 }
1101
1102 for (ln = path->first; ln != NULL; ln = ln->next) {
1103 CachedDir *dir = ln->datum;
1104 if (dir == dotLast)
1105 continue;
1106 if (dir == dot) {
1107 if (checkedDot)
1108 continue;
1109 checkedDot = TRUE;
1110 }
1111 if ((file = DirLookupSubdir(dir, name)) != NULL)
1112 return file;
1113 }
1114
1115 if (hasLastDot) {
1116 if (dot && !checkedDot) {
1117 checkedDot = TRUE;
1118 if ((file = DirLookupSubdir(dot, name)) != NULL)
1119 return file;
1120 }
1121 if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
1122 return file;
1123 }
1124
1125 if (checkedDot) {
1126 /*
1127 * Already checked by the given name, since . was in
1128 * the path, so no point in proceeding.
1129 */
1130 DIR_DEBUG0(" Checked . already, returning NULL\n");
1131 return NULL;
1132 }
1133
1134 } else { /* name[0] == '/' */
1135 SearchPathNode *ln;
1136
1137 /*
1138 * For absolute names, compare directory path prefix against
1139 * the the directory path of each member on the search path
1140 * for an exact match. If we have an exact match on any member
1141 * of the search path, use the cached contents of that member
1142 * to lookup the final file component. If that lookup fails we
1143 * can safely assume that the file does not exist at all.
1144 * This is signified by DirLookupAbs() returning an empty
1145 * string.
1146 */
1147 DIR_DEBUG0(" Trying exact path matches...\n");
1148
1149 if (!hasLastDot && cur &&
1150 ((file = DirLookupAbs(cur, name, base)) != NULL)) {
1151 if (file[0] == '\0') {
1152 free(file);
1153 return NULL;
1154 }
1155 return file;
1156 }
1157
1158 for (ln = path->first; ln != NULL; ln = ln->next) {
1159 CachedDir *dir = ln->datum;
1160 if (dir == dotLast)
1161 continue;
1162 if ((file = DirLookupAbs(dir, name, base)) != NULL) {
1163 if (file[0] == '\0') {
1164 free(file);
1165 return NULL;
1166 }
1167 return file;
1168 }
1169 }
1170
1171 if (hasLastDot && cur &&
1172 ((file = DirLookupAbs(cur, name, base)) != NULL)) {
1173 if (file[0] == '\0') {
1174 free(file);
1175 return NULL;
1176 }
1177 return file;
1178 }
1179 }
1180
1181 /*
1182 * Didn't find it that way, either. Sigh. Phase 3. Add its directory
1183 * onto the search path in any case, just in case, then look for the
1184 * thing in the hash table. If we find it, grand. We return a new
1185 * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
1186 * Note that if the directory holding the file doesn't exist, this
1187 * will do an extra search of the final directory on the path. Unless
1188 * something weird happens, this search won't succeed and life will
1189 * be groovy.
1190 *
1191 * Sigh. We cannot add the directory onto the search path because
1192 * of this amusing case:
1193 * $(INSTALLDIR)/$(FILE): $(FILE)
1194 *
1195 * $(FILE) exists in $(INSTALLDIR) but not in the current one.
1196 * When searching for $(FILE), we will find it in $(INSTALLDIR)
1197 * b/c we added it here. This is not good...
1198 */
1199 #if 0
1200 {
1201 CachedDir *dir;
1202 char *prefix;
1203
1204 if (base == trailing_dot) {
1205 base = strrchr(name, '/');
1206 base++;
1207 }
1208 prefix = bmake_strsedup(name, base - 1);
1209 (void)Dir_AddDir(path, prefix);
1210 free(prefix);
1211
1212 bigmisses++;
1213 if (path->last == NULL)
1214 return NULL;
1215
1216 dir = path->last->datum;
1217 if (HashSet_Contains(&dir->files, base))
1218 return bmake_strdup(name);
1219 return NULL;
1220 }
1221 #else
1222 DIR_DEBUG1(" Looking for \"%s\" ...\n", name);
1223
1224 bigmisses++;
1225 if (cached_stat(name, &cst) == 0) {
1226 return bmake_strdup(name);
1227 }
1228
1229 DIR_DEBUG0(" failed. Returning NULL\n");
1230 return NULL;
1231 #endif
1232 }
1233
1234
1235 /* Search for a path starting at a given directory and then working our way
1236 * up towards the root.
1237 *
1238 * Input:
1239 * here starting directory
1240 * search_path the relative path we are looking for
1241 *
1242 * Results:
1243 * The found path, or NULL.
1244 */
1245 char *
1246 Dir_FindHereOrAbove(const char *here, const char *search_path)
1247 {
1248 struct cached_stat cst;
1249 char *dirbase, *dirbase_end;
1250 char *try, *try_end;
1251
1252 /* copy out our starting point */
1253 dirbase = bmake_strdup(here);
1254 dirbase_end = dirbase + strlen(dirbase);
1255
1256 /* loop until we determine a result */
1257 for (;;) {
1258
1259 /* try and stat(2) it ... */
1260 try = str_concat3(dirbase, "/", search_path);
1261 if (cached_stat(try, &cst) != -1) {
1262 /*
1263 * success! if we found a file, chop off
1264 * the filename so we return a directory.
1265 */
1266 if ((cst.cst_mode & S_IFMT) != S_IFDIR) {
1267 try_end = try + strlen(try);
1268 while (try_end > try && *try_end != '/')
1269 try_end--;
1270 if (try_end > try)
1271 *try_end = '\0'; /* chop! */
1272 }
1273
1274 free(dirbase);
1275 return try;
1276 }
1277 free(try);
1278
1279 /*
1280 * nope, we didn't find it. if we used up dirbase we've
1281 * reached the root and failed.
1282 */
1283 if (dirbase_end == dirbase)
1284 break; /* failed! */
1285
1286 /*
1287 * truncate dirbase from the end to move up a dir
1288 */
1289 while (dirbase_end > dirbase && *dirbase_end != '/')
1290 dirbase_end--;
1291 *dirbase_end = '\0'; /* chop! */
1292 }
1293
1294 free(dirbase);
1295 return NULL;
1296 }
1297
1298 /*
1299 * This is an implied source, and it may have moved,
1300 * see if we can find it via the current .PATH
1301 */
1302 static char *
1303 ResolveMovedDepends(GNode *gn)
1304 {
1305 char *fullName;
1306
1307 char *base = strrchr(gn->name, '/');
1308 if (base == NULL)
1309 return NULL;
1310 base++;
1311
1312 fullName = Dir_FindFile(base, Suff_FindPath(gn));
1313 if (fullName == NULL)
1314 return NULL;
1315
1316 /*
1317 * Put the found file in gn->path so that we give that to the compiler.
1318 */
1319 /*
1320 * XXX: Better just reset gn->path to NULL; updating it is already done
1321 * by Dir_UpdateMTime.
1322 */
1323 gn->path = bmake_strdup(fullName);
1324 if (!Job_RunTarget(".STALE", gn->fname))
1325 fprintf(stdout, /* XXX: Why stdout? */
1326 "%s: %s, %d: ignoring stale %s for %s, found %s\n",
1327 progname, gn->fname, gn->lineno,
1328 makeDependfile, gn->name, fullName);
1329
1330 return fullName;
1331 }
1332
1333 static char *
1334 ResolveFullName(GNode *gn)
1335 {
1336 char *fullName;
1337
1338 fullName = gn->path;
1339 if (fullName == NULL && !(gn->type & OP_NOPATH)) {
1340
1341 fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
1342
1343 if (fullName == NULL && gn->flags & FROM_DEPEND &&
1344 !Lst_IsEmpty(&gn->implicitParents))
1345 fullName = ResolveMovedDepends(gn);
1346
1347 DIR_DEBUG2("Found '%s' as '%s'\n",
1348 gn->name, fullName ? fullName : "(not found)");
1349 }
1350
1351 if (fullName == NULL)
1352 fullName = bmake_strdup(gn->name);
1353
1354 /* XXX: Is every piece of memory freed as it should? */
1355
1356 return fullName;
1357 }
1358
1359 /* Search gn along dirSearchPath and store its modification time in gn->mtime.
1360 * If no file is found, store 0 instead.
1361 *
1362 * The found file is stored in gn->path, unless the node already had a path. */
1363 void
1364 Dir_UpdateMTime(GNode *gn, Boolean recheck)
1365 {
1366 char *fullName;
1367 struct cached_stat cst;
1368
1369 if (gn->type & OP_ARCHV) {
1370 Arch_UpdateMTime(gn);
1371 return;
1372 }
1373
1374 if (gn->type & OP_PHONY) {
1375 gn->mtime = 0;
1376 return;
1377 }
1378
1379 fullName = ResolveFullName(gn);
1380
1381 if (cached_stats(fullName, &cst, recheck ? CST_UPDATE : CST_NONE) < 0) {
1382 if (gn->type & OP_MEMBER) {
1383 if (fullName != gn->path)
1384 free(fullName);
1385 Arch_UpdateMemberMTime(gn);
1386 return;
1387 }
1388
1389 cst.cst_mtime = 0;
1390 }
1391
1392 if (fullName != NULL && gn->path == NULL)
1393 gn->path = fullName;
1394 /* XXX: else free(fullName)? */
1395
1396 gn->mtime = cst.cst_mtime;
1397 }
1398
1399 /* Read the list of filenames in the directory and store the result
1400 * in openDirs.
1401 *
1402 * If a path is given, append the directory to that path.
1403 *
1404 * Input:
1405 * path The path to which the directory should be
1406 * added, or NULL to only add the directory to openDirs
1407 * name The name of the directory to add.
1408 * The name is not normalized in any way.
1409 */
1410 CachedDir *
1411 Dir_AddDir(SearchPath *path, const char *name)
1412 /*
1413 * XXX: Maybe return const CachedDir, as a hint that the return value must
1414 * not be freed since it is owned by openDirs.
1415 */
1416 {
1417 CachedDir *dir = NULL; /* the added directory */
1418 DIR *d;
1419 struct dirent *dp;
1420
1421 if (path != NULL && strcmp(name, ".DOTLAST") == 0) {
1422 SearchPathNode *ln;
1423
1424 /* XXX: Linear search gets slow with thousands of entries. */
1425 for (ln = path->first; ln != NULL; ln = ln->next) {
1426 CachedDir *pathDir = ln->datum;
1427 if (strcmp(pathDir->name, name) == 0)
1428 return pathDir;
1429 }
1430
1431 dotLast->refCount++;
1432 Lst_Prepend(path, dotLast);
1433 }
1434
1435 if (path != NULL)
1436 dir = OpenDirs_Find(&openDirs, name);
1437 if (dir != NULL) {
1438 if (Lst_FindDatum(path, dir) == NULL) {
1439 dir->refCount++;
1440 Lst_Append(path, dir);
1441 }
1442 return dir;
1443 }
1444
1445 DIR_DEBUG1("Caching %s ...", name);
1446
1447 if ((d = opendir(name)) != NULL) {
1448 dir = bmake_malloc(sizeof *dir);
1449 dir->name = bmake_strdup(name);
1450 dir->hits = 0;
1451 dir->refCount = 1;
1452 HashSet_Init(&dir->files);
1453
1454 while ((dp = readdir(d)) != NULL) {
1455 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
1456 /*
1457 * The sun directory library doesn't check for a 0 inode
1458 * (0-inode slots just take up space), so we have to do
1459 * it ourselves.
1460 */
1461 if (dp->d_fileno == 0)
1462 continue;
1463 #endif /* sun && d_ino */
1464 (void)HashSet_Add(&dir->files, dp->d_name);
1465 }
1466 (void)closedir(d);
1467 OpenDirs_Add(&openDirs, dir);
1468 if (path != NULL)
1469 Lst_Append(path, dir);
1470 }
1471 DIR_DEBUG0("done\n");
1472 return dir;
1473 }
1474
1475 /* Return a copy of dirSearchPath, incrementing the reference counts for
1476 * the contained directories. */
1477 SearchPath *
1478 Dir_CopyDirSearchPath(void)
1479 {
1480 SearchPath *path = SearchPath_New();
1481 SearchPathNode *ln;
1482 for (ln = dirSearchPath.first; ln != NULL; ln = ln->next) {
1483 CachedDir *dir = ln->datum;
1484 dir->refCount++;
1485 Lst_Append(path, dir);
1486 }
1487 return path;
1488 }
1489
1490 /*-
1491 *-----------------------------------------------------------------------
1492 * SearchPath_ToFlags --
1493 * Make a string by taking all the directories in the given search
1494 * path and preceding them by the given flag. Used by the suffix
1495 * module to create variables for compilers based on suffix search
1496 * paths.
1497 *
1498 * Input:
1499 * flag flag which should precede each directory
1500 * path list of directories
1501 *
1502 * Results:
1503 * The string mentioned above. Note that there is no space between
1504 * the given flag and each directory. The empty string is returned if
1505 * Things don't go well.
1506 *
1507 * Side Effects:
1508 * None
1509 *-----------------------------------------------------------------------
1510 */
1511 char *
1512 SearchPath_ToFlags(const char *flag, SearchPath *path)
1513 {
1514 Buffer buf;
1515 SearchPathNode *ln;
1516
1517 Buf_Init(&buf);
1518
1519 if (path != NULL) {
1520 for (ln = path->first; ln != NULL; ln = ln->next) {
1521 CachedDir *dir = ln->datum;
1522 Buf_AddStr(&buf, " ");
1523 Buf_AddStr(&buf, flag);
1524 Buf_AddStr(&buf, dir->name);
1525 }
1526 }
1527
1528 return Buf_Destroy(&buf, FALSE);
1529 }
1530
1531 /* Nuke a directory descriptor, if possible. Callback procedure for the
1532 * suffixes module when destroying a search path.
1533 *
1534 * Input:
1535 * dirp The directory descriptor to nuke
1536 */
1537 static void
1538 Dir_Destroy(CachedDir *dir)
1539 {
1540 dir->refCount--;
1541
1542 if (dir->refCount == 0) {
1543 OpenDirs_Remove(&openDirs, dir->name);
1544
1545 HashSet_Done(&dir->files);
1546 free(dir->name);
1547 free(dir);
1548 }
1549 }
1550
1551 /* Free the search path and all directories mentioned in it. */
1552 void
1553 SearchPath_Free(SearchPath *path)
1554 {
1555 SearchPathNode *ln;
1556
1557 for (ln = path->first; ln != NULL; ln = ln->next) {
1558 CachedDir *dir = ln->datum;
1559 Dir_Destroy(dir);
1560 }
1561 Lst_Free(path);
1562 }
1563
1564 /* Clear out all elements from the given search path.
1565 * The path is set to the empty list but is not destroyed. */
1566 void
1567 SearchPath_Clear(SearchPath *path)
1568 {
1569 while (!Lst_IsEmpty(path)) {
1570 CachedDir *dir = Lst_Dequeue(path);
1571 Dir_Destroy(dir);
1572 }
1573 }
1574
1575
1576 /* Concatenate two paths, adding the second to the end of the first,
1577 * skipping duplicates. */
1578 void
1579 SearchPath_AddAll(SearchPath *dst, SearchPath *src)
1580 {
1581 SearchPathNode *ln;
1582
1583 for (ln = src->first; ln != NULL; ln = ln->next) {
1584 CachedDir *dir = ln->datum;
1585 if (Lst_FindDatum(dst, dir) == NULL) {
1586 dir->refCount++;
1587 Lst_Append(dst, dir);
1588 }
1589 }
1590 }
1591
1592 static int
1593 percentage(int num, int den)
1594 {
1595 return den != 0 ? num * 100 / den : 0;
1596 }
1597
1598 /********** DEBUG INFO **********/
1599 void
1600 Dir_PrintDirectories(void)
1601 {
1602 CachedDirListNode *ln;
1603
1604 debug_printf("#*** Directory Cache:\n");
1605 debug_printf(
1606 "# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
1607 hits, misses, nearmisses, bigmisses,
1608 percentage(hits, hits + bigmisses + nearmisses));
1609 debug_printf("# %-20s referenced\thits\n", "directory");
1610
1611 for (ln = openDirs.list.first; ln != NULL; ln = ln->next) {
1612 CachedDir *dir = ln->datum;
1613 debug_printf("# %-20s %10d\t%4d\n",
1614 dir->name, dir->refCount, dir->hits);
1615 }
1616 }
1617
1618 void
1619 SearchPath_Print(SearchPath *path)
1620 {
1621 SearchPathNode *node;
1622 for (node = path->first; node != NULL; node = node->next) {
1623 const CachedDir *dir = node->datum;
1624 debug_printf("%s ", dir->name);
1625 }
1626 }
1627