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