[BACK]Return to dir.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / make

Annotation of src/usr.bin/make/dir.c, Revision 1.44

1.31      espie       1: /*     $OpenPackages$ */
1.44    ! espie       2: /*     $OpenBSD: dir.c,v 1.43 2005/06/26 15:19:12 mickey Exp $ */
1.7       millert     3: /*     $NetBSD: dir.c,v 1.14 1997/03/29 16:51:26 christos Exp $        */
1.1       deraadt     4:
                      5: /*
1.31      espie       6:  * Copyright (c) 1999 Marc Espie.
                      7:  *
                      8:  * Extensive code changes for the OpenBSD project.
                      9:  *
                     10:  * Redistribution and use in source and binary forms, with or without
                     11:  * modification, are permitted provided that the following conditions
                     12:  * are met:
                     13:  * 1. Redistributions of source code must retain the above copyright
                     14:  *    notice, this list of conditions and the following disclaimer.
                     15:  * 2. Redistributions in binary form must reproduce the above copyright
                     16:  *    notice, this list of conditions and the following disclaimer in the
                     17:  *    documentation and/or other materials provided with the distribution.
                     18:  *
                     19:  * THIS SOFTWARE IS PROVIDED BY THE OPENBSD PROJECT AND CONTRIBUTORS
                     20:  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
                     21:  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
                     22:  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OPENBSD
                     23:  * PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
                     24:  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
                     25:  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     26:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     27:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     28:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
                     29:  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     30:  */
                     31: /*
1.1       deraadt    32:  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
                     33:  * Copyright (c) 1988, 1989 by Adam de Boor
                     34:  * Copyright (c) 1989 by Berkeley Softworks
                     35:  * All rights reserved.
                     36:  *
                     37:  * This code is derived from software contributed to Berkeley by
                     38:  * Adam de Boor.
                     39:  *
                     40:  * Redistribution and use in source and binary forms, with or without
                     41:  * modification, are permitted provided that the following conditions
                     42:  * are met:
                     43:  * 1. Redistributions of source code must retain the above copyright
                     44:  *    notice, this list of conditions and the following disclaimer.
                     45:  * 2. Redistributions in binary form must reproduce the above copyright
                     46:  *    notice, this list of conditions and the following disclaimer in the
                     47:  *    documentation and/or other materials provided with the distribution.
1.40      millert    48:  * 3. Neither the name of the University nor the names of its contributors
1.1       deraadt    49:  *    may be used to endorse or promote products derived from this software
                     50:  *    without specific prior written permission.
                     51:  *
                     52:  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
                     53:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     54:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     55:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
                     56:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     57:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     58:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     59:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     60:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     61:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     62:  * SUCH DAMAGE.
                     63:  */
                     64:
1.34      espie      65: #include <sys/param.h>
1.32      espie      66: #include <sys/stat.h>
                     67: #include <dirent.h>
1.34      espie      68: #include <limits.h>
1.25      espie      69: #include <stddef.h>
1.1       deraadt    70: #include <stdio.h>
1.44    ! espie      71: #include <stdint.h>
1.34      espie      72: #include <stdlib.h>
1.32      espie      73: #include <string.h>
                     74: #include "config.h"
                     75: #include "defines.h"
1.25      espie      76: #include "ohash.h"
1.1       deraadt    77: #include "dir.h"
1.32      espie      78: #include "lst.h"
                     79: #include "memory.h"
                     80: #include "buf.h"
                     81: #include "gnode.h"
                     82: #include "arch.h"
                     83: #include "targ.h"
                     84: #include "error.h"
                     85: #include "str.h"
                     86: #include "timestamp.h"
                     87:
                     88:
                     89: typedef struct Path_ {
                     90:     int          refCount;     /* Number of paths with this directory */
                     91: #ifdef DEBUG_DIRECTORY_CACHE
                     92:     int          hits;         /* the number of times a file in this
                     93:                                 * directory has been found */
1.24      espie      94: #endif
1.32      espie      95:     struct ohash   files;      /* Hash table of files in directory */
                     96:     char         name[1];      /* Name of directory */
                     97: } Path;
1.1       deraadt    98:
1.31      espie      99: /*     A search path consists of a Lst of Path structures. A Path structure
1.1       deraadt   100:  *     has in it the name of the directory and a hash table of all the files
                    101:  *     in the directory. This is used to cut down on the number of system
                    102:  *     calls necessary to find implicit dependents and their like. Since
                    103:  *     these searches are made before any actions are taken, we need not
                    104:  *     worry about the directory changing due to creation commands. If this
                    105:  *     hampers the style of some makefiles, they must be changed.
                    106:  *
                    107:  *     A list of all previously-read directories is kept in the
1.25      espie     108:  *     openDirectories cache.
1.1       deraadt   109:  *
                    110:  *     The need for the caching of whole directories is brought about by
                    111:  *     the multi-level transformation code in suff.c, which tends to search
                    112:  *     for far more files than regular make does. In the initial
                    113:  *     implementation, the amount of time spent performing "stat" calls was
                    114:  *     truly astronomical. The problem with hashing at the start is,
                    115:  *     of course, that pmake doesn't then detect changes to these directories
                    116:  *     during the course of the make. Three possibilities suggest themselves:
                    117:  *
                    118:  *         1) just use stat to test for a file's existence. As mentioned
                    119:  *            above, this is very inefficient due to the number of checks
                    120:  *            engendered by the multi-level transformation code.
                    121:  *         2) use readdir() and company to search the directories, keeping
                    122:  *            them open between checks. I have tried this and while it
                    123:  *            didn't slow down the process too much, it could severely
                    124:  *            affect the amount of parallelism available as each directory
                    125:  *            open would take another file descriptor out of play for
                    126:  *            handling I/O for another job. Given that it is only recently
                    127:  *            that UNIX OS's have taken to allowing more than 20 or 32
                    128:  *            file descriptors for a process, this doesn't seem acceptable
                    129:  *            to me.
                    130:  *         3) record the mtime of the directory in the Path structure and
                    131:  *            verify the directory hasn't changed since the contents were
                    132:  *            hashed. This will catch the creation or deletion of files,
                    133:  *            but not the updating of files. However, since it is the
                    134:  *            creation and deletion that is the problem, this could be
                    135:  *            a good thing to do. Unfortunately, if the directory (say ".")
                    136:  *            were fairly large and changed fairly frequently, the constant
                    137:  *            rehashing could seriously degrade performance. It might be
                    138:  *            good in such cases to keep track of the number of rehashes
                    139:  *            and if the number goes over a (small) limit, resort to using
                    140:  *            stat in its place.
                    141:  *
                    142:  *     An additional thing to consider is that pmake is used primarily
                    143:  *     to create C programs and until recently pcc-based compilers refused
                    144:  *     to allow you to specify where the resulting object file should be
                    145:  *     placed. This forced all objects to be created in the current
                    146:  *     directory. This isn't meant as a full excuse, just an explanation of
                    147:  *     some of the reasons for the caching used here.
                    148:  *
                    149:  *     One more note: the location of a target's file is only performed
                    150:  *     on the downward traversal of the graph and then only for terminal
                    151:  *     nodes in the graph. This could be construed as wrong in some cases,
                    152:  *     but prevents inadvertent modification of files when the "installed"
                    153:  *     directory for a file is provided in the search path.
                    154:  *
                    155:  *     Another data structure maintained by this module is an mtime
                    156:  *     cache used when the searching of cached directories fails to find
                    157:  *     a file. In the past, Dir_FindFile would simply perform an access()
                    158:  *     call in such a case to determine if the file could be found using
                    159:  *     just the name given. When this hit, however, all that was gained
                    160:  *     was the knowledge that the file existed. Given that an access() is
                    161:  *     essentially a stat() without the copyout() call, and that the same
                    162:  *     filesystem overhead would have to be incurred in Dir_MTime, it made
                    163:  *     sense to replace the access() with a stat() and record the mtime
1.31      espie     164:  *     in a cache for when Dir_MTime was actually called.  */
1.1       deraadt   165:
1.32      espie     166: static LIST   thedirSearchPath;                /* main search path */
                    167: Lst          dirSearchPath= &thedirSearchPath;
