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