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