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.44 2005/11/05 15:35:10 swildner 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
;
195 /* the list of all open directories */
196 static TAILQ_HEAD(, Dir
) openDirectories
;
199 * Variables for gathering statistics on the efficiency of the hashing
202 static int hits
; /* Found in directory cache */
203 static int misses
; /* Sad, but not evil misses */
204 static int nearmisses
; /* Found under search path */
205 static int bigmisses
; /* Sought by itself */
207 static Dir
*dot
; /* contents of current directory */
209 /* Results of doing a last-resort stat in Path_FindFile --
210 * if we have to go to the system to find the file, we might as well
211 * have its mtime on record.
212 * XXX: If this is done way early, there's a chance other rules will
213 * have already updated the file, in which case we'll update it again.
214 * Generally, there won't be two rules to update a single file, so this
215 * should be ok, but...
217 static Hash_Table mtimes
;
220 * initialize things for this module
221 * add the "." directory
222 * add curdir if it is not the same as objdir
228 Hash_InitTable(&mtimes
, 0);
229 TAILQ_INIT(&dirSearchPath
);
230 TAILQ_INIT(&openDirectories
);
234 * add the "." directory
235 * add curdir if it is not the same as objdir
238 Dir_CurObj(const char curdir
[], const char objdir
[])
241 dot
= Path_AddDir(NULL
, ".");
243 err(1, "cannot open current directory");
246 * We always need to have dot around, so we increment its
247 * reference count to make sure it's not destroyed.
251 if (strcmp(objdir
, curdir
) != 0)
252 Path_AddDir(&dirSearchPath
, curdir
);
256 *-----------------------------------------------------------------------
257 * Dir_HasWildcards --
258 * See if the given name has any wildcard characters in it.
261 * returns true if the word should be expanded, false otherwise
265 *-----------------------------------------------------------------------
268 Dir_HasWildcards(const char *name
)
271 int wild
= 0, brace
= 0, bracket
= 0;
273 for (cp
= name
; *cp
; cp
++) {
297 return (wild
&& bracket
== 0 && brace
== 0);
301 *-----------------------------------------------------------------------
303 * Given a pattern and a Dir structure, see if any files
304 * match the pattern and add their names to the 'expansions' list if
305 * any do. This is incomplete -- it doesn't take care of patterns like
306 * src / *src / *.c properly (just *.c on any of the directories), but it
313 * File names are added to the expansions lst. The directory will be
314 * fully hashed when this is done.
315 *-----------------------------------------------------------------------
318 DirMatchFiles(const char *pattern
, const Dir
*p
, Lst
*expansions
)
320 Hash_Search search
; /* Index into the directory's table */
321 Hash_Entry
*entry
; /* Current entry in the table */
322 bool isDot
; /* true if the directory being searched is . */
324 isDot
= (*p
->name
== '.' && p
->name
[1] == '\0');
326 for (entry
= Hash_EnumFirst(&p
->files
, &search
);
328 entry
= Hash_EnumNext(&search
)) {
330 * See if the file matches the given pattern. Note we follow
331 * the UNIX convention that dot files will only be found if
332 * the pattern begins with a dot (note also that as a side
333 * effect of the hashing scheme, .* won't match . or ..
334 * since they aren't hashed).
336 if (Str_Match(entry
->name
, pattern
) &&
337 ((entry
->name
[0] != '.') ||
338 (pattern
[0] == '.'))) {
339 Lst_AtEnd(expansions
, (isDot
? estrdup(entry
->name
) :
340 str_concat(p
->name
, '/', entry
->name
)));
347 *-----------------------------------------------------------------------
349 * Expand curly braces like the C shell. Does this recursively.
350 * Note the special case: if after the piece of the curly brace is
351 * done there are no wildcard characters in the result, the result is
352 * placed on the list WITHOUT CHECKING FOR ITS EXISTENCE. The
353 * given arguments are the entire word to expand, the first curly
354 * brace in the word, the search path, and the list to store the
361 * The given list is filled with the expansions...
363 *-----------------------------------------------------------------------
366 DirExpandCurly(const char *word
, const char *brace
, struct Path
*path
,
369 const char *end
; /* Character after the closing brace */
370 const char *cp
; /* Current position in brace clause */
371 const char *start
; /* Start of current piece of brace clause */
372 int bracelevel
; /* Number of braces we've seen. If we see a right brace
373 * when this is 0, we've hit the end of the clause. */
374 char *file
; /* Current expansion */
375 int otherLen
; /* The length of the other pieces of the expansion
376 * (chars before and after the clause in 'word') */
377 char *cp2
; /* Pointer for checking for wildcards in
378 * expansion before calling Dir_Expand */
383 * Find the end of the brace clause first, being wary of nested brace
386 for (end
= start
, bracelevel
= 0; *end
!= '\0'; end
++) {
389 else if ((*end
== '}') && (bracelevel
-- == 0))
393 Error("Unterminated {} clause \"%s\"", start
);
398 otherLen
= brace
- word
+ strlen(end
);
400 for (cp
= start
; cp
< end
; cp
++) {
402 * Find the end of this piece of the clause.
408 else if ((*cp
== '}') && (bracelevel
-- <= 0))
413 * Allocate room for the combination and install the
416 file
= emalloc(otherLen
+ cp
- start
+ 1);
418 strncpy(file
, word
, brace
- word
);
420 strncpy(&file
[brace
- word
], start
, cp
- start
);
421 strcpy(&file
[(brace
- word
) + (cp
- start
)], end
);
424 * See if the result has any wildcards in it. If we find one,
425 * call Dir_Expand right away, telling it to place the result
426 * on our list of expansions.
428 for (cp2
= file
; *cp2
!= '\0'; cp2
++) {
434 Path_Expand(file
, path
, expansions
);
442 * Hit the end w/o finding any wildcards, so stick
443 * the expansion on the end of the list.
445 Lst_AtEnd(expansions
, file
);
455 *-----------------------------------------------------------------------
457 * Internal expand routine. Passes through the directories in the
458 * path one by one, calling DirMatchFiles for each. NOTE: This still
459 * doesn't handle patterns in directories... Works given a word to
460 * expand, a path to look in, and a list to store expansions in.
466 * Things are added to the expansions list.
468 *-----------------------------------------------------------------------
471 DirExpandInt(const char *word
, const struct Path
*path
, Lst
*expansions
)
473 struct PathElement
*pe
;
475 TAILQ_FOREACH(pe
, path
, link
)
476 DirMatchFiles(word
, pe
->dir
, expansions
);
480 *-----------------------------------------------------------------------
482 * Expand the given word into a list of words by globbing it looking
483 * in the directories on the given search path.
486 * A list of words consisting of the files which exist along the search
487 * path matching the given pattern is placed in expansions.
490 * Directories may be opened. Who knows?
491 *-----------------------------------------------------------------------
494 Path_Expand(char *word
, struct Path
*path
, Lst
*expansions
)
499 DEBUGF(DIR, ("expanding \"%s\"...", word
));
501 cp
= strchr(word
, '{');
503 DirExpandCurly(word
, cp
, path
, expansions
);
505 cp
= strchr(word
, '/');
508 * The thing has a directory component -- find the
509 * first wildcard in the string.
511 for (cp
= word
; *cp
!= '\0'; cp
++) {
512 if (*cp
== '?' || *cp
== '[' ||
513 *cp
== '*' || *cp
== '{') {
519 * This one will be fun.
521 DirExpandCurly(word
, cp
, path
, expansions
);
523 } else if (*cp
!= '\0') {
525 * Back up to the start of the component
529 while (cp
> word
&& *cp
!= '/')
535 * If the glob isn't in the first
536 * component, try and find all the
537 * components up to the one with a
542 dirpath
= Path_FindFile(word
, path
);
545 * dirpath is null if can't find the
547 * XXX: Path_FindFile won't find internal
548 * components. i.e. if the path contains
549 * ../Etc/Object and we're looking for
550 * Etc, * it won't be found. Ah well.
551 * Probably not important.
553 if (dirpath
!= NULL
) {
555 &dirpath
[strlen(dirpath
)
558 TAILQ_HEAD_INITIALIZER(tp
);
562 Path_AddDir(&tp
, dirpath
);
563 DirExpandInt(cp
+ 1, &tp
,
569 * Start the search from the local
572 DirExpandInt(word
, path
, expansions
);
576 * Return the file -- this should never happen.
578 DirExpandInt(word
, path
, expansions
);
582 * First the files in dot
584 DirMatchFiles(word
, dot
, expansions
);
587 * Then the files in every other directory on the path.
589 DirExpandInt(word
, path
, expansions
);
593 LST_FOREACH(ln
, expansions
)
594 DEBUGF(DIR, ("%s ", (const char *)Lst_Datum(ln
)));
601 * Find the file with the given name along the given search path.
604 * The path to the file or NULL. This path is guaranteed to be in a
605 * different part of memory than name and so may be safely free'd.
608 * If the file is found in a directory which is not on the path
609 * already (either 'name' is absolute or it is a relative path
610 * [ dir1/.../dirn/file ] which exists below one of the directories
611 * already on the search path), its directory is added to the end
612 * of the path on the assumption that there will be more files in
613 * that directory later on. Sometimes this is true. Sometimes not.
616 Path_FindFile(char *name
, struct Path
*path
)
618 char *p1
; /* pointer into p->name */
619 char *p2
; /* pointer into name */
620 char *file
; /* the current filename to check */
621 const struct PathElement
*pe
; /* current path member */
622 char *cp
; /* final component of the name */
623 bool hasSlash
; /* true if 'name' contains a / */
624 struct stat stb
; /* Buffer for stat, if necessary */
625 Hash_Entry
*entry
; /* Entry for mtimes table */
628 * Find the final component of the name and note whether it has a
629 * slash in it (the name, I mean)
631 cp
= strrchr(name
, '/');
640 DEBUGF(DIR, ("Searching for %s...", name
));
642 * No matter what, we always look for the file in the current directory
643 * before anywhere else and we *do not* add the ./ to it if it exists.
644 * This is so there are no conflicts between what the user specifies
645 * (fish.c) and what pmake finds (./fish.c).
647 if ((!hasSlash
|| (cp
- name
== 2 && *name
== '.')) &&
648 (Hash_FindEntry(&dot
->files
, cp
) != NULL
)) {
649 DEBUGF(DIR, ("in '.'\n"));
652 return (estrdup(name
));
656 * We look through all the directories on the path seeking one which
657 * contains the final component of the given name and whose final
658 * component(s) match the name's initial component(s). If such a beast
659 * is found, we concatenate the directory name and the final component
660 * and return the resulting string. If we don't find any such thing,
661 * we go on to phase two...
663 TAILQ_FOREACH(pe
, path
, link
) {
664 DEBUGF(DIR, ("%s...", pe
->dir
->name
));
665 if (Hash_FindEntry(&pe
->dir
->files
, cp
) != NULL
) {
666 DEBUGF(DIR, ("here..."));
669 * If the name had a slash, its initial
670 * components and p's final components must
671 * match. This is false if a mismatch is
672 * encountered before all of the initial
673 * components have been checked (p2 > name at
674 * the end of the loop), or we matched only
675 * part of one of the components of p
676 * along with all the rest of them (*p1 != '/').
678 p1
= pe
->dir
->name
+ strlen(pe
->dir
->name
) - 1;
680 while (p2
>= name
&& p1
>= pe
->dir
->name
&&
684 if (p2
>= name
|| (p1
>= pe
->dir
->name
&&
686 DEBUGF(DIR, ("component mismatch -- "
691 file
= str_concat(pe
->dir
->name
, '/', cp
);
692 DEBUGF(DIR, ("returning %s\n", file
));
696 } else if (hasSlash
) {
698 * If the file has a leading path component and that
699 * component exactly matches the entire name of the
700 * current search directory, we assume the file
701 * doesn't exist and return NULL.
703 for (p1
= pe
->dir
->name
, p2
= name
; *p1
&& *p1
== *p2
;
706 if (*p1
== '\0' && p2
== cp
- 1) {
707 if (*cp
== '\0' || ISDOT(cp
) || ISDOTDOT(cp
)) {
708 DEBUGF(DIR, ("returning %s\n", name
));
709 return (estrdup(name
));
711 DEBUGF(DIR, ("must be here but isn't --"
712 " returning NULL\n"));
720 * We didn't find the file on any existing members of the directory.
721 * If the name doesn't contain a slash, that means it doesn't exist.
722 * If it *does* contain a slash, however, there is still hope: it
723 * could be in a subdirectory of one of the members of the search
724 * path. (eg. /usr/include and sys/types.h. The above search would
725 * fail to turn up types.h in /usr/include, but it *is* in
726 * /usr/include/sys/types.h) If we find such a beast, we assume there
727 * will be more (what else can we assume?) and add all but the last
728 * component of the resulting name onto the search path (at the
729 * end). This phase is only performed if the file is *not* absolute.
732 DEBUGF(DIR, ("failed.\n"));
738 bool checkedDot
= false;
740 DEBUGF(DIR, ("failed. Trying subdirectories..."));
741 TAILQ_FOREACH(pe
, path
, link
) {
742 if (pe
->dir
!= dot
) {
743 file
= str_concat(pe
->dir
->name
, '/', name
);
746 * Checking in dot -- DON'T put a leading ./
749 file
= estrdup(name
);
752 DEBUGF(DIR, ("checking %s...", file
));
754 if (stat(file
, &stb
) == 0) {
755 DEBUGF(DIR, ("got it.\n"));
758 * We've found another directory to search. We
759 * know there's a slash in 'file' because we put
760 * one there. We nuke it after finding it and
761 * call Path_AddDir to add this new directory
762 * onto the existing search path. Once that's
763 * done, we restore the slash and triumphantly
764 * return the file name, knowing that should a
765 * file in this directory every be referenced
766 * again in such a manner, we will find it
767 * without having to do numerous numbers of
768 * access calls. Hurrah!
770 cp
= strrchr(file
, '/');
772 Path_AddDir(path
, file
);
776 * Save the modification time so if
777 * it's needed, we don't have to fetch it again.
779 DEBUGF(DIR, ("Caching %s for %s\n",
780 Targ_FmtTime(stb
.st_mtime
), file
));
781 entry
= Hash_CreateEntry(&mtimes
, file
, NULL
);
783 (void *)(long)stb
.st_mtime
);
791 DEBUGF(DIR, ("failed. "));
795 * Already checked by the given name, since . was in
796 * the path, so no point in proceeding...
798 DEBUGF(DIR, ("Checked . already, returning NULL\n"));
804 * Didn't find it that way, either. Sigh. Phase 3. Add its directory
805 * onto the search path in any case, just in case, then look for the
806 * thing in the hash table. If we find it, grand. We return a new
807 * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
808 * Note that if the directory holding the file doesn't exist, this will
809 * do an extra search of the final directory on the path. Unless
810 * something weird happens, this search won't succeed and life will
813 * Sigh. We cannot add the directory onto the search path because
814 * of this amusing case:
815 * $(INSTALLDIR)/$(FILE): $(FILE)
817 * $(FILE) exists in $(INSTALLDIR) but not in the current one.
818 * When searching for $(FILE), we will find it in $(INSTALLDIR)
819 * b/c we added it here. This is not good...
823 Path_AddDir(path
, name
);
827 pe
= TAILQ_LAST(path
, Path
);
831 if (Hash_FindEntry(&pe
->dir
->files
, cp
) != NULL
) {
832 return (estrdup(name
));
836 DEBUGF(DIR, ("Looking for \"%s\"...", name
));
839 entry
= Hash_FindEntry(&mtimes
, name
);
841 DEBUGF(DIR, ("got it (in mtime cache)\n"));
842 return (estrdup(name
));
843 } else if (stat(name
, &stb
) == 0) {
844 entry
= Hash_CreateEntry(&mtimes
, name
, NULL
);
845 DEBUGF(DIR, ("Caching %s for %s\n",
846 Targ_FmtTime(stb
.st_mtime
), name
));
847 Hash_SetValue(entry
, (void *)(long)stb
.st_mtime
);
848 return (estrdup(name
));
850 DEBUGF(DIR, ("failed. Returning NULL\n"));
857 *-----------------------------------------------------------------------
859 * Find the modification time of the file described by gn along the
860 * search path dirSearchPath.
863 * The modification time or 0 if it doesn't exist
866 * The modification time is placed in the node's mtime slot.
867 * If the node didn't have a path entry before, and Dir_FindFile
868 * found one for it, the full name is placed in the path slot.
869 *-----------------------------------------------------------------------
874 char *fullName
; /* the full pathname of name */
875 struct stat stb
; /* buffer for finding the mod time */
878 if (gn
->type
& OP_ARCHV
)
879 return (Arch_MTime(gn
));
881 else if (gn
->path
== NULL
)
882 fullName
= Path_FindFile(gn
->name
, &dirSearchPath
);
886 if (fullName
== NULL
)
887 fullName
= estrdup(gn
->name
);
889 entry
= Hash_FindEntry(&mtimes
, fullName
);
892 * Only do this once -- the second time folks are checking to
893 * see if the file was actually updated, so we need to
894 * actually go to the filesystem.
896 DEBUGF(DIR, ("Using cached time %s for %s\n",
897 Targ_FmtTime((time_t)(long)Hash_GetValue(entry
)),
899 stb
.st_mtime
= (time_t)(long)Hash_GetValue(entry
);
900 Hash_DeleteEntry(&mtimes
, entry
);
901 } else if (stat(fullName
, &stb
) < 0) {
902 if (gn
->type
& OP_MEMBER
) {
903 if (fullName
!= gn
->path
)
905 return (Arch_MemMTime(gn
));
910 if (fullName
&& gn
->path
== NULL
)
913 gn
->mtime
= stb
.st_mtime
;
918 *-----------------------------------------------------------------------
920 * Add the given name to the end of the given path.
926 * A structure is added to the list and the directory is
928 *-----------------------------------------------------------------------
931 Path_AddDir(struct Path
*path
, const char *name
)
933 Dir
*d
; /* pointer to new Path structure */
934 DIR *dir
; /* for reading directory */
935 struct PathElement
*pe
;
936 struct dirent
*dp
; /* entry in directory */
938 /* check whether we know this directory */
939 TAILQ_FOREACH(d
, &openDirectories
, link
) {
940 if (strcmp(d
->name
, name
) == 0) {
945 /* Check whether its already on the path. */
946 TAILQ_FOREACH(pe
, path
, link
) {
950 /* Add it to the path */
952 pe
= emalloc(sizeof(*pe
));
954 TAILQ_INSERT_TAIL(path
, pe
, link
);
959 DEBUGF(DIR, ("Caching %s...", name
));
961 if ((dir
= opendir(name
)) == NULL
) {
962 DEBUGF(DIR, (" cannot open\n"));
966 d
= emalloc(sizeof(*d
));
967 d
->name
= estrdup(name
);
970 Hash_InitTable(&d
->files
, -1);
972 while ((dp
= readdir(dir
)) != NULL
) {
973 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
975 * The sun directory library doesn't check for
976 * a 0 inode (0-inode slots just take up space),
977 * so we have to do it ourselves.
979 if (dp
->d_fileno
== 0)
981 #endif /* sun && d_ino */
983 /* Skip the '.' and '..' entries by checking
984 * for them specifically instead of assuming
985 * readdir() reuturns them in that order when
986 * first going through a directory. This is
987 * needed for XFS over NFS filesystems since
988 * SGI does not guarantee that these are the
989 * first two entries returned from readdir().
991 if (ISDOT(dp
->d_name
) || ISDOTDOT(dp
->d_name
))
994 Hash_CreateEntry(&d
->files
, dp
->d_name
, NULL
);
999 /* Add it to the path */
1001 pe
= emalloc(sizeof(*pe
));
1003 TAILQ_INSERT_TAIL(path
, pe
, link
);
1006 /* Add to list of all directories */
1007 TAILQ_INSERT_TAIL(&openDirectories
, d
, link
);
1009 DEBUGF(DIR, ("done\n"));
1016 * Duplicate a path. Ups the reference count for the directories.
1019 Path_Duplicate(struct Path
*dst
, const struct Path
*src
)
1021 struct PathElement
*ped
, *pes
;
1023 TAILQ_FOREACH(pes
, src
, link
) {
1024 ped
= emalloc(sizeof(*ped
));
1025 ped
->dir
= pes
->dir
;
1026 ped
->dir
->refCount
++;
1027 TAILQ_INSERT_TAIL(dst
, ped
, link
);
1033 * Make a string by taking all the directories in the given search
1034 * path and preceding them by the given flag. Used by the suffix
1035 * module to create variables for compilers based on suffix search
1039 * The string mentioned above. Note that there is no space between
1040 * the given flag and each directory. The empty string is returned if
1041 * Things don't go well.
1044 Path_MakeFlags(const char *flag
, const struct Path
*path
)
1046 char *str
; /* the string which will be returned */
1047 char *tstr
; /* the current directory preceded by 'flag' */
1049 const struct PathElement
*pe
;
1053 TAILQ_FOREACH(pe
, path
, link
) {
1054 tstr
= str_concat(flag
, '\0', pe
->dir
->name
);
1055 nstr
= str_concat(str
, ' ', tstr
);
1067 * Destroy a path. This decrements the reference counts of all
1068 * directories of this path and, if a reference count goes 0,
1069 * destroys the directory object.
1072 Path_Clear(struct Path
*path
)
1074 struct PathElement
*pe
;
1076 while ((pe
= TAILQ_FIRST(path
)) != NULL
) {
1077 pe
->dir
->refCount
--;
1078 TAILQ_REMOVE(path
, pe
, link
);
1079 if (pe
->dir
->refCount
== 0) {
1080 TAILQ_REMOVE(&openDirectories
, pe
->dir
, link
);
1081 Hash_DeleteTable(&pe
->dir
->files
);
1082 free(pe
->dir
->name
);
1092 * Concatenate two paths, adding the second to the end of the first.
1093 * Make sure to avoid duplicates.
1096 * Reference counts for added dirs are upped.
1099 Path_Concat(struct Path
*path1
, const struct Path
*path2
)
1101 struct PathElement
*p1
, *p2
;
1103 TAILQ_FOREACH(p2
, path2
, link
) {
1104 TAILQ_FOREACH(p1
, path1
, link
) {
1105 if (p1
->dir
== p2
->dir
)
1109 p1
= emalloc(sizeof(*p1
));
1111 p1
->dir
->refCount
++;
1112 TAILQ_INSERT_TAIL(path1
, p1
, link
);
1117 /********** DEBUG INFO **********/
1119 Dir_PrintDirectories(void)
1123 printf("#*** Directory Cache:\n");
1124 printf("# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
1125 hits
, misses
, nearmisses
, bigmisses
,
1126 (hits
+ bigmisses
+ nearmisses
?
1127 hits
* 100 / (hits
+ bigmisses
+ nearmisses
) : 0));
1128 printf("# %-20s referenced\thits\n", "directory");
1129 TAILQ_FOREACH(d
, &openDirectories
, link
)
1130 printf("# %-20s %10d\t%4d\n", d
->name
, d
->refCount
, d
->hits
);
1134 Path_Print(const struct Path
*path
)
1136 const struct PathElement
*p
;
1138 TAILQ_FOREACH(p
, path
, link
)
1139 printf("%s ", p
->dir
->name
);