dir.c revision 1.172 1 /* $NetBSD: dir.c,v 1.172 2020/10/22 05:50:02 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.172 2020/10/22 05:50:02 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 static void MAKE_ATTR_UNUSED
235 OpenDirs_Done(OpenDirs *odirs)
236 {
237 CachedDirListNode *ln = odirs->list->first;
238 while (ln != NULL) {
239 CachedDirListNode *next = ln->next;
240 CachedDir *dir = ln->datum;
241 Dir_Destroy(dir); /* removes the dir from odirs->list */
242 ln = next;
243 }
244 Lst_Free(odirs->list);
245 Hash_DeleteTable(&odirs->table);
246 }
247
248 static CachedDir *
249 OpenDirs_Find(OpenDirs *odirs, const char *name)
250 {
251 CachedDirListNode *ln = Hash_FindValue(&odirs->table, name);
252 return ln != NULL ? ln->datum : NULL;
253 }
254
255 static void
256 OpenDirs_Add(OpenDirs *odirs, CachedDir *cdir)
257 {
258 HashEntry *he = Hash_FindEntry(&odirs->table, cdir->name);
259 if (he != NULL)
260 return;
261 he = Hash_CreateEntry(&odirs->table, cdir->name, NULL);
262 Lst_Append(odirs->list, cdir);
263 Hash_SetValue(he, odirs->list->last);
264 }
265
266 static void
267 OpenDirs_Remove(OpenDirs *odirs, const char *name)
268 {
269 HashEntry *he = Hash_FindEntry(&odirs->table, name);
270 CachedDirListNode *ln;
271 if (he == NULL)
272 return;
273 ln = Hash_GetValue(he);
274 Hash_DeleteEntry(&odirs->table, he);
275 Lst_Remove(odirs->list, ln);
276 }
277
278 static OpenDirs openDirs; /* the list of all open directories */
279
280 /*
281 * Variables for gathering statistics on the efficiency of the hashing
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 /*
306 * We use stat(2) a lot, cache the results.
307 * mtime and mode are all we care about.
308 */
309 struct cache_st {
310 time_t lmtime; /* lstat */
311 time_t mtime; /* stat */
312 mode_t mode;
313 };
314
315 /* minimize changes below */
316 typedef enum CachedStatsFlags {
317 CST_LSTAT = 0x01, /* call lstat(2) instead of stat(2) */
318 CST_UPDATE = 0x02 /* ignore existing cached entry */
319 } CachedStatsFlags;
320
321 /* Returns 0 and the result of stat(2) or lstat(2) in *mst, or -1 on error. */
322 static int
323 cached_stats(HashTable *htp, const char *pathname, struct make_stat *mst,
324 CachedStatsFlags flags)
325 {
326 HashEntry *entry;
327 struct stat sys_st;
328 struct cache_st *cst;
329 int rc;
330
331 if (!pathname || !pathname[0])
332 return -1;
333
334 entry = Hash_FindEntry(htp, pathname);
335
336 if (entry && !(flags & CST_UPDATE)) {
337 cst = Hash_GetValue(entry);
338
339 mst->mst_mode = cst->mode;
340 mst->mst_mtime = (flags & CST_LSTAT) ? cst->lmtime : cst->mtime;
341 if (mst->mst_mtime) {
342 DIR_DEBUG2("Using cached time %s for %s\n",
343 Targ_FmtTime(mst->mst_mtime), pathname);
344 return 0;
345 }
346 }
347
348 rc = (flags & CST_LSTAT)
349 ? lstat(pathname, &sys_st)
350 : stat(pathname, &sys_st);
351 if (rc == -1)
352 return -1;
353
354 if (sys_st.st_mtime == 0)
355 sys_st.st_mtime = 1; /* avoid confusion with missing file */
356
357 mst->mst_mode = sys_st.st_mode;
358 mst->mst_mtime = sys_st.st_mtime;
359
360 if (entry == NULL)
361 entry = Hash_CreateEntry(htp, pathname, NULL);
362 if (Hash_GetValue(entry) == NULL) {
363 Hash_SetValue(entry, bmake_malloc(sizeof(*cst)));
364 memset(Hash_GetValue(entry), 0, sizeof(*cst));
365 }
366 cst = Hash_GetValue(entry);
367 if (flags & CST_LSTAT) {
368 cst->lmtime = sys_st.st_mtime;
369 } else {
370 cst->mtime = sys_st.st_mtime;
371 }
372 cst->mode = sys_st.st_mode;
373 DIR_DEBUG2(" Caching %s for %s\n",
374 Targ_FmtTime(sys_st.st_mtime), pathname);
375
376 return 0;
377 }
378
379 int
380 cached_stat(const char *pathname, struct make_stat *st)
381 {
382 return cached_stats(&mtimes, pathname, st, 0);
383 }
384
385 int
386 cached_lstat(const char *pathname, struct make_stat *st)
387 {
388 return cached_stats(&lmtimes, pathname, st, CST_LSTAT);
389 }
390
391 /* Initialize the directories module. */
392 void
393 Dir_Init(void)
394 {
395 dirSearchPath = Lst_New();
396 OpenDirs_Init(&openDirs);
397 Hash_InitTable(&mtimes);
398 Hash_InitTable(&lmtimes);
399 }
400
401 void
402 Dir_InitDir(const char *cdname)
403 {
404 Dir_InitCur(cdname);
405
406 dotLast = bmake_malloc(sizeof(CachedDir));
407 dotLast->refCount = 1;
408 dotLast->hits = 0;
409 dotLast->name = bmake_strdup(".DOTLAST");
410 Hash_InitTable(&dotLast->files);
411 }
412
413 /*
414 * Called by Dir_InitDir and whenever .CURDIR is assigned to.
415 */
416 void
417 Dir_InitCur(const char *cdname)
418 {
419 CachedDir *dir;
420
421 if (cdname != NULL) {
422 /*
423 * Our build directory is not the same as our source directory.
424 * Keep this one around too.
425 */
426 if ((dir = Dir_AddDir(NULL, cdname))) {
427 dir->refCount++;
428 if (cur && cur != dir) {
429 /*
430 * We've been here before, clean up.
431 */
432 cur->refCount--;
433 Dir_Destroy(cur);
434 }
435 cur = dir;
436 }
437 }
438 }
439
440 /* (Re)initialize "dot" (current/object directory) path hash.
441 * Some directories may be opened. */
442 void
443 Dir_InitDot(void)
444 {
445 if (dot != NULL) {
446 /* Remove old entry from openDirs, but do not destroy. */
447 OpenDirs_Remove(&openDirs, dot->name);
448 }
449
450 dot = Dir_AddDir(NULL, ".");
451
452 if (dot == NULL) {
453 Error("Cannot open `.' (%s)", strerror(errno));
454 exit(1);
455 }
456
457 /*
458 * We always need to have dot around, so we increment its reference count
459 * to make sure it's not destroyed.
460 */
461 dot->refCount++;
462 Dir_SetPATH(); /* initialize */
463 }
464
465 /* Clean up the directories module. */
466 void
467 Dir_End(void)
468 {
469 #ifdef CLEANUP
470 if (cur) {
471 cur->refCount--;
472 Dir_Destroy(cur);
473 }
474 dot->refCount--;
475 dotLast->refCount--;
476 Dir_Destroy(dotLast);
477 Dir_Destroy(dot);
478 Dir_ClearPath(dirSearchPath);
479 Lst_Free(dirSearchPath);
480 OpenDirs_Done(&openDirs);
481 Hash_DeleteTable(&mtimes);
482 #endif
483 }
484
485 /*
486 * We want ${.PATH} to indicate the order in which we will actually
487 * search, so we rebuild it after any .PATH: target.
488 * This is the simplest way to deal with the effect of .DOTLAST.
489 */
490 void
491 Dir_SetPATH(void)
492 {
493 CachedDirListNode *ln;
494 Boolean hasLastDot = FALSE; /* true if we should search dot last */
495
496 Var_Delete(".PATH", VAR_GLOBAL);
497
498 if ((ln = dirSearchPath->first) != NULL) {
499 CachedDir *dir = ln->datum;
500 if (dir == dotLast) {
501 hasLastDot = TRUE;
502 Var_Append(".PATH", dotLast->name, VAR_GLOBAL);
503 }
504 }
505
506 if (!hasLastDot) {
507 if (dot)
508 Var_Append(".PATH", dot->name, VAR_GLOBAL);
509 if (cur)
510 Var_Append(".PATH", cur->name, VAR_GLOBAL);
511 }
512
513 for (ln = dirSearchPath->first; ln != NULL; ln = ln->next) {
514 CachedDir *dir = ln->datum;
515 if (dir == dotLast)
516 continue;
517 if (dir == dot && hasLastDot)
518 continue;
519 Var_Append(".PATH", dir->name, VAR_GLOBAL);
520 }
521
522 if (hasLastDot) {
523 if (dot)
524 Var_Append(".PATH", dot->name, VAR_GLOBAL);
525 if (cur)
526 Var_Append(".PATH", cur->name, VAR_GLOBAL);
527 }
528 }
529
530 /* See if the CachedDir structure describes the same directory as the
531 * given one by comparing their names. Called from Dir_AddDir via
532 * Lst_Find when searching the list of open directories. */
533 static Boolean
534 DirFindName(const void *p, const void *desiredName)
535 {
536 const CachedDir *dir = p;
537 return strcmp(dir->name, desiredName) == 0;
538 }
539
540 /* See if the given name has any wildcard characters in it. Be careful not to
541 * expand unmatching brackets or braces.
542 *
543 * XXX: This code is not 100% correct ([^]] fails etc.). I really don't think
544 * that make(1) should be expanding patterns, because then you have to set a
545 * mechanism for escaping the expansion!
546 *
547 * Input:
548 * name name to check
549 *
550 * Results:
551 * returns TRUE if the word should be expanded, FALSE otherwise
552 */
553 Boolean
554 Dir_HasWildcards(const char *name)
555 {
556 const char *cp;
557 Boolean wild = FALSE;
558 int braces = 0, brackets = 0;
559
560 for (cp = name; *cp; cp++) {
561 switch (*cp) {
562 case '{':
563 braces++;
564 wild = TRUE;
565 break;
566 case '}':
567 braces--;
568 break;
569 case '[':
570 brackets++;
571 wild = TRUE;
572 break;
573 case ']':
574 brackets--;
575 break;
576 case '?':
577 case '*':
578 wild = TRUE;
579 break;
580 default:
581 break;
582 }
583 }
584 return wild && brackets == 0 && braces == 0;
585 }
586
587 /*-
588 *-----------------------------------------------------------------------
589 * DirMatchFiles --
590 * Given a pattern and a CachedDir structure, see if any files
591 * match the pattern and add their names to the 'expansions' list if
592 * any do. This is incomplete -- it doesn't take care of patterns like
593 * src / *src / *.c properly (just *.c on any of the directories), but it
594 * will do for now.
595 *
596 * Input:
597 * pattern Pattern to look for
598 * dir Directory to search
599 * expansion Place to store the results
600 *
601 * Side Effects:
602 * File names are added to the expansions lst. The directory will be
603 * fully hashed when this is done.
604 *-----------------------------------------------------------------------
605 */
606 static void
607 DirMatchFiles(const char *pattern, CachedDir *dir, StringList *expansions)
608 {
609 HashIter hi;
610 HashEntry *entry; /* Current entry in the table */
611 Boolean isDot; /* TRUE if the directory being searched is . */
612
613 isDot = (dir->name[0] == '.' && dir->name[1] == '\0');
614
615 HashIter_Init(&hi, &dir->files);
616 while ((entry = HashIter_Next(&hi)) != NULL) {
617 /*
618 * See if the file matches the given pattern. Note we follow the UNIX
619 * convention that dot files will only be found if the pattern
620 * begins with a dot (note also that as a side effect of the hashing
621 * scheme, .* won't match . or .. since they aren't hashed).
622 */
623 if (Str_Match(entry->key, pattern) &&
624 (entry->key[0] != '.' || pattern[0] == '.'))
625 {
626 Lst_Append(expansions,
627 (isDot ? bmake_strdup(entry->key) :
628 str_concat3(dir->name, "/", entry->key)));
629 }
630 }
631 }
632
633 /* Find the next closing brace in the string, taking nested braces into
634 * account. */
635 static const char *
636 closing_brace(const char *p)
637 {
638 int nest = 0;
639 while (*p != '\0') {
640 if (*p == '}' && nest == 0)
641 break;
642 if (*p == '{')
643 nest++;
644 if (*p == '}')
645 nest--;
646 p++;
647 }
648 return p;
649 }
650
651 /* Find the next closing brace or comma in the string, taking nested braces
652 * into account. */
653 static const char *
654 separator_comma(const char *p)
655 {
656 int nest = 0;
657 while (*p != '\0') {
658 if ((*p == '}' || *p == ',') && nest == 0)
659 break;
660 if (*p == '{')
661 nest++;
662 if (*p == '}')
663 nest--;
664 p++;
665 }
666 return p;
667 }
668
669 static Boolean
670 contains_wildcard(const char *p)
671 {
672 for (; *p != '\0'; p++) {
673 switch (*p) {
674 case '*':
675 case '?':
676 case '{':
677 case '[':
678 return TRUE;
679 }
680 }
681 return FALSE;
682 }
683
684 static char *
685 concat3(const char *a, size_t a_len, const char *b, size_t b_len,
686 const char *c, size_t c_len)
687 {
688 size_t s_len = a_len + b_len + c_len;
689 char *s = bmake_malloc(s_len + 1);
690 memcpy(s, a, a_len);
691 memcpy(s + a_len, b, b_len);
692 memcpy(s + a_len + b_len, c, c_len);
693 s[s_len] = '\0';
694 return s;
695 }
696
697 /*-
698 *-----------------------------------------------------------------------
699 * DirExpandCurly --
700 * Expand curly braces like the C shell. Does this recursively.
701 * Note the special case: if after the piece of the curly brace is
702 * done there are no wildcard characters in the result, the result is
703 * placed on the list WITHOUT CHECKING FOR ITS EXISTENCE.
704 *
705 * Input:
706 * word Entire word to expand
707 * brace First curly brace in it
708 * path Search path to use
709 * expansions Place to store the expansions
710 *
711 * Results:
712 * None.
713 *
714 * Side Effects:
715 * The given list is filled with the expansions...
716 *
717 *-----------------------------------------------------------------------
718 */
719 static void
720 DirExpandCurly(const char *word, const char *brace, SearchPath *path,
721 StringList *expansions)
722 {
723 const char *prefix, *middle, *piece, *middle_end, *suffix;
724 size_t prefix_len, suffix_len;
725
726 /* Split the word into prefix '{' middle '}' suffix. */
727
728 middle = brace + 1;
729 middle_end = closing_brace(middle);
730 if (*middle_end == '\0') {
731 Error("Unterminated {} clause \"%s\"", middle);
732 return;
733 }
734
735 prefix = word;
736 prefix_len = (size_t)(brace - prefix);
737 suffix = middle_end + 1;
738 suffix_len = strlen(suffix);
739
740 /* Split the middle into pieces, separated by commas. */
741
742 piece = middle;
743 while (piece < middle_end + 1) {
744 const char *piece_end = separator_comma(piece);
745 size_t piece_len = (size_t)(piece_end - piece);
746
747 char *file = concat3(prefix, prefix_len, piece, piece_len,
748 suffix, suffix_len);
749
750 if (contains_wildcard(file)) {
751 Dir_Expand(file, path, expansions);
752 free(file);
753 } else {
754 Lst_Append(expansions, file);
755 }
756
757 piece = piece_end + 1; /* skip over the comma or closing brace */
758 }
759 }
760
761
762 /*-
763 *-----------------------------------------------------------------------
764 * DirExpandInt --
765 * Internal expand routine. Passes through the directories in the
766 * path one by one, calling DirMatchFiles for each. NOTE: This still
767 * doesn't handle patterns in directories...
768 *
769 * Input:
770 * word Word to expand
771 * path Directory in which to look
772 * expansions Place to store the result
773 *
774 * Results:
775 * None.
776 *
777 * Side Effects:
778 * Things are added to the expansions list.
779 *
780 *-----------------------------------------------------------------------
781 */
782 static void
783 DirExpandInt(const char *word, SearchPath *path, StringList *expansions)
784 {
785 SearchPathNode *ln;
786 for (ln = path->first; ln != NULL; ln = ln->next) {
787 CachedDir *dir = ln->datum;
788 DirMatchFiles(word, dir, expansions);
789 }
790 }
791
792 static void
793 DirPrintExpansions(StringList *words)
794 {
795 StringListNode *ln;
796 for (ln = words->first; ln != NULL; ln = ln->next) {
797 const char *word = ln->datum;
798 debug_printf("%s ", word);
799 }
800 debug_printf("\n");
801 }
802
803 /*-
804 *-----------------------------------------------------------------------
805 * Dir_Expand --
806 * Expand the given word into a list of words by globbing it looking
807 * in the directories on the given search path.
808 *
809 * Input:
810 * word the word to expand
811 * path the list of directories in which to find the
812 * resulting files
813 * expansions the list on which to place the results
814 *
815 * Results:
816 * A list of words consisting of the files which exist along the search
817 * path matching the given pattern.
818 *
819 * Side Effects:
820 * Directories may be opened. Who knows?
821 * Undefined behavior if the word is really in read-only memory.
822 *-----------------------------------------------------------------------
823 */
824 void
825 Dir_Expand(const char *word, SearchPath *path, StringList *expansions)
826 {
827 const char *cp;
828
829 assert(path != NULL);
830 assert(expansions != NULL);
831
832 DIR_DEBUG1("Expanding \"%s\"... ", word);
833
834 cp = strchr(word, '{');
835 if (cp) {
836 DirExpandCurly(word, cp, path, expansions);
837 } else {
838 cp = strchr(word, '/');
839 if (cp) {
840 /*
841 * The thing has a directory component -- find the first wildcard
842 * in the string.
843 */
844 for (cp = word; *cp; cp++) {
845 if (*cp == '?' || *cp == '[' || *cp == '*' || *cp == '{') {
846 break;
847 }
848 }
849 if (*cp == '{') {
850 /*
851 * This one will be fun.
852 */
853 DirExpandCurly(word, cp, path, expansions);
854 return;
855 } else if (*cp != '\0') {
856 /*
857 * Back up to the start of the component
858 */
859 while (cp > word && *cp != '/') {
860 cp--;
861 }
862 if (cp != word) {
863 char sc;
864 char *dirpath;
865 /*
866 * If the glob isn't in the first component, try and find
867 * all the components up to the one with a wildcard.
868 */
869 sc = cp[1];
870 ((char *)UNCONST(cp))[1] = '\0';
871 dirpath = Dir_FindFile(word, path);
872 ((char *)UNCONST(cp))[1] = sc;
873 /*
874 * dirpath is null if can't find the leading component
875 * XXX: Dir_FindFile won't find internal components.
876 * i.e. if the path contains ../Etc/Object and we're
877 * looking for Etc, it won't be found. Ah well.
878 * Probably not important.
879 */
880 if (dirpath != NULL) {
881 char *dp = &dirpath[strlen(dirpath) - 1];
882 if (*dp == '/')
883 *dp = '\0';
884 path = Lst_New();
885 (void)Dir_AddDir(path, dirpath);
886 DirExpandInt(cp + 1, path, expansions);
887 Lst_Free(path);
888 }
889 } else {
890 /*
891 * Start the search from the local directory
892 */
893 DirExpandInt(word, path, expansions);
894 }
895 } else {
896 /*
897 * Return the file -- this should never happen.
898 */
899 DirExpandInt(word, path, expansions);
900 }
901 } else {
902 /*
903 * First the files in dot
904 */
905 DirMatchFiles(word, dot, expansions);
906
907 /*
908 * Then the files in every other directory on the path.
909 */
910 DirExpandInt(word, path, expansions);
911 }
912 }
913 if (DEBUG(DIR))
914 DirPrintExpansions(expansions);
915 }
916
917 /*-
918 *-----------------------------------------------------------------------
919 * DirLookup --
920 * Find if the file with the given name exists in the given path.
921 *
922 * Results:
923 * The path to the file or NULL. This path is guaranteed to be in a
924 * different part of memory than name and so may be safely free'd.
925 *
926 * Side Effects:
927 * None.
928 *-----------------------------------------------------------------------
929 */
930 static char *
931 DirLookup(CachedDir *dir, const char *name MAKE_ATTR_UNUSED, const char *cp,
932 Boolean hasSlash MAKE_ATTR_UNUSED)
933 {
934 char *file; /* the current filename to check */
935
936 DIR_DEBUG1(" %s ...\n", dir->name);
937
938 if (Hash_FindEntry(&dir->files, cp) == NULL)
939 return NULL;
940
941 file = str_concat3(dir->name, "/", cp);
942 DIR_DEBUG1(" returning %s\n", file);
943 dir->hits++;
944 hits++;
945 return file;
946 }
947
948
949 /*-
950 *-----------------------------------------------------------------------
951 * DirLookupSubdir --
952 * Find if the file with the given name exists in the given path.
953 *
954 * Results:
955 * The path to the file or NULL. This path is guaranteed to be in a
956 * different part of memory than name and so may be safely free'd.
957 *
958 * Side Effects:
959 * If the file is found, it is added in the modification times hash
960 * table.
961 *-----------------------------------------------------------------------
962 */
963 static char *
964 DirLookupSubdir(CachedDir *dir, const char *name)
965 {
966 struct make_stat mst;
967 char *file; /* the current filename to check */
968
969 if (dir != dot) {
970 file = str_concat3(dir->name, "/", name);
971 } else {
972 /*
973 * Checking in dot -- DON'T put a leading ./ on the thing.
974 */
975 file = bmake_strdup(name);
976 }
977
978 DIR_DEBUG1("checking %s ...\n", file);
979
980 if (cached_stat(file, &mst) == 0) {
981 nearmisses++;
982 return file;
983 }
984 free(file);
985 return NULL;
986 }
987
988 /*-
989 *-----------------------------------------------------------------------
990 * DirLookupAbs --
991 * Find if the file with the given name exists in the given path.
992 *
993 * Results:
994 * The path to the file, the empty string or NULL. If the file is
995 * the empty string, the search should be terminated.
996 * This path is guaranteed to be in a different part of memory
997 * than name and so may be safely free'd.
998 *
999 * Side Effects:
1000 * None.
1001 *-----------------------------------------------------------------------
1002 */
1003 static char *
1004 DirLookupAbs(CachedDir *dir, const char *name, const char *cp)
1005 {
1006 char *p1; /* pointer into dir->name */
1007 const char *p2; /* pointer into name */
1008
1009 DIR_DEBUG1(" %s ...\n", dir->name);
1010
1011 /*
1012 * If the file has a leading path component and that component
1013 * exactly matches the entire name of the current search
1014 * directory, we can attempt another cache lookup. And if we don't
1015 * have a hit, we can safely assume the file does not exist at all.
1016 */
1017 for (p1 = dir->name, p2 = name; *p1 && *p1 == *p2; p1++, p2++) {
1018 continue;
1019 }
1020 if (*p1 != '\0' || p2 != cp - 1) {
1021 return NULL;
1022 }
1023
1024 if (Hash_FindEntry(&dir->files, cp) == NULL) {
1025 DIR_DEBUG0(" must be here but isn't -- returning\n");
1026 /* Return empty string: terminates search */
1027 return bmake_strdup("");
1028 }
1029
1030 dir->hits++;
1031 hits++;
1032 DIR_DEBUG1(" returning %s\n", name);
1033 return bmake_strdup(name);
1034 }
1035
1036 /*-
1037 *-----------------------------------------------------------------------
1038 * DirFindDot --
1039 * Find the file given on "." or curdir
1040 *
1041 * Results:
1042 * The path to the file or NULL. This path is guaranteed to be in a
1043 * different part of memory than name and so may be safely free'd.
1044 *
1045 * Side Effects:
1046 * Hit counts change
1047 *-----------------------------------------------------------------------
1048 */
1049 static char *
1050 DirFindDot(Boolean hasSlash MAKE_ATTR_UNUSED, const char *name, const char *cp)
1051 {
1052
1053 if (Hash_FindEntry(&dot->files, cp) != NULL) {
1054 DIR_DEBUG0(" in '.'\n");
1055 hits++;
1056 dot->hits++;
1057 return bmake_strdup(name);
1058 }
1059 if (cur && Hash_FindEntry(&cur->files, cp) != NULL) {
1060 DIR_DEBUG1(" in ${.CURDIR} = %s\n", cur->name);
1061 hits++;
1062 cur->hits++;
1063 return str_concat3(cur->name, "/", cp);
1064 }
1065
1066 return NULL;
1067 }
1068
1069 /*-
1070 *-----------------------------------------------------------------------
1071 * Dir_FindFile --
1072 * Find the file with the given name along the given search path.
1073 *
1074 * Input:
1075 * name the file to find
1076 * path the Lst of directories to search
1077 *
1078 * Results:
1079 * The path to the file or NULL. This path is guaranteed to be in a
1080 * different part of memory than name and so may be safely free'd.
1081 *
1082 * Side Effects:
1083 * If the file is found in a directory which is not on the path
1084 * already (either 'name' is absolute or it is a relative path
1085 * [ dir1/.../dirn/file ] which exists below one of the directories
1086 * already on the search path), its directory is added to the end
1087 * of the path on the assumption that there will be more files in
1088 * that directory later on. Sometimes this is true. Sometimes not.
1089 *-----------------------------------------------------------------------
1090 */
1091 char *
1092 Dir_FindFile(const char *name, SearchPath *path)
1093 {
1094 SearchPathNode *ln;
1095 char *file; /* the current filename to check */
1096 const char *base; /* Terminal name of file */
1097 Boolean hasLastDot = FALSE; /* true if we should search dot last */
1098 Boolean hasSlash; /* true if 'name' contains a / */
1099 struct make_stat mst; /* Buffer for stat, if necessary */
1100 const char *trailing_dot = ".";
1101
1102 /*
1103 * Find the final component of the name and note whether it has a
1104 * slash in it (the name, I mean)
1105 */
1106 base = strrchr(name, '/');
1107 if (base) {
1108 hasSlash = TRUE;
1109 base++;
1110 } else {
1111 hasSlash = FALSE;
1112 base = name;
1113 }
1114
1115 DIR_DEBUG1("Searching for %s ...", name);
1116
1117 if (path == NULL) {
1118 DIR_DEBUG0("couldn't open path, file not found\n");
1119 misses++;
1120 return NULL;
1121 }
1122
1123 if ((ln = path->first) != NULL) {
1124 CachedDir *dir = ln->datum;
1125 if (dir == dotLast) {
1126 hasLastDot = TRUE;
1127 DIR_DEBUG0("[dot last]...");
1128 }
1129 }
1130 DIR_DEBUG0("\n");
1131
1132 /*
1133 * If there's no leading directory components or if the leading
1134 * directory component is exactly `./', consult the cached contents
1135 * of each of the directories on the search path.
1136 */
1137 if (!hasSlash || (base - name == 2 && *name == '.')) {
1138 /*
1139 * We look through all the directories on the path seeking one which
1140 * contains the final component of the given name. If such a beast
1141 * is found, we concatenate the directory name and the final
1142 * component and return the resulting string. If we don't find any
1143 * such thing, we go on to phase two...
1144 *
1145 * No matter what, we always look for the file in the current
1146 * directory before anywhere else (unless we found the magic
1147 * DOTLAST path, in which case we search it last) and we *do not*
1148 * add the ./ to it if it exists.
1149 * This is so there are no conflicts between what the user
1150 * specifies (fish.c) and what pmake finds (./fish.c).
1151 */
1152 if (!hasLastDot && (file = DirFindDot(hasSlash, name, base)) != NULL)
1153 return file;
1154
1155 for (; ln != NULL; ln = ln->next) {
1156 CachedDir *dir = ln->datum;
1157 if (dir == dotLast)
1158 continue;
1159 if ((file = DirLookup(dir, name, base, hasSlash)) != NULL)
1160 return file;
1161 }
1162
1163 if (hasLastDot && (file = DirFindDot(hasSlash, name, base)) != NULL)
1164 return file;
1165 }
1166
1167 /*
1168 * We didn't find the file on any directory in the search path.
1169 * If the name doesn't contain a slash, that means it doesn't exist.
1170 * If it *does* contain a slash, however, there is still hope: it
1171 * could be in a subdirectory of one of the members of the search
1172 * path. (eg. /usr/include and sys/types.h. The above search would
1173 * fail to turn up types.h in /usr/include, but it *is* in
1174 * /usr/include/sys/types.h).
1175 * [ This no longer applies: If we find such a beast, we assume there
1176 * will be more (what else can we assume?) and add all but the last
1177 * component of the resulting name onto the search path (at the
1178 * end).]
1179 * This phase is only performed if the file is *not* absolute.
1180 */
1181 if (!hasSlash) {
1182 DIR_DEBUG0(" failed.\n");
1183 misses++;
1184 return NULL;
1185 }
1186
1187 if (*base == '\0') {
1188 /* we were given a trailing "/" */
1189 base = trailing_dot;
1190 }
1191
1192 if (name[0] != '/') {
1193 Boolean checkedDot = FALSE;
1194
1195 DIR_DEBUG0(" Trying subdirectories...\n");
1196
1197 if (!hasLastDot) {
1198 if (dot) {
1199 checkedDot = TRUE;
1200 if ((file = DirLookupSubdir(dot, name)) != NULL)
1201 return file;
1202 }
1203 if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
1204 return file;
1205 }
1206
1207 for (ln = path->first; ln != NULL; ln = ln->next) {
1208 CachedDir *dir = ln->datum;
1209 if (dir == dotLast)
1210 continue;
1211 if (dir == dot) {
1212 if (checkedDot)
1213 continue;
1214 checkedDot = TRUE;
1215 }
1216 if ((file = DirLookupSubdir(dir, name)) != NULL)
1217 return file;
1218 }
1219
1220 if (hasLastDot) {
1221 if (dot && !checkedDot) {
1222 checkedDot = TRUE;
1223 if ((file = DirLookupSubdir(dot, name)) != NULL)
1224 return file;
1225 }
1226 if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
1227 return file;
1228 }
1229
1230 if (checkedDot) {
1231 /*
1232 * Already checked by the given name, since . was in the path,
1233 * so no point in proceeding...
1234 */
1235 DIR_DEBUG0(" Checked . already, returning NULL\n");
1236 return NULL;
1237 }
1238
1239 } else { /* name[0] == '/' */
1240
1241 /*
1242 * For absolute names, compare directory path prefix against the
1243 * the directory path of each member on the search path for an exact
1244 * match. If we have an exact match on any member of the search path,
1245 * use the cached contents of that member to lookup the final file
1246 * component. If that lookup fails we can safely assume that the
1247 * file does not exist at all. This is signified by DirLookupAbs()
1248 * returning an empty string.
1249 */
1250 DIR_DEBUG0(" Trying exact path matches...\n");
1251
1252 if (!hasLastDot && cur &&
1253 ((file = DirLookupAbs(cur, name, base)) != NULL)) {
1254 if (file[0] == '\0') {
1255 free(file);
1256 return NULL;
1257 }
1258 return file;
1259 }
1260
1261 for (ln = path->first; ln != NULL; ln = ln->next) {
1262 CachedDir *dir = ln->datum;
1263 if (dir == dotLast)
1264 continue;
1265 if ((file = DirLookupAbs(dir, name, base)) != NULL) {
1266 if (file[0] == '\0') {
1267 free(file);
1268 return NULL;
1269 }
1270 return file;
1271 }
1272 }
1273
1274 if (hasLastDot && cur &&
1275 ((file = DirLookupAbs(cur, name, base)) != NULL)) {
1276 if (file[0] == '\0') {
1277 free(file);
1278 return NULL;
1279 }
1280 return file;
1281 }
1282 }
1283
1284 /*
1285 * Didn't find it that way, either. Sigh. Phase 3. Add its directory
1286 * onto the search path in any case, just in case, then look for the
1287 * thing in the hash table. If we find it, grand. We return a new
1288 * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
1289 * Note that if the directory holding the file doesn't exist, this will
1290 * do an extra search of the final directory on the path. Unless something
1291 * weird happens, this search won't succeed and life will be groovy.
1292 *
1293 * Sigh. We cannot add the directory onto the search path because
1294 * of this amusing case:
1295 * $(INSTALLDIR)/$(FILE): $(FILE)
1296 *
1297 * $(FILE) exists in $(INSTALLDIR) but not in the current one.
1298 * When searching for $(FILE), we will find it in $(INSTALLDIR)
1299 * b/c we added it here. This is not good...
1300 */
1301 #ifdef notdef
1302 if (base == trailing_dot) {
1303 base = strrchr(name, '/');
1304 base++;
1305 }
1306 base[-1] = '\0';
1307 (void)Dir_AddDir(path, name);
1308 base[-1] = '/';
1309
1310 bigmisses++;
1311 ln = Lst_Last(path);
1312 if (ln == NULL) {
1313 return NULL;
1314 } else {
1315 dir = LstNode_Datum(ln);
1316 }
1317
1318 if (Hash_FindEntry(&dir->files, base) != NULL) {
1319 return bmake_strdup(name);
1320 } else {
1321 return NULL;
1322 }
1323 #else /* !notdef */
1324 DIR_DEBUG1(" Looking for \"%s\" ...\n", name);
1325
1326 bigmisses++;
1327 if (cached_stat(name, &mst) == 0) {
1328 return bmake_strdup(name);
1329 }
1330
1331 DIR_DEBUG0(" failed. Returning NULL\n");
1332 return NULL;
1333 #endif /* notdef */
1334 }
1335
1336
1337 /* Search for a path starting at a given directory and then working our way
1338 * up towards the root.
1339 *
1340 * Input:
1341 * here starting directory
1342 * search_path the relative path we are looking for
1343 *
1344 * Results:
1345 * The found path, or NULL.
1346 */
1347 char *
1348 Dir_FindHereOrAbove(const char *here, const char *search_path)
1349 {
1350 struct make_stat mst;
1351 char *dirbase, *dirbase_end;
1352 char *try, *try_end;
1353
1354 /* copy out our starting point */
1355 dirbase = bmake_strdup(here);
1356 dirbase_end = dirbase + strlen(dirbase);
1357
1358 /* loop until we determine a result */
1359 for (;;) {
1360
1361 /* try and stat(2) it ... */
1362 try = str_concat3(dirbase, "/", search_path);
1363 if (cached_stat(try, &mst) != -1) {
1364 /*
1365 * success! if we found a file, chop off
1366 * the filename so we return a directory.
1367 */
1368 if ((mst.mst_mode & S_IFMT) != S_IFDIR) {
1369 try_end = try + strlen(try);
1370 while (try_end > try && *try_end != '/')
1371 try_end--;
1372 if (try_end > try)
1373 *try_end = '\0'; /* chop! */
1374 }
1375
1376 free(dirbase);
1377 return try;
1378 }
1379 free(try);
1380
1381 /*
1382 * nope, we didn't find it. if we used up dirbase we've
1383 * reached the root and failed.
1384 */
1385 if (dirbase_end == dirbase)
1386 break; /* failed! */
1387
1388 /*
1389 * truncate dirbase from the end to move up a dir
1390 */
1391 while (dirbase_end > dirbase && *dirbase_end != '/')
1392 dirbase_end--;
1393 *dirbase_end = '\0'; /* chop! */
1394 }
1395
1396 free(dirbase);
1397 return NULL;
1398 }
1399
1400 /*-
1401 *-----------------------------------------------------------------------
1402 * Dir_MTime --
1403 * Find the modification time of the file described by gn along the
1404 * search path dirSearchPath.
1405 *
1406 * Input:
1407 * gn the file whose modification time is desired
1408 *
1409 * Results:
1410 * The modification time or 0 if it doesn't exist
1411 *
1412 * Side Effects:
1413 * The modification time is placed in the node's mtime slot.
1414 * If the node didn't have a path entry before, and Dir_FindFile
1415 * found one for it, the full name is placed in the path slot.
1416 *-----------------------------------------------------------------------
1417 */
1418 time_t
1419 Dir_MTime(GNode *gn, Boolean recheck)
1420 {
1421 char *fullName; /* the full pathname of name */
1422 struct make_stat mst; /* buffer for finding the mod time */
1423
1424 if (gn->type & OP_ARCHV) {
1425 return Arch_MTime(gn);
1426 } else if (gn->type & OP_PHONY) {
1427 gn->mtime = 0;
1428 return 0;
1429 } else if (gn->path == NULL) {
1430 if (gn->type & OP_NOPATH)
1431 fullName = NULL;
1432 else {
1433 fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
1434 if (fullName == NULL && gn->flags & FROM_DEPEND &&
1435 !Lst_IsEmpty(gn->implicitParents)) {
1436 char *cp;
1437
1438 cp = strrchr(gn->name, '/');
1439 if (cp) {
1440 /*
1441 * This is an implied source, and it may have moved,
1442 * see if we can find it via the current .PATH
1443 */
1444 cp++;
1445
1446 fullName = Dir_FindFile(cp, Suff_FindPath(gn));
1447 if (fullName) {
1448 /*
1449 * Put the found file in gn->path
1450 * so that we give that to the compiler.
1451 */
1452 gn->path = bmake_strdup(fullName);
1453 if (!Job_RunTarget(".STALE", gn->fname))
1454 fprintf(stdout,
1455 "%s: %s, %d: ignoring stale %s for %s, "
1456 "found %s\n", progname, gn->fname,
1457 gn->lineno,
1458 makeDependfile, gn->name, fullName);
1459 }
1460 }
1461 }
1462 DIR_DEBUG2("Found '%s' as '%s'\n",
1463 gn->name, fullName ? fullName : "(not found)");
1464 }
1465 } else {
1466 fullName = gn->path;
1467 }
1468
1469 if (fullName == NULL) {
1470 fullName = bmake_strdup(gn->name);
1471 }
1472
1473 if (cached_stats(&mtimes, fullName, &mst, recheck ? CST_UPDATE : 0) < 0) {
1474 if (gn->type & OP_MEMBER) {
1475 if (fullName != gn->path)
1476 free(fullName);
1477 return Arch_MemMTime(gn);
1478 } else {
1479 mst.mst_mtime = 0;
1480 }
1481 }
1482
1483 if (fullName && gn->path == NULL) {
1484 gn->path = fullName;
1485 }
1486
1487 gn->mtime = mst.mst_mtime;
1488 return gn->mtime;
1489 }
1490
1491 /* Read the list of filenames in the directory and store the result
1492 * in openDirectories.
1493 *
1494 * If a path is given, append the directory to that path.
1495 *
1496 * Input:
1497 * path The path to which the directory should be
1498 * added, or NULL to only add the directory to
1499 * openDirectories
1500 * name The name of the directory to add.
1501 * The name is not normalized in any way.
1502 */
1503 CachedDir *
1504 Dir_AddDir(SearchPath *path, const char *name)
1505 {
1506 CachedDir *dir = NULL; /* the added directory */
1507 DIR *d;
1508 struct dirent *dp;
1509
1510 if (path != NULL && strcmp(name, ".DOTLAST") == 0) {
1511 SearchPathNode *ln = Lst_Find(path, DirFindName, name);
1512 if (ln != NULL)
1513 return ln->datum;
1514
1515 dotLast->refCount++;
1516 Lst_Prepend(path, dotLast);
1517 }
1518
1519 if (path != NULL)
1520 dir = OpenDirs_Find(&openDirs, name);
1521 if (dir != NULL) {
1522 if (Lst_FindDatum(path, dir) == NULL) {
1523 dir->refCount++;
1524 Lst_Append(path, dir);
1525 }
1526 return dir;
1527 }
1528
1529 DIR_DEBUG1("Caching %s ...", name);
1530
1531 if ((d = opendir(name)) != NULL) {
1532 dir = bmake_malloc(sizeof(CachedDir));
1533 dir->name = bmake_strdup(name);
1534 dir->hits = 0;
1535 dir->refCount = 1;
1536 Hash_InitTable(&dir->files);
1537
1538 while ((dp = readdir(d)) != NULL) {
1539 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
1540 /*
1541 * The sun directory library doesn't check for a 0 inode
1542 * (0-inode slots just take up space), so we have to do
1543 * it ourselves.
1544 */
1545 if (dp->d_fileno == 0) {
1546 continue;
1547 }
1548 #endif /* sun && d_ino */
1549 (void)Hash_CreateEntry(&dir->files, dp->d_name, NULL);
1550 }
1551 (void)closedir(d);
1552 OpenDirs_Add(&openDirs, dir);
1553 if (path != NULL)
1554 Lst_Append(path, dir);
1555 }
1556 DIR_DEBUG0("done\n");
1557 return dir;
1558 }
1559
1560 /*-
1561 *-----------------------------------------------------------------------
1562 * Dir_CopyDir --
1563 * Callback function for duplicating a search path via Lst_Copy.
1564 * Ups the reference count for the directory.
1565 *
1566 * Results:
1567 * Returns the Path it was given.
1568 *-----------------------------------------------------------------------
1569 */
1570 void *
1571 Dir_CopyDir(void *p)
1572 {
1573 CachedDir *dir = p;
1574 dir->refCount++;
1575 return dir;
1576 }
1577
1578 /*-
1579 *-----------------------------------------------------------------------
1580 * Dir_MakeFlags --
1581 * Make a string by taking all the directories in the given search
1582 * path and preceding them by the given flag. Used by the suffix
1583 * module to create variables for compilers based on suffix search
1584 * paths.
1585 *
1586 * Input:
1587 * flag flag which should precede each directory
1588 * path list of directories
1589 *
1590 * Results:
1591 * The string mentioned above. Note that there is no space between
1592 * the given flag and each directory. The empty string is returned if
1593 * Things don't go well.
1594 *
1595 * Side Effects:
1596 * None
1597 *-----------------------------------------------------------------------
1598 */
1599 char *
1600 Dir_MakeFlags(const char *flag, SearchPath *path)
1601 {
1602 Buffer buf;
1603 SearchPathNode *ln;
1604
1605 Buf_Init(&buf, 0);
1606
1607 if (path != NULL) {
1608 for (ln = path->first; ln != NULL; ln = ln->next) {
1609 CachedDir *dir = ln->datum;
1610 Buf_AddStr(&buf, " ");
1611 Buf_AddStr(&buf, flag);
1612 Buf_AddStr(&buf, dir->name);
1613 }
1614 }
1615
1616 return Buf_Destroy(&buf, FALSE);
1617 }
1618
1619 /*-
1620 *-----------------------------------------------------------------------
1621 * Dir_Destroy --
1622 * Nuke a directory descriptor, if possible. Callback procedure
1623 * for the suffixes module when destroying a search path.
1624 *
1625 * Input:
1626 * dirp The directory descriptor to nuke
1627 *
1628 * Results:
1629 * None.
1630 *
1631 * Side Effects:
1632 * If no other path references this directory (refCount == 0),
1633 * the CachedDir and all its data are freed.
1634 *
1635 *-----------------------------------------------------------------------
1636 */
1637 void
1638 Dir_Destroy(void *dirp)
1639 {
1640 CachedDir *dir = dirp;
1641 dir->refCount--;
1642
1643 if (dir->refCount == 0) {
1644 OpenDirs_Remove(&openDirs, dir->name);
1645
1646 Hash_DeleteTable(&dir->files);
1647 free(dir->name);
1648 free(dir);
1649 }
1650 }
1651
1652 /*-
1653 *-----------------------------------------------------------------------
1654 * Dir_ClearPath --
1655 * Clear out all elements of the given search path. This is different
1656 * from destroying the list, notice.
1657 *
1658 * Input:
1659 * path Path to clear
1660 *
1661 * Results:
1662 * None.
1663 *
1664 * Side Effects:
1665 * The path is set to the empty list.
1666 *
1667 *-----------------------------------------------------------------------
1668 */
1669 void
1670 Dir_ClearPath(SearchPath *path)
1671 {
1672 while (!Lst_IsEmpty(path)) {
1673 CachedDir *dir = Lst_Dequeue(path);
1674 Dir_Destroy(dir);
1675 }
1676 }
1677
1678
1679 /*-
1680 *-----------------------------------------------------------------------
1681 * Dir_Concat --
1682 * Concatenate two paths, adding the second to the end of the first.
1683 * Makes sure to avoid duplicates.
1684 *
1685 * Input:
1686 * path1 Dest
1687 * path2 Source
1688 *
1689 * Results:
1690 * None
1691 *
1692 * Side Effects:
1693 * Reference counts for added dirs are upped.
1694 *
1695 *-----------------------------------------------------------------------
1696 */
1697 void
1698 Dir_Concat(SearchPath *path1, SearchPath *path2)
1699 {
1700 SearchPathNode *ln;
1701
1702 for (ln = path2->first; ln != NULL; ln = ln->next) {
1703 CachedDir *dir = ln->datum;
1704 if (Lst_FindDatum(path1, dir) == NULL) {
1705 dir->refCount++;
1706 Lst_Append(path1, dir);
1707 }
1708 }
1709 }
1710
1711 static int
1712 percentage(int num, int den)
1713 {
1714 return den != 0 ? num * 100 / den : 0;
1715 }
1716
1717 /********** DEBUG INFO **********/
1718 void
1719 Dir_PrintDirectories(void)
1720 {
1721 CachedDirListNode *ln;
1722
1723 debug_printf("#*** Directory Cache:\n");
1724 debug_printf("# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
1725 hits, misses, nearmisses, bigmisses,
1726 percentage(hits, hits + bigmisses + nearmisses));
1727 debug_printf("# %-20s referenced\thits\n", "directory");
1728
1729 for (ln = openDirs.list->first; ln != NULL; ln = ln->next) {
1730 CachedDir *dir = ln->datum;
1731 debug_printf("# %-20s %10d\t%4d\n", dir->name, dir->refCount,
1732 dir->hits);
1733 }
1734 }
1735
1736 void
1737 Dir_PrintPath(SearchPath *path)
1738 {
1739 SearchPathNode *node;
1740 for (node = path->first; node != NULL; node = node->next) {
1741 const CachedDir *dir = node->datum;
1742 debug_printf("%s ", dir->name);
1743 }
1744 }
1745