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