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