dir.c revision 1.150 1 /* $NetBSD: dir.c,v 1.150 2020/09/27 22:17:07 rillig Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
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 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 /*
36 * Copyright (c) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
39 *
40 * This code is derived from software contributed to Berkeley by
41 * Adam de Boor.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
58 *
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
70 */
71
72 /*-
73 * dir.c --
74 * Directory searching using wildcards and/or normal names...
75 * Used both for source wildcarding in the Makefile and for finding
76 * implicit sources.
77 *
78 * The interface for this module is:
79 * Dir_Init Initialize the module.
80 *
81 * Dir_InitCur Set the cur CachedDir.
82 *
83 * Dir_InitDot Set the dot CachedDir.
84 *
85 * Dir_End Cleanup the module.
86 *
87 * Dir_SetPATH Set ${.PATH} to reflect state of dirSearchPath.
88 *
89 * Dir_HasWildcards
90 * Returns TRUE if the name given it needs to
91 * be wildcard-expanded.
92 *
93 * Dir_Expand Given a pattern and a path, return a Lst of names
94 * which match the pattern on the search path.
95 *
96 * Dir_FindFile Searches for a file on a given search path.
97 * If it exists, the entire path is returned.
98 * Otherwise NULL is returned.
99 *
100 * Dir_FindHereOrAbove
101 * Search for a path in the current directory and
102 * then all the directories above it in turn until
103 * the path is found or we reach the root ("/").
104 *
105 * Dir_MTime Return the modification time of a node. The file
106 * is searched for along the default search path.
107 * The path and mtime fields of the node are filled in.
108 *
109 * Dir_AddDir Add a directory to a search path.
110 *
111 * Dir_MakeFlags Given a search path and a command flag, create
112 * a string with each of the directories in the path
113 * preceded by the command flag and all of them
114 * separated by a space.
115 *
116 * Dir_Destroy Destroy an element of a search path. Frees up all
117 * things that can be freed for the element as long
118 * as the element is no longer referenced by any other
119 * search path.
120 *
121 * Dir_ClearPath Resets a search path to the empty list.
122 *
123 * For debugging:
124 * Dir_PrintDirectories Print stats about the directory cache.
125 */
126
127 #include <sys/types.h>
128 #include <sys/stat.h>
129
130 #include <dirent.h>
131 #include <errno.h>
132 #include <stdio.h>
133
134 #include "make.h"
135 #include "dir.h"
136 #include "job.h"
137
138 /* "@(#)dir.c 8.2 (Berkeley) 1/2/94" */
139 MAKE_RCSID("$NetBSD: dir.c,v 1.150 2020/09/27 22:17:07 rillig Exp $");
140
141 #define DIR_DEBUG0(fmt) \
142 if (!DEBUG(DIR)) (void) 0; else fprintf(debug_file, fmt)
143
144 #define DIR_DEBUG1(fmt, arg1) \
145 if (!DEBUG(DIR)) (void) 0; else fprintf(debug_file, fmt, arg1)
146
147 #define DIR_DEBUG2(fmt, arg1, arg2) \
148 if (!DEBUG(DIR)) (void) 0; else fprintf(debug_file, fmt, arg1, arg2)
149
150
151 /*
152 * A search path consists of a list of CachedDir structures. A CachedDir
153 * has in it the name of the directory and a hash table of all the files
154 * in the directory. This is used to cut down on the number of system
155 * calls necessary to find implicit dependents and their like. Since
156 * these searches are made before any actions are taken, we need not
157 * worry about the directory changing due to creation commands. If this
158 * hampers the style of some makefiles, they must be changed.
159 *
160 * A list of all previously-read directories is kept in the
161 * openDirectories Lst. This list is checked first before a directory
162 * is opened.
163 *
164 * The need for the caching of whole directories is brought about by
165 * the multi-level transformation code in suff.c, which tends to search
166 * for far more files than regular make does. In the initial
167 * implementation, the amount of time spent performing "stat" calls was
168 * truly astronomical. The problem with hashing at the start is,
169 * of course, that pmake doesn't then detect changes to these directories
170 * during the course of the make. Three possibilities suggest themselves:
171 *
172 * 1) just use stat to test for a file's existence. As mentioned
173 * above, this is very inefficient due to the number of checks
174 * engendered by the multi-level transformation code.
175 * 2) use readdir() and company to search the directories, keeping
176 * them open between checks. I have tried this and while it
177 * didn't slow down the process too much, it could severely
178 * affect the amount of parallelism available as each directory
179 * open would take another file descriptor out of play for
180 * handling I/O for another job. Given that it is only recently
181 * that UNIX OS's have taken to allowing more than 20 or 32
182 * file descriptors for a process, this doesn't seem acceptable
183 * to me.
184 * 3) record the mtime of the directory in the CachedDir structure and
185 * verify the directory hasn't changed since the contents were
186 * hashed. This will catch the creation or deletion of files,
187 * but not the updating of files. However, since it is the
188 * creation and deletion that is the problem, this could be
189 * a good thing to do. Unfortunately, if the directory (say ".")
190 * were fairly large and changed fairly frequently, the constant
191 * rehashing could seriously degrade performance. It might be
192 * good in such cases to keep track of the number of rehashes
193 * and if the number goes over a (small) limit, resort to using
194 * stat in its place.
195 *
196 * An additional thing to consider is that pmake is used primarily
197 * to create C programs and until recently pcc-based compilers refused
198 * to allow you to specify where the resulting object file should be
199 * placed. This forced all objects to be created in the current
200 * directory. This isn't meant as a full excuse, just an explanation of
201 * some of the reasons for the caching used here.
202 *
203 * One more note: the location of a target's file is only performed
204 * on the downward traversal of the graph and then only for terminal
205 * nodes in the graph. This could be construed as wrong in some cases,
206 * but prevents inadvertent modification of files when the "installed"
207 * directory for a file is provided in the search path.
208 *
209 * Another data structure maintained by this module is an mtime
210 * cache used when the searching of cached directories fails to find
211 * a file. In the past, Dir_FindFile would simply perform an access()
212 * call in such a case to determine if the file could be found using
213 * just the name given. When this hit, however, all that was gained
214 * was the knowledge that the file existed. Given that an access() is
215 * essentially a stat() without the copyout() call, and that the same
216 * filesystem overhead would have to be incurred in Dir_MTime, it made
217 * sense to replace the access() with a stat() and record the mtime
218 * in a cache for when Dir_MTime was actually called.
219 */
220
221 typedef List CachedDirList;
222 typedef ListNode CachedDirListNode;
223
224 typedef ListNode SearchPathNode;
225
226 SearchPath *dirSearchPath; /* main search path */
227
228 static CachedDirList *openDirectories; /* the list of all open directories */
229
230 /*
231 * Variables for gathering statistics on the efficiency of the hashing
232 * mechanism.
233 */
234 static int hits; /* Found in directory cache */
235 static int misses; /* Sad, but not evil misses */
236 static int nearmisses; /* Found under search path */
237 static int bigmisses; /* Sought by itself */
238
239 static CachedDir *dot; /* contents of current directory */
240 static CachedDir *cur; /* contents of current directory, if not dot */
241 static CachedDir *dotLast; /* a fake path entry indicating we need to
242 * look for . last */
243
244 /* Results of doing a last-resort stat in Dir_FindFile -- if we have to go to
245 * the system to find the file, we might as well have its mtime on record.
246 *
247 * XXX: If this is done way early, there's a chance other rules will have
248 * already updated the file, in which case we'll update it again. Generally,
249 * there won't be two rules to update a single file, so this should be ok,
250 * but... */
251 static Hash_Table mtimes;
252
253 static Hash_Table lmtimes; /* same as mtimes but for lstat */
254
255 static void DirExpandInt(const char *, SearchPath *, StringList *);
256 static char *DirLookup(CachedDir *, const char *, const char *, Boolean);
257 static char *DirLookupSubdir(CachedDir *, const char *);
258 static char *DirFindDot(Boolean, const char *, const char *);
259 static char *DirLookupAbs(CachedDir *, const char *, const char *);
260
261
262 /*
263 * We use stat(2) a lot, cache the results.
264 * mtime and mode are all we care about.
265 */
266 struct cache_st {
267 time_t lmtime; /* lstat */
268 time_t mtime; /* stat */
269 mode_t mode;
270 };
271
272 /* minimize changes below */
273 typedef enum {
274 CST_LSTAT = 0x01, /* call lstat(2) instead of stat(2) */
275 CST_UPDATE = 0x02 /* ignore existing cached entry */
276 } CachedStatsFlags;
277
278 /* Returns 0 and the result of stat(2) or lstat(2) in *mst, or -1 on error. */
279 static int
280 cached_stats(Hash_Table *htp, const char *pathname, struct make_stat *mst,
281 CachedStatsFlags flags)
282 {
283 Hash_Entry *entry;
284 struct stat sys_st;
285 struct cache_st *cst;
286 int rc;
287
288 if (!pathname || !pathname[0])
289 return -1;
290
291 entry = Hash_FindEntry(htp, pathname);
292
293 if (entry && !(flags & CST_UPDATE)) {
294 cst = Hash_GetValue(entry);
295
296 mst->mst_mode = cst->mode;
297 mst->mst_mtime = (flags & CST_LSTAT) ? cst->lmtime : cst->mtime;
298 if (mst->mst_mtime) {
299 DIR_DEBUG2("Using cached time %s for %s\n",
300 Targ_FmtTime(mst->mst_mtime), pathname);
301 return 0;
302 }
303 }
304
305 rc = (flags & CST_LSTAT)
306 ? lstat(pathname, &sys_st)
307 : stat(pathname, &sys_st);
308 if (rc == -1)
309 return -1;
310
311 if (sys_st.st_mtime == 0)
312 sys_st.st_mtime = 1; /* avoid confusion with missing file */
313
314 mst->mst_mode = sys_st.st_mode;
315 mst->mst_mtime = sys_st.st_mtime;
316
317 if (entry == NULL)
318 entry = Hash_CreateEntry(htp, pathname, NULL);
319 if (Hash_GetValue(entry) == NULL) {
320 Hash_SetValue(entry, bmake_malloc(sizeof(*cst)));
321 memset(Hash_GetValue(entry), 0, sizeof(*cst));
322 }
323 cst = Hash_GetValue(entry);
324 if (flags & CST_LSTAT) {
325 cst->lmtime = sys_st.st_mtime;
326 } else {
327 cst->mtime = sys_st.st_mtime;
328 }
329 cst->mode = sys_st.st_mode;
330 DIR_DEBUG2(" Caching %s for %s\n",
331 Targ_FmtTime(sys_st.st_mtime), pathname);
332
333 return 0;
334 }
335
336 int
337 cached_stat(const char *pathname, struct make_stat *st)
338 {
339 return cached_stats(&mtimes, pathname, st, 0);
340 }
341
342 int
343 cached_lstat(const char *pathname, struct make_stat *st)
344 {
345 return cached_stats(&lmtimes, pathname, st, CST_LSTAT);
346 }
347
348 /* Initialize things for this module. */
349 void
350 Dir_Init(void)
351 {
352 dirSearchPath = Lst_Init();
353 openDirectories = Lst_Init();
354 Hash_InitTable(&mtimes);
355 Hash_InitTable(&lmtimes);
356 }
357
358 void
359 Dir_InitDir(const char *cdname)
360 {
361 Dir_InitCur(cdname);
362
363 dotLast = bmake_malloc(sizeof(CachedDir));
364 dotLast->refCount = 1;
365 dotLast->hits = 0;
366 dotLast->name = bmake_strdup(".DOTLAST");
367 Hash_InitTable(&dotLast->files);
368 }
369
370 /*
371 * Called by Dir_InitDir and whenever .CURDIR is assigned to.
372 */
373 void
374 Dir_InitCur(const char *cdname)
375 {
376 CachedDir *dir;
377
378 if (cdname != NULL) {
379 /*
380 * Our build directory is not the same as our source directory.
381 * Keep this one around too.
382 */
383 if ((dir = Dir_AddDir(NULL, cdname))) {
384 dir->refCount += 1;
385 if (cur && cur != dir) {
386 /*
387 * We've been here before, cleanup.
388 */
389 cur->refCount -= 1;
390 Dir_Destroy(cur);
391 }
392 cur = dir;
393 }
394 }
395 }
396
397 /* (Re)initialize "dot" (current/object directory) path hash.
398 * Some directories may be opened. */
399 void
400 Dir_InitDot(void)
401 {
402 if (dot != NULL) {
403 CachedDirListNode *ln;
404
405 /* Remove old entry from openDirectories, but do not destroy. */
406 ln = Lst_FindDatum(openDirectories, dot);
407 Lst_Remove(openDirectories, ln);
408 }
409
410 dot = Dir_AddDir(NULL, ".");
411
412 if (dot == NULL) {
413 Error("Cannot open `.' (%s)", strerror(errno));
414 exit(1);
415 }
416
417 /*
418 * We always need to have dot around, so we increment its reference count
419 * to make sure it's not destroyed.
420 */
421 dot->refCount += 1;
422 Dir_SetPATH(); /* initialize */
423 }
424
425 /* Clean up things for this module. */
426 void
427 Dir_End(void)
428 {
429 #ifdef CLEANUP
430 if (cur) {
431 cur->refCount -= 1;
432 Dir_Destroy(cur);
433 }
434 dot->refCount -= 1;
435 dotLast->refCount -= 1;
436 Dir_Destroy(dotLast);
437 Dir_Destroy(dot);
438 Dir_ClearPath(dirSearchPath);
439 Lst_Free(dirSearchPath);
440 Dir_ClearPath(openDirectories);
441 Lst_Free(openDirectories);
442 Hash_DeleteTable(&mtimes);
443 #endif
444 }
445
446 /*
447 * We want ${.PATH} to indicate the order in which we will actually
448 * search, so we rebuild it after any .PATH: target.
449 * This is the simplest way to deal with the effect of .DOTLAST.
450 */
451 void
452 Dir_SetPATH(void)
453 {
454 CachedDirListNode *ln;
455 Boolean hasLastDot = FALSE; /* true if we should search dot last */
456
457 Var_Delete(".PATH", VAR_GLOBAL);
458
459 Lst_Open(dirSearchPath);
460 if ((ln = Lst_First(dirSearchPath)) != NULL) {
461 CachedDir *dir = LstNode_Datum(ln);
462 if (dir == dotLast) {
463 hasLastDot = TRUE;
464 Var_Append(".PATH", dotLast->name, VAR_GLOBAL);
465 }
466 }
467
468 if (!hasLastDot) {
469 if (dot)
470 Var_Append(".PATH", dot->name, VAR_GLOBAL);
471 if (cur)
472 Var_Append(".PATH", cur->name, VAR_GLOBAL);
473 }
474
475 while ((ln = Lst_Next(dirSearchPath)) != NULL) {
476 CachedDir *dir = LstNode_Datum(ln);
477 if (dir == dotLast)
478 continue;
479 if (dir == dot && hasLastDot)
480 continue;
481 Var_Append(".PATH", dir->name, VAR_GLOBAL);
482 }
483
484 if (hasLastDot) {
485 if (dot)
486 Var_Append(".PATH", dot->name, VAR_GLOBAL);
487 if (cur)
488 Var_Append(".PATH", cur->name, VAR_GLOBAL);
489 }
490 Lst_Close(dirSearchPath);
491 }
492
493 /* See if the CachedDir structure describes the same directory as the
494 * given one by comparing their names. Called from Dir_AddDir via
495 * Lst_Find when searching the list of open directories. */
496 static Boolean
497 DirFindName(const void *p, const void *desiredName)
498 {
499 const CachedDir *dir = p;
500 return strcmp(dir->name, desiredName) == 0;
501 }
502
503 /* See if the given name has any wildcard characters in it. Be careful not to
504 * expand unmatching brackets or braces.
505 *
506 * XXX: This code is not 100% correct ([^]] fails etc.). I really don't think
507 * that make(1) should be expanding patterns, because then you have to set a
508 * mechanism for escaping the expansion!
509 *
510 * Input:
511 * name name to check
512 *
513 * Results:
514 * returns TRUE if the word should be expanded, FALSE otherwise
515 */
516 Boolean
517 Dir_HasWildcards(const char *name)
518 {
519 const char *cp;
520 Boolean wild = FALSE;
521 int braces = 0, brackets = 0;
522
523 for (cp = name; *cp; cp++) {
524 switch (*cp) {
525 case '{':
526 braces++;
527 wild = TRUE;
528 break;
529 case '}':
530 braces--;
531 break;
532 case '[':
533 brackets++;
534 wild = TRUE;
535 break;
536 case ']':
537 brackets--;
538 break;
539 case '?':
540 case '*':
541 wild = TRUE;
542 break;
543 default:
544 break;
545 }
546 }
547 return wild && brackets == 0 && braces == 0;
548 }
549
550 /*-
551 *-----------------------------------------------------------------------
552 * DirMatchFiles --
553 * Given a pattern and a CachedDir structure, see if any files
554 * match the pattern and add their names to the 'expansions' list if
555 * any do. This is incomplete -- it doesn't take care of patterns like
556 * src / *src / *.c properly (just *.c on any of the directories), but it
557 * will do for now.
558 *
559 * Input:
560 * pattern Pattern to look for
561 * dir Directory to search
562 * expansion Place to store the results
563 *
564 * Side Effects:
565 * File names are added to the expansions lst. The directory will be
566 * fully hashed when this is done.
567 *-----------------------------------------------------------------------
568 */
569 static void
570 DirMatchFiles(const char *pattern, CachedDir *dir, StringList *expansions)
571 {
572 Hash_Search search; /* Index into the directory's table */
573 Hash_Entry *entry; /* Current entry in the table */
574 Boolean isDot; /* TRUE if the directory being searched is . */
575
576 isDot = (dir->name[0] == '.' && dir->name[1] == '\0');
577
578 for (entry = Hash_EnumFirst(&dir->files, &search);
579 entry != NULL;
580 entry = Hash_EnumNext(&search))
581 {
582 /*
583 * See if the file matches the given pattern. Note we follow the UNIX
584 * convention that dot files will only be found if the pattern
585 * begins with a dot (note also that as a side effect of the hashing
586 * scheme, .* won't match . or .. since they aren't hashed).
587 */
588 if (Str_Match(entry->name, pattern) &&
589 ((entry->name[0] != '.') ||
590 (pattern[0] == '.')))
591 {
592 Lst_Append(expansions,
593 (isDot ? bmake_strdup(entry->name) :
594 str_concat3(dir->name, "/", entry->name)));
595 }
596 }
597 }
598
599 /* Find the next closing brace in the string, taking nested braces into
600 * account. */
601 static const char *
602 closing_brace(const char *p)
603 {
604 int nest = 0;
605 while (*p != '\0') {
606 if (*p == '}' && nest == 0)
607 break;
608 if (*p == '{')
609 nest++;
610 if (*p == '}')
611 nest--;
612 p++;
613 }
614 return p;
615 }
616
617 /* Find the next closing brace or comma in the string, taking nested braces
618 * into account. */
619 static const char *
620 separator_comma(const char *p)
621 {
622 int nest = 0;
623 while (*p != '\0') {
624 if ((*p == '}' || *p == ',') && nest == 0)
625 break;
626 if (*p == '{')
627 nest++;
628 if (*p == '}')
629 nest--;
630 p++;
631 }
632 return p;
633 }
634
635 static Boolean
636 contains_wildcard(const char *p)
637 {
638 for (; *p != '\0'; p++) {
639 switch (*p) {
640 case '*':
641 case '?':
642 case '{':
643 case '[':
644 return TRUE;
645 }
646 }
647 return FALSE;
648 }
649
650 static char *
651 concat3(const char *a, size_t a_len, const char *b, size_t b_len,
652 const char *c, size_t c_len)
653 {
654 size_t s_len = a_len + b_len + c_len;
655 char *s = bmake_malloc(s_len + 1);
656 memcpy(s, a, a_len);
657 memcpy(s + a_len, b, b_len);
658 memcpy(s + a_len + b_len, c, c_len);
659 s[s_len] = '\0';
660 return s;
661 }
662
663 /*-
664 *-----------------------------------------------------------------------
665 * DirExpandCurly --
666 * Expand curly braces like the C shell. Does this recursively.
667 * Note the special case: if after the piece of the curly brace is
668 * done there are no wildcard characters in the result, the result is
669 * placed on the list WITHOUT CHECKING FOR ITS EXISTENCE.
670 *
671 * Input:
672 * word Entire word to expand
673 * brace First curly brace in it
674 * path Search path to use
675 * expansions Place to store the expansions
676 *
677 * Results:
678 * None.
679 *
680 * Side Effects:
681 * The given list is filled with the expansions...
682 *
683 *-----------------------------------------------------------------------
684 */
685 static void
686 DirExpandCurly(const char *word, const char *brace, SearchPath *path,
687 StringList *expansions)
688 {
689 const char *prefix, *middle, *piece, *middle_end, *suffix;
690 size_t prefix_len, suffix_len;
691
692 /* Split the word into prefix '{' middle '}' suffix. */
693
694 middle = brace + 1;
695 middle_end = closing_brace(middle);
696 if (*middle_end == '\0') {
697 Error("Unterminated {} clause \"%s\"", middle);
698 return;
699 }
700
701 prefix = word;
702 prefix_len = (size_t)(brace - prefix);
703 suffix = middle_end + 1;
704 suffix_len = strlen(suffix);
705
706 /* Split the middle into pieces, separated by commas. */
707
708 piece = middle;
709 while (piece < middle_end + 1) {
710 const char *piece_end = separator_comma(piece);
711 size_t piece_len = (size_t)(piece_end - piece);
712
713 char *file = concat3(prefix, prefix_len, piece, piece_len,
714 suffix, suffix_len);
715
716 if (contains_wildcard(file)) {
717 Dir_Expand(file, path, expansions);
718 free(file);
719 } else {
720 Lst_Append(expansions, file);
721 }
722
723 piece = piece_end + 1; /* skip over the comma or closing brace */
724 }
725 }
726
727
728 /*-
729 *-----------------------------------------------------------------------
730 * DirExpandInt --
731 * Internal expand routine. Passes through the directories in the
732 * path one by one, calling DirMatchFiles for each. NOTE: This still
733 * doesn't handle patterns in directories...
734 *
735 * Input:
736 * word Word to expand
737 * path Directory in which to look
738 * expansions Place to store the result
739 *
740 * Results:
741 * None.
742 *
743 * Side Effects:
744 * Things are added to the expansions list.
745 *
746 *-----------------------------------------------------------------------
747 */
748 static void
749 DirExpandInt(const char *word, SearchPath *path, StringList *expansions)
750 {
751 SearchPathNode *ln;
752 for (ln = path->first; ln != NULL; ln = ln->next) {
753 CachedDir *dir = ln->datum;
754 DirMatchFiles(word, dir, expansions);
755 }
756 }
757
758 static void
759 DirPrintExpansions(StringList *words)
760 {
761 StringListNode *ln;
762 for (ln = words->first; ln != NULL; ln = ln->next) {
763 const char *word = ln->datum;
764 fprintf(debug_file, "%s ", word);
765 }
766 fprintf(debug_file, "\n");
767 }
768
769 /*-
770 *-----------------------------------------------------------------------
771 * Dir_Expand --
772 * Expand the given word into a list of words by globbing it looking
773 * in the directories on the given search path.
774 *
775 * Input:
776 * word the word to expand
777 * path the list of directories in which to find the
778 * resulting files
779 * expansions the list on which to place the results
780 *
781 * Results:
782 * A list of words consisting of the files which exist along the search
783 * path matching the given pattern.
784 *
785 * Side Effects:
786 * Directories may be opened. Who knows?
787 * Undefined behavior if the word is really in read-only memory.
788 *-----------------------------------------------------------------------
789 */
790 void
791 Dir_Expand(const char *word, SearchPath *path, StringList *expansions)
792 {
793 const char *cp;
794
795 assert(path != NULL);
796 assert(expansions != NULL);
797
798 DIR_DEBUG1("Expanding \"%s\"... ", word);
799
800 cp = strchr(word, '{');
801 if (cp) {
802 DirExpandCurly(word, cp, path, expansions);
803 } else {
804 cp = strchr(word, '/');
805 if (cp) {
806 /*
807 * The thing has a directory component -- find the first wildcard
808 * in the string.
809 */
810 for (cp = word; *cp; cp++) {
811 if (*cp == '?' || *cp == '[' || *cp == '*' || *cp == '{') {
812 break;
813 }
814 }
815 if (*cp == '{') {
816 /*
817 * This one will be fun.
818 */
819 DirExpandCurly(word, cp, path, expansions);
820 return;
821 } else if (*cp != '\0') {
822 /*
823 * Back up to the start of the component
824 */
825 while (cp > word && *cp != '/') {
826 cp--;
827 }
828 if (cp != word) {
829 char sc;
830 char *dirpath;
831 /*
832 * If the glob isn't in the first component, try and find
833 * all the components up to the one with a wildcard.
834 */
835 sc = cp[1];
836 ((char *)UNCONST(cp))[1] = '\0';
837 dirpath = Dir_FindFile(word, path);
838 ((char *)UNCONST(cp))[1] = sc;
839 /*
840 * dirpath is null if can't find the leading component
841 * XXX: Dir_FindFile won't find internal components.
842 * i.e. if the path contains ../Etc/Object and we're
843 * looking for Etc, it won't be found. Ah well.
844 * Probably not important.
845 */
846 if (dirpath != NULL) {
847 char *dp = &dirpath[strlen(dirpath) - 1];
848 if (*dp == '/')
849 *dp = '\0';
850 path = Lst_Init();
851 (void)Dir_AddDir(path, dirpath);
852 DirExpandInt(cp + 1, path, expansions);
853 Lst_Free(path);
854 }
855 } else {
856 /*
857 * Start the search from the local directory
858 */
859 DirExpandInt(word, path, expansions);
860 }
861 } else {
862 /*
863 * Return the file -- this should never happen.
864 */
865 DirExpandInt(word, path, expansions);
866 }
867 } else {
868 /*
869 * First the files in dot
870 */
871 DirMatchFiles(word, dot, expansions);
872
873 /*
874 * Then the files in every other directory on the path.
875 */
876 DirExpandInt(word, path, expansions);
877 }
878 }
879 if (DEBUG(DIR))
880 DirPrintExpansions(expansions);
881 }
882
883 /*-
884 *-----------------------------------------------------------------------
885 * DirLookup --
886 * Find if the file with the given name exists in the given path.
887 *
888 * Results:
889 * The path to the file or NULL. This path is guaranteed to be in a
890 * different part of memory than name and so may be safely free'd.
891 *
892 * Side Effects:
893 * None.
894 *-----------------------------------------------------------------------
895 */
896 static char *
897 DirLookup(CachedDir *dir, const char *name MAKE_ATTR_UNUSED, const char *cp,
898 Boolean hasSlash MAKE_ATTR_UNUSED)
899 {
900 char *file; /* the current filename to check */
901
902 DIR_DEBUG1(" %s ...\n", dir->name);
903
904 if (Hash_FindEntry(&dir->files, cp) == NULL)
905 return NULL;
906
907 file = str_concat3(dir->name, "/", cp);
908 DIR_DEBUG1(" returning %s\n", file);
909 dir->hits += 1;
910 hits += 1;
911 return file;
912 }
913
914
915 /*-
916 *-----------------------------------------------------------------------
917 * DirLookupSubdir --
918 * Find if the file with the given name exists in the given path.
919 *
920 * Results:
921 * The path to the file or NULL. This path is guaranteed to be in a
922 * different part of memory than name and so may be safely free'd.
923 *
924 * Side Effects:
925 * If the file is found, it is added in the modification times hash
926 * table.
927 *-----------------------------------------------------------------------
928 */
929 static char *
930 DirLookupSubdir(CachedDir *dir, const char *name)
931 {
932 struct make_stat mst;
933 char *file; /* the current filename to check */
934
935 if (dir != dot) {
936 file = str_concat3(dir->name, "/", name);
937 } else {
938 /*
939 * Checking in dot -- DON'T put a leading ./ on the thing.
940 */
941 file = bmake_strdup(name);
942 }
943
944 DIR_DEBUG1("checking %s ...\n", file);
945
946 if (cached_stat(file, &mst) == 0) {
947 nearmisses += 1;
948 return file;
949 }
950 free(file);
951 return NULL;
952 }
953
954 /*-
955 *-----------------------------------------------------------------------
956 * DirLookupAbs --
957 * Find if the file with the given name exists in the given path.
958 *
959 * Results:
960 * The path to the file, the empty string or NULL. If the file is
961 * the empty string, the search should be terminated.
962 * This path is guaranteed to be in a different part of memory
963 * than name and so may be safely free'd.
964 *
965 * Side Effects:
966 * None.
967 *-----------------------------------------------------------------------
968 */
969 static char *
970 DirLookupAbs(CachedDir *dir, const char *name, const char *cp)
971 {
972 char *p1; /* pointer into dir->name */
973 const char *p2; /* pointer into name */
974
975 DIR_DEBUG1(" %s ...\n", dir->name);
976
977 /*
978 * If the file has a leading path component and that component
979 * exactly matches the entire name of the current search
980 * directory, we can attempt another cache lookup. And if we don't
981 * have a hit, we can safely assume the file does not exist at all.
982 */
983 for (p1 = dir->name, p2 = name; *p1 && *p1 == *p2; p1++, p2++) {
984 continue;
985 }
986 if (*p1 != '\0' || p2 != cp - 1) {
987 return NULL;
988 }
989
990 if (Hash_FindEntry(&dir->files, cp) == NULL) {
991 DIR_DEBUG0(" must be here but isn't -- returning\n");
992 /* Return empty string: terminates search */
993 return bmake_strdup("");
994 }
995
996 dir->hits += 1;
997 hits += 1;
998 DIR_DEBUG1(" returning %s\n", name);
999 return bmake_strdup(name);
1000 }
1001
1002 /*-
1003 *-----------------------------------------------------------------------
1004 * DirFindDot --
1005 * Find the file given on "." or curdir
1006 *
1007 * Results:
1008 * The path to the file or NULL. This path is guaranteed to be in a
1009 * different part of memory than name and so may be safely free'd.
1010 *
1011 * Side Effects:
1012 * Hit counts change
1013 *-----------------------------------------------------------------------
1014 */
1015 static char *
1016 DirFindDot(Boolean hasSlash MAKE_ATTR_UNUSED, const char *name, const char *cp)
1017 {
1018
1019 if (Hash_FindEntry(&dot->files, cp) != NULL) {
1020 DIR_DEBUG0(" in '.'\n");
1021 hits += 1;
1022 dot->hits += 1;
1023 return bmake_strdup(name);
1024 }
1025 if (cur && Hash_FindEntry(&cur->files, cp) != NULL) {
1026 DIR_DEBUG1(" in ${.CURDIR} = %s\n", cur->name);
1027 hits += 1;
1028 cur->hits += 1;
1029 return str_concat3(cur->name, "/", cp);
1030 }
1031
1032 return NULL;
1033 }
1034
1035 /*-
1036 *-----------------------------------------------------------------------
1037 * Dir_FindFile --
1038 * Find the file with the given name along the given search path.
1039 *
1040 * Input:
1041 * name the file to find
1042 * path the Lst of directories to search
1043 *
1044 * Results:
1045 * The path to the file or NULL. This path is guaranteed to be in a
1046 * different part of memory than name and so may be safely free'd.
1047 *
1048 * Side Effects:
1049 * If the file is found in a directory which is not on the path
1050 * already (either 'name' is absolute or it is a relative path
1051 * [ dir1/.../dirn/file ] which exists below one of the directories
1052 * already on the search path), its directory is added to the end
1053 * of the path on the assumption that there will be more files in
1054 * that directory later on. Sometimes this is true. Sometimes not.
1055 *-----------------------------------------------------------------------
1056 */
1057 char *
1058 Dir_FindFile(const char *name, SearchPath *path)
1059 {
1060 SearchPathNode *ln;
1061 char *file; /* the current filename to check */
1062 CachedDir *dir;
1063 const char *base; /* Terminal name of file */
1064 Boolean hasLastDot = FALSE; /* true if we should search dot last */
1065 Boolean hasSlash; /* true if 'name' contains a / */
1066 struct make_stat mst; /* Buffer for stat, if necessary */
1067 const char *trailing_dot = ".";
1068
1069 /*
1070 * Find the final component of the name and note whether it has a
1071 * slash in it (the name, I mean)
1072 */
1073 base = strrchr(name, '/');
1074 if (base) {
1075 hasSlash = TRUE;
1076 base += 1;
1077 } else {
1078 hasSlash = FALSE;
1079 base = name;
1080 }
1081
1082 DIR_DEBUG1("Searching for %s ...", name);
1083
1084 if (path == NULL) {
1085 DIR_DEBUG0("couldn't open path, file not found\n");
1086 misses += 1;
1087 return NULL;
1088 }
1089
1090 Lst_Open(path);
1091 if ((ln = Lst_First(path)) != NULL) {
1092 dir = LstNode_Datum(ln);
1093 if (dir == dotLast) {
1094 hasLastDot = TRUE;
1095 DIR_DEBUG0("[dot last]...");
1096 }
1097 }
1098 DIR_DEBUG0("\n");
1099
1100 /*
1101 * If there's no leading directory components or if the leading
1102 * directory component is exactly `./', consult the cached contents
1103 * of each of the directories on the search path.
1104 */
1105 if (!hasSlash || (base - name == 2 && *name == '.')) {
1106 /*
1107 * We look through all the directories on the path seeking one which
1108 * contains the final component of the given name. If such a beast
1109 * is found, we concatenate the directory name and the final
1110 * component and return the resulting string. If we don't find any
1111 * such thing, we go on to phase two...
1112 *
1113 * No matter what, we always look for the file in the current
1114 * directory before anywhere else (unless we found the magic
1115 * DOTLAST path, in which case we search it last) and we *do not*
1116 * add the ./ to it if it exists.
1117 * This is so there are no conflicts between what the user
1118 * specifies (fish.c) and what pmake finds (./fish.c).
1119 */
1120 if (!hasLastDot && (file = DirFindDot(hasSlash, name, base)) != NULL) {
1121 Lst_Close(path);
1122 return file;
1123 }
1124
1125 while ((ln = Lst_Next(path)) != NULL) {
1126 dir = LstNode_Datum(ln);
1127 if (dir == dotLast)
1128 continue;
1129 if ((file = DirLookup(dir, name, base, hasSlash)) != NULL) {
1130 Lst_Close(path);
1131 return file;
1132 }
1133 }
1134
1135 if (hasLastDot && (file = DirFindDot(hasSlash, name, base)) != NULL) {
1136 Lst_Close(path);
1137 return file;
1138 }
1139 }
1140 Lst_Close(path);
1141
1142 /*
1143 * We didn't find the file on any directory in the search path.
1144 * If the name doesn't contain a slash, that means it doesn't exist.
1145 * If it *does* contain a slash, however, there is still hope: it
1146 * could be in a subdirectory of one of the members of the search
1147 * path. (eg. /usr/include and sys/types.h. The above search would
1148 * fail to turn up types.h in /usr/include, but it *is* in
1149 * /usr/include/sys/types.h).
1150 * [ This no longer applies: If we find such a beast, we assume there
1151 * will be more (what else can we assume?) and add all but the last
1152 * component of the resulting name onto the search path (at the
1153 * end).]
1154 * This phase is only performed if the file is *not* absolute.
1155 */
1156 if (!hasSlash) {
1157 DIR_DEBUG0(" failed.\n");
1158 misses += 1;
1159 return NULL;
1160 }
1161
1162 if (*base == '\0') {
1163 /* we were given a trailing "/" */
1164 base = trailing_dot;
1165 }
1166
1167 if (name[0] != '/') {
1168 Boolean checkedDot = FALSE;
1169
1170 DIR_DEBUG0(" Trying subdirectories...\n");
1171
1172 if (!hasLastDot) {
1173 if (dot) {
1174 checkedDot = TRUE;
1175 if ((file = DirLookupSubdir(dot, name)) != NULL)
1176 return file;
1177 }
1178 if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
1179 return file;
1180 }
1181
1182 Lst_Open(path);
1183 while ((ln = Lst_Next(path)) != NULL) {
1184 dir = LstNode_Datum(ln);
1185 if (dir == dotLast)
1186 continue;
1187 if (dir == dot) {
1188 if (checkedDot)
1189 continue;
1190 checkedDot = TRUE;
1191 }
1192 if ((file = DirLookupSubdir(dir, name)) != NULL) {
1193 Lst_Close(path);
1194 return file;
1195 }
1196 }
1197 Lst_Close(path);
1198
1199 if (hasLastDot) {
1200 if (dot && !checkedDot) {
1201 checkedDot = TRUE;
1202 if ((file = DirLookupSubdir(dot, name)) != NULL)
1203 return file;
1204 }
1205 if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
1206 return file;
1207 }
1208
1209 if (checkedDot) {
1210 /*
1211 * Already checked by the given name, since . was in the path,
1212 * so no point in proceeding...
1213 */
1214 DIR_DEBUG0(" Checked . already, returning NULL\n");
1215 return NULL;
1216 }
1217
1218 } else { /* name[0] == '/' */
1219
1220 /*
1221 * For absolute names, compare directory path prefix against the
1222 * the directory path of each member on the search path for an exact
1223 * match. If we have an exact match on any member of the search path,
1224 * use the cached contents of that member to lookup the final file
1225 * component. If that lookup fails we can safely assume that the
1226 * file does not exist at all. This is signified by DirLookupAbs()
1227 * returning an empty string.
1228 */
1229 DIR_DEBUG0(" Trying exact path matches...\n");
1230
1231 if (!hasLastDot && cur &&
1232 ((file = DirLookupAbs(cur, name, base)) != NULL)) {
1233 if (file[0] == '\0') {
1234 free(file);
1235 return NULL;
1236 }
1237 return file;
1238 }
1239
1240 Lst_Open(path);
1241 while ((ln = Lst_Next(path)) != NULL) {
1242 dir = LstNode_Datum(ln);
1243 if (dir == dotLast)
1244 continue;
1245 if ((file = DirLookupAbs(dir, name, base)) != NULL) {
1246 Lst_Close(path);
1247 if (file[0] == '\0') {
1248 free(file);
1249 return NULL;
1250 }
1251 return file;
1252 }
1253 }
1254 Lst_Close(path);
1255
1256 if (hasLastDot && cur &&
1257 ((file = DirLookupAbs(cur, name, base)) != NULL)) {
1258 if (file[0] == '\0') {
1259 free(file);
1260 return NULL;
1261 }
1262 return file;
1263 }
1264 }
1265
1266 /*
1267 * Didn't find it that way, either. Sigh. Phase 3. Add its directory
1268 * onto the search path in any case, just in case, then look for the
1269 * thing in the hash table. If we find it, grand. We return a new
1270 * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
1271 * Note that if the directory holding the file doesn't exist, this will
1272 * do an extra search of the final directory on the path. Unless something
1273 * weird happens, this search won't succeed and life will be groovy.
1274 *
1275 * Sigh. We cannot add the directory onto the search path because
1276 * of this amusing case:
1277 * $(INSTALLDIR)/$(FILE): $(FILE)
1278 *
1279 * $(FILE) exists in $(INSTALLDIR) but not in the current one.
1280 * When searching for $(FILE), we will find it in $(INSTALLDIR)
1281 * b/c we added it here. This is not good...
1282 */
1283 #ifdef notdef
1284 if (base == trailing_dot) {
1285 base = strrchr(name, '/');
1286 base += 1;
1287 }
1288 base[-1] = '\0';
1289 (void)Dir_AddDir(path, name);
1290 base[-1] = '/';
1291
1292 bigmisses += 1;
1293 ln = Lst_Last(path);
1294 if (ln == NULL) {
1295 return NULL;
1296 } else {
1297 dir = LstNode_Datum(ln);
1298 }
1299
1300 if (Hash_FindEntry(&dir->files, base) != NULL) {
1301 return bmake_strdup(name);
1302 } else {
1303 return NULL;
1304 }
1305 #else /* !notdef */
1306 DIR_DEBUG1(" Looking for \"%s\" ...\n", name);
1307
1308 bigmisses += 1;
1309 if (cached_stat(name, &mst) == 0) {
1310 return bmake_strdup(name);
1311 }
1312
1313 DIR_DEBUG0(" failed. Returning NULL\n");
1314 return NULL;
1315 #endif /* notdef */
1316 }
1317
1318
1319 /*-
1320 *-----------------------------------------------------------------------
1321 * Dir_FindHereOrAbove --
1322 * search for a path starting at a given directory and then working
1323 * our way up towards the root.
1324 *
1325 * Input:
1326 * here starting directory
1327 * search_path the path we are looking for
1328 * result the result of a successful search is placed here
1329 * result_len the length of the result buffer
1330 * (typically MAXPATHLEN + 1)
1331 *
1332 * Results:
1333 * 0 on failure, 1 on success [in which case the found path is put
1334 * in the result buffer].
1335 *
1336 * Side Effects:
1337 *-----------------------------------------------------------------------
1338 */
1339 Boolean
1340 Dir_FindHereOrAbove(const char *here, const char *search_path,
1341 char *result, int result_len)
1342 {
1343 struct make_stat mst;
1344 char dirbase[MAXPATHLEN + 1], *dirbase_end;
1345 char try[MAXPATHLEN + 1], *try_end;
1346
1347 /* copy out our starting point */
1348 snprintf(dirbase, sizeof(dirbase), "%s", here);
1349 dirbase_end = dirbase + strlen(dirbase);
1350
1351 /* loop until we determine a result */
1352 while (TRUE) {
1353
1354 /* try and stat(2) it ... */
1355 snprintf(try, sizeof(try), "%s/%s", dirbase, search_path);
1356 if (cached_stat(try, &mst) != -1) {
1357 /*
1358 * success! if we found a file, chop off
1359 * the filename so we return a directory.
1360 */
1361 if ((mst.mst_mode & S_IFMT) != S_IFDIR) {
1362 try_end = try + strlen(try);
1363 while (try_end > try && *try_end != '/')
1364 try_end--;
1365 if (try_end > try)
1366 *try_end = '\0'; /* chop! */
1367 }
1368
1369 snprintf(result, result_len, "%s", try);
1370 return TRUE;
1371 }
1372
1373 /*
1374 * nope, we didn't find it. if we used up dirbase we've
1375 * reached the root and failed.
1376 */
1377 if (dirbase_end == dirbase)
1378 break; /* failed! */
1379
1380 /*
1381 * truncate dirbase from the end to move up a dir
1382 */
1383 while (dirbase_end > dirbase && *dirbase_end != '/')
1384 dirbase_end--;
1385 *dirbase_end = '\0'; /* chop! */
1386
1387 } /* while (TRUE) */
1388
1389 return FALSE;
1390 }
1391
1392 /*-
1393 *-----------------------------------------------------------------------
1394 * Dir_MTime --
1395 * Find the modification time of the file described by gn along the
1396 * search path dirSearchPath.
1397 *
1398 * Input:
1399 * gn the file whose modification time is desired
1400 *
1401 * Results:
1402 * The modification time or 0 if it doesn't exist
1403 *
1404 * Side Effects:
1405 * The modification time is placed in the node's mtime slot.
1406 * If the node didn't have a path entry before, and Dir_FindFile
1407 * found one for it, the full name is placed in the path slot.
1408 *-----------------------------------------------------------------------
1409 */
1410 int
1411 Dir_MTime(GNode *gn, Boolean recheck)
1412 {
1413 char *fullName; /* the full pathname of name */
1414 struct make_stat mst; /* buffer for finding the mod time */
1415
1416 if (gn->type & OP_ARCHV) {
1417 return Arch_MTime(gn);
1418 } else if (gn->type & OP_PHONY) {
1419 gn->mtime = 0;
1420 return 0;
1421 } else if (gn->path == NULL) {
1422 if (gn->type & OP_NOPATH)
1423 fullName = NULL;
1424 else {
1425 fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
1426 if (fullName == NULL && gn->flags & FROM_DEPEND &&
1427 !Lst_IsEmpty(gn->implicitParents)) {
1428 char *cp;
1429
1430 cp = strrchr(gn->name, '/');
1431 if (cp) {
1432 /*
1433 * This is an implied source, and it may have moved,
1434 * see if we can find it via the current .PATH
1435 */
1436 cp++;
1437
1438 fullName = Dir_FindFile(cp, Suff_FindPath(gn));
1439 if (fullName) {
1440 /*
1441 * Put the found file in gn->path
1442 * so that we give that to the compiler.
1443 */
1444 gn->path = bmake_strdup(fullName);
1445 if (!Job_RunTarget(".STALE", gn->fname))
1446 fprintf(stdout,
1447 "%s: %s, %d: ignoring stale %s for %s, "
1448 "found %s\n", progname, gn->fname,
1449 gn->lineno,
1450 makeDependfile, gn->name, fullName);
1451 }
1452 }
1453 }
1454 DIR_DEBUG2("Found '%s' as '%s'\n",
1455 gn->name, fullName ? fullName : "(not found)");
1456 }
1457 } else {
1458 fullName = gn->path;
1459 }
1460
1461 if (fullName == NULL) {
1462 fullName = bmake_strdup(gn->name);
1463 }
1464
1465 if (cached_stats(&mtimes, fullName, &mst, recheck ? CST_UPDATE : 0) < 0) {
1466 if (gn->type & OP_MEMBER) {
1467 if (fullName != gn->path)
1468 free(fullName);
1469 return Arch_MemMTime(gn);
1470 } else {
1471 mst.mst_mtime = 0;
1472 }
1473 }
1474
1475 if (fullName && gn->path == NULL) {
1476 gn->path = fullName;
1477 }
1478
1479 gn->mtime = mst.mst_mtime;
1480 return gn->mtime;
1481 }
1482
1483 /* Read the list of filenames in the directory and store the result
1484 * in openDirectories.
1485 *
1486 * If a path is given, append the directory to that path.
1487 *
1488 * Input:
1489 * path The path to which the directory should be
1490 * added, or NULL to only add the directory to
1491 * openDirectories
1492 * name The name of the directory to add.
1493 * The name is not normalized in any way.
1494 */
1495 CachedDir *
1496 Dir_AddDir(SearchPath *path, const char *name)
1497 {
1498 SearchPathNode *ln = NULL;
1499 CachedDir *dir = NULL; /* the added directory */
1500 DIR *d;
1501 struct dirent *dp;
1502
1503 if (path != NULL && strcmp(name, ".DOTLAST") == 0) {
1504 ln = Lst_Find(path, DirFindName, name);
1505 if (ln != NULL)
1506 return LstNode_Datum(ln);
1507
1508 dotLast->refCount++;
1509 Lst_Prepend(path, dotLast);
1510 }
1511
1512 if (path != NULL)
1513 ln = Lst_Find(openDirectories, DirFindName, name);
1514 if (ln != NULL) {
1515 dir = LstNode_Datum(ln);
1516 if (Lst_FindDatum(path, dir) == NULL) {
1517 dir->refCount += 1;
1518 Lst_Append(path, dir);
1519 }
1520 return dir;
1521 }
1522
1523 DIR_DEBUG1("Caching %s ...", name);
1524
1525 if ((d = opendir(name)) != NULL) {
1526 dir = bmake_malloc(sizeof(CachedDir));
1527 dir->name = bmake_strdup(name);
1528 dir->hits = 0;
1529 dir->refCount = 1;
1530 Hash_InitTable(&dir->files);
1531
1532 while ((dp = readdir(d)) != NULL) {
1533 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
1534 /*
1535 * The sun directory library doesn't check for a 0 inode
1536 * (0-inode slots just take up space), so we have to do
1537 * it ourselves.
1538 */
1539 if (dp->d_fileno == 0) {
1540 continue;
1541 }
1542 #endif /* sun && d_ino */
1543 (void)Hash_CreateEntry(&dir->files, dp->d_name, NULL);
1544 }
1545 (void)closedir(d);
1546 Lst_Append(openDirectories, dir);
1547 if (path != NULL)
1548 Lst_Append(path, dir);
1549 }
1550 DIR_DEBUG0("done\n");
1551 return dir;
1552 }
1553
1554 /*-
1555 *-----------------------------------------------------------------------
1556 * Dir_CopyDir --
1557 * Callback function for duplicating a search path via Lst_Copy.
1558 * Ups the reference count for the directory.
1559 *
1560 * Results:
1561 * Returns the Path it was given.
1562 *-----------------------------------------------------------------------
1563 */
1564 void *
1565 Dir_CopyDir(void *p)
1566 {
1567 CachedDir *dir = (CachedDir *)p;
1568 dir->refCount += 1;
1569
1570 return p;
1571 }
1572
1573 /*-
1574 *-----------------------------------------------------------------------
1575 * Dir_MakeFlags --
1576 * Make a string by taking all the directories in the given search
1577 * path and preceding them by the given flag. Used by the suffix
1578 * module to create variables for compilers based on suffix search
1579 * paths.
1580 *
1581 * Input:
1582 * flag flag which should precede each directory
1583 * path list of directories
1584 *
1585 * Results:
1586 * The string mentioned above. Note that there is no space between
1587 * the given flag and each directory. The empty string is returned if
1588 * Things don't go well.
1589 *
1590 * Side Effects:
1591 * None
1592 *-----------------------------------------------------------------------
1593 */
1594 char *
1595 Dir_MakeFlags(const char *flag, SearchPath *path)
1596 {
1597 Buffer buf;
1598 SearchPathNode *ln;
1599
1600 Buf_Init(&buf, 0);
1601
1602 if (path != NULL) {
1603 for (ln = path->first; ln != NULL; ln = ln->next) {
1604 CachedDir *dir = ln->datum;
1605 Buf_AddStr(&buf, " ");
1606 Buf_AddStr(&buf, flag);
1607 Buf_AddStr(&buf, dir->name);
1608 }
1609 }
1610
1611 return Buf_Destroy(&buf, FALSE);
1612 }
1613
1614 /*-
1615 *-----------------------------------------------------------------------
1616 * Dir_Destroy --
1617 * Nuke a directory descriptor, if possible. Callback procedure
1618 * for the suffixes module when destroying a search path.
1619 *
1620 * Input:
1621 * dirp The directory descriptor to nuke
1622 *
1623 * Results:
1624 * None.
1625 *
1626 * Side Effects:
1627 * If no other path references this directory (refCount == 0),
1628 * the CachedDir and all its data are freed.
1629 *
1630 *-----------------------------------------------------------------------
1631 */
1632 void
1633 Dir_Destroy(void *dirp)
1634 {
1635 CachedDir *dir = dirp;
1636 dir->refCount -= 1;
1637
1638 if (dir->refCount == 0) {
1639 CachedDirListNode *node;
1640
1641 node = Lst_FindDatum(openDirectories, dir);
1642 if (node != NULL)
1643 Lst_Remove(openDirectories, node);
1644
1645 Hash_DeleteTable(&dir->files);
1646 free(dir->name);
1647 free(dir);
1648 }
1649 }
1650
1651 /*-
1652 *-----------------------------------------------------------------------
1653 * Dir_ClearPath --
1654 * Clear out all elements of the given search path. This is different
1655 * from destroying the list, notice.
1656 *
1657 * Input:
1658 * path Path to clear
1659 *
1660 * Results:
1661 * None.
1662 *
1663 * Side Effects:
1664 * The path is set to the empty list.
1665 *
1666 *-----------------------------------------------------------------------
1667 */
1668 void
1669 Dir_ClearPath(SearchPath *path)
1670 {
1671 while (!Lst_IsEmpty(path)) {
1672 CachedDir *dir = Lst_Dequeue(path);
1673 Dir_Destroy(dir);
1674 }
1675 }
1676
1677
1678 /*-
1679 *-----------------------------------------------------------------------
1680 * Dir_Concat --
1681 * Concatenate two paths, adding the second to the end of the first.
1682 * Makes sure to avoid duplicates.
1683 *
1684 * Input:
1685 * path1 Dest
1686 * path2 Source
1687 *
1688 * Results:
1689 * None
1690 *
1691 * Side Effects:
1692 * Reference counts for added dirs are upped.
1693 *
1694 *-----------------------------------------------------------------------
1695 */
1696 void
1697 Dir_Concat(SearchPath *path1, SearchPath *path2)
1698 {
1699 SearchPathNode *ln;
1700
1701 for (ln = path2->first; ln != NULL; ln = ln->next) {
1702 CachedDir *dir = ln->datum;
1703 if (Lst_FindDatum(path1, dir) == NULL) {
1704 dir->refCount += 1;
1705 Lst_Append(path1, dir);
1706 }
1707 }
1708 }
1709
1710 static int
1711 percentage(int num, int den)
1712 {
1713 return den != 0 ? num * 100 / den : 0;
1714 }
1715
1716 /********** DEBUG INFO **********/
1717 void
1718 Dir_PrintDirectories(void)
1719 {
1720 CachedDirListNode *ln;
1721
1722 fprintf(debug_file, "#*** Directory Cache:\n");
1723 fprintf(debug_file,
1724 "# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
1725 hits, misses, nearmisses, bigmisses,
1726 percentage(hits, hits + bigmisses + nearmisses));
1727 fprintf(debug_file, "# %-20s referenced\thits\n", "directory");
1728
1729 for (ln = openDirectories->first; ln != NULL; ln = ln->next) {
1730 CachedDir *dir = ln->datum;
1731 fprintf(debug_file, "# %-20s %10d\t%4d\n", dir->name, dir->refCount,
1732 dir->hits);
1733 }
1734 }
1735
1736 void
1737 Dir_PrintPath(SearchPath *path)
1738 {
1739 SearchPathNode *node;
1740 for (node = path->first; node != NULL; node = node->next) {
1741 const CachedDir *dir = node->datum;
1742 fprintf(debug_file, "%s ", dir->name);
1743 }
1744 }
1745