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