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