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