1 /* $NetBSD: dir.c,v 1.76 2020/07/03 08:13:23 rillig 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 static char rcsid[] = "$NetBSD: dir.c,v 1.76 2020/07/03 08:13:23 rillig Exp $";
75 #include <sys/cdefs.h>
78 static char sccsid[] = "@(#)dir.c 8.2 (Berkeley) 1/2/94";
80 __RCSID("$NetBSD: dir.c,v 1.76 2020/07/03 08:13:23 rillig Exp $");
87 * Directory searching using wildcards and/or normal names...
88 * Used both for source wildcarding in the Makefile and for finding
91 * The interface for this module is:
92 * Dir_Init Initialize the module.
94 * Dir_InitCur Set the cur Path.
96 * Dir_InitDot Set the dot Path.
98 * Dir_End Cleanup the module.
100 * Dir_SetPATH Set ${.PATH} to reflect state of dirSearchPath.
102 * Dir_HasWildcards Returns TRUE if the name given it needs to
103 * be wildcard-expanded.
105 * Dir_Expand Given a pattern and a path, return a Lst of names
106 * which match the pattern on the search path.
108 * Dir_FindFile Searches for a file on a given search path.
109 * If it exists, the entire path is returned.
110 * Otherwise NULL is returned.
112 * Dir_FindHereOrAbove Search for a path in the current directory and
113 * then all the directories above it in turn until
114 * the path is found or we reach the root ("/").
116 * Dir_MTime Return the modification time of a node. The file
117 * is searched for along the default search path.
118 * The path and mtime fields of the node are filled
121 * Dir_AddDir Add a directory to a search path.
123 * Dir_MakeFlags Given a search path and a command flag, create
124 * a string with each of the directories in the path
125 * preceded by the command flag and all of them
126 * separated by a space.
128 * Dir_Destroy Destroy an element of a search path. Frees up all
129 * things that can be freed for the element as long
130 * as the element is no longer referenced by any other
132 * Dir_ClearPath Resets a search path to the empty list.
135 * Dir_PrintDirectories Print stats about the directory cache.
138 #include <sys/types.h>
139 #include <sys/stat.h>
151 * A search path consists of a Lst of Path structures. A Path structure
152 * has in it the name of the directory and a hash table of all the files
153 * in the directory. This is used to cut down on the number of system
154 * calls necessary to find implicit dependents and their like. Since
155 * these searches are made before any actions are taken, we need not
156 * worry about the directory changing due to creation commands. If this
157 * hampers the style of some makefiles, they must be changed.
159 * A list of all previously-read directories is kept in the
160 * openDirectories Lst. This list is checked first before a directory
163 * The need for the caching of whole directories is brought about by
164 * the multi-level transformation code in suff.c, which tends to search
165 * for far more files than regular make does. In the initial
166 * implementation, the amount of time spent performing "stat" calls was
167 * truly astronomical. The problem with hashing at the start is,
168 * of course, that pmake doesn't then detect changes to these directories
169 * during the course of the make. Three possibilities suggest themselves:
171 * 1) just use stat to test for a file's existence. As mentioned
172 * above, this is very inefficient due to the number of checks
173 * engendered by the multi-level transformation code.
174 * 2) use readdir() and company to search the directories, keeping
175 * them open between checks. I have tried this and while it
176 * didn't slow down the process too much, it could severely
177 * affect the amount of parallelism available as each directory
178 * open would take another file descriptor out of play for
179 * handling I/O for another job. Given that it is only recently
180 * that UNIX OS's have taken to allowing more than 20 or 32
181 * file descriptors for a process, this doesn't seem acceptable
183 * 3) record the mtime of the directory in the Path structure and
184 * verify the directory hasn't changed since the contents were
185 * hashed. This will catch the creation or deletion of files,
186 * but not the updating of files. However, since it is the
187 * creation and deletion that is the problem, this could be
188 * a good thing to do. Unfortunately, if the directory (say ".")
189 * were fairly large and changed fairly frequently, the constant
190 * rehashing could seriously degrade performance. It might be
191 * good in such cases to keep track of the number of rehashes
192 * and if the number goes over a (small) limit, resort to using
195 * An additional thing to consider is that pmake is used primarily
196 * to create C programs and until recently pcc-based compilers refused
197 * to allow you to specify where the resulting object file should be
198 * placed. This forced all objects to be created in the current
199 * directory. This isn't meant as a full excuse, just an explanation of
200 * some of the reasons for the caching used here.
202 * One more note: the location of a target's file is only performed
203 * on the downward traversal of the graph and then only for terminal
204 * nodes in the graph. This could be construed as wrong in some cases,
205 * but prevents inadvertent modification of files when the "installed"
206 * directory for a file is provided in the search path.
208 * Another data structure maintained by this module is an mtime
209 * cache used when the searching of cached directories fails to find
210 * a file. In the past, Dir_FindFile would simply perform an access()
211 * call in such a case to determine if the file could be found using
212 * just the name given. When this hit, however, all that was gained
213 * was the knowledge that the file existed. Given that an access() is
214 * essentially a stat() without the copyout() call, and that the same
215 * filesystem overhead would have to be incurred in Dir_MTime, it made
216 * sense to replace the access() with a stat() and record the mtime
217 * in a cache for when Dir_MTime was actually called.
220 Lst dirSearchPath; /* main search path */
222 static Lst openDirectories; /* the list of all open directories */
225 * Variables for gathering statistics on the efficiency of the hashing
228 static int hits, /* Found in directory cache */
229 misses, /* Sad, but not evil misses */
230 nearmisses, /* Found under search path */
231 bigmisses; /* Sought by itself */
233 static Path *dot; /* contents of current directory */
234 static Path *cur; /* contents of current directory, if not dot */
235 static Path *dotLast; /* a fake path entry indicating we need to
237 static Hash_Table mtimes; /* Results of doing a last-resort stat in
238 * Dir_FindFile -- if we have to go to the
239 * system to find the file, we might as well
240 * have its mtime on record. XXX: If this is done
241 * way early, there's a chance other rules will
242 * have already updated the file, in which case
243 * we'll update it again. Generally, there won't
244 * be two rules to update a single file, so this
245 * should be ok, but... */
247 static Hash_Table lmtimes; /* same as mtimes but for lstat */
249 static int DirFindName(const void *, const void *);
250 static int DirMatchFiles(const char *, Path *, Lst);
251 static void DirExpandCurly(const char *, const char *, Lst, Lst);
252 static void DirExpandInt(const char *, Lst, Lst);
253 static int DirPrintWord(void *, void *);
254 static int DirPrintDir(void *, void *);
255 static char *DirLookup(Path *, const char *, const char *, Boolean);
256 static char *DirLookupSubdir(Path *, const char *);
257 static char *DirFindDot(Boolean, const char *, const char *);
258 static char *DirLookupAbs(Path *, const char *, const char *);
262 * We use stat(2) a lot, cache the results
263 * mtime and mode are all we care about.
266 time_t lmtime; /* lstat */
267 time_t mtime; /* stat */
271 /* minimize changes below */
276 cached_stats(Hash_Table *htp, const char *pathname, struct stat *st, int flags)
279 struct cache_st *cst;
282 if (!pathname || !pathname[0])
285 entry = Hash_FindEntry(htp, pathname);
287 if (entry && (flags & CST_UPDATE) == 0) {
288 cst = entry->clientPtr;
290 memset(st, 0, sizeof(*st));
291 st->st_mode = cst->mode;
292 st->st_mtime = (flags & CST_LSTAT) ? cst->lmtime : cst->mtime;
295 fprintf(debug_file, "Using cached time %s for %s\n",
296 Targ_FmtTime(st->st_mtime), pathname);
302 rc = (flags & CST_LSTAT) ? lstat(pathname, st) : stat(pathname, st);
306 if (st->st_mtime == 0)
307 st->st_mtime = 1; /* avoid confusion with missing file */
310 entry = Hash_CreateEntry(htp, pathname, NULL);
311 if (!entry->clientPtr) {
312 entry->clientPtr = bmake_malloc(sizeof(*cst));
313 memset(entry->clientPtr, 0, sizeof(*cst));
315 cst = entry->clientPtr;
316 if ((flags & CST_LSTAT)) {
317 cst->lmtime = st->st_mtime;
319 cst->mtime = st->st_mtime;
321 cst->mode = st->st_mode;
323 fprintf(debug_file, " Caching %s for %s\n",
324 Targ_FmtTime(st->st_mtime), pathname);
331 cached_stat(const char *pathname, void *st)
333 return cached_stats(&mtimes, pathname, st, 0);
337 cached_lstat(const char *pathname, void *st)
339 return cached_stats(&lmtimes, pathname, st, CST_LSTAT);
343 *-----------------------------------------------------------------------
345 * initialize things for this module
351 * some directories may be opened.
352 *-----------------------------------------------------------------------
355 Dir_Init(const char *cdname)
358 dirSearchPath = Lst_Init(FALSE);
359 openDirectories = Lst_Init(FALSE);
360 Hash_InitTable(&mtimes, 0);
361 Hash_InitTable(&lmtimes, 0);
366 dotLast = bmake_malloc(sizeof(Path));
367 dotLast->refCount = 1;
369 dotLast->name = bmake_strdup(".DOTLAST");
370 Hash_InitTable(&dotLast->files, -1);
374 * Called by Dir_Init() and whenever .CURDIR is assigned to.
377 Dir_InitCur(const char *cdname)
381 if (cdname != NULL) {
383 * Our build directory is not the same as our source directory.
384 * Keep this one around too.
386 if ((p = Dir_AddDir(NULL, cdname))) {
388 if (cur && cur != p) {
390 * We've been here before, cleanup.
401 *-----------------------------------------------------------------------
403 * (re)initialize "dot" (current/object directory) path hash
409 * some directories may be opened.
410 *-----------------------------------------------------------------------
418 /* Remove old entry from openDirectories, but do not destroy. */
419 ln = Lst_Member(openDirectories, dot);
420 (void)Lst_Remove(openDirectories, ln);
423 dot = Dir_AddDir(NULL, ".");
426 Error("Cannot open `.' (%s)", strerror(errno));
431 * We always need to have dot around, so we increment its reference count
432 * to make sure it's not destroyed.
435 Dir_SetPATH(); /* initialize */
439 *-----------------------------------------------------------------------
441 * cleanup things for this module
448 *-----------------------------------------------------------------------
459 dotLast->refCount -= 1;
460 Dir_Destroy(dotLast);
462 Dir_ClearPath(dirSearchPath);
463 Lst_Destroy(dirSearchPath, NULL);
464 Dir_ClearPath(openDirectories);
465 Lst_Destroy(openDirectories, NULL);
466 Hash_DeleteTable(&mtimes);
471 * We want ${.PATH} to indicate the order in which we will actually
472 * search, so we rebuild it after any .PATH: target.
473 * This is the simplest way to deal with the effect of .DOTLAST.
478 LstNode ln; /* a list element */
480 Boolean hasLastDot = FALSE; /* true we should search dot last */
482 Var_Delete(".PATH", VAR_GLOBAL);
484 if (Lst_Open(dirSearchPath) == SUCCESS) {
485 if ((ln = Lst_First(dirSearchPath)) != NULL) {
486 p = (Path *)Lst_Datum(ln);
489 Var_Append(".PATH", dotLast->name, VAR_GLOBAL);
495 Var_Append(".PATH", dot->name, VAR_GLOBAL);
497 Var_Append(".PATH", cur->name, VAR_GLOBAL);
500 while ((ln = Lst_Next(dirSearchPath)) != NULL) {
501 p = (Path *)Lst_Datum(ln);
504 if (p == dot && hasLastDot)
506 Var_Append(".PATH", p->name, VAR_GLOBAL);
511 Var_Append(".PATH", dot->name, VAR_GLOBAL);
513 Var_Append(".PATH", cur->name, VAR_GLOBAL);
515 Lst_Close(dirSearchPath);
520 *-----------------------------------------------------------------------
522 * See if the Path structure describes the same directory as the
523 * given one by comparing their names. Called from Dir_AddDir via
524 * Lst_Find when searching the list of open directories.
531 * 0 if it is the same. Non-zero otherwise
535 *-----------------------------------------------------------------------
538 DirFindName(const void *p, const void *dname)
540 return strcmp(((const Path *)p)->name, dname);
544 *-----------------------------------------------------------------------
545 * Dir_HasWildcards --
546 * see if the given name has any wildcard characters in it
547 * be careful not to expand unmatching brackets or braces.
548 * XXX: This code is not 100% correct. ([^]] fails etc.)
549 * I really don't think that make(1) should be expanding
550 * patterns, because then you have to set a mechanism for
551 * escaping the expansion!
557 * returns TRUE if the word should be expanded, FALSE otherwise
561 *-----------------------------------------------------------------------
564 Dir_HasWildcards(char *name)
567 int wild = 0, brace = 0, bracket = 0;
569 for (cp = name; *cp; cp++) {
593 return wild && bracket == 0 && brace == 0;
597 *-----------------------------------------------------------------------
599 * Given a pattern and a Path structure, see if any files
600 * match the pattern and add their names to the 'expansions' list if
601 * any do. This is incomplete -- it doesn't take care of patterns like
602 * src / *src / *.c properly (just *.c on any of the directories), but it
606 * pattern Pattern to look for
607 * p Directory to search
608 * expansion Place to store the results
614 * File names are added to the expansions lst. The directory will be
615 * fully hashed when this is done.
616 *-----------------------------------------------------------------------
619 DirMatchFiles(const char *pattern, Path *p, Lst expansions)
621 Hash_Search search; /* Index into the directory's table */
622 Hash_Entry *entry; /* Current entry in the table */
623 Boolean isDot; /* TRUE if the directory being searched is . */
625 isDot = (*p->name == '.' && p->name[1] == '\0');
627 for (entry = Hash_EnumFirst(&p->files, &search);
629 entry = Hash_EnumNext(&search))
632 * See if the file matches the given pattern. Note we follow the UNIX
633 * convention that dot files will only be found if the pattern
634 * begins with a dot (note also that as a side effect of the hashing
635 * scheme, .* won't match . or .. since they aren't hashed).
637 if (Str_Match(entry->name, pattern) &&
638 ((entry->name[0] != '.') ||
639 (pattern[0] == '.')))
641 (void)Lst_AtEnd(expansions,
642 (isDot ? bmake_strdup(entry->name) :
643 str_concat(p->name, entry->name,
651 *-----------------------------------------------------------------------
653 * Expand curly braces like the C shell. Does this recursively.
654 * Note the special case: if after the piece of the curly brace is
655 * done there are no wildcard characters in the result, the result is
656 * placed on the list WITHOUT CHECKING FOR ITS EXISTENCE.
659 * word Entire word to expand
660 * brace First curly brace in it
661 * path Search path to use
662 * expansions Place to store the expansions
668 * The given list is filled with the expansions...
670 *-----------------------------------------------------------------------
673 DirExpandCurly(const char *word, const char *brace, Lst path, Lst expansions)
675 const char *end; /* Character after the closing brace */
676 const char *cp; /* Current position in brace clause */
677 const char *start; /* Start of current piece of brace clause */
678 int bracelevel; /* Number of braces we've seen. If we see a
679 * right brace when this is 0, we've hit the
680 * end of the clause. */
681 char *file; /* Current expansion */
682 int otherLen; /* The length of the other pieces of the
683 * expansion (chars before and after the
684 * clause in 'word') */
685 char *cp2; /* Pointer for checking for wildcards in
686 * expansion before calling Dir_Expand */
691 * Find the end of the brace clause first, being wary of nested brace
694 for (end = start, bracelevel = 0; *end != '\0'; end++) {
697 } else if ((*end == '}') && (bracelevel-- == 0)) {
702 Error("Unterminated {} clause \"%s\"", start);
707 otherLen = brace - word + strlen(end);
709 for (cp = start; cp < end; cp++) {
711 * Find the end of this piece of the clause.
717 } else if ((*cp == '}') && (bracelevel-- <= 0)) {
723 * Allocate room for the combination and install the three pieces.
725 file = bmake_malloc(otherLen + cp - start + 1);
727 strncpy(file, word, brace-word);
730 strncpy(&file[brace-word], start, cp-start);
732 strcpy(&file[(brace-word)+(cp-start)], end);
735 * See if the result has any wildcards in it. If we find one, call
736 * Dir_Expand right away, telling it to place the result on our list
739 for (cp2 = file; *cp2 != '\0'; cp2++) {
745 Dir_Expand(file, path, expansions);
751 * Hit the end w/o finding any wildcards, so stick the expansion
752 * on the end of the list.
754 (void)Lst_AtEnd(expansions, file);
765 *-----------------------------------------------------------------------
767 * Internal expand routine. Passes through the directories in the
768 * path one by one, calling DirMatchFiles for each. NOTE: This still
769 * doesn't handle patterns in directories...
772 * word Word to expand
773 * path Path on which to look
774 * expansions Place to store the result
780 * Things are added to the expansions list.
782 *-----------------------------------------------------------------------
785 DirExpandInt(const char *word, Lst path, Lst expansions)
787 LstNode ln; /* Current node */
788 Path *p; /* Directory in the node */
790 if (Lst_Open(path) == SUCCESS) {
791 while ((ln = Lst_Next(path)) != NULL) {
792 p = (Path *)Lst_Datum(ln);
793 DirMatchFiles(word, p, expansions);
800 *-----------------------------------------------------------------------
802 * Print a word in the list of expansions. Callback for Dir_Expand
803 * when DEBUG(DIR), via Lst_ForEach.
809 * The passed word is printed, followed by a space.
811 *-----------------------------------------------------------------------
814 DirPrintWord(void *word, void *dummy MAKE_ATTR_UNUSED)
816 fprintf(debug_file, "%s ", (char *)word);
822 *-----------------------------------------------------------------------
824 * Expand the given word into a list of words by globbing it looking
825 * in the directories on the given search path.
828 * word the word to expand
829 * path the list of directories in which to find the
831 * expansions the list on which to place the results
834 * A list of words consisting of the files which exist along the search
835 * path matching the given pattern.
838 * Directories may be opened. Who knows?
839 *-----------------------------------------------------------------------
842 Dir_Expand(const char *word, Lst path, Lst expansions)
847 fprintf(debug_file, "Expanding \"%s\"... ", word);
850 cp = strchr(word, '{');
852 DirExpandCurly(word, cp, path, expansions);
854 cp = strchr(word, '/');
857 * The thing has a directory component -- find the first wildcard
860 for (cp = word; *cp; cp++) {
861 if (*cp == '?' || *cp == '[' || *cp == '*' || *cp == '{') {
867 * This one will be fun.
869 DirExpandCurly(word, cp, path, expansions);
871 } else if (*cp != '\0') {
873 * Back up to the start of the component
877 while (cp > word && *cp != '/') {
883 * If the glob isn't in the first component, try and find
884 * all the components up to the one with a wildcard.
887 ((char *)UNCONST(cp))[1] = '\0';
888 dirpath = Dir_FindFile(word, path);
889 ((char *)UNCONST(cp))[1] = sc;
891 * dirpath is null if can't find the leading component
892 * XXX: Dir_FindFile won't find internal components.
893 * i.e. if the path contains ../Etc/Object and we're
894 * looking for Etc, it won't be found. Ah well.
895 * Probably not important.
897 if (dirpath != NULL) {
898 char *dp = &dirpath[strlen(dirpath) - 1];
901 path = Lst_Init(FALSE);
902 (void)Dir_AddDir(path, dirpath);
903 DirExpandInt(cp+1, path, expansions);
904 Lst_Destroy(path, NULL);
908 * Start the search from the local directory
910 DirExpandInt(word, path, expansions);
914 * Return the file -- this should never happen.
916 DirExpandInt(word, path, expansions);
920 * First the files in dot
922 DirMatchFiles(word, dot, expansions);
925 * Then the files in every other directory on the path.
927 DirExpandInt(word, path, expansions);
931 Lst_ForEach(expansions, DirPrintWord, NULL);
932 fprintf(debug_file, "\n");
937 *-----------------------------------------------------------------------
939 * Find if the file with the given name exists in the given path.
942 * The path to the file or NULL. This path is guaranteed to be in a
943 * different part of memory than name and so may be safely free'd.
947 *-----------------------------------------------------------------------
950 DirLookup(Path *p, const char *name MAKE_ATTR_UNUSED, const char *cp,
951 Boolean hasSlash MAKE_ATTR_UNUSED)
953 char *file; /* the current filename to check */
956 fprintf(debug_file, " %s ...\n", p->name);
959 if (Hash_FindEntry(&p->files, cp) == NULL)
962 file = str_concat(p->name, cp, STR_ADDSLASH);
964 fprintf(debug_file, " returning %s\n", file);
973 *-----------------------------------------------------------------------
975 * Find if the file with the given name exists in the given path.
978 * The path to the file or NULL. This path is guaranteed to be in a
979 * different part of memory than name and so may be safely free'd.
982 * If the file is found, it is added in the modification times hash
984 *-----------------------------------------------------------------------
987 DirLookupSubdir(Path *p, const char *name)
989 struct stat stb; /* Buffer for stat, if necessary */
990 char *file; /* the current filename to check */
993 file = str_concat(p->name, name, STR_ADDSLASH);
996 * Checking in dot -- DON'T put a leading ./ on the thing.
998 file = bmake_strdup(name);
1002 fprintf(debug_file, "checking %s ...\n", file);
1005 if (cached_stat(file, &stb) == 0) {
1014 *-----------------------------------------------------------------------
1016 * Find if the file with the given name exists in the given path.
1019 * The path to the file, the empty string or NULL. If the file is
1020 * the empty string, the search should be terminated.
1021 * This path is guaranteed to be in a different part of memory
1022 * than name and so may be safely free'd.
1026 *-----------------------------------------------------------------------
1029 DirLookupAbs(Path *p, const char *name, const char *cp)
1031 char *p1; /* pointer into p->name */
1032 const char *p2; /* pointer into name */
1035 fprintf(debug_file, " %s ...\n", p->name);
1039 * If the file has a leading path component and that component
1040 * exactly matches the entire name of the current search
1041 * directory, we can attempt another cache lookup. And if we don't
1042 * have a hit, we can safely assume the file does not exist at all.
1044 for (p1 = p->name, p2 = name; *p1 && *p1 == *p2; p1++, p2++) {
1047 if (*p1 != '\0' || p2 != cp - 1) {
1051 if (Hash_FindEntry(&p->files, cp) == NULL) {
1053 fprintf(debug_file, " must be here but isn't -- returning\n");
1055 /* Return empty string: terminates search */
1056 return bmake_strdup("");
1062 fprintf(debug_file, " returning %s\n", name);
1064 return bmake_strdup(name);
1068 *-----------------------------------------------------------------------
1070 * Find the file given on "." or curdir
1073 * The path to the file or NULL. This path is guaranteed to be in a
1074 * different part of memory than name and so may be safely free'd.
1078 *-----------------------------------------------------------------------
1081 DirFindDot(Boolean hasSlash MAKE_ATTR_UNUSED, const char *name, const char *cp)
1084 if (Hash_FindEntry(&dot->files, cp) != NULL) {
1086 fprintf(debug_file, " in '.'\n");
1090 return bmake_strdup(name);
1093 Hash_FindEntry(&cur->files, cp) != NULL) {
1095 fprintf(debug_file, " in ${.CURDIR} = %s\n", cur->name);
1099 return str_concat(cur->name, cp, STR_ADDSLASH);
1106 *-----------------------------------------------------------------------
1108 * Find the file with the given name along the given search path.
1111 * name the file to find
1112 * path the Lst of directories to search
1115 * The path to the file or NULL. This path is guaranteed to be in a
1116 * different part of memory than name and so may be safely free'd.
1119 * If the file is found in a directory which is not on the path
1120 * already (either 'name' is absolute or it is a relative path
1121 * [ dir1/.../dirn/file ] which exists below one of the directories
1122 * already on the search path), its directory is added to the end
1123 * of the path on the assumption that there will be more files in
1124 * that directory later on. Sometimes this is true. Sometimes not.
1125 *-----------------------------------------------------------------------
1128 Dir_FindFile(const char *name, Lst path)
1130 LstNode ln; /* a list element */
1131 char *file; /* the current filename to check */
1132 Path *p; /* current path member */
1133 const char *cp; /* Terminal name of file */
1134 Boolean hasLastDot = FALSE; /* true we should search dot last */
1135 Boolean hasSlash; /* true if 'name' contains a / */
1136 struct stat stb; /* Buffer for stat, if necessary */
1137 const char *trailing_dot = ".";
1140 * Find the final component of the name and note whether it has a
1141 * slash in it (the name, I mean)
1143 cp = strrchr(name, '/');
1153 fprintf(debug_file, "Searching for %s ...", name);
1156 if (Lst_Open(path) == FAILURE) {
1158 fprintf(debug_file, "couldn't open path, file not found\n");
1164 if ((ln = Lst_First(path)) != NULL) {
1165 p = (Path *)Lst_Datum(ln);
1169 fprintf(debug_file, "[dot last]...");
1173 fprintf(debug_file, "\n");
1177 * If there's no leading directory components or if the leading
1178 * directory component is exactly `./', consult the cached contents
1179 * of each of the directories on the search path.
1181 if (!hasSlash || (cp - name == 2 && *name == '.')) {
1183 * We look through all the directories on the path seeking one which
1184 * contains the final component of the given name. If such a beast
1185 * is found, we concatenate the directory name and the final
1186 * component and return the resulting string. If we don't find any
1187 * such thing, we go on to phase two...
1189 * No matter what, we always look for the file in the current
1190 * directory before anywhere else (unless we found the magic
1191 * DOTLAST path, in which case we search it last) and we *do not*
1192 * add the ./ to it if it exists.
1193 * This is so there are no conflicts between what the user
1194 * specifies (fish.c) and what pmake finds (./fish.c).
1197 (file = DirFindDot(hasSlash, name, cp)) != NULL) {
1202 while ((ln = Lst_Next(path)) != NULL) {
1203 p = (Path *)Lst_Datum(ln);
1206 if ((file = DirLookup(p, name, cp, hasSlash)) != NULL) {
1213 (file = DirFindDot(hasSlash, name, cp)) != NULL) {
1221 * We didn't find the file on any directory in the search path.
1222 * If the name doesn't contain a slash, that means it doesn't exist.
1223 * If it *does* contain a slash, however, there is still hope: it
1224 * could be in a subdirectory of one of the members of the search
1225 * path. (eg. /usr/include and sys/types.h. The above search would
1226 * fail to turn up types.h in /usr/include, but it *is* in
1227 * /usr/include/sys/types.h).
1228 * [ This no longer applies: If we find such a beast, we assume there
1229 * will be more (what else can we assume?) and add all but the last
1230 * component of the resulting name onto the search path (at the
1232 * This phase is only performed if the file is *not* absolute.
1236 fprintf(debug_file, " failed.\n");
1243 /* we were given a trailing "/" */
1247 if (name[0] != '/') {
1248 Boolean checkedDot = FALSE;
1251 fprintf(debug_file, " Trying subdirectories...\n");
1257 if ((file = DirLookupSubdir(dot, name)) != NULL)
1260 if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
1264 (void)Lst_Open(path);
1265 while ((ln = Lst_Next(path)) != NULL) {
1266 p = (Path *)Lst_Datum(ln);
1274 if ((file = DirLookupSubdir(p, name)) != NULL) {
1282 if (dot && !checkedDot) {
1284 if ((file = DirLookupSubdir(dot, name)) != NULL)
1287 if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
1293 * Already checked by the given name, since . was in the path,
1294 * so no point in proceeding...
1297 fprintf(debug_file, " Checked . already, returning NULL\n");
1302 } else { /* name[0] == '/' */
1305 * For absolute names, compare directory path prefix against the
1306 * the directory path of each member on the search path for an exact
1307 * match. If we have an exact match on any member of the search path,
1308 * use the cached contents of that member to lookup the final file
1309 * component. If that lookup fails we can safely assume that the
1310 * file does not exist at all. This is signified by DirLookupAbs()
1311 * returning an empty string.
1314 fprintf(debug_file, " Trying exact path matches...\n");
1317 if (!hasLastDot && cur && ((file = DirLookupAbs(cur, name, cp))
1319 if (file[0] == '\0') {
1326 (void)Lst_Open(path);
1327 while ((ln = Lst_Next(path)) != NULL) {
1328 p = (Path *)Lst_Datum(ln);
1331 if ((file = DirLookupAbs(p, name, cp)) != NULL) {
1333 if (file[0] == '\0') {
1342 if (hasLastDot && cur && ((file = DirLookupAbs(cur, name, cp))
1344 if (file[0] == '\0') {
1353 * Didn't find it that way, either. Sigh. Phase 3. Add its directory
1354 * onto the search path in any case, just in case, then look for the
1355 * thing in the hash table. If we find it, grand. We return a new
1356 * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
1357 * Note that if the directory holding the file doesn't exist, this will
1358 * do an extra search of the final directory on the path. Unless something
1359 * weird happens, this search won't succeed and life will be groovy.
1361 * Sigh. We cannot add the directory onto the search path because
1362 * of this amusing case:
1363 * $(INSTALLDIR)/$(FILE): $(FILE)
1365 * $(FILE) exists in $(INSTALLDIR) but not in the current one.
1366 * When searching for $(FILE), we will find it in $(INSTALLDIR)
1367 * b/c we added it here. This is not good...
1370 if (cp == traling_dot) {
1371 cp = strrchr(name, '/');
1375 (void)Dir_AddDir(path, name);
1379 ln = Lst_Last(path);
1383 p = (Path *)Lst_Datum(ln);
1386 if (Hash_FindEntry(&p->files, cp) != NULL) {
1387 return bmake_strdup(name);
1393 fprintf(debug_file, " Looking for \"%s\" ...\n", name);
1397 if (cached_stat(name, &stb) == 0) {
1398 return bmake_strdup(name);
1402 fprintf(debug_file, " failed. Returning NULL\n");
1410 *-----------------------------------------------------------------------
1411 * Dir_FindHereOrAbove --
1412 * search for a path starting at a given directory and then working
1413 * our way up towards the root.
1416 * here starting directory
1417 * search_path the path we are looking for
1418 * result the result of a successful search is placed here
1419 * rlen the length of the result buffer
1420 * (typically MAXPATHLEN + 1)
1423 * 0 on failure, 1 on success [in which case the found path is put
1424 * in the result buffer].
1427 *-----------------------------------------------------------------------
1430 Dir_FindHereOrAbove(char *here, char *search_path, char *result, int rlen) {
1433 char dirbase[MAXPATHLEN + 1], *db_end;
1434 char try[MAXPATHLEN + 1], *try_end;
1436 /* copy out our starting point */
1437 snprintf(dirbase, sizeof(dirbase), "%s", here);
1438 db_end = dirbase + strlen(dirbase);
1440 /* loop until we determine a result */
1443 /* try and stat(2) it ... */
1444 snprintf(try, sizeof(try), "%s/%s", dirbase, search_path);
1445 if (cached_stat(try, &st) != -1) {
1447 * success! if we found a file, chop off
1448 * the filename so we return a directory.
1450 if ((st.st_mode & S_IFMT) != S_IFDIR) {
1451 try_end = try + strlen(try);
1452 while (try_end > try && *try_end != '/')
1455 *try_end = 0; /* chop! */
1461 snprintf(result, rlen, "%s", try);
1466 * nope, we didn't find it. if we used up dirbase we've
1467 * reached the root and failed.
1469 if (db_end == dirbase)
1470 break; /* failed! */
1473 * truncate dirbase from the end to move up a dir
1475 while (db_end > dirbase && *db_end != '/')
1477 *db_end = 0; /* chop! */
1488 *-----------------------------------------------------------------------
1490 * Find the modification time of the file described by gn along the
1491 * search path dirSearchPath.
1494 * gn the file whose modification time is desired
1497 * The modification time or 0 if it doesn't exist
1500 * The modification time is placed in the node's mtime slot.
1501 * If the node didn't have a path entry before, and Dir_FindFile
1502 * found one for it, the full name is placed in the path slot.
1503 *-----------------------------------------------------------------------
1506 Dir_MTime(GNode *gn, Boolean recheck)
1508 char *fullName; /* the full pathname of name */
1509 struct stat stb; /* buffer for finding the mod time */
1511 if (gn->type & OP_ARCHV) {
1512 return Arch_MTime(gn);
1513 } else if (gn->type & OP_PHONY) {
1516 } else if (gn->path == NULL) {
1517 if (gn->type & OP_NOPATH)
1520 fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
1521 if (fullName == NULL && gn->flags & FROM_DEPEND &&
1522 !Lst_IsEmpty(gn->iParents)) {
1525 cp = strrchr(gn->name, '/');
1528 * This is an implied source, and it may have moved,
1529 * see if we can find it via the current .PATH
1533 fullName = Dir_FindFile(cp, Suff_FindPath(gn));
1536 * Put the found file in gn->path
1537 * so that we give that to the compiler.
1539 gn->path = bmake_strdup(fullName);
1540 if (!Job_RunTarget(".STALE", gn->fname))
1542 "%s: %s, %d: ignoring stale %s for %s, "
1543 "found %s\n", progname, gn->fname, gn->lineno,
1544 makeDependfile, gn->name, fullName);
1549 fprintf(debug_file, "Found '%s' as '%s'\n",
1550 gn->name, fullName ? fullName : "(not found)" );
1553 fullName = gn->path;
1556 if (fullName == NULL) {
1557 fullName = bmake_strdup(gn->name);
1560 if (cached_stats(&mtimes, fullName, &stb, recheck ? CST_UPDATE : 0) < 0) {
1561 if (gn->type & OP_MEMBER) {
1562 if (fullName != gn->path)
1564 return Arch_MemMTime(gn);
1570 if (fullName && gn->path == NULL) {
1571 gn->path = fullName;
1574 gn->mtime = stb.st_mtime;
1579 *-----------------------------------------------------------------------
1581 * Add the given name to the end of the given path. The order of
1582 * the arguments is backwards so ParseDoDependency can do a
1583 * Lst_ForEach of its list of paths...
1586 * path the path to which the directory should be
1588 * name the name of the directory to add
1594 * A structure is added to the list and the directory is
1596 *-----------------------------------------------------------------------
1599 Dir_AddDir(Lst path, const char *name)
1601 LstNode ln = NULL; /* node in case Path structure is found */
1602 Path *p = NULL; /* pointer to new Path structure */
1603 DIR *d; /* for reading directory */
1604 struct dirent *dp; /* entry in directory */
1606 if (strcmp(name, ".DOTLAST") == 0) {
1607 ln = Lst_Find(path, name, DirFindName);
1609 return (Path *)Lst_Datum(ln);
1611 dotLast->refCount += 1;
1612 (void)Lst_AtFront(path, dotLast);
1617 ln = Lst_Find(openDirectories, name, DirFindName);
1619 p = (Path *)Lst_Datum(ln);
1620 if (path && Lst_Member(path, p) == NULL) {
1622 (void)Lst_AtEnd(path, p);
1626 fprintf(debug_file, "Caching %s ...", name);
1629 if ((d = opendir(name)) != NULL) {
1630 p = bmake_malloc(sizeof(Path));
1631 p->name = bmake_strdup(name);
1634 Hash_InitTable(&p->files, -1);
1636 while ((dp = readdir(d)) != NULL) {
1637 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
1639 * The sun directory library doesn't check for a 0 inode
1640 * (0-inode slots just take up space), so we have to do
1643 if (dp->d_fileno == 0) {
1646 #endif /* sun && d_ino */
1647 (void)Hash_CreateEntry(&p->files, dp->d_name, NULL);
1650 (void)Lst_AtEnd(openDirectories, p);
1652 (void)Lst_AtEnd(path, p);
1655 fprintf(debug_file, "done\n");
1662 *-----------------------------------------------------------------------
1664 * Callback function for duplicating a search path via Lst_Duplicate.
1665 * Ups the reference count for the directory.
1668 * Returns the Path it was given.
1671 * The refCount of the path is incremented.
1673 *-----------------------------------------------------------------------
1676 Dir_CopyDir(void *p)
1678 ((Path *)p)->refCount += 1;
1684 *-----------------------------------------------------------------------
1686 * Make a string by taking all the directories in the given search
1687 * path and preceding them by the given flag. Used by the suffix
1688 * module to create variables for compilers based on suffix search
1692 * flag flag which should precede each directory
1693 * path list of directories
1696 * The string mentioned above. Note that there is no space between
1697 * the given flag and each directory. The empty string is returned if
1698 * Things don't go well.
1702 *-----------------------------------------------------------------------
1705 Dir_MakeFlags(const char *flag, Lst path)
1707 char *str; /* the string which will be returned */
1708 char *s1, *s2;/* the current directory preceded by 'flag' */
1709 LstNode ln; /* the node of the current directory */
1710 Path *p; /* the structure describing the current directory */
1712 str = bmake_strdup("");
1714 if (Lst_Open(path) == SUCCESS) {
1715 while ((ln = Lst_Next(path)) != NULL) {
1716 p = (Path *)Lst_Datum(ln);
1717 s2 = str_concat(flag, p->name, 0);
1718 str = str_concat(s1 = str, s2, STR_ADDSPACE);
1729 *-----------------------------------------------------------------------
1731 * Nuke a directory descriptor, if possible. Callback procedure
1732 * for the suffixes module when destroying a search path.
1735 * pp The directory descriptor to nuke
1741 * If no other path references this directory (refCount == 0),
1742 * the Path and all its data are freed.
1744 *-----------------------------------------------------------------------
1747 Dir_Destroy(void *pp)
1749 Path *p = (Path *)pp;
1752 if (p->refCount == 0) {
1755 ln = Lst_Member(openDirectories, p);
1756 (void)Lst_Remove(openDirectories, ln);
1758 Hash_DeleteTable(&p->files);
1765 *-----------------------------------------------------------------------
1767 * Clear out all elements of the given search path. This is different
1768 * from destroying the list, notice.
1771 * path Path to clear
1777 * The path is set to the empty list.
1779 *-----------------------------------------------------------------------
1782 Dir_ClearPath(Lst path)
1785 while (!Lst_IsEmpty(path)) {
1786 p = (Path *)Lst_DeQueue(path);
1793 *-----------------------------------------------------------------------
1795 * Concatenate two paths, adding the second to the end of the first.
1796 * Makes sure to avoid duplicates.
1806 * Reference counts for added dirs are upped.
1808 *-----------------------------------------------------------------------
1811 Dir_Concat(Lst path1, Lst path2)
1816 for (ln = Lst_First(path2); ln != NULL; ln = Lst_Succ(ln)) {
1817 p = (Path *)Lst_Datum(ln);
1818 if (Lst_Member(path1, p) == NULL) {
1820 (void)Lst_AtEnd(path1, p);
1825 /********** DEBUG INFO **********/
1827 Dir_PrintDirectories(void)
1832 fprintf(debug_file, "#*** Directory Cache:\n");
1833 fprintf(debug_file, "# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
1834 hits, misses, nearmisses, bigmisses,
1835 (hits+bigmisses+nearmisses ?
1836 hits * 100 / (hits + bigmisses + nearmisses) : 0));
1837 fprintf(debug_file, "# %-20s referenced\thits\n", "directory");
1838 if (Lst_Open(openDirectories) == SUCCESS) {
1839 while ((ln = Lst_Next(openDirectories)) != NULL) {
1840 p = (Path *)Lst_Datum(ln);
1841 fprintf(debug_file, "# %-20s %10d\t%4d\n", p->name, p->refCount, p->hits);
1843 Lst_Close(openDirectories);
1848 DirPrintDir(void *p, void *dummy MAKE_ATTR_UNUSED)
1850 fprintf(debug_file, "%s ", ((Path *)p)->name);
1855 Dir_PrintPath(Lst path)
1857 Lst_ForEach(path, DirPrintDir, NULL);