1.1       deraadt   168:
1.32      espie     169: #ifdef DEBUG_DIRECTORY_CACHE
1.31      espie     170: /* Variables for gathering statistics on the efficiency of the hashing
                    171:  * mechanism.  */
                    172: static int    hits,                    /* Found in directory cache */
                    173:              misses,                   /* Sad, but not evil misses */
                    174:              nearmisses,               /* Found under search path */
                    175:              bigmisses;                /* Sought by itself */
1.32      espie     176: #endif
1.1       deraadt   177:
1.31      espie     178: static Path      *dot;                 /* contents of current directory */
1.27      espie     179:
                    180: struct file_stamp {
                    181:        TIMESTAMP mtime;                /* time stamp... */
                    182:        char name[1];                   /* ...for that file.  */
                    183: };
                    184:
1.31      espie     185: static struct ohash   openDirectories; /* cache all open directories */
                    186:
1.32      espie     187: /* Global structure used to cache mtimes.  XXX We don't cache an mtime
                    188:  * before a caller actually looks up for the given time, because of the
                    189:  * possibility a caller might update the file and invalidate the cache
                    190:  * entry, and we don't look up in this cache except as a last resort.
                    191:  */
                    192: static struct ohash mtimes;
1.1       deraadt   193:
1.31      espie     194:
1.27      espie     195: /* There are three distinct hash structures:
                    196:  * - to collate files's last modification times (global mtimes)
                    197:  * - to collate file names (in each Path structure)
                    198:  * - to collate known directories (global openDirectories).  */
1.30      espie     199: static struct ohash_info stamp_info = { offsetof(struct file_stamp, name),
1.27      espie     200:     NULL, hash_alloc, hash_free, element_alloc };
                    201:
1.31      espie     202: static struct ohash_info file_info = { 0,
1.26      espie     203:     NULL, hash_alloc, hash_free, element_alloc };
                    204:
1.31      espie     205: static struct ohash_info dir_info = { offsetof(Path, name),
1.25      espie     206:     NULL, hash_alloc, hash_free, element_alloc };
1.1       deraadt   207:
1.32      espie     208: /* add_file(path, name): add a file name to a path hash structure. */
1.31      espie     209: static void add_file(Path *, const char *);
1.32      espie     210: /* n = find_file_hashi(p, name, end, hv): retrieve name in a path hash
                    211:  *     structure. */
1.44    ! espie     212: static char *find_file_hashi(Path *, const char *, const char *, uint32_t);
1.32      espie     213:
                    214: /* stamp = find_stampi(name, end): look for (name, end) in the global
                    215:  *     cache. */
1.31      espie     216: static struct file_stamp *find_stampi(const char *, const char *);
1.32      espie     217: /* record_stamp(name, timestamp): record timestamp for name in the global
                    218:  *     cache. */
                    219: static void record_stamp(const char *, TIMESTAMP);
                    220:
                    221: /* free_hash(o): free a ohash structure, where each element can be free'd. */
1.31      espie     222: static void free_hash(struct ohash *);
                    223:
1.32      espie     224: /* p = DirReaddiri(name, end): read an actual directory, caching results
                    225:  *     as we go.  */
                    226: static Path *DirReaddiri(const char *, const char *);
                    227: /* Handles wildcard expansion on a given directory. */
                    228: static void DirMatchFilesi(const char *, const char *, Path *, Lst);
                    229: /* Handles simple wildcard expansion on a path. */
                    230: static void PathMatchFilesi(const char *, const char *, Lst, Lst);
                    231: /* Handles wildcards expansion except for curly braces. */
                    232: static void DirExpandWildi(const char *, const char *, Lst, Lst);
                    233: #define DirExpandWild(s, l1, l2) DirExpandWildi(s, strchr(s, '\0'), l1, l2)
                    234: /* Handles wildcard expansion including curly braces. */
                    235: static void DirExpandCurlyi(const char *, const char *, Lst, Lst);
1.31      espie     236:
1.32      espie     237: /* Debugging: show each word in an expansion list. */
1.31      espie     238: static void DirPrintWord(void *);
1.32      espie     239: /* Debugging: show a dir name in a path. */
1.31      espie     240: static void DirPrintDir(void *);
1.1       deraadt   241:
1.26      espie     242: static void
1.41      espie     243: record_stamp(const char *file, TIMESTAMP t)
1.27      espie     244: {
1.38      deraadt   245:     unsigned int       slot;
1.31      espie     246:     const char         *end = NULL;
                    247:     struct file_stamp  *n;
1.27      espie     248:
1.30      espie     249:     slot = ohash_qlookupi(&mtimes, file, &end);
                    250:     n = ohash_find(&mtimes, slot);
1.27      espie     251:     if (n)
                    252:        n->mtime = t;
                    253:     else {
1.30      espie     254:        n = ohash_create_entry(&stamp_info, file, &end);
1.27      espie     255:        n->mtime = t;
1.30      espie     256:        ohash_insert(&mtimes, slot, n);
1.27      espie     257:     }
                    258: }
1.31      espie     259:
1.27      espie     260: static struct file_stamp *
1.41      espie     261: find_stampi(const char *file, const char *efile)
1.27      espie     262: {
1.41      espie     263:     return ohash_find(&mtimes, ohash_qlookupi(&mtimes, file, &efile));
1.27      espie     264: }
                    265:
                    266: static void
