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