Home | History | Annotate | Line # | Download | only in make
dir.c revision 1.155
      1 /*	$NetBSD: dir.c,v 1.155 2020/10/02 22:20:25 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  * dir.c --
     74  *	Directory searching using wildcards and/or normal names...
     75  *	Used both for source wildcarding in the Makefile and for finding
     76  *	implicit sources.
     77  *
     78  * The interface for this module is:
     79  *	Dir_Init	Initialize the module.
     80  *
     81  *	Dir_InitCur	Set the cur CachedDir.
     82  *
     83  *	Dir_InitDot	Set the dot CachedDir.
     84  *
     85  *	Dir_End		Cleanup the module.
     86  *
     87  *	Dir_SetPATH	Set ${.PATH} to reflect state of dirSearchPath.
     88  *
     89  *	Dir_HasWildcards
     90  *			Returns TRUE if the name given it needs to
     91  *			be wildcard-expanded.
     92  *
     93  *	Dir_Expand	Given a pattern and a path, return a Lst of names
     94  *			which match the pattern on the search path.
     95  *
     96  *	Dir_FindFile	Searches for a file on a given search path.
     97  *			If it exists, the entire path is returned.
     98  *			Otherwise NULL is returned.
     99  *
    100  *	Dir_FindHereOrAbove
    101  *			Search for a path in the current directory and
    102  *			then all the directories above it in turn until
    103  *			the path is found or we reach the root ("/").
    104  *
    105  *	Dir_MTime	Return the modification time of a node. The file
    106  *			is searched for along the default search path.
    107  *			The path and mtime fields of the node are filled in.
    108  *
    109  *	Dir_AddDir	Add a directory to a search path.
    110  *
    111  *	Dir_MakeFlags	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  *	Dir_Destroy	Destroy an element of a search path. Frees up all
    117  *			things that can be freed for the element as long
    118  *			as the element is no longer referenced by any other
    119  *			search path.
    120  *
    121  *	Dir_ClearPath	Resets a search path to the empty list.
    122  *
    123  * For debugging:
    124  *	Dir_PrintDirectories	Print stats about the directory cache.
    125  */
    126 
    127 #include <sys/types.h>
    128 #include <sys/stat.h>
    129 
    130 #include <dirent.h>
    131 #include <errno.h>
    132 #include <stdio.h>
    133 
    134 #include "make.h"
    135 #include "dir.h"
    136 #include "job.h"
    137 
    138 /*	"@(#)dir.c	8.2 (Berkeley) 1/2/94"	*/
    139 MAKE_RCSID("$NetBSD: dir.c,v 1.155 2020/10/02 22:20:25 rillig Exp $");
    140 
    141 #define DIR_DEBUG0(text) DEBUG0(DIR, text)
    142 #define DIR_DEBUG1(fmt, arg1) DEBUG1(DIR, fmt, arg1)
    143 #define DIR_DEBUG2(fmt, arg1, arg2) DEBUG2(DIR, fmt, arg1, arg2)
    144 
    145 /*
    146  *	A search path consists of a list of CachedDir structures. A CachedDir
    147  *	has in it the name of the directory and a hash table of all the files
    148  *	in the directory. This is used to cut down on the number of system
    149  *	calls necessary to find implicit dependents and their like. Since
    150  *	these searches are made before any actions are taken, we need not
    151  *	worry about the directory changing due to creation commands. If this
    152  *	hampers the style of some makefiles, they must be changed.
    153  *
    154  *	A list of all previously-read directories is kept in the
    155  *	openDirectories Lst. This list is checked first before a directory
    156  *	is opened.
    157  *
    158  *	The need for the caching of whole directories is brought about by
    159  *	the multi-level transformation code in suff.c, which tends to search
    160  *	for far more files than regular make does. In the initial
    161  *	implementation, the amount of time spent performing "stat" calls was
    162  *	truly astronomical. The problem with hashing at the start is,
    163  *	of course, that pmake doesn't then detect changes to these directories
    164  *	during the course of the make. Three possibilities suggest themselves:
    165  *
    166  *	    1) just use stat to test for a file's existence. As mentioned
    167  *	       above, this is very inefficient due to the number of checks
    168  *	       engendered by the multi-level transformation code.
    169  *	    2) use readdir() and company to search the directories, keeping
    170  *	       them open between checks. I have tried this and while it
    171  *	       didn't slow down the process too much, it could severely
    172  *	       affect the amount of parallelism available as each directory
    173  *	       open would take another file descriptor out of play for
    174  *	       handling I/O for another job. Given that it is only recently
    175  *	       that UNIX OS's have taken to allowing more than 20 or 32
    176  *	       file descriptors for a process, this doesn't seem acceptable
    177  *	       to me.
    178  *	    3) record the mtime of the directory in the CachedDir structure and
    179  *	       verify the directory hasn't changed since the contents were
    180  *	       hashed. This will catch the creation or deletion of files,
    181  *	       but not the updating of files. However, since it is the
    182  *	       creation and deletion that is the problem, this could be
    183  *	       a good thing to do. Unfortunately, if the directory (say ".")
    184  *	       were fairly large and changed fairly frequently, the constant
    185  *	       rehashing could seriously degrade performance. It might be
    186  *	       good in such cases to keep track of the number of rehashes
    187  *	       and if the number goes over a (small) limit, resort to using
    188  *	       stat in its place.
    189  *
    190  *	An additional thing to consider is that pmake is used primarily
    191  *	to create C programs and until recently pcc-based compilers refused
    192  *	to allow you to specify where the resulting object file should be
    193  *	placed. This forced all objects to be created in the current
    194  *	directory. This isn't meant as a full excuse, just an explanation of
    195  *	some of the reasons for the caching used here.
    196  *
    197  *	One more note: the location of a target's file is only performed
    198  *	on the downward traversal of the graph and then only for terminal
    199  *	nodes in the graph. This could be construed as wrong in some cases,
    200  *	but prevents inadvertent modification of files when the "installed"
    201  *	directory for a file is provided in the search path.
    202  *
    203  *	Another data structure maintained by this module is an mtime
    204  *	cache used when the searching of cached directories fails to find
    205  *	a file. In the past, Dir_FindFile would simply perform an access()
    206  *	call in such a case to determine if the file could be found using
    207  *	just the name given. When this hit, however, all that was gained
    208  *	was the knowledge that the file existed. Given that an access() is
    209  *	essentially a stat() without the copyout() call, and that the same
    210  *	filesystem overhead would have to be incurred in Dir_MTime, it made
    211  *	sense to replace the access() with a stat() and record the mtime
    212  *	in a cache for when Dir_MTime was actually called.
    213  */
    214 
    215 typedef List CachedDirList;
    216 typedef ListNode CachedDirListNode;
    217 
    218 typedef ListNode SearchPathNode;
    219 
    220 SearchPath *dirSearchPath;		/* main search path */
    221 
    222 /* A list of cached directories, with fast lookup by directory name. */
    223 typedef struct OpenDirs {
    224     CachedDirList *list;
    225     Hash_Table /* of CachedDirListNode */ table;
    226 } OpenDirs;
    227 
    228 static void
    229 OpenDirs_Init(OpenDirs *odirs)
    230 {
    231     odirs->list = Lst_Init();
    232     Hash_InitTable(&odirs->table);
    233 }
    234 
    235 static void MAKE_ATTR_UNUSED
    236 OpenDirs_Done(OpenDirs *odirs)
    237 {
    238     Dir_ClearPath(odirs->list);
    239     Lst_Free(odirs->list);
    240     Hash_DeleteTable(&odirs->table);
    241 }
    242 
    243 static CachedDir *
    244 OpenDirs_Find(OpenDirs *odirs, const char *name)
    245 {
    246     CachedDirListNode *ln = Hash_FindValue(&odirs->table, name);
    247     return ln != NULL ? ln->datum : NULL;
    248 }
    249 
    250 static void
    251 OpenDirs_Add(OpenDirs *odirs, CachedDir *cdir)
    252 {
    253     Hash_Entry *he = Hash_FindEntry(&odirs->table, cdir->name);
    254     if (he != NULL)
    255 	return;
    256     he = Hash_CreateEntry(&odirs->table, cdir->name, NULL);
    257     Lst_Append(odirs->list, cdir);
    258     Hash_SetValue(he, odirs->list->last);
    259 }
    260 
    261 static void
    262 OpenDirs_Remove(OpenDirs *odirs, const char *name)
    263 {
    264     Hash_Entry *he = Hash_FindEntry(&odirs->table, name);
    265     CachedDirListNode *ln;
    266     if (he == NULL)
    267 	return;
    268     ln = Hash_GetValue(he);
    269     Hash_DeleteEntry(&odirs->table, he);
    270     Lst_Remove(odirs->list, ln);
    271 }
    272 
    273 static OpenDirs openDirs;	/* the list of all open directories */
    274 
    275 /*
    276  * Variables for gathering statistics on the efficiency of the hashing
    277  * mechanism.
    278  */
    279 static int hits;		/* Found in directory cache */
    280 static int misses;		/* Sad, but not evil misses */
    281 static int nearmisses;		/* Found under search path */
    282 static int bigmisses;		/* Sought by itself */
    283 
    284 static CachedDir *dot;		/* contents of current directory */
    285 static CachedDir *cur;		/* contents of current directory, if not dot */
    286 static CachedDir *dotLast;	/* a fake path entry indicating we need to
    287 				 * look for . last */
    288 
    289 /* Results of doing a last-resort stat in Dir_FindFile -- if we have to go to
    290  * the system to find the file, we might as well have its mtime on record.
    291  *
    292  * XXX: If this is done way early, there's a chance other rules will have
    293  * already updated the file, in which case we'll update it again. Generally,
    294  * there won't be two rules to update a single file, so this should be ok,
    295  * but... */
    296 static Hash_Table mtimes;
    297 
    298 static Hash_Table lmtimes;	/* same as mtimes but for lstat */
    299 
    300 /*
    301  * We use stat(2) a lot, cache the results.
    302  * mtime and mode are all we care about.
    303  */
    304 struct cache_st {
    305     time_t lmtime;		/* lstat */
    306     time_t mtime;		/* stat */
    307     mode_t mode;
    308 };
    309 
    310 /* minimize changes below */
    311 typedef enum {
    312     CST_LSTAT = 0x01,		/* call lstat(2) instead of stat(2) */
    313     CST_UPDATE = 0x02		/* ignore existing cached entry */
    314 } CachedStatsFlags;
    315 
    316 /* Returns 0 and the result of stat(2) or lstat(2) in *mst, or -1 on error. */
    317 static int
    318 cached_stats(Hash_Table *htp, const char *pathname, struct make_stat *mst,
    319 	     CachedStatsFlags flags)
    320 {
    321     Hash_Entry *entry;
    322     struct stat sys_st;
    323     struct cache_st *cst;
    324     int rc;
    325 
    326     if (!pathname || !pathname[0])
    327 	return -1;
    328 
    329     entry = Hash_FindEntry(htp, pathname);
    330 
    331     if (entry && !(flags & CST_UPDATE)) {
    332 	cst = Hash_GetValue(entry);
    333 
    334 	mst->mst_mode = cst->mode;
    335 	mst->mst_mtime = (flags & CST_LSTAT) ? cst->lmtime : cst->mtime;
    336 	if (mst->mst_mtime) {
    337 	    DIR_DEBUG2("Using cached time %s for %s\n",
    338 		       Targ_FmtTime(mst->mst_mtime), pathname);
    339 	    return 0;
    340 	}
    341     }
    342 
    343     rc = (flags & CST_LSTAT)
    344 	 ? lstat(pathname, &sys_st)
    345 	 : stat(pathname, &sys_st);
    346     if (rc == -1)
    347 	return -1;
    348 
    349     if (sys_st.st_mtime == 0)
    350 	sys_st.st_mtime = 1;	/* avoid confusion with missing file */
    351 
    352     mst->mst_mode = sys_st.st_mode;
    353     mst->mst_mtime = sys_st.st_mtime;
    354 
    355     if (entry == NULL)
    356 	entry = Hash_CreateEntry(htp, pathname, NULL);
    357     if (Hash_GetValue(entry) == NULL) {
    358 	Hash_SetValue(entry, bmake_malloc(sizeof(*cst)));
    359 	memset(Hash_GetValue(entry), 0, sizeof(*cst));
    360     }
    361     cst = Hash_GetValue(entry);
    362     if (flags & CST_LSTAT) {
    363 	cst->lmtime = sys_st.st_mtime;
    364     } else {
    365 	cst->mtime = sys_st.st_mtime;
    366     }
    367     cst->mode = sys_st.st_mode;
    368     DIR_DEBUG2("   Caching %s for %s\n",
    369 	       Targ_FmtTime(sys_st.st_mtime), pathname);
    370 
    371     return 0;
    372 }
    373 
    374 int
    375 cached_stat(const char *pathname, struct make_stat *st)
    376 {
    377     return cached_stats(&mtimes, pathname, st, 0);
    378 }
    379 
    380 int
    381 cached_lstat(const char *pathname, struct make_stat *st)
    382 {
    383     return cached_stats(&lmtimes, pathname, st, CST_LSTAT);
    384 }
    385 
    386 /* Initialize things for this module. */
    387 void
    388 Dir_Init(void)
    389 {
    390     dirSearchPath = Lst_Init();
    391     OpenDirs_Init(&openDirs);
    392     Hash_InitTable(&mtimes);
    393     Hash_InitTable(&lmtimes);
    394 }
    395 
    396 void
    397 Dir_InitDir(const char *cdname)
    398 {
    399     Dir_InitCur(cdname);
    400 
    401     dotLast = bmake_malloc(sizeof(CachedDir));
    402     dotLast->refCount = 1;
    403     dotLast->hits = 0;
    404     dotLast->name = bmake_strdup(".DOTLAST");
    405     Hash_InitTable(&dotLast->files);
    406 }
    407 
    408 /*
    409  * Called by Dir_InitDir and whenever .CURDIR is assigned to.
    410  */
    411 void
    412 Dir_InitCur(const char *cdname)
    413 {
    414     CachedDir *dir;
    415 
    416     if (cdname != NULL) {
    417 	/*
    418 	 * Our build directory is not the same as our source directory.
    419 	 * Keep this one around too.
    420 	 */
    421 	if ((dir = Dir_AddDir(NULL, cdname))) {
    422 	    dir->refCount++;
    423 	    if (cur && cur != dir) {
    424 		/*
    425 		 * We've been here before, cleanup.
    426 		 */
    427 		cur->refCount--;
    428 		Dir_Destroy(cur);
    429 	    }
    430 	    cur = dir;
    431 	}
    432     }
    433 }
    434 
    435 /* (Re)initialize "dot" (current/object directory) path hash.
    436  * Some directories may be opened. */
    437 void
    438 Dir_InitDot(void)
    439 {
    440     if (dot != NULL) {
    441 	/* Remove old entry from openDirs, but do not destroy. */
    442 	OpenDirs_Remove(&openDirs, dot->name);
    443     }
    444 
    445     dot = Dir_AddDir(NULL, ".");
    446 
    447     if (dot == NULL) {
    448 	Error("Cannot open `.' (%s)", strerror(errno));
    449 	exit(1);
    450     }
    451 
    452     /*
    453      * We always need to have dot around, so we increment its reference count
    454      * to make sure it's not destroyed.
    455      */
    456     dot->refCount++;
    457     Dir_SetPATH();		/* initialize */
    458 }
    459 
    460 /* Clean up things for this module. */
    461 void
    462 Dir_End(void)
    463 {
    464 #ifdef CLEANUP
    465     if (cur) {
    466 	cur->refCount--;
    467 	Dir_Destroy(cur);
    468     }
    469     dot->refCount--;
    470     dotLast->refCount--;
    471     Dir_Destroy(dotLast);
    472     Dir_Destroy(dot);
    473     Dir_ClearPath(dirSearchPath);
    474     Lst_Free(dirSearchPath);
    475     OpenDirs_Done(&openDirs);
    476     Hash_DeleteTable(&mtimes);
    477 #endif
    478 }
    479 
    480 /*
    481  * We want ${.PATH} to indicate the order in which we will actually
    482  * search, so we rebuild it after any .PATH: target.
    483  * This is the simplest way to deal with the effect of .DOTLAST.
    484  */
    485 void
    486 Dir_SetPATH(void)
    487 {
    488     CachedDirListNode *ln;
    489     Boolean hasLastDot = FALSE;	/* true if we should search dot last */
    490 
    491     Var_Delete(".PATH", VAR_GLOBAL);
    492 
    493     Lst_Open(dirSearchPath);
    494     if ((ln = Lst_First(dirSearchPath)) != NULL) {
    495 	CachedDir *dir = LstNode_Datum(ln);
    496 	if (dir == dotLast) {
    497 	    hasLastDot = TRUE;
    498 	    Var_Append(".PATH", dotLast->name, VAR_GLOBAL);
    499 	}
    500     }
    501 
    502     if (!hasLastDot) {
    503 	if (dot)
    504 	    Var_Append(".PATH", dot->name, VAR_GLOBAL);
    505 	if (cur)
    506 	    Var_Append(".PATH", cur->name, VAR_GLOBAL);
    507     }
    508 
    509     while ((ln = Lst_Next(dirSearchPath)) != NULL) {
    510 	CachedDir *dir = LstNode_Datum(ln);
    511 	if (dir == dotLast)
    512 	    continue;
    513 	if (dir == dot && hasLastDot)
    514 	    continue;
    515 	Var_Append(".PATH", dir->name, VAR_GLOBAL);
    516     }
    517 
    518     if (hasLastDot) {
    519 	if (dot)
    520 	    Var_Append(".PATH", dot->name, VAR_GLOBAL);
    521 	if (cur)
    522 	    Var_Append(".PATH", cur->name, VAR_GLOBAL);
    523     }
    524     Lst_Close(dirSearchPath);
    525 }
    526 
    527 /* See if the CachedDir structure describes the same directory as the
    528  * given one by comparing their names. Called from Dir_AddDir via
    529  * Lst_Find when searching the list of open directories. */
    530 static Boolean
    531 DirFindName(const void *p, const void *desiredName)
    532 {
    533     const CachedDir *dir = p;
    534     return strcmp(dir->name, desiredName) == 0;
    535 }
    536 
    537 /* See if the given name has any wildcard characters in it. Be careful not to
    538  * expand unmatching brackets or braces.
    539  *
    540  * XXX: This code is not 100% correct ([^]] fails etc.). I really don't think
    541  * that make(1) should be expanding patterns, because then you have to set a
    542  * mechanism for escaping the expansion!
    543  *
    544  * Input:
    545  *	name		name to check
    546  *
    547  * Results:
    548  *	returns TRUE if the word should be expanded, FALSE otherwise
    549  */
    550 Boolean
    551 Dir_HasWildcards(const char *name)
    552 {
    553     const char *cp;
    554     Boolean wild = FALSE;
    555     int braces = 0, brackets = 0;
    556 
    557     for (cp = name; *cp; cp++) {
    558 	switch (*cp) {
    559 	case '{':
    560 	    braces++;
    561 	    wild = TRUE;
    562 	    break;
    563 	case '}':
    564 	    braces--;
    565 	    break;
    566 	case '[':
    567 	    brackets++;
    568 	    wild = TRUE;
    569 	    break;
    570 	case ']':
    571 	    brackets--;
    572 	    break;
    573 	case '?':
    574 	case '*':
    575 	    wild = TRUE;
    576 	    break;
    577 	default:
    578 	    break;
    579 	}
    580     }
    581     return wild && brackets == 0 && braces == 0;
    582 }
    583 
    584 /*-
    585  *-----------------------------------------------------------------------
    586  * DirMatchFiles --
    587  *	Given a pattern and a CachedDir structure, see if any files
    588  *	match the pattern and add their names to the 'expansions' list if
    589  *	any do. This is incomplete -- it doesn't take care of patterns like
    590  *	src / *src / *.c properly (just *.c on any of the directories), but it
    591  *	will do for now.
    592  *
    593  * Input:
    594  *	pattern		Pattern to look for
    595  *	dir		Directory to search
    596  *	expansion	Place to store the results
    597  *
    598  * Side Effects:
    599  *	File names are added to the expansions lst. The directory will be
    600  *	fully hashed when this is done.
    601  *-----------------------------------------------------------------------
    602  */
    603 static void
    604 DirMatchFiles(const char *pattern, CachedDir *dir, StringList *expansions)
    605 {
    606     Hash_Search search;		/* Index into the directory's table */
    607     Hash_Entry *entry;		/* Current entry in the table */
    608     Boolean isDot;		/* TRUE if the directory being searched is . */
    609 
    610     isDot = (dir->name[0] == '.' && dir->name[1] == '\0');
    611 
    612     for (entry = Hash_EnumFirst(&dir->files, &search);
    613 	 entry != NULL;
    614 	 entry = Hash_EnumNext(&search))
    615     {
    616 	/*
    617 	 * See if the file matches the given pattern. Note we follow the UNIX
    618 	 * convention that dot files will only be found if the pattern
    619 	 * begins with a dot (note also that as a side effect of the hashing
    620 	 * scheme, .* won't match . or .. since they aren't hashed).
    621 	 */
    622 	if (Str_Match(entry->name, pattern) &&
    623 	    ((entry->name[0] != '.') ||
    624 	     (pattern[0] == '.')))
    625 	{
    626 	    Lst_Append(expansions,
    627 		       (isDot ? bmake_strdup(entry->name) :
    628 			str_concat3(dir->name, "/", entry->name)));
    629 	}
    630     }
    631 }
    632 
    633 /* Find the next closing brace in the string, taking nested braces into
    634  * account. */
    635 static const char *
    636 closing_brace(const char *p)
    637 {
    638     int nest = 0;
    639     while (*p != '\0') {
    640 	if (*p == '}' && nest == 0)
    641 	    break;
    642 	if (*p == '{')
    643 	    nest++;
    644 	if (*p == '}')
    645 	    nest--;
    646 	p++;
    647     }
    648     return p;
    649 }
    650 
    651 /* Find the next closing brace or comma in the string, taking nested braces
    652  * into account. */
    653 static const char *
    654 separator_comma(const char *p)
    655 {
    656     int nest = 0;
    657     while (*p != '\0') {
    658 	if ((*p == '}' || *p == ',') && nest == 0)
    659 	    break;
    660 	if (*p == '{')
    661 	    nest++;
    662 	if (*p == '}')
    663 	    nest--;
    664 	p++;
    665     }
    666     return p;
    667 }
    668 
    669 static Boolean
    670 contains_wildcard(const char *p)
    671 {
    672     for (; *p != '\0'; p++) {
    673 	switch (*p) {
    674 	case '*':
    675 	case '?':
    676 	case '{':
    677 	case '[':
    678 	    return TRUE;
    679 	}
    680     }
    681     return FALSE;
    682 }
    683 
    684 static char *
    685 concat3(const char *a, size_t a_len, const char *b, size_t b_len,
    686 	const char *c, size_t c_len)
    687 {
    688     size_t s_len = a_len + b_len + c_len;
    689     char *s = bmake_malloc(s_len + 1);
    690     memcpy(s, a, a_len);
    691     memcpy(s + a_len, b, b_len);
    692     memcpy(s + a_len + b_len, c, c_len);
    693     s[s_len] = '\0';
    694     return s;
    695 }
    696 
    697 /*-
    698  *-----------------------------------------------------------------------
    699  * DirExpandCurly --
    700  *	Expand curly braces like the C shell. Does this recursively.
    701  *	Note the special case: if after the piece of the curly brace is
    702  *	done there are no wildcard characters in the result, the result is
    703  *	placed on the list WITHOUT CHECKING FOR ITS EXISTENCE.
    704  *
    705  * Input:
    706  *	word		Entire word to expand
    707  *	brace		First curly brace in it
    708  *	path		Search path to use
    709  *	expansions	Place to store the expansions
    710  *
    711  * Results:
    712  *	None.
    713  *
    714  * Side Effects:
    715  *	The given list is filled with the expansions...
    716  *
    717  *-----------------------------------------------------------------------
    718  */
    719 static void
    720 DirExpandCurly(const char *word, const char *brace, SearchPath *path,
    721 	       StringList *expansions)
    722 {
    723     const char *prefix, *middle, *piece, *middle_end, *suffix;
    724     size_t prefix_len, suffix_len;
    725 
    726     /* Split the word into prefix '{' middle '}' suffix. */
    727 
    728     middle = brace + 1;
    729     middle_end = closing_brace(middle);
    730     if (*middle_end == '\0') {
    731 	Error("Unterminated {} clause \"%s\"", middle);
    732 	return;
    733     }
    734 
    735     prefix = word;
    736     prefix_len = (size_t)(brace - prefix);
    737     suffix = middle_end + 1;
    738     suffix_len = strlen(suffix);
    739 
    740     /* Split the middle into pieces, separated by commas. */
    741 
    742     piece = middle;
    743     while (piece < middle_end + 1) {
    744 	const char *piece_end = separator_comma(piece);
    745 	size_t piece_len = (size_t)(piece_end - piece);
    746 
    747 	char *file = concat3(prefix, prefix_len, piece, piece_len,
    748 			     suffix, suffix_len);
    749 
    750 	if (contains_wildcard(file)) {
    751 	    Dir_Expand(file, path, expansions);
    752 	    free(file);
    753 	} else {
    754 	    Lst_Append(expansions, file);
    755 	}
    756 
    757 	piece = piece_end + 1;	/* skip over the comma or closing brace */
    758     }
    759 }
    760 
    761 
    762 /*-
    763  *-----------------------------------------------------------------------
    764  * DirExpandInt --
    765  *	Internal expand routine. Passes through the directories in the
    766  *	path one by one, calling DirMatchFiles for each. NOTE: This still
    767  *	doesn't handle patterns in directories...
    768  *
    769  * Input:
    770  *	word		Word to expand
    771  *	path		Directory in which to look
    772  *	expansions	Place to store the result
    773  *
    774  * Results:
    775  *	None.
    776  *
    777  * Side Effects:
    778  *	Things are added to the expansions list.
    779  *
    780  *-----------------------------------------------------------------------
    781  */
    782 static void
    783 DirExpandInt(const char *word, SearchPath *path, StringList *expansions)
    784 {
    785     SearchPathNode *ln;
    786     for (ln = path->first; ln != NULL; ln = ln->next) {
    787 	CachedDir *dir = ln->datum;
    788 	DirMatchFiles(word, dir, expansions);
    789     }
    790 }
    791 
    792 static void
    793 DirPrintExpansions(StringList *words)
    794 {
    795     StringListNode *ln;
    796     for (ln = words->first; ln != NULL; ln = ln->next) {
    797 	const char *word = ln->datum;
    798 	debug_printf("%s ", word);
    799     }
    800     debug_printf("\n");
    801 }
    802 
    803 /*-
    804  *-----------------------------------------------------------------------
    805  * Dir_Expand  --
    806  *	Expand the given word into a list of words by globbing it looking
    807  *	in the directories on the given search path.
    808  *
    809  * Input:
    810  *	word		the word to expand
    811  *	path		the list of directories in which to find the
    812  *			resulting files
    813  *	expansions	the list on which to place the results
    814  *
    815  * Results:
    816  *	A list of words consisting of the files which exist along the search
    817  *	path matching the given pattern.
    818  *
    819  * Side Effects:
    820  *	Directories may be opened. Who knows?
    821  *	Undefined behavior if the word is really in read-only memory.
    822  *-----------------------------------------------------------------------
    823  */
    824 void
    825 Dir_Expand(const char *word, SearchPath *path, StringList *expansions)
    826 {
    827     const char *cp;
    828 
    829     assert(path != NULL);
    830     assert(expansions != NULL);
    831 
    832     DIR_DEBUG1("Expanding \"%s\"... ", word);
    833 
    834     cp = strchr(word, '{');
    835     if (cp) {
    836 	DirExpandCurly(word, cp, path, expansions);
    837     } else {
    838 	cp = strchr(word, '/');
    839 	if (cp) {
    840 	    /*
    841 	     * The thing has a directory component -- find the first wildcard
    842 	     * in the string.
    843 	     */
    844 	    for (cp = word; *cp; cp++) {
    845 		if (*cp == '?' || *cp == '[' || *cp == '*' || *cp == '{') {
    846 		    break;
    847 		}
    848 	    }
    849 	    if (*cp == '{') {
    850 		/*
    851 		 * This one will be fun.
    852 		 */
    853 		DirExpandCurly(word, cp, path, expansions);
    854 		return;
    855 	    } else if (*cp != '\0') {
    856 		/*
    857 		 * Back up to the start of the component
    858 		 */
    859 		while (cp > word && *cp != '/') {
    860 		    cp--;
    861 		}
    862 		if (cp != word) {
    863 		    char sc;
    864 		    char *dirpath;
    865 		    /*
    866 		     * If the glob isn't in the first component, try and find
    867 		     * all the components up to the one with a wildcard.
    868 		     */
    869 		    sc = cp[1];
    870 		    ((char *)UNCONST(cp))[1] = '\0';
    871 		    dirpath = Dir_FindFile(word, path);
    872 		    ((char *)UNCONST(cp))[1] = sc;
    873 		    /*
    874 		     * dirpath is null if can't find the leading component
    875 		     * XXX: Dir_FindFile won't find internal components.
    876 		     * i.e. if the path contains ../Etc/Object and we're
    877 		     * looking for Etc, it won't be found. Ah well.
    878 		     * Probably not important.
    879 		     */
    880 		    if (dirpath != NULL) {
    881 			char *dp = &dirpath[strlen(dirpath) - 1];
    882 			if (*dp == '/')
    883 			    *dp = '\0';
    884 			path = Lst_Init();
    885 			(void)Dir_AddDir(path, dirpath);
    886 			DirExpandInt(cp + 1, path, expansions);
    887 			Lst_Free(path);
    888 		    }
    889 		} else {
    890 		    /*
    891 		     * Start the search from the local directory
    892 		     */
    893 		    DirExpandInt(word, path, expansions);
    894 		}
    895 	    } else {
    896 		/*
    897 		 * Return the file -- this should never happen.
    898 		 */
    899 		DirExpandInt(word, path, expansions);
    900 	    }
    901 	} else {
    902 	    /*
    903 	     * First the files in dot
    904 	     */
    905 	    DirMatchFiles(word, dot, expansions);
    906 
    907 	    /*
    908 	     * Then the files in every other directory on the path.
    909 	     */
    910 	    DirExpandInt(word, path, expansions);
    911 	}
    912     }
    913     if (DEBUG(DIR))
    914 	DirPrintExpansions(expansions);
    915 }
    916 
    917 /*-
    918  *-----------------------------------------------------------------------
    919  * DirLookup  --
    920  *	Find if the file with the given name exists in the given path.
    921  *
    922  * Results:
    923  *	The path to the file or NULL. This path is guaranteed to be in a
    924  *	different part of memory than name and so may be safely free'd.
    925  *
    926  * Side Effects:
    927  *	None.
    928  *-----------------------------------------------------------------------
    929  */
    930 static char *
    931 DirLookup(CachedDir *dir, const char *name MAKE_ATTR_UNUSED, const char *cp,
    932 	  Boolean hasSlash MAKE_ATTR_UNUSED)
    933 {
    934     char *file;			/* the current filename to check */
    935 
    936     DIR_DEBUG1("   %s ...\n", dir->name);
    937 
    938     if (Hash_FindEntry(&dir->files, cp) == NULL)
    939 	return NULL;
    940 
    941     file = str_concat3(dir->name, "/", cp);
    942     DIR_DEBUG1("   returning %s\n", file);
    943     dir->hits++;
    944     hits++;
    945     return file;
    946 }
    947 
    948 
    949 /*-
    950  *-----------------------------------------------------------------------
    951  * DirLookupSubdir  --
    952  *	Find if the file with the given name exists in the given path.
    953  *
    954  * Results:
    955  *	The path to the file or NULL. This path is guaranteed to be in a
    956  *	different part of memory than name and so may be safely free'd.
    957  *
    958  * Side Effects:
    959  *	If the file is found, it is added in the modification times hash
    960  *	table.
    961  *-----------------------------------------------------------------------
    962  */
    963 static char *
    964 DirLookupSubdir(CachedDir *dir, const char *name)
    965 {
    966     struct make_stat mst;
    967     char *file;			/* the current filename to check */
    968 
    969     if (dir != dot) {
    970 	file = str_concat3(dir->name, "/", name);
    971     } else {
    972 	/*
    973 	 * Checking in dot -- DON'T put a leading ./ on the thing.
    974 	 */
    975 	file = bmake_strdup(name);
    976     }
    977 
    978     DIR_DEBUG1("checking %s ...\n", file);
    979 
    980     if (cached_stat(file, &mst) == 0) {
    981 	nearmisses++;
    982 	return file;
    983     }
    984     free(file);
    985     return NULL;
    986 }
    987 
    988 /*-
    989  *-----------------------------------------------------------------------
    990  * DirLookupAbs  --
    991  *	Find if the file with the given name exists in the given path.
    992  *
    993  * Results:
    994  *	The path to the file, the empty string or NULL. If the file is
    995  *	the empty string, the search should be terminated.
    996  *	This path is guaranteed to be in a different part of memory
    997  *	than name and so may be safely free'd.
    998  *
    999  * Side Effects:
   1000  *	None.
   1001  *-----------------------------------------------------------------------
   1002  */
   1003 static char *
   1004 DirLookupAbs(CachedDir *dir, const char *name, const char *cp)
   1005 {
   1006     char *p1;			/* pointer into dir->name */
   1007     const char *p2;		/* pointer into name */
   1008 
   1009     DIR_DEBUG1("   %s ...\n", dir->name);
   1010 
   1011     /*
   1012      * If the file has a leading path component and that component
   1013      * exactly matches the entire name of the current search
   1014      * directory, we can attempt another cache lookup. And if we don't
   1015      * have a hit, we can safely assume the file does not exist at all.
   1016      */
   1017     for (p1 = dir->name, p2 = name; *p1 && *p1 == *p2; p1++, p2++) {
   1018 	continue;
   1019     }
   1020     if (*p1 != '\0' || p2 != cp - 1) {
   1021 	return NULL;
   1022     }
   1023 
   1024     if (Hash_FindEntry(&dir->files, cp) == NULL) {
   1025 	DIR_DEBUG0("   must be here but isn't -- returning\n");
   1026 	/* Return empty string: terminates search */
   1027 	return bmake_strdup("");
   1028     }
   1029 
   1030     dir->hits++;
   1031     hits++;
   1032     DIR_DEBUG1("   returning %s\n", name);
   1033     return bmake_strdup(name);
   1034 }
   1035 
   1036 /*-
   1037  *-----------------------------------------------------------------------
   1038  * DirFindDot  --
   1039  *	Find the file given on "." or curdir
   1040  *
   1041  * Results:
   1042  *	The path to the file or NULL. This path is guaranteed to be in a
   1043  *	different part of memory than name and so may be safely free'd.
   1044  *
   1045  * Side Effects:
   1046  *	Hit counts change
   1047  *-----------------------------------------------------------------------
   1048  */
   1049 static char *
   1050 DirFindDot(Boolean hasSlash MAKE_ATTR_UNUSED, const char *name, const char *cp)
   1051 {
   1052 
   1053     if (Hash_FindEntry(&dot->files, cp) != NULL) {
   1054 	DIR_DEBUG0("   in '.'\n");
   1055 	hits++;
   1056 	dot->hits++;
   1057 	return bmake_strdup(name);
   1058     }
   1059     if (cur && Hash_FindEntry(&cur->files, cp) != NULL) {
   1060 	DIR_DEBUG1("   in ${.CURDIR} = %s\n", cur->name);
   1061 	hits++;
   1062 	cur->hits++;
   1063 	return str_concat3(cur->name, "/", cp);
   1064     }
   1065 
   1066     return NULL;
   1067 }
   1068 
   1069 /*-
   1070  *-----------------------------------------------------------------------
   1071  * Dir_FindFile  --
   1072  *	Find the file with the given name along the given search path.
   1073  *
   1074  * Input:
   1075  *	name		the file to find
   1076  *	path		the Lst of directories to search
   1077  *
   1078  * Results:
   1079  *	The path to the file or NULL. This path is guaranteed to be in a
   1080  *	different part of memory than name and so may be safely free'd.
   1081  *
   1082  * Side Effects:
   1083  *	If the file is found in a directory which is not on the path
   1084  *	already (either 'name' is absolute or it is a relative path
   1085  *	[ dir1/.../dirn/file ] which exists below one of the directories
   1086  *	already on the search path), its directory is added to the end
   1087  *	of the path on the assumption that there will be more files in
   1088  *	that directory later on. Sometimes this is true. Sometimes not.
   1089  *-----------------------------------------------------------------------
   1090  */
   1091 char *
   1092 Dir_FindFile(const char *name, SearchPath *path)
   1093 {
   1094     SearchPathNode *ln;
   1095     char *file;			/* the current filename to check */
   1096     CachedDir *dir;
   1097     const char *base;		/* Terminal name of file */
   1098     Boolean hasLastDot = FALSE;	/* true if we should search dot last */
   1099     Boolean hasSlash;		/* true if 'name' contains a / */
   1100     struct make_stat mst;	/* Buffer for stat, if necessary */
   1101     const char *trailing_dot = ".";
   1102 
   1103     /*
   1104      * Find the final component of the name and note whether it has a
   1105      * slash in it (the name, I mean)
   1106      */
   1107     base = strrchr(name, '/');
   1108     if (base) {
   1109 	hasSlash = TRUE;
   1110 	base++;
   1111     } else {
   1112 	hasSlash = FALSE;
   1113 	base = name;
   1114     }
   1115 
   1116     DIR_DEBUG1("Searching for %s ...", name);
   1117 
   1118     if (path == NULL) {
   1119 	DIR_DEBUG0("couldn't open path, file not found\n");
   1120 	misses++;
   1121 	return NULL;
   1122     }
   1123 
   1124     Lst_Open(path);
   1125     if ((ln = Lst_First(path)) != NULL) {
   1126 	dir = LstNode_Datum(ln);
   1127 	if (dir == dotLast) {
   1128 	    hasLastDot = TRUE;
   1129 	    DIR_DEBUG0("[dot last]...");
   1130 	}
   1131     }
   1132     DIR_DEBUG0("\n");
   1133 
   1134     /*
   1135      * If there's no leading directory components or if the leading
   1136      * directory component is exactly `./', consult the cached contents
   1137      * of each of the directories on the search path.
   1138      */
   1139     if (!hasSlash || (base - name == 2 && *name == '.')) {
   1140 	/*
   1141 	 * We look through all the directories on the path seeking one which
   1142 	 * contains the final component of the given name.  If such a beast
   1143 	 * is found, we concatenate the directory name and the final
   1144 	 * component and return the resulting string. If we don't find any
   1145 	 * such thing, we go on to phase two...
   1146 	 *
   1147 	 * No matter what, we always look for the file in the current
   1148 	 * directory before anywhere else (unless we found the magic
   1149 	 * DOTLAST path, in which case we search it last) and we *do not*
   1150 	 * add the ./ to it if it exists.
   1151 	 * This is so there are no conflicts between what the user
   1152 	 * specifies (fish.c) and what pmake finds (./fish.c).
   1153 	 */
   1154 	if (!hasLastDot && (file = DirFindDot(hasSlash, name, base)) != NULL) {
   1155 	    Lst_Close(path);
   1156 	    return file;
   1157 	}
   1158 
   1159 	while ((ln = Lst_Next(path)) != NULL) {
   1160 	    dir = LstNode_Datum(ln);
   1161 	    if (dir == dotLast)
   1162 		continue;
   1163 	    if ((file = DirLookup(dir, name, base, hasSlash)) != NULL) {
   1164 		Lst_Close(path);
   1165 		return file;
   1166 	    }
   1167 	}
   1168 
   1169 	if (hasLastDot && (file = DirFindDot(hasSlash, name, base)) != NULL) {
   1170 	    Lst_Close(path);
   1171 	    return file;
   1172 	}
   1173     }
   1174     Lst_Close(path);
   1175 
   1176     /*
   1177      * We didn't find the file on any directory in the search path.
   1178      * If the name doesn't contain a slash, that means it doesn't exist.
   1179      * If it *does* contain a slash, however, there is still hope: it
   1180      * could be in a subdirectory of one of the members of the search
   1181      * path. (eg. /usr/include and sys/types.h. The above search would
   1182      * fail to turn up types.h in /usr/include, but it *is* in
   1183      * /usr/include/sys/types.h).
   1184      * [ This no longer applies: If we find such a beast, we assume there
   1185      * will be more (what else can we assume?) and add all but the last
   1186      * component of the resulting name onto the search path (at the
   1187      * end).]
   1188      * This phase is only performed if the file is *not* absolute.
   1189      */
   1190     if (!hasSlash) {
   1191 	DIR_DEBUG0("   failed.\n");
   1192 	misses++;
   1193 	return NULL;
   1194     }
   1195 
   1196     if (*base == '\0') {
   1197 	/* we were given a trailing "/" */
   1198 	base = trailing_dot;
   1199     }
   1200 
   1201     if (name[0] != '/') {
   1202 	Boolean checkedDot = FALSE;
   1203 
   1204 	DIR_DEBUG0("   Trying subdirectories...\n");
   1205 
   1206 	if (!hasLastDot) {
   1207 	    if (dot) {
   1208 		checkedDot = TRUE;
   1209 		if ((file = DirLookupSubdir(dot, name)) != NULL)
   1210 		    return file;
   1211 	    }
   1212 	    if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
   1213 		return file;
   1214 	}
   1215 
   1216 	Lst_Open(path);
   1217 	while ((ln = Lst_Next(path)) != NULL) {
   1218 	    dir = LstNode_Datum(ln);
   1219 	    if (dir == dotLast)
   1220 		continue;
   1221 	    if (dir == dot) {
   1222 		if (checkedDot)
   1223 		    continue;
   1224 		checkedDot = TRUE;
   1225 	    }
   1226 	    if ((file = DirLookupSubdir(dir, name)) != NULL) {
   1227 		Lst_Close(path);
   1228 		return file;
   1229 	    }
   1230 	}
   1231 	Lst_Close(path);
   1232 
   1233 	if (hasLastDot) {
   1234 	    if (dot && !checkedDot) {
   1235 		checkedDot = TRUE;
   1236 		if ((file = DirLookupSubdir(dot, name)) != NULL)
   1237 		    return file;
   1238 	    }
   1239 	    if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
   1240 		return file;
   1241 	}
   1242 
   1243 	if (checkedDot) {
   1244 	    /*
   1245 	     * Already checked by the given name, since . was in the path,
   1246 	     * so no point in proceeding...
   1247 	     */
   1248 	    DIR_DEBUG0("   Checked . already, returning NULL\n");
   1249 	    return NULL;
   1250 	}
   1251 
   1252     } else { /* name[0] == '/' */
   1253 
   1254 	/*
   1255 	 * For absolute names, compare directory path prefix against the
   1256 	 * the directory path of each member on the search path for an exact
   1257 	 * match. If we have an exact match on any member of the search path,
   1258 	 * use the cached contents of that member to lookup the final file
   1259 	 * component. If that lookup fails we can safely assume that the
   1260 	 * file does not exist at all.  This is signified by DirLookupAbs()
   1261 	 * returning an empty string.
   1262 	 */
   1263 	DIR_DEBUG0("   Trying exact path matches...\n");
   1264 
   1265 	if (!hasLastDot && cur &&
   1266 	    ((file = DirLookupAbs(cur, name, base)) != NULL)) {
   1267 	    if (file[0] == '\0') {
   1268 		free(file);
   1269 		return NULL;
   1270 	    }
   1271 	    return file;
   1272 	}
   1273 
   1274 	Lst_Open(path);
   1275 	while ((ln = Lst_Next(path)) != NULL) {
   1276 	    dir = LstNode_Datum(ln);
   1277 	    if (dir == dotLast)
   1278 		continue;
   1279 	    if ((file = DirLookupAbs(dir, name, base)) != NULL) {
   1280 		Lst_Close(path);
   1281 		if (file[0] == '\0') {
   1282 		    free(file);
   1283 		    return NULL;
   1284 		}
   1285 		return file;
   1286 	    }
   1287 	}
   1288 	Lst_Close(path);
   1289 
   1290 	if (hasLastDot && cur &&
   1291 	    ((file = DirLookupAbs(cur, name, base)) != NULL)) {
   1292 	    if (file[0] == '\0') {
   1293 		free(file);
   1294 		return NULL;
   1295 	    }
   1296 	    return file;
   1297 	}
   1298     }
   1299 
   1300     /*
   1301      * Didn't find it that way, either. Sigh. Phase 3. Add its directory
   1302      * onto the search path in any case, just in case, then look for the
   1303      * thing in the hash table. If we find it, grand. We return a new
   1304      * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
   1305      * Note that if the directory holding the file doesn't exist, this will
   1306      * do an extra search of the final directory on the path. Unless something
   1307      * weird happens, this search won't succeed and life will be groovy.
   1308      *
   1309      * Sigh. We cannot add the directory onto the search path because
   1310      * of this amusing case:
   1311      * $(INSTALLDIR)/$(FILE): $(FILE)
   1312      *
   1313      * $(FILE) exists in $(INSTALLDIR) but not in the current one.
   1314      * When searching for $(FILE), we will find it in $(INSTALLDIR)
   1315      * b/c we added it here. This is not good...
   1316      */
   1317 #ifdef notdef
   1318     if (base == trailing_dot) {
   1319 	base = strrchr(name, '/');
   1320 	base++;
   1321     }
   1322     base[-1] = '\0';
   1323     (void)Dir_AddDir(path, name);
   1324     base[-1] = '/';
   1325 
   1326     bigmisses++;
   1327     ln = Lst_Last(path);
   1328     if (ln == NULL) {
   1329 	return NULL;
   1330     } else {
   1331 	dir = LstNode_Datum(ln);
   1332     }
   1333 
   1334     if (Hash_FindEntry(&dir->files, base) != NULL) {
   1335 	return bmake_strdup(name);
   1336     } else {
   1337 	return NULL;
   1338     }
   1339 #else /* !notdef */
   1340     DIR_DEBUG1("   Looking for \"%s\" ...\n", name);
   1341 
   1342     bigmisses++;
   1343     if (cached_stat(name, &mst) == 0) {
   1344 	return bmake_strdup(name);
   1345     }
   1346 
   1347     DIR_DEBUG0("   failed. Returning NULL\n");
   1348     return NULL;
   1349 #endif /* notdef */
   1350 }
   1351 
   1352 
   1353 /*-
   1354  *-----------------------------------------------------------------------
   1355  * Dir_FindHereOrAbove  --
   1356  *	search for a path starting at a given directory and then working
   1357  *	our way up towards the root.
   1358  *
   1359  * Input:
   1360  *	here		starting directory
   1361  *	search_path	the path we are looking for
   1362  *	result		the result of a successful search is placed here
   1363  *	result_len	the length of the result buffer
   1364  *			(typically MAXPATHLEN + 1)
   1365  *
   1366  * Results:
   1367  *	0 on failure, 1 on success [in which case the found path is put
   1368  *	in the result buffer].
   1369  *
   1370  * Side Effects:
   1371  *-----------------------------------------------------------------------
   1372  */
   1373 Boolean
   1374 Dir_FindHereOrAbove(const char *here, const char *search_path,
   1375 		    char *result, int result_len)
   1376 {
   1377     struct make_stat mst;
   1378     char dirbase[MAXPATHLEN + 1], *dirbase_end;
   1379     char try[MAXPATHLEN + 1], *try_end;
   1380 
   1381     /* copy out our starting point */
   1382     snprintf(dirbase, sizeof(dirbase), "%s", here);
   1383     dirbase_end = dirbase + strlen(dirbase);
   1384 
   1385     /* loop until we determine a result */
   1386     while (TRUE) {
   1387 
   1388 	/* try and stat(2) it ... */
   1389 	snprintf(try, sizeof(try), "%s/%s", dirbase, search_path);
   1390 	if (cached_stat(try, &mst) != -1) {
   1391 	    /*
   1392 	     * success!  if we found a file, chop off
   1393 	     * the filename so we return a directory.
   1394 	     */
   1395 	    if ((mst.mst_mode & S_IFMT) != S_IFDIR) {
   1396 		try_end = try + strlen(try);
   1397 		while (try_end > try && *try_end != '/')
   1398 		    try_end--;
   1399 		if (try_end > try)
   1400 		    *try_end = '\0';	/* chop! */
   1401 	    }
   1402 
   1403 	    snprintf(result, result_len, "%s", try);
   1404 	    return TRUE;
   1405 	}
   1406 
   1407 	/*
   1408 	 * nope, we didn't find it.  if we used up dirbase we've
   1409 	 * reached the root and failed.
   1410 	 */
   1411 	if (dirbase_end == dirbase)
   1412 	    break;		/* failed! */
   1413 
   1414 	/*
   1415 	 * truncate dirbase from the end to move up a dir
   1416 	 */
   1417 	while (dirbase_end > dirbase && *dirbase_end != '/')
   1418 	    dirbase_end--;
   1419 	*dirbase_end = '\0';	/* chop! */
   1420 
   1421     } /* while (TRUE) */
   1422 
   1423     return FALSE;
   1424 }
   1425 
   1426 /*-
   1427  *-----------------------------------------------------------------------
   1428  * Dir_MTime  --
   1429  *	Find the modification time of the file described by gn along the
   1430  *	search path dirSearchPath.
   1431  *
   1432  * Input:
   1433  *	gn		the file whose modification time is desired
   1434  *
   1435  * Results:
   1436  *	The modification time or 0 if it doesn't exist
   1437  *
   1438  * Side Effects:
   1439  *	The modification time is placed in the node's mtime slot.
   1440  *	If the node didn't have a path entry before, and Dir_FindFile
   1441  *	found one for it, the full name is placed in the path slot.
   1442  *-----------------------------------------------------------------------
   1443  */
   1444 int
   1445 Dir_MTime(GNode *gn, Boolean recheck)
   1446 {
   1447     char *fullName;		/* the full pathname of name */
   1448     struct make_stat mst;	/* buffer for finding the mod time */
   1449 
   1450     if (gn->type & OP_ARCHV) {
   1451 	return Arch_MTime(gn);
   1452     } else if (gn->type & OP_PHONY) {
   1453 	gn->mtime = 0;
   1454 	return 0;
   1455     } else if (gn->path == NULL) {
   1456 	if (gn->type & OP_NOPATH)
   1457 	    fullName = NULL;
   1458 	else {
   1459 	    fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
   1460 	    if (fullName == NULL && gn->flags & FROM_DEPEND &&
   1461 		!Lst_IsEmpty(gn->implicitParents)) {
   1462 		char *cp;
   1463 
   1464 		cp = strrchr(gn->name, '/');
   1465 		if (cp) {
   1466 		    /*
   1467 		     * This is an implied source, and it may have moved,
   1468 		     * see if we can find it via the current .PATH
   1469 		     */
   1470 		    cp++;
   1471 
   1472 		    fullName = Dir_FindFile(cp, Suff_FindPath(gn));
   1473 		    if (fullName) {
   1474 			/*
   1475 			 * Put the found file in gn->path
   1476 			 * so that we give that to the compiler.
   1477 			 */
   1478 			gn->path = bmake_strdup(fullName);
   1479 			if (!Job_RunTarget(".STALE", gn->fname))
   1480 			    fprintf(stdout,
   1481 				    "%s: %s, %d: ignoring stale %s for %s, "
   1482 				    "found %s\n", progname, gn->fname,
   1483 				    gn->lineno,
   1484 				    makeDependfile, gn->name, fullName);
   1485 		    }
   1486 		}
   1487 	    }
   1488 	    DIR_DEBUG2("Found '%s' as '%s'\n",
   1489 		       gn->name, fullName ? fullName : "(not found)");
   1490 	}
   1491     } else {
   1492 	fullName = gn->path;
   1493     }
   1494 
   1495     if (fullName == NULL) {
   1496 	fullName = bmake_strdup(gn->name);
   1497     }
   1498 
   1499     if (cached_stats(&mtimes, fullName, &mst, recheck ? CST_UPDATE : 0) < 0) {
   1500 	if (gn->type & OP_MEMBER) {
   1501 	    if (fullName != gn->path)
   1502 		free(fullName);
   1503 	    return Arch_MemMTime(gn);
   1504 	} else {
   1505 	    mst.mst_mtime = 0;
   1506 	}
   1507     }
   1508 
   1509     if (fullName && gn->path == NULL) {
   1510 	gn->path = fullName;
   1511     }
   1512 
   1513     gn->mtime = mst.mst_mtime;
   1514     return gn->mtime;
   1515 }
   1516 
   1517 /* Read the list of filenames in the directory and store the result
   1518  * in openDirectories.
   1519  *
   1520  * If a path is given, append the directory to that path.
   1521  *
   1522  * Input:
   1523  *	path		The path to which the directory should be
   1524  *			added, or NULL to only add the directory to
   1525  *			openDirectories
   1526  *	name		The name of the directory to add.
   1527  *			The name is not normalized in any way.
   1528  */
   1529 CachedDir *
   1530 Dir_AddDir(SearchPath *path, const char *name)
   1531 {
   1532     CachedDir *dir = NULL;	/* the added directory */
   1533     DIR *d;
   1534     struct dirent *dp;
   1535 
   1536     if (path != NULL && strcmp(name, ".DOTLAST") == 0) {
   1537 	SearchPathNode *ln = Lst_Find(path, DirFindName, name);
   1538 	if (ln != NULL)
   1539 	    return LstNode_Datum(ln);
   1540 
   1541 	dotLast->refCount++;
   1542 	Lst_Prepend(path, dotLast);
   1543     }
   1544 
   1545     if (path != NULL)
   1546 	dir = OpenDirs_Find(&openDirs, name);
   1547     if (dir != NULL) {
   1548 	if (Lst_FindDatum(path, dir) == NULL) {
   1549 	    dir->refCount++;
   1550 	    Lst_Append(path, dir);
   1551 	}
   1552 	return dir;
   1553     }
   1554 
   1555     DIR_DEBUG1("Caching %s ...", name);
   1556 
   1557     if ((d = opendir(name)) != NULL) {
   1558 	dir = bmake_malloc(sizeof(CachedDir));
   1559 	dir->name = bmake_strdup(name);
   1560 	dir->hits = 0;
   1561 	dir->refCount = 1;
   1562 	Hash_InitTable(&dir->files);
   1563 
   1564 	while ((dp = readdir(d)) != NULL) {
   1565 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
   1566 	    /*
   1567 	     * The sun directory library doesn't check for a 0 inode
   1568 	     * (0-inode slots just take up space), so we have to do
   1569 	     * it ourselves.
   1570 	     */
   1571 	    if (dp->d_fileno == 0) {
   1572 		continue;
   1573 	    }
   1574 #endif /* sun && d_ino */
   1575 	    (void)Hash_CreateEntry(&dir->files, dp->d_name, NULL);
   1576 	}
   1577 	(void)closedir(d);
   1578 	OpenDirs_Add(&openDirs, dir);
   1579 	if (path != NULL)
   1580 	    Lst_Append(path, dir);
   1581     }
   1582     DIR_DEBUG0("done\n");
   1583     return dir;
   1584 }
   1585 
   1586 /*-
   1587  *-----------------------------------------------------------------------
   1588  * Dir_CopyDir --
   1589  *	Callback function for duplicating a search path via Lst_Copy.
   1590  *	Ups the reference count for the directory.
   1591  *
   1592  * Results:
   1593  *	Returns the Path it was given.
   1594  *-----------------------------------------------------------------------
   1595  */
   1596 void *
   1597 Dir_CopyDir(void *p)
   1598 {
   1599     CachedDir *dir = (CachedDir *)p;
   1600     dir->refCount++;
   1601 
   1602     return p;
   1603 }
   1604 
   1605 /*-
   1606  *-----------------------------------------------------------------------
   1607  * Dir_MakeFlags --
   1608  *	Make a string by taking all the directories in the given search
   1609  *	path and preceding them by the given flag. Used by the suffix
   1610  *	module to create variables for compilers based on suffix search
   1611  *	paths.
   1612  *
   1613  * Input:
   1614  *	flag		flag which should precede each directory
   1615  *	path		list of directories
   1616  *
   1617  * Results:
   1618  *	The string mentioned above. Note that there is no space between
   1619  *	the given flag and each directory. The empty string is returned if
   1620  *	Things don't go well.
   1621  *
   1622  * Side Effects:
   1623  *	None
   1624  *-----------------------------------------------------------------------
   1625  */
   1626 char *
   1627 Dir_MakeFlags(const char *flag, SearchPath *path)
   1628 {
   1629     Buffer buf;
   1630     SearchPathNode *ln;
   1631 
   1632     Buf_Init(&buf, 0);
   1633 
   1634     if (path != NULL) {
   1635 	for (ln = path->first; ln != NULL; ln = ln->next) {
   1636 	    CachedDir *dir = ln->datum;
   1637 	    Buf_AddStr(&buf, " ");
   1638 	    Buf_AddStr(&buf, flag);
   1639 	    Buf_AddStr(&buf, dir->name);
   1640 	}
   1641     }
   1642 
   1643     return Buf_Destroy(&buf, FALSE);
   1644 }
   1645 
   1646 /*-
   1647  *-----------------------------------------------------------------------
   1648  * Dir_Destroy --
   1649  *	Nuke a directory descriptor, if possible. Callback procedure
   1650  *	for the suffixes module when destroying a search path.
   1651  *
   1652  * Input:
   1653  *	dirp		The directory descriptor to nuke
   1654  *
   1655  * Results:
   1656  *	None.
   1657  *
   1658  * Side Effects:
   1659  *	If no other path references this directory (refCount == 0),
   1660  *	the CachedDir and all its data are freed.
   1661  *
   1662  *-----------------------------------------------------------------------
   1663  */
   1664 void
   1665 Dir_Destroy(void *dirp)
   1666 {
   1667     CachedDir *dir = dirp;
   1668     dir->refCount--;
   1669 
   1670     if (dir->refCount == 0) {
   1671 	OpenDirs_Remove(&openDirs, dir->name);
   1672 
   1673 	Hash_DeleteTable(&dir->files);
   1674 	free(dir->name);
   1675 	free(dir);
   1676     }
   1677 }
   1678 
   1679 /*-
   1680  *-----------------------------------------------------------------------
   1681  * Dir_ClearPath --
   1682  *	Clear out all elements of the given search path. This is different
   1683  *	from destroying the list, notice.
   1684  *
   1685  * Input:
   1686  *	path		Path to clear
   1687  *
   1688  * Results:
   1689  *	None.
   1690  *
   1691  * Side Effects:
   1692  *	The path is set to the empty list.
   1693  *
   1694  *-----------------------------------------------------------------------
   1695  */
   1696 void
   1697 Dir_ClearPath(SearchPath *path)
   1698 {
   1699     while (!Lst_IsEmpty(path)) {
   1700 	CachedDir *dir = Lst_Dequeue(path);
   1701 	Dir_Destroy(dir);
   1702     }
   1703 }
   1704 
   1705 
   1706 /*-
   1707  *-----------------------------------------------------------------------
   1708  * Dir_Concat --
   1709  *	Concatenate two paths, adding the second to the end of the first.
   1710  *	Makes sure to avoid duplicates.
   1711  *
   1712  * Input:
   1713  *	path1		Dest
   1714  *	path2		Source
   1715  *
   1716  * Results:
   1717  *	None
   1718  *
   1719  * Side Effects:
   1720  *	Reference counts for added dirs are upped.
   1721  *
   1722  *-----------------------------------------------------------------------
   1723  */
   1724 void
   1725 Dir_Concat(SearchPath *path1, SearchPath *path2)
   1726 {
   1727     SearchPathNode *ln;
   1728 
   1729     for (ln = path2->first; ln != NULL; ln = ln->next) {
   1730 	CachedDir *dir = ln->datum;
   1731 	if (Lst_FindDatum(path1, dir) == NULL) {
   1732 	    dir->refCount++;
   1733 	    Lst_Append(path1, dir);
   1734 	}
   1735     }
   1736 }
   1737 
   1738 static int
   1739 percentage(int num, int den)
   1740 {
   1741     return den != 0 ? num * 100 / den : 0;
   1742 }
   1743 
   1744 /********** DEBUG INFO **********/
   1745 void
   1746 Dir_PrintDirectories(void)
   1747 {
   1748     CachedDirListNode *ln;
   1749 
   1750     debug_printf("#*** Directory Cache:\n");
   1751     debug_printf("# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
   1752 		 hits, misses, nearmisses, bigmisses,
   1753 		 percentage(hits, hits + bigmisses + nearmisses));
   1754     debug_printf("# %-20s referenced\thits\n", "directory");
   1755 
   1756     for (ln = openDirs.list->first; ln != NULL; ln = ln->next) {
   1757 	CachedDir *dir = ln->datum;
   1758 	debug_printf("# %-20s %10d\t%4d\n", dir->name, dir->refCount,
   1759 		     dir->hits);
   1760     }
   1761 }
   1762 
   1763 void
   1764 Dir_PrintPath(SearchPath *path)
   1765 {
   1766     SearchPathNode *node;
   1767     for (node = path->first; node != NULL; node = node->next) {
   1768 	const CachedDir *dir = node->datum;
   1769 	debug_printf("%s ", dir->name);
   1770     }
   1771 }
   1772