1.41      espie     267: add_file(Path *p, const char *file)
1.26      espie     268: {
1.38      deraadt   269:     unsigned int       slot;
1.31      espie     270:     const char         *end = NULL;
                    271:     char               *n;
                    272:     struct ohash       *h = &p->files;
1.26      espie     273:
1.30      espie     274:     slot = ohash_qlookupi(h, file, &end);
                    275:     n = ohash_find(h, slot);
1.26      espie     276:     if (n == NULL) {
1.30      espie     277:        n = ohash_create_entry(&file_info, file, &end);
                    278:        ohash_insert(h, slot, n);
1.26      espie     279:     }
                    280: }
1.31      espie     281:
1.26      espie     282: static char *
1.44    ! espie     283: find_file_hashi(Path *p, const char *file, const char *efile, uint32_t hv)
1.26      espie     284: {
1.30      espie     285:     struct ohash       *h = &p->files;
1.26      espie     286:
1.41      espie     287:     return ohash_find(h, ohash_lookup_interval(h, file, efile, hv));
1.26      espie     288: }
                    289:
                    290: static void
1.41      espie     291: free_hash(struct ohash *h)
1.26      espie     292: {
1.31      espie     293:     void               *e;
1.38      deraadt   294:     unsigned int       i;
1.26      espie     295:
1.30      espie     296:     for (e = ohash_first(h, &i); e != NULL; e = ohash_next(h, &i))
1.26      espie     297:        free(e);
1.30      espie     298:     ohash_delete(h);
1.26      espie     299: }
                    300:
1.32      espie     301:
                    302: /* Side Effects: cache the current directory */
1.1       deraadt   303: void
1.41      espie     304: Dir_Init(void)
1.1       deraadt   305: {
1.32      espie     306:     char *dotname = ".";
                    307:
1.37      espie     308:     Static_Lst_Init(dirSearchPath);
1.30      espie     309:     ohash_init(&openDirectories, 4, &dir_info);
                    310:     ohash_init(&mtimes, 4, &stamp_info);
1.6       millert   311:
1.32      espie     312:
                    313:     dot = DirReaddiri(dotname, dotname+1);
1.1       deraadt   314:
1.31      espie     315:     if (!dot)
1.43      mickey    316:        Fatal("Can't access current directory");
1.31      espie     317:
1.25      espie     318:     /* We always need to have dot around, so we increment its reference count
1.31      espie     319:      * to make sure it won't be destroyed.  */
1.25      espie     320:     dot->refCount++;
1.1       deraadt   321: }
                    322:
1.32      espie     323: #ifdef CLEANUP
1.1       deraadt   324: void
1.41      espie     325: Dir_End(void)
1.1       deraadt   326: {
1.25      espie     327:     struct Path *p;
                    328:     unsigned int i;
                    329:
                    330:     dot->refCount--;
1.17      espie     331:     Dir_Destroy(dot);
1.32      espie     332:     Lst_Destroy(dirSearchPath, Dir_Destroy);
1.30      espie     333:     for (p = ohash_first(&openDirectories, &i); p != NULL;
1.31      espie     334:        p = ohash_next(&openDirectories, &i))
1.25      espie     335:            Dir_Destroy(p);
1.30      espie     336:     ohash_delete(&openDirectories);
1.28      espie     337:     free_hash(&mtimes);
1.32      espie     338: }
1.9       espie     339: #endif
1.1       deraadt   340:
1.32      espie     341:
                    342: /* XXX: This code is not 100% correct ([^]] fails) */
                    343: bool
1.41      espie     344: Dir_HasWildcardsi(const char *name, const char *ename)
1.1       deraadt   345: {
1.31      espie     346:     const char         *cp;
1.32      espie     347:     bool               wild = false;
1.28      espie     348:     unsigned long      brace = 0, bracket = 0;
1.6       millert   349:
1.41      espie     350:     for (cp = name; cp != ename; cp++) {
1.28      espie     351:        switch (*cp) {
1.1       deraadt   352:        case '{':
1.7       millert   353:            brace++;
1.32      espie     354:            wild = true;
1.7       millert   355:            break;
                    356:        case '}':
1.28      espie     357:            if (brace == 0)
1.32      espie     358:                return false;
1.7       millert   359:            brace--;
                    360:            break;
1.1       deraadt   361:        case '[':
1.7       millert   362:            bracket++;
1.32      espie     363:            wild = true;
1.7       millert   364:            break;
                    365:        case ']':
1.28      espie     366:            if (bracket == 0)
1.32      espie     367:                return false;
1.7       millert   368:            bracket--;
                    369:            break;
1.1       deraadt   370:        case '?':
                    371:        case '*':
1.32      espie     372:            wild = true;
1.7       millert   373:            break;
                    374:        default:
                    375:            break;
1.1       deraadt   376:        }
                    377:     }
1.28      espie     378:     return wild && bracket == 0 && brace == 0;
1.1       deraadt   379: }
                    380:
                    381: /*-
                    382:  *-----------------------------------------------------------------------
1.32      espie     383:  * DirMatchFilesi --
1.31      espie     384:  *     Given a pattern and a Path structure, see if any files
1.1       deraadt   385:  *     match the pattern and add their names to the 'expansions' list if
                    386:  *     any do. This is incomplete -- it doesn't take care of patterns like
                    387:  *     src / *src / *.c properly (just *.c on any of the directories), but it
                    388:  *     will do for now.
                    389:  *-----------------------------------------------------------------------
                    390:  */
1.26      espie     391: static void
1.41      espie     392: DirMatchFilesi(const char *word, const char *eword, Path *p, Lst expansions)
1.31      espie     393: {
                    394:     unsigned int       search;         /* Index into the directory's table */
                    395:     const char         *entry;         /* Current entry in the table */
1.32      espie     396:     bool               isDot;          /* Is the directory "." ? */
1.6       millert   397:
1.31      espie     398:     isDot = p->name[0] == '.' && p->name[1] == '\0';
1.6       millert   399:
1.30      espie     400:     for (entry = ohash_first(&p->files, &search); entry != NULL;
                    401:         entry = ohash_next(&p->files, &search)) {
1.31      espie     402:        /* See if the file matches the given pattern. We follow the UNIX
1.1       deraadt   403:         * convention that dot files will only be found if the pattern
1.31      espie     404:         * begins with a dot (the hashing scheme doesn't hash . or ..,
                    405:         * so they won't match `.*'.  */
1.41      espie     406:        if (*word != '.' && *entry == '.')
1.31      espie     407:            continue;
1.41      espie     408:        if (Str_Matchi(entry, strchr(entry, '\0'), word, eword))
1.13      espie     409:            Lst_AtEnd(expansions,
1.32      espie     410:                isDot ? estrdup(entry) : Str_concat(p->name, entry, '/'));
1.1       deraadt   411:     }
                    412: }
                    413:
                    414: /*-
                    415:  *-----------------------------------------------------------------------
1.32      espie     416:  * PathMatchFilesi --
1.31      espie     417:  *     Traverse directories in the path, calling DirMatchFiles for each.
                    418:  *     NOTE: This doesn't handle patterns in directories.
1.1       deraadt   419:  *-----------------------------------------------------------------------
                    420:  */
                    421: static void
