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