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