1.41      espie     422: PathMatchFilesi(const char *word, const char *eword, Lst path, Lst expansions)
1.31      espie     423: {
                    424:     LstNode    ln;             /* Current node */
1.1       deraadt   425:
1.31      espie     426:     for (ln = Lst_First(path); ln != NULL; ln = Lst_Adv(ln))
1.41      espie     427:        DirMatchFilesi(word, eword, (Path *)Lst_Datum(ln), expansions);
1.31      espie     428: }
1.1       deraadt   429:
1.31      espie     430: static void
1.41      espie     431: DirPrintWord(void *word)
1.31      espie     432: {
                    433:     printf("%s ", (char *)word);
1.1       deraadt   434: }
                    435:
                    436: /*-
                    437:  *-----------------------------------------------------------------------
1.32      espie     438:  * DirExpandWildi:
1.31      espie     439:  *     Expand all wild cards in a fully qualified name, except for
                    440:  *     curly braces.
1.32      espie     441:  * Side-effect:
                    442:  *     Will hash any directory in which a file is found, and add it to
                    443:  *     the path, on the assumption that future lookups will find files
                    444:  *     there as well.
1.1       deraadt   445:  *-----------------------------------------------------------------------
                    446:  */
                    447: static void
1.41      espie     448: DirExpandWildi(const char *word, const char *eword, Lst path, Lst expansions)
1.31      espie     449: {
                    450:     const char *cp;
                    451:     const char *slash;         /* keep track of first slash before wildcard */
                    452:
1.41      espie     453:     slash = memchr(word, '/', eword - word);
1.31      espie     454:     if (slash == NULL) {
                    455:        /* First the files in dot.  */
1.41      espie     456:        DirMatchFilesi(word, eword, dot, expansions);
1.1       deraadt   457:
1.31      espie     458:        /* Then the files in every other directory on the path.  */
1.41      espie     459:        PathMatchFilesi(word, eword, path, expansions);
1.31      espie     460:        return;
                    461:     }
                    462:     /* The thing has a directory component -- find the first wildcard
                    463:      * in the string.  */
                    464:     slash = word;
1.41      espie     465:     for (cp = word; cp != eword; cp++) {
1.31      espie     466:        if (*cp == '/')
                    467:            slash = cp;
                    468:        if (*cp == '?' || *cp == '[' || *cp == '*') {
                    469:
                    470:            if (slash != word) {
                    471:                char    *dirpath;
                    472:
                    473:                /* If the glob isn't in the first component, try and find
                    474:                 * all the components up to the one with a wildcard.  */
                    475:                dirpath = Dir_FindFilei(word, slash+1, path);
                    476:                /* dirpath is null if we can't find the leading component
                    477:                 * XXX: Dir_FindFile won't find internal components.
                    478:                 * i.e. if the path contains ../Etc/Object and we're
                    479:                 * looking for Etc, it won't be found. */
                    480:                if (dirpath != NULL) {
1.32      espie     481:                    char *dp;
1.31      espie     482:                    LIST temp;
                    483:
1.32      espie     484:                    dp = strchr(dirpath, '\0');
                    485:                    while (dp > dirpath && dp[-1] == '/')
                    486:                        dp--;
                    487:
1.31      espie     488:                    Lst_Init(&temp);
1.32      espie     489:                    Dir_AddDiri(&temp, dirpath, dp);
1.41      espie     490:                    PathMatchFilesi(slash+1, eword, &temp, expansions);
1.31      espie     491:                    Lst_Destroy(&temp, NOFREE);
                    492:                }
                    493:            } else
                    494:                /* Start the search from the local directory.  */
1.41      espie     495:                PathMatchFilesi(word, eword, path, expansions);
1.31      espie     496:            return;
                    497:        }
1.1       deraadt   498:     }
1.31      espie     499:     /* Return the file -- this should never happen.  */
1.41      espie     500:     PathMatchFilesi(word, eword, path, expansions);
1.1       deraadt   501: }
                    502:
                    503: /*-
                    504:  *-----------------------------------------------------------------------
1.31      espie     505:  * DirExpandCurly --
                    506:  *     Expand curly braces like the C shell, and other wildcards as per
                    507:  *     Str_Match.
1.32      espie     508:  *     XXX: if curly expansion yields a result with
1.31      espie     509:  *     no wildcards, the result is placed on the list WITHOUT CHECKING
                    510:  *     FOR ITS EXISTENCE.
1.1       deraadt   511:  *-----------------------------------------------------------------------
                    512:  */
