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