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