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