dir.c revision 1.77       1 /*	$NetBSD: dir.c,v 1.77 2020/07/31 16:59:34 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.77 2020/07/31 16:59:34 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.77 2020/07/31 16:59:34 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 	      misses,	      /* Sad, but not evil misses */
    230 	      nearmisses,     /* Found under search path */
    231 	      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 static Hash_Table mtimes;   /* Results of doing a last-resort stat in
    238 			     * Dir_FindFile -- if we have to go to the
    239 			     * system to find the file, we might as well
    240 			     * have its mtime on record. XXX: If this is done
    241 			     * way early, there's a chance other rules will
    242 			     * have already updated the file, in which case
    243 			     * we'll update it again. Generally, there won't
    244 			     * be two rules to update a single file, so this
    245 			     * should be ok, but... */
    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 /*-
    651  *-----------------------------------------------------------------------
    652  * DirExpandCurly --
    653  *	Expand curly braces like the C shell. Does this recursively.
    654  *	Note the special case: if after the piece of the curly brace is
    655  *	done there are no wildcard characters in the result, the result is
    656  *	placed on the list WITHOUT CHECKING FOR ITS EXISTENCE.
    657  *
    658  * Input:
    659  *	word		Entire word to expand
    660  *	brace		First curly brace in it
    661  *	path		Search path to use
    662  *	expansions	Place to store the expansions
    663  *
    664  * Results:
    665  *	None.
    666  *
    667  * Side Effects:
    668  *	The given list is filled with the expansions...
    669  *
    670  *-----------------------------------------------------------------------
    671  */
    672 static void
    673 DirExpandCurly(const char *word, const char *brace, Lst path, Lst expansions)
    674 {
    675     const char   *end;	    	/* Character after the closing brace */
    676     const char   *cp;	    	/* Current position in brace clause */
    677     const char   *start;   	/* Start of current piece of brace clause */
    678     int	    	  bracelevel;	/* Number of braces we've seen. If we see a
    679 				 * right brace when this is 0, we've hit the
    680 				 * end of the clause. */
    681     char    	 *file;    	/* Current expansion */
    682     int	    	  otherLen; 	/* The length of the other pieces of the
    683 				 * expansion (chars before and after the
    684 				 * clause in 'word') */
    685     char    	 *cp2;	    	/* Pointer for checking for wildcards in
    686 				 * expansion before calling Dir_Expand */
    687 
    688     start = brace+1;
    689 
    690     /*
    691      * Find the end of the brace clause first, being wary of nested brace
    692      * clauses.
    693      */
    694     for (end = start, bracelevel = 0; *end != '\0'; end++) {
    695 	if (*end == '{') {
    696 	    bracelevel++;
    697 	} else if ((*end == '}') && (bracelevel-- == 0)) {
    698 	    break;
    699 	}
    700     }
    701     if (*end == '\0') {
    702 	Error("Unterminated {} clause \"%s\"", start);
    703 	return;
    704     } else {
    705 	end++;
    706     }
    707     otherLen = brace - word + strlen(end);
    708 
    709     for (cp = start; cp < end; cp++) {
    710 	/*
    711 	 * Find the end of this piece of the clause.
    712 	 */
    713 	bracelevel = 0;
    714 	while (*cp != ',') {
    715 	    if (*cp == '{') {
    716 		bracelevel++;
    717 	    } else if ((*cp == '}') && (bracelevel-- <= 0)) {
    718 		break;
    719 	    }
    720 	    cp++;
    721 	}
    722 	/*
    723 	 * Allocate room for the combination and install the three pieces.
    724 	 */
    725 	file = bmake_malloc(otherLen + cp - start + 1);
    726 	char *fileend = file;
    727 	if (brace != word) {
    728 	    memcpy(file, word, brace - word);
    729 	    fileend += brace - word;
    730 	}
    731 	if (cp != start) {
    732 	    memcpy(fileend, start, cp - start);
    733 	    fileend += cp - start;
    734 	}
    735 	strcpy(fileend, end);
    736 
    737 	/*
    738 	 * See if the result has any wildcards in it. If we find one, call
    739 	 * Dir_Expand right away, telling it to place the result on our list
    740 	 * of expansions.
    741 	 */
    742 	for (cp2 = file; *cp2 != '\0'; cp2++) {
    743 	    switch(*cp2) {
    744 	    case '*':
    745 	    case '?':
    746 	    case '{':
    747 	    case '[':
    748 		Dir_Expand(file, path, expansions);
    749 		goto next;
    750 	    }
    751 	}
    752 	if (*cp2 == '\0') {
    753 	    /*
    754 	     * Hit the end w/o finding any wildcards, so stick the expansion
    755 	     * on the end of the list.
    756 	     */
    757 	    (void)Lst_AtEnd(expansions, file);
    758 	} else {
    759 	next:
    760 	    free(file);
    761 	}
    762 	start = cp+1;
    763     }
    764 }
    765 
    766 
    767 /*-
    768  *-----------------------------------------------------------------------
    769  * DirExpandInt --
    770  *	Internal expand routine. Passes through the directories in the
    771  *	path one by one, calling DirMatchFiles for each. NOTE: This still
    772  *	doesn't handle patterns in directories...
    773  *
    774  * Input:
    775  *	word		Word to expand
    776  *	path		Path on which to look
    777  *	expansions	Place to store the result
    778  *
    779  * Results:
    780  *	None.
    781  *
    782  * Side Effects:
    783  *	Things are added to the expansions list.
    784  *
    785  *-----------------------------------------------------------------------
    786  */
    787 static void
    788 DirExpandInt(const char *word, Lst path, Lst expansions)
    789 {
    790     LstNode 	  ln;	    	/* Current node */
    791     Path	  *p;	    	/* Directory in the node */
    792 
    793     if (Lst_Open(path) == SUCCESS) {
    794 	while ((ln = Lst_Next(path)) != NULL) {
    795 	    p = (Path *)Lst_Datum(ln);
    796 	    DirMatchFiles(word, p, expansions);
    797 	}
    798 	Lst_Close(path);
    799     }
    800 }
    801 
    802 /*-
    803  *-----------------------------------------------------------------------
    804  * DirPrintWord --
    805  *	Print a word in the list of expansions. Callback for Dir_Expand
    806  *	when DEBUG(DIR), via Lst_ForEach.
    807  *
    808  * Results:
    809  *	=== 0
    810  *
    811  * Side Effects:
    812  *	The passed word is printed, followed by a space.
    813  *
    814  *-----------------------------------------------------------------------
    815  */
    816 static int
    817 DirPrintWord(void *word, void *dummy MAKE_ATTR_UNUSED)
    818 {
    819     fprintf(debug_file, "%s ", (char *)word);
    820 
    821     return 0;
    822 }
    823 
    824 /*-
    825  *-----------------------------------------------------------------------
    826  * Dir_Expand  --
    827  *	Expand the given word into a list of words by globbing it looking
    828  *	in the directories on the given search path.
    829  *
    830  * Input:
    831  *	word		the word to expand
    832  *	path		the list of directories in which to find the
    833  *			resulting files
    834  *	expansions	the list on which to place the results
    835  *
    836  * Results:
    837  *	A list of words consisting of the files which exist along the search
    838  *	path matching the given pattern.
    839  *
    840  * Side Effects:
    841  *	Directories may be opened. Who knows?
    842  *-----------------------------------------------------------------------
    843  */
    844 void
    845 Dir_Expand(const char *word, Lst path, Lst expansions)
    846 {
    847     const char    	  *cp;
    848 
    849     if (DEBUG(DIR)) {
    850 	fprintf(debug_file, "Expanding \"%s\"... ", word);
    851     }
    852 
    853     cp = strchr(word, '{');
    854     if (cp) {
    855 	DirExpandCurly(word, cp, path, expansions);
    856     } else {
    857 	cp = strchr(word, '/');
    858 	if (cp) {
    859 	    /*
    860 	     * The thing has a directory component -- find the first wildcard
    861 	     * in the string.
    862 	     */
    863 	    for (cp = word; *cp; cp++) {
    864 		if (*cp == '?' || *cp == '[' || *cp == '*' || *cp == '{') {
    865 		    break;
    866 		}
    867 	    }
    868 	    if (*cp == '{') {
    869 		/*
    870 		 * This one will be fun.
    871 		 */
    872 		DirExpandCurly(word, cp, path, expansions);
    873 		return;
    874 	    } else if (*cp != '\0') {
    875 		/*
    876 		 * Back up to the start of the component
    877 		 */
    878 		char  *dirpath;
    879 
    880 		while (cp > word && *cp != '/') {
    881 		    cp--;
    882 		}
    883 		if (cp != word) {
    884 		    char sc;
    885 		    /*
    886 		     * If the glob isn't in the first component, try and find
    887 		     * all the components up to the one with a wildcard.
    888 		     */
    889 		    sc = cp[1];
    890 		    ((char *)UNCONST(cp))[1] = '\0';
    891 		    dirpath = Dir_FindFile(word, path);
    892 		    ((char *)UNCONST(cp))[1] = sc;
    893 		    /*
    894 		     * dirpath is null if can't find the leading component
    895 		     * XXX: Dir_FindFile won't find internal components.
    896 		     * i.e. if the path contains ../Etc/Object and we're
    897 		     * looking for Etc, it won't be found. Ah well.
    898 		     * Probably not important.
    899 		     */
    900 		    if (dirpath != NULL) {
    901 			char *dp = &dirpath[strlen(dirpath) - 1];
    902 			if (*dp == '/')
    903 			    *dp = '\0';
    904 			path = Lst_Init(FALSE);
    905 			(void)Dir_AddDir(path, dirpath);
    906 			DirExpandInt(cp+1, path, expansions);
    907 			Lst_Destroy(path, NULL);
    908 		    }
    909 		} else {
    910 		    /*
    911 		     * Start the search from the local directory
    912 		     */
    913 		    DirExpandInt(word, path, expansions);
    914 		}
    915 	    } else {
    916 		/*
    917 		 * Return the file -- this should never happen.
    918 		 */
    919 		DirExpandInt(word, path, expansions);
    920 	    }
    921 	} else {
    922 	    /*
    923 	     * First the files in dot
    924 	     */
    925 	    DirMatchFiles(word, dot, expansions);
    926 
    927 	    /*
    928 	     * Then the files in every other directory on the path.
    929 	     */
    930 	    DirExpandInt(word, path, expansions);
    931 	}
    932     }
    933     if (DEBUG(DIR)) {
    934 	Lst_ForEach(expansions, DirPrintWord, NULL);
    935 	fprintf(debug_file, "\n");
    936     }
    937 }
    938 
    939 /*-
    940  *-----------------------------------------------------------------------
    941  * DirLookup  --
    942  *	Find if the file with the given name exists in the given path.
    943  *
    944  * Results:
    945  *	The path to the file or NULL. This path is guaranteed to be in a
    946  *	different part of memory than name and so may be safely free'd.
    947  *
    948  * Side Effects:
    949  *	None.
    950  *-----------------------------------------------------------------------
    951  */
    952 static char *
    953 DirLookup(Path *p, const char *name MAKE_ATTR_UNUSED, const char *cp,
    954           Boolean hasSlash MAKE_ATTR_UNUSED)
    955 {
    956     char *file;		/* the current filename to check */
    957 
    958     if (DEBUG(DIR)) {
    959 	fprintf(debug_file, "   %s ...\n", p->name);
    960     }
    961 
    962     if (Hash_FindEntry(&p->files, cp) == NULL)
    963 	return NULL;
    964 
    965     file = str_concat(p->name, cp, STR_ADDSLASH);
    966     if (DEBUG(DIR)) {
    967 	fprintf(debug_file, "   returning %s\n", file);
    968     }
    969     p->hits += 1;
    970     hits += 1;
    971     return file;
    972 }
    973 
    974 
    975 /*-
    976  *-----------------------------------------------------------------------
    977  * DirLookupSubdir  --
    978  *	Find if the file with the given name exists in the given path.
    979  *
    980  * Results:
    981  *	The path to the file or NULL. This path is guaranteed to be in a
    982  *	different part of memory than name and so may be safely free'd.
    983  *
    984  * Side Effects:
    985  *	If the file is found, it is added in the modification times hash
    986  *	table.
    987  *-----------------------------------------------------------------------
    988  */
    989 static char *
    990 DirLookupSubdir(Path *p, const char *name)
    991 {
    992     struct stat	  stb;		/* Buffer for stat, if necessary */
    993     char 	 *file;		/* the current filename to check */
    994 
    995     if (p != dot) {
    996 	file = str_concat(p->name, name, STR_ADDSLASH);
    997     } else {
    998 	/*
    999 	 * Checking in dot -- DON'T put a leading ./ on the thing.
   1000 	 */
   1001 	file = bmake_strdup(name);
   1002     }
   1003 
   1004     if (DEBUG(DIR)) {
   1005 	fprintf(debug_file, "checking %s ...\n", file);
   1006     }
   1007 
   1008     if (cached_stat(file, &stb) == 0) {
   1009 	nearmisses += 1;
   1010 	return file;
   1011     }
   1012     free(file);
   1013     return NULL;
   1014 }
   1015 
   1016 /*-
   1017  *-----------------------------------------------------------------------
   1018  * DirLookupAbs  --
   1019  *	Find if the file with the given name exists in the given path.
   1020  *
   1021  * Results:
   1022  *	The path to the file, the empty string or NULL. If the file is
   1023  *	the empty string, the search should be terminated.
   1024  *	This path is guaranteed to be in a different part of memory
   1025  *	than name and so may be safely free'd.
   1026  *
   1027  * Side Effects:
   1028  *	None.
   1029  *-----------------------------------------------------------------------
   1030  */
   1031 static char *
   1032 DirLookupAbs(Path *p, const char *name, const char *cp)
   1033 {
   1034 	char *p1;		/* pointer into p->name */
   1035 	const char *p2;		/* pointer into name */
   1036 
   1037 	if (DEBUG(DIR)) {
   1038 		fprintf(debug_file, "   %s ...\n", p->name);
   1039 	}
   1040 
   1041 	/*
   1042 	 * If the file has a leading path component and that component
   1043 	 * exactly matches the entire name of the current search
   1044 	 * directory, we can attempt another cache lookup. And if we don't
   1045 	 * have a hit, we can safely assume the file does not exist at all.
   1046 	 */
   1047 	for (p1 = p->name, p2 = name; *p1 && *p1 == *p2; p1++, p2++) {
   1048 		continue;
   1049 	}
   1050 	if (*p1 != '\0' || p2 != cp - 1) {
   1051 		return NULL;
   1052 	}
   1053 
   1054 	if (Hash_FindEntry(&p->files, cp) == NULL) {
   1055 		if (DEBUG(DIR)) {
   1056 			fprintf(debug_file, "   must be here but isn't -- returning\n");
   1057 		}
   1058 		/* Return empty string: terminates search */
   1059 		return bmake_strdup("");
   1060 	}
   1061 
   1062 	p->hits += 1;
   1063 	hits += 1;
   1064 	if (DEBUG(DIR)) {
   1065 		fprintf(debug_file, "   returning %s\n", name);
   1066 	}
   1067 	return bmake_strdup(name);
   1068 }
   1069 
   1070 /*-
   1071  *-----------------------------------------------------------------------
   1072  * DirFindDot  --
   1073  *	Find the file given on "." or curdir
   1074  *
   1075  * Results:
   1076  *	The path to the file or NULL. This path is guaranteed to be in a
   1077  *	different part of memory than name and so may be safely free'd.
   1078  *
   1079  * Side Effects:
   1080  *	Hit counts change
   1081  *-----------------------------------------------------------------------
   1082  */
   1083 static char *
   1084 DirFindDot(Boolean hasSlash MAKE_ATTR_UNUSED, const char *name, const char *cp)
   1085 {
   1086 
   1087 	if (Hash_FindEntry(&dot->files, cp) != NULL) {
   1088 	    if (DEBUG(DIR)) {
   1089 		fprintf(debug_file, "   in '.'\n");
   1090 	    }
   1091 	    hits += 1;
   1092 	    dot->hits += 1;
   1093 	    return bmake_strdup(name);
   1094 	}
   1095 	if (cur &&
   1096 	    Hash_FindEntry(&cur->files, cp) != NULL) {
   1097 	    if (DEBUG(DIR)) {
   1098 		fprintf(debug_file, "   in ${.CURDIR} = %s\n", cur->name);
   1099 	    }
   1100 	    hits += 1;
   1101 	    cur->hits += 1;
   1102 	    return str_concat(cur->name, cp, STR_ADDSLASH);
   1103 	}
   1104 
   1105 	return NULL;
   1106 }
   1107 
   1108 /*-
   1109  *-----------------------------------------------------------------------
   1110  * Dir_FindFile  --
   1111  *	Find the file with the given name along the given search path.
   1112  *
   1113  * Input:
   1114  *	name		the file to find
   1115  *	path		the Lst of directories to search
   1116  *
   1117  * Results:
   1118  *	The path to the file or NULL. This path is guaranteed to be in a
   1119  *	different part of memory than name and so may be safely free'd.
   1120  *
   1121  * Side Effects:
   1122  *	If the file is found in a directory which is not on the path
   1123  *	already (either 'name' is absolute or it is a relative path
   1124  *	[ dir1/.../dirn/file ] which exists below one of the directories
   1125  *	already on the search path), its directory is added to the end
   1126  *	of the path on the assumption that there will be more files in
   1127  *	that directory later on. Sometimes this is true. Sometimes not.
   1128  *-----------------------------------------------------------------------
   1129  */
   1130 char *
   1131 Dir_FindFile(const char *name, Lst path)
   1132 {
   1133     LstNode       ln;			/* a list element */
   1134     char	  *file;		/* the current filename to check */
   1135     Path	  *p;			/* current path member */
   1136     const char	  *cp;			/* Terminal name of file */
   1137     Boolean	  hasLastDot = FALSE;	/* true we should search dot last */
   1138     Boolean	  hasSlash;		/* true if 'name' contains a / */
   1139     struct stat	  stb;			/* Buffer for stat, if necessary */
   1140     const char   *trailing_dot = ".";
   1141 
   1142     /*
   1143      * Find the final component of the name and note whether it has a
   1144      * slash in it (the name, I mean)
   1145      */
   1146     cp = strrchr(name, '/');
   1147     if (cp) {
   1148 	hasSlash = TRUE;
   1149 	cp += 1;
   1150     } else {
   1151 	hasSlash = FALSE;
   1152 	cp = name;
   1153     }
   1154 
   1155     if (DEBUG(DIR)) {
   1156 	fprintf(debug_file, "Searching for %s ...", name);
   1157     }
   1158 
   1159     if (Lst_Open(path) == FAILURE) {
   1160 	if (DEBUG(DIR)) {
   1161 	    fprintf(debug_file, "couldn't open path, file not found\n");
   1162 	}
   1163 	misses += 1;
   1164 	return NULL;
   1165     }
   1166 
   1167     if ((ln = Lst_First(path)) != NULL) {
   1168 	p = (Path *)Lst_Datum(ln);
   1169 	if (p == dotLast) {
   1170 	    hasLastDot = TRUE;
   1171             if (DEBUG(DIR))
   1172 		fprintf(debug_file, "[dot last]...");
   1173 	}
   1174     }
   1175     if (DEBUG(DIR)) {
   1176 	fprintf(debug_file, "\n");
   1177     }
   1178 
   1179     /*
   1180      * If there's no leading directory components or if the leading
   1181      * directory component is exactly `./', consult the cached contents
   1182      * of each of the directories on the search path.
   1183      */
   1184     if (!hasSlash || (cp - name == 2 && *name == '.')) {
   1185 	    /*
   1186 	     * We look through all the directories on the path seeking one which
   1187 	     * contains the final component of the given name.  If such a beast
   1188 	     * is found, we concatenate the directory name and the final
   1189 	     * component and return the resulting string. If we don't find any
   1190 	     * such thing, we go on to phase two...
   1191 	     *
   1192 	     * No matter what, we always look for the file in the current
   1193 	     * directory before anywhere else (unless we found the magic
   1194 	     * DOTLAST path, in which case we search it last) and we *do not*
   1195 	     * add the ./ to it if it exists.
   1196 	     * This is so there are no conflicts between what the user
   1197 	     * specifies (fish.c) and what pmake finds (./fish.c).
   1198 	     */
   1199 	    if (!hasLastDot &&
   1200 			(file = DirFindDot(hasSlash, name, cp)) != NULL) {
   1201 		    Lst_Close(path);
   1202 		    return file;
   1203 	    }
   1204 
   1205 	    while ((ln = Lst_Next(path)) != NULL) {
   1206 		p = (Path *)Lst_Datum(ln);
   1207 		if (p == dotLast)
   1208 		    continue;
   1209 		if ((file = DirLookup(p, name, cp, hasSlash)) != NULL) {
   1210 		    Lst_Close(path);
   1211 		    return file;
   1212 		}
   1213 	    }
   1214 
   1215 	    if (hasLastDot &&
   1216 			(file = DirFindDot(hasSlash, name, cp)) != NULL) {
   1217 		    Lst_Close(path);
   1218 		    return file;
   1219 	    }
   1220     }
   1221     Lst_Close(path);
   1222 
   1223     /*
   1224      * We didn't find the file on any directory in the search path.
   1225      * If the name doesn't contain a slash, that means it doesn't exist.
   1226      * If it *does* contain a slash, however, there is still hope: it
   1227      * could be in a subdirectory of one of the members of the search
   1228      * path. (eg. /usr/include and sys/types.h. The above search would
   1229      * fail to turn up types.h in /usr/include, but it *is* in
   1230      * /usr/include/sys/types.h).
   1231      * [ This no longer applies: If we find such a beast, we assume there
   1232      * will be more (what else can we assume?) and add all but the last
   1233      * component of the resulting name onto the search path (at the
   1234      * end).]
   1235      * This phase is only performed if the file is *not* absolute.
   1236      */
   1237     if (!hasSlash) {
   1238 	if (DEBUG(DIR)) {
   1239 	    fprintf(debug_file, "   failed.\n");
   1240 	}
   1241 	misses += 1;
   1242 	return NULL;
   1243     }
   1244 
   1245     if (*cp == '\0') {
   1246 	/* we were given a trailing "/" */
   1247 	cp = trailing_dot;
   1248     }
   1249 
   1250     if (name[0] != '/') {
   1251 	Boolean	checkedDot = FALSE;
   1252 
   1253 	if (DEBUG(DIR)) {
   1254 	    fprintf(debug_file, "   Trying subdirectories...\n");
   1255 	}
   1256 
   1257 	if (!hasLastDot) {
   1258 		if (dot) {
   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 	(void)Lst_Open(path);
   1268 	while ((ln = Lst_Next(path)) != NULL) {
   1269 	    p = (Path *)Lst_Datum(ln);
   1270 	    if (p == dotLast)
   1271 		continue;
   1272 	    if (p == dot) {
   1273 		    if (checkedDot)
   1274 			    continue;
   1275 		checkedDot = TRUE;
   1276 	    }
   1277 	    if ((file = DirLookupSubdir(p, name)) != NULL) {
   1278 		Lst_Close(path);
   1279 		return file;
   1280 	    }
   1281 	}
   1282 	Lst_Close(path);
   1283 
   1284 	if (hasLastDot) {
   1285 		if (dot && !checkedDot) {
   1286 			checkedDot = TRUE;
   1287 			if ((file = DirLookupSubdir(dot, name)) != NULL)
   1288 				return file;
   1289 		}
   1290 		if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
   1291 			return file;
   1292 	}
   1293 
   1294 	if (checkedDot) {
   1295 	    /*
   1296 	     * Already checked by the given name, since . was in the path,
   1297 	     * so no point in proceeding...
   1298 	     */
   1299 	    if (DEBUG(DIR)) {
   1300 		fprintf(debug_file, "   Checked . already, returning NULL\n");
   1301 	    }
   1302 	    return NULL;
   1303 	}
   1304 
   1305     } else { /* name[0] == '/' */
   1306 
   1307 	/*
   1308 	 * For absolute names, compare directory path prefix against the
   1309 	 * the directory path of each member on the search path for an exact
   1310 	 * match. If we have an exact match on any member of the search path,
   1311 	 * use the cached contents of that member to lookup the final file
   1312 	 * component. If that lookup fails we can safely assume that the
   1313 	 * file does not exist at all.  This is signified by DirLookupAbs()
   1314 	 * returning an empty string.
   1315 	 */
   1316 	if (DEBUG(DIR)) {
   1317 	    fprintf(debug_file, "   Trying exact path matches...\n");
   1318 	}
   1319 
   1320 	if (!hasLastDot && cur && ((file = DirLookupAbs(cur, name, cp))
   1321 		!= NULL)) {
   1322 	    if (file[0] == '\0') {
   1323 		free(file);
   1324 		return NULL;
   1325 	    }
   1326 	    return file;
   1327 	}
   1328 
   1329 	(void)Lst_Open(path);
   1330 	while ((ln = Lst_Next(path)) != NULL) {
   1331 	    p = (Path *)Lst_Datum(ln);
   1332 	    if (p == dotLast)
   1333 		continue;
   1334 	    if ((file = DirLookupAbs(p, name, cp)) != NULL) {
   1335 		Lst_Close(path);
   1336 		if (file[0] == '\0') {
   1337 		    free(file);
   1338 		    return NULL;
   1339 		}
   1340 		return file;
   1341 	    }
   1342 	}
   1343 	Lst_Close(path);
   1344 
   1345 	if (hasLastDot && cur && ((file = DirLookupAbs(cur, name, cp))
   1346 		!= NULL)) {
   1347 	    if (file[0] == '\0') {
   1348 		free(file);
   1349 		return NULL;
   1350 	    }
   1351 	    return file;
   1352 	}
   1353     }
   1354 
   1355     /*
   1356      * Didn't find it that way, either. Sigh. Phase 3. Add its directory
   1357      * onto the search path in any case, just in case, then look for the
   1358      * thing in the hash table. If we find it, grand. We return a new
   1359      * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
   1360      * Note that if the directory holding the file doesn't exist, this will
   1361      * do an extra search of the final directory on the path. Unless something
   1362      * weird happens, this search won't succeed and life will be groovy.
   1363      *
   1364      * Sigh. We cannot add the directory onto the search path because
   1365      * of this amusing case:
   1366      * $(INSTALLDIR)/$(FILE): $(FILE)
   1367      *
   1368      * $(FILE) exists in $(INSTALLDIR) but not in the current one.
   1369      * When searching for $(FILE), we will find it in $(INSTALLDIR)
   1370      * b/c we added it here. This is not good...
   1371      */
   1372 #ifdef notdef
   1373     if (cp == traling_dot) {
   1374 	cp = strrchr(name, '/');
   1375 	cp += 1;
   1376     }
   1377     cp[-1] = '\0';
   1378     (void)Dir_AddDir(path, name);
   1379     cp[-1] = '/';
   1380 
   1381     bigmisses += 1;
   1382     ln = Lst_Last(path);
   1383     if (ln == NULL) {
   1384 	return NULL;
   1385     } else {
   1386 	p = (Path *)Lst_Datum(ln);
   1387     }
   1388 
   1389     if (Hash_FindEntry(&p->files, cp) != NULL) {
   1390 	return bmake_strdup(name);
   1391     } else {
   1392 	return NULL;
   1393     }
   1394 #else /* !notdef */
   1395     if (DEBUG(DIR)) {
   1396 	fprintf(debug_file, "   Looking for \"%s\" ...\n", name);
   1397     }
   1398 
   1399     bigmisses += 1;
   1400     if (cached_stat(name, &stb) == 0) {
   1401 	return bmake_strdup(name);
   1402     }
   1403 
   1404     if (DEBUG(DIR)) {
   1405 	fprintf(debug_file, "   failed. Returning NULL\n");
   1406     }
   1407     return NULL;
   1408 #endif /* notdef */
   1409 }
   1410 
   1411 
   1412 /*-
   1413  *-----------------------------------------------------------------------
   1414  * Dir_FindHereOrAbove  --
   1415  *	search for a path starting at a given directory and then working
   1416  *	our way up towards the root.
   1417  *
   1418  * Input:
   1419  *	here		starting directory
   1420  *	search_path	the path we are looking for
   1421  *	result		the result of a successful search is placed here
   1422  *	rlen		the length of the result buffer
   1423  *			(typically MAXPATHLEN + 1)
   1424  *
   1425  * Results:
   1426  *	0 on failure, 1 on success [in which case the found path is put
   1427  *	in the result buffer].
   1428  *
   1429  * Side Effects:
   1430  *-----------------------------------------------------------------------
   1431  */
   1432 int
   1433 Dir_FindHereOrAbove(char *here, char *search_path, char *result, int rlen) {
   1434 
   1435 	struct stat st;
   1436 	char dirbase[MAXPATHLEN + 1], *db_end;
   1437         char try[MAXPATHLEN + 1], *try_end;
   1438 
   1439 	/* copy out our starting point */
   1440 	snprintf(dirbase, sizeof(dirbase), "%s", here);
   1441 	db_end = dirbase + strlen(dirbase);
   1442 
   1443 	/* loop until we determine a result */
   1444 	while (1) {
   1445 
   1446 		/* try and stat(2) it ... */
   1447 		snprintf(try, sizeof(try), "%s/%s", dirbase, search_path);
   1448 		if (cached_stat(try, &st) != -1) {
   1449 			/*
   1450 			 * success!  if we found a file, chop off
   1451 			 * the filename so we return a directory.
   1452 			 */
   1453 			if ((st.st_mode & S_IFMT) != S_IFDIR) {
   1454 				try_end = try + strlen(try);
   1455 				while (try_end > try && *try_end != '/')
   1456 					try_end--;
   1457 				if (try_end > try)
   1458 					*try_end = 0;	/* chop! */
   1459 			}
   1460 
   1461 			/*
   1462 			 * done!
   1463 			 */
   1464 			snprintf(result, rlen, "%s", try);
   1465 			return 1;
   1466 		}
   1467 
   1468 		/*
   1469 		 * nope, we didn't find it.  if we used up dirbase we've
   1470 		 * reached the root and failed.
   1471 		 */
   1472 		if (db_end == dirbase)
   1473 			break;		/* failed! */
   1474 
   1475 		/*
   1476 		 * truncate dirbase from the end to move up a dir
   1477 		 */
   1478 		while (db_end > dirbase && *db_end != '/')
   1479 			db_end--;
   1480 		*db_end = 0;		/* chop! */
   1481 
   1482 	} /* while (1) */
   1483 
   1484 	/*
   1485 	 * we failed...
   1486 	 */
   1487 	return 0;
   1488 }
   1489 
   1490 /*-
   1491  *-----------------------------------------------------------------------
   1492  * Dir_MTime  --
   1493  *	Find the modification time of the file described by gn along the
   1494  *	search path dirSearchPath.
   1495  *
   1496  * Input:
   1497  *	gn		the file whose modification time is desired
   1498  *
   1499  * Results:
   1500  *	The modification time or 0 if it doesn't exist
   1501  *
   1502  * Side Effects:
   1503  *	The modification time is placed in the node's mtime slot.
   1504  *	If the node didn't have a path entry before, and Dir_FindFile
   1505  *	found one for it, the full name is placed in the path slot.
   1506  *-----------------------------------------------------------------------
   1507  */
   1508 int
   1509 Dir_MTime(GNode *gn, Boolean recheck)
   1510 {
   1511     char          *fullName;  /* the full pathname of name */
   1512     struct stat	  stb;	      /* buffer for finding the mod time */
   1513 
   1514     if (gn->type & OP_ARCHV) {
   1515 	return Arch_MTime(gn);
   1516     } else if (gn->type & OP_PHONY) {
   1517 	gn->mtime = 0;
   1518 	return 0;
   1519     } else if (gn->path == NULL) {
   1520 	if (gn->type & OP_NOPATH)
   1521 	    fullName = NULL;
   1522 	else {
   1523 	    fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
   1524 	    if (fullName == NULL && gn->flags & FROM_DEPEND &&
   1525 		!Lst_IsEmpty(gn->iParents)) {
   1526 		char *cp;
   1527 
   1528 		cp = strrchr(gn->name, '/');
   1529 		if (cp) {
   1530 		    /*
   1531 		     * This is an implied source, and it may have moved,
   1532 		     * see if we can find it via the current .PATH
   1533 		     */
   1534 		    cp++;
   1535 
   1536 		    fullName = Dir_FindFile(cp, Suff_FindPath(gn));
   1537 		    if (fullName) {
   1538 			/*
   1539 			 * Put the found file in gn->path
   1540 			 * so that we give that to the compiler.
   1541 			 */
   1542 			gn->path = bmake_strdup(fullName);
   1543 			if (!Job_RunTarget(".STALE", gn->fname))
   1544 			    fprintf(stdout,
   1545 				"%s: %s, %d: ignoring stale %s for %s, "
   1546 				"found %s\n", progname, gn->fname, gn->lineno,
   1547 				makeDependfile, gn->name, fullName);
   1548 		    }
   1549 		}
   1550 	    }
   1551 	    if (DEBUG(DIR))
   1552 		fprintf(debug_file, "Found '%s' as '%s'\n",
   1553 			gn->name, fullName ? fullName : "(not found)" );
   1554 	}
   1555     } else {
   1556 	fullName = gn->path;
   1557     }
   1558 
   1559     if (fullName == NULL) {
   1560 	fullName = bmake_strdup(gn->name);
   1561     }
   1562 
   1563     if (cached_stats(&mtimes, fullName, &stb, recheck ? CST_UPDATE : 0) < 0) {
   1564 	if (gn->type & OP_MEMBER) {
   1565 	    if (fullName != gn->path)
   1566 		free(fullName);
   1567 	    return Arch_MemMTime(gn);
   1568 	} else {
   1569 	    stb.st_mtime = 0;
   1570 	}
   1571     }
   1572 
   1573     if (fullName && gn->path == NULL) {
   1574 	gn->path = fullName;
   1575     }
   1576 
   1577     gn->mtime = stb.st_mtime;
   1578     return gn->mtime;
   1579 }
   1580 
   1581 /*-
   1582  *-----------------------------------------------------------------------
   1583  * Dir_AddDir --
   1584  *	Add the given name to the end of the given path. The order of
   1585  *	the arguments is backwards so ParseDoDependency can do a
   1586  *	Lst_ForEach of its list of paths...
   1587  *
   1588  * Input:
   1589  *	path		the path to which the directory should be
   1590  *			added
   1591  *	name		the name of the directory to add
   1592  *
   1593  * Results:
   1594  *	none
   1595  *
   1596  * Side Effects:
   1597  *	A structure is added to the list and the directory is
   1598  *	read and hashed.
   1599  *-----------------------------------------------------------------------
   1600  */
   1601 Path *
   1602 Dir_AddDir(Lst path, const char *name)
   1603 {
   1604     LstNode       ln = NULL; /* node in case Path structure is found */
   1605     Path	  *p = NULL;  /* pointer to new Path structure */
   1606     DIR     	  *d;	      /* for reading directory */
   1607     struct dirent *dp;	      /* entry in directory */
   1608 
   1609     if (strcmp(name, ".DOTLAST") == 0) {
   1610 	ln = Lst_Find(path, name, DirFindName);
   1611 	if (ln != NULL)
   1612 	    return (Path *)Lst_Datum(ln);
   1613 	else {
   1614 	    dotLast->refCount += 1;
   1615 	    (void)Lst_AtFront(path, dotLast);
   1616 	}
   1617     }
   1618 
   1619     if (path)
   1620 	ln = Lst_Find(openDirectories, name, DirFindName);
   1621     if (ln != NULL) {
   1622 	p = (Path *)Lst_Datum(ln);
   1623 	if (path && Lst_Member(path, p) == NULL) {
   1624 	    p->refCount += 1;
   1625 	    (void)Lst_AtEnd(path, p);
   1626 	}
   1627     } else {
   1628 	if (DEBUG(DIR)) {
   1629 	    fprintf(debug_file, "Caching %s ...", name);
   1630 	}
   1631 
   1632 	if ((d = opendir(name)) != NULL) {
   1633 	    p = bmake_malloc(sizeof(Path));
   1634 	    p->name = bmake_strdup(name);
   1635 	    p->hits = 0;
   1636 	    p->refCount = 1;
   1637 	    Hash_InitTable(&p->files, -1);
   1638 
   1639 	    while ((dp = readdir(d)) != NULL) {
   1640 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
   1641 		/*
   1642 		 * The sun directory library doesn't check for a 0 inode
   1643 		 * (0-inode slots just take up space), so we have to do
   1644 		 * it ourselves.
   1645 		 */
   1646 		if (dp->d_fileno == 0) {
   1647 		    continue;
   1648 		}
   1649 #endif /* sun && d_ino */
   1650 		(void)Hash_CreateEntry(&p->files, dp->d_name, NULL);
   1651 	    }
   1652 	    (void)closedir(d);
   1653 	    (void)Lst_AtEnd(openDirectories, p);
   1654 	    if (path != NULL)
   1655 		(void)Lst_AtEnd(path, p);
   1656 	}
   1657 	if (DEBUG(DIR)) {
   1658 	    fprintf(debug_file, "done\n");
   1659 	}
   1660     }
   1661     return p;
   1662 }
   1663 
   1664 /*-
   1665  *-----------------------------------------------------------------------
   1666  * Dir_CopyDir --
   1667  *	Callback function for duplicating a search path via Lst_Duplicate.
   1668  *	Ups the reference count for the directory.
   1669  *
   1670  * Results:
   1671  *	Returns the Path it was given.
   1672  *
   1673  * Side Effects:
   1674  *	The refCount of the path is incremented.
   1675  *
   1676  *-----------------------------------------------------------------------
   1677  */
   1678 void *
   1679 Dir_CopyDir(void *p)
   1680 {
   1681     ((Path *)p)->refCount += 1;
   1682 
   1683     return p;
   1684 }
   1685 
   1686 /*-
   1687  *-----------------------------------------------------------------------
   1688  * Dir_MakeFlags --
   1689  *	Make a string by taking all the directories in the given search
   1690  *	path and preceding them by the given flag. Used by the suffix
   1691  *	module to create variables for compilers based on suffix search
   1692  *	paths.
   1693  *
   1694  * Input:
   1695  *	flag		flag which should precede each directory
   1696  *	path		list of directories
   1697  *
   1698  * Results:
   1699  *	The string mentioned above. Note that there is no space between
   1700  *	the given flag and each directory. The empty string is returned if
   1701  *	Things don't go well.
   1702  *
   1703  * Side Effects:
   1704  *	None
   1705  *-----------------------------------------------------------------------
   1706  */
   1707 char *
   1708 Dir_MakeFlags(const char *flag, Lst path)
   1709 {
   1710     char	  *str;	  /* the string which will be returned */
   1711     char	  *s1, *s2;/* the current directory preceded by 'flag' */
   1712     LstNode	  ln;	  /* the node of the current directory */
   1713     Path	  *p;	  /* the structure describing the current directory */
   1714 
   1715     str = bmake_strdup("");
   1716 
   1717     if (Lst_Open(path) == SUCCESS) {
   1718 	while ((ln = Lst_Next(path)) != NULL) {
   1719 	    p = (Path *)Lst_Datum(ln);
   1720 	    s2 = str_concat(flag, p->name, 0);
   1721 	    str = str_concat(s1 = str, s2, STR_ADDSPACE);
   1722 	    free(s1);
   1723 	    free(s2);
   1724 	}
   1725 	Lst_Close(path);
   1726     }
   1727 
   1728     return str;
   1729 }
   1730 
   1731 /*-
   1732  *-----------------------------------------------------------------------
   1733  * Dir_Destroy --
   1734  *	Nuke a directory descriptor, if possible. Callback procedure
   1735  *	for the suffixes module when destroying a search path.
   1736  *
   1737  * Input:
   1738  *	pp		The directory descriptor to nuke
   1739  *
   1740  * Results:
   1741  *	None.
   1742  *
   1743  * Side Effects:
   1744  *	If no other path references this directory (refCount == 0),
   1745  *	the Path and all its data are freed.
   1746  *
   1747  *-----------------------------------------------------------------------
   1748  */
   1749 void
   1750 Dir_Destroy(void *pp)
   1751 {
   1752     Path    	  *p = (Path *)pp;
   1753     p->refCount -= 1;
   1754 
   1755     if (p->refCount == 0) {
   1756 	LstNode	ln;
   1757 
   1758 	ln = Lst_Member(openDirectories, p);
   1759 	(void)Lst_Remove(openDirectories, ln);
   1760 
   1761 	Hash_DeleteTable(&p->files);
   1762 	free(p->name);
   1763 	free(p);
   1764     }
   1765 }
   1766 
   1767 /*-
   1768  *-----------------------------------------------------------------------
   1769  * Dir_ClearPath --
   1770  *	Clear out all elements of the given search path. This is different
   1771  *	from destroying the list, notice.
   1772  *
   1773  * Input:
   1774  *	path		Path to clear
   1775  *
   1776  * Results:
   1777  *	None.
   1778  *
   1779  * Side Effects:
   1780  *	The path is set to the empty list.
   1781  *
   1782  *-----------------------------------------------------------------------
   1783  */
   1784 void
   1785 Dir_ClearPath(Lst path)
   1786 {
   1787     Path    *p;
   1788     while (!Lst_IsEmpty(path)) {
   1789 	p = (Path *)Lst_DeQueue(path);
   1790 	Dir_Destroy(p);
   1791     }
   1792 }
   1793 
   1794 
   1795 /*-
   1796  *-----------------------------------------------------------------------
   1797  * Dir_Concat --
   1798  *	Concatenate two paths, adding the second to the end of the first.
   1799  *	Makes sure to avoid duplicates.
   1800  *
   1801  * Input:
   1802  *	path1		Dest
   1803  *	path2		Source
   1804  *
   1805  * Results:
   1806  *	None
   1807  *
   1808  * Side Effects:
   1809  *	Reference counts for added dirs are upped.
   1810  *
   1811  *-----------------------------------------------------------------------
   1812  */
   1813 void
   1814 Dir_Concat(Lst path1, Lst path2)
   1815 {
   1816     LstNode ln;
   1817     Path    *p;
   1818 
   1819     for (ln = Lst_First(path2); ln != NULL; ln = Lst_Succ(ln)) {
   1820 	p = (Path *)Lst_Datum(ln);
   1821 	if (Lst_Member(path1, p) == NULL) {
   1822 	    p->refCount += 1;
   1823 	    (void)Lst_AtEnd(path1, p);
   1824 	}
   1825     }
   1826 }
   1827 
   1828 /********** DEBUG INFO **********/
   1829 void
   1830 Dir_PrintDirectories(void)
   1831 {
   1832     LstNode	ln;
   1833     Path	*p;
   1834 
   1835     fprintf(debug_file, "#*** Directory Cache:\n");
   1836     fprintf(debug_file, "# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
   1837 	      hits, misses, nearmisses, bigmisses,
   1838 	      (hits+bigmisses+nearmisses ?
   1839 	       hits * 100 / (hits + bigmisses + nearmisses) : 0));
   1840     fprintf(debug_file, "# %-20s referenced\thits\n", "directory");
   1841     if (Lst_Open(openDirectories) == SUCCESS) {
   1842 	while ((ln = Lst_Next(openDirectories)) != NULL) {
   1843 	    p = (Path *)Lst_Datum(ln);
   1844 	    fprintf(debug_file, "# %-20s %10d\t%4d\n", p->name, p->refCount, p->hits);
   1845 	}
   1846 	Lst_Close(openDirectories);
   1847     }
   1848 }
   1849 
   1850 static int
   1851 DirPrintDir(void *p, void *dummy MAKE_ATTR_UNUSED)
   1852 {
   1853     fprintf(debug_file, "%s ", ((Path *)p)->name);
   1854     return 0;
   1855 }
   1856 
   1857 void
   1858 Dir_PrintPath(Lst path)
   1859 {
   1860     Lst_ForEach(path, DirPrintDir, NULL);
   1861 }
   1862