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