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