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