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