Home | History | Annotate | Line # | Download | only in make
dir.c revision 1.206
      1 /*	$NetBSD: dir.c,v 1.206 2020/11/14 11:22:17 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Adam de Boor.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     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.
     21  *
     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
     32  * SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Copyright (c) 1988, 1989 by Adam de Boor
     37  * Copyright (c) 1989 by Berkeley Softworks
     38  * All rights reserved.
     39  *
     40  * This code is derived from software contributed to Berkeley by
     41  * Adam de Boor.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     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.
     58  *
     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
     69  * SUCH DAMAGE.
     70  */
     71 
     72 /* Directory searching using wildcards and/or normal names.
     73  * Used both for source wildcarding in the makefile and for finding
     74  * implicit sources.
     75  *
     76  * The interface for this module is:
     77  *	Dir_Init	Initialize the module.
     78  *
     79  *	Dir_InitCur	Set the cur CachedDir.
     80  *
     81  *	Dir_InitDot	Set the dot CachedDir.
     82  *
     83  *	Dir_End		Clean up the module.
     84  *
     85  *	Dir_SetPATH	Set ${.PATH} to reflect state of dirSearchPath.
     86  *
     87  *	Dir_HasWildcards
     88  *			Returns TRUE if the name given it needs to
     89  *			be wildcard-expanded.
     90  *
     91  *	Dir_Expand	Given a pattern and a path, return a Lst of names
     92  *			which match the pattern on the search path.
     93  *
     94  *	Dir_FindFile	Searches for a file on a given search path.
     95  *			If it exists, the entire path is returned.
     96  *			Otherwise NULL is returned.
     97  *
     98  *	Dir_FindHereOrAbove
     99  *			Search for a path in the current directory and
    100  *			then all the directories above it in turn until
    101  *			the path is found or we reach the root ("/").
    102  *
    103  *	Dir_UpdateMTime
    104  *			Update the modification time and path of a node with
    105  *			data from the file corresponding to the node.
    106  *
    107  *	Dir_AddDir	Add a directory to a search path.
    108  *
    109  *	Dir_MakeFlags	Given a search path and a command flag, create
    110  *			a string with each of the directories in the path
    111  *			preceded by the command flag and all of them
    112  *			separated by a space.
    113  *
    114  *	Dir_Destroy	Destroy an element of a search path. Frees up all
    115  *			things that can be freed for the element as long
    116  *			as the element is no longer referenced by any other
    117  *			search path.
    118  *
    119  *	Dir_ClearPath	Resets a search path to the empty list.
    120  *
    121  * For debugging:
    122  *	Dir_PrintDirectories
    123  *			Print stats about the directory cache.
    124  */
    125 
    126 #include <sys/types.h>
    127 #include <sys/stat.h>
    128 
    129 #include <dirent.h>
    130 #include <errno.h>
    131 
    132 #include "make.h"
    133 #include "dir.h"
    134 #include "job.h"
    135 
    136 /*	"@(#)dir.c	8.2 (Berkeley) 1/2/94"	*/
    137 MAKE_RCSID("$NetBSD: dir.c,v 1.206 2020/11/14 11:22:17 rillig Exp $");
    138 
    139 #define DIR_DEBUG0(text) DEBUG0(DIR, text)
    140 #define DIR_DEBUG1(fmt, arg1) DEBUG1(DIR, fmt, arg1)
    141 #define DIR_DEBUG2(fmt, arg1, arg2) DEBUG2(DIR, fmt, arg1, arg2)
    142 
    143 /* A search path is a list of CachedDir structures. A CachedDir has in it the
    144  * name of the directory and the names of all the files in the directory.
    145  * This is used to cut down on the number of system calls necessary to find
    146  * implicit dependents and their like. Since these searches are made before
    147  * any actions are taken, we need not worry about the directory changing due
    148  * to creation commands. If this hampers the style of some makefiles, they
    149  * must be changed.
    150  *
    151  * All previously-read directories are kept in openDirs, which is checked
    152  * first before a directory is opened.
    153  *
    154  * The need for the caching of whole directories is brought about by the
    155  * multi-level transformation code in suff.c, which tends to search for far
    156  * more files than regular make does. In the initial implementation, the
    157  * amount of time spent performing "stat" calls was truly astronomical.
    158  * The problem with caching at the start is, of course, that pmake doesn't
    159  * then detect changes to these directories during the course of the make.
    160  * Three possibilities suggest themselves:
    161  *
    162  * 1)	just use stat to test for a file's existence. As mentioned above,
    163  *	this is very inefficient due to the number of checks engendered by
    164  *	the multi-level transformation code.
    165  *
    166  * 2)	use readdir() and company to search the directories, keeping them
    167  *	open between checks. I have tried this and while it didn't slow down
    168  *	the process too much, it could severely affect the amount of
    169  *	parallelism available as each directory open would take another file
    170  *	descriptor out of play for handling I/O for another job. Given that
    171  *	it is only recently (as of 1993 or earlier) that UNIX OS's have taken
    172  *	to allowing more than 20 or 32 file descriptors for a process, this
    173  *	doesn't seem acceptable to me.
    174  *
    175  * 3)	record the mtime of the directory in the CachedDir structure and
    176  *	verify the directory hasn't changed since the contents were cached.
    177  *	This will catch the creation or deletion of files, but not the
    178  *	updating of files. However, since it is the creation and deletion
    179  *	that is the problem, this could be a good thing to do. Unfortunately,
    180  *	if the directory (say ".") were fairly large and changed fairly
    181  *	frequently, the constant reloading could seriously degrade
    182  *	performance. It might be good in such cases to keep track of the
    183  *	number of reloadings and if the number goes over a (small) limit,
    184  *	resort to using stat in its place.
    185  *
    186  * An additional thing to consider is that pmake is used primarily to create
    187  * C programs and until recently (as of 1993 or earlier) pcc-based compilers
    188  * refused to allow you to specify where the resulting object file should be
    189  * placed. This forced all objects to be created in the current directory.
    190  * This isn't meant as a full excuse, just an explanation of some of the
    191  * reasons for the caching used here.
    192  *
    193  * One more note: the location of a target's file is only performed on the
    194  * downward traversal of the graph and then only for terminal nodes in the
    195  * graph. This could be construed as wrong in some cases, but prevents
    196  * inadvertent modification of files when the "installed" directory for a
    197  * file is provided in the search path.
    198  *
    199  * Another data structure maintained by this module is an mtime cache used
    200  * when the searching of cached directories fails to find a file. In the past,
    201  * Dir_FindFile would simply perform an access() call in such a case to
    202  * determine if the file could be found using just the name given. When this
    203  * hit, however, all that was gained was the knowledge that the file existed.
    204  * Given that an access() is essentially a stat() without the copyout() call,
    205  * and that the same filesystem overhead would have to be incurred in
    206  * Dir_MTime, it made sense to replace the access() with a stat() and record
    207  * the mtime in a cache for when Dir_UpdateMTime was actually called.
    208  */
    209 
    210 typedef List CachedDirList;
    211 typedef ListNode CachedDirListNode;
    212 
    213 typedef ListNode SearchPathNode;
    214 
    215 SearchPath *dirSearchPath;		/* main search path */
    216 
    217 /* A list of cached directories, with fast lookup by directory name. */
    218 typedef struct OpenDirs {
    219     CachedDirList *list;
    220     HashTable /* of CachedDirListNode */ table;
    221 } OpenDirs;
    222 
    223 static void
    224 OpenDirs_Init(OpenDirs *odirs)
    225 {
    226     odirs->list = Lst_New();
    227     HashTable_Init(&odirs->table);
    228 }
    229 
    230 #ifdef CLEANUP
    231 static void
    232 OpenDirs_Done(OpenDirs *odirs)
    233 {
    234     CachedDirListNode *ln = odirs->list->first;
    235     while (ln != NULL) {
    236 	CachedDirListNode *next = ln->next;
    237 	CachedDir *dir = ln->datum;
    238 	Dir_Destroy(dir);	/* removes the dir from odirs->list */
    239 	ln = next;
    240     }
    241     Lst_Free(odirs->list);
    242     HashTable_Done(&odirs->table);
    243 }
    244 #endif
    245 
    246 static CachedDir *
    247 OpenDirs_Find(OpenDirs *odirs, const char *name)
    248 {
    249     CachedDirListNode *ln = HashTable_FindValue(&odirs->table, name);
    250     return ln != NULL ? ln->datum : NULL;
    251 }
    252 
    253 static void
    254 OpenDirs_Add(OpenDirs *odirs, CachedDir *cdir)
    255 {
    256     HashEntry *he = HashTable_FindEntry(&odirs->table, cdir->name);
    257     if (he != NULL)
    258 	return;
    259     he = HashTable_CreateEntry(&odirs->table, cdir->name, NULL);
    260     Lst_Append(odirs->list, cdir);
    261     HashEntry_Set(he, odirs->list->last);
    262 }
    263 
    264 static void
    265 OpenDirs_Remove(OpenDirs *odirs, const char *name)
    266 {
    267     HashEntry *he = HashTable_FindEntry(&odirs->table, name);
    268     CachedDirListNode *ln;
    269     if (he == NULL)
    270 	return;
    271     ln = HashEntry_Get(he);
    272     HashTable_DeleteEntry(&odirs->table, he);
    273     Lst_Remove(odirs->list, ln);
    274 }
    275 
    276 static OpenDirs openDirs;	/* all cached directories */
    277 
    278 /*
    279  * Variables for gathering statistics on the efficiency of the caching
    280  * mechanism.
    281  */
    282 static int hits;		/* Found in directory cache */
    283 static int misses;		/* Sad, but not evil misses */
    284 static int nearmisses;		/* Found under search path */
    285 static int bigmisses;		/* Sought by itself */
    286 
    287 static CachedDir *dot;		/* contents of current directory */
    288 static CachedDir *cur;		/* contents of current directory, if not dot */
    289 static CachedDir *dotLast;	/* a fake path entry indicating we need to
    290 				 * look for . last */
    291 
    292 /* Results of doing a last-resort stat in Dir_FindFile -- if we have to go to
    293  * the system to find the file, we might as well have its mtime on record.
    294  *
    295  * XXX: If this is done way early, there's a chance other rules will have
    296  * already updated the file, in which case we'll update it again. Generally,
    297  * there won't be two rules to update a single file, so this should be ok,
    298  * but... */
    299 static HashTable mtimes;
    300 
    301 static HashTable lmtimes;	/* same as mtimes but for lstat */
    302 
    303 /*
    304  * We use stat(2) a lot, cache the results.
    305  * mtime and mode are all we care about.
    306  */
    307 struct cache_st {
    308     time_t lmtime;		/* lstat; XXX: is probably redundant */
    309     time_t mtime;		/* stat */
    310     mode_t mode;
    311 };
    312 
    313 typedef enum CachedStatsFlags {
    314     CST_NONE	= 0,
    315     CST_LSTAT	= 1 << 0,	/* call lstat(2) instead of stat(2) */
    316     CST_UPDATE	= 1 << 1	/* ignore existing cached entry */
    317 } CachedStatsFlags;
    318 
    319 /* Returns 0 and the result of stat(2) or lstat(2) in *mst, or -1 on error. */
    320 static int
    321 cached_stats(HashTable *tbl, const char *pathname, struct make_stat *mst,
    322 	     CachedStatsFlags flags)
    323 {
    324     HashEntry *entry;
    325     struct stat sys_st;
    326     struct cache_st *cst;
    327     int rc;
    328 
    329     if (pathname == NULL || pathname[0] == '\0')
    330 	return -1;		/* This can happen in meta mode. */
    331 
    332     entry = HashTable_FindEntry(tbl, pathname);
    333 
    334     if (entry != NULL && !(flags & CST_UPDATE)) {
    335 	cst = HashEntry_Get(entry);
    336 
    337 	mst->mst_mode = cst->mode;
    338 	mst->mst_mtime = (flags & CST_LSTAT) ? cst->lmtime : cst->mtime;
    339 	/* XXX: Checking for mst_mtime != 0 is probably redundant since
    340 	 * nonexistent files are not cached. */
    341 	if (mst->mst_mtime != 0) {
    342 	    DIR_DEBUG2("Using cached time %s for %s\n",
    343 		       Targ_FmtTime(mst->mst_mtime), pathname);
    344 	    return 0;
    345 	}
    346 	/* Continue with the normal lookup to see whether the file has been
    347 	 * created in the meantime. */
    348     }
    349 
    350     rc = (flags & CST_LSTAT)
    351 	 ? lstat(pathname, &sys_st)
    352 	 : stat(pathname, &sys_st);
    353     if (rc == -1)
    354 	return -1;
    355 
    356     if (sys_st.st_mtime == 0)
    357 	sys_st.st_mtime = 1;	/* avoid confusion with missing file */
    358 
    359     mst->mst_mode = sys_st.st_mode;
    360     mst->mst_mtime = sys_st.st_mtime;
    361 
    362     if (entry != NULL)
    363 	cst = entry->value;
    364     else {
    365 	entry = HashTable_CreateEntry(tbl, pathname, NULL);
    366 	cst = bmake_malloc(sizeof *cst);
    367 	memset(cst, 0, sizeof *cst);
    368 	HashEntry_Set(entry, cst);
    369     }
    370     if (flags & CST_LSTAT) {
    371 	cst->lmtime = sys_st.st_mtime;
    372     } else {
    373 	cst->mtime = sys_st.st_mtime;
    374     }
    375     cst->mode = sys_st.st_mode;
    376     DIR_DEBUG2("   Caching %s for %s\n",
    377 	       Targ_FmtTime(sys_st.st_mtime), pathname);
    378 
    379     return 0;
    380 }
    381 
    382 int
    383 cached_stat(const char *pathname, struct make_stat *st)
    384 {
    385     return cached_stats(&mtimes, pathname, st, CST_NONE);
    386 }
    387 
    388 int
    389 cached_lstat(const char *pathname, struct make_stat *st)
    390 {
    391     return cached_stats(&lmtimes, pathname, st, CST_LSTAT);
    392 }
    393 
    394 /* Initialize the directories module. */
    395 void
    396 Dir_Init(void)
    397 {
    398     dirSearchPath = Lst_New();
    399     OpenDirs_Init(&openDirs);
    400     HashTable_Init(&mtimes);
    401     HashTable_Init(&lmtimes);
    402 }
    403 
    404 void
    405 Dir_InitDir(const char *cdname)
    406 {
    407     Dir_InitCur(cdname);
    408 
    409     dotLast = bmake_malloc(sizeof *dotLast);
    410     dotLast->refCount = 1;
    411     dotLast->hits = 0;
    412     dotLast->name = bmake_strdup(".DOTLAST");
    413     HashTable_Init(&dotLast->files);
    414 }
    415 
    416 /*
    417  * Called by Dir_InitDir and whenever .CURDIR is assigned to.
    418  */
    419 void
    420 Dir_InitCur(const char *cdname)
    421 {
    422     CachedDir *dir;
    423 
    424     if (cdname == NULL)
    425 	return;
    426 
    427     /*
    428      * Our build directory is not the same as our source directory.
    429      * Keep this one around too.
    430      */
    431     dir = Dir_AddDir(NULL, cdname);
    432     if (dir == NULL)
    433 	return;
    434 
    435     /* XXX: Reference counting is wrong here.
    436      * If this function is called repeatedly with the same directory name,
    437      * its reference count increases each time even though the number of
    438      * actual references stays the same. */
    439 
    440     dir->refCount++;
    441     if (cur != NULL && cur != dir) {
    442 	/*
    443 	 * We've been here before, clean up.
    444 	 */
    445 	cur->refCount--;
    446 	Dir_Destroy(cur);
    447     }
    448     cur = dir;
    449 }
    450 
    451 /* (Re)initialize "dot" (current/object directory) path hash.
    452  * Some directories may be opened. */
    453 void
    454 Dir_InitDot(void)
    455 {
    456     if (dot != NULL) {
    457 	/* Remove old entry from openDirs, but do not destroy. */
    458 	OpenDirs_Remove(&openDirs, dot->name);
    459     }
    460 
    461     dot = Dir_AddDir(NULL, ".");
    462 
    463     if (dot == NULL) {
    464 	Error("Cannot open `.' (%s)", strerror(errno));
    465 	exit(1);
    466     }
    467 
    468     /*
    469      * We always need to have dot around, so we increment its reference count
    470      * to make sure it's not destroyed.
    471      */
    472     dot->refCount++;
    473     Dir_SetPATH();		/* initialize */
    474 }
    475 
    476 /* Clean up the directories module. */
    477 void
    478 Dir_End(void)
    479 {
    480 #ifdef CLEANUP
    481     if (cur) {
    482 	cur->refCount--;
    483 	Dir_Destroy(cur);
    484     }
    485     dot->refCount--;
    486     dotLast->refCount--;
    487     Dir_Destroy(dotLast);
    488     Dir_Destroy(dot);
    489     Dir_ClearPath(dirSearchPath);
    490     Lst_Free(dirSearchPath);
    491     OpenDirs_Done(&openDirs);
    492     HashTable_Done(&mtimes);
    493 #endif
    494 }
    495 
    496 /*
    497  * We want ${.PATH} to indicate the order in which we will actually
    498  * search, so we rebuild it after any .PATH: target.
    499  * This is the simplest way to deal with the effect of .DOTLAST.
    500  */
    501 void
    502 Dir_SetPATH(void)
    503 {
    504     CachedDirListNode *ln;
    505     Boolean hasLastDot = FALSE;	/* true if we should search dot last */
    506 
    507     Var_Delete(".PATH", VAR_GLOBAL);
    508 
    509     if ((ln = dirSearchPath->first) != NULL) {
    510 	CachedDir *dir = ln->datum;
    511 	if (dir == dotLast) {
    512 	    hasLastDot = TRUE;
    513 	    Var_Append(".PATH", dotLast->name, VAR_GLOBAL);
    514 	}
    515     }
    516 
    517     if (!hasLastDot) {
    518 	if (dot)
    519 	    Var_Append(".PATH", dot->name, VAR_GLOBAL);
    520 	if (cur)
    521 	    Var_Append(".PATH", cur->name, VAR_GLOBAL);
    522     }
    523 
    524     for (ln = dirSearchPath->first; ln != NULL; ln = ln->next) {
    525 	CachedDir *dir = ln->datum;
    526 	if (dir == dotLast)
    527 	    continue;
    528 	if (dir == dot && hasLastDot)
    529 	    continue;
    530 	Var_Append(".PATH", dir->name, VAR_GLOBAL);
    531     }
    532 
    533     if (hasLastDot) {
    534 	if (dot)
    535 	    Var_Append(".PATH", dot->name, VAR_GLOBAL);
    536 	if (cur)
    537 	    Var_Append(".PATH", cur->name, VAR_GLOBAL);
    538     }
    539 }
    540 
    541 /* See if the given name has any wildcard characters in it and all braces and
    542  * brackets are properly balanced.
    543  *
    544  * XXX: This code is not 100% correct ([^]] fails etc.). I really don't think
    545  * that make(1) should be expanding patterns, because then you have to set a
    546  * mechanism for escaping the expansion!
    547  *
    548  * Return TRUE if the word should be expanded, FALSE otherwise.
    549  */
    550 Boolean
    551 Dir_HasWildcards(const char *name)
    552 {
    553     const char *p;
    554     Boolean wild = FALSE;
    555     int braces = 0, brackets = 0;
    556 
    557     for (p = name; *p != '\0'; p++) {
    558 	switch (*p) {
    559 	case '{':
    560 	    braces++;
    561 	    wild = TRUE;
    562 	    break;
    563 	case '}':
    564 	    braces--;
    565 	    break;
    566 	case '[':
    567 	    brackets++;
    568 	    wild = TRUE;
    569 	    break;
    570 	case ']':
    571 	    brackets--;
    572 	    break;
    573 	case '?':
    574 	case '*':
    575 	    wild = TRUE;
    576 	    break;
    577 	default:
    578 	    break;
    579 	}
    580     }
    581     return wild && brackets == 0 && braces == 0;
    582 }
    583 
    584 /* See if any files match the pattern and add their names to the 'expansions'
    585  * list if they do.
    586  *
    587  * This is incomplete -- wildcards are only expanded in the final path
    588  * component, but not in directories like src/lib*c/file*.c, but it
    589  * will do for now (now being 1993 until at least 2020). To expand these,
    590  * use the ':sh' variable modifier such as in ${:!echo src/lib*c/file*.c!}.
    591  *
    592  * Input:
    593  *	pattern		Pattern to look for
    594  *	dir		Directory to search
    595  *	expansion	Place to store the results
    596  */
    597 static void
    598 DirMatchFiles(const char *pattern, CachedDir *dir, StringList *expansions)
    599 {
    600     const char *dirName = dir->name;
    601     Boolean isDot = dirName[0] == '.' && dirName[1] == '\0';
    602     HashIter hi;
    603 
    604     /* XXX: Iterating over all hash entries is inefficient.  If the pattern
    605      * is a plain string without any wildcards, a direct lookup is faster. */
    606 
    607     HashIter_Init(&hi, &dir->files);
    608     while (HashIter_Next(&hi) != NULL) {
    609 	const char *base = hi.entry->key;
    610 
    611 	if (!Str_Match(base, pattern))
    612 	    continue;
    613 
    614 	/*
    615 	 * Follow the UNIX convention that dot files are only found if the
    616 	 * pattern begins with a dot. The pattern '.*' does not match '.' or
    617 	 * '..' since these are not included in the directory cache.
    618 	 *
    619 	 * This means that the pattern '[a-z.]*' does not find '.file', which
    620 	 * is consistent with bash, NetBSD sh and csh.
    621 	 */
    622 	if (base[0] == '.' && pattern[0] != '.')
    623 	    continue;
    624 
    625 	{
    626 	    char *fullName = isDot
    627 			     ? bmake_strdup(base)
    628 			     : str_concat3(dirName, "/", base);
    629 	    Lst_Append(expansions, fullName);
    630 	}
    631     }
    632 }
    633 
    634 /* Find the next closing brace in the string, taking nested braces into
    635  * account. */
    636 static const char *
    637 closing_brace(const char *p)
    638 {
    639     int nest = 0;
    640     while (*p != '\0') {
    641 	if (*p == '}' && nest == 0)
    642 	    break;
    643 	if (*p == '{')
    644 	    nest++;
    645 	if (*p == '}')
    646 	    nest--;
    647 	p++;
    648     }
    649     return p;
    650 }
    651 
    652 /* Find the next closing brace or comma in the string, taking nested braces
    653  * into account. */
    654 static const char *
    655 separator_comma(const char *p)
    656 {
    657     int nest = 0;
    658     while (*p != '\0') {
    659 	if ((*p == '}' || *p == ',') && nest == 0)
    660 	    break;
    661 	if (*p == '{')
    662 	    nest++;
    663 	if (*p == '}')
    664 	    nest--;
    665 	p++;
    666     }
    667     return p;
    668 }
    669 
    670 static Boolean
    671 contains_wildcard(const char *p)
    672 {
    673     for (; *p != '\0'; p++) {
    674 	switch (*p) {
    675 	case '*':
    676 	case '?':
    677 	case '{':
    678 	case '[':
    679 	    return TRUE;
    680 	}
    681     }
    682     return FALSE;
    683 }
    684 
    685 static char *
    686 concat3(const char *a, size_t a_len, const char *b, size_t b_len,
    687 	const char *c, size_t c_len)
    688 {
    689     size_t s_len = a_len + b_len + c_len;
    690     char *s = bmake_malloc(s_len + 1);
    691     memcpy(s, a, a_len);
    692     memcpy(s + a_len, b, b_len);
    693     memcpy(s + a_len + b_len, c, c_len);
    694     s[s_len] = '\0';
    695     return s;
    696 }
    697 
    698 /* Expand curly braces like the C shell. Brace expansion by itself is purely
    699  * textual, the expansions are not looked up in the file system. But if an
    700  * expanded word contains wildcard characters, it is expanded further,
    701  * matching only the actually existing files.
    702  *
    703  * Example: "{a{b,c}}" expands to "ab" and "ac".
    704  * Example: "{a}" expands to "a".
    705  * Example: "{a,*.c}" expands to "a" and all "*.c" files that exist.
    706  *
    707  * Input:
    708  *	word		Entire word to expand
    709  *	brace		First curly brace in it
    710  *	path		Search path to use
    711  *	expansions	Place to store the expansions
    712  */
    713 static void
    714 DirExpandCurly(const char *word, const char *brace, SearchPath *path,
    715 	       StringList *expansions)
    716 {
    717     const char *prefix, *middle, *piece, *middle_end, *suffix;
    718     size_t prefix_len, suffix_len;
    719 
    720     /* Split the word into prefix '{' middle '}' suffix. */
    721 
    722     middle = brace + 1;
    723     middle_end = closing_brace(middle);
    724     if (*middle_end == '\0') {
    725 	Error("Unterminated {} clause \"%s\"", middle);
    726 	return;
    727     }
    728 
    729     prefix = word;
    730     prefix_len = (size_t)(brace - prefix);
    731     suffix = middle_end + 1;
    732     suffix_len = strlen(suffix);
    733 
    734     /* Split the middle into pieces, separated by commas. */
    735 
    736     piece = middle;
    737     while (piece < middle_end + 1) {
    738 	const char *piece_end = separator_comma(piece);
    739 	size_t piece_len = (size_t)(piece_end - piece);
    740 
    741 	char *file = concat3(prefix, prefix_len, piece, piece_len,
    742 			     suffix, suffix_len);
    743 
    744 	if (contains_wildcard(file)) {
    745 	    Dir_Expand(file, path, expansions);
    746 	    free(file);
    747 	} else {
    748 	    Lst_Append(expansions, file);
    749 	}
    750 
    751 	piece = piece_end + 1;	/* skip over the comma or closing brace */
    752     }
    753 }
    754 
    755 
    756 /* Expand the word in each of the directories from the path. */
    757 static void
    758 DirExpandPath(const char *word, SearchPath *path, StringList *expansions)
    759 {
    760     SearchPathNode *ln;
    761     for (ln = path->first; ln != NULL; ln = ln->next) {
    762 	CachedDir *dir = ln->datum;
    763 	DirMatchFiles(word, dir, expansions);
    764     }
    765 }
    766 
    767 static void
    768 PrintExpansions(StringList *expansions)
    769 {
    770     const char *sep = "";
    771     StringListNode *ln;
    772     for (ln = expansions->first; ln != NULL; ln = ln->next) {
    773 	const char *word = ln->datum;
    774 	debug_printf("%s%s", sep, word);
    775 	sep = " ";
    776     }
    777     debug_printf("\n");
    778 }
    779 
    780 /* Expand the given word into a list of words by globbing it, looking in the
    781  * directories on the given search path.
    782  *
    783  * Input:
    784  *	word		the word to expand
    785  *	path		the directories in which to find the files
    786  *	expansions	the list on which to place the results
    787  */
    788 void
    789 Dir_Expand(const char *word, SearchPath *path, StringList *expansions)
    790 {
    791     const char *cp;
    792 
    793     assert(path != NULL);
    794     assert(expansions != NULL);
    795 
    796     DIR_DEBUG1("Expanding \"%s\"... ", word);
    797 
    798     cp = strchr(word, '{');
    799     if (cp) {
    800 	DirExpandCurly(word, cp, path, expansions);
    801     } else {
    802 	cp = strchr(word, '/');
    803 	if (cp) {
    804 	    /*
    805 	     * The thing has a directory component -- find the first wildcard
    806 	     * in the string.
    807 	     */
    808 	    for (cp = word; *cp; cp++) {
    809 		if (*cp == '?' || *cp == '[' || *cp == '*') {
    810 		    break;
    811 		}
    812 	    }
    813 
    814 	    if (*cp != '\0') {
    815 		/*
    816 		 * Back up to the start of the component
    817 		 */
    818 		while (cp > word && *cp != '/') {
    819 		    cp--;
    820 		}
    821 		if (cp != word) {
    822 		    char *prefix = bmake_strsedup(word, cp + 1);
    823 		    /*
    824 		     * If the glob isn't in the first component, try and find
    825 		     * all the components up to the one with a wildcard.
    826 		     */
    827 		    char *dirpath = Dir_FindFile(prefix, path);
    828 		    free(prefix);
    829 		    /*
    830 		     * dirpath is null if can't find the leading component
    831 		     * XXX: Dir_FindFile won't find internal components.
    832 		     * i.e. if the path contains ../Etc/Object and we're
    833 		     * looking for Etc, it won't be found. Ah well.
    834 		     * Probably not important.
    835 		     */
    836 		    if (dirpath != NULL) {
    837 			char *dp = &dirpath[strlen(dirpath) - 1];
    838 			if (*dp == '/')
    839 			    *dp = '\0';
    840 			path = Lst_New();
    841 			(void)Dir_AddDir(path, dirpath);
    842 			DirExpandPath(cp + 1, path, expansions);
    843 			Lst_Free(path);
    844 		    }
    845 		} else {
    846 		    /*
    847 		     * Start the search from the local directory
    848 		     */
    849 		    DirExpandPath(word, path, expansions);
    850 		}
    851 	    } else {
    852 		/*
    853 		 * Return the file -- this should never happen.
    854 		 */
    855 		DirExpandPath(word, path, expansions);
    856 	    }
    857 	} else {
    858 	    /*
    859 	     * First the files in dot
    860 	     */
    861 	    DirMatchFiles(word, dot, expansions);
    862 
    863 	    /*
    864 	     * Then the files in every other directory on the path.
    865 	     */
    866 	    DirExpandPath(word, path, expansions);
    867 	}
    868     }
    869     if (DEBUG(DIR))
    870 	PrintExpansions(expansions);
    871 }
    872 
    873 /* Find if the file with the given name exists in the given path.
    874  * Return the freshly allocated path to the file, or NULL. */
    875 static char *
    876 DirLookup(CachedDir *dir, const char *base)
    877 {
    878     char *file;			/* the current filename to check */
    879 
    880     DIR_DEBUG1("   %s ...\n", dir->name);
    881 
    882     if (HashTable_FindEntry(&dir->files, base) == NULL)
    883 	return NULL;
    884 
    885     file = str_concat3(dir->name, "/", base);
    886     DIR_DEBUG1("   returning %s\n", file);
    887     dir->hits++;
    888     hits++;
    889     return file;
    890 }
    891 
    892 
    893 /* Find if the file with the given name exists in the given directory.
    894  * Return the freshly allocated path to the file, or NULL. */
    895 static char *
    896 DirLookupSubdir(CachedDir *dir, const char *name)
    897 {
    898     struct make_stat mst;
    899     char *file = dir == dot ? bmake_strdup(name)
    900 			    : str_concat3(dir->name, "/", name);
    901 
    902     DIR_DEBUG1("checking %s ...\n", file);
    903 
    904     if (cached_stat(file, &mst) == 0) {
    905 	nearmisses++;
    906 	return file;
    907     }
    908     free(file);
    909     return NULL;
    910 }
    911 
    912 /* Find if the file with the given name exists in the given path.
    913  * Return the freshly allocated path to the file, the empty string, or NULL.
    914  * Returning the empty string means that the search should be terminated.
    915  */
    916 static char *
    917 DirLookupAbs(CachedDir *dir, const char *name, const char *cp)
    918 {
    919     const char *dnp;		/* pointer into dir->name */
    920     const char *np;		/* pointer into name */
    921 
    922     DIR_DEBUG1("   %s ...\n", dir->name);
    923 
    924     /*
    925      * If the file has a leading path component and that component
    926      * exactly matches the entire name of the current search
    927      * directory, we can attempt another cache lookup. And if we don't
    928      * have a hit, we can safely assume the file does not exist at all.
    929      */
    930     for (dnp = dir->name, np = name; *dnp != '\0' && *dnp == *np; dnp++, np++)
    931 	continue;
    932     if (*dnp != '\0' || np != cp - 1)
    933 	return NULL;
    934 
    935     if (HashTable_FindEntry(&dir->files, cp) == NULL) {
    936 	DIR_DEBUG0("   must be here but isn't -- returning\n");
    937 	return bmake_strdup("");	/* to terminate the search */
    938     }
    939 
    940     dir->hits++;
    941     hits++;
    942     DIR_DEBUG1("   returning %s\n", name);
    943     return bmake_strdup(name);
    944 }
    945 
    946 /* Find the file given on "." or curdir.
    947  * Return the freshly allocated path to the file, or NULL. */
    948 static char *
    949 DirFindDot(const char *name, const char *base)
    950 {
    951 
    952     if (HashTable_FindEntry(&dot->files, base) != NULL) {
    953 	DIR_DEBUG0("   in '.'\n");
    954 	hits++;
    955 	dot->hits++;
    956 	return bmake_strdup(name);
    957     }
    958 
    959     if (cur != NULL && HashTable_FindEntry(&cur->files, base) != NULL) {
    960 	DIR_DEBUG1("   in ${.CURDIR} = %s\n", cur->name);
    961 	hits++;
    962 	cur->hits++;
    963 	return str_concat3(cur->name, "/", base);
    964     }
    965 
    966     return NULL;
    967 }
    968 
    969 /* Find the file with the given name along the given search path.
    970  *
    971  * If the file is found in a directory that is not on the path
    972  * already (either 'name' is absolute or it is a relative path
    973  * [ dir1/.../dirn/file ] which exists below one of the directories
    974  * already on the search path), its directory is added to the end
    975  * of the path, on the assumption that there will be more files in
    976  * that directory later on. Sometimes this is true. Sometimes not.
    977  *
    978  * Input:
    979  *	name		the file to find
    980  *	path		the directories to search, or NULL
    981  *
    982  * Results:
    983  *	The freshly allocated path to the file, or NULL.
    984  */
    985 char *
    986 Dir_FindFile(const char *name, SearchPath *path)
    987 {
    988     SearchPathNode *ln;
    989     char *file;			/* the current filename to check */
    990     const char *base;		/* Terminal name of file */
    991     Boolean hasLastDot = FALSE;	/* true if we should search dot last */
    992     Boolean hasSlash;		/* true if 'name' contains a / */
    993     struct make_stat mst;	/* Buffer for stat, if necessary */
    994     const char *trailing_dot = ".";
    995 
    996     /*
    997      * Find the final component of the name and note whether it has a
    998      * slash in it (the name, I mean)
    999      */
   1000     base = strrchr(name, '/');
   1001     if (base) {
   1002 	hasSlash = TRUE;
   1003 	base++;
   1004     } else {
   1005 	hasSlash = FALSE;
   1006 	base = name;
   1007     }
   1008 
   1009     DIR_DEBUG1("Searching for %s ...", name);
   1010 
   1011     if (path == NULL) {
   1012 	DIR_DEBUG0("couldn't open path, file not found\n");
   1013 	misses++;
   1014 	return NULL;
   1015     }
   1016 
   1017     if ((ln = path->first) != NULL) {
   1018 	CachedDir *dir = ln->datum;
   1019 	if (dir == dotLast) {
   1020 	    hasLastDot = TRUE;
   1021 	    DIR_DEBUG0("[dot last]...");
   1022 	}
   1023     }
   1024     DIR_DEBUG0("\n");
   1025 
   1026     /*
   1027      * If there's no leading directory components or if the leading
   1028      * directory component is exactly `./', consult the cached contents
   1029      * of each of the directories on the search path.
   1030      */
   1031     if (!hasSlash || (base - name == 2 && *name == '.')) {
   1032 	/*
   1033 	 * We look through all the directories on the path seeking one which
   1034 	 * contains the final component of the given name.  If such a beast
   1035 	 * is found, we concatenate the directory name and the final
   1036 	 * component and return the resulting string. If we don't find any
   1037 	 * such thing, we go on to phase two...
   1038 	 *
   1039 	 * No matter what, we always look for the file in the current
   1040 	 * directory before anywhere else (unless we found the magic
   1041 	 * DOTLAST path, in which case we search it last) and we *do not*
   1042 	 * add the ./ to it if it exists.
   1043 	 * This is so there are no conflicts between what the user
   1044 	 * specifies (fish.c) and what pmake finds (./fish.c).
   1045 	 */
   1046 	if (!hasLastDot && (file = DirFindDot(name, base)) != NULL)
   1047 	    return file;
   1048 
   1049 	for (; ln != NULL; ln = ln->next) {
   1050 	    CachedDir *dir = ln->datum;
   1051 	    if (dir == dotLast)
   1052 		continue;
   1053 	    if ((file = DirLookup(dir, base)) != NULL)
   1054 		return file;
   1055 	}
   1056 
   1057 	if (hasLastDot && (file = DirFindDot(name, base)) != NULL)
   1058 	    return file;
   1059     }
   1060 
   1061     /*
   1062      * We didn't find the file on any directory in the search path.
   1063      * If the name doesn't contain a slash, that means it doesn't exist.
   1064      * If it *does* contain a slash, however, there is still hope: it
   1065      * could be in a subdirectory of one of the members of the search
   1066      * path. (eg. /usr/include and sys/types.h. The above search would
   1067      * fail to turn up types.h in /usr/include, but it *is* in
   1068      * /usr/include/sys/types.h).
   1069      * [ This no longer applies: If we find such a beast, we assume there
   1070      * will be more (what else can we assume?) and add all but the last
   1071      * component of the resulting name onto the search path (at the
   1072      * end).]
   1073      * This phase is only performed if the file is *not* absolute.
   1074      */
   1075     if (!hasSlash) {
   1076 	DIR_DEBUG0("   failed.\n");
   1077 	misses++;
   1078 	return NULL;
   1079     }
   1080 
   1081     if (*base == '\0') {
   1082 	/* we were given a trailing "/" */
   1083 	base = trailing_dot;
   1084     }
   1085 
   1086     if (name[0] != '/') {
   1087 	Boolean checkedDot = FALSE;
   1088 
   1089 	DIR_DEBUG0("   Trying subdirectories...\n");
   1090 
   1091 	if (!hasLastDot) {
   1092 	    if (dot) {
   1093 		checkedDot = TRUE;
   1094 		if ((file = DirLookupSubdir(dot, name)) != NULL)
   1095 		    return file;
   1096 	    }
   1097 	    if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
   1098 		return file;
   1099 	}
   1100 
   1101 	for (ln = path->first; ln != NULL; ln = ln->next) {
   1102 	    CachedDir *dir = ln->datum;
   1103 	    if (dir == dotLast)
   1104 		continue;
   1105 	    if (dir == dot) {
   1106 		if (checkedDot)
   1107 		    continue;
   1108 		checkedDot = TRUE;
   1109 	    }
   1110 	    if ((file = DirLookupSubdir(dir, name)) != NULL)
   1111 		return file;
   1112 	}
   1113 
   1114 	if (hasLastDot) {
   1115 	    if (dot && !checkedDot) {
   1116 		checkedDot = TRUE;
   1117 		if ((file = DirLookupSubdir(dot, name)) != NULL)
   1118 		    return file;
   1119 	    }
   1120 	    if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
   1121 		return file;
   1122 	}
   1123 
   1124 	if (checkedDot) {
   1125 	    /*
   1126 	     * Already checked by the given name, since . was in the path,
   1127 	     * so no point in proceeding...
   1128 	     */
   1129 	    DIR_DEBUG0("   Checked . already, returning NULL\n");
   1130 	    return NULL;
   1131 	}
   1132 
   1133     } else { /* name[0] == '/' */
   1134 
   1135 	/*
   1136 	 * For absolute names, compare directory path prefix against the
   1137 	 * the directory path of each member on the search path for an exact
   1138 	 * match. If we have an exact match on any member of the search path,
   1139 	 * use the cached contents of that member to lookup the final file
   1140 	 * component. If that lookup fails we can safely assume that the
   1141 	 * file does not exist at all.  This is signified by DirLookupAbs()
   1142 	 * returning an empty string.
   1143 	 */
   1144 	DIR_DEBUG0("   Trying exact path matches...\n");
   1145 
   1146 	if (!hasLastDot && cur &&
   1147 	    ((file = DirLookupAbs(cur, name, base)) != NULL)) {
   1148 	    if (file[0] == '\0') {
   1149 		free(file);
   1150 		return NULL;
   1151 	    }
   1152 	    return file;
   1153 	}
   1154 
   1155 	for (ln = path->first; ln != NULL; ln = ln->next) {
   1156 	    CachedDir *dir = ln->datum;
   1157 	    if (dir == dotLast)
   1158 		continue;
   1159 	    if ((file = DirLookupAbs(dir, name, base)) != NULL) {
   1160 		if (file[0] == '\0') {
   1161 		    free(file);
   1162 		    return NULL;
   1163 		}
   1164 		return file;
   1165 	    }
   1166 	}
   1167 
   1168 	if (hasLastDot && cur &&
   1169 	    ((file = DirLookupAbs(cur, name, base)) != NULL)) {
   1170 	    if (file[0] == '\0') {
   1171 		free(file);
   1172 		return NULL;
   1173 	    }
   1174 	    return file;
   1175 	}
   1176     }
   1177 
   1178     /*
   1179      * Didn't find it that way, either. Sigh. Phase 3. Add its directory
   1180      * onto the search path in any case, just in case, then look for the
   1181      * thing in the hash table. If we find it, grand. We return a new
   1182      * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
   1183      * Note that if the directory holding the file doesn't exist, this will
   1184      * do an extra search of the final directory on the path. Unless something
   1185      * weird happens, this search won't succeed and life will be groovy.
   1186      *
   1187      * Sigh. We cannot add the directory onto the search path because
   1188      * of this amusing case:
   1189      * $(INSTALLDIR)/$(FILE): $(FILE)
   1190      *
   1191      * $(FILE) exists in $(INSTALLDIR) but not in the current one.
   1192      * When searching for $(FILE), we will find it in $(INSTALLDIR)
   1193      * b/c we added it here. This is not good...
   1194      */
   1195 #if 0
   1196     if (base == trailing_dot) {
   1197 	base = strrchr(name, '/');
   1198 	base++;
   1199     }
   1200     base[-1] = '\0';
   1201     (void)Dir_AddDir(path, name);
   1202     base[-1] = '/';
   1203 
   1204     bigmisses++;
   1205     ln = Lst_Last(path);
   1206     if (ln == NULL) {
   1207 	return NULL;
   1208     } else {
   1209 	dir = LstNode_Datum(ln);
   1210     }
   1211 
   1212     if (Hash_FindEntry(&dir->files, base) != NULL) {
   1213 	return bmake_strdup(name);
   1214     } else {
   1215 	return NULL;
   1216     }
   1217 #else
   1218     DIR_DEBUG1("   Looking for \"%s\" ...\n", name);
   1219 
   1220     bigmisses++;
   1221     if (cached_stat(name, &mst) == 0) {
   1222 	return bmake_strdup(name);
   1223     }
   1224 
   1225     DIR_DEBUG0("   failed. Returning NULL\n");
   1226     return NULL;
   1227 #endif
   1228 }
   1229 
   1230 
   1231 /* Search for a path starting at a given directory and then working our way
   1232  * up towards the root.
   1233  *
   1234  * Input:
   1235  *	here		starting directory
   1236  *	search_path	the relative path we are looking for
   1237  *
   1238  * Results:
   1239  *	The found path, or NULL.
   1240  */
   1241 char *
   1242 Dir_FindHereOrAbove(const char *here, const char *search_path)
   1243 {
   1244     struct make_stat mst;
   1245     char *dirbase, *dirbase_end;
   1246     char *try, *try_end;
   1247 
   1248     /* copy out our starting point */
   1249     dirbase = bmake_strdup(here);
   1250     dirbase_end = dirbase + strlen(dirbase);
   1251 
   1252     /* loop until we determine a result */
   1253     for (;;) {
   1254 
   1255 	/* try and stat(2) it ... */
   1256 	try = str_concat3(dirbase, "/", search_path);
   1257 	if (cached_stat(try, &mst) != -1) {
   1258 	    /*
   1259 	     * success!  if we found a file, chop off
   1260 	     * the filename so we return a directory.
   1261 	     */
   1262 	    if ((mst.mst_mode & S_IFMT) != S_IFDIR) {
   1263 		try_end = try + strlen(try);
   1264 		while (try_end > try && *try_end != '/')
   1265 		    try_end--;
   1266 		if (try_end > try)
   1267 		    *try_end = '\0';	/* chop! */
   1268 	    }
   1269 
   1270 	    free(dirbase);
   1271 	    return try;
   1272 	}
   1273 	free(try);
   1274 
   1275 	/*
   1276 	 * nope, we didn't find it.  if we used up dirbase we've
   1277 	 * reached the root and failed.
   1278 	 */
   1279 	if (dirbase_end == dirbase)
   1280 	    break;		/* failed! */
   1281 
   1282 	/*
   1283 	 * truncate dirbase from the end to move up a dir
   1284 	 */
   1285 	while (dirbase_end > dirbase && *dirbase_end != '/')
   1286 	    dirbase_end--;
   1287 	*dirbase_end = '\0';	/* chop! */
   1288     }
   1289 
   1290     free(dirbase);
   1291     return NULL;
   1292 }
   1293 
   1294 /* Search gn along dirSearchPath and store its modification time in gn->mtime.
   1295  * If no file is found, store 0 instead.
   1296  *
   1297  * The found file is stored in gn->path, unless the node already had a path. */
   1298 void
   1299 Dir_UpdateMTime(GNode *gn, Boolean recheck)
   1300 {
   1301     char *fullName;		/* the full pathname of name */
   1302     struct make_stat mst;	/* buffer for finding the mod time */
   1303     CachedStatsFlags flags;
   1304 
   1305     if (gn->type & OP_ARCHV) {
   1306 	Arch_UpdateMTime(gn);
   1307 	return;
   1308     }
   1309 
   1310     if (gn->type & OP_PHONY) {
   1311 	gn->mtime = 0;
   1312 	return;
   1313     }
   1314 
   1315     if (gn->path == NULL) {
   1316 	if (gn->type & OP_NOPATH)
   1317 	    fullName = NULL;
   1318 	else {
   1319 	    fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
   1320 	    if (fullName == NULL && gn->flags & FROM_DEPEND &&
   1321 		!Lst_IsEmpty(gn->implicitParents)) {
   1322 		char *cp;
   1323 
   1324 		cp = strrchr(gn->name, '/');
   1325 		if (cp) {
   1326 		    /*
   1327 		     * This is an implied source, and it may have moved,
   1328 		     * see if we can find it via the current .PATH
   1329 		     */
   1330 		    cp++;
   1331 
   1332 		    fullName = Dir_FindFile(cp, Suff_FindPath(gn));
   1333 		    if (fullName) {
   1334 			/*
   1335 			 * Put the found file in gn->path
   1336 			 * so that we give that to the compiler.
   1337 			 */
   1338 			gn->path = bmake_strdup(fullName);
   1339 			if (!Job_RunTarget(".STALE", gn->fname))
   1340 			    fprintf(stdout,
   1341 				    "%s: %s, %d: ignoring stale %s for %s, "
   1342 				    "found %s\n", progname, gn->fname,
   1343 				    gn->lineno,
   1344 				    makeDependfile, gn->name, fullName);
   1345 		    }
   1346 		}
   1347 	    }
   1348 	    DIR_DEBUG2("Found '%s' as '%s'\n",
   1349 		       gn->name, fullName ? fullName : "(not found)");
   1350 	}
   1351     } else {
   1352 	fullName = gn->path;
   1353     }
   1354 
   1355     if (fullName == NULL)
   1356 	fullName = bmake_strdup(gn->name);
   1357 
   1358     flags = recheck ? CST_UPDATE : CST_NONE;
   1359     if (cached_stats(&mtimes, fullName, &mst, flags) < 0) {
   1360 	if (gn->type & OP_MEMBER) {
   1361 	    if (fullName != gn->path)
   1362 		free(fullName);
   1363 	    Arch_UpdateMemberMTime(gn);
   1364 	    return;
   1365 	}
   1366 
   1367 	mst.mst_mtime = 0;
   1368     }
   1369 
   1370     if (fullName != NULL && gn->path == NULL)
   1371 	gn->path = fullName;
   1372 
   1373     gn->mtime = mst.mst_mtime;
   1374 }
   1375 
   1376 /* Read the list of filenames in the directory and store the result
   1377  * in openDirectories.
   1378  *
   1379  * If a path is given, append the directory to that path.
   1380  *
   1381  * Input:
   1382  *	path		The path to which the directory should be
   1383  *			added, or NULL to only add the directory to
   1384  *			openDirectories
   1385  *	name		The name of the directory to add.
   1386  *			The name is not normalized in any way.
   1387  */
   1388 CachedDir *
   1389 Dir_AddDir(SearchPath *path, const char *name)
   1390 {
   1391     CachedDir *dir = NULL;	/* the added directory */
   1392     DIR *d;
   1393     struct dirent *dp;
   1394 
   1395     if (path != NULL && strcmp(name, ".DOTLAST") == 0) {
   1396 	SearchPathNode *ln;
   1397 
   1398 	/* XXX: Linear search gets slow with thousands of entries. */
   1399 	for (ln = path->first; ln != NULL; ln = ln->next) {
   1400 	    CachedDir *pathDir = ln->datum;
   1401 	    if (strcmp(pathDir->name, name) == 0)
   1402 		return pathDir;
   1403 	}
   1404 
   1405 	dotLast->refCount++;
   1406 	Lst_Prepend(path, dotLast);
   1407     }
   1408 
   1409     if (path != NULL)
   1410 	dir = OpenDirs_Find(&openDirs, name);
   1411     if (dir != NULL) {
   1412 	if (Lst_FindDatum(path, dir) == NULL) {
   1413 	    dir->refCount++;
   1414 	    Lst_Append(path, dir);
   1415 	}
   1416 	return dir;
   1417     }
   1418 
   1419     DIR_DEBUG1("Caching %s ...", name);
   1420 
   1421     if ((d = opendir(name)) != NULL) {
   1422 	dir = bmake_malloc(sizeof *dir);
   1423 	dir->name = bmake_strdup(name);
   1424 	dir->hits = 0;
   1425 	dir->refCount = 1;
   1426 	HashTable_Init(&dir->files);
   1427 
   1428 	while ((dp = readdir(d)) != NULL) {
   1429 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
   1430 	    /*
   1431 	     * The sun directory library doesn't check for a 0 inode
   1432 	     * (0-inode slots just take up space), so we have to do
   1433 	     * it ourselves.
   1434 	     */
   1435 	    if (dp->d_fileno == 0) {
   1436 		continue;
   1437 	    }
   1438 #endif /* sun && d_ino */
   1439 	    (void)HashTable_CreateEntry(&dir->files, dp->d_name, NULL);
   1440 	}
   1441 	(void)closedir(d);
   1442 	OpenDirs_Add(&openDirs, dir);
   1443 	if (path != NULL)
   1444 	    Lst_Append(path, dir);
   1445     }
   1446     DIR_DEBUG0("done\n");
   1447     return dir;
   1448 }
   1449 
   1450 /* Return a copy of dirSearchPath, incrementing the reference counts for
   1451  * the contained directories. */
   1452 SearchPath *
   1453 Dir_CopyDirSearchPath(void)
   1454 {
   1455     SearchPath *path = Lst_New();
   1456     SearchPathNode *ln;
   1457     for (ln = dirSearchPath->first; ln != NULL; ln = ln->next) {
   1458 	CachedDir *dir = ln->datum;
   1459 	dir->refCount++;
   1460 	Lst_Append(path, dir);
   1461     }
   1462     return path;
   1463 }
   1464 
   1465 /*-
   1466  *-----------------------------------------------------------------------
   1467  * Dir_MakeFlags --
   1468  *	Make a string by taking all the directories in the given search
   1469  *	path and preceding them by the given flag. Used by the suffix
   1470  *	module to create variables for compilers based on suffix search
   1471  *	paths.
   1472  *
   1473  * Input:
   1474  *	flag		flag which should precede each directory
   1475  *	path		list of directories
   1476  *
   1477  * Results:
   1478  *	The string mentioned above. Note that there is no space between
   1479  *	the given flag and each directory. The empty string is returned if
   1480  *	Things don't go well.
   1481  *
   1482  * Side Effects:
   1483  *	None
   1484  *-----------------------------------------------------------------------
   1485  */
   1486 char *
   1487 Dir_MakeFlags(const char *flag, SearchPath *path)
   1488 {
   1489     Buffer buf;
   1490     SearchPathNode *ln;
   1491 
   1492     Buf_Init(&buf);
   1493 
   1494     if (path != NULL) {
   1495 	for (ln = path->first; ln != NULL; ln = ln->next) {
   1496 	    CachedDir *dir = ln->datum;
   1497 	    Buf_AddStr(&buf, " ");
   1498 	    Buf_AddStr(&buf, flag);
   1499 	    Buf_AddStr(&buf, dir->name);
   1500 	}
   1501     }
   1502 
   1503     return Buf_Destroy(&buf, FALSE);
   1504 }
   1505 
   1506 /* Nuke a directory descriptor, if possible. Callback procedure for the
   1507  * suffixes module when destroying a search path.
   1508  *
   1509  * Input:
   1510  *	dirp		The directory descriptor to nuke
   1511  */
   1512 void
   1513 Dir_Destroy(void *dirp)
   1514 {
   1515     CachedDir *dir = dirp;
   1516     dir->refCount--;
   1517 
   1518     if (dir->refCount == 0) {
   1519 	OpenDirs_Remove(&openDirs, dir->name);
   1520 
   1521 	HashTable_Done(&dir->files);
   1522 	free(dir->name);
   1523 	free(dir);
   1524     }
   1525 }
   1526 
   1527 /* Clear out all elements from the given search path.
   1528  * The path is set to the empty list but is not destroyed. */
   1529 void
   1530 Dir_ClearPath(SearchPath *path)
   1531 {
   1532     while (!Lst_IsEmpty(path)) {
   1533 	CachedDir *dir = Lst_Dequeue(path);
   1534 	Dir_Destroy(dir);
   1535     }
   1536 }
   1537 
   1538 
   1539 /* Concatenate two paths, adding the second to the end of the first,
   1540  * skipping duplicates. */
   1541 void
   1542 Dir_Concat(SearchPath *dst, SearchPath *src)
   1543 {
   1544     SearchPathNode *ln;
   1545 
   1546     for (ln = src->first; ln != NULL; ln = ln->next) {
   1547 	CachedDir *dir = ln->datum;
   1548 	if (Lst_FindDatum(dst, dir) == NULL) {
   1549 	    dir->refCount++;
   1550 	    Lst_Append(dst, dir);
   1551 	}
   1552     }
   1553 }
   1554 
   1555 static int
   1556 percentage(int num, int den)
   1557 {
   1558     return den != 0 ? num * 100 / den : 0;
   1559 }
   1560 
   1561 /********** DEBUG INFO **********/
   1562 void
   1563 Dir_PrintDirectories(void)
   1564 {
   1565     CachedDirListNode *ln;
   1566 
   1567     debug_printf("#*** Directory Cache:\n");
   1568     debug_printf("# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
   1569 		 hits, misses, nearmisses, bigmisses,
   1570 		 percentage(hits, hits + bigmisses + nearmisses));
   1571     debug_printf("# %-20s referenced\thits\n", "directory");
   1572 
   1573     for (ln = openDirs.list->first; ln != NULL; ln = ln->next) {
   1574 	CachedDir *dir = ln->datum;
   1575 	debug_printf("# %-20s %10d\t%4d\n", dir->name, dir->refCount,
   1576 		     dir->hits);
   1577     }
   1578 }
   1579 
   1580 void
   1581 Dir_PrintPath(SearchPath *path)
   1582 {
   1583     SearchPathNode *node;
   1584     for (node = path->first; node != NULL; node = node->next) {
   1585 	const CachedDir *dir = node->datum;
   1586 	debug_printf("%s ", dir->name);
   1587     }
   1588 }
   1589