1.18      espie     513: static void
1.41      espie     514: DirExpandCurlyi(const char *word, const char *eword, Lst path, Lst expansions)
1.1       deraadt   515: {
1.31      espie     516:     const char *cp2;           /* Pointer for checking for wildcards in
                    517:                                 * expansion before calling Dir_Expand */
                    518:     LIST       curled;         /* Queue of words to expand */
                    519:     char       *toexpand;      /* Current word to expand */
1.32      espie     520:     bool       dowild;         /* Wildcard left after curlies ? */
1.31      espie     521:
                    522:     /* Determine once and for all if there is something else going on */
1.32      espie     523:     dowild = false;
1.41      espie     524:     for (cp2 = word; cp2 != eword; cp2++)
1.31      espie     525:        if (*cp2 == '*' || *cp2 == '?' || *cp2 == '[') {
1.32      espie     526:                dowild = true;
1.31      espie     527:                break;
                    528:        }
                    529:
                    530:     /* Prime queue with copy of initial word */
                    531:     Lst_Init(&curled);
1.41      espie     532:     Lst_EnQueue(&curled, Str_dupi(word, eword));
1.31      espie     533:     while ((toexpand = (char *)Lst_DeQueue(&curled)) != NULL) {
                    534:        const char      *brace;
                    535:        const char      *start; /* Start of current chunk of brace clause */
                    536:        const char      *end;   /* Character after the closing brace */
                    537:        int             bracelevel;
                    538:                                /* Keep track of nested braces. If we hit
                    539:                                 * the right brace with bracelevel == 0,
                    540:                                 * this is the end of the clause. */
1.39      espie     541:        size_t          endLen;
                    542:                                /* The length of the ending non-curlied
                    543:                                 * part of the current expansion */
1.31      espie     544:
                    545:        /* End case: no curly left to expand */
                    546:        brace = strchr(toexpand, '{');
                    547:        if (brace == NULL) {
                    548:            if (dowild) {
                    549:                DirExpandWild(toexpand, path, expansions);
                    550:                free(toexpand);
                    551:            } else
                    552:                Lst_AtEnd(expansions, toexpand);
1.33      espie     553:            continue;
                    554:        }
1.31      espie     555:
                    556:        start = brace+1;
                    557:
                    558:        /* Find the end of the brace clause first, being wary of nested brace
                    559:         * clauses.  */
                    560:        for (end = start, bracelevel = 0;; end++) {
                    561:            if (*end == '{')
                    562:                bracelevel++;
                    563:            else if (*end == '\0') {
                    564:                Error("Unterminated {} clause \"%s\"", start);
                    565:                return;
                    566:            } else if (*end == '}' && bracelevel-- == 0)
                    567:                break;
                    568:        }
                    569:        end++;
1.39      espie     570:        endLen = strlen(end);
1.31      espie     571:
1.33      espie     572:        for (;;) {
1.31      espie     573:            char        *file;  /* To hold current expansion */
1.34      espie     574:            const char  *cp;    /* Current position in brace clause */
1.33      espie     575:
                    576:            /* Find the end of the current expansion */
                    577:            for (bracelevel = 0, cp = start;
                    578:                bracelevel != 0 || (*cp != '}' && *cp != ','); cp++) {
1.31      espie     579:                if (*cp == '{')
                    580:                    bracelevel++;
1.33      espie     581:                else if (*cp == '}')
                    582:                    bracelevel--;
1.31      espie     583:            }
1.33      espie     584:
1.31      espie     585:            /* Build the current combination and enqueue it.  */
1.39      espie     586:            file = emalloc((brace - toexpand) + (cp - start) + endLen + 1);
1.31      espie     587:            if (brace != toexpand)
1.33      espie     588:                memcpy(file, toexpand, brace-toexpand);
1.31      espie     589:            if (cp != start)
1.33      espie     590:                memcpy(file+(brace-toexpand), start, cp-start);
1.39      espie     591:            memcpy(file+(brace-toexpand)+(cp-start), end, endLen + 1);
1.31      espie     592:            Lst_EnQueue(&curled, file);
1.33      espie     593:            if (*cp == '}')
                    594:                break;
                    595:            start = cp+1;
1.31      espie     596:        }
1.33      espie     597:        free(toexpand);
1.31      espie     598:     }
1.1       deraadt   599: }
                    600:
1.32      espie     601: /* Side effects:
                    602:  *     Dir_Expandi will hash directories that were not yet visited */
1.1       deraadt   603: void
1.41      espie     604: Dir_Expandi(const char *word, const char *eword, Lst path, Lst expansions)
1.1       deraadt   605: {
1.31      espie     606:     const char *cp;
1.1       deraadt   607:
1.32      espie     608:     if (DEBUG(DIR)) {
1.41      espie     609:        char *s = Str_dupi(word, eword);
1.32      espie     610:        printf("expanding \"%s\"...", s);
                    611:        free(s);
                    612:     }
1.6       millert   613:
1.41      espie     614:     cp = memchr(word, '{', eword - word);
1.31      espie     615:     if (cp)
1.41      espie     616:        DirExpandCurlyi(word, eword, path, expansions);
1.31      espie     617:     else
1.41      espie     618:        DirExpandWildi(word, eword, path, expansions);
1.6       millert   619:
1.1       deraadt   620:     if (DEBUG(DIR)) {
1.18      espie     621:        Lst_Every(expansions, DirPrintWord);
1.1       deraadt   622:        fputc('\n', stdout);
                    623:     }
                    624: }
                    625:
1.32      espie     626:
1.1       deraadt   627: /*-
                    628:  * Side Effects:
                    629:  *     If the file is found in a directory which is not on the path
                    630:  *     already (either 'name' is absolute or it is a relative path
                    631:  *     [ dir1/.../dirn/file ] which exists below one of the directories
                    632:  *     already on the search path), its directory is added to the end
                    633:  *     of the path on the assumption that there will be more files in
1.32      espie     634:  *     that directory later on.
1.1       deraadt   635:  */
                    636: char *
