Home | History | Annotate | Line # | Download | only in make
dir.c revision 1.209
      1 /*	$NetBSD: dir.c,v 1.209 2020/11/14 19:36:31 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.209 2020/11/14 19:36:31 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 typedef enum CachedStatsFlags {
    304     CST_NONE	= 0,
    305     CST_LSTAT	= 1 << 0,	/* call lstat(2) instead of stat(2) */
    306     CST_UPDATE	= 1 << 1	/* ignore existing cached entry */
    307 } CachedStatsFlags;
    308 
    309 /* Returns 0 and the result of stat(2) or lstat(2) in *out_cst,
    310  * or -1 on error. */
    311 static int
    312 cached_stats(const char *pathname, struct cached_stat *out_cst,
    313 	     CachedStatsFlags flags)
    314 {
    315     HashTable *tbl = flags & CST_LSTAT ? &lmtimes : &mtimes;
    316     HashEntry *entry;
    317     struct stat sys_st;
    318     struct cached_stat *cst;
    319     int rc;
    320 
    321     if (pathname == NULL || pathname[0] == '\0')
    322 	return -1;		/* This can happen in meta mode. */
    323 
    324     entry = HashTable_FindEntry(tbl, pathname);
    325 
    326     if (entry != NULL && !(flags & CST_UPDATE)) {
    327 	cst = HashEntry_Get(entry);
    328 
    329 	*out_cst = *cst;
    330 	DIR_DEBUG2("Using cached time %s for %s\n",
    331 		   Targ_FmtTime(cst->cst_mtime), pathname);
    332 	return 0;
    333     }
    334 
    335     rc = (flags & CST_LSTAT ? lstat : stat)(pathname, &sys_st);
    336     if (rc == -1)
    337 	return -1;		/* don't cache negative lookups */
    338 
    339     if (sys_st.st_mtime == 0)
    340 	sys_st.st_mtime = 1;	/* avoid confusion with missing file */
    341 
    342     if (entry != NULL)
    343 	cst = entry->value;
    344     else {
    345 	entry = HashTable_CreateEntry(tbl, pathname, NULL);
    346 	cst = bmake_malloc(sizeof *cst);
    347 	memset(cst, 0, sizeof *cst);
    348 	HashEntry_Set(entry, cst);
    349     }
    350 
    351     cst->cst_mtime = sys_st.st_mtime;
    352     cst->cst_mode = sys_st.st_mode;
    353 
    354     *out_cst = *cst;
    355     DIR_DEBUG2("   Caching %s for %s\n",
    356 	       Targ_FmtTime(sys_st.st_mtime), pathname);
    357 
    358     return 0;
    359 }
    360 
    361 int
    362 cached_stat(const char *pathname, struct cached_stat *cst)
    363 {
    364     return cached_stats(pathname, cst, CST_NONE);
    365 }
    366 
    367 int
    368 cached_lstat(const char *pathname, struct cached_stat *cst)
    369 {
    370     return cached_stats(pathname, cst, CST_LSTAT);
    371 }
    372 
    373 /* Initialize the directories module. */
    374 void
    375 Dir_Init(void)
    376 {
    377     dirSearchPath = Lst_New();
    378     OpenDirs_Init(&openDirs);
    379     HashTable_Init(&mtimes);
    380     HashTable_Init(&lmtimes);
    381 }
    382 
    383 void
    384 Dir_InitDir(const char *cdname)
    385 {
    386     Dir_InitCur(cdname);
    387 
    388     dotLast = bmake_malloc(sizeof *dotLast);
    389     dotLast->refCount = 1;
    390     dotLast->hits = 0;
    391     dotLast->name = bmake_strdup(".DOTLAST");
    392     HashTable_Init(&dotLast->files);
    393 }
    394 
    395 /*
    396  * Called by Dir_InitDir and whenever .CURDIR is assigned to.
    397  */
    398 void
    399 Dir_InitCur(const char *cdname)
    400 {
    401     CachedDir *dir;
    402 
    403     if (cdname == NULL)
    404 	return;
    405 
    406     /*
    407      * Our build directory is not the same as our source directory.
    408      * Keep this one around too.
    409      */
    410     dir = Dir_AddDir(NULL, cdname);
    411     if (dir == NULL)
    412 	return;
    413 
    414     /* XXX: Reference counting is wrong here.
    415      * If this function is called repeatedly with the same directory name,
    416      * its reference count increases each time even though the number of
    417      * actual references stays the same. */
    418 
    419     dir->refCount++;
    420     if (cur != NULL && cur != dir) {
    421 	/*
    422 	 * We've been here before, clean up.
    423 	 */
    424 	cur->refCount--;
    425 	Dir_Destroy(cur);
    426     }
    427     cur = dir;
    428 }
    429 
    430 /* (Re)initialize "dot" (current/object directory) path hash.
    431  * Some directories may be opened. */
    432 void
    433 Dir_InitDot(void)
    434 {
    435     if (dot != NULL) {
    436 	/* Remove old entry from openDirs, but do not destroy. */
    437 	OpenDirs_Remove(&openDirs, dot->name);
    438     }
    439 
    440     dot = Dir_AddDir(NULL, ".");
    441 
    442     if (dot == NULL) {
    443 	Error("Cannot open `.' (%s)", strerror(errno));
    444 	exit(1);
    445     }
    446 
    447     /*
    448      * We always need to have dot around, so we increment its reference count
    449      * to make sure it's not destroyed.
    450      */
    451     dot->refCount++;
    452     Dir_SetPATH();		/* initialize */
    453 }
    454 
    455 /* Clean up the directories module. */
    456 void
    457 Dir_End(void)
    458 {
    459 #ifdef CLEANUP
    460     if (cur) {
    461 	cur->refCount--;
    462 	Dir_Destroy(cur);
    463     }
    464     dot->refCount--;
    465     dotLast->refCount--;
    466     Dir_Destroy(dotLast);
    467     Dir_Destroy(dot);
    468     Dir_ClearPath(dirSearchPath);
    469     Lst_Free(dirSearchPath);
    470     OpenDirs_Done(&openDirs);
    471     HashTable_Done(&mtimes);
    472 #endif
    473 }
    474 
    475 /*
    476  * We want ${.PATH} to indicate the order in which we will actually
    477  * search, so we rebuild it after any .PATH: target.
    478  * This is the simplest way to deal with the effect of .DOTLAST.
    479  */
    480 void
    481 Dir_SetPATH(void)
    482 {
    483     CachedDirListNode *ln;
    484     Boolean hasLastDot = FALSE;	/* true if we should search dot last */
    485 
    486     Var_Delete(".PATH", VAR_GLOBAL);
    487 
    488     if ((ln = dirSearchPath->first) != NULL) {
    489 	CachedDir *dir = ln->datum;
    490 	if (dir == dotLast) {
    491 	    hasLastDot = TRUE;
    492 	    Var_Append(".PATH", dotLast->name, VAR_GLOBAL);
    493 	}
    494     }
    495 
    496     if (!hasLastDot) {
    497 	if (dot)
    498 	    Var_Append(".PATH", dot->name, VAR_GLOBAL);
    499 	if (cur)
    500 	    Var_Append(".PATH", cur->name, VAR_GLOBAL);
    501     }
    502 
    503     for (ln = dirSearchPath->first; ln != NULL; ln = ln->next) {
    504 	CachedDir *dir = ln->datum;
    505 	if (dir == dotLast)
    506 	    continue;
    507 	if (dir == dot && hasLastDot)
    508 	    continue;
    509 	Var_Append(".PATH", dir->name, VAR_GLOBAL);
    510     }
    511 
    512     if (hasLastDot) {
    513 	if (dot)
    514 	    Var_Append(".PATH", dot->name, VAR_GLOBAL);
    515 	if (cur)
    516 	    Var_Append(".PATH", cur->name, VAR_GLOBAL);
    517     }
    518 }
    519 
    520 /* See if the given name has any wildcard characters in it and all braces and
    521  * brackets are properly balanced.
    522  *
    523  * XXX: This code is not 100% correct ([^]] fails etc.). I really don't think
    524  * that make(1) should be expanding patterns, because then you have to set a
    525  * mechanism for escaping the expansion!
    526  *
    527  * Return TRUE if the word should be expanded, FALSE otherwise.
    528  */
    529 Boolean
    530 Dir_HasWildcards(const char *name)
    531 {
    532     const char *p;
    533     Boolean wild = FALSE;
    534     int braces = 0, brackets = 0;
    535 
    536     for (p = name; *p != '\0'; p++) {
    537 	switch (*p) {
    538 	case '{':
    539 	    braces++;
    540 	    wild = TRUE;
    541 	    break;
    542 	case '}':
    543 	    braces--;
    544 	    break;
    545 	case '[':
    546 	    brackets++;
    547 	    wild = TRUE;
    548 	    break;
    549 	case ']':
    550 	    brackets--;
    551 	    break;
    552 	case '?':
    553 	case '*':
    554 	    wild = TRUE;
    555 	    break;
    556 	default:
    557 	    break;
    558 	}
    559     }
    560     return wild && brackets == 0 && braces == 0;
    561 }
    562 
    563 /* See if any files match the pattern and add their names to the 'expansions'
    564  * list if they do.
    565  *
    566  * This is incomplete -- wildcards are only expanded in the final path
    567  * component, but not in directories like src/lib*c/file*.c, but it
    568  * will do for now (now being 1993 until at least 2020). To expand these,
    569  * use the ':sh' variable modifier such as in ${:!echo src/lib*c/file*.c!}.
    570  *
    571  * Input:
    572  *	pattern		Pattern to look for
    573  *	dir		Directory to search
    574  *	expansion	Place to store the results
    575  */
    576 static void
    577 DirMatchFiles(const char *pattern, CachedDir *dir, StringList *expansions)
    578 {
    579     const char *dirName = dir->name;
    580     Boolean isDot = dirName[0] == '.' && dirName[1] == '\0';
    581     HashIter hi;
    582 
    583     /* XXX: Iterating over all hash entries is inefficient.  If the pattern
    584      * is a plain string without any wildcards, a direct lookup is faster. */
    585 
    586     HashIter_Init(&hi, &dir->files);
    587     while (HashIter_Next(&hi) != NULL) {
    588 	const char *base = hi.entry->key;
    589 
    590 	if (!Str_Match(base, pattern))
    591 	    continue;
    592 
    593 	/*
    594 	 * Follow the UNIX convention that dot files are only found if the
    595 	 * pattern begins with a dot. The pattern '.*' does not match '.' or
    596 	 * '..' since these are not included in the directory cache.
    597 	 *
    598 	 * This means that the pattern '[a-z.]*' does not find '.file', which
    599 	 * is consistent with bash, NetBSD sh and csh.
    600 	 */
    601 	if (base[0] == '.' && pattern[0] != '.')
    602 	    continue;
    603 
    604 	{
    605 	    char *fullName = isDot
    606 			     ? bmake_strdup(base)
    607 			     : str_concat3(dirName, "/", base);
    608 	    Lst_Append(expansions, fullName);
    609 	}
    610     }
    611 }
    612 
    613 /* Find the next closing brace in the string, taking nested braces into
    614  * account. */
    615 static const char *
    616 closing_brace(const char *p)
    617 {
    618     int nest = 0;
    619     while (*p != '\0') {
    620 	if (*p == '}' && nest == 0)
    621 	    break;
    622 	if (*p == '{')
    623 	    nest++;
    624 	if (*p == '}')
    625 	    nest--;
    626 	p++;
    627     }
    628     return p;
    629 }
    630 
    631 /* Find the next closing brace or comma in the string, taking nested braces
    632  * into account. */
    633 static const char *
    634 separator_comma(const char *p)
    635 {
    636     int nest = 0;
    637     while (*p != '\0') {
    638 	if ((*p == '}' || *p == ',') && nest == 0)
    639 	    break;
    640 	if (*p == '{')
    641 	    nest++;
    642 	if (*p == '}')
    643 	    nest--;
    644 	p++;
    645     }
    646     return p;
    647 }
    648 
    649 static Boolean
    650 contains_wildcard(const char *p)
    651 {
    652     for (; *p != '\0'; p++) {
    653 	switch (*p) {
    654 	case '*':
    655 	case '?':
    656 	case '{':
    657 	case '[':
    658 	    return TRUE;
    659 	}
    660     }
    661     return FALSE;
    662 }
    663 
    664 static char *
    665 concat3(const char *a, size_t a_len, const char *b, size_t b_len,
    666 	const char *c, size_t c_len)
    667 {
    668     size_t s_len = a_len + b_len + c_len;
    669     char *s = bmake_malloc(s_len + 1);
    670     memcpy(s, a, a_len);
    671     memcpy(s + a_len, b, b_len);
    672     memcpy(s + a_len + b_len, c, c_len);
    673     s[s_len] = '\0';
    674     return s;
    675 }
    676 
    677 /* Expand curly braces like the C shell. Brace expansion by itself is purely
    678  * textual, the expansions are not looked up in the file system. But if an
    679  * expanded word contains wildcard characters, it is expanded further,
    680  * matching only the actually existing files.
    681  *
    682  * Example: "{a{b,c}}" expands to "ab" and "ac".
    683  * Example: "{a}" expands to "a".
    684  * Example: "{a,*.c}" expands to "a" and all "*.c" files that exist.
    685  *
    686  * Input:
    687  *	word		Entire word to expand
    688  *	brace		First curly brace in it
    689  *	path		Search path to use
    690  *	expansions	Place to store the expansions
    691  */
    692 static void
    693 DirExpandCurly(const char *word, const char *brace, SearchPath *path,
    694 	       StringList *expansions)
    695 {
    696     const char *prefix, *middle, *piece, *middle_end, *suffix;
    697     size_t prefix_len, suffix_len;
    698 
    699     /* Split the word into prefix '{' middle '}' suffix. */
    700 
    701     middle = brace + 1;
    702     middle_end = closing_brace(middle);
    703     if (*middle_end == '\0') {
    704 	Error("Unterminated {} clause \"%s\"", middle);
    705 	return;
    706     }
    707 
    708     prefix = word;
    709     prefix_len = (size_t)(brace - prefix);
    710     suffix = middle_end + 1;
    711     suffix_len = strlen(suffix);
    712 
    713     /* Split the middle into pieces, separated by commas. */
    714 
    715     piece = middle;
    716     while (piece < middle_end + 1) {
    717 	const char *piece_end = separator_comma(piece);
    718 	size_t piece_len = (size_t)(piece_end - piece);
    719 
    720 	char *file = concat3(prefix, prefix_len, piece, piece_len,
    721 			     suffix, suffix_len);
    722 
    723 	if (contains_wildcard(file)) {
    724 	    Dir_Expand(file, path, expansions);
    725 	    free(file);
    726 	} else {
    727 	    Lst_Append(expansions, file);
    728 	}
    729 
    730 	piece = piece_end + 1;	/* skip over the comma or closing brace */
    731     }
    732 }
    733 
    734 
    735 /* Expand the word in each of the directories from the path. */
    736 static void
    737 DirExpandPath(const char *word, SearchPath *path, StringList *expansions)
    738 {
    739     SearchPathNode *ln;
    740     for (ln = path->first; ln != NULL; ln = ln->next) {
    741 	CachedDir *dir = ln->datum;
    742 	DirMatchFiles(word, dir, expansions);
    743     }
    744 }
    745 
    746 static void
    747 PrintExpansions(StringList *expansions)
    748 {
    749     const char *sep = "";
    750     StringListNode *ln;
    751     for (ln = expansions->first; ln != NULL; ln = ln->next) {
    752 	const char *word = ln->datum;
    753 	debug_printf("%s%s", sep, word);
    754 	sep = " ";
    755     }
    756     debug_printf("\n");
    757 }
    758 
    759 /* Expand the given word into a list of words by globbing it, looking in the
    760  * directories on the given search path.
    761  *
    762  * Input:
    763  *	word		the word to expand
    764  *	path		the directories in which to find the files
    765  *	expansions	the list on which to place the results
    766  */
    767 void
    768 Dir_Expand(const char *word, SearchPath *path, StringList *expansions)
    769 {
    770     const char *cp;
    771 
    772     assert(path != NULL);
    773     assert(expansions != NULL);
    774 
    775     DIR_DEBUG1("Expanding \"%s\"... ", word);
    776 
    777     cp = strchr(word, '{');
    778     if (cp) {
    779 	DirExpandCurly(word, cp, path, expansions);
    780     } else {
    781 	cp = strchr(word, '/');
    782 	if (cp) {
    783 	    /*
    784 	     * The thing has a directory component -- find the first wildcard
    785 	     * in the string.
    786 	     */
    787 	    for (cp = word; *cp; cp++) {
    788 		if (*cp == '?' || *cp == '[' || *cp == '*') {
    789 		    break;
    790 		}
    791 	    }
    792 
    793 	    if (*cp != '\0') {
    794 		/*
    795 		 * Back up to the start of the component
    796 		 */
    797 		while (cp > word && *cp != '/') {
    798 		    cp--;
    799 		}
    800 		if (cp != word) {
    801 		    char *prefix = bmake_strsedup(word, cp + 1);
    802 		    /*
    803 		     * If the glob isn't in the first component, try and find
    804 		     * all the components up to the one with a wildcard.
    805 		     */
    806 		    char *dirpath = Dir_FindFile(prefix, path);
    807 		    free(prefix);
    808 		    /*
    809 		     * dirpath is null if can't find the leading component
    810 		     * XXX: Dir_FindFile won't find internal components.
    811 		     * i.e. if the path contains ../Etc/Object and we're
    812 		     * looking for Etc, it won't be found. Ah well.
    813 		     * Probably not important.
    814 		     */
    815 		    if (dirpath != NULL) {
    816 			char *dp = &dirpath[strlen(dirpath) - 1];
    817 			if (*dp == '/')
    818 			    *dp = '\0';
    819 			path = Lst_New();
    820 			(void)Dir_AddDir(path, dirpath);
    821 			DirExpandPath(cp + 1, path, expansions);
    822 			Lst_Free(path);
    823 		    }
    824 		} else {
    825 		    /*
    826 		     * Start the search from the local directory
    827 		     */
    828 		    DirExpandPath(word, path, expansions);
    829 		}
    830 	    } else {
    831 		/*
    832 		 * Return the file -- this should never happen.
    833 		 */
    834 		DirExpandPath(word, path, expansions);
    835 	    }
    836 	} else {
    837 	    /*
    838 	     * First the files in dot
    839 	     */
    840 	    DirMatchFiles(word, dot, expansions);
    841 
    842 	    /*
    843 	     * Then the files in every other directory on the path.
    844 	     */
    845 	    DirExpandPath(word, path, expansions);
    846 	}
    847     }
    848     if (DEBUG(DIR))
    849 	PrintExpansions(expansions);
    850 }
    851 
    852 /* Find if the file with the given name exists in the given path.
    853  * Return the freshly allocated path to the file, or NULL. */
    854 static char *
    855 DirLookup(CachedDir *dir, const char *base)
    856 {
    857     char *file;			/* the current filename to check */
    858 
    859     DIR_DEBUG1("   %s ...\n", dir->name);
    860 
    861     if (HashTable_FindEntry(&dir->files, base) == NULL)
    862 	return NULL;
    863 
    864     file = str_concat3(dir->name, "/", base);
    865     DIR_DEBUG1("   returning %s\n", file);
    866     dir->hits++;
    867     hits++;
    868     return file;
    869 }
    870 
    871 
    872 /* Find if the file with the given name exists in the given directory.
    873  * Return the freshly allocated path to the file, or NULL. */
    874 static char *
    875 DirLookupSubdir(CachedDir *dir, const char *name)
    876 {
    877     struct cached_stat cst;
    878     char *file = dir == dot ? bmake_strdup(name)
    879 			    : str_concat3(dir->name, "/", name);
    880 
    881     DIR_DEBUG1("checking %s ...\n", file);
    882 
    883     if (cached_stat(file, &cst) == 0) {
    884 	nearmisses++;
    885 	return file;
    886     }
    887     free(file);
    888     return NULL;
    889 }
    890 
    891 /* Find if the file with the given name exists in the given path.
    892  * Return the freshly allocated path to the file, the empty string, or NULL.
    893  * Returning the empty string means that the search should be terminated.
    894  */
    895 static char *
    896 DirLookupAbs(CachedDir *dir, const char *name, const char *cp)
    897 {
    898     const char *dnp;		/* pointer into dir->name */
    899     const char *np;		/* pointer into name */
    900 
    901     DIR_DEBUG1("   %s ...\n", dir->name);
    902 
    903     /*
    904      * If the file has a leading path component and that component
    905      * exactly matches the entire name of the current search
    906      * directory, we can attempt another cache lookup. And if we don't
    907      * have a hit, we can safely assume the file does not exist at all.
    908      */
    909     for (dnp = dir->name, np = name; *dnp != '\0' && *dnp == *np; dnp++, np++)
    910 	continue;
    911     if (*dnp != '\0' || np != cp - 1)
    912 	return NULL;
    913 
    914     if (HashTable_FindEntry(&dir->files, cp) == NULL) {
    915 	DIR_DEBUG0("   must be here but isn't -- returning\n");
    916 	return bmake_strdup("");	/* to terminate the search */
    917     }
    918 
    919     dir->hits++;
    920     hits++;
    921     DIR_DEBUG1("   returning %s\n", name);
    922     return bmake_strdup(name);
    923 }
    924 
    925 /* Find the file given on "." or curdir.
    926  * Return the freshly allocated path to the file, or NULL. */
    927 static char *
    928 DirFindDot(const char *name, const char *base)
    929 {
    930 
    931     if (HashTable_FindEntry(&dot->files, base) != NULL) {
    932 	DIR_DEBUG0("   in '.'\n");
    933 	hits++;
    934 	dot->hits++;
    935 	return bmake_strdup(name);
    936     }
    937 
    938     if (cur != NULL && HashTable_FindEntry(&cur->files, base) != NULL) {
    939 	DIR_DEBUG1("   in ${.CURDIR} = %s\n", cur->name);
    940 	hits++;
    941 	cur->hits++;
    942 	return str_concat3(cur->name, "/", base);
    943     }
    944 
    945     return NULL;
    946 }
    947 
    948 /* Find the file with the given name along the given search path.
    949  *
    950  * If the file is found in a directory that is not on the path
    951  * already (either 'name' is absolute or it is a relative path
    952  * [ dir1/.../dirn/file ] which exists below one of the directories
    953  * already on the search path), its directory is added to the end
    954  * of the path, on the assumption that there will be more files in
    955  * that directory later on. Sometimes this is true. Sometimes not.
    956  *
    957  * Input:
    958  *	name		the file to find
    959  *	path		the directories to search, or NULL
    960  *
    961  * Results:
    962  *	The freshly allocated path to the file, or NULL.
    963  */
    964 char *
    965 Dir_FindFile(const char *name, SearchPath *path)
    966 {
    967     SearchPathNode *ln;
    968     char *file;			/* the current filename to check */
    969     const char *base;		/* Terminal name of file */
    970     Boolean hasLastDot = FALSE;	/* true if we should search dot last */
    971     Boolean hasSlash;		/* true if 'name' contains a / */
    972     struct cached_stat cst;	/* Buffer for stat, if necessary */
    973     const char *trailing_dot = ".";
    974 
    975     /*
    976      * Find the final component of the name and note whether it has a
    977      * slash in it (the name, I mean)
    978      */
    979     base = strrchr(name, '/');
    980     if (base) {
    981 	hasSlash = TRUE;
    982 	base++;
    983     } else {
    984 	hasSlash = FALSE;
    985 	base = name;
    986     }
    987 
    988     DIR_DEBUG1("Searching for %s ...", name);
    989 
    990     if (path == NULL) {
    991 	DIR_DEBUG0("couldn't open path, file not found\n");
    992 	misses++;
    993 	return NULL;
    994     }
    995 
    996     if ((ln = path->first) != NULL) {
    997 	CachedDir *dir = ln->datum;
    998 	if (dir == dotLast) {
    999 	    hasLastDot = TRUE;
   1000 	    DIR_DEBUG0("[dot last]...");
   1001 	}
   1002     }
   1003     DIR_DEBUG0("\n");
   1004 
   1005     /*
   1006      * If there's no leading directory components or if the leading
   1007      * directory component is exactly `./', consult the cached contents
   1008      * of each of the directories on the search path.
   1009      */
   1010     if (!hasSlash || (base - name == 2 && *name == '.')) {
   1011 	/*
   1012 	 * We look through all the directories on the path seeking one which
   1013 	 * contains the final component of the given name.  If such a beast
   1014 	 * is found, we concatenate the directory name and the final
   1015 	 * component and return the resulting string. If we don't find any
   1016 	 * such thing, we go on to phase two...
   1017 	 *
   1018 	 * No matter what, we always look for the file in the current
   1019 	 * directory before anywhere else (unless we found the magic
   1020 	 * DOTLAST path, in which case we search it last) and we *do not*
   1021 	 * add the ./ to it if it exists.
   1022 	 * This is so there are no conflicts between what the user
   1023 	 * specifies (fish.c) and what pmake finds (./fish.c).
   1024 	 */
   1025 	if (!hasLastDot && (file = DirFindDot(name, base)) != NULL)
   1026 	    return file;
   1027 
   1028 	for (; ln != NULL; ln = ln->next) {
   1029 	    CachedDir *dir = ln->datum;
   1030 	    if (dir == dotLast)
   1031 		continue;
   1032 	    if ((file = DirLookup(dir, base)) != NULL)
   1033 		return file;
   1034 	}
   1035 
   1036 	if (hasLastDot && (file = DirFindDot(name, base)) != NULL)
   1037 	    return file;
   1038     }
   1039 
   1040     /*
   1041      * We didn't find the file on any directory in the search path.
   1042      * If the name doesn't contain a slash, that means it doesn't exist.
   1043      * If it *does* contain a slash, however, there is still hope: it
   1044      * could be in a subdirectory of one of the members of the search
   1045      * path. (eg. /usr/include and sys/types.h. The above search would
   1046      * fail to turn up types.h in /usr/include, but it *is* in
   1047      * /usr/include/sys/types.h).
   1048      * [ This no longer applies: If we find such a beast, we assume there
   1049      * will be more (what else can we assume?) and add all but the last
   1050      * component of the resulting name onto the search path (at the
   1051      * end).]
   1052      * This phase is only performed if the file is *not* absolute.
   1053      */
   1054     if (!hasSlash) {
   1055 	DIR_DEBUG0("   failed.\n");
   1056 	misses++;
   1057 	return NULL;
   1058     }
   1059 
   1060     if (*base == '\0') {
   1061 	/* we were given a trailing "/" */
   1062 	base = trailing_dot;
   1063     }
   1064 
   1065     if (name[0] != '/') {
   1066 	Boolean checkedDot = FALSE;
   1067 
   1068 	DIR_DEBUG0("   Trying subdirectories...\n");
   1069 
   1070 	if (!hasLastDot) {
   1071 	    if (dot) {
   1072 		checkedDot = TRUE;
   1073 		if ((file = DirLookupSubdir(dot, name)) != NULL)
   1074 		    return file;
   1075 	    }
   1076 	    if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
   1077 		return file;
   1078 	}
   1079 
   1080 	for (ln = path->first; ln != NULL; ln = ln->next) {
   1081 	    CachedDir *dir = ln->datum;
   1082 	    if (dir == dotLast)
   1083 		continue;
   1084 	    if (dir == dot) {
   1085 		if (checkedDot)
   1086 		    continue;
   1087 		checkedDot = TRUE;
   1088 	    }
   1089 	    if ((file = DirLookupSubdir(dir, name)) != NULL)
   1090 		return file;
   1091 	}
   1092 
   1093 	if (hasLastDot) {
   1094 	    if (dot && !checkedDot) {
   1095 		checkedDot = TRUE;
   1096 		if ((file = DirLookupSubdir(dot, name)) != NULL)
   1097 		    return file;
   1098 	    }
   1099 	    if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
   1100 		return file;
   1101 	}
   1102 
   1103 	if (checkedDot) {
   1104 	    /*
   1105 	     * Already checked by the given name, since . was in the path,
   1106 	     * so no point in proceeding...
   1107 	     */
   1108 	    DIR_DEBUG0("   Checked . already, returning NULL\n");
   1109 	    return NULL;
   1110 	}
   1111 
   1112     } else { /* name[0] == '/' */
   1113 
   1114 	/*
   1115 	 * For absolute names, compare directory path prefix against the
   1116 	 * the directory path of each member on the search path for an exact
   1117 	 * match. If we have an exact match on any member of the search path,
   1118 	 * use the cached contents of that member to lookup the final file
   1119 	 * component. If that lookup fails we can safely assume that the
   1120 	 * file does not exist at all.  This is signified by DirLookupAbs()
   1121 	 * returning an empty string.
   1122 	 */
   1123 	DIR_DEBUG0("   Trying exact path matches...\n");
   1124 
   1125 	if (!hasLastDot && cur &&
   1126 	    ((file = DirLookupAbs(cur, name, base)) != NULL)) {
   1127 	    if (file[0] == '\0') {
   1128 		free(file);
   1129 		return NULL;
   1130 	    }
   1131 	    return file;
   1132 	}
   1133 
   1134 	for (ln = path->first; ln != NULL; ln = ln->next) {
   1135 	    CachedDir *dir = ln->datum;
   1136 	    if (dir == dotLast)
   1137 		continue;
   1138 	    if ((file = DirLookupAbs(dir, name, base)) != NULL) {
   1139 		if (file[0] == '\0') {
   1140 		    free(file);
   1141 		    return NULL;
   1142 		}
   1143 		return file;
   1144 	    }
   1145 	}
   1146 
   1147 	if (hasLastDot && cur &&
   1148 	    ((file = DirLookupAbs(cur, name, base)) != NULL)) {
   1149 	    if (file[0] == '\0') {
   1150 		free(file);
   1151 		return NULL;
   1152 	    }
   1153 	    return file;
   1154 	}
   1155     }
   1156 
   1157     /*
   1158      * Didn't find it that way, either. Sigh. Phase 3. Add its directory
   1159      * onto the search path in any case, just in case, then look for the
   1160      * thing in the hash table. If we find it, grand. We return a new
   1161      * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
   1162      * Note that if the directory holding the file doesn't exist, this will
   1163      * do an extra search of the final directory on the path. Unless something
   1164      * weird happens, this search won't succeed and life will be groovy.
   1165      *
   1166      * Sigh. We cannot add the directory onto the search path because
   1167      * of this amusing case:
   1168      * $(INSTALLDIR)/$(FILE): $(FILE)
   1169      *
   1170      * $(FILE) exists in $(INSTALLDIR) but not in the current one.
   1171      * When searching for $(FILE), we will find it in $(INSTALLDIR)
   1172      * b/c we added it here. This is not good...
   1173      */
   1174 #if 0
   1175     if (base == trailing_dot) {
   1176 	base = strrchr(name, '/');
   1177 	base++;
   1178     }
   1179     base[-1] = '\0';
   1180     (void)Dir_AddDir(path, name);
   1181     base[-1] = '/';
   1182 
   1183     bigmisses++;
   1184     ln = Lst_Last(path);
   1185     if (ln == NULL) {
   1186 	return NULL;
   1187     } else {
   1188 	dir = LstNode_Datum(ln);
   1189     }
   1190 
   1191     if (Hash_FindEntry(&dir->files, base) != NULL) {
   1192 	return bmake_strdup(name);
   1193     } else {
   1194 	return NULL;
   1195     }
   1196 #else
   1197     DIR_DEBUG1("   Looking for \"%s\" ...\n", name);
   1198 
   1199     bigmisses++;
   1200     if (cached_stat(name, &cst) == 0) {
   1201 	return bmake_strdup(name);
   1202     }
   1203 
   1204     DIR_DEBUG0("   failed. Returning NULL\n");
   1205     return NULL;
   1206 #endif
   1207 }
   1208 
   1209 
   1210 /* Search for a path starting at a given directory and then working our way
   1211  * up towards the root.
   1212  *
   1213  * Input:
   1214  *	here		starting directory
   1215  *	search_path	the relative path we are looking for
   1216  *
   1217  * Results:
   1218  *	The found path, or NULL.
   1219  */
   1220 char *
   1221 Dir_FindHereOrAbove(const char *here, const char *search_path)
   1222 {
   1223     struct cached_stat cst;
   1224     char *dirbase, *dirbase_end;
   1225     char *try, *try_end;
   1226 
   1227     /* copy out our starting point */
   1228     dirbase = bmake_strdup(here);
   1229     dirbase_end = dirbase + strlen(dirbase);
   1230 
   1231     /* loop until we determine a result */
   1232     for (;;) {
   1233 
   1234 	/* try and stat(2) it ... */
   1235 	try = str_concat3(dirbase, "/", search_path);
   1236 	if (cached_stat(try, &cst) != -1) {
   1237 	    /*
   1238 	     * success!  if we found a file, chop off
   1239 	     * the filename so we return a directory.
   1240 	     */
   1241 	    if ((cst.cst_mode & S_IFMT) != S_IFDIR) {
   1242 		try_end = try + strlen(try);
   1243 		while (try_end > try && *try_end != '/')
   1244 		    try_end--;
   1245 		if (try_end > try)
   1246 		    *try_end = '\0';	/* chop! */
   1247 	    }
   1248 
   1249 	    free(dirbase);
   1250 	    return try;
   1251 	}
   1252 	free(try);
   1253 
   1254 	/*
   1255 	 * nope, we didn't find it.  if we used up dirbase we've
   1256 	 * reached the root and failed.
   1257 	 */
   1258 	if (dirbase_end == dirbase)
   1259 	    break;		/* failed! */
   1260 
   1261 	/*
   1262 	 * truncate dirbase from the end to move up a dir
   1263 	 */
   1264 	while (dirbase_end > dirbase && *dirbase_end != '/')
   1265 	    dirbase_end--;
   1266 	*dirbase_end = '\0';	/* chop! */
   1267     }
   1268 
   1269     free(dirbase);
   1270     return NULL;
   1271 }
   1272 
   1273 /* Search gn along dirSearchPath and store its modification time in gn->mtime.
   1274  * If no file is found, store 0 instead.
   1275  *
   1276  * The found file is stored in gn->path, unless the node already had a path. */
   1277 void
   1278 Dir_UpdateMTime(GNode *gn, Boolean recheck)
   1279 {
   1280     char *fullName;
   1281     struct cached_stat cst;
   1282 
   1283     if (gn->type & OP_ARCHV) {
   1284 	Arch_UpdateMTime(gn);
   1285 	return;
   1286     }
   1287 
   1288     if (gn->type & OP_PHONY) {
   1289 	gn->mtime = 0;
   1290 	return;
   1291     }
   1292 
   1293     if (gn->path == NULL) {
   1294 	if (gn->type & OP_NOPATH)
   1295 	    fullName = NULL;
   1296 	else {
   1297 	    fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
   1298 	    if (fullName == NULL && gn->flags & FROM_DEPEND &&
   1299 		!Lst_IsEmpty(gn->implicitParents)) {
   1300 		char *cp;
   1301 
   1302 		cp = strrchr(gn->name, '/');
   1303 		if (cp) {
   1304 		    /*
   1305 		     * This is an implied source, and it may have moved,
   1306 		     * see if we can find it via the current .PATH
   1307 		     */
   1308 		    cp++;
   1309 
   1310 		    fullName = Dir_FindFile(cp, Suff_FindPath(gn));
   1311 		    if (fullName) {
   1312 			/*
   1313 			 * Put the found file in gn->path
   1314 			 * so that we give that to the compiler.
   1315 			 */
   1316 			gn->path = bmake_strdup(fullName);
   1317 			if (!Job_RunTarget(".STALE", gn->fname))
   1318 			    fprintf(stdout,
   1319 				    "%s: %s, %d: ignoring stale %s for %s, "
   1320 				    "found %s\n", progname, gn->fname,
   1321 				    gn->lineno,
   1322 				    makeDependfile, gn->name, fullName);
   1323 		    }
   1324 		}
   1325 	    }
   1326 	    DIR_DEBUG2("Found '%s' as '%s'\n",
   1327 		       gn->name, fullName ? fullName : "(not found)");
   1328 	}
   1329     } else {
   1330 	fullName = gn->path;
   1331     }
   1332 
   1333     if (fullName == NULL)
   1334 	fullName = bmake_strdup(gn->name);
   1335 
   1336     if (cached_stats(fullName, &cst, recheck ? CST_UPDATE : CST_NONE) < 0) {
   1337 	if (gn->type & OP_MEMBER) {
   1338 	    if (fullName != gn->path)
   1339 		free(fullName);
   1340 	    Arch_UpdateMemberMTime(gn);
   1341 	    return;
   1342 	}
   1343 
   1344 	cst.cst_mtime = 0;
   1345     }
   1346 
   1347     if (fullName != NULL && gn->path == NULL)
   1348 	gn->path = fullName;
   1349 
   1350     gn->mtime = cst.cst_mtime;
   1351 }
   1352 
   1353 /* Read the list of filenames in the directory and store the result
   1354  * in openDirectories.
   1355  *
   1356  * If a path is given, append the directory to that path.
   1357  *
   1358  * Input:
   1359  *	path		The path to which the directory should be
   1360  *			added, or NULL to only add the directory to
   1361  *			openDirectories
   1362  *	name		The name of the directory to add.
   1363  *			The name is not normalized in any way.
   1364  */
   1365 CachedDir *
   1366 Dir_AddDir(SearchPath *path, const char *name)
   1367 {
   1368     CachedDir *dir = NULL;	/* the added directory */
   1369     DIR *d;
   1370     struct dirent *dp;
   1371 
   1372     if (path != NULL && strcmp(name, ".DOTLAST") == 0) {
   1373 	SearchPathNode *ln;
   1374 
   1375 	/* XXX: Linear search gets slow with thousands of entries. */
   1376 	for (ln = path->first; ln != NULL; ln = ln->next) {
   1377 	    CachedDir *pathDir = ln->datum;
   1378 	    if (strcmp(pathDir->name, name) == 0)
   1379 		return pathDir;
   1380 	}
   1381 
   1382 	dotLast->refCount++;
   1383 	Lst_Prepend(path, dotLast);
   1384     }
   1385 
   1386     if (path != NULL)
   1387 	dir = OpenDirs_Find(&openDirs, name);
   1388     if (dir != NULL) {
   1389 	if (Lst_FindDatum(path, dir) == NULL) {
   1390 	    dir->refCount++;
   1391 	    Lst_Append(path, dir);
   1392 	}
   1393 	return dir;
   1394     }
   1395 
   1396     DIR_DEBUG1("Caching %s ...", name);
   1397 
   1398     if ((d = opendir(name)) != NULL) {
   1399 	dir = bmake_malloc(sizeof *dir);
   1400 	dir->name = bmake_strdup(name);
   1401 	dir->hits = 0;
   1402 	dir->refCount = 1;
   1403 	HashTable_Init(&dir->files);
   1404 
   1405 	while ((dp = readdir(d)) != NULL) {
   1406 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
   1407 	    /*
   1408 	     * The sun directory library doesn't check for a 0 inode
   1409 	     * (0-inode slots just take up space), so we have to do
   1410 	     * it ourselves.
   1411 	     */
   1412 	    if (dp->d_fileno == 0) {
   1413 		continue;
   1414 	    }
   1415 #endif /* sun && d_ino */
   1416 	    (void)HashTable_CreateEntry(&dir->files, dp->d_name, NULL);
   1417 	}
   1418 	(void)closedir(d);
   1419 	OpenDirs_Add(&openDirs, dir);
   1420 	if (path != NULL)
   1421 	    Lst_Append(path, dir);
   1422     }
   1423     DIR_DEBUG0("done\n");
   1424     return dir;
   1425 }
   1426 
   1427 /* Return a copy of dirSearchPath, incrementing the reference counts for
   1428  * the contained directories. */
   1429 SearchPath *
   1430 Dir_CopyDirSearchPath(void)
   1431 {
   1432     SearchPath *path = Lst_New();
   1433     SearchPathNode *ln;
   1434     for (ln = dirSearchPath->first; ln != NULL; ln = ln->next) {
   1435 	CachedDir *dir = ln->datum;
   1436 	dir->refCount++;
   1437 	Lst_Append(path, dir);
   1438     }
   1439     return path;
   1440 }
   1441 
   1442 /*-
   1443  *-----------------------------------------------------------------------
   1444  * Dir_MakeFlags --
   1445  *	Make a string by taking all the directories in the given search
   1446  *	path and preceding them by the given flag. Used by the suffix
   1447  *	module to create variables for compilers based on suffix search
   1448  *	paths.
   1449  *
   1450  * Input:
   1451  *	flag		flag which should precede each directory
   1452  *	path		list of directories
   1453  *
   1454  * Results:
   1455  *	The string mentioned above. Note that there is no space between
   1456  *	the given flag and each directory. The empty string is returned if
   1457  *	Things don't go well.
   1458  *
   1459  * Side Effects:
   1460  *	None
   1461  *-----------------------------------------------------------------------
   1462  */
   1463 char *
   1464 Dir_MakeFlags(const char *flag, SearchPath *path)
   1465 {
   1466     Buffer buf;
   1467     SearchPathNode *ln;
   1468 
   1469     Buf_Init(&buf);
   1470 
   1471     if (path != NULL) {
   1472 	for (ln = path->first; ln != NULL; ln = ln->next) {
   1473 	    CachedDir *dir = ln->datum;
   1474 	    Buf_AddStr(&buf, " ");
   1475 	    Buf_AddStr(&buf, flag);
   1476 	    Buf_AddStr(&buf, dir->name);
   1477 	}
   1478     }
   1479 
   1480     return Buf_Destroy(&buf, FALSE);
   1481 }
   1482 
   1483 /* Nuke a directory descriptor, if possible. Callback procedure for the
   1484  * suffixes module when destroying a search path.
   1485  *
   1486  * Input:
   1487  *	dirp		The directory descriptor to nuke
   1488  */
   1489 void
   1490 Dir_Destroy(void *dirp)
   1491 {
   1492     CachedDir *dir = dirp;
   1493     dir->refCount--;
   1494 
   1495     if (dir->refCount == 0) {
   1496 	OpenDirs_Remove(&openDirs, dir->name);
   1497 
   1498 	HashTable_Done(&dir->files);
   1499 	free(dir->name);
   1500 	free(dir);
   1501     }
   1502 }
   1503 
   1504 /* Clear out all elements from the given search path.
   1505  * The path is set to the empty list but is not destroyed. */
   1506 void
   1507 Dir_ClearPath(SearchPath *path)
   1508 {
   1509     while (!Lst_IsEmpty(path)) {
   1510 	CachedDir *dir = Lst_Dequeue(path);
   1511 	Dir_Destroy(dir);
   1512     }
   1513 }
   1514 
   1515 
   1516 /* Concatenate two paths, adding the second to the end of the first,
   1517  * skipping duplicates. */
   1518 void
   1519 Dir_Concat(SearchPath *dst, SearchPath *src)
   1520 {
   1521     SearchPathNode *ln;
   1522 
   1523     for (ln = src->first; ln != NULL; ln = ln->next) {
   1524 	CachedDir *dir = ln->datum;
   1525 	if (Lst_FindDatum(dst, dir) == NULL) {
   1526 	    dir->refCount++;
   1527 	    Lst_Append(dst, dir);
   1528 	}
   1529     }
   1530 }
   1531 
   1532 static int
   1533 percentage(int num, int den)
   1534 {
   1535     return den != 0 ? num * 100 / den : 0;
   1536 }
   1537 
   1538 /********** DEBUG INFO **********/
   1539 void
   1540 Dir_PrintDirectories(void)
   1541 {
   1542     CachedDirListNode *ln;
   1543 
   1544     debug_printf("#*** Directory Cache:\n");
   1545     debug_printf("# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
   1546 		 hits, misses, nearmisses, bigmisses,
   1547 		 percentage(hits, hits + bigmisses + nearmisses));
   1548     debug_printf("# %-20s referenced\thits\n", "directory");
   1549 
   1550     for (ln = openDirs.list->first; ln != NULL; ln = ln->next) {
   1551 	CachedDir *dir = ln->datum;
   1552 	debug_printf("# %-20s %10d\t%4d\n", dir->name, dir->refCount,
   1553 		     dir->hits);
   1554     }
   1555 }
   1556 
   1557 void
   1558 Dir_PrintPath(SearchPath *path)
   1559 {
   1560     SearchPathNode *node;
   1561     for (node = path->first; node != NULL; node = node->next) {
   1562 	const CachedDir *dir = node->datum;
   1563 	debug_printf("%s ", dir->name);
   1564     }
   1565 }
   1566