2 * Copyright (c) 1988, 1989, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1988, 1989 by Adam de Boor
5 * Copyright (c) 1989 by Berkeley Softworks
8 * This code is derived from software contributed to Berkeley by
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * @(#)dir.c 8.2 (Berkeley) 1/2/94
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
47 * Directory searching using wildcards and/or normal names...
48 * Used both for source wildcarding in the Makefile and for finding
51 * The interface for this module is:
52 * Dir_Init Initialize the module.
54 * Dir_HasWildcards Returns TRUE if the name given it needs to
55 * be wildcard-expanded.
57 * Dir_Expand Given a pattern and a path, return a Lst of names
58 * which match the pattern on the search path.
60 * Dir_FindFile Searches for a file on a given search path.
61 * If it exists, the entire path is returned.
62 * Otherwise NULL is returned.
64 * Dir_MTime Return the modification time of a node. The file
65 * is searched for along the default search path.
66 * The path and mtime fields of the node are filled
69 * Dir_AddDir Add a directory to a search path.
71 * Dir_MakeFlags Given a search path and a command flag, create
72 * a string with each of the directories in the path
73 * preceded by the command flag and all of them
74 * separated by a space.
76 * Dir_Destroy Destroy an element of a search path. Frees up all
77 * things that can be freed for the element as long
78 * as the element is no longer referenced by any other
80 * Dir_ClearPath Resets a search path to the empty list.
83 * Dir_PrintDirectories Print stats about the directory cache.
87 #include <sys/types.h>
96 * A search path consists of a Lst of Path structures. A Path structure
97 * has in it the name of the directory and a hash table of all the files
98 * in the directory. This is used to cut down on the number of system
99 * calls necessary to find implicit dependents and their like. Since
100 * these searches are made before any actions are taken, we need not
101 * worry about the directory changing due to creation commands. If this
102 * hampers the style of some makefiles, they must be changed.
104 * A list of all previously-read directories is kept in the
105 * openDirectories Lst. This list is checked first before a directory
108 * The need for the caching of whole directories is brought about by
109 * the multi-level transformation code in suff.c, which tends to search
110 * for far more files than regular make does. In the initial
111 * implementation, the amount of time spent performing "stat" calls was
112 * truly astronomical. The problem with hashing at the start is,
113 * of course, that pmake doesn't then detect changes to these directories
114 * during the course of the make. Three possibilities suggest themselves:
116 * 1) just use stat to test for a file's existence. As mentioned
117 * above, this is very inefficient due to the number of checks
118 * engendered by the multi-level transformation code.
119 * 2) use readdir() and company to search the directories, keeping
120 * them open between checks. I have tried this and while it
121 * didn't slow down the process too much, it could severely
122 * affect the amount of parallelism available as each directory
123 * open would take another file descriptor out of play for
124 * handling I/O for another job. Given that it is only recently
125 * that UNIX OS's have taken to allowing more than 20 or 32
126 * file descriptors for a process, this doesn't seem acceptable
128 * 3) record the mtime of the directory in the Path structure and
129 * verify the directory hasn't changed since the contents were
130 * hashed. This will catch the creation or deletion of files,
131 * but not the updating of files. However, since it is the
132 * creation and deletion that is the problem, this could be
133 * a good thing to do. Unfortunately, if the directory (say ".")
134 * were fairly large and changed fairly frequently, the constant
135 * rehashing could seriously degrade performance. It might be
136 * good in such cases to keep track of the number of rehashes
137 * and if the number goes over a (small) limit, resort to using
140 * An additional thing to consider is that pmake is used primarily
141 * to create C programs and until recently pcc-based compilers refused
142 * to allow you to specify where the resulting object file should be
143 * placed. This forced all objects to be created in the current
144 * directory. This isn't meant as a full excuse, just an explanation of
145 * some of the reasons for the caching used here.
147 * One more note: the location of a target's file is only performed
148 * on the downward traversal of the graph and then only for terminal
149 * nodes in the graph. This could be construed as wrong in some cases,
150 * but prevents inadvertent modification of files when the "installed"
151 * directory for a file is provided in the search path.
153 * Another data structure maintained by this module is an mtime
154 * cache used when the searching of cached directories fails to find
155 * a file. In the past, Dir_FindFile would simply perform an access()
156 * call in such a case to determine if the file could be found using
157 * just the name given. When this hit, however, all that was gained
158 * was the knowledge that the file existed. Given that an access() is
159 * essentially a stat() without the copyout() call, and that the same
160 * filesystem overhead would have to be incurred in Dir_MTime, it made
161 * sense to replace the access() with a stat() and record the mtime
162 * in a cache for when Dir_MTime was actually called.
165 /* main search path */
166 Lst dirSearchPath = Lst_Initializer(dirSearchPath);
168 /* the list of all open directories */
169 static Lst openDirectories = Lst_Initializer(openDirectories);
172 * Variables for gathering statistics on the efficiency of the hashing
175 static int hits; /* Found in directory cache */
176 static int misses; /* Sad, but not evil misses */
177 static int nearmisses; /* Found under search path */
178 static int bigmisses; /* Sought by itself */
180 static Path *dot; /* contents of current directory */
182 /* Results of doing a last-resort stat in Dir_FindFile --
183 * if we have to go to the system to find the file, we might as well
184 * have its mtime on record.
185 * XXX: If this is done way early, there's a chance other rules will
186 * have already updated the file, in which case we'll update it again.
187 * Generally, there won't be two rules to update a single file, so this
188 * should be ok, but...
190 static Hash_Table mtimes;
192 static int DirPrintWord(void *, void *);
193 static int DirPrintDir(void *, void *);
196 *-----------------------------------------------------------------------
198 * initialize things for this module
205 *-----------------------------------------------------------------------
211 Hash_InitTable(&mtimes, 0);
215 *-----------------------------------------------------------------------
217 * initialize the "." directory
223 * some directories may be opened.
224 *-----------------------------------------------------------------------
231 Dir_AddDir(&openDirectories, ".");
232 if ((ln = Lst_Last(&openDirectories)) == NULL)
233 err(1, "cannot open current directory");
237 * We always need to have dot around, so we increment its
238 * reference count to make sure it's not destroyed.
244 *-----------------------------------------------------------------------
246 * See if the Path structure describes the same directory as the
247 * given one by comparing their names. Called from Dir_AddDir via
248 * Lst_Find when searching the list of open directories.
251 * 0 if it is the same. Non-zero otherwise
255 *-----------------------------------------------------------------------
258 DirFindName(const void *p, const void *dname)
261 return (strcmp(((const Path *)p)->name, dname));
265 *-----------------------------------------------------------------------
266 * Dir_HasWildcards --
267 * See if the given name has any wildcard characters in it.
270 * returns TRUE if the word should be expanded, FALSE otherwise
274 *-----------------------------------------------------------------------
277 Dir_HasWildcards(const char *name)
280 int wild = 0, brace = 0, bracket = 0;
282 for (cp = name; *cp; cp++) {
306 return (wild && bracket == 0 && brace == 0);
310 *-----------------------------------------------------------------------
312 * Given a pattern and a Path structure, see if any files
313 * match the pattern and add their names to the 'expansions' list if
314 * any do. This is incomplete -- it doesn't take care of patterns like
315 * src / *src / *.c properly (just *.c on any of the directories), but it
322 * File names are added to the expansions lst. The directory will be
323 * fully hashed when this is done.
324 *-----------------------------------------------------------------------
327 DirMatchFiles(const char *pattern, const Path *p, Lst *expansions)
329 Hash_Search search; /* Index into the directory's table */
330 Hash_Entry *entry; /* Current entry in the table */
331 Boolean isDot; /* TRUE if the directory being searched is . */
333 isDot = (*p->name == '.' && p->name[1] == '\0');
335 for (entry = Hash_EnumFirst(&p->files, &search);
337 entry = Hash_EnumNext(&search)) {
339 * See if the file matches the given pattern. Note we follow
340 * the UNIX convention that dot files will only be found if
341 * the pattern begins with a dot (note also that as a side
342 * effect of the hashing scheme, .* won't match . or ..
343 * since they aren't hashed).
345 if (Str_Match(entry->name, pattern) &&
346 ((entry->name[0] != '.') ||
347 (pattern[0] == '.'))) {
348 Lst_AtEnd(expansions, (isDot ? estrdup(entry->name) :
349 str_concat(p->name, entry->name, STR_ADDSLASH)));
356 *-----------------------------------------------------------------------
358 * Expand curly braces like the C shell. Does this recursively.
359 * Note the special case: if after the piece of the curly brace is
360 * done there are no wildcard characters in the result, the result is
361 * placed on the list WITHOUT CHECKING FOR ITS EXISTENCE. The
362 * given arguments are the entire word to expand, the first curly
363 * brace in the word, the search path, and the list to store the
370 * The given list is filled with the expansions...
372 *-----------------------------------------------------------------------
375 DirExpandCurly(const char *word, const char *brace, Lst *path, Lst *expansions)
377 const char *end; /* Character after the closing brace */
378 const char *cp; /* Current position in brace clause */
379 const char *start; /* Start of current piece of brace clause */
380 int bracelevel; /* Number of braces we've seen. If we see a right brace
381 * when this is 0, we've hit the end of the clause. */
382 char *file; /* Current expansion */
383 int otherLen; /* The length of the other pieces of the expansion
384 * (chars before and after the clause in 'word') */
385 char *cp2; /* Pointer for checking for wildcards in
386 * expansion before calling Dir_Expand */
391 * Find the end of the brace clause first, being wary of nested brace
394 for (end = start, bracelevel = 0; *end != '\0'; end++) {
397 else if ((*end == '}') && (bracelevel-- == 0))
401 Error("Unterminated {} clause \"%s\"", start);
406 otherLen = brace - word + strlen(end);
408 for (cp = start; cp < end; cp++) {
410 * Find the end of this piece of the clause.
416 else if ((*cp == '}') && (bracelevel-- <= 0))
421 * Allocate room for the combination and install the
424 file = emalloc(otherLen + cp - start + 1);
426 strncpy(file, word, brace - word);
428 strncpy(&file[brace - word], start, cp - start);
429 strcpy(&file[(brace - word) + (cp - start)], end);
432 * See if the result has any wildcards in it. If we find one,
433 * call Dir_Expand right away, telling it to place the result
434 * on our list of expansions.
436 for (cp2 = file; *cp2 != '\0'; cp2++) {
442 Dir_Expand(file, path, expansions);
450 * Hit the end w/o finding any wildcards, so stick
451 * the expansion on the end of the list.
453 Lst_AtEnd(expansions, file);
463 *-----------------------------------------------------------------------
465 * Internal expand routine. Passes through the directories in the
466 * path one by one, calling DirMatchFiles for each. NOTE: This still
467 * doesn't handle patterns in directories... Works given a word to
468 * expand, a path to look in, and a list to store expansions in.
474 * Things are added to the expansions list.
476 *-----------------------------------------------------------------------
479 DirExpandInt(const char *word, Lst *path, Lst *expansions)
481 LstNode *ln; /* Current node */
483 for (ln = Lst_First(path); ln != NULL; ln = Lst_Succ(ln))
484 DirMatchFiles(word, (Path *)Lst_Datum(ln), expansions);
488 *-----------------------------------------------------------------------
490 * Print a word in the list of expansions. Callback for Dir_Expand
491 * when DEBUG(DIR), via Lst_ForEach.
497 * The passed word is printed, followed by a space.
499 *-----------------------------------------------------------------------
502 DirPrintWord(void *word, void *dummy __unused)
505 DEBUGF(DIR, ("%s ", (char *)word));
511 *-----------------------------------------------------------------------
513 * Expand the given word into a list of words by globbing it looking
514 * in the directories on the given search path.
517 * A list of words consisting of the files which exist along the search
518 * path matching the given pattern is placed in expansions.
521 * Directories may be opened. Who knows?
522 *-----------------------------------------------------------------------
525 Dir_Expand(char *word, Lst *path, Lst *expansions)
529 DEBUGF(DIR, ("expanding \"%s\"...", word));
531 cp = strchr(word, '{');
533 DirExpandCurly(word, cp, path, expansions);
535 cp = strchr(word, '/');
538 * The thing has a directory component -- find the
539 * first wildcard in the string.
541 for (cp = word; *cp != '\0'; cp++) {
542 if (*cp == '?' || *cp == '[' ||
543 *cp == '*' || *cp == '{') {
549 * This one will be fun.
551 DirExpandCurly(word, cp, path, expansions);
553 } else if (*cp != '\0') {
555 * Back up to the start of the component
559 while (cp > word && *cp != '/')
565 * If the glob isn't in the first
566 * component, try and find all the
567 * components up to the one with a
572 dirpath = Dir_FindFile(word, path);
575 * dirpath is null if can't find the
577 * XXX: Dir_FindFile won't find internal
578 * components. i.e. if the path contains
579 * ../Etc/Object and we're looking for
580 * Etc, * it won't be found. Ah well.
581 * Probably not important.
583 if (dirpath != NULL) {
585 &dirpath[strlen(dirpath)
587 Lst tp = Lst_Initializer(tp);
591 Dir_AddDir(&tp, dirpath);
592 DirExpandInt(cp + 1, &tp,
594 Lst_Destroy(&tp, NOFREE);
598 * Start the search from the local
601 DirExpandInt(word, path, expansions);
605 * Return the file -- this should never happen.
607 DirExpandInt(word, path, expansions);
611 * First the files in dot
613 DirMatchFiles(word, dot, expansions);
616 * Then the files in every other directory on the path.
618 DirExpandInt(word, path, expansions);
622 Lst_ForEach(expansions, DirPrintWord, (void *)NULL);
628 *-----------------------------------------------------------------------
630 * Find the file with the given name along the given search path.
633 * The path to the file or NULL. This path is guaranteed to be in a
634 * different part of memory than name and so may be safely free'd.
637 * If the file is found in a directory which is not on the path
638 * already (either 'name' is absolute or it is a relative path
639 * [ dir1/.../dirn/file ] which exists below one of the directories
640 * already on the search path), its directory is added to the end
641 * of the path on the assumption that there will be more files in
642 * that directory later on. Sometimes this is true. Sometimes not.
643 *-----------------------------------------------------------------------
646 Dir_FindFile(char *name, Lst *path)
648 char *p1; /* pointer into p->name */
649 char *p2; /* pointer into name */
650 LstNode *ln; /* a list element */
651 char *file; /* the current filename to check */
652 Path *p; /* current path member */
653 char *cp; /* final component of the name */
654 Boolean hasSlash; /* true if 'name' contains a / */
655 struct stat stb; /* Buffer for stat, if necessary */
656 Hash_Entry *entry; /* Entry for mtimes table */
659 * Find the final component of the name and note whether it has a
660 * slash in it (the name, I mean)
662 cp = strrchr(name, '/');
671 DEBUGF(DIR, ("Searching for %s...", name));
673 * No matter what, we always look for the file in the current directory
674 * before anywhere else and we *do not* add the ./ to it if it exists.
675 * This is so there are no conflicts between what the user specifies
676 * (fish.c) and what pmake finds (./fish.c).
678 if ((!hasSlash || (cp - name == 2 && *name == '.')) &&
679 (Hash_FindEntry(&dot->files, cp) != NULL)) {
680 DEBUGF(DIR, ("in '.'\n"));
683 return (estrdup(name));
687 * We look through all the directories on the path seeking one which
688 * contains the final component of the given name and whose final
689 * component(s) match the name's initial component(s). If such a beast
690 * is found, we concatenate the directory name and the final component
691 * and return the resulting string. If we don't find any such thing,
692 * we go on to phase two...
694 for (ln = Lst_First(path); ln != NULL; ln = Lst_Succ(ln)) {
696 DEBUGF(DIR, ("%s...", p->name));
697 if (Hash_FindEntry(&p->files, cp) != NULL) {
698 DEBUGF(DIR, ("here..."));
701 * If the name had a slash, its initial
702 * components and p's final components must
703 * match. This is false if a mismatch is
704 * encountered before all of the initial
705 * components have been checked (p2 > name at
706 * the end of the loop), or we matched only
707 * part of one of the components of p
708 * along with all the rest of them (*p1 != '/').
710 p1 = p->name + strlen(p->name) - 1;
712 while (p2 >= name && p1 >= p->name &&
716 if (p2 >= name || (p1 >= p->name &&
718 DEBUGF(DIR, ("component mismatch -- "
723 file = str_concat(p->name, cp, STR_ADDSLASH);
724 DEBUGF(DIR, ("returning %s\n", file));
728 } else if (hasSlash) {
730 * If the file has a leading path component and that
731 * component exactly matches the entire name of the
732 * current search directory, we assume the file
733 * doesn't exist and return NULL.
735 for (p1 = p->name, p2 = name; *p1 && *p1 == *p2;
738 if (*p1 == '\0' && p2 == cp - 1) {
739 if (*cp == '\0' || ISDOT(cp) || ISDOTDOT(cp)) {
740 DEBUGF(DIR, ("returning %s\n", name));
741 return (estrdup(name));
743 DEBUGF(DIR, ("must be here but isn't --"
744 " returning NULL\n"));
752 * We didn't find the file on any existing members of the directory.
753 * If the name doesn't contain a slash, that means it doesn't exist.
754 * If it *does* contain a slash, however, there is still hope: it
755 * could be in a subdirectory of one of the members of the search
756 * path. (eg. /usr/include and sys/types.h. The above search would
757 * fail to turn up types.h in /usr/include, but it *is* in
758 * /usr/include/sys/types.h) If we find such a beast, we assume there
759 * will be more (what else can we assume?) and add all but the last
760 * component of the resulting name onto the search path (at the
761 * end). This phase is only performed if the file is *not* absolute.
764 DEBUGF(DIR, ("failed.\n"));
770 Boolean checkedDot = FALSE;
772 DEBUGF(DIR, ("failed. Trying subdirectories..."));
773 for (ln = Lst_First(path); ln != NULL; ln = Lst_Succ(ln)) {
776 file = str_concat(p->name, name, STR_ADDSLASH);
779 * Checking in dot -- DON'T put a leading ./
782 file = estrdup(name);
785 DEBUGF(DIR, ("checking %s...", file));
787 if (stat(file, &stb) == 0) {
788 DEBUGF(DIR, ("got it.\n"));
791 * We've found another directory to search. We
792 * know there's a slash in 'file' because we put
793 * one there. We nuke it after finding it and
794 * call Dir_AddDir to add this new directory
795 * onto the existing search path. Once that's
796 * done, we restore the slash and triumphantly
797 * return the file name, knowing that should a
798 * file in this directory every be referenced
799 * again in such a manner, we will find it
800 * without having to do numerous numbers of
801 * access calls. Hurrah!
803 cp = strrchr(file, '/');
805 Dir_AddDir(path, file);
809 * Save the modification time so if
810 * it's needed, we don't have to fetch it again.
812 DEBUGF(DIR, ("Caching %s for %s\n",
813 Targ_FmtTime(stb.st_mtime), file));
814 entry = Hash_CreateEntry(&mtimes, file,
817 (void *)(long)stb.st_mtime);
825 DEBUGF(DIR, ("failed. "));
829 * Already checked by the given name, since . was in
830 * the path, so no point in proceeding...
832 DEBUGF(DIR, ("Checked . already, returning NULL\n"));
838 * Didn't find it that way, either. Sigh. Phase 3. Add its directory
839 * onto the search path in any case, just in case, then look for the
840 * thing in the hash table. If we find it, grand. We return a new
841 * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
842 * Note that if the directory holding the file doesn't exist, this will
843 * do an extra search of the final directory on the path. Unless
844 * something weird happens, this search won't succeed and life will
847 * Sigh. We cannot add the directory onto the search path because
848 * of this amusing case:
849 * $(INSTALLDIR)/$(FILE): $(FILE)
851 * $(FILE) exists in $(INSTALLDIR) but not in the current one.
852 * When searching for $(FILE), we will find it in $(INSTALLDIR)
853 * b/c we added it here. This is not good...
857 Dir_AddDir(path, name);
867 if (Hash_FindEntry(&p->files, cp) != NULL) {
868 return (estrdup(name));
872 DEBUGF(DIR, ("Looking for \"%s\"...", name));
875 entry = Hash_FindEntry(&mtimes, name);
877 DEBUGF(DIR, ("got it (in mtime cache)\n"));
878 return (estrdup(name));
879 } else if (stat (name, &stb) == 0) {
880 entry = Hash_CreateEntry(&mtimes, name, (Boolean *)NULL);
881 DEBUGF(DIR, ("Caching %s for %s\n",
882 Targ_FmtTime(stb.st_mtime), name));
883 Hash_SetValue(entry, (void *)(long)stb.st_mtime);
884 return (estrdup(name));
886 DEBUGF(DIR, ("failed. Returning NULL\n"));
893 *-----------------------------------------------------------------------
895 * Find the modification time of the file described by gn along the
896 * search path dirSearchPath.
899 * The modification time or 0 if it doesn't exist
902 * The modification time is placed in the node's mtime slot.
903 * If the node didn't have a path entry before, and Dir_FindFile
904 * found one for it, the full name is placed in the path slot.
905 *-----------------------------------------------------------------------
910 char *fullName; /* the full pathname of name */
911 struct stat stb; /* buffer for finding the mod time */
914 if (gn->type & OP_ARCHV)
915 return (Arch_MTime(gn));
917 else if (gn->path == NULL)
918 fullName = Dir_FindFile(gn->name, &dirSearchPath);
922 if (fullName == NULL)
923 fullName = estrdup(gn->name);
925 entry = Hash_FindEntry(&mtimes, fullName);
928 * Only do this once -- the second time folks are checking to
929 * see if the file was actually updated, so we need to
930 * actually go to the filesystem.
932 DEBUGF(DIR, ("Using cached time %s for %s\n",
933 Targ_FmtTime((time_t)(long)Hash_GetValue(entry)),
935 stb.st_mtime = (time_t)(long)Hash_GetValue(entry);
936 Hash_DeleteEntry(&mtimes, entry);
937 } else if (stat(fullName, &stb) < 0) {
938 if (gn->type & OP_MEMBER) {
939 if (fullName != gn->path)
941 return (Arch_MemMTime(gn));
946 if (fullName && gn->path == (char *)NULL)
949 gn->mtime = stb.st_mtime;
954 *-----------------------------------------------------------------------
956 * Add the given name to the end of the given path. The order of
957 * the arguments is backwards so ParseDoDependency can do a
958 * Lst_ForEach of its list of paths...
964 * A structure is added to the list and the directory is
966 *-----------------------------------------------------------------------
969 Dir_AddDir(Lst *path, char *name)
971 LstNode *ln; /* node in case Path structure is found */
972 Path *p; /* pointer to new Path structure */
973 DIR *d; /* for reading directory */
974 struct dirent *dp; /* entry in directory */
976 ln = Lst_Find(&openDirectories, name, DirFindName);
979 if (Lst_Member(path, p) == NULL) {
984 DEBUGF(DIR, ("Caching %s...", name));
986 if ((d = opendir(name)) != NULL) {
987 p = emalloc(sizeof(Path));
988 p->name = estrdup(name);
991 Hash_InitTable(&p->files, -1);
993 while ((dp = readdir(d)) != NULL) {
994 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
996 * The sun directory library doesn't check for
997 * a 0 inode (0-inode slots just take up space),
998 * so we have to do it ourselves.
1000 if (dp->d_fileno == 0)
1002 #endif /* sun && d_ino */
1004 /* Skip the '.' and '..' entries by checking
1005 * for them specifically instead of assuming
1006 * readdir() reuturns them in that order when
1007 * first going through a directory. This is
1008 * needed for XFS over NFS filesystems since
1009 * SGI does not guarantee that these are the
1010 * first two entries returned from readdir().
1012 if (ISDOT(dp->d_name) || ISDOTDOT(dp->d_name))
1015 Hash_CreateEntry(&p->files, dp->d_name,
1019 Lst_AtEnd(&openDirectories, p);
1020 if (path != &openDirectories)
1023 DEBUGF(DIR, ("done\n"));
1028 *-----------------------------------------------------------------------
1030 * Callback function for duplicating a search path via Lst_Duplicate.
1031 * Ups the reference count for the directory.
1034 * Returns the Path it was given.
1037 * The refCount of the path is incremented.
1039 *-----------------------------------------------------------------------
1042 Dir_CopyDir(void *p)
1045 ((Path *)p)->refCount += 1;
1051 *-----------------------------------------------------------------------
1053 * Make a string by taking all the directories in the given search
1054 * path and preceding them by the given flag. Used by the suffix
1055 * module to create variables for compilers based on suffix search
1059 * The string mentioned above. Note that there is no space between
1060 * the given flag and each directory. The empty string is returned if
1061 * Things don't go well.
1065 *-----------------------------------------------------------------------
1068 Dir_MakeFlags(char *flag, Lst *path)
1070 char *str; /* the string which will be returned */
1071 char *tstr; /* the current directory preceded by 'flag' */
1073 LstNode *ln; /* the node of the current directory */
1074 Path *p; /* the structure describing the current directory */
1078 for (ln = Lst_First(path); ln != NULL; ln = Lst_Succ(ln)) {
1080 tstr = str_concat(flag, p->name, 0);
1081 nstr = str_concat(str, tstr, STR_ADDSPACE);
1091 *-----------------------------------------------------------------------
1093 * Nuke a directory descriptor, if possible. Callback procedure
1094 * for the suffixes module when destroying a search path.
1100 * If no other path references this directory (refCount == 0),
1101 * the Path and all its data are freed.
1103 *-----------------------------------------------------------------------
1106 Dir_Destroy(void *pp)
1112 if (p->refCount == 0) {
1115 if ((ln = Lst_Member(&openDirectories, p)) != NULL)
1116 Lst_Remove(&openDirectories, ln);
1118 Hash_DeleteTable(&p->files);
1125 *-----------------------------------------------------------------------
1127 * Clear out all elements of the given search path. This is different
1128 * from destroying the list, notice.
1134 * The path is set to the empty list.
1136 *-----------------------------------------------------------------------
1139 Dir_ClearPath(Lst *path)
1143 while (!Lst_IsEmpty(path)) {
1144 p = Lst_DeQueue(path);
1151 *-----------------------------------------------------------------------
1153 * Concatenate two paths, adding the second to the end of the first.
1154 * Makes sure to avoid duplicates.
1160 * Reference counts for added dirs are upped.
1162 *-----------------------------------------------------------------------
1165 Dir_Concat(Lst *path1, Lst *path2)
1170 for (ln = Lst_First(path2); ln != NULL; ln = Lst_Succ(ln)) {
1172 if (Lst_Member(path1, p) == NULL) {
1174 Lst_AtEnd(path1, p);
1179 /********** DEBUG INFO **********/
1181 Dir_PrintDirectories(void)
1186 printf("#*** Directory Cache:\n");
1187 printf("# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
1188 hits, misses, nearmisses, bigmisses,
1189 (hits + bigmisses + nearmisses ?
1190 hits * 100 / (hits + bigmisses + nearmisses) : 0));
1191 printf("# %-20s referenced\thits\n", "directory");
1192 for (ln = Lst_First(&openDirectories); ln != NULL; ln = Lst_Succ(ln)) {
1194 printf("# %-20s %10d\t%4d\n", p->name, p->refCount, p->hits);
1199 DirPrintDir(void *p, void *dummy __unused)
1202 printf("%s ", ((Path *)p)->name);
1208 Dir_PrintPath(Lst *path)
1211 Lst_ForEach(path, DirPrintDir, (void *)NULL);