1.41      espie     637: Dir_FindFilei(const char *name, const char *ename, Lst path)
1.31      espie     638: {
1.32      espie     639:     Path               *p;     /* current path member */
1.31      espie     640:     char               *p1;    /* pointer into p->name */
                    641:     const char         *p2;    /* pointer into name */
                    642:     LstNode            ln;     /* a list element */
                    643:     char               *file;  /* the current filename to check */
                    644:     char               *temp;  /* index into file */
                    645:     const char         *cp;    /* index of first slash, if any */
1.32      espie     646:     bool               hasSlash;
1.31      espie     647:     struct stat        stb;    /* Buffer for stat, if necessary */
                    648:     struct file_stamp  *entry; /* Entry for mtimes table */
1.44    ! espie     649:     uint32_t           hv;     /* hash value for last component in file name */
1.41      espie     650:     char               *q;     /* Str_dupi(name, ename) */
1.31      espie     651:
1.32      espie     652:     /* Find the final component of the name and note whether name has a
                    653:      * slash in it */
1.41      espie     654:     cp = Str_rchri(name, ename, '/');
1.1       deraadt   655:     if (cp) {
1.32      espie     656:        hasSlash = true;
1.31      espie     657:        cp++;
1.1       deraadt   658:     } else {
1.32      espie     659:        hasSlash = false;
1.1       deraadt   660:        cp = name;
                    661:     }
1.6       millert   662:
1.41      espie     663:     hv = ohash_interval(cp, &ename);
1.26      espie     664:
1.31      espie     665:     if (DEBUG(DIR))
1.1       deraadt   666:        printf("Searching for %s...", name);
1.31      espie     667:     /* No matter what, we always look for the file in the current directory
1.32      espie     668:      * before anywhere else and we always return exactly what the caller
                    669:      * specified. */
1.1       deraadt   670:     if ((!hasSlash || (cp - name == 2 && *name == '.')) &&
1.41      espie     671:        find_file_hashi(dot, cp, ename, hv) != NULL) {
1.26      espie     672:            if (DEBUG(DIR))
1.1       deraadt   673:                printf("in '.'\n");
1.32      espie     674: #ifdef DEBUG_DIRECTORY_CACHE
1.31      espie     675:            hits++;
                    676:            dot->hits++;
1.32      espie     677: #endif
1.41      espie     678:            return Str_dupi(name, ename);
1.1       deraadt   679:     }
1.6       millert   680:
1.32      espie     681:     /* Then, we look through all the directories on path, seeking one
                    682:      * containing the final component of name and whose final
                    683:      * component(s) match name's initial component(s).
                    684:      * If found, we concatenate the directory name and the
                    685:      * final component and return the resulting string.  */
1.26      espie     686:     for (ln = Lst_First(path); ln != NULL; ln = Lst_Adv(ln)) {
1.22      espie     687:        p = (Path *)Lst_Datum(ln);
1.26      espie     688:        if (DEBUG(DIR))
1.1       deraadt   689:            printf("%s...", p->name);
1.41      espie     690:        if (find_file_hashi(p, cp, ename, hv) != NULL) {
1.26      espie     691:            if (DEBUG(DIR))
1.1       deraadt   692:                printf("here...");
                    693:            if (hasSlash) {
1.31      espie     694:                /* If the name had a slash, its initial components and p's
1.1       deraadt   695:                 * final components must match. This is false if a mismatch
                    696:                 * is encountered before all of the initial components
                    697:                 * have been checked (p2 > name at the end of the loop), or
                    698:                 * we matched only part of one of the components of p
1.31      espie     699:                 * along with all the rest of them (*p1 != '/').  */
                    700:                p1 = p->name + strlen(p->name) - 1;
1.1       deraadt   701:                p2 = cp - 2;
                    702:                while (p2 >= name && p1 >= p->name && *p1 == *p2) {
1.31      espie     703:                    p1--;
                    704:                    p2--;
1.1       deraadt   705:                }
                    706:                if (p2 >= name || (p1 >= p->name && *p1 != '/')) {
1.26      espie     707:                    if (DEBUG(DIR))
1.1       deraadt   708:                        printf("component mismatch -- continuing...");
                    709:                    continue;
                    710:                }
                    711:            }
1.41      espie     712:            file = Str_concati(p->name, strchr(p->name, '\0'), cp, ename, '/');
1.26      espie     713:            if (DEBUG(DIR))
1.1       deraadt   714:                printf("returning %s\n", file);
1.32      espie     715: #ifdef DEBUG_DIRECTORY_CACHE
1.31      espie     716:            p->hits++;
                    717:            hits++;
1.32      espie     718: #endif
1.26      espie     719:            return file;
1.1       deraadt   720:        } else if (hasSlash) {
1.26      espie     721:            /* If the file has a leading path component and that component
1.1       deraadt   722:             * exactly matches the entire name of the current search
1.26      espie     723:             * directory, we assume the file doesn't exist and return NULL.  */
1.31      espie     724:            for (p1 = p->name, p2 = name; *p1 && *p1 == *p2; p1++, p2++)
1.1       deraadt   725:                continue;
                    726:            if (*p1 == '\0' && p2 == cp - 1) {
1.26      espie     727:                if (DEBUG(DIR))
1.31      espie     728:                    printf("has to be here but isn't -- returning NULL\n");
1.26      espie     729:                return NULL;
1.1       deraadt   730:            }
                    731:        }
                    732:     }
1.6       millert   733:
1.32      espie     734:     /* We didn't find the file on any existing member of the path.
                    735:      * If the name doesn't contain a slash, end of story.
                    736:      * If it does contain a slash, however, it could be in a subdirectory
                    737:      * of one of the members of the search path. (eg., for path=/usr/include
                    738:      * and name=sys/types.h, the above search fails to turn up types.h
                    739:      * in /usr/include, even though /usr/include/sys/types.h exists).
                    740:      *
                    741:      * We only perform this look-up for non-absolute file names.
                    742:      *
                    743:      * Whenever we score a hit, we assume there will be more matches from
                    744:      * that directory, and append all but the last component of the
                    745:      * resulting name onto the search path. */
1.1       deraadt   746:     if (!hasSlash) {
1.26      espie     747:        if (DEBUG(DIR))
1.1       deraadt   748:            printf("failed.\n");
1.32      espie     749: #ifdef DEBUG_DIRECTORY_CACHE
1.31      espie     750:        misses++;
1.32      espie     751: #endif
1.26      espie     752:        return NULL;
1.1       deraadt   753:     }
1.6       millert   754:
1.1       deraadt   755:     if (*name != '/') {
1.32      espie     756:        bool checkedDot = false;
1.6       millert   757:
1.26      espie     758:        if (DEBUG(DIR))
1.1       deraadt   759:            printf("failed. Trying subdirectories...");
1.26      espie     760:        for (ln = Lst_First(path); ln != NULL; ln = Lst_Adv(ln)) {
1.22      espie     761:            p = (Path *)Lst_Datum(ln);
1.26      espie     762:            if (p != dot)
1.41      espie     763:                file = Str_concati(p->name, strchr(p->name, '\0'), name, ename, '/');
1.26      espie     764:            else {
                    765:                /* Checking in dot -- DON'T put a leading ./ on the thing.  */
1.41      espie     766:                file = Str_dupi(name, ename);
1.32      espie     767:                checkedDot = true;
1.1       deraadt   768:            }
1.26      espie     769:            if (DEBUG(DIR))
1.1       deraadt   770:                printf("checking %s...", file);
1.6       millert   771:
1.26      espie     772:            if (stat(file, &stb) == 0) {
1.31      espie     773:                TIMESTAMP mtime;
1.27      espie     774:
1.32      espie     775:                ts_set_from_stat(stb, mtime);
1.26      espie     776:                if (DEBUG(DIR))
1.1       deraadt   777:                    printf("got it.\n");
1.6       millert   778:
1.32      espie     779:                /* We've found another directory to search. We know there
                    780:                 * is a slash in 'file'. We call Dir_AddDiri to add the
                    781:                 * new directory onto the existing search path. Once
                    782:                 * that's done, we return the file name, knowing that
                    783:                 * should a file in this directory ever be referenced again
                    784:                 * in such a manner, we will find it without having to do
                    785:                 * numerous access calls.  */
1.31      espie     786:                temp = strrchr(file, '/');
1.32      espie     787:                Dir_AddDiri(path, file, temp);
1.6       millert   788:
1.26      espie     789:                /* Save the modification time so if it's needed, we don't have
                    790:                 * to fetch it again.  */
                    791:                if (DEBUG(DIR))
1.29      espie     792:                    printf("Caching %s for %s\n", Targ_FmtTime(mtime),
1.1       deraadt   793:                            file);
1.27      espie     794:                record_stamp(file, mtime);
1.32      espie     795: #ifdef DEBUG_DIRECTORY_CACHE
1.31      espie     796:                nearmisses++;
1.32      espie     797: #endif
1.26      espie     798:                return file;
                    799:            } else
                    800:                free(file);
1.1       deraadt   801:        }
1.6       millert   802:
1.26      espie     803:        if (DEBUG(DIR))
1.1       deraadt   804:            printf("failed. ");
1.31      espie     805:
1.1       deraadt   806:        if (checkedDot) {
1.26      espie     807:            /* Already checked by the given name, since . was in the path,
                    808:             * so no point in proceeding...  */
                    809:            if (DEBUG(DIR))
1.1       deraadt   810:                printf("Checked . already, returning NULL\n");
1.26      espie     811:            return NULL;
1.1       deraadt   812:        }
                    813:     }
1.6       millert   814:
1.32      espie     815:     /* Didn't find it that way, either. Last resort: look for the file
                    816:      * in the global mtime cache, then on the disk.
                    817:      * If this doesn't succeed, we finally return a NULL pointer.
1.1       deraadt   818:      *
1.32      espie     819:      * We cannot add this directory onto the search path because
1.1       deraadt   820:      * of this amusing case:
                    821:      * $(INSTALLDIR)/$(FILE): $(FILE)
                    822:      *
                    823:      * $(FILE) exists in $(INSTALLDIR) but not in the current one.
                    824:      * When searching for $(FILE), we will find it in $(INSTALLDIR)
1.26      espie     825:      * b/c we added it here. This is not good...  */
1.41      espie     826:     q = Str_dupi(name, ename);
1.26      espie     827:     if (DEBUG(DIR))
1.31      espie     828:        printf("Looking for \"%s\"...", q);
1.6       millert   829:
1.32      espie     830: #ifdef DEBUG_DIRECTORY_CACHE
1.31      espie     831:     bigmisses++;
1.32      espie     832: #endif
1.41      espie     833:     entry = find_stampi(name, ename);
1.27      espie     834:     if (entry != NULL) {
1.26      espie     835:        if (DEBUG(DIR))
1.1       deraadt   836:            printf("got it (in mtime cache)\n");
1.31      espie     837:        return q;
                    838:     } else if (stat(q, &stb) == 0) {
                    839:        TIMESTAMP mtime;
1.27      espie     840:
1.32      espie     841:        ts_set_from_stat(stb, mtime);
1.26      espie     842:        if (DEBUG(DIR))
1.29      espie     843:            printf("Caching %s for %s\n", Targ_FmtTime(mtime),
1.31      espie     844:                    q);
                    845:        record_stamp(q, mtime);
                    846:        return q;
1.1       deraadt   847:     } else {
1.26      espie     848:        if (DEBUG(DIR))
1.1       deraadt   849:            printf("failed. Returning NULL\n");
1.31      espie     850:        free(q);
1.26      espie     851:        return NULL;
1.1       deraadt   852:     }
                    853: }
                    854:
