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