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