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
40 * $FreeBSD: src/usr.bin/make/dir.c,v 1.47 2005/02/04 07:50:59 harti Exp $
41 * $DragonFly: src/usr.bin/make/dir.c,v 1.36 2005/03/31 22:16:35 okumoto Exp $
46 * Directory searching using wildcards and/or normal names...
47 * Used both for source wildcarding in the Makefile and for finding
50 * The interface for this module is:
51 * Dir_Init Initialize the module.
53 * Dir_HasWildcards Returns TRUE if the name given it needs to
54 * be wildcard-expanded.
56 * Path_Expand Given a pattern and a path, return a Lst of names
57 * which match the pattern on the search path.
59 * Path_FindFile Searches for a file on a given search path.
60 * If it exists, the entire path is returned.
61 * Otherwise NULL is returned.
63 * Dir_MTime Return the modification time of a node. The file
64 * is searched for along the default search path.
65 * The path and mtime fields of the node are filled in.
67 * Path_AddDir Add a directory to a search path.
69 * Dir_MakeFlags Given a search path and a command flag, create
70 * a string with each of the directories in the path
71 * preceded by the command flag and all of them
72 * separated by a space.
74 * Dir_Destroy Destroy an element of a search path. Frees up all
75 * things that can be freed for the element as long
76 * as the element is no longer referenced by any other
79 * Dir_ClearPath Resets a search path to the empty list.
82 * Dir_PrintDirectories Print stats about the directory cache.
85 #include <sys/types.h>
106 * A search path consists of a list of Dir structures. A Dir structure
107 * has in it the name of the directory and a hash table of all the files
108 * in the directory. This is used to cut down on the number of system
109 * calls necessary to find implicit dependents and their like. Since
110 * these searches are made before any actions are taken, we need not
111 * worry about the directory changing due to creation commands. If this
112 * hampers the style of some makefiles, they must be changed.
114 * A list of all previously-read directories is kept in the
115 * openDirectories list. This list is checked first before a directory
118 * The need for the caching of whole directories is brought about by
119 * the multi-level transformation code in suff.c, which tends to search
120 * for far more files than regular make does. In the initial
121 * implementation, the amount of time spent performing "stat" calls was
122 * truly astronomical. The problem with hashing at the start is,
123 * of course, that pmake doesn't then detect changes to these directories
124 * during the course of the make. Three possibilities suggest themselves:
126 * 1) just use stat to test for a file's existence. As mentioned
127 * above, this is very inefficient due to the number of checks
128 * engendered by the multi-level transformation code.
129 * 2) use readdir() and company to search the directories, keeping
130 * them open between checks. I have tried this and while it
131 * didn't slow down the process too much, it could severely
132 * affect the amount of parallelism available as each directory
133 * open would take another file descriptor out of play for
134 * handling I/O for another job. Given that it is only recently
135 * that UNIX OS's have taken to allowing more than 20 or 32
136 * file descriptors for a process, this doesn't seem acceptable
138 * 3) record the mtime of the directory in the Dir structure and
139 * verify the directory hasn't changed since the contents were
140 * hashed. This will catch the creation or deletion of files,
141 * but not the updating of files. However, since it is the
142 * creation and deletion that is the problem, this could be
143 * a good thing to do. Unfortunately, if the directory (say ".")
144 * were fairly large and changed fairly frequently, the constant
145 * rehashing could seriously degrade performance. It might be
146 * good in such cases to keep track of the number of rehashes
147 * and if the number goes over a (small) limit, resort to using
150 * An additional thing to consider is that pmake is used primarily
151 * to create C programs and until recently pcc-based compilers refused
152 * to allow you to specify where the resulting object file should be
153 * placed. This forced all objects to be created in the current
154 * directory. This isn't meant as a full excuse, just an explanation of
155 * some of the reasons for the caching used here.
157 * One more note: the location of a target's file is only performed
158 * on the downward traversal of the graph and then only for terminal
159 * nodes in the graph. This could be construed as wrong in some cases,
160 * but prevents inadvertent modification of files when the "installed"
161 * directory for a file is provided in the search path.
163 * Another data structure maintained by this module is an mtime
164 * cache used when the searching of cached directories fails to find
165 * a file. In the past, Path_FindFile would simply perform an access()
166 * call in such a case to determine if the file could be found using
167 * just the name given. When this hit, however, all that was gained
168 * was the knowledge that the file existed. Given that an access() is
169 * essentially a stat() without the copyout() call, and that the same
170 * filesystem overhead would have to be incurred in Dir_MTime, it made
171 * sense to replace the access() with a stat() and record the mtime
172 * in a cache for when Dir_MTime was actually called.
176 char *name; /* Name of directory */
177 int refCount; /* No. of paths with this directory */
178 int hits; /* No. of times a file has been found here */
179 Hash_Table files; /* Hash table of files in directory */
180 TAILQ_ENTRY(Dir) link; /* allDirs link */
184 * A path is a list of pointers to directories. These directories are
185 * reference counted so a directory can be on more than one path.
188 struct Dir *dir; /* pointer to the directory */
189 TAILQ_ENTRY(PathElement) link; /* path link */
192 /* main search path */
193 struct Path dirSearchPath = TAILQ_HEAD_INITIALIZER(dirSearchPath);
195 /* the list of all open directories */
196 static TAILQ_HEAD(, Dir) openDirectories =
197 TAILQ_HEAD_INITIALIZER(openDirectories);
200 * Variables for gathering statistics on the efficiency of the hashing
203 static int hits; /* Found in directory cache */
204 static int misses; /* Sad, but not evil misses */
205 static int nearmisses; /* Found under search path */
206 static int bigmisses; /* Sought by itself */
208 static Dir *dot; /* contents of current directory */
210 /* Results of doing a last-resort stat in Path_FindFile --
211 * if we have to go to the system to find the file, we might as well
212 * have its mtime on record.
213 * XXX: If this is done way early, there's a chance other rules will
214 * have already updated the file, in which case we'll update it again.
215 * Generally, there won't be two rules to update a single file, so this
216 * should be ok, but...
218 static Hash_Table mtimes;
221 *-----------------------------------------------------------------------
223 * initialize things for this module
230 *-----------------------------------------------------------------------
236 Hash_InitTable(&mtimes, 0);
240 *-----------------------------------------------------------------------
242 * initialize the "." directory
248 * some directories may be opened.
249 *-----------------------------------------------------------------------
255 dot = Path_AddDir(NULL, ".");
257 err(1, "cannot open current directory");
260 * We always need to have dot around, so we increment its
261 * reference count to make sure it's not destroyed.
267 *-----------------------------------------------------------------------
268 * Dir_HasWildcards --
269 * See if the given name has any wildcard characters in it.
272 * returns TRUE if the word should be expanded, FALSE otherwise
276 *-----------------------------------------------------------------------
279 Dir_HasWildcards(const char *name)
282 int wild = 0, brace = 0, bracket = 0;
284 for (cp = name; *cp; cp++) {
308 return (wild && bracket == 0 && brace == 0);
312 *-----------------------------------------------------------------------
314 * Given a pattern and a Dir structure, see if any files
315 * match the pattern and add their names to the 'expansions' list if
316 * any do. This is incomplete -- it doesn't take care of patterns like
317 * src / *src / *.c properly (just *.c on any of the directories), but it
324 * File names are added to the expansions lst. The directory will be
325 * fully hashed when this is done.
326 *-----------------------------------------------------------------------
329 DirMatchFiles(const char *pattern, const Dir *p, Lst *expansions)
331 Hash_Search search; /* Index into the directory's table */
332 Hash_Entry *entry; /* Current entry in the table */
333 Boolean isDot; /* TRUE if the directory being searched is . */
335 isDot = (*p->name == '.' && p->name[1] == '\0');
337 for (entry = Hash_EnumFirst(&p->files, &search);
339 entry = Hash_EnumNext(&search)) {
341 * See if the file matches the given pattern. Note we follow
342 * the UNIX convention that dot files will only be found if
343 * the pattern begins with a dot (note also that as a side
344 * effect of the hashing scheme, .* won't match . or ..
345 * since they aren't hashed).
347 if (Str_Match(entry->name, pattern) &&
348 ((entry->name[0] != '.') ||
349 (pattern[0] == '.'))) {
350 Lst_AtEnd(expansions, (isDot ? estrdup(entry->name) :
351 str_concat(p->name, entry->name, STR_ADDSLASH)));
358 *-----------------------------------------------------------------------
360 * Expand curly braces like the C shell. Does this recursively.
361 * Note the special case: if after the piece of the curly brace is
362 * done there are no wildcard characters in the result, the result is
363 * placed on the list WITHOUT CHECKING FOR ITS EXISTENCE. The
364 * given arguments are the entire word to expand, the first curly
365 * brace in the word, the search path, and the list to store the
372 * The given list is filled with the expansions...
374 *-----------------------------------------------------------------------
377 DirExpandCurly(const char *word, const char *brace, struct Path *path,
380 const char *end; /* Character after the closing brace */
381 const char *cp; /* Current position in brace clause */
382 const char *start; /* Start of current piece of brace clause */
383 int bracelevel; /* Number of braces we've seen. If we see a right brace
384 * when this is 0, we've hit the end of the clause. */
385 char *file; /* Current expansion */
386 int otherLen; /* The length of the other pieces of the expansion
387 * (chars before and after the clause in 'word') */
388 char *cp2; /* Pointer for checking for wildcards in
389 * expansion before calling Dir_Expand */
394 * Find the end of the brace clause first, being wary of nested brace
397 for (end = start, bracelevel = 0; *end != '\0'; end++) {
400 else if ((*end == '}') && (bracelevel-- == 0))
404 Error("Unterminated {} clause \"%s\"", start);
409 otherLen = brace - word + strlen(end);
411 for (cp = start; cp < end; cp++) {
413 * Find the end of this piece of the clause.
419 else if ((*cp == '}') && (bracelevel-- <= 0))
424 * Allocate room for the combination and install the
427 file = emalloc(otherLen + cp - start + 1);
429 strncpy(file, word, brace - word);
431 strncpy(&file[brace - word], start, cp - start);
432 strcpy(&file[(brace - word) + (cp - start)], end);
435 * See if the result has any wildcards in it. If we find one,
436 * call Dir_Expand right away, telling it to place the result
437 * on our list of expansions.
439 for (cp2 = file; *cp2 != '\0'; cp2++) {
445 Path_Expand(file, path, expansions);
453 * Hit the end w/o finding any wildcards, so stick
454 * the expansion on the end of the list.
456 Lst_AtEnd(expansions, file);
466 *-----------------------------------------------------------------------
468 * Internal expand routine. Passes through the directories in the
469 * path one by one, calling DirMatchFiles for each. NOTE: This still
470 * doesn't handle patterns in directories... Works given a word to
471 * expand, a path to look in, and a list to store expansions in.
477 * Things are added to the expansions list.
479 *-----------------------------------------------------------------------
482 DirExpandInt(const char *word, const struct Path *path, Lst *expansions)
484 struct PathElement *pe;
486 TAILQ_FOREACH(pe, path, link)
487 DirMatchFiles(word, pe->dir, expansions);
491 *-----------------------------------------------------------------------
493 * Expand the given word into a list of words by globbing it looking
494 * in the directories on the given search path.
497 * A list of words consisting of the files which exist along the search
498 * path matching the given pattern is placed in expansions.
501 * Directories may be opened. Who knows?
502 *-----------------------------------------------------------------------
505 Path_Expand(char *word, struct Path *path, Lst *expansions)
510 DEBUGF(DIR, ("expanding \"%s\"...", word));
512 cp = strchr(word, '{');
514 DirExpandCurly(word, cp, path, expansions);
516 cp = strchr(word, '/');
519 * The thing has a directory component -- find the
520 * first wildcard in the string.
522 for (cp = word; *cp != '\0'; cp++) {
523 if (*cp == '?' || *cp == '[' ||
524 *cp == '*' || *cp == '{') {
530 * This one will be fun.
532 DirExpandCurly(word, cp, path, expansions);
534 } else if (*cp != '\0') {
536 * Back up to the start of the component
540 while (cp > word && *cp != '/')
546 * If the glob isn't in the first
547 * component, try and find all the
548 * components up to the one with a
553 dirpath = Path_FindFile(word, path);
556 * dirpath is null if can't find the
558 * XXX: Path_FindFile won't find internal
559 * components. i.e. if the path contains
560 * ../Etc/Object and we're looking for
561 * Etc, * it won't be found. Ah well.
562 * Probably not important.
564 if (dirpath != NULL) {
566 &dirpath[strlen(dirpath)
569 TAILQ_HEAD_INITIALIZER(tp);
573 Path_AddDir(&tp, dirpath);
574 DirExpandInt(cp + 1, &tp,
580 * Start the search from the local
583 DirExpandInt(word, path, expansions);
587 * Return the file -- this should never happen.
589 DirExpandInt(word, path, expansions);
593 * First the files in dot
595 DirMatchFiles(word, dot, expansions);
598 * Then the files in every other directory on the path.
600 DirExpandInt(word, path, expansions);
604 LST_FOREACH(ln, expansions)
605 DEBUGF(DIR, ("%s ", (const char *)Lst_Datum(ln)));
612 * Find the file with the given name along the given search path.
615 * The path to the file or NULL. This path is guaranteed to be in a
616 * different part of memory than name and so may be safely free'd.
619 * If the file is found in a directory which is not on the path
620 * already (either 'name' is absolute or it is a relative path
621 * [ dir1/.../dirn/file ] which exists below one of the directories
622 * already on the search path), its directory is added to the end
623 * of the path on the assumption that there will be more files in
624 * that directory later on. Sometimes this is true. Sometimes not.
627 Path_FindFile(char *name, struct Path *path)
629 char *p1; /* pointer into p->name */
630 char *p2; /* pointer into name */
631 char *file; /* the current filename to check */
632 const struct PathElement *pe; /* current path member */
633 char *cp; /* final component of the name */
634 Boolean hasSlash; /* true if 'name' contains a / */
635 struct stat stb; /* Buffer for stat, if necessary */
636 Hash_Entry *entry; /* Entry for mtimes table */
639 * Find the final component of the name and note whether it has a
640 * slash in it (the name, I mean)
642 cp = strrchr(name, '/');
651 DEBUGF(DIR, ("Searching for %s...", name));
653 * No matter what, we always look for the file in the current directory
654 * before anywhere else and we *do not* add the ./ to it if it exists.
655 * This is so there are no conflicts between what the user specifies
656 * (fish.c) and what pmake finds (./fish.c).
658 if ((!hasSlash || (cp - name == 2 && *name == '.')) &&
659 (Hash_FindEntry(&dot->files, cp) != NULL)) {
660 DEBUGF(DIR, ("in '.'\n"));
663 return (estrdup(name));
667 * We look through all the directories on the path seeking one which
668 * contains the final component of the given name and whose final
669 * component(s) match the name's initial component(s). If such a beast
670 * is found, we concatenate the directory name and the final component
671 * and return the resulting string. If we don't find any such thing,
672 * we go on to phase two...
674 TAILQ_FOREACH(pe, path, link) {
675 DEBUGF(DIR, ("%s...", pe->dir->name));
676 if (Hash_FindEntry(&pe->dir->files, cp) != NULL) {
677 DEBUGF(DIR, ("here..."));
680 * If the name had a slash, its initial
681 * components and p's final components must
682 * match. This is false if a mismatch is
683 * encountered before all of the initial
684 * components have been checked (p2 > name at
685 * the end of the loop), or we matched only
686 * part of one of the components of p
687 * along with all the rest of them (*p1 != '/').
689 p1 = pe->dir->name + strlen(pe->dir->name) - 1;
691 while (p2 >= name && p1 >= pe->dir->name &&
695 if (p2 >= name || (p1 >= pe->dir->name &&
697 DEBUGF(DIR, ("component mismatch -- "
702 file = str_concat(pe->dir->name, cp, STR_ADDSLASH);
703 DEBUGF(DIR, ("returning %s\n", file));
707 } else if (hasSlash) {
709 * If the file has a leading path component and that
710 * component exactly matches the entire name of the
711 * current search directory, we assume the file
712 * doesn't exist and return NULL.
714 for (p1 = pe->dir->name, p2 = name; *p1 && *p1 == *p2;
717 if (*p1 == '\0' && p2 == cp - 1) {
718 if (*cp == '\0' || ISDOT(cp) || ISDOTDOT(cp)) {
719 DEBUGF(DIR, ("returning %s\n", name));
720 return (estrdup(name));
722 DEBUGF(DIR, ("must be here but isn't --"
723 " returning NULL\n"));
731 * We didn't find the file on any existing members of the directory.
732 * If the name doesn't contain a slash, that means it doesn't exist.
733 * If it *does* contain a slash, however, there is still hope: it
734 * could be in a subdirectory of one of the members of the search
735 * path. (eg. /usr/include and sys/types.h. The above search would
736 * fail to turn up types.h in /usr/include, but it *is* in
737 * /usr/include/sys/types.h) If we find such a beast, we assume there
738 * will be more (what else can we assume?) and add all but the last
739 * component of the resulting name onto the search path (at the
740 * end). This phase is only performed if the file is *not* absolute.
743 DEBUGF(DIR, ("failed.\n"));
749 Boolean checkedDot = FALSE;
751 DEBUGF(DIR, ("failed. Trying subdirectories..."));
752 TAILQ_FOREACH(pe, path, link) {
753 if (pe->dir != dot) {
754 file = str_concat(pe->dir->name,
758 * Checking in dot -- DON'T put a leading ./
761 file = estrdup(name);
764 DEBUGF(DIR, ("checking %s...", file));
766 if (stat(file, &stb) == 0) {
767 DEBUGF(DIR, ("got it.\n"));
770 * We've found another directory to search. We
771 * know there's a slash in 'file' because we put
772 * one there. We nuke it after finding it and
773 * call Path_AddDir to add this new directory
774 * onto the existing search path. Once that's
775 * done, we restore the slash and triumphantly
776 * return the file name, knowing that should a
777 * file in this directory every be referenced
778 * again in such a manner, we will find it
779 * without having to do numerous numbers of
780 * access calls. Hurrah!
782 cp = strrchr(file, '/');
784 Path_AddDir(path, file);
788 * Save the modification time so if
789 * it's needed, we don't have to fetch it again.
791 DEBUGF(DIR, ("Caching %s for %s\n",
792 Targ_FmtTime(stb.st_mtime), file));
793 entry = Hash_CreateEntry(&mtimes, file,
796 (void *)(long)stb.st_mtime);
804 DEBUGF(DIR, ("failed. "));
808 * Already checked by the given name, since . was in
809 * the path, so no point in proceeding...
811 DEBUGF(DIR, ("Checked . already, returning NULL\n"));
817 * Didn't find it that way, either. Sigh. Phase 3. Add its directory
818 * onto the search path in any case, just in case, then look for the
819 * thing in the hash table. If we find it, grand. We return a new
820 * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
821 * Note that if the directory holding the file doesn't exist, this will
822 * do an extra search of the final directory on the path. Unless
823 * something weird happens, this search won't succeed and life will
826 * Sigh. We cannot add the directory onto the search path because
827 * of this amusing case:
828 * $(INSTALLDIR)/$(FILE): $(FILE)
830 * $(FILE) exists in $(INSTALLDIR) but not in the current one.
831 * When searching for $(FILE), we will find it in $(INSTALLDIR)
832 * b/c we added it here. This is not good...
836 Path_AddDir(path, name);
840 pe = TAILQ_LAST(path, Path);
844 if (Hash_FindEntry(&pe->dir->files, cp) != NULL) {
845 return (estrdup(name));
849 DEBUGF(DIR, ("Looking for \"%s\"...", name));
852 entry = Hash_FindEntry(&mtimes, name);
854 DEBUGF(DIR, ("got it (in mtime cache)\n"));
855 return (estrdup(name));
856 } else if (stat (name, &stb) == 0) {
857 entry = Hash_CreateEntry(&mtimes, name, (Boolean *)NULL);
858 DEBUGF(DIR, ("Caching %s for %s\n",
859 Targ_FmtTime(stb.st_mtime), name));
860 Hash_SetValue(entry, (void *)(long)stb.st_mtime);
861 return (estrdup(name));
863 DEBUGF(DIR, ("failed. Returning NULL\n"));
870 *-----------------------------------------------------------------------
872 * Find the modification time of the file described by gn along the
873 * search path dirSearchPath.
876 * The modification time or 0 if it doesn't exist
879 * The modification time is placed in the node's mtime slot.
880 * If the node didn't have a path entry before, and Dir_FindFile
881 * found one for it, the full name is placed in the path slot.
882 *-----------------------------------------------------------------------
887 char *fullName; /* the full pathname of name */
888 struct stat stb; /* buffer for finding the mod time */
891 if (gn->type & OP_ARCHV)
892 return (Arch_MTime(gn));
894 else if (gn->path == NULL)
895 fullName = Path_FindFile(gn->name, &dirSearchPath);
899 if (fullName == NULL)
900 fullName = estrdup(gn->name);
902 entry = Hash_FindEntry(&mtimes, fullName);
905 * Only do this once -- the second time folks are checking to
906 * see if the file was actually updated, so we need to
907 * actually go to the filesystem.
909 DEBUGF(DIR, ("Using cached time %s for %s\n",
910 Targ_FmtTime((time_t)(long)Hash_GetValue(entry)),
912 stb.st_mtime = (time_t)(long)Hash_GetValue(entry);
913 Hash_DeleteEntry(&mtimes, entry);
914 } else if (stat(fullName, &stb) < 0) {
915 if (gn->type & OP_MEMBER) {
916 if (fullName != gn->path)
918 return (Arch_MemMTime(gn));
923 if (fullName && gn->path == (char *)NULL)
926 gn->mtime = stb.st_mtime;
931 *-----------------------------------------------------------------------
933 * Add the given name to the end of the given path.
939 * A structure is added to the list and the directory is
941 *-----------------------------------------------------------------------
944 Path_AddDir(struct Path *path, const char *name)
946 Dir *d; /* pointer to new Path structure */
947 DIR *dir; /* for reading directory */
948 struct PathElement *pe;
949 struct dirent *dp; /* entry in directory */
951 /* check whether we know this directory */
952 TAILQ_FOREACH(d, &openDirectories, link) {
953 if (strcmp(d->name, name) == 0) {
958 /* Check whether its already on the path. */
959 TAILQ_FOREACH(pe, path, link) {
963 /* Add it to the path */
965 pe = emalloc(sizeof(*pe));
967 TAILQ_INSERT_TAIL(path, pe, link);
972 DEBUGF(DIR, ("Caching %s...", name));
974 if ((dir = opendir(name)) == NULL) {
975 DEBUGF(DIR, (" cannot open\n"));
979 d = emalloc(sizeof(*d));
980 d->name = estrdup(name);
983 Hash_InitTable(&d->files, -1);
985 while ((dp = readdir(dir)) != NULL) {
986 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
988 * The sun directory library doesn't check for
989 * a 0 inode (0-inode slots just take up space),
990 * so we have to do it ourselves.
992 if (dp->d_fileno == 0)
994 #endif /* sun && d_ino */
996 /* Skip the '.' and '..' entries by checking
997 * for them specifically instead of assuming
998 * readdir() reuturns them in that order when
999 * first going through a directory. This is
1000 * needed for XFS over NFS filesystems since
1001 * SGI does not guarantee that these are the
1002 * first two entries returned from readdir().
1004 if (ISDOT(dp->d_name) || ISDOTDOT(dp->d_name))
1007 Hash_CreateEntry(&d->files, dp->d_name, (Boolean *)NULL);
1012 /* Add it to the path */
1014 pe = emalloc(sizeof(*pe));
1016 TAILQ_INSERT_TAIL(path, pe, link);
1019 /* Add to list of all directories */
1020 TAILQ_INSERT_TAIL(&openDirectories, d, link);
1022 DEBUGF(DIR, ("done\n"));
1029 * Duplicate a path. Ups the reference count for the directories.
1032 Path_Duplicate(struct Path *dst, const struct Path *src)
1034 struct PathElement *ped, *pes;
1036 TAILQ_FOREACH(pes, src, link) {
1037 ped = emalloc(sizeof(*ped));
1038 ped->dir = pes->dir;
1039 ped->dir->refCount++;
1040 TAILQ_INSERT_TAIL(dst, ped, link);
1046 * Make a string by taking all the directories in the given search
1047 * path and preceding them by the given flag. Used by the suffix
1048 * module to create variables for compilers based on suffix search
1052 * The string mentioned above. Note that there is no space between
1053 * the given flag and each directory. The empty string is returned if
1054 * Things don't go well.
1057 Path_MakeFlags(const char *flag, const struct Path *path)
1059 char *str; /* the string which will be returned */
1060 char *tstr; /* the current directory preceded by 'flag' */
1062 const struct PathElement *pe;
1066 TAILQ_FOREACH(pe, path, link) {
1067 tstr = str_concat(flag, pe->dir->name, 0);
1068 nstr = str_concat(str, tstr, STR_ADDSPACE);
1080 * Destroy a path. This decrements the reference counts of all
1081 * directories of this path and, if a reference count goes 0,
1082 * destroys the directory object.
1085 Path_Clear(struct Path *path)
1087 struct PathElement *pe;
1089 while ((pe = TAILQ_FIRST(path)) != NULL) {
1090 pe->dir->refCount--;
1091 TAILQ_REMOVE(path, pe, link);
1092 if (pe->dir->refCount == 0) {
1093 TAILQ_REMOVE(&openDirectories, pe->dir, link);
1094 Hash_DeleteTable(&pe->dir->files);
1095 free(pe->dir->name);
1105 * Concatenate two paths, adding the second to the end of the first.
1106 * Make sure to avoid duplicates.
1109 * Reference counts for added dirs are upped.
1112 Path_Concat(struct Path *path1, const struct Path *path2)
1114 struct PathElement *p1, *p2;
1116 TAILQ_FOREACH(p2, path2, link) {
1117 TAILQ_FOREACH(p1, path1, link) {
1118 if (p1->dir == p2->dir)
1122 p1 = emalloc(sizeof(*p1));
1124 p1->dir->refCount++;
1125 TAILQ_INSERT_TAIL(path1, p1, link);
1130 /********** DEBUG INFO **********/
1132 Dir_PrintDirectories(void)
1136 printf("#*** Directory Cache:\n");
1137 printf("# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
1138 hits, misses, nearmisses, bigmisses,
1139 (hits + bigmisses + nearmisses ?
1140 hits * 100 / (hits + bigmisses + nearmisses) : 0));
1141 printf("# %-20s referenced\thits\n", "directory");
1142 TAILQ_FOREACH(d, &openDirectories, link)
1143 printf("# %-20s %10d\t%4d\n", d->name, d->refCount, d->hits);
1147 Path_Print(const struct Path *path)
1149 const struct PathElement *p;
1151 TAILQ_FOREACH(p, path, link)
1152 printf("%s ", p->dir->name);