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