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