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