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