1.25      espie     855: /* Read a directory, either from the disk, or from the cache.  */
                    856: static Path *
1.41      espie     857: DirReaddiri(const char *name, const char *ename)
1.25      espie     858: {
1.31      espie     859:     Path               *p;     /* pointer to new Path structure */
                    860:     DIR                *d;     /* for reading directory */
                    861:     struct dirent      *dp;    /* entry in directory */
                    862:     unsigned int       slot;
1.25      espie     863:
1.41      espie     864:     slot = ohash_qlookupi(&openDirectories, name, &ename);
1.30      espie     865:     p = ohash_find(&openDirectories, slot);
1.25      espie     866:
                    867:     if (p != NULL)
                    868:        return p;
                    869:
1.41      espie     870:     p = ohash_create_entry(&dir_info, name, &ename);
1.32      espie     871: #ifdef DEBUG_DIRECTORY_CACHE
1.25      espie     872:     p->hits = 0;
1.32      espie     873: #endif
1.25      espie     874:     p->refCount = 0;
1.30      espie     875:     ohash_init(&p->files, 4, &file_info);
1.25      espie     876:
                    877:     if (DEBUG(DIR)) {
                    878:        printf("Caching %s...", p->name);
                    879:        fflush(stdout);
                    880:     }
                    881:
1.31      espie     882:     if ((d = opendir(p->name)) == NULL)
                    883:        return NULL;
1.25      espie     884:
                    885:     while ((dp = readdir(d)) != NULL) {
1.42      espie     886:        if (dp->d_name[0] == '.' &&
                    887:            (dp->d_name[1] == '\0' ||
                    888:                (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
                    889:                continue;
1.26      espie     890:        add_file(p, dp->d_name);
1.25      espie     891:     }
                    892:     (void)closedir(d);
                    893:     if (DEBUG(DIR))
                    894:        printf("done\n");
                    895:
1.30      espie     896:     ohash_insert(&openDirectories, slot, p);
1.25      espie     897:     return p;
                    898: }
                    899:
1.1       deraadt   900: /*-
                    901:  *-----------------------------------------------------------------------
1.32      espie     902:  * Dir_AddDiri --
1.1       deraadt   903:  *     Add the given name to the end of the given path. The order of
                    904:  *     the arguments is backwards so ParseDoDependency can do a
                    905:  *     Lst_ForEach of its list of paths...
                    906:  *
                    907:  * Side Effects:
1.6       millert   908:  *     A structure is added to the list and the directory is
1.1       deraadt   909:  *     read and hashed.
                    910:  *-----------------------------------------------------------------------
                    911:  */
1.31      espie     912:
1.1       deraadt   913: void
1.41      espie     914: Dir_AddDiri(Lst path, const char *name, const char *ename)
1.1       deraadt   915: {
1.25      espie     916:     Path       *p;     /* pointer to new Path structure */
1.6       millert   917:
1.41      espie     918:     p = DirReaddiri(name, ename);
1.25      espie     919:     if (p == NULL)
1.31      espie     920:        return;
1.25      espie     921:     if (p->refCount == 0)
1.31      espie     922:        Lst_AtEnd(path, p);
1.32      espie     923:     else if (!Lst_AddNew(path, p))
1.31      espie     924:        return;
1.25      espie     925:     p->refCount++;
1.1       deraadt   926: }
                    927:
                    928: /*-
                    929:  *-----------------------------------------------------------------------
                    930:  * Dir_CopyDir --
                    931:  *     Callback function for duplicating a search path via Lst_Duplicate.
                    932:  *     Ups the reference count for the directory.
                    933:  *
                    934:  * Results:
                    935:  *     Returns the Path it was given.
                    936:  *
                    937:  * Side Effects:
                    938:  *     The refCount of the path is incremented.
                    939:  *-----------------------------------------------------------------------
                    940:  */
1.19      espie     941: void *
1.41      espie     942: Dir_CopyDir(void *p)
1.1       deraadt   943: {
1.31      espie     944:     ((Path *)p)->refCount++;
1.17      espie     945:     return p;
1.1       deraadt   946: }
                    947:
                    948: /*-
                    949:  *-----------------------------------------------------------------------
                    950:  * Dir_MakeFlags --
                    951:  *     Make a string by taking all the directories in the given search
                    952:  *     path and preceding them by the given flag. Used by the suffix
                    953:  *     module to create variables for compilers based on suffix search
                    954:  *     paths.
                    955:  *
                    956:  * Results:
                    957:  *     The string mentioned above. Note that there is no space between
                    958:  *     the given flag and each directory. The empty string is returned if
                    959:  *     Things don't go well.
                    960:  *-----------------------------------------------------------------------
                    961:  */
                    962: char *
1.41      espie     963: Dir_MakeFlags(const char *flag, Lst path)
1.1       deraadt   964: {
                    965:     LstNode      ln;     /* the node of the current directory */
1.23      espie     966:     BUFFER       buf;
1.6       millert   967:
1.23      espie     968:     Buf_Init(&buf, 0);
1.6       millert   969:
1.23      espie     970:     for (ln = Lst_First(path); ln != NULL; ln = Lst_Adv(ln)) {
                    971:            Buf_AddString(&buf, flag);
                    972:            Buf_AddString(&buf, ((Path *)Lst_Datum(ln))->name);
                    973:            Buf_AddSpace(&buf);
1.1       deraadt   974:     }
1.6       millert   975:
1.23      espie     976:     return Buf_Retrieve(&buf);
1.1       deraadt   977: }
                    978:
                    979: /*-
                    980:  *-----------------------------------------------------------------------
                    981:  * Dir_Destroy --
                    982:  *     Nuke a directory descriptor, if possible. Callback procedure
                    983:  *     for the suffixes module when destroying a search path.
                    984:  *
                    985:  * Side Effects:
                    986:  *     If no other path references this directory (refCount == 0),
                    987:  *     the Path and all its data are freed.
                    988:  *-----------------------------------------------------------------------
                    989:  */
                    990: void
1.41      espie     991: Dir_Destroy(void *pp)
1.1       deraadt   992: {
1.31      espie     993:     Path       *p = (Path *)pp;
1.1       deraadt   994:
1.25      espie     995:     if (--p->refCount == 0) {
1.31      espie     996:        ohash_remove(&openDirectories, ohash_qlookup(&openDirectories, p->name));
1.26      espie     997:        free_hash(&p->files);
1.19      espie     998:        free(p);
1.1       deraadt   999:     }
                   1000: }
                   1001:
                   1002: /*-
                   1003:  *-----------------------------------------------------------------------
                   1004:  * Dir_Concat --
                   1005:  *     Concatenate two paths, adding the second to the end of the first.
                   1006:  *     Makes sure to avoid duplicates.
                   1007:  *
                   1008:  * Side Effects:
                   1009:  *     Reference counts for added dirs are upped.
                   1010:  *-----------------------------------------------------------------------
                   1011:  */
                   1012: void
1.41      espie    1013: Dir_Concat(Lst path1, Lst path2)
1.1       deraadt  1014: {
1.31      espie    1015:     LstNode    ln;
                   1016:     Path       *p;
1.1       deraadt  1017:
1.22      espie    1018:     for (ln = Lst_First(path2); ln != NULL; ln = Lst_Adv(ln)) {
1.1       deraadt  1019:        p = (Path *)Lst_Datum(ln);
1.32      espie    1020:        if (Lst_AddNew(path1, p))
1.31      espie    1021:            p->refCount++;
1.1       deraadt  1022:     }
                   1023: }
                   1024:
1.32      espie    1025: #ifdef DEBUG_DIRECTORY_CACHE
1.1       deraadt  1026: void
1.41      espie    1027: Dir_PrintDirectories(void)
1.1       deraadt  1028: {
1.31      espie    1029:     Path               *p;
                   1030:     unsigned int       i;
1.6       millert  1031:
1.31      espie    1032:     printf("#*** Directory Cache:\n");
                   1033:     printf("# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
1.1       deraadt  1034:              hits, misses, nearmisses, bigmisses,
                   1035:              (hits+bigmisses+nearmisses ?
                   1036:               hits * 100 / (hits + bigmisses + nearmisses) : 0));
1.31      espie    1037:     printf("# %-20s referenced\thits\n", "directory");
1.30      espie    1038:     for (p = ohash_first(&openDirectories, &i); p != NULL;
1.31      espie    1039:        p = ohash_next(&openDirectories, &i))
1.25      espie    1040:            printf("# %-20s %10d\t%4d\n", p->name, p->refCount, p->hits);
1.1       deraadt  1041: }
1.32      espie    1042: #endif
1.1       deraadt  1043:
1.31      espie    1044: static void
1.41      espie    1045: DirPrintDir(void *p)
1.6       millert  1046: {
1.18      espie    1047:     printf("%s ", ((Path *)p)->name);
1.1       deraadt  1048: }
                   1049:
                   1050: void
1.41      espie    1051: Dir_PrintPath(Lst path)
1.1       deraadt  1052: {
1.18      espie    1053:     Lst_Every(path, DirPrintDir);
1.29      espie    1054: }
                   1055:
1.32      espie    1056: TIMESTAMP
1.41      espie    1057: Dir_MTime(GNode *gn)
1.32      espie    1058: {
                   1059:     char         *fullName;  /* the full pathname of name */
                   1060:     struct stat   stb;       /* buffer for finding the mod time */
                   1061:     struct file_stamp
                   1062:                  *entry;
                   1063:     unsigned int  slot;
                   1064:     TIMESTAMP    mtime;
                   1065:
                   1066:     if (gn->type & OP_ARCHV)
                   1067:        return Arch_MTime(gn);
                   1068:
                   1069:     if (gn->path == NULL) {
                   1070:        fullName = Dir_FindFile(gn->name, dirSearchPath);
                   1071:        if (fullName == NULL)
                   1072:            fullName = estrdup(gn->name);
                   1073:     } else
                   1074:        fullName = gn->path;
                   1075:
                   1076:     slot = ohash_qlookup(&mtimes, fullName);
                   1077:     entry = ohash_find(&mtimes, slot);
                   1078:     if (entry != NULL) {
                   1079:        /* Only do this once -- the second time folks are checking to
                   1080:         * see if the file was actually updated, so we need to actually go
                   1081:         * to the file system.  */
                   1082:        if (DEBUG(DIR))
                   1083:            printf("Using cached time %s for %s\n",
                   1084:                    Targ_FmtTime(entry->mtime), fullName);
                   1085:        mtime = entry->mtime;
                   1086:        free(entry);
                   1087:        ohash_remove(&mtimes, slot);
                   1088:     } else if (stat(fullName, &stb) == 0)
                   1089:        ts_set_from_stat(stb, mtime);
                   1090:     else {
                   1091:        if (gn->type & OP_MEMBER) {
                   1092:            if (fullName != gn->path)
                   1093:                free(fullName);
                   1094:            return Arch_MemMTime(gn);
                   1095:        } else
                   1096:            ts_set_out_of_date(mtime);
                   1097:     }
                   1098:     if (fullName && gn->path == NULL)
                   1099:        gn->path = fullName;
1.29      espie    1100:
1.32      espie    1101:     gn->mtime = mtime;
                   1102:     return gn->mtime;
1.1       deraadt  1103: }
1.32      espie    1104: