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