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