xref: /netbsd-src/usr.bin/make/dir.c (revision 220b5c059a84c51ea44107ea8951a57ffaecdc8c)
1 /*	$NetBSD: dir.c,v 1.28 2001/11/12 21:58:17 tv 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.28 2001/11/12 21:58:17 tv 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.28 2001/11/12 21:58:17 tv 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 
1014     if (lastDot && (file = DirFindDot(hasSlash, name, cp)) != NULL)
1015 	return file;
1016 
1017     /*
1018      * We didn't find the file on any existing members of the directory.
1019      * If the name doesn't contain a slash, that means it doesn't exist.
1020      * If it *does* contain a slash, however, there is still hope: it
1021      * could be in a subdirectory of one of the members of the search
1022      * path. (eg. /usr/include and sys/types.h. The above search would
1023      * fail to turn up types.h in /usr/include, but it *is* in
1024      * /usr/include/sys/types.h) If we find such a beast, we assume there
1025      * will be more (what else can we assume?) and add all but the last
1026      * component of the resulting name onto the search path (at the
1027      * end). This phase is only performed if the file is *not* absolute.
1028      */
1029     if (!hasSlash) {
1030 	if (DEBUG(DIR)) {
1031 	    printf("failed.\n");
1032 	}
1033 	misses += 1;
1034 	return ((char *) NULL);
1035     }
1036 
1037     if (*name != '/') {
1038 	Boolean	checkedDot = FALSE;
1039 
1040 	if (DEBUG(DIR)) {
1041 	    printf("failed. Trying subdirectories...");
1042 	}
1043 
1044 	if (!lastDot && cur && (file = DirLookupSubdir(cur, name)) != NULL)
1045 	    return file;
1046 
1047 	(void) Lst_Open (path);
1048 	while ((ln = Lst_Next (path)) != NILLNODE) {
1049 	    p = (Path *) Lst_Datum (ln);
1050 	    if (p == dotLast)
1051 		continue;
1052 	    if (p == dot)
1053 		checkedDot = TRUE;
1054 	    if ((file = DirLookupSubdir(p, name)) != NULL) {
1055 		Lst_Close (path);
1056 		return file;
1057 	    }
1058 	}
1059 
1060 	if (lastDot && cur && (file = DirLookupSubdir(cur, name)) != NULL)
1061 	    return file;
1062 
1063 	if (DEBUG(DIR)) {
1064 	    printf("failed. ");
1065 	}
1066 	Lst_Close (path);
1067 
1068 	if (checkedDot) {
1069 	    /*
1070 	     * Already checked by the given name, since . was in the path,
1071 	     * so no point in proceeding...
1072 	     */
1073 	    if (DEBUG(DIR)) {
1074 		printf("Checked . already, returning NULL\n");
1075 	    }
1076 	    return(NULL);
1077 	}
1078     }
1079 
1080     /*
1081      * Didn't find it that way, either. Sigh. Phase 3. Add its directory
1082      * onto the search path in any case, just in case, then look for the
1083      * thing in the hash table. If we find it, grand. We return a new
1084      * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
1085      * Note that if the directory holding the file doesn't exist, this will
1086      * do an extra search of the final directory on the path. Unless something
1087      * weird happens, this search won't succeed and life will be groovy.
1088      *
1089      * Sigh. We cannot add the directory onto the search path because
1090      * of this amusing case:
1091      * $(INSTALLDIR)/$(FILE): $(FILE)
1092      *
1093      * $(FILE) exists in $(INSTALLDIR) but not in the current one.
1094      * When searching for $(FILE), we will find it in $(INSTALLDIR)
1095      * b/c we added it here. This is not good...
1096      */
1097 #ifdef notdef
1098     cp[-1] = '\0';
1099     (void) Dir_AddDir (path, name);
1100     cp[-1] = '/';
1101 
1102     bigmisses += 1;
1103     ln = Lst_Last (path);
1104     if (ln == NILLNODE) {
1105 	return ((char *) NULL);
1106     } else {
1107 	p = (Path *) Lst_Datum (ln);
1108     }
1109 
1110     if (Hash_FindEntry (&p->files, cp) != (Hash_Entry *)NULL) {
1111 	return (estrdup (name));
1112     } else {
1113 	return ((char *) NULL);
1114     }
1115 #else /* !notdef */
1116     if (DEBUG(DIR)) {
1117 	printf("Looking for \"%s\"...", name);
1118     }
1119 
1120     bigmisses += 1;
1121     entry = Hash_FindEntry(&mtimes, name);
1122     if (entry != (Hash_Entry *)NULL) {
1123 	if (DEBUG(DIR)) {
1124 	    printf("got it (in mtime cache)\n");
1125 	}
1126 	return(estrdup(name));
1127     } else if (stat (name, &stb) == 0) {
1128 	entry = Hash_CreateEntry(&mtimes, name, (Boolean *)NULL);
1129 	if (DEBUG(DIR)) {
1130 	    printf("Caching %s for %s\n", Targ_FmtTime(stb.st_mtime),
1131 		    name);
1132 	}
1133 	Hash_SetValue(entry, (long)stb.st_mtime);
1134 	return (estrdup (name));
1135     } else {
1136 	if (DEBUG(DIR)) {
1137 	    printf("failed. Returning NULL\n");
1138 	}
1139 	return ((char *)NULL);
1140     }
1141 #endif /* notdef */
1142 }
1143 
1144 /*-
1145  *-----------------------------------------------------------------------
1146  * Dir_MTime  --
1147  *	Find the modification time of the file described by gn along the
1148  *	search path dirSearchPath.
1149  *
1150  * Results:
1151  *	The modification time or 0 if it doesn't exist
1152  *
1153  * Side Effects:
1154  *	The modification time is placed in the node's mtime slot.
1155  *	If the node didn't have a path entry before, and Dir_FindFile
1156  *	found one for it, the full name is placed in the path slot.
1157  *-----------------------------------------------------------------------
1158  */
1159 int
1160 Dir_MTime (gn)
1161     GNode         *gn;	      /* the file whose modification time is
1162 			       * desired */
1163 {
1164     char          *fullName;  /* the full pathname of name */
1165     struct stat	  stb;	      /* buffer for finding the mod time */
1166     Hash_Entry	  *entry;
1167 
1168     if (gn->type & OP_ARCHV) {
1169 	return Arch_MTime (gn);
1170     } else if (gn->path == (char *)NULL) {
1171 	if (gn->type & (OP_PHONY|OP_NOPATH))
1172 	    fullName = NULL;
1173 	else
1174 	    fullName = Dir_FindFile (gn->name, dirSearchPath);
1175     } else {
1176 	fullName = gn->path;
1177     }
1178 
1179     if (fullName == (char *)NULL) {
1180 	fullName = estrdup(gn->name);
1181     }
1182 
1183     entry = Hash_FindEntry(&mtimes, fullName);
1184     if (entry != (Hash_Entry *)NULL) {
1185 	/*
1186 	 * Only do this once -- the second time folks are checking to
1187 	 * see if the file was actually updated, so we need to actually go
1188 	 * to the file system.
1189 	 */
1190 	if (DEBUG(DIR)) {
1191 	    printf("Using cached time %s for %s\n",
1192 		    Targ_FmtTime((time_t)(long)Hash_GetValue(entry)), fullName);
1193 	}
1194 	stb.st_mtime = (time_t)(long)Hash_GetValue(entry);
1195 	Hash_DeleteEntry(&mtimes, entry);
1196     } else if (stat (fullName, &stb) < 0) {
1197 	if (gn->type & OP_MEMBER) {
1198 	    if (fullName != gn->path)
1199 		free(fullName);
1200 	    return Arch_MemMTime (gn);
1201 	} else {
1202 	    stb.st_mtime = 0;
1203 	}
1204     }
1205     if (fullName && gn->path == (char *)NULL) {
1206 	gn->path = fullName;
1207     }
1208 
1209     gn->mtime = stb.st_mtime;
1210     return (gn->mtime);
1211 }
1212 
1213 /*-
1214  *-----------------------------------------------------------------------
1215  * Dir_AddDir --
1216  *	Add the given name to the end of the given path. The order of
1217  *	the arguments is backwards so ParseDoDependency can do a
1218  *	Lst_ForEach of its list of paths...
1219  *
1220  * Results:
1221  *	none
1222  *
1223  * Side Effects:
1224  *	A structure is added to the list and the directory is
1225  *	read and hashed.
1226  *-----------------------------------------------------------------------
1227  */
1228 Path *
1229 Dir_AddDir (path, name)
1230     Lst           path;	      /* the path to which the directory should be
1231 			       * added */
1232     const char   *name;	      /* the name of the directory to add */
1233 {
1234     LstNode       ln;	      /* node in case Path structure is found */
1235     register Path *p = NULL;  /* pointer to new Path structure */
1236     DIR     	  *d;	      /* for reading directory */
1237     register struct dirent *dp; /* entry in directory */
1238 
1239     if (strcmp(name, ".DOTLAST") == 0) {
1240 	ln = Lst_Find (path, (ClientData)name, DirFindName);
1241 	if (ln != NILLNODE)
1242 	    return (Path *) Lst_Datum(ln);
1243 	else {
1244 	    dotLast->refCount += 1;
1245 	    (void)Lst_AtFront(path, (ClientData)dotLast);
1246 	}
1247     }
1248 
1249     ln = Lst_Find (openDirectories, (ClientData)name, DirFindName);
1250     if (ln != NILLNODE) {
1251 	p = (Path *)Lst_Datum (ln);
1252 	if (Lst_Member(path, (ClientData)p) == NILLNODE) {
1253 	    p->refCount += 1;
1254 	    (void)Lst_AtEnd (path, (ClientData)p);
1255 	}
1256     } else {
1257 	if (DEBUG(DIR)) {
1258 	    printf("Caching %s...", name);
1259 	    fflush(stdout);
1260 	}
1261 
1262 	if ((d = opendir (name)) != (DIR *) NULL) {
1263 	    p = (Path *) emalloc (sizeof (Path));
1264 	    p->name = estrdup (name);
1265 	    p->hits = 0;
1266 	    p->refCount = 1;
1267 	    Hash_InitTable (&p->files, -1);
1268 
1269 	    /*
1270 	     * Skip the first two entries -- these will *always* be . and ..
1271 	     */
1272 	    (void)readdir(d);
1273 	    (void)readdir(d);
1274 
1275 	    while ((dp = readdir (d)) != (struct dirent *) NULL) {
1276 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
1277 		/*
1278 		 * The sun directory library doesn't check for a 0 inode
1279 		 * (0-inode slots just take up space), so we have to do
1280 		 * it ourselves.
1281 		 */
1282 		if (dp->d_fileno == 0) {
1283 		    continue;
1284 		}
1285 #endif /* sun && d_ino */
1286 		(void)Hash_CreateEntry(&p->files, dp->d_name, (Boolean *)NULL);
1287 	    }
1288 	    (void) closedir (d);
1289 	    (void)Lst_AtEnd (openDirectories, (ClientData)p);
1290 	    if (path != NULL)
1291 		(void)Lst_AtEnd (path, (ClientData)p);
1292 	}
1293 	if (DEBUG(DIR)) {
1294 	    printf("done\n");
1295 	}
1296     }
1297     return p;
1298 }
1299 
1300 /*-
1301  *-----------------------------------------------------------------------
1302  * Dir_CopyDir --
1303  *	Callback function for duplicating a search path via Lst_Duplicate.
1304  *	Ups the reference count for the directory.
1305  *
1306  * Results:
1307  *	Returns the Path it was given.
1308  *
1309  * Side Effects:
1310  *	The refCount of the path is incremented.
1311  *
1312  *-----------------------------------------------------------------------
1313  */
1314 ClientData
1315 Dir_CopyDir(p)
1316     ClientData p;
1317 {
1318     ((Path *) p)->refCount += 1;
1319 
1320     return ((ClientData)p);
1321 }
1322 
1323 /*-
1324  *-----------------------------------------------------------------------
1325  * Dir_MakeFlags --
1326  *	Make a string by taking all the directories in the given search
1327  *	path and preceding them by the given flag. Used by the suffix
1328  *	module to create variables for compilers based on suffix search
1329  *	paths.
1330  *
1331  * Results:
1332  *	The string mentioned above. Note that there is no space between
1333  *	the given flag and each directory. The empty string is returned if
1334  *	Things don't go well.
1335  *
1336  * Side Effects:
1337  *	None
1338  *-----------------------------------------------------------------------
1339  */
1340 char *
1341 Dir_MakeFlags (flag, path)
1342     char	  *flag;  /* flag which should precede each directory */
1343     Lst	    	  path;	  /* list of directories */
1344 {
1345     char	  *str;	  /* the string which will be returned */
1346     char	  *tstr;  /* the current directory preceded by 'flag' */
1347     LstNode	  ln;	  /* the node of the current directory */
1348     Path	  *p;	  /* the structure describing the current directory */
1349 
1350     str = estrdup ("");
1351 
1352     if (Lst_Open (path) == SUCCESS) {
1353 	while ((ln = Lst_Next (path)) != NILLNODE) {
1354 	    p = (Path *) Lst_Datum (ln);
1355 	    tstr = str_concat (flag, p->name, 0);
1356 	    str = str_concat (str, tstr, STR_ADDSPACE | STR_DOFREE);
1357 	}
1358 	Lst_Close (path);
1359     }
1360 
1361     return (str);
1362 }
1363 
1364 /*-
1365  *-----------------------------------------------------------------------
1366  * Dir_Destroy --
1367  *	Nuke a directory descriptor, if possible. Callback procedure
1368  *	for the suffixes module when destroying a search path.
1369  *
1370  * Results:
1371  *	None.
1372  *
1373  * Side Effects:
1374  *	If no other path references this directory (refCount == 0),
1375  *	the Path and all its data are freed.
1376  *
1377  *-----------------------------------------------------------------------
1378  */
1379 void
1380 Dir_Destroy (pp)
1381     ClientData 	  pp;	    /* The directory descriptor to nuke */
1382 {
1383     Path    	  *p = (Path *) pp;
1384     p->refCount -= 1;
1385 
1386     if (p->refCount == 0) {
1387 	LstNode	ln;
1388 
1389 	ln = Lst_Member (openDirectories, (ClientData)p);
1390 	(void) Lst_Remove (openDirectories, ln);
1391 
1392 	Hash_DeleteTable (&p->files);
1393 	free((Address)p->name);
1394 	free((Address)p);
1395     }
1396 }
1397 
1398 /*-
1399  *-----------------------------------------------------------------------
1400  * Dir_ClearPath --
1401  *	Clear out all elements of the given search path. This is different
1402  *	from destroying the list, notice.
1403  *
1404  * Results:
1405  *	None.
1406  *
1407  * Side Effects:
1408  *	The path is set to the empty list.
1409  *
1410  *-----------------------------------------------------------------------
1411  */
1412 void
1413 Dir_ClearPath(path)
1414     Lst	    path; 	/* Path to clear */
1415 {
1416     Path    *p;
1417     while (!Lst_IsEmpty(path)) {
1418 	p = (Path *)Lst_DeQueue(path);
1419 	Dir_Destroy((ClientData) p);
1420     }
1421 }
1422 
1423 
1424 /*-
1425  *-----------------------------------------------------------------------
1426  * Dir_Concat --
1427  *	Concatenate two paths, adding the second to the end of the first.
1428  *	Makes sure to avoid duplicates.
1429  *
1430  * Results:
1431  *	None
1432  *
1433  * Side Effects:
1434  *	Reference counts for added dirs are upped.
1435  *
1436  *-----------------------------------------------------------------------
1437  */
1438 void
1439 Dir_Concat(path1, path2)
1440     Lst	    path1;  	/* Dest */
1441     Lst	    path2;  	/* Source */
1442 {
1443     LstNode ln;
1444     Path    *p;
1445 
1446     for (ln = Lst_First(path2); ln != NILLNODE; ln = Lst_Succ(ln)) {
1447 	p = (Path *)Lst_Datum(ln);
1448 	if (Lst_Member(path1, (ClientData)p) == NILLNODE) {
1449 	    p->refCount += 1;
1450 	    (void)Lst_AtEnd(path1, (ClientData)p);
1451 	}
1452     }
1453 }
1454 
1455 /********** DEBUG INFO **********/
1456 void
1457 Dir_PrintDirectories()
1458 {
1459     LstNode	ln;
1460     Path	*p;
1461 
1462     printf ("#*** Directory Cache:\n");
1463     printf ("# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
1464 	      hits, misses, nearmisses, bigmisses,
1465 	      (hits+bigmisses+nearmisses ?
1466 	       hits * 100 / (hits + bigmisses + nearmisses) : 0));
1467     printf ("# %-20s referenced\thits\n", "directory");
1468     if (Lst_Open (openDirectories) == SUCCESS) {
1469 	while ((ln = Lst_Next (openDirectories)) != NILLNODE) {
1470 	    p = (Path *) Lst_Datum (ln);
1471 	    printf ("# %-20s %10d\t%4d\n", p->name, p->refCount, p->hits);
1472 	}
1473 	Lst_Close (openDirectories);
1474     }
1475 }
1476 
1477 static int DirPrintDir (p, dummy)
1478     ClientData	p;
1479     ClientData	dummy;
1480 {
1481     printf ("%s ", ((Path *) p)->name);
1482     return (dummy ? 0 : 0);
1483 }
1484 
1485 void
1486 Dir_PrintPath (path)
1487     Lst	path;
1488 {
1489     Lst_ForEach (path, DirPrintDir, (ClientData)0);
1490 }
1491