]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - usr.bin/make/dir.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.git] / usr.bin / make / dir.c
1 /*-
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1988, 1989 by Adam de Boor
5  * Copyright (c) 1989 by Berkeley Softworks
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Adam de Boor.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by the University of
22  *      California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  * @(#)dir.c    8.2 (Berkeley) 1/2/94
40  */
41
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44
45 /*-
46  * dir.c --
47  *      Directory searching using wildcards and/or normal names...
48  *      Used both for source wildcarding in the Makefile and for finding
49  *      implicit sources.
50  *
51  * The interface for this module is:
52  *      Dir_Init        Initialize the module.
53  *
54  *      Dir_HasWildcards Returns TRUE if the name given it needs to
55  *                      be wildcard-expanded.
56  *
57  *      Path_Expand     Given a pattern and a path, return a Lst of names
58  *                      which match the pattern on the search path.
59  *
60  *      Path_FindFile   Searches for a file on a given search path.
61  *                      If it exists, the entire path is returned.
62  *                      Otherwise NULL is returned.
63  *
64  *      Dir_MTime       Return the modification time of a node. The file
65  *                      is searched for along the default search path.
66  *                      The path and mtime fields of the node are filled in.
67  *
68  *      Path_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  *
80  *      Dir_ClearPath   Resets a search path to the empty list.
81  *
82  * For debugging:
83  *      Dir_PrintDirectories    Print stats about the directory cache.
84  */
85
86 #include <sys/types.h>
87 #include <sys/stat.h>
88 #include <dirent.h>
89 #include <err.h>
90 #include <stdio.h>
91 #include <stdlib.h>
92 #include <string.h>
93 #include <unistd.h>
94
95 #include "arch.h"
96 #include "dir.h"
97 #include "globals.h"
98 #include "GNode.h"
99 #include "hash.h"
100 #include "lst.h"
101 #include "make.h"
102 #include "str.h"
103 #include "targ.h"
104 #include "util.h"
105
106 /*
107  *      A search path consists of a list of Dir structures. A Dir 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 list. 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 Dir 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, Path_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 typedef struct Dir {
177         char    *name;          /* Name of directory */
178         int     refCount;       /* No. of paths with this directory */
179         int     hits;           /* No. of times a file has been found here */
180         Hash_Table files;       /* Hash table of files in directory */
181         TAILQ_ENTRY(Dir) link;  /* allDirs link */
182 } Dir;
183
184 /*
185  * A path is a list of pointers to directories. These directories are
186  * reference counted so a directory can be on more than one path.
187  */
188 struct PathElement {
189         struct Dir      *dir;   /* pointer to the directory */
190         TAILQ_ENTRY(PathElement) link;  /* path link */
191 };
192
193 /* main search path */
194 struct Path dirSearchPath = TAILQ_HEAD_INITIALIZER(dirSearchPath);
195
196 /* the list of all open directories */
197 static TAILQ_HEAD(, Dir) openDirectories =
198     TAILQ_HEAD_INITIALIZER(openDirectories);
199
200 /*
201  * Variables for gathering statistics on the efficiency of the hashing
202  * mechanism.
203  */
204 static int hits;        /* Found in directory cache */
205 static int misses;      /* Sad, but not evil misses */
206 static int nearmisses;  /* Found under search path */
207 static int bigmisses;   /* Sought by itself */
208
209 static Dir *dot;            /* contents of current directory */
210
211 /* Results of doing a last-resort stat in Path_FindFile --
212  * if we have to go to the system to find the file, we might as well
213  * have its mtime on record.
214  * XXX: If this is done way early, there's a chance other rules will
215  * have already updated the file, in which case we'll update it again.
216  * Generally, there won't be two rules to update a single file, so this
217  * should be ok, but...
218  */
219 static Hash_Table mtimes;
220
221 /*-
222  *-----------------------------------------------------------------------
223  * Dir_Init --
224  *      initialize things for this module
225  *
226  * Results:
227  *      none
228  *
229  * Side Effects:
230  *      none
231  *-----------------------------------------------------------------------
232  */
233 void
234 Dir_Init(void)
235 {
236
237         Hash_InitTable(&mtimes, 0);
238 }
239
240 /*-
241  *-----------------------------------------------------------------------
242  * Dir_InitDot --
243  *      initialize the "." directory
244  *
245  * Results:
246  *      none
247  *
248  * Side Effects:
249  *      some directories may be opened.
250  *-----------------------------------------------------------------------
251  */
252 void
253 Dir_InitDot(void)
254 {
255
256         dot = Path_AddDir(NULL, ".");
257         if (dot == NULL)
258                 err(1, "cannot open current directory");
259
260         /*
261          * We always need to have dot around, so we increment its
262          * reference count to make sure it's not destroyed.
263          */
264         dot->refCount += 1;
265 }
266
267 /*-
268  *-----------------------------------------------------------------------
269  * Dir_HasWildcards  --
270  *      See if the given name has any wildcard characters in it.
271  *
272  * Results:
273  *      returns TRUE if the word should be expanded, FALSE otherwise
274  *
275  * Side Effects:
276  *      none
277  *-----------------------------------------------------------------------
278  */
279 Boolean
280 Dir_HasWildcards(const char *name)
281 {
282         const char *cp;
283         int wild = 0, brace = 0, bracket = 0;
284
285         for (cp = name; *cp; cp++) {
286                 switch (*cp) {
287                 case '{':
288                         brace++;
289                         wild = 1;
290                         break;
291                 case '}':
292                         brace--;
293                         break;
294                 case '[':
295                         bracket++;
296                         wild = 1;
297                         break;
298                 case ']':
299                         bracket--;
300                         break;
301                 case '?':
302                 case '*':
303                         wild = 1;
304                         break;
305                 default:
306                         break;
307                 }
308         }
309         return (wild && bracket == 0 && brace == 0);
310 }
311
312 /*-
313  *-----------------------------------------------------------------------
314  * DirMatchFiles --
315  *      Given a pattern and a Dir structure, see if any files
316  *      match the pattern and add their names to the 'expansions' list if
317  *      any do. This is incomplete -- it doesn't take care of patterns like
318  *      src / *src / *.c properly (just *.c on any of the directories), but it
319  *      will do for now.
320  *
321  * Results:
322  *      Always returns 0
323  *
324  * Side Effects:
325  *      File names are added to the expansions lst. The directory will be
326  *      fully hashed when this is done.
327  *-----------------------------------------------------------------------
328  */
329 static int
330 DirMatchFiles(const char *pattern, const Dir *p, Lst *expansions)
331 {
332         Hash_Search search;     /* Index into the directory's table */
333         Hash_Entry *entry;      /* Current entry in the table */
334         Boolean isDot;          /* TRUE if the directory being searched is . */
335
336         isDot = (*p->name == '.' && p->name[1] == '\0');
337
338         for (entry = Hash_EnumFirst(&p->files, &search);
339             entry != NULL;
340             entry = Hash_EnumNext(&search)) {
341                 /*
342                  * See if the file matches the given pattern. Note we follow
343                  * the UNIX convention that dot files will only be found if
344                  * the pattern begins with a dot (note also that as a side
345                  * effect of the hashing scheme, .* won't match . or ..
346                  * since they aren't hashed).
347                  */
348                 if (Str_Match(entry->name, pattern) &&
349                     ((entry->name[0] != '.') ||
350                     (pattern[0] == '.'))) {
351                         Lst_AtEnd(expansions, (isDot ? estrdup(entry->name) :
352                             str_concat(p->name, entry->name, STR_ADDSLASH)));
353                 }
354         }
355         return (0);
356 }
357
358 /*-
359  *-----------------------------------------------------------------------
360  * DirExpandCurly --
361  *      Expand curly braces like the C shell. Does this recursively.
362  *      Note the special case: if after the piece of the curly brace is
363  *      done there are no wildcard characters in the result, the result is
364  *      placed on the list WITHOUT CHECKING FOR ITS EXISTENCE.  The
365  *      given arguments are the entire word to expand, the first curly
366  *      brace in the word, the search path, and the list to store the
367  *      expansions in.
368  *
369  * Results:
370  *      None.
371  *
372  * Side Effects:
373  *      The given list is filled with the expansions...
374  *
375  *-----------------------------------------------------------------------
376  */
377 static void
378 DirExpandCurly(const char *word, const char *brace, struct Path *path,
379     Lst *expansions)
380 {
381         const char *end;        /* Character after the closing brace */
382         const char *cp;         /* Current position in brace clause */
383         const char *start;      /* Start of current piece of brace clause */
384         int bracelevel; /* Number of braces we've seen. If we see a right brace
385                          * when this is 0, we've hit the end of the clause. */
386         char *file;     /* Current expansion */
387         int otherLen;   /* The length of the other pieces of the expansion
388                          * (chars before and after the clause in 'word') */
389         char *cp2;      /* Pointer for checking for wildcards in
390                          * expansion before calling Dir_Expand */
391
392         start = brace + 1;
393
394         /*
395          * Find the end of the brace clause first, being wary of nested brace
396          * clauses.
397          */
398         for (end = start, bracelevel = 0; *end != '\0'; end++) {
399                 if (*end == '{')
400                         bracelevel++;
401                 else if ((*end == '}') && (bracelevel-- == 0))
402                         break;
403         }
404         if (*end == '\0') {
405                 Error("Unterminated {} clause \"%s\"", start);
406                 return;
407         } else
408                 end++;
409
410         otherLen = brace - word + strlen(end);
411
412         for (cp = start; cp < end; cp++) {
413                 /*
414                  * Find the end of this piece of the clause.
415                  */
416                 bracelevel = 0;
417                 while (*cp != ',') {
418                         if (*cp == '{')
419                                 bracelevel++;
420                         else if ((*cp == '}') && (bracelevel-- <= 0))
421                                 break;
422                         cp++;
423                 }
424                 /*
425                  * Allocate room for the combination and install the
426                  * three pieces.
427                  */
428                 file = emalloc(otherLen + cp - start + 1);
429                 if (brace != word)
430                         strncpy(file, word, brace - word);
431                 if (cp != start)
432                         strncpy(&file[brace - word], start, cp - start);
433                 strcpy(&file[(brace - word) + (cp - start)], end);
434
435                 /*
436                  * See if the result has any wildcards in it. If we find one,
437                  * call Dir_Expand right away, telling it to place the result
438                  * on our list of expansions.
439                  */
440                 for (cp2 = file; *cp2 != '\0'; cp2++) {
441                         switch (*cp2) {
442                         case '*':
443                         case '?':
444                         case '{':
445                         case '[':
446                                 Path_Expand(file, path, expansions);
447                                 goto next;
448                         default:
449                                 break;
450                         }
451                 }
452                 if (*cp2 == '\0') {
453                         /*
454                          * Hit the end w/o finding any wildcards, so stick
455                          * the expansion on the end of the list.
456                          */
457                         Lst_AtEnd(expansions, file);
458                 } else {
459                 next:
460                         free(file);
461                 }
462                 start = cp + 1;
463         }
464 }
465
466 /*-
467  *-----------------------------------------------------------------------
468  * DirExpandInt --
469  *      Internal expand routine. Passes through the directories in the
470  *      path one by one, calling DirMatchFiles for each. NOTE: This still
471  *      doesn't handle patterns in directories...  Works given a word to
472  *      expand, a path to look in, and a list to store expansions in.
473  *
474  * Results:
475  *      None.
476  *
477  * Side Effects:
478  *      Things are added to the expansions list.
479  *
480  *-----------------------------------------------------------------------
481  */
482 static void
483 DirExpandInt(const char *word, const struct Path *path, Lst *expansions)
484 {
485         struct PathElement *pe;
486
487         TAILQ_FOREACH(pe, path, link)
488                 DirMatchFiles(word, pe->dir, expansions);
489 }
490
491 /*-
492  *-----------------------------------------------------------------------
493  * Dir_Expand  --
494  *      Expand the given word into a list of words by globbing it looking
495  *      in the directories on the given search path.
496  *
497  * Results:
498  *      A list of words consisting of the files which exist along the search
499  *      path matching the given pattern is placed in expansions.
500  *
501  * Side Effects:
502  *      Directories may be opened. Who knows?
503  *-----------------------------------------------------------------------
504  */
505 void
506 Path_Expand(char *word, struct Path *path, Lst *expansions)
507 {
508         LstNode *ln;
509         char *cp;
510
511         DEBUGF(DIR, ("expanding \"%s\"...", word));
512
513         cp = strchr(word, '{');
514         if (cp != NULL)
515                 DirExpandCurly(word, cp, path, expansions);
516         else {
517                 cp = strchr(word, '/');
518                 if (cp != NULL) {
519                         /*
520                          * The thing has a directory component -- find the
521                          * first wildcard in the string.
522                          */
523                         for (cp = word; *cp != '\0'; cp++) {
524                                 if (*cp == '?' || *cp == '[' ||
525                                     *cp == '*' || *cp == '{') {
526                                         break;
527                                 }
528                         }
529                         if (*cp == '{') {
530                                 /*
531                                  * This one will be fun.
532                                  */
533                                 DirExpandCurly(word, cp, path, expansions);
534                                 return;
535                         } else if (*cp != '\0') {
536                                 /*
537                                  * Back up to the start of the component
538                                  */
539                                 char *dirpath;
540
541                                 while (cp > word && *cp != '/')
542                                         cp--;
543                                 if (cp != word) {
544                                         char sc;
545
546                                         /*
547                                          * If the glob isn't in the first
548                                          * component, try and find all the
549                                          * components up to the one with a
550                                          * wildcard.
551                                          */
552                                         sc = cp[1];
553                                         cp[1] = '\0';
554                                         dirpath = Path_FindFile(word, path);
555                                         cp[1] = sc;
556                                         /*
557                                          * dirpath is null if can't find the
558                                          * leading component
559                                          * XXX: Path_FindFile won't find internal
560                                          * components. i.e. if the path contains
561                                          * ../Etc/Object and we're looking for
562                                          * Etc, * it won't be found. Ah well.
563                                          * Probably not important.
564                                          */
565                                         if (dirpath != NULL) {
566                                                 char *dp =
567                                                     &dirpath[strlen(dirpath)
568                                                     - 1];
569                                                 struct Path tp =
570                                                     TAILQ_HEAD_INITIALIZER(tp);
571
572                                                 if (*dp == '/')
573                                                         *dp = '\0';
574                                                 Path_AddDir(&tp, dirpath);
575                                                 DirExpandInt(cp + 1, &tp,
576                                                     expansions);
577                                                 Path_Clear(&tp);
578                                         }
579                                 } else {
580                                         /*
581                                          * Start the search from the local
582                                          * directory
583                                          */
584                                         DirExpandInt(word, path, expansions);
585                                 }
586                         } else {
587                                 /*
588                                  * Return the file -- this should never happen.
589                                  */
590                                 DirExpandInt(word, path, expansions);
591                         }
592                 } else {
593                         /*
594                          * First the files in dot
595                          */
596                         DirMatchFiles(word, dot, expansions);
597
598                         /*
599                          * Then the files in every other directory on the path.
600                          */
601                         DirExpandInt(word, path, expansions);
602                 }
603         }
604         if (DEBUG(DIR)) {
605                 LST_FOREACH(ln, expansions)
606                         DEBUGF(DIR, ("%s ", (const char *)Lst_Datum(ln)));
607                 DEBUGF(DIR, ("\n"));
608         }
609 }
610
611 /**
612  * Path_FindFile
613  *      Find the file with the given name along the given search path.
614  *
615  * Results:
616  *      The path to the file or NULL. This path is guaranteed to be in a
617  *      different part of memory than name and so may be safely free'd.
618  *
619  * Side Effects:
620  *      If the file is found in a directory which is not on the path
621  *      already (either 'name' is absolute or it is a relative path
622  *      [ dir1/.../dirn/file ] which exists below one of the directories
623  *      already on the search path), its directory is added to the end
624  *      of the path on the assumption that there will be more files in
625  *      that directory later on. Sometimes this is true. Sometimes not.
626  */
627 char *
628 Path_FindFile(char *name, struct Path *path)
629 {
630         char *p1;               /* pointer into p->name */
631         char *p2;               /* pointer into name */
632         char *file;             /* the current filename to check */
633         const struct PathElement *pe;   /* current path member */
634         char *cp;               /* final component of the name */
635         Boolean hasSlash;       /* true if 'name' contains a / */
636         struct stat stb;        /* Buffer for stat, if necessary */
637         Hash_Entry *entry;      /* Entry for mtimes table */
638
639         /*
640          * Find the final component of the name and note whether it has a
641          * slash in it (the name, I mean)
642          */
643         cp = strrchr(name, '/');
644         if (cp != NULL) {
645                 hasSlash = TRUE;
646                 cp += 1;
647         } else {
648                 hasSlash = FALSE;
649                 cp = name;
650         }
651
652         DEBUGF(DIR, ("Searching for %s...", name));
653         /*
654          * No matter what, we always look for the file in the current directory
655          * before anywhere else and we *do not* add the ./ to it if it exists.
656          * This is so there are no conflicts between what the user specifies
657          * (fish.c) and what pmake finds (./fish.c).
658          */
659         if ((!hasSlash || (cp - name == 2 && *name == '.')) &&
660             (Hash_FindEntry(&dot->files, cp) != NULL)) {
661                 DEBUGF(DIR, ("in '.'\n"));
662                 hits += 1;
663                 dot->hits += 1;
664                 return (estrdup(name));
665         }
666
667         /*
668          * We look through all the directories on the path seeking one which
669          * contains the final component of the given name and whose final
670          * component(s) match the name's initial component(s). If such a beast
671          * is found, we concatenate the directory name and the final component
672          * and return the resulting string. If we don't find any such thing,
673          * we go on to phase two...
674          */
675         TAILQ_FOREACH(pe, path, link) {
676                 DEBUGF(DIR, ("%s...", pe->dir->name));
677                 if (Hash_FindEntry(&pe->dir->files, cp) != NULL) {
678                         DEBUGF(DIR, ("here..."));
679                         if (hasSlash) {
680                                 /*
681                                  * If the name had a slash, its initial
682                                  * components and p's final components must
683                                  * match. This is false if a mismatch is
684                                  * encountered before all of the initial
685                                  * components have been checked (p2 > name at
686                                  * the end of the loop), or we matched only
687                                  * part of one of the components of p
688                                  * along with all the rest of them (*p1 != '/').
689                                  */
690                                 p1 = pe->dir->name + strlen(pe->dir->name) - 1;
691                                 p2 = cp - 2;
692                                 while (p2 >= name && p1 >= pe->dir->name &&
693                                     *p1 == *p2) {
694                                         p1 -= 1; p2 -= 1;
695                                 }
696                                 if (p2 >= name || (p1 >= pe->dir->name &&
697                                     *p1 != '/')) {
698                                         DEBUGF(DIR, ("component mismatch -- "
699                                             "continuing..."));
700                                         continue;
701                                 }
702                         }
703                         file = str_concat(pe->dir->name, cp, STR_ADDSLASH);
704                         DEBUGF(DIR, ("returning %s\n", file));
705                         pe->dir->hits += 1;
706                         hits += 1;
707                         return (file);
708                 } else if (hasSlash) {
709                         /*
710                          * If the file has a leading path component and that
711                          * component exactly matches the entire name of the
712                          * current search directory, we assume the file
713                          * doesn't exist and return NULL.
714                          */
715                         for (p1 = pe->dir->name, p2 = name; *p1 && *p1 == *p2;
716                             p1++, p2++)
717                                 continue;
718                         if (*p1 == '\0' && p2 == cp - 1) {
719                                 if (*cp == '\0' || ISDOT(cp) || ISDOTDOT(cp)) {
720                                         DEBUGF(DIR, ("returning %s\n", name));
721                                         return (estrdup(name));
722                                 } else {
723                                         DEBUGF(DIR, ("must be here but isn't --"
724                                             " returning NULL\n"));
725                                         return (NULL);
726                                 }
727                         }
728                 }
729         }
730
731         /*
732          * We didn't find the file on any existing members of the directory.
733          * If the name doesn't contain a slash, that means it doesn't exist.
734          * If it *does* contain a slash, however, there is still hope: it
735          * could be in a subdirectory of one of the members of the search
736          * path. (eg. /usr/include and sys/types.h. The above search would
737          * fail to turn up types.h in /usr/include, but it *is* in
738          * /usr/include/sys/types.h) If we find such a beast, we assume there
739          * will be more (what else can we assume?) and add all but the last
740          * component of the resulting name onto the search path (at the
741          * end). This phase is only performed if the file is *not* absolute.
742          */
743         if (!hasSlash) {
744                 DEBUGF(DIR, ("failed.\n"));
745                 misses += 1;
746                 return (NULL);
747         }
748
749         if (*name != '/') {
750                 Boolean checkedDot = FALSE;
751
752                 DEBUGF(DIR, ("failed. Trying subdirectories..."));
753                 TAILQ_FOREACH(pe, path, link) {
754                         if (pe->dir != dot) {
755                                 file = str_concat(pe->dir->name,
756                                     name, STR_ADDSLASH);
757                         } else {
758                                 /*
759                                  * Checking in dot -- DON'T put a leading ./
760                                  * on the thing.
761                                  */
762                                 file = estrdup(name);
763                                 checkedDot = TRUE;
764                         }
765                         DEBUGF(DIR, ("checking %s...", file));
766
767                         if (stat(file, &stb) == 0) {
768                                 DEBUGF(DIR, ("got it.\n"));
769
770                                 /*
771                                  * We've found another directory to search. We
772                                  * know there's a slash in 'file' because we put
773                                  * one there. We nuke it after finding it and
774                                  * call Path_AddDir to add this new directory
775                                  * onto the existing search path. Once that's
776                                  * done, we restore the slash and triumphantly
777                                  * return the file name, knowing that should a
778                                  * file in this directory every be referenced
779                                  * again in such a manner, we will find it
780                                  * without having to do numerous numbers of
781                                  * access calls. Hurrah!
782                                  */
783                                 cp = strrchr(file, '/');
784                                 *cp = '\0';
785                                 Path_AddDir(path, file);
786                                 *cp = '/';
787
788                                 /*
789                                  * Save the modification time so if
790                                  * it's needed, we don't have to fetch it again.
791                                  */
792                                 DEBUGF(DIR, ("Caching %s for %s\n",
793                                     Targ_FmtTime(stb.st_mtime), file));
794                                 entry = Hash_CreateEntry(&mtimes, file,
795                                     (Boolean *)NULL);
796                                 Hash_SetValue(entry,
797                                     (void *)(long)stb.st_mtime);
798                                 nearmisses += 1;
799                                 return (file);
800                         } else {
801                                 free(file);
802                         }
803                 }
804
805                 DEBUGF(DIR, ("failed. "));
806
807                 if (checkedDot) {
808                         /*
809                          * Already checked by the given name, since . was in
810                          * the path, so no point in proceeding...
811                          */
812                         DEBUGF(DIR, ("Checked . already, returning NULL\n"));
813                         return (NULL);
814                 }
815         }
816
817         /*
818          * Didn't find it that way, either. Sigh. Phase 3. Add its directory
819          * onto the search path in any case, just in case, then look for the
820          * thing in the hash table. If we find it, grand. We return a new
821          * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
822          * Note that if the directory holding the file doesn't exist, this will
823          * do an extra search of the final directory on the path. Unless
824          * something weird happens, this search won't succeed and life will
825          * be groovy.
826          *
827          * Sigh. We cannot add the directory onto the search path because
828          * of this amusing case:
829          * $(INSTALLDIR)/$(FILE): $(FILE)
830          *
831          * $(FILE) exists in $(INSTALLDIR) but not in the current one.
832          * When searching for $(FILE), we will find it in $(INSTALLDIR)
833          * b/c we added it here. This is not good...
834          */
835 #ifdef notdef
836         cp[-1] = '\0';
837         Path_AddDir(path, name);
838         cp[-1] = '/';
839
840         bigmisses += 1;
841         pe = TAILQ_LAST(path, Path);
842         if (pe == NULL)
843                 return (NULL);
844
845         if (Hash_FindEntry(&pe->dir->files, cp) != NULL) {
846                 return (estrdup(name));
847
848         return (NULL);
849 #else /* !notdef */
850         DEBUGF(DIR, ("Looking for \"%s\"...", name));
851
852         bigmisses += 1;
853         entry = Hash_FindEntry(&mtimes, name);
854         if (entry != NULL) {
855                 DEBUGF(DIR, ("got it (in mtime cache)\n"));
856                 return (estrdup(name));
857         } else if (stat (name, &stb) == 0) {
858                 entry = Hash_CreateEntry(&mtimes, name, (Boolean *)NULL);
859                 DEBUGF(DIR, ("Caching %s for %s\n",
860                     Targ_FmtTime(stb.st_mtime), name));
861                 Hash_SetValue(entry, (void *)(long)stb.st_mtime);
862                 return (estrdup(name));
863         } else {
864                 DEBUGF(DIR, ("failed. Returning NULL\n"));
865                 return (NULL);
866         }
867 #endif /* notdef */
868 }
869
870 /*-
871  *-----------------------------------------------------------------------
872  * Dir_MTime  --
873  *      Find the modification time of the file described by gn along the
874  *      search path dirSearchPath.
875  *
876  * Results:
877  *      The modification time or 0 if it doesn't exist
878  *
879  * Side Effects:
880  *      The modification time is placed in the node's mtime slot.
881  *      If the node didn't have a path entry before, and Dir_FindFile
882  *      found one for it, the full name is placed in the path slot.
883  *-----------------------------------------------------------------------
884  */
885 int
886 Dir_MTime(GNode *gn)
887 {
888         char *fullName;         /* the full pathname of name */
889         struct stat stb;        /* buffer for finding the mod time */
890         Hash_Entry *entry;
891
892         if (gn->type & OP_ARCHV)
893                 return (Arch_MTime(gn));
894
895         else if (gn->path == NULL)
896                 fullName = Path_FindFile(gn->name, &dirSearchPath);
897         else
898                 fullName = gn->path;
899
900         if (fullName == NULL)
901                 fullName = estrdup(gn->name);
902
903         entry = Hash_FindEntry(&mtimes, fullName);
904         if (entry != NULL) {
905                 /*
906                  * Only do this once -- the second time folks are checking to
907                  * see if the file was actually updated, so we need to
908                  * actually go to the filesystem.
909                  */
910                 DEBUGF(DIR, ("Using cached time %s for %s\n",
911                     Targ_FmtTime((time_t)(long)Hash_GetValue(entry)),
912                     fullName));
913                 stb.st_mtime = (time_t)(long)Hash_GetValue(entry);
914                 Hash_DeleteEntry(&mtimes, entry);
915         } else if (stat(fullName, &stb) < 0) {
916                 if (gn->type & OP_MEMBER) {
917                         if (fullName != gn->path)
918                                 free(fullName);
919                         return (Arch_MemMTime(gn));
920                 } else {
921                         stb.st_mtime = 0;
922                 }
923         }
924         if (fullName && gn->path == (char *)NULL)
925                 gn->path = fullName;
926
927         gn->mtime = stb.st_mtime;
928         return (gn->mtime);
929 }
930
931 /*-
932  *-----------------------------------------------------------------------
933  * Path_AddDir --
934  *      Add the given name to the end of the given path.
935  *
936  * Results:
937  *      none
938  *
939  * Side Effects:
940  *      A structure is added to the list and the directory is
941  *      read and hashed.
942  *-----------------------------------------------------------------------
943  */
944 struct Dir *
945 Path_AddDir(struct Path *path, const char *name)
946 {
947         Dir *d;                 /* pointer to new Path structure */
948         DIR *dir;               /* for reading directory */
949         struct PathElement *pe;
950         struct dirent *dp;      /* entry in directory */
951
952         /* check whether we know this directory */
953         TAILQ_FOREACH(d, &openDirectories, link) {
954                 if (strcmp(d->name, name) == 0) {
955                         /* Found it. */
956                         if (path == NULL)
957                                 return (d);
958
959                         /* Check whether its already on the path. */
960                         TAILQ_FOREACH(pe, path, link) {
961                                 if (pe->dir == d)
962                                         return (d);
963                         }
964                         /* Add it to the path */
965                         d->refCount += 1;
966                         pe = emalloc(sizeof(*pe));
967                         pe->dir = d;
968                         TAILQ_INSERT_TAIL(path, pe, link);
969                         return (d);
970                 }
971         }
972
973         DEBUGF(DIR, ("Caching %s...", name));
974
975         if ((dir = opendir(name)) == NULL) {
976                 DEBUGF(DIR, (" cannot open\n"));
977                 return (NULL);
978         }
979
980         d = emalloc(sizeof(*d));
981         d->name = estrdup(name);
982         d->hits = 0;
983         d->refCount = 1;
984         Hash_InitTable(&d->files, -1);
985
986         while ((dp = readdir(dir)) != NULL) {
987 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
988                 /*
989                  * The sun directory library doesn't check for
990                  * a 0 inode (0-inode slots just take up space),
991                  * so we have to do it ourselves.
992                  */
993                 if (dp->d_fileno == 0)
994                         continue;
995 #endif /* sun && d_ino */
996
997                 /* Skip the '.' and '..' entries by checking
998                  * for them specifically instead of assuming
999                  * readdir() reuturns them in that order when
1000                  * first going through a directory.  This is
1001                  * needed for XFS over NFS filesystems since
1002                  * SGI does not guarantee that these are the
1003                  * first two entries returned from readdir().
1004                  */
1005                 if (ISDOT(dp->d_name) || ISDOTDOT(dp->d_name))
1006                         continue;
1007
1008                 Hash_CreateEntry(&d->files, dp->d_name, (Boolean *)NULL);
1009         }
1010         closedir(dir);
1011
1012         if (path != NULL) {
1013                 /* Add it to the path */
1014                 d->refCount += 1;
1015                 pe = emalloc(sizeof(*pe));
1016                 pe->dir = d;
1017                 TAILQ_INSERT_TAIL(path, pe, link);
1018         }
1019
1020         /* Add to list of all directories */
1021         TAILQ_INSERT_TAIL(&openDirectories, d, link);
1022
1023         DEBUGF(DIR, ("done\n"));
1024
1025         return (d);
1026 }
1027
1028 /**
1029  * Path_Duplicate
1030  *      Duplicate a path. Ups the reference count for the directories.
1031  */
1032 void
1033 Path_Duplicate(struct Path *dst, const struct Path *src)
1034 {
1035         struct PathElement *ped, *pes;
1036
1037         TAILQ_FOREACH(pes, src, link) {
1038                 ped = emalloc(sizeof(*ped));
1039                 ped->dir = pes->dir;
1040                 ped->dir->refCount++;
1041                 TAILQ_INSERT_TAIL(dst, ped, link);
1042         }
1043 }
1044
1045 /**
1046  * Path_MakeFlags
1047  *      Make a string by taking all the directories in the given search
1048  *      path and preceding them by the given flag. Used by the suffix
1049  *      module to create variables for compilers based on suffix search
1050  *      paths.
1051  *
1052  * Results:
1053  *      The string mentioned above. Note that there is no space between
1054  *      the given flag and each directory. The empty string is returned if
1055  *      Things don't go well.
1056  */
1057 char *
1058 Path_MakeFlags(const char *flag, const struct Path *path)
1059 {
1060         char *str;      /* the string which will be returned */
1061         char *tstr;     /* the current directory preceded by 'flag' */
1062         char *nstr;
1063         const struct PathElement *pe;
1064
1065         str = estrdup("");
1066
1067         TAILQ_FOREACH(pe, path, link) {
1068                 tstr = str_concat(flag, pe->dir->name, 0);
1069                 nstr = str_concat(str, tstr, STR_ADDSPACE);
1070                 free(str);
1071                 free(tstr);
1072                 str = nstr;
1073         }
1074
1075         return (str);
1076 }
1077
1078 /**
1079  * Path_Clear
1080  *
1081  *      Destroy a path. This decrements the reference counts of all
1082  *      directories of this path and, if a reference count goes 0,
1083  *      destroys the directory object.
1084  */
1085 void
1086 Path_Clear(struct Path *path)
1087 {
1088         struct PathElement *pe;
1089
1090         while ((pe = TAILQ_FIRST(path)) != NULL) {
1091                 pe->dir->refCount--;
1092                 TAILQ_REMOVE(path, pe, link);
1093                 if (pe->dir->refCount == 0) {
1094                         TAILQ_REMOVE(&openDirectories, pe->dir, link);
1095                         Hash_DeleteTable(&pe->dir->files);
1096                         free(pe->dir->name);
1097                         free(pe->dir);
1098                 }
1099                 free(pe);
1100         }
1101 }
1102
1103 /**
1104  * Path_Concat
1105  *
1106  *      Concatenate two paths, adding the second to the end of the first.
1107  *      Make sure to avoid duplicates.
1108  *
1109  * Side Effects:
1110  *      Reference counts for added dirs are upped.
1111  */
1112 void
1113 Path_Concat(struct Path *path1, const struct Path *path2)
1114 {
1115         struct PathElement *p1, *p2;
1116
1117         TAILQ_FOREACH(p2, path2, link) {
1118                 TAILQ_FOREACH(p1, path1, link) {
1119                         if (p1->dir == p2->dir)
1120                                 break;
1121                 }
1122                 if (p1 == NULL) {
1123                         p1 = emalloc(sizeof(*p1));
1124                         p1->dir = p2->dir;
1125                         p1->dir->refCount++;
1126                         TAILQ_INSERT_TAIL(path1, p1, link);
1127                 }
1128         }
1129 }
1130
1131 /********** DEBUG INFO **********/
1132 void
1133 Dir_PrintDirectories(void)
1134 {
1135         const Dir *d;
1136
1137         printf("#*** Directory Cache:\n");
1138         printf("# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
1139             hits, misses, nearmisses, bigmisses,
1140             (hits + bigmisses + nearmisses ?
1141             hits * 100 / (hits + bigmisses + nearmisses) : 0));
1142         printf("# %-20s referenced\thits\n", "directory");
1143         TAILQ_FOREACH(d, &openDirectories, link)
1144                 printf("# %-20s %10d\t%4d\n", d->name, d->refCount, d->hits);
1145 }
1146
1147 void
1148 Path_Print(const struct Path *path)
1149 {
1150         const struct PathElement *p;
1151
1152         TAILQ_FOREACH(p, path, link)
1153                 printf("%s ", p->dir->name);
1154 }