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