Home | History | Annotate | Line # | Download | only in make
dir.c revision 1.21
      1 /*	$NetBSD: dir.c,v 1.21 1999/07/11 02:06:57 thorpej 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.21 1999/07/11 02:06:57 thorpej 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.21 1999/07/11 02:06:57 thorpej 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     if (cur) {
    279 	cur->refCount -= 1;
    280 	Dir_Destroy((ClientData) cur);
    281     }
    282     dot->refCount -= 1;
    283     dotLast->refCount -= 1;
    284     Dir_Destroy((ClientData) dotLast);
    285     Dir_Destroy((ClientData) dot);
    286     Dir_ClearPath(dirSearchPath);
    287     Lst_Destroy(dirSearchPath, NOFREE);
    288     Dir_ClearPath(openDirectories);
    289     Lst_Destroy(openDirectories, NOFREE);
    290     Hash_DeleteTable(&mtimes);
    291 }
    292 
    293 /*-
    294  *-----------------------------------------------------------------------
    295  * DirFindName --
    296  *	See if the Path structure describes the same directory as the
    297  *	given one by comparing their names. Called from Dir_AddDir via
    298  *	Lst_Find when searching the list of open directories.
    299  *
    300  * Results:
    301  *	0 if it is the same. Non-zero otherwise
    302  *
    303  * Side Effects:
    304  *	None
    305  *-----------------------------------------------------------------------
    306  */
    307 static int
    308 DirFindName (p, dname)
    309     ClientData    p;	      /* Current name */
    310     ClientData	  dname;      /* Desired name */
    311 {
    312     return (strcmp (((Path *)p)->name, (char *) dname));
    313 }
    314 
    315 /*-
    316  *-----------------------------------------------------------------------
    317  * Dir_HasWildcards  --
    318  *	see if the given name has any wildcard characters in it
    319  *	be careful not to expand unmatching brackets or braces.
    320  *	XXX: This code is not 100% correct. ([^]] fails etc.)
    321  *	I really don't think that make(1) should be expanding
    322  *	patterns, because then you have to set a mechanism for
    323  *	escaping the expansion!
    324  *
    325  * Results:
    326  *	returns TRUE if the word should be expanded, FALSE otherwise
    327  *
    328  * Side Effects:
    329  *	none
    330  *-----------------------------------------------------------------------
    331  */
    332 Boolean
    333 Dir_HasWildcards (name)
    334     char          *name;	/* name to check */
    335 {
    336     register char *cp;
    337     int wild = 0, brace = 0, bracket = 0;
    338 
    339     for (cp = name; *cp; cp++) {
    340 	switch(*cp) {
    341 	case '{':
    342 		brace++;
    343 		wild = 1;
    344 		break;
    345 	case '}':
    346 		brace--;
    347 		break;
    348 	case '[':
    349 		bracket++;
    350 		wild = 1;
    351 		break;
    352 	case ']':
    353 		bracket--;
    354 		break;
    355 	case '?':
    356 	case '*':
    357 		wild = 1;
    358 		break;
    359 	default:
    360 		break;
    361 	}
    362     }
    363     return wild && bracket == 0 && brace == 0;
    364 }
    365 
    366 /*-
    367  *-----------------------------------------------------------------------
    368  * DirMatchFiles --
    369  * 	Given a pattern and a Path structure, see if any files
    370  *	match the pattern and add their names to the 'expansions' list if
    371  *	any do. This is incomplete -- it doesn't take care of patterns like
    372  *	src / *src / *.c properly (just *.c on any of the directories), but it
    373  *	will do for now.
    374  *
    375  * Results:
    376  *	Always returns 0
    377  *
    378  * Side Effects:
    379  *	File names are added to the expansions lst. The directory will be
    380  *	fully hashed when this is done.
    381  *-----------------------------------------------------------------------
    382  */
    383 static int
    384 DirMatchFiles (pattern, p, expansions)
    385     char	  *pattern;   	/* Pattern to look for */
    386     Path	  *p;         	/* Directory to search */
    387     Lst	    	  expansions;	/* Place to store the results */
    388 {
    389     Hash_Search	  search;   	/* Index into the directory's table */
    390     Hash_Entry	  *entry;   	/* Current entry in the table */
    391     Boolean 	  isDot;    	/* TRUE if the directory being searched is . */
    392 
    393     isDot = (*p->name == '.' && p->name[1] == '\0');
    394 
    395     for (entry = Hash_EnumFirst(&p->files, &search);
    396 	 entry != (Hash_Entry *)NULL;
    397 	 entry = Hash_EnumNext(&search))
    398     {
    399 	/*
    400 	 * See if the file matches the given pattern. Note we follow the UNIX
    401 	 * convention that dot files will only be found if the pattern
    402 	 * begins with a dot (note also that as a side effect of the hashing
    403 	 * scheme, .* won't match . or .. since they aren't hashed).
    404 	 */
    405 	if (Str_Match(entry->name, pattern) &&
    406 	    ((entry->name[0] != '.') ||
    407 	     (pattern[0] == '.')))
    408 	{
    409 	    (void)Lst_AtEnd(expansions,
    410 			    (isDot ? estrdup(entry->name) :
    411 			     str_concat(p->name, entry->name,
    412 					STR_ADDSLASH)));
    413 	}
    414     }
    415     return (0);
    416 }
    417 
    418 /*-
    419  *-----------------------------------------------------------------------
    420  * DirExpandCurly --
    421  *	Expand curly braces like the C shell. Does this recursively.
    422  *	Note the special case: if after the piece of the curly brace is
    423  *	done there are no wildcard characters in the result, the result is
    424  *	placed on the list WITHOUT CHECKING FOR ITS EXISTENCE.
    425  *
    426  * Results:
    427  *	None.
    428  *
    429  * Side Effects:
    430  *	The given list is filled with the expansions...
    431  *
    432  *-----------------------------------------------------------------------
    433  */
    434 static void
    435 DirExpandCurly(word, brace, path, expansions)
    436     char    	  *word;    	/* Entire word to expand */
    437     char    	  *brace;   	/* First curly brace in it */
    438     Lst	    	  path;	    	/* Search path to use */
    439     Lst	    	  expansions;	/* Place to store the expansions */
    440 {
    441     char    	  *end;	    	/* Character after the closing brace */
    442     char    	  *cp;	    	/* Current position in brace clause */
    443     char    	  *start;   	/* Start of current piece of brace clause */
    444     int	    	  bracelevel;	/* Number of braces we've seen. If we see a
    445 				 * right brace when this is 0, we've hit the
    446 				 * end of the clause. */
    447     char    	  *file;    	/* Current expansion */
    448     int	    	  otherLen; 	/* The length of the other pieces of the
    449 				 * expansion (chars before and after the
    450 				 * clause in 'word') */
    451     char    	  *cp2;	    	/* Pointer for checking for wildcards in
    452 				 * expansion before calling Dir_Expand */
    453 
    454     start = brace+1;
    455 
    456     /*
    457      * Find the end of the brace clause first, being wary of nested brace
    458      * clauses.
    459      */
    460     for (end = start, bracelevel = 0; *end != '\0'; end++) {
    461 	if (*end == '{') {
    462 	    bracelevel++;
    463 	} else if ((*end == '}') && (bracelevel-- == 0)) {
    464 	    break;
    465 	}
    466     }
    467     if (*end == '\0') {
    468 	Error("Unterminated {} clause \"%s\"", start);
    469 	return;
    470     } else {
    471 	end++;
    472     }
    473     otherLen = brace - word + strlen(end);
    474 
    475     for (cp = start; cp < end; cp++) {
    476 	/*
    477 	 * Find the end of this piece of the clause.
    478 	 */
    479 	bracelevel = 0;
    480 	while (*cp != ',') {
    481 	    if (*cp == '{') {
    482 		bracelevel++;
    483 	    } else if ((*cp == '}') && (bracelevel-- <= 0)) {
    484 		break;
    485 	    }
    486 	    cp++;
    487 	}
    488 	/*
    489 	 * Allocate room for the combination and install the three pieces.
    490 	 */
    491 	file = emalloc(otherLen + cp - start + 1);
    492 	if (brace != word) {
    493 	    strncpy(file, word, brace-word);
    494 	}
    495 	if (cp != start) {
    496 	    strncpy(&file[brace-word], start, cp-start);
    497 	}
    498 	strcpy(&file[(brace-word)+(cp-start)], end);
    499 
    500 	/*
    501 	 * See if the result has any wildcards in it. If we find one, call
    502 	 * Dir_Expand right away, telling it to place the result on our list
    503 	 * of expansions.
    504 	 */
    505 	for (cp2 = file; *cp2 != '\0'; cp2++) {
    506 	    switch(*cp2) {
    507 	    case '*':
    508 	    case '?':
    509 	    case '{':
    510 	    case '[':
    511 		Dir_Expand(file, path, expansions);
    512 		goto next;
    513 	    }
    514 	}
    515 	if (*cp2 == '\0') {
    516 	    /*
    517 	     * Hit the end w/o finding any wildcards, so stick the expansion
    518 	     * on the end of the list.
    519 	     */
    520 	    (void)Lst_AtEnd(expansions, file);
    521 	} else {
    522 	next:
    523 	    free(file);
    524 	}
    525 	start = cp+1;
    526     }
    527 }
    528 
    529 
    530 /*-
    531  *-----------------------------------------------------------------------
    532  * DirExpandInt --
    533  *	Internal expand routine. Passes through the directories in the
    534  *	path one by one, calling DirMatchFiles for each. NOTE: This still
    535  *	doesn't handle patterns in directories...
    536  *
    537  * Results:
    538  *	None.
    539  *
    540  * Side Effects:
    541  *	Things are added to the expansions list.
    542  *
    543  *-----------------------------------------------------------------------
    544  */
    545 static void
    546 DirExpandInt(word, path, expansions)
    547     char    	  *word;    	/* Word to expand */
    548     Lst	    	  path;	    	/* Path on which to look */
    549     Lst	    	  expansions;	/* Place to store the result */
    550 {
    551     LstNode 	  ln;	    	/* Current node */
    552     Path	  *p;	    	/* Directory in the node */
    553 
    554     if (Lst_Open(path) == SUCCESS) {
    555 	while ((ln = Lst_Next(path)) != NILLNODE) {
    556 	    p = (Path *)Lst_Datum(ln);
    557 	    DirMatchFiles(word, p, expansions);
    558 	}
    559 	Lst_Close(path);
    560     }
    561 }
    562 
    563 /*-
    564  *-----------------------------------------------------------------------
    565  * DirPrintWord --
    566  *	Print a word in the list of expansions. Callback for Dir_Expand
    567  *	when DEBUG(DIR), via Lst_ForEach.
    568  *
    569  * Results:
    570  *	=== 0
    571  *
    572  * Side Effects:
    573  *	The passed word is printed, followed by a space.
    574  *
    575  *-----------------------------------------------------------------------
    576  */
    577 static int
    578 DirPrintWord(word, dummy)
    579     ClientData  word;
    580     ClientData  dummy;
    581 {
    582     printf("%s ", (char *) word);
    583 
    584     return(dummy ? 0 : 0);
    585 }
    586 
    587 /*-
    588  *-----------------------------------------------------------------------
    589  * Dir_Expand  --
    590  *	Expand the given word into a list of words by globbing it looking
    591  *	in the directories on the given search path.
    592  *
    593  * Results:
    594  *	A list of words consisting of the files which exist along the search
    595  *	path matching the given pattern.
    596  *
    597  * Side Effects:
    598  *	Directories may be opened. Who knows?
    599  *-----------------------------------------------------------------------
    600  */
    601 void
    602 Dir_Expand (word, path, expansions)
    603     char    *word;      /* the word to expand */
    604     Lst     path;   	/* the list of directories in which to find
    605 			 * the resulting files */
    606     Lst	    expansions;	/* the list on which to place the results */
    607 {
    608     char    	  *cp;
    609 
    610     if (DEBUG(DIR)) {
    611 	printf("expanding \"%s\"...", word);
    612     }
    613 
    614     cp = strchr(word, '{');
    615     if (cp) {
    616 	DirExpandCurly(word, cp, path, expansions);
    617     } else {
    618 	cp = strchr(word, '/');
    619 	if (cp) {
    620 	    /*
    621 	     * The thing has a directory component -- find the first wildcard
    622 	     * in the string.
    623 	     */
    624 	    for (cp = word; *cp; cp++) {
    625 		if (*cp == '?' || *cp == '[' || *cp == '*' || *cp == '{') {
    626 		    break;
    627 		}
    628 	    }
    629 	    if (*cp == '{') {
    630 		/*
    631 		 * This one will be fun.
    632 		 */
    633 		DirExpandCurly(word, cp, path, expansions);
    634 		return;
    635 	    } else if (*cp != '\0') {
    636 		/*
    637 		 * Back up to the start of the component
    638 		 */
    639 		char  *dirpath;
    640 
    641 		while (cp > word && *cp != '/') {
    642 		    cp--;
    643 		}
    644 		if (cp != word) {
    645 		    char sc;
    646 		    /*
    647 		     * If the glob isn't in the first component, try and find
    648 		     * all the components up to the one with a wildcard.
    649 		     */
    650 		    sc = cp[1];
    651 		    cp[1] = '\0';
    652 		    dirpath = Dir_FindFile(word, path);
    653 		    cp[1] = sc;
    654 		    /*
    655 		     * dirpath is null if can't find the leading component
    656 		     * XXX: Dir_FindFile won't find internal components.
    657 		     * i.e. if the path contains ../Etc/Object and we're
    658 		     * looking for Etc, it won't be found. Ah well.
    659 		     * Probably not important.
    660 		     */
    661 		    if (dirpath != (char *)NULL) {
    662 			char *dp = &dirpath[strlen(dirpath) - 1];
    663 			if (*dp == '/')
    664 			    *dp = '\0';
    665 			path = Lst_Init(FALSE);
    666 			(void) Dir_AddDir(path, dirpath);
    667 			DirExpandInt(cp+1, path, expansions);
    668 			Lst_Destroy(path, NOFREE);
    669 		    }
    670 		} else {
    671 		    /*
    672 		     * Start the search from the local directory
    673 		     */
    674 		    DirExpandInt(word, path, expansions);
    675 		}
    676 	    } else {
    677 		/*
    678 		 * Return the file -- this should never happen.
    679 		 */
    680 		DirExpandInt(word, path, expansions);
    681 	    }
    682 	} else {
    683 	    /*
    684 	     * First the files in dot
    685 	     */
    686 	    DirMatchFiles(word, dot, expansions);
    687 
    688 	    /*
    689 	     * Then the files in every other directory on the path.
    690 	     */
    691 	    DirExpandInt(word, path, expansions);
    692 	}
    693     }
    694     if (DEBUG(DIR)) {
    695 	Lst_ForEach(expansions, DirPrintWord, (ClientData) 0);
    696 	fputc('\n', stdout);
    697     }
    698 }
    699 
    700 /*-
    701  *-----------------------------------------------------------------------
    702  * DirLookup  --
    703  *	Find if the file with the given name exists in the given path.
    704  *
    705  * Results:
    706  *	The path to the file, the empty string or NULL. If the file is
    707  *	the empty string, the search should be terminated.
    708  *	This path is guaranteed to be in a
    709  *	different part of memory than name and so may be safely free'd.
    710  *
    711  * Side Effects:
    712  *	None.
    713  *-----------------------------------------------------------------------
    714  */
    715 static char *
    716 DirLookup(p, name, cp, hasSlash)
    717     Path *p;
    718     char *name;
    719     char *cp;
    720     Boolean hasSlash;
    721 {
    722     char *p1;		/* pointer into p->name */
    723     char *p2;		/* pointer into name */
    724     char *file;		/* the current filename to check */
    725 
    726     if (DEBUG(DIR)) {
    727 	printf("%s...", p->name);
    728     }
    729     if (Hash_FindEntry (&p->files, cp) != (Hash_Entry *)NULL) {
    730 	if (DEBUG(DIR)) {
    731 	    printf("here...");
    732 	}
    733 	if (hasSlash) {
    734 	    /*
    735 	     * If the name had a slash, its initial components and p's
    736 	     * final components must match. This is false if a mismatch
    737 	     * is encountered before all of the initial components
    738 	     * have been checked (p2 > name at the end of the loop), or
    739 	     * we matched only part of one of the components of p
    740 	     * along with all the rest of them (*p1 != '/').
    741 	     */
    742 	    p1 = p->name + strlen (p->name) - 1;
    743 	    p2 = cp - 2;
    744 	    while (p2 >= name && p1 >= p->name && *p1 == *p2) {
    745 		p1 -= 1; p2 -= 1;
    746 	    }
    747 	    if (p2 >= name || (p1 >= p->name && *p1 != '/')) {
    748 		if (DEBUG(DIR)) {
    749 		    printf("component mismatch -- continuing...");
    750 		}
    751 		return NULL;
    752 	    }
    753 	}
    754 	file = str_concat (p->name, cp, STR_ADDSLASH);
    755 	if (DEBUG(DIR)) {
    756 	    printf("returning %s\n", file);
    757 	}
    758 	p->hits += 1;
    759 	hits += 1;
    760 	return file;
    761     } else if (hasSlash) {
    762 	/*
    763 	 * If the file has a leading path component and that component
    764 	 * exactly matches the entire name of the current search
    765 	 * directory, we assume the file doesn't exist and return NULL.
    766 	 */
    767 	for (p1 = p->name, p2 = name; *p1 && *p1 == *p2; p1++, p2++) {
    768 	    continue;
    769 	}
    770 	if (*p1 == '\0' && p2 == cp - 1) {
    771 	    if (DEBUG(DIR)) {
    772 		printf("must be here but isn't -- returing\n");
    773 	    }
    774 	    return "";
    775 	}
    776     }
    777     return NULL;
    778 }
    779 
    780 
    781 /*-
    782  *-----------------------------------------------------------------------
    783  * DirLookupSubdir  --
    784  *	Find if the file with the given name exists in the given path.
    785  *
    786  * Results:
    787  *	The path to the file or NULL. This path is guaranteed to be in a
    788  *	different part of memory than name and so may be safely free'd.
    789  *
    790  * Side Effects:
    791  *	If the file is found, it is added in the modification times hash
    792  *	table.
    793  *-----------------------------------------------------------------------
    794  */
    795 static char *
    796 DirLookupSubdir(p, name)
    797     Path *p;
    798     char *name;
    799 {
    800     struct stat	  stb;		/* Buffer for stat, if necessary */
    801     Hash_Entry	 *entry;	/* Entry for mtimes table */
    802     char 	 *file;		/* the current filename to check */
    803 
    804     if (p != dot) {
    805 	file = str_concat (p->name, name, STR_ADDSLASH);
    806     } else {
    807 	/*
    808 	 * Checking in dot -- DON'T put a leading ./ on the thing.
    809 	 */
    810 	file = estrdup(name);
    811     }
    812 
    813     if (DEBUG(DIR)) {
    814 	printf("checking %s...", file);
    815     }
    816 
    817     if (stat (file, &stb) == 0) {
    818 	if (DEBUG(DIR)) {
    819 	    printf("got it.\n");
    820 	}
    821 
    822 	/*
    823 	 * Save the modification time so if it's needed, we don't have
    824 	 * to fetch it again.
    825 	 */
    826 	if (DEBUG(DIR)) {
    827 	    printf("Caching %s for %s\n", Targ_FmtTime(stb.st_mtime),
    828 		    file);
    829 	}
    830 	entry = Hash_CreateEntry(&mtimes, (char *) file,
    831 				 (Boolean *)NULL);
    832 	Hash_SetValue(entry, (long)stb.st_mtime);
    833 	nearmisses += 1;
    834 	return (file);
    835     }
    836     free (file);
    837     return NULL;
    838 }
    839 
    840 /*-
    841  *-----------------------------------------------------------------------
    842  * DirFindDot  --
    843  *	Find the file given on "." or curdir
    844  *
    845  * Results:
    846  *	The path to the file or NULL. This path is guaranteed to be in a
    847  *	different part of memory than name and so may be safely free'd.
    848  *
    849  * Side Effects:
    850  *	Hit counts change
    851  *-----------------------------------------------------------------------
    852  */
    853 static char *
    854 DirFindDot(hasSlash, name, cp)
    855     Boolean hasSlash;
    856     char *name;
    857     char *cp;
    858 {
    859     char *file;
    860 
    861     if ((!hasSlash || (cp - name == 2 && *name == '.'))) {
    862 	if (Hash_FindEntry (&dot->files, cp) != (Hash_Entry *)NULL) {
    863 	    if (DEBUG(DIR)) {
    864 		printf("in '.'\n");
    865 	    }
    866 	    hits += 1;
    867 	    dot->hits += 1;
    868 	    return (estrdup (name));
    869 	}
    870 	if (cur &&
    871 	    Hash_FindEntry (&cur->files, cp) != (Hash_Entry *)NULL) {
    872 	    if (DEBUG(DIR)) {
    873 		printf("in ${.CURDIR} = %s\n", cur->name);
    874 	    }
    875 	    hits += 1;
    876 	    cur->hits += 1;
    877 	    return str_concat (cur->name, cp, STR_ADDSLASH);
    878 	}
    879     }
    880 
    881 
    882     if (cur && (file = DirLookup(cur, name, cp, hasSlash)) != NULL) {
    883 	if (*file)
    884 	    return file;
    885 	else
    886 	    return NULL;
    887     }
    888     return NULL;
    889 }
    890 
    891 /*-
    892  *-----------------------------------------------------------------------
    893  * Dir_FindFile  --
    894  *	Find the file with the given name along the given search path.
    895  *
    896  * Results:
    897  *	The path to the file or NULL. This path is guaranteed to be in a
    898  *	different part of memory than name and so may be safely free'd.
    899  *
    900  * Side Effects:
    901  *	If the file is found in a directory which is not on the path
    902  *	already (either 'name' is absolute or it is a relative path
    903  *	[ dir1/.../dirn/file ] which exists below one of the directories
    904  *	already on the search path), its directory is added to the end
    905  *	of the path on the assumption that there will be more files in
    906  *	that directory later on. Sometimes this is true. Sometimes not.
    907  *-----------------------------------------------------------------------
    908  */
    909 char *
    910 Dir_FindFile (name, path)
    911     char    	  *name;    /* the file to find */
    912     Lst           path;	    /* the Lst of directories to search */
    913 {
    914     LstNode       ln;			/* a list element */
    915     register char *file;		/* the current filename to check */
    916     register Path *p;			/* current path member */
    917     register char *cp;			/* index of first slash, if any */
    918     Boolean	  lastDot = TRUE;	/* true we should search dot last */
    919     Boolean	  hasSlash;		/* true if 'name' contains a / */
    920     struct stat	  stb;			/* Buffer for stat, if necessary */
    921     Hash_Entry	  *entry;		/* Entry for mtimes table */
    922 
    923     /*
    924      * Find the final component of the name and note whether it has a
    925      * slash in it (the name, I mean)
    926      */
    927     cp = strrchr (name, '/');
    928     if (cp) {
    929 	hasSlash = TRUE;
    930 	cp += 1;
    931     } else {
    932 	hasSlash = FALSE;
    933 	cp = name;
    934     }
    935 
    936     if (DEBUG(DIR)) {
    937 	printf("Searching for %s...", name);
    938     }
    939 
    940     if (Lst_Open (path) == FAILURE) {
    941 	if (DEBUG(DIR)) {
    942 	    printf("couldn't open path, file not found\n");
    943 	}
    944 	misses += 1;
    945 	return ((char *) NULL);
    946     }
    947 
    948     if ((ln = Lst_First (path)) != NILLNODE) {
    949 	p = (Path *) Lst_Datum (ln);
    950 	if (p == dotLast)
    951 	    lastDot = TRUE;
    952 	if (DEBUG(DIR)) {
    953 	    printf("[dot last]...");
    954 	}
    955     }
    956 
    957     /*
    958      * No matter what, we always look for the file in the current directory
    959      * before anywhere else and we *do not* add the ./ to it if it exists.
    960      * This is so there are no conflicts between what the user specifies
    961      * (fish.c) and what pmake finds (./fish.c).
    962      * Unless we found the magic DOTLAST path...
    963      */
    964     if (!lastDot && (file = DirFindDot(hasSlash, name, cp)) != NULL)
    965 	return file;
    966 
    967 
    968     /*
    969      * We look through all the directories on the path seeking one which
    970      * contains the final component of the given name and whose final
    971      * component(s) match the name's initial component(s). If such a beast
    972      * is found, we concatenate the directory name and the final component
    973      * and return the resulting string. If we don't find any such thing,
    974      * we go on to phase two...
    975      */
    976     while ((ln = Lst_Next (path)) != NILLNODE) {
    977 	p = (Path *) Lst_Datum (ln);
    978 	if (p == dotLast)
    979 	    continue;
    980         if ((file = DirLookup(p, name, cp, hasSlash)) != NULL) {
    981 	    Lst_Close (path);
    982 	    if (*file)
    983 		return file;
    984 	    else
    985 		return NULL;
    986 	}
    987     }
    988 
    989     if (lastDot && (file = DirFindDot(hasSlash, name, cp)) != NULL)
    990 	return file;
    991 
    992     /*
    993      * We didn't find the file on any existing members of the directory.
    994      * If the name doesn't contain a slash, that means it doesn't exist.
    995      * If it *does* contain a slash, however, there is still hope: it
    996      * could be in a subdirectory of one of the members of the search
    997      * path. (eg. /usr/include and sys/types.h. The above search would
    998      * fail to turn up types.h in /usr/include, but it *is* in
    999      * /usr/include/sys/types.h) If we find such a beast, we assume there
   1000      * will be more (what else can we assume?) and add all but the last
   1001      * component of the resulting name onto the search path (at the
   1002      * end). This phase is only performed if the file is *not* absolute.
   1003      */
   1004     if (!hasSlash) {
   1005 	if (DEBUG(DIR)) {
   1006 	    printf("failed.\n");
   1007 	}
   1008 	misses += 1;
   1009 	return ((char *) NULL);
   1010     }
   1011 
   1012     if (*name != '/') {
   1013 	Boolean	checkedDot = FALSE;
   1014 
   1015 	if (DEBUG(DIR)) {
   1016 	    printf("failed. Trying subdirectories...");
   1017 	}
   1018 
   1019 	if (!lastDot && cur && (file = DirLookupSubdir(cur, name)) != NULL)
   1020 	    return file;
   1021 
   1022 	(void) Lst_Open (path);
   1023 	while ((ln = Lst_Next (path)) != NILLNODE) {
   1024 	    p = (Path *) Lst_Datum (ln);
   1025 	    if (p == dotLast)
   1026 		continue;
   1027 	    if (p == dot)
   1028 		checkedDot = TRUE;
   1029 	    if ((file = DirLookupSubdir(p, name)) != NULL) {
   1030 		Lst_Close (path);
   1031 		return file;
   1032 	    }
   1033 	}
   1034 
   1035 	if (lastDot && cur && (file = DirLookupSubdir(cur, name)) != NULL)
   1036 	    return file;
   1037 
   1038 	if (DEBUG(DIR)) {
   1039 	    printf("failed. ");
   1040 	}
   1041 	Lst_Close (path);
   1042 
   1043 	if (checkedDot) {
   1044 	    /*
   1045 	     * Already checked by the given name, since . was in the path,
   1046 	     * so no point in proceeding...
   1047 	     */
   1048 	    if (DEBUG(DIR)) {
   1049 		printf("Checked . already, returning NULL\n");
   1050 	    }
   1051 	    return(NULL);
   1052 	}
   1053     }
   1054 
   1055     /*
   1056      * Didn't find it that way, either. Sigh. Phase 3. Add its directory
   1057      * onto the search path in any case, just in case, then look for the
   1058      * thing in the hash table. If we find it, grand. We return a new
   1059      * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
   1060      * Note that if the directory holding the file doesn't exist, this will
   1061      * do an extra search of the final directory on the path. Unless something
   1062      * weird happens, this search won't succeed and life will be groovy.
   1063      *
   1064      * Sigh. We cannot add the directory onto the search path because
   1065      * of this amusing case:
   1066      * $(INSTALLDIR)/$(FILE): $(FILE)
   1067      *
   1068      * $(FILE) exists in $(INSTALLDIR) but not in the current one.
   1069      * When searching for $(FILE), we will find it in $(INSTALLDIR)
   1070      * b/c we added it here. This is not good...
   1071      */
   1072 #ifdef notdef
   1073     cp[-1] = '\0';
   1074     (void) Dir_AddDir (path, name);
   1075     cp[-1] = '/';
   1076 
   1077     bigmisses += 1;
   1078     ln = Lst_Last (path);
   1079     if (ln == NILLNODE) {
   1080 	return ((char *) NULL);
   1081     } else {
   1082 	p = (Path *) Lst_Datum (ln);
   1083     }
   1084 
   1085     if (Hash_FindEntry (&p->files, cp) != (Hash_Entry *)NULL) {
   1086 	return (estrdup (name));
   1087     } else {
   1088 	return ((char *) NULL);
   1089     }
   1090 #else /* !notdef */
   1091     if (DEBUG(DIR)) {
   1092 	printf("Looking for \"%s\"...", name);
   1093     }
   1094 
   1095     bigmisses += 1;
   1096     entry = Hash_FindEntry(&mtimes, name);
   1097     if (entry != (Hash_Entry *)NULL) {
   1098 	if (DEBUG(DIR)) {
   1099 	    printf("got it (in mtime cache)\n");
   1100 	}
   1101 	return(estrdup(name));
   1102     } else if (stat (name, &stb) == 0) {
   1103 	entry = Hash_CreateEntry(&mtimes, name, (Boolean *)NULL);
   1104 	if (DEBUG(DIR)) {
   1105 	    printf("Caching %s for %s\n", Targ_FmtTime(stb.st_mtime),
   1106 		    name);
   1107 	}
   1108 	Hash_SetValue(entry, (long)stb.st_mtime);
   1109 	return (estrdup (name));
   1110     } else {
   1111 	if (DEBUG(DIR)) {
   1112 	    printf("failed. Returning NULL\n");
   1113 	}
   1114 	return ((char *)NULL);
   1115     }
   1116 #endif /* notdef */
   1117 }
   1118 
   1119 /*-
   1120  *-----------------------------------------------------------------------
   1121  * Dir_MTime  --
   1122  *	Find the modification time of the file described by gn along the
   1123  *	search path dirSearchPath.
   1124  *
   1125  * Results:
   1126  *	The modification time or 0 if it doesn't exist
   1127  *
   1128  * Side Effects:
   1129  *	The modification time is placed in the node's mtime slot.
   1130  *	If the node didn't have a path entry before, and Dir_FindFile
   1131  *	found one for it, the full name is placed in the path slot.
   1132  *-----------------------------------------------------------------------
   1133  */
   1134 int
   1135 Dir_MTime (gn)
   1136     GNode         *gn;	      /* the file whose modification time is
   1137 			       * desired */
   1138 {
   1139     char          *fullName;  /* the full pathname of name */
   1140     struct stat	  stb;	      /* buffer for finding the mod time */
   1141     Hash_Entry	  *entry;
   1142 
   1143     if (gn->type & OP_ARCHV) {
   1144 	return Arch_MTime (gn);
   1145     } else if (gn->path == (char *)NULL) {
   1146 	if (gn->type & (OP_PHONY|OP_NOPATH))
   1147 	    fullName = NULL;
   1148 	else
   1149 	    fullName = Dir_FindFile (gn->name, dirSearchPath);
   1150     } else {
   1151 	fullName = gn->path;
   1152     }
   1153 
   1154     if (fullName == (char *)NULL) {
   1155 	fullName = estrdup(gn->name);
   1156     }
   1157 
   1158     entry = Hash_FindEntry(&mtimes, fullName);
   1159     if (entry != (Hash_Entry *)NULL) {
   1160 	/*
   1161 	 * Only do this once -- the second time folks are checking to
   1162 	 * see if the file was actually updated, so we need to actually go
   1163 	 * to the file system.
   1164 	 */
   1165 	if (DEBUG(DIR)) {
   1166 	    printf("Using cached time %s for %s\n",
   1167 		    Targ_FmtTime((time_t)(long)Hash_GetValue(entry)), fullName);
   1168 	}
   1169 	stb.st_mtime = (time_t)(long)Hash_GetValue(entry);
   1170 	Hash_DeleteEntry(&mtimes, entry);
   1171     } else if (stat (fullName, &stb) < 0) {
   1172 	if (gn->type & OP_MEMBER) {
   1173 	    if (fullName != gn->path)
   1174 		free(fullName);
   1175 	    return Arch_MemMTime (gn);
   1176 	} else {
   1177 	    stb.st_mtime = 0;
   1178 	}
   1179     }
   1180     if (fullName && gn->path == (char *)NULL) {
   1181 	gn->path = fullName;
   1182     }
   1183 
   1184     gn->mtime = stb.st_mtime;
   1185     return (gn->mtime);
   1186 }
   1187 
   1188 /*-
   1189  *-----------------------------------------------------------------------
   1190  * Dir_AddDir --
   1191  *	Add the given name to the end of the given path. The order of
   1192  *	the arguments is backwards so ParseDoDependency can do a
   1193  *	Lst_ForEach of its list of paths...
   1194  *
   1195  * Results:
   1196  *	none
   1197  *
   1198  * Side Effects:
   1199  *	A structure is added to the list and the directory is
   1200  *	read and hashed.
   1201  *-----------------------------------------------------------------------
   1202  */
   1203 Path *
   1204 Dir_AddDir (path, name)
   1205     Lst           path;	      /* the path to which the directory should be
   1206 			       * added */
   1207     const char   *name;	      /* the name of the directory to add */
   1208 {
   1209     LstNode       ln;	      /* node in case Path structure is found */
   1210     register Path *p = NULL;  /* pointer to new Path structure */
   1211     DIR     	  *d;	      /* for reading directory */
   1212     register struct dirent *dp; /* entry in directory */
   1213 
   1214     if (strcmp(name, ".DOTLAST") == 0) {
   1215 	ln = Lst_Find (path, (ClientData)name, DirFindName);
   1216 	if (ln != NILLNODE)
   1217 	    return (Path *) Lst_Datum(ln);
   1218 	else {
   1219 	    dotLast->refCount += 1;
   1220 	    (void)Lst_AtFront(path, (ClientData)dotLast);
   1221 	}
   1222     }
   1223 
   1224     ln = Lst_Find (openDirectories, (ClientData)name, DirFindName);
   1225     if (ln != NILLNODE) {
   1226 	p = (Path *)Lst_Datum (ln);
   1227 	if (Lst_Member(path, (ClientData)p) == NILLNODE) {
   1228 	    p->refCount += 1;
   1229 	    (void)Lst_AtEnd (path, (ClientData)p);
   1230 	}
   1231     } else {
   1232 	if (DEBUG(DIR)) {
   1233 	    printf("Caching %s...", name);
   1234 	    fflush(stdout);
   1235 	}
   1236 
   1237 	if ((d = opendir (name)) != (DIR *) NULL) {
   1238 	    p = (Path *) emalloc (sizeof (Path));
   1239 	    p->name = estrdup (name);
   1240 	    p->hits = 0;
   1241 	    p->refCount = 1;
   1242 	    Hash_InitTable (&p->files, -1);
   1243 
   1244 	    /*
   1245 	     * Skip the first two entries -- these will *always* be . and ..
   1246 	     */
   1247 	    (void)readdir(d);
   1248 	    (void)readdir(d);
   1249 
   1250 	    while ((dp = readdir (d)) != (struct dirent *) NULL) {
   1251 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
   1252 		/*
   1253 		 * The sun directory library doesn't check for a 0 inode
   1254 		 * (0-inode slots just take up space), so we have to do
   1255 		 * it ourselves.
   1256 		 */
   1257 		if (dp->d_fileno == 0) {
   1258 		    continue;
   1259 		}
   1260 #endif /* sun && d_ino */
   1261 		(void)Hash_CreateEntry(&p->files, dp->d_name, (Boolean *)NULL);
   1262 	    }
   1263 	    (void) closedir (d);
   1264 	    (void)Lst_AtEnd (openDirectories, (ClientData)p);
   1265 	    if (path != NULL)
   1266 		(void)Lst_AtEnd (path, (ClientData)p);
   1267 	}
   1268 	if (DEBUG(DIR)) {
   1269 	    printf("done\n");
   1270 	}
   1271     }
   1272     return p;
   1273 }
   1274 
   1275 /*-
   1276  *-----------------------------------------------------------------------
   1277  * Dir_CopyDir --
   1278  *	Callback function for duplicating a search path via Lst_Duplicate.
   1279  *	Ups the reference count for the directory.
   1280  *
   1281  * Results:
   1282  *	Returns the Path it was given.
   1283  *
   1284  * Side Effects:
   1285  *	The refCount of the path is incremented.
   1286  *
   1287  *-----------------------------------------------------------------------
   1288  */
   1289 ClientData
   1290 Dir_CopyDir(p)
   1291     ClientData p;
   1292 {
   1293     ((Path *) p)->refCount += 1;
   1294 
   1295     return ((ClientData)p);
   1296 }
   1297 
   1298 /*-
   1299  *-----------------------------------------------------------------------
   1300  * Dir_MakeFlags --
   1301  *	Make a string by taking all the directories in the given search
   1302  *	path and preceding them by the given flag. Used by the suffix
   1303  *	module to create variables for compilers based on suffix search
   1304  *	paths.
   1305  *
   1306  * Results:
   1307  *	The string mentioned above. Note that there is no space between
   1308  *	the given flag and each directory. The empty string is returned if
   1309  *	Things don't go well.
   1310  *
   1311  * Side Effects:
   1312  *	None
   1313  *-----------------------------------------------------------------------
   1314  */
   1315 char *
   1316 Dir_MakeFlags (flag, path)
   1317     char	  *flag;  /* flag which should precede each directory */
   1318     Lst	    	  path;	  /* list of directories */
   1319 {
   1320     char	  *str;	  /* the string which will be returned */
   1321     char	  *tstr;  /* the current directory preceded by 'flag' */
   1322     LstNode	  ln;	  /* the node of the current directory */
   1323     Path	  *p;	  /* the structure describing the current directory */
   1324 
   1325     str = estrdup ("");
   1326 
   1327     if (Lst_Open (path) == SUCCESS) {
   1328 	while ((ln = Lst_Next (path)) != NILLNODE) {
   1329 	    p = (Path *) Lst_Datum (ln);
   1330 	    tstr = str_concat (flag, p->name, 0);
   1331 	    str = str_concat (str, tstr, STR_ADDSPACE | STR_DOFREE);
   1332 	}
   1333 	Lst_Close (path);
   1334     }
   1335 
   1336     return (str);
   1337 }
   1338 
   1339 /*-
   1340  *-----------------------------------------------------------------------
   1341  * Dir_Destroy --
   1342  *	Nuke a directory descriptor, if possible. Callback procedure
   1343  *	for the suffixes module when destroying a search path.
   1344  *
   1345  * Results:
   1346  *	None.
   1347  *
   1348  * Side Effects:
   1349  *	If no other path references this directory (refCount == 0),
   1350  *	the Path and all its data are freed.
   1351  *
   1352  *-----------------------------------------------------------------------
   1353  */
   1354 void
   1355 Dir_Destroy (pp)
   1356     ClientData 	  pp;	    /* The directory descriptor to nuke */
   1357 {
   1358     Path    	  *p = (Path *) pp;
   1359     p->refCount -= 1;
   1360 
   1361     if (p->refCount == 0) {
   1362 	LstNode	ln;
   1363 
   1364 	ln = Lst_Member (openDirectories, (ClientData)p);
   1365 	(void) Lst_Remove (openDirectories, ln);
   1366 
   1367 	Hash_DeleteTable (&p->files);
   1368 	free((Address)p->name);
   1369 	free((Address)p);
   1370     }
   1371 }
   1372 
   1373 /*-
   1374  *-----------------------------------------------------------------------
   1375  * Dir_ClearPath --
   1376  *	Clear out all elements of the given search path. This is different
   1377  *	from destroying the list, notice.
   1378  *
   1379  * Results:
   1380  *	None.
   1381  *
   1382  * Side Effects:
   1383  *	The path is set to the empty list.
   1384  *
   1385  *-----------------------------------------------------------------------
   1386  */
   1387 void
   1388 Dir_ClearPath(path)
   1389     Lst	    path; 	/* Path to clear */
   1390 {
   1391     Path    *p;
   1392     while (!Lst_IsEmpty(path)) {
   1393 	p = (Path *)Lst_DeQueue(path);
   1394 	Dir_Destroy((ClientData) p);
   1395     }
   1396 }
   1397 
   1398 
   1399 /*-
   1400  *-----------------------------------------------------------------------
   1401  * Dir_Concat --
   1402  *	Concatenate two paths, adding the second to the end of the first.
   1403  *	Makes sure to avoid duplicates.
   1404  *
   1405  * Results:
   1406  *	None
   1407  *
   1408  * Side Effects:
   1409  *	Reference counts for added dirs are upped.
   1410  *
   1411  *-----------------------------------------------------------------------
   1412  */
   1413 void
   1414 Dir_Concat(path1, path2)
   1415     Lst	    path1;  	/* Dest */
   1416     Lst	    path2;  	/* Source */
   1417 {
   1418     LstNode ln;
   1419     Path    *p;
   1420 
   1421     for (ln = Lst_First(path2); ln != NILLNODE; ln = Lst_Succ(ln)) {
   1422 	p = (Path *)Lst_Datum(ln);
   1423 	if (Lst_Member(path1, (ClientData)p) == NILLNODE) {
   1424 	    p->refCount += 1;
   1425 	    (void)Lst_AtEnd(path1, (ClientData)p);
   1426 	}
   1427     }
   1428 }
   1429 
   1430 /********** DEBUG INFO **********/
   1431 void
   1432 Dir_PrintDirectories()
   1433 {
   1434     LstNode	ln;
   1435     Path	*p;
   1436 
   1437     printf ("#*** Directory Cache:\n");
   1438     printf ("# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
   1439 	      hits, misses, nearmisses, bigmisses,
   1440 	      (hits+bigmisses+nearmisses ?
   1441 	       hits * 100 / (hits + bigmisses + nearmisses) : 0));
   1442     printf ("# %-20s referenced\thits\n", "directory");
   1443     if (Lst_Open (openDirectories) == SUCCESS) {
   1444 	while ((ln = Lst_Next (openDirectories)) != NILLNODE) {
   1445 	    p = (Path *) Lst_Datum (ln);
   1446 	    printf ("# %-20s %10d\t%4d\n", p->name, p->refCount, p->hits);
   1447 	}
   1448 	Lst_Close (openDirectories);
   1449     }
   1450 }
   1451 
   1452 static int DirPrintDir (p, dummy)
   1453     ClientData	p;
   1454     ClientData	dummy;
   1455 {
   1456     printf ("%s ", ((Path *) p)->name);
   1457     return (dummy ? 0 : 0);
   1458 }
   1459 
   1460 void
   1461 Dir_PrintPath (path)
   1462     Lst	path;
   1463 {
   1464     Lst_ForEach (path, DirPrintDir, (ClientData)0);
   1465 }
   1466