1 /* $NetBSD: dir.c,v 1.280 2023/01/24 00:24:02 sjg Exp $ */
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
36 * Copyright (c) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
40 * This code is derived from software contributed to Berkeley by
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
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.
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
73 * Directory searching using wildcards and/or normal names.
74 * Used both for source wildcarding in the makefile and for finding
77 * The interface for this module is:
78 * Dir_Init Initialize the module.
80 * Dir_InitCur Set the cur CachedDir.
82 * Dir_InitDot Set the dot CachedDir.
84 * Dir_End Clean up the module.
86 * Dir_SetPATH Set ${.PATH} to reflect state of dirSearchPath.
89 * Returns true if the name given it needs to
90 * be wildcard-expanded.
93 * Expand a filename pattern to find all matching files
94 * from the search path.
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.
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 ("/").
106 * Update the modification time and path of a node with
107 * data from the file corresponding to the node.
109 * SearchPath_Add Add a directory to a search path.
112 * Given a search path and a command flag, create
113 * a string with each of the directories in the path
114 * preceded by the command flag and all of them
115 * separated by a space.
117 * Dir_Destroy Destroy an element of a search path. Frees up all
118 * things that can be freed for the element as long
119 * as the element is no longer referenced by any other
123 * Resets a search path to the empty list.
126 * Dir_PrintDirectories
127 * Print stats about the directory cache.
130 #include <sys/types.h>
131 #include <sys/stat.h>
140 /* "@(#)dir.c 8.2 (Berkeley) 1/2/94" */
141 MAKE_RCSID("$NetBSD: dir.c,v 1.280 2023/01/24 00:24:02 sjg Exp $");
144 * A search path is a list of CachedDir structures. A CachedDir has in it the
145 * name of the directory and the names of all the files in the directory.
146 * This is used to cut down on the number of system calls necessary to find
147 * implicit dependents and their like. Since these searches are made before
148 * any actions are taken, we need not worry about the directory changing due
149 * to creation commands. If this hampers the style of some makefiles, they
152 * All previously-read directories are kept in openDirs, which is checked
153 * first before a directory is opened.
155 * The need for the caching of whole directories is brought about by the
156 * multi-level transformation code in suff.c, which tends to search for far
157 * more files than regular make does. In the initial implementation, the
158 * amount of time spent performing "stat" calls was truly astronomical.
159 * The problem with caching at the start is, of course, that pmake doesn't
160 * then detect changes to these directories during the course of the make.
161 * Three possibilities suggest themselves:
163 * 1) just use stat to test for a file's existence. As mentioned above,
164 * this is very inefficient due to the number of checks engendered by
165 * the multi-level transformation code.
167 * 2) use readdir() and company to search the directories, keeping them
168 * open between checks. I have tried this and while it didn't slow down
169 * the process too much, it could severely affect the amount of
170 * parallelism available as each directory open would take another file
171 * descriptor out of play for handling I/O for another job. Given that
172 * it is only recently (as of 1993 or earlier) that UNIX OS's have taken
173 * to allowing more than 20 or 32 file descriptors for a process, this
174 * doesn't seem acceptable to me.
176 * 3) record the mtime of the directory in the CachedDir structure and
177 * verify the directory hasn't changed since the contents were cached.
178 * This will catch the creation or deletion of files, but not the
179 * updating of files. However, since it is the creation and deletion
180 * that is the problem, this could be a good thing to do. Unfortunately,
181 * if the directory (say ".") were fairly large and changed fairly
182 * frequently, the constant reloading could seriously degrade
183 * performance. It might be good in such cases to keep track of the
184 * number of reloadings and if the number goes over a (small) limit,
185 * resort to using stat in its place.
187 * An additional thing to consider is that pmake is used primarily to create
188 * C programs and until recently (as of 1993 or earlier) pcc-based compilers
189 * refused to allow you to specify where the resulting object file should be
190 * placed. This forced all objects to be created in the current directory.
191 * This isn't meant as a full excuse, just an explanation of some of the
192 * reasons for the caching used here.
194 * One more note: the location of a target's file is only performed on the
195 * downward traversal of the graph and then only for terminal nodes in the
196 * graph. This could be construed as wrong in some cases, but prevents
197 * inadvertent modification of files when the "installed" directory for a
198 * file is provided in the search path.
200 * Another data structure maintained by this module is an mtime cache used
201 * when the searching of cached directories fails to find a file. In the past,
202 * Dir_FindFile would simply perform an access() call in such a case to
203 * determine if the file could be found using just the name given. When this
204 * hit, however, all that was gained was the knowledge that the file existed.
205 * Given that an access() is essentially a stat() without the copyout() call,
206 * and that the same filesystem overhead would have to be incurred in
207 * Dir_MTime, it made sense to replace the access() with a stat() and record
208 * the mtime in a cache for when Dir_UpdateMTime was actually called.
212 /* A cache for the filenames in a directory. */
215 * Name of directory, either absolute or relative to the current
216 * directory. The name is not normalized in any way, that is, "."
217 * and "./." are different.
219 * Not sure what happens when .CURDIR is assigned a new value; see
225 * The number of SearchPaths that refer to this directory.
226 * Plus the number of global variables that refer to this directory.
227 * References from openDirs do not count though.
231 /* The number of times a file in this directory has been found. */
234 /* The names of the directory entries. */
238 typedef List CachedDirList;
239 typedef ListNode CachedDirListNode;
241 typedef ListNode SearchPathNode;
243 /* A list of cached directories, with fast lookup by directory name. */
244 typedef struct OpenDirs {
246 HashTable /* of CachedDirListNode */ table;
250 SearchPath dirSearchPath = { LST_INIT }; /* main search path */
252 static OpenDirs openDirs; /* all cached directories */
255 * Variables for gathering statistics on the efficiency of the caching
258 static int hits; /* Found in directory cache */
259 static int misses; /* Sad, but not evil misses */
260 static int nearmisses; /* Found under search path */
261 static int bigmisses; /* Sought by itself */
263 /* The cached contents of ".", the relative current directory. */
264 static CachedDir *dot = NULL;
265 /* The cached contents of the absolute current directory. */
266 static CachedDir *cur = NULL;
267 /* A fake path entry indicating we need to look for '.' last. */
268 static CachedDir *dotLast = NULL;
271 * Results of doing a last-resort stat in Dir_FindFile -- if we have to go to
272 * the system to find the file, we might as well have its mtime on record.
274 * XXX: If this is done way early, there's a chance other rules will have
275 * already updated the file, in which case we'll update it again. Generally,
276 * there won't be two rules to update a single file, so this should be ok,
279 static HashTable mtimes;
281 static HashTable lmtimes; /* same as mtimes but for lstat */
284 static void OpenDirs_Remove(OpenDirs *, const char *);
288 CachedDir_New(const char *name)
290 CachedDir *dir = bmake_malloc(sizeof *dir);
292 dir->name = bmake_strdup(name);
295 HashSet_Init(&dir->files);
298 DEBUG2(DIR, "CachedDir %p new for \"%s\"\n", dir, dir->name);
305 CachedDir_Ref(CachedDir *dir)
310 DEBUG3(DIR, "CachedDir %p ++ %d for \"%s\"\n",
311 dir, dir->refCount, dir->name);
318 CachedDir_Unref(CachedDir *dir)
323 DEBUG3(DIR, "CachedDir %p -- %d for \"%s\"\n",
324 dir, dir->refCount, dir->name);
327 if (dir->refCount > 0)
331 DEBUG2(DIR, "CachedDir %p free for \"%s\"\n", dir, dir->name);
334 OpenDirs_Remove(&openDirs, dir->name);
337 HashSet_Done(&dir->files);
341 /* Update the value of the CachedDir variable, updating the reference counts. */
343 CachedDir_Assign(CachedDir **var, CachedDir *dir)
352 CachedDir_Unref(prev);
356 OpenDirs_Init(OpenDirs *odirs)
358 Lst_Init(&odirs->list);
359 HashTable_Init(&odirs->table);
364 OpenDirs_Done(OpenDirs *odirs)
366 CachedDirListNode *ln = odirs->list.first;
367 DEBUG1(DIR, "OpenDirs_Done: %u entries to remove\n",
368 odirs->table.numEntries);
370 CachedDirListNode *next = ln->next;
371 CachedDir *dir = ln->datum;
372 DEBUG2(DIR, "OpenDirs_Done: refCount %d for \"%s\"\n",
373 dir->refCount, dir->name);
374 CachedDir_Unref(dir); /* removes the dir from odirs->list */
377 Lst_Done(&odirs->list);
378 HashTable_Done(&odirs->table);
383 OpenDirs_Find(OpenDirs *odirs, const char *name)
385 CachedDirListNode *ln = HashTable_FindValue(&odirs->table, name);
386 return ln != NULL ? ln->datum : NULL;
390 OpenDirs_Add(OpenDirs *odirs, CachedDir *cdir)
392 if (HashTable_FindEntry(&odirs->table, cdir->name) != NULL)
394 Lst_Append(&odirs->list, cdir);
395 HashTable_Set(&odirs->table, cdir->name, odirs->list.last);
399 OpenDirs_Remove(OpenDirs *odirs, const char *name)
401 HashEntry *he = HashTable_FindEntry(&odirs->table, name);
402 CachedDirListNode *ln;
405 ln = HashEntry_Get(he);
406 HashTable_DeleteEntry(&odirs->table, he);
407 Lst_Remove(&odirs->list, ln);
411 * Returns 0 and the result of stat(2) or lstat(2) in *out_cst,
415 cached_stats(const char *pathname, struct cached_stat *out_cst,
416 bool useLstat, bool forceRefresh)
418 HashTable *tbl = useLstat ? &lmtimes : &mtimes;
420 struct cached_stat *cst;
423 if (pathname == NULL || pathname[0] == '\0')
424 return -1; /* This can happen in meta mode. */
426 cst = HashTable_FindValue(tbl, pathname);
427 if (cst != NULL && !forceRefresh) {
429 DEBUG2(DIR, "Using cached time %s for %s\n",
430 Targ_FmtTime(cst->cst_mtime), pathname);
434 rc = (useLstat ? lstat : stat)(pathname, &sys_st);
436 return -1; /* don't cache negative lookups */
438 if (sys_st.st_mtime == 0)
439 sys_st.st_mtime = 1; /* avoid confusion with missing file */
442 cst = bmake_malloc(sizeof *cst);
443 HashTable_Set(tbl, pathname, cst);
446 cst->cst_mtime = sys_st.st_mtime;
447 cst->cst_mode = sys_st.st_mode;
450 DEBUG2(DIR, " Caching %s for %s\n",
451 Targ_FmtTime(sys_st.st_mtime), pathname);
457 cached_stat(const char *pathname, struct cached_stat *cst)
459 return cached_stats(pathname, cst, false, false);
463 cached_lstat(const char *pathname, struct cached_stat *cst)
465 return cached_stats(pathname, cst, true, false);
468 /* Initialize the directories module. */
472 OpenDirs_Init(&openDirs);
473 HashTable_Init(&mtimes);
474 HashTable_Init(&lmtimes);
475 CachedDir_Assign(&dotLast, CachedDir_New(".DOTLAST"));
479 * Called by Dir_InitDir and whenever .CURDIR is assigned to.
482 Dir_InitCur(const char *newCurdir)
486 if (newCurdir == NULL)
490 * Our build directory is not the same as our source directory.
491 * Keep this one around too.
493 dir = SearchPath_Add(NULL, newCurdir);
497 CachedDir_Assign(&cur, dir);
501 * (Re)initialize "dot" (current/object directory) path hash.
502 * Some directories may be cached.
509 dir = SearchPath_Add(NULL, ".");
511 Error("Cannot open `.' (%s)", strerror(errno));
512 exit(2); /* Not 1 so -q can distinguish error */
515 CachedDir_Assign(&dot, dir);
517 Dir_SetPATH(); /* initialize */
520 /* Clean up the directories module. */
525 CachedDir_Assign(&cur, NULL);
526 CachedDir_Assign(&dot, NULL);
527 CachedDir_Assign(&dotLast, NULL);
528 SearchPath_Clear(&dirSearchPath);
529 OpenDirs_Done(&openDirs);
530 HashTable_Done(&mtimes);
531 HashTable_Done(&lmtimes);
536 * We want ${.PATH} to indicate the order in which we will actually
537 * search, so we rebuild it after any .PATH: target.
538 * This is the simplest way to deal with the effect of .DOTLAST.
543 CachedDirListNode *ln;
544 bool seenDotLast = false; /* true if we should search '.' last */
546 Global_Delete(".PATH");
548 if ((ln = dirSearchPath.dirs.first) != NULL) {
549 CachedDir *dir = ln->datum;
550 if (dir == dotLast) {
552 Global_Append(".PATH", dotLast->name);
558 Global_Append(".PATH", dot->name);
560 Global_Append(".PATH", cur->name);
563 for (ln = dirSearchPath.dirs.first; ln != NULL; ln = ln->next) {
564 CachedDir *dir = ln->datum;
567 if (dir == dot && seenDotLast)
569 Global_Append(".PATH", dir->name);
574 Global_Append(".PATH", dot->name);
576 Global_Append(".PATH", cur->name);
584 CachedDirListNode *ln;
586 Var_ReadOnly(".SYSPATH", false);
587 Global_Delete(".SYSPATH");
588 for (ln = sysIncPath->dirs.first; ln != NULL; ln = ln->next) {
589 CachedDir *dir = ln->datum;
590 Global_Append(".SYSPATH", dir->name);
592 Var_ReadOnly(".SYSPATH", true);
596 * See if the given name has any wildcard characters in it and all braces and
597 * brackets are properly balanced.
599 * XXX: This code is not 100% correct ([^]] fails etc.). I really don't think
600 * that make(1) should be expanding patterns, because then you have to set a
601 * mechanism for escaping the expansion!
603 * Return true if the word should be expanded, false otherwise.
606 Dir_HasWildcards(const char *name)
610 int braces = 0, brackets = 0;
612 for (p = name; *p != '\0'; p++) {
636 return wild && brackets == 0 && braces == 0;
640 * See if any files match the pattern and add their names to the 'expansions'
643 * This is incomplete -- wildcards are only expanded in the final path
644 * component, but not in directories like src/lib*c/file*.c, but it
645 * will do for now (now being 1993 until at least 2020). To expand these,
646 * delegate the work to the shell, using the '!=' variable assignment
647 * operator, the ':sh' variable modifier or the ':!...!' variable modifier,
648 * such as in ${:!echo src/lib*c/file*.c!}.
651 * pattern Pattern to look for
652 * dir Directory to search
653 * expansion Place to store the results
656 DirMatchFiles(const char *pattern, CachedDir *dir, StringList *expansions)
658 const char *dirName = dir->name;
659 bool isDot = dirName[0] == '.' && dirName[1] == '\0';
663 * XXX: Iterating over all hash entries is inefficient. If the
664 * pattern is a plain string without any wildcards, a direct lookup
668 HashIter_InitSet(&hi, &dir->files);
669 while (HashIter_Next(&hi) != NULL) {
670 const char *base = hi.entry->key;
672 if (!Str_Match(base, pattern))
676 * Follow the UNIX convention that dot files are only found
677 * if the pattern begins with a dot. The pattern '.*' does
678 * not match '.' or '..' since these are not included in the
681 * This means that the pattern '[a-z.]*' does not find
682 * '.file', which is consistent with NetBSD sh, NetBSD ksh,
683 * bash, dash, csh and probably many other shells as well.
685 if (base[0] == '.' && pattern[0] != '.')
689 char *fullName = isDot
691 : str_concat3(dirName, "/", base);
692 Lst_Append(expansions, fullName);
698 * Find the next closing brace in the string, taking nested braces into
702 closing_brace(const char *p)
706 if (*p == '}' && nest == 0)
718 * Find the next closing brace or comma in the string, taking nested braces
722 separator_comma(const char *p)
726 if ((*p == '}' || *p == ',') && nest == 0)
738 contains_wildcard(const char *p)
740 for (; *p != '\0'; p++) {
753 concat3(const char *a, size_t a_len, const char *b, size_t b_len,
754 const char *c, size_t c_len)
756 size_t s_len = a_len + b_len + c_len;
757 char *s = bmake_malloc(s_len + 1);
759 memcpy(s + a_len, b, b_len);
760 memcpy(s + a_len + b_len, c, c_len);
766 * Expand curly braces like the C shell. Brace expansion by itself is purely
767 * textual, the expansions are not looked up in the file system. But if an
768 * expanded word contains wildcard characters, it is expanded further,
769 * matching only the actually existing files.
771 * Example: "{a{b,c}}" expands to "ab" and "ac".
772 * Example: "{a}" expands to "a".
773 * Example: "{a,*.c}" expands to "a" and all "*.c" files that exist.
776 * word Entire word to expand
777 * brace First curly brace in it
778 * path Search path to use
779 * expansions Place to store the expansions
782 DirExpandCurly(const char *word, const char *brace, SearchPath *path,
783 StringList *expansions)
785 const char *prefix, *middle, *piece, *middle_end, *suffix;
786 size_t prefix_len, suffix_len;
788 /* Split the word into prefix '{' middle '}' suffix. */
791 middle_end = closing_brace(middle);
792 if (*middle_end == '\0') {
793 Error("Unterminated {} clause \"%s\"", middle);
798 prefix_len = (size_t)(brace - prefix);
799 suffix = middle_end + 1;
800 suffix_len = strlen(suffix);
802 /* Split the middle into pieces, separated by commas. */
805 while (piece < middle_end + 1) {
806 const char *piece_end = separator_comma(piece);
807 size_t piece_len = (size_t)(piece_end - piece);
809 char *file = concat3(prefix, prefix_len, piece, piece_len,
812 if (contains_wildcard(file)) {
813 SearchPath_Expand(path, file, expansions);
816 Lst_Append(expansions, file);
819 /* skip over the comma or closing brace */
820 piece = piece_end + 1;
825 /* Expand the word in each of the directories from the path. */
827 DirExpandPath(const char *word, SearchPath *path, StringList *expansions)
830 for (ln = path->dirs.first; ln != NULL; ln = ln->next) {
831 CachedDir *dir = ln->datum;
832 DirMatchFiles(word, dir, expansions);
837 PrintExpansions(StringList *expansions)
839 const char *sep = "";
841 for (ln = expansions->first; ln != NULL; ln = ln->next) {
842 const char *word = ln->datum;
843 debug_printf("%s%s", sep, word);
850 * The wildcard isn't in the first component.
851 * Find all the components up to the one with the wildcard.
854 SearchPath_ExpandMiddle(SearchPath *path, const char *pattern,
855 const char *wildcardComponent, StringList *expansions)
857 char *prefix, *dirpath, *end;
858 SearchPath *partPath;
860 prefix = bmake_strsedup(pattern, wildcardComponent + 1);
862 * XXX: Check the "the directory is added to the path" part.
863 * It is probably surprising that the directory before a
864 * wildcard gets added to the path.
867 * XXX: Only the first match of the prefix in the path is
868 * taken, any others are ignored. The expectation may be
869 * that the pattern is expanded in the whole path.
871 dirpath = Dir_FindFile(prefix, path);
875 * dirpath is null if can't find the leading component
877 * XXX: Dir_FindFile won't find internal components. i.e. if the
878 * path contains ../Etc/Object and we're looking for Etc, it won't
879 * be found. Ah well. Probably not important.
881 * XXX: Check whether the above comment is still true.
886 end = &dirpath[strlen(dirpath) - 1];
887 /* XXX: What about multiple trailing slashes? */
891 partPath = SearchPath_New();
892 (void)SearchPath_Add(partPath, dirpath);
893 DirExpandPath(wildcardComponent + 1, partPath, expansions);
894 SearchPath_Free(partPath);
898 * Expand the given pattern into a list of existing filenames by globbing it,
899 * looking in each directory from the search path.
902 * path the directories in which to find the files
903 * pattern the pattern to expand
904 * expansions the list on which to place the results
907 SearchPath_Expand(SearchPath *path, const char *pattern, StringList *expansions)
909 const char *brace, *slash, *wildcard, *wildcardComponent;
911 assert(path != NULL);
912 assert(expansions != NULL);
914 DEBUG1(DIR, "Expanding \"%s\"... ", pattern);
916 brace = strchr(pattern, '{');
918 DirExpandCurly(pattern, brace, path, expansions);
922 /* At this point, the pattern does not contain '{'. */
924 slash = strchr(pattern, '/');
926 /* The pattern has no directory component. */
928 /* First the files in dot. */
929 DirMatchFiles(pattern, dot, expansions);
930 /* Then the files in every other directory on the path. */
931 DirExpandPath(pattern, path, expansions);
935 /* At this point, the pattern has a directory component. */
937 /* Find the first wildcard in the pattern. */
938 for (wildcard = pattern; *wildcard != '\0'; wildcard++)
939 if (*wildcard == '?' || *wildcard == '[' || *wildcard == '*')
942 if (*wildcard == '\0') {
944 * No directory component and no wildcard at all -- this
945 * should never happen as in such a simple case there is no
946 * need to expand anything.
948 DirExpandPath(pattern, path, expansions);
952 /* Back up to the start of the component containing the wildcard. */
953 /* XXX: This handles '///' and '/' differently. */
954 wildcardComponent = wildcard;
955 while (wildcardComponent > pattern && *wildcardComponent != '/')
958 if (wildcardComponent == pattern) {
959 /* The first component contains the wildcard. */
960 /* Start the search from the local directory */
961 DirExpandPath(pattern, path, expansions);
963 SearchPath_ExpandMiddle(path, pattern, wildcardComponent,
969 PrintExpansions(expansions);
973 * Find if the file with the given name exists in the given path.
974 * Return the freshly allocated path to the file, or NULL.
977 DirLookup(CachedDir *dir, const char *base)
979 char *file; /* the current filename to check */
981 DEBUG1(DIR, " %s ...\n", dir->name);
983 if (!HashSet_Contains(&dir->files, base))
986 file = str_concat3(dir->name, "/", base);
987 DEBUG1(DIR, " returning %s\n", file);
995 * Find if the file with the given name exists in the given directory.
996 * Return the freshly allocated path to the file, or NULL.
999 DirLookupSubdir(CachedDir *dir, const char *name)
1001 struct cached_stat cst;
1002 char *file = dir == dot
1003 ? bmake_strdup(name)
1004 : str_concat3(dir->name, "/", name);
1006 DEBUG1(DIR, "checking %s ...\n", file);
1008 if (cached_stat(file, &cst) == 0) {
1017 * Find if the file with the given name exists in the given path.
1018 * Return the freshly allocated path to the file, the empty string, or NULL.
1019 * Returning the empty string means that the search should be terminated.
1022 DirLookupAbs(CachedDir *dir, const char *name, const char *cp)
1024 const char *dnp; /* pointer into dir->name */
1025 const char *np; /* pointer into name */
1027 DEBUG1(DIR, " %s ...\n", dir->name);
1030 * If the file has a leading path component and that component
1031 * exactly matches the entire name of the current search
1032 * directory, we can attempt another cache lookup. And if we don't
1033 * have a hit, we can safely assume the file does not exist at all.
1035 for (dnp = dir->name, np = name;
1036 *dnp != '\0' && *dnp == *np; dnp++, np++)
1038 if (*dnp != '\0' || np != cp - 1)
1041 if (!HashSet_Contains(&dir->files, cp)) {
1042 DEBUG0(DIR, " must be here but isn't -- returning\n");
1043 return bmake_strdup(""); /* to terminate the search */
1048 DEBUG1(DIR, " returning %s\n", name);
1049 return bmake_strdup(name);
1053 * Find the given file in "." or curdir.
1054 * Return the freshly allocated path to the file, or NULL.
1057 DirFindDot(const char *name, const char *base)
1060 if (HashSet_Contains(&dot->files, base)) {
1061 DEBUG0(DIR, " in '.'\n");
1064 return bmake_strdup(name);
1067 if (cur != NULL && HashSet_Contains(&cur->files, base)) {
1068 DEBUG1(DIR, " in ${.CURDIR} = %s\n", cur->name);
1071 return str_concat3(cur->name, "/", base);
1078 FindFileRelative(SearchPath *path, bool seenDotLast,
1079 const char *name, char **out_file)
1082 bool checkedDot = false;
1085 DEBUG0(DIR, " Trying subdirectories...\n");
1090 if ((file = DirLookupSubdir(dot, name)) != NULL)
1094 (file = DirLookupSubdir(cur, name)) != NULL)
1098 for (ln = path->dirs.first; ln != NULL; ln = ln->next) {
1099 CachedDir *dir = ln->datum;
1107 if ((file = DirLookupSubdir(dir, name)) != NULL)
1112 if (dot != NULL && !checkedDot) {
1114 if ((file = DirLookupSubdir(dot, name)) != NULL)
1118 (file = DirLookupSubdir(cur, name)) != NULL)
1124 * Already checked by the given name, since . was in
1125 * the path, so no point in proceeding.
1127 DEBUG0(DIR, " Checked . already, returning NULL\n");
1140 FindFileAbsolute(SearchPath *path, bool seenDotLast,
1141 const char *name, const char *base, char **out_file)
1147 * For absolute names, compare directory path prefix against
1148 * the the directory path of each member on the search path
1149 * for an exact match. If we have an exact match on any member
1150 * of the search path, use the cached contents of that member
1151 * to lookup the final file component. If that lookup fails we
1152 * can safely assume that the file does not exist at all.
1153 * This is signified by DirLookupAbs() returning an empty
1156 DEBUG0(DIR, " Trying exact path matches...\n");
1158 if (!seenDotLast && cur != NULL &&
1159 ((file = DirLookupAbs(cur, name, base)) != NULL))
1162 for (ln = path->dirs.first; ln != NULL; ln = ln->next) {
1163 CachedDir *dir = ln->datum;
1166 if ((file = DirLookupAbs(dir, name, base)) != NULL)
1170 if (seenDotLast && cur != NULL &&
1171 ((file = DirLookupAbs(cur, name, base)) != NULL))
1177 if (file[0] == '\0') {
1186 * Find the file with the given name along the given search path.
1188 * If the file is found in a directory that is not on the path
1189 * already (either 'name' is absolute or it is a relative path
1190 * [ dir1/.../dirn/file ] which exists below one of the directories
1191 * already on the search path), its directory is added to the end
1192 * of the path, on the assumption that there will be more files in
1193 * that directory later on. Sometimes this is true. Sometimes not.
1196 * name the file to find
1197 * path the directories to search, or NULL
1200 * The freshly allocated path to the file, or NULL.
1203 Dir_FindFile(const char *name, SearchPath *path)
1205 char *file; /* the current filename to check */
1206 bool seenDotLast = false; /* true if we should search dot last */
1207 struct cached_stat cst; /* Buffer for stat, if necessary */
1208 const char *trailing_dot = ".";
1209 const char *base = str_basename(name);
1211 DEBUG1(DIR, "Searching for %s ...", name);
1214 DEBUG0(DIR, "couldn't open path, file not found\n");
1219 if (path->dirs.first != NULL) {
1220 CachedDir *dir = path->dirs.first->datum;
1221 if (dir == dotLast) {
1223 DEBUG0(DIR, "[dot last]...");
1229 * If there's no leading directory components or if the leading
1230 * directory component is exactly `./', consult the cached contents
1231 * of each of the directories on the search path.
1233 if (base == name || (base - name == 2 && *name == '.')) {
1237 * We look through all the directories on the path seeking one
1238 * which contains the final component of the given name. If
1239 * such a file is found, we concatenate the directory name
1240 * and the final component and return the resulting string.
1241 * If we don't find any such thing, we go on to phase two.
1243 * No matter what, we always look for the file in the current
1244 * directory before anywhere else (unless we found the magic
1245 * DOTLAST path, in which case we search it last) and we *do
1246 * not* add the ./ to it if it exists.
1247 * This is so there are no conflicts between what the user
1248 * specifies (fish.c) and what pmake finds (./fish.c).
1250 if (!seenDotLast && (file = DirFindDot(name, base)) != NULL)
1253 for (ln = path->dirs.first; ln != NULL; ln = ln->next) {
1254 CachedDir *dir = ln->datum;
1257 if ((file = DirLookup(dir, base)) != NULL)
1261 if (seenDotLast && (file = DirFindDot(name, base)) != NULL)
1266 * We didn't find the file on any directory in the search path.
1267 * If the name doesn't contain a slash, that means it doesn't exist.
1268 * If it *does* contain a slash, however, there is still hope: it
1269 * could be in a subdirectory of one of the members of the search
1270 * path. (eg. /usr/include and sys/types.h. The above search would
1271 * fail to turn up types.h in /usr/include, but it *is* in
1272 * /usr/include/sys/types.h).
1273 * [ This no longer applies: If we find such a file, we assume there
1274 * will be more (what else can we assume?) and add all but the last
1275 * component of the resulting name onto the search path (at the
1277 * This phase is only performed if the file is *not* absolute.
1280 DEBUG0(DIR, " failed.\n");
1285 if (*base == '\0') {
1286 /* we were given a trailing "/" */
1287 base = trailing_dot;
1290 if (name[0] != '/') {
1291 if (FindFileRelative(path, seenDotLast, name, &file))
1294 if (FindFileAbsolute(path, seenDotLast, name, base, &file))
1299 * Didn't find it that way, either. Sigh. Phase 3. Add its directory
1300 * onto the search path in any case, just in case, then look for the
1301 * thing in the hash table. If we find it, grand. We return a new
1302 * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
1303 * Note that if the directory holding the file doesn't exist, this
1304 * will do an extra search of the final directory on the path. Unless
1305 * something weird happens, this search won't succeed and life will
1308 * Sigh. We cannot add the directory onto the search path because
1309 * of this amusing case:
1310 * $(INSTALLDIR)/$(FILE): $(FILE)
1312 * $(FILE) exists in $(INSTALLDIR) but not in the current one.
1313 * When searching for $(FILE), we will find it in $(INSTALLDIR)
1314 * b/c we added it here. This is not good...
1321 if (base == trailing_dot) {
1322 base = strrchr(name, '/');
1325 prefix = bmake_strsedup(name, base - 1);
1326 (void)SearchPath_Add(path, prefix);
1330 if (path->last == NULL)
1333 dir = path->last->datum;
1334 if (HashSet_Contains(&dir->files, base))
1335 return bmake_strdup(name);
1339 DEBUG1(DIR, " Looking for \"%s\" ...\n", name);
1342 if (cached_stat(name, &cst) == 0) {
1343 return bmake_strdup(name);
1346 DEBUG0(DIR, " failed. Returning NULL\n");
1353 * Search for a path starting at a given directory and then working our way
1354 * up towards the root.
1357 * here starting directory
1358 * search_path the relative path we are looking for
1361 * The found path, or NULL.
1364 Dir_FindHereOrAbove(const char *here, const char *search_path)
1366 struct cached_stat cst;
1367 char *dirbase, *dirbase_end;
1368 char *try, *try_end;
1370 /* copy out our starting point */
1371 dirbase = bmake_strdup(here);
1372 dirbase_end = dirbase + strlen(dirbase);
1374 /* loop until we determine a result */
1377 /* try and stat(2) it ... */
1378 try = str_concat3(dirbase, "/", search_path);
1379 if (cached_stat(try, &cst) != -1) {
1381 * success! if we found a file, chop off
1382 * the filename so we return a directory.
1384 if ((cst.cst_mode & S_IFMT) != S_IFDIR) {
1385 try_end = try + strlen(try);
1386 while (try_end > try && *try_end != '/')
1389 *try_end = '\0'; /* chop! */
1398 * nope, we didn't find it. if we used up dirbase we've
1399 * reached the root and failed.
1401 if (dirbase_end == dirbase)
1402 break; /* failed! */
1405 * truncate dirbase from the end to move up a dir
1407 while (dirbase_end > dirbase && *dirbase_end != '/')
1409 *dirbase_end = '\0'; /* chop! */
1417 * This is an implied source, and it may have moved,
1418 * see if we can find it via the current .PATH
1421 ResolveMovedDepends(GNode *gn)
1425 const char *base = str_basename(gn->name);
1426 if (base == gn->name)
1429 fullName = Dir_FindFile(base, Suff_FindPath(gn));
1430 if (fullName == NULL)
1434 * Put the found file in gn->path so that we give that to the compiler.
1437 * XXX: Better just reset gn->path to NULL; updating it is already done
1438 * by Dir_UpdateMTime.
1440 gn->path = bmake_strdup(fullName);
1441 if (!Job_RunTarget(".STALE", gn->fname))
1442 fprintf(stdout, /* XXX: Why stdout? */
1443 "%s: %s, %u: ignoring stale %s for %s, found %s\n",
1444 progname, gn->fname, gn->lineno,
1445 makeDependfile, gn->name, fullName);
1451 ResolveFullName(GNode *gn)
1455 fullName = gn->path;
1456 if (fullName == NULL && !(gn->type & OP_NOPATH)) {
1458 fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
1460 if (fullName == NULL && gn->flags.fromDepend &&
1461 !Lst_IsEmpty(&gn->implicitParents))
1462 fullName = ResolveMovedDepends(gn);
1464 DEBUG2(DIR, "Found '%s' as '%s'\n",
1465 gn->name, fullName != NULL ? fullName : "(not found)");
1468 if (fullName == NULL)
1469 fullName = bmake_strdup(gn->name);
1471 /* XXX: Is every piece of memory freed as it should? */
1477 * Search gn along dirSearchPath and store its modification time in gn->mtime.
1478 * If no file is found, store 0 instead.
1480 * The found file is stored in gn->path, unless the node already had a path.
1483 Dir_UpdateMTime(GNode *gn, bool forceRefresh)
1486 struct cached_stat cst;
1488 if (gn->type & OP_ARCHV) {
1489 Arch_UpdateMTime(gn);
1493 if (gn->type & OP_PHONY) {
1498 fullName = ResolveFullName(gn);
1500 if (cached_stats(fullName, &cst, false, forceRefresh) < 0) {
1501 if (gn->type & OP_MEMBER) {
1502 if (fullName != gn->path)
1504 Arch_UpdateMemberMTime(gn);
1511 if (fullName != NULL && gn->path == NULL)
1512 gn->path = fullName;
1513 /* XXX: else free(fullName)? */
1515 gn->mtime = cst.cst_mtime;
1519 * Read the directory and add it to the cache in openDirs.
1520 * If a path is given, add the directory to that path as well.
1523 CacheNewDir(const char *name, SearchPath *path)
1525 CachedDir *dir = NULL;
1529 if ((d = opendir(name)) == NULL) {
1530 DEBUG1(DIR, "Caching %s ... not found\n", name);
1534 DEBUG1(DIR, "Caching %s ...\n", name);
1536 dir = CachedDir_New(name);
1538 while ((dp = readdir(d)) != NULL) {
1540 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
1542 * The sun directory library doesn't check for a 0 inode
1543 * (0-inode slots just take up space), so we have to do
1546 if (dp->d_fileno == 0)
1548 #endif /* sun && d_ino */
1550 (void)HashSet_Add(&dir->files, dp->d_name);
1554 OpenDirs_Add(&openDirs, dir);
1556 Lst_Append(&path->dirs, CachedDir_Ref(dir));
1558 DEBUG1(DIR, "Caching %s done\n", name);
1563 * Read the list of filenames in the directory and store the result
1566 * If a path is given, append the directory to that path.
1569 * path The path to which the directory should be
1570 * added, or NULL to only add the directory to openDirs
1571 * name The name of the directory to add.
1572 * The name is not normalized in any way.
1574 * result If no path is given and the directory exists, the
1575 * returned CachedDir has a reference count of 0. It
1576 * must either be assigned to a variable using
1577 * CachedDir_Assign or be appended to a SearchPath using
1578 * Lst_Append and CachedDir_Ref.
1581 SearchPath_Add(SearchPath *path, const char *name)
1584 if (path != NULL && strcmp(name, ".DOTLAST") == 0) {
1587 /* XXX: Linear search gets slow with thousands of entries. */
1588 for (ln = path->dirs.first; ln != NULL; ln = ln->next) {
1589 CachedDir *pathDir = ln->datum;
1590 if (strcmp(pathDir->name, name) == 0)
1594 Lst_Prepend(&path->dirs, CachedDir_Ref(dotLast));
1598 /* XXX: Why is OpenDirs only checked if path != NULL? */
1599 CachedDir *dir = OpenDirs_Find(&openDirs, name);
1601 if (Lst_FindDatum(&path->dirs, dir) == NULL)
1602 Lst_Append(&path->dirs, CachedDir_Ref(dir));
1607 return CacheNewDir(name, path);
1611 * Return a copy of dirSearchPath, incrementing the reference counts for
1612 * the contained directories.
1615 Dir_CopyDirSearchPath(void)
1617 SearchPath *path = SearchPath_New();
1619 for (ln = dirSearchPath.dirs.first; ln != NULL; ln = ln->next) {
1620 CachedDir *dir = ln->datum;
1621 Lst_Append(&path->dirs, CachedDir_Ref(dir));
1627 * Make a string by taking all the directories in the given search path and
1628 * preceding them by the given flag. Used by the suffix module to create
1629 * variables for compilers based on suffix search paths.
1632 * flag flag which should precede each directory
1633 * path list of directories
1636 * The string mentioned above. Note that there is no space between the
1637 * given flag and each directory. The empty string is returned if things
1641 SearchPath_ToFlags(SearchPath *path, const char *flag)
1649 for (ln = path->dirs.first; ln != NULL; ln = ln->next) {
1650 CachedDir *dir = ln->datum;
1651 Buf_AddStr(&buf, " ");
1652 Buf_AddStr(&buf, flag);
1653 Buf_AddStr(&buf, dir->name);
1657 return Buf_DoneData(&buf);
1660 /* Free the search path and all directories mentioned in it. */
1662 SearchPath_Free(SearchPath *path)
1666 for (ln = path->dirs.first; ln != NULL; ln = ln->next) {
1667 CachedDir *dir = ln->datum;
1668 CachedDir_Unref(dir);
1670 Lst_Done(&path->dirs);
1675 * Clear out all elements from the given search path.
1676 * The path is set to the empty list but is not destroyed.
1679 SearchPath_Clear(SearchPath *path)
1681 while (!Lst_IsEmpty(&path->dirs)) {
1682 CachedDir *dir = Lst_Dequeue(&path->dirs);
1683 CachedDir_Unref(dir);
1689 * Concatenate two paths, adding the second to the end of the first,
1690 * skipping duplicates.
1693 SearchPath_AddAll(SearchPath *dst, SearchPath *src)
1697 for (ln = src->dirs.first; ln != NULL; ln = ln->next) {
1698 CachedDir *dir = ln->datum;
1699 if (Lst_FindDatum(&dst->dirs, dir) == NULL)
1700 Lst_Append(&dst->dirs, CachedDir_Ref(dir));
1705 percentage(int num, int den)
1707 return den != 0 ? num * 100 / den : 0;
1710 /********** DEBUG INFO **********/
1712 Dir_PrintDirectories(void)
1714 CachedDirListNode *ln;
1716 debug_printf("#*** Directory Cache:\n");
1718 "# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
1719 hits, misses, nearmisses, bigmisses,
1720 percentage(hits, hits + bigmisses + nearmisses));
1721 debug_printf("# refs hits directory\n");
1723 for (ln = openDirs.list.first; ln != NULL; ln = ln->next) {
1724 CachedDir *dir = ln->datum;
1725 debug_printf("# %4d %4d %s\n",
1726 dir->refCount, dir->hits, dir->name);
1731 SearchPath_Print(const SearchPath *path)
1735 for (ln = path->dirs.first; ln != NULL; ln = ln->next) {
1736 const CachedDir *dir = ln->datum;
1737 debug_printf("%s ", dir->name);