dir.c revision 1.120 1 /* $NetBSD: dir.c,v 1.120 2020/08/28 04:59:17 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.120 2020/08/28 04:59:17 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.120 2020/08/28 04:59:17 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_Member(openDirectories, dot);
421 Lst_Remove(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_Free(dirSearchPath);
465 Dir_ClearPath(openDirectories);
466 Lst_Free(openDirectories);
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 if we should search dot last */
482
483 Var_Delete(".PATH", VAR_GLOBAL);
484
485 Lst_Open(dirSearchPath);
486 if ((ln = Lst_First(dirSearchPath)) != NULL) {
487 p = Lst_Datum(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_Next(dirSearchPath)) != NULL) {
502 p = Lst_Datum(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_Close(dirSearchPath);
517 }
518
519 /*-
520 *-----------------------------------------------------------------------
521 * DirFindName --
522 * See if the Path structure describes the same directory as the
523 * given one by comparing their names. Called from Dir_AddDir via
524 * Lst_Find when searching the list of open directories.
525 *
526 * Input:
527 * p Current name
528 * dname Desired name
529 *
530 * Results:
531 * 0 if it is the same. Non-zero otherwise
532 *
533 * Side Effects:
534 * None
535 *-----------------------------------------------------------------------
536 */
537 static int
538 DirFindName(const void *p, const void *dname)
539 {
540 return strcmp(((const Path *)p)->name, dname);
541 }
542
543 /*-
544 *-----------------------------------------------------------------------
545 * Dir_HasWildcards --
546 * see if the given name has any wildcard characters in it
547 * be careful not to expand unmatching brackets or braces.
548 * XXX: This code is not 100% correct. ([^]] fails etc.)
549 * I really don't think that make(1) should be expanding
550 * patterns, because then you have to set a mechanism for
551 * escaping the expansion!
552 *
553 * Input:
554 * name name to check
555 *
556 * Results:
557 * returns TRUE if the word should be expanded, FALSE otherwise
558 *
559 * Side Effects:
560 * none
561 *-----------------------------------------------------------------------
562 */
563 Boolean
564 Dir_HasWildcards(char *name)
565 {
566 char *cp;
567 int wild = 0, brace = 0, bracket = 0;
568
569 for (cp = name; *cp; cp++) {
570 switch (*cp) {
571 case '{':
572 brace++;
573 wild = 1;
574 break;
575 case '}':
576 brace--;
577 break;
578 case '[':
579 bracket++;
580 wild = 1;
581 break;
582 case ']':
583 bracket--;
584 break;
585 case '?':
586 case '*':
587 wild = 1;
588 break;
589 default:
590 break;
591 }
592 }
593 return wild && bracket == 0 && brace == 0;
594 }
595
596 /*-
597 *-----------------------------------------------------------------------
598 * DirMatchFiles --
599 * Given a pattern and a Path structure, see if any files
600 * match the pattern and add their names to the 'expansions' list if
601 * any do. This is incomplete -- it doesn't take care of patterns like
602 * src / *src / *.c properly (just *.c on any of the directories), but it
603 * will do for now.
604 *
605 * Input:
606 * pattern Pattern to look for
607 * p Directory to search
608 * expansion Place to store the results
609 *
610 * Side Effects:
611 * File names are added to the expansions lst. The directory will be
612 * fully hashed when this is done.
613 *-----------------------------------------------------------------------
614 */
615 static void
616 DirMatchFiles(const char *pattern, Path *p, Lst expansions)
617 {
618 Hash_Search search; /* Index into the directory's table */
619 Hash_Entry *entry; /* Current entry in the table */
620 Boolean isDot; /* TRUE if the directory being searched is . */
621
622 isDot = (*p->name == '.' && p->name[1] == '\0');
623
624 for (entry = Hash_EnumFirst(&p->files, &search);
625 entry != NULL;
626 entry = Hash_EnumNext(&search))
627 {
628 /*
629 * See if the file matches the given pattern. Note we follow the UNIX
630 * convention that dot files will only be found if the pattern
631 * begins with a dot (note also that as a side effect of the hashing
632 * scheme, .* won't match . or .. since they aren't hashed).
633 */
634 if (Str_Match(entry->name, pattern) &&
635 ((entry->name[0] != '.') ||
636 (pattern[0] == '.')))
637 {
638 Lst_Append(expansions,
639 (isDot ? bmake_strdup(entry->name) :
640 str_concat3(p->name, "/", entry->name)));
641 }
642 }
643 }
644
645 /* Find the next closing brace in the string, taking nested braces into
646 * account. */
647 static const char *
648 closing_brace(const char *p)
649 {
650 int nest = 0;
651 while (*p != '\0') {
652 if (*p == '}' && nest == 0)
653 break;
654 if (*p == '{')
655 nest++;
656 if (*p == '}')
657 nest--;
658 p++;
659 }
660 return p;
661 }
662
663 /* Find the next closing brace or comma in the string, taking nested braces
664 * into account. */
665 static const char *
666 separator_comma(const char *p)
667 {
668 int nest = 0;
669 while (*p != '\0') {
670 if ((*p == '}' || *p == ',') && nest == 0)
671 break;
672 if (*p == '{')
673 nest++;
674 if (*p == '}')
675 nest--;
676 p++;
677 }
678 return p;
679 }
680
681 static Boolean
682 contains_wildcard(const char *p)
683 {
684 for (; *p != '\0'; p++) {
685 switch (*p) {
686 case '*':
687 case '?':
688 case '{':
689 case '[':
690 return TRUE;
691 }
692 }
693 return FALSE;
694 }
695
696 static char *
697 concat3(const char *a, size_t a_len, const char *b, size_t b_len,
698 const char *c, size_t c_len)
699 {
700 size_t s_len = a_len + b_len + c_len;
701 char *s = bmake_malloc(s_len + 1);
702 memcpy(s, a, a_len);
703 memcpy(s + a_len, b, b_len);
704 memcpy(s + a_len + b_len, c, c_len);
705 s[s_len] = '\0';
706 return s;
707 }
708
709 /*-
710 *-----------------------------------------------------------------------
711 * DirExpandCurly --
712 * Expand curly braces like the C shell. Does this recursively.
713 * Note the special case: if after the piece of the curly brace is
714 * done there are no wildcard characters in the result, the result is
715 * placed on the list WITHOUT CHECKING FOR ITS EXISTENCE.
716 *
717 * Input:
718 * word Entire word to expand
719 * brace First curly brace in it
720 * path Search path to use
721 * expansions Place to store the expansions
722 *
723 * Results:
724 * None.
725 *
726 * Side Effects:
727 * The given list is filled with the expansions...
728 *
729 *-----------------------------------------------------------------------
730 */
731 static void
732 DirExpandCurly(const char *word, const char *brace, Lst path, Lst expansions)
733 {
734 const char *prefix, *middle, *piece, *middle_end, *suffix;
735 size_t prefix_len, suffix_len;
736
737 /* Split the word into prefix '{' middle '}' suffix. */
738
739 middle = brace + 1;
740 middle_end = closing_brace(middle);
741 if (*middle_end == '\0') {
742 Error("Unterminated {} clause \"%s\"", middle);
743 return;
744 }
745
746 prefix = word;
747 prefix_len = (size_t)(brace - prefix);
748 suffix = middle_end + 1;
749 suffix_len = strlen(suffix);
750
751 /* Split the middle into pieces, separated by commas. */
752
753 piece = middle;
754 while (piece < middle_end + 1) {
755 const char *piece_end = separator_comma(piece);
756 size_t piece_len = (size_t)(piece_end - piece);
757
758 char *file = concat3(prefix, prefix_len, piece, piece_len,
759 suffix, suffix_len);
760
761 if (contains_wildcard(file)) {
762 Dir_Expand(file, path, expansions);
763 free(file);
764 } else {
765 Lst_Append(expansions, file);
766 }
767
768 piece = piece_end + 1; /* skip over the comma or closing brace */
769 }
770 }
771
772
773 /*-
774 *-----------------------------------------------------------------------
775 * DirExpandInt --
776 * Internal expand routine. Passes through the directories in the
777 * path one by one, calling DirMatchFiles for each. NOTE: This still
778 * doesn't handle patterns in directories...
779 *
780 * Input:
781 * word Word to expand
782 * path Path on which to look
783 * expansions Place to store the result
784 *
785 * Results:
786 * None.
787 *
788 * Side Effects:
789 * Things are added to the expansions list.
790 *
791 *-----------------------------------------------------------------------
792 */
793 static void
794 DirExpandInt(const char *word, Lst path, Lst expansions)
795 {
796 LstNode ln; /* Current node */
797
798 Lst_Open(path);
799 while ((ln = Lst_Next(path)) != NULL) {
800 Path *p = Lst_Datum(ln);
801 DirMatchFiles(word, p, expansions);
802 }
803 Lst_Close(path);
804 }
805
806 /* Print a word in the list of expansions.
807 * Callback for Dir_Expand when DEBUG(DIR), via Lst_ForEach. */
808 static int
809 DirPrintWord(void *word, void *dummy MAKE_ATTR_UNUSED)
810 {
811 fprintf(debug_file, "%s ", (char *)word);
812
813 return 0;
814 }
815
816 /*-
817 *-----------------------------------------------------------------------
818 * Dir_Expand --
819 * Expand the given word into a list of words by globbing it looking
820 * in the directories on the given search path.
821 *
822 * Input:
823 * word the word to expand
824 * path the list of directories in which to find the
825 * resulting files
826 * expansions the list on which to place the results
827 *
828 * Results:
829 * A list of words consisting of the files which exist along the search
830 * path matching the given pattern.
831 *
832 * Side Effects:
833 * Directories may be opened. Who knows?
834 * Undefined behavior if the word is really in read-only memory.
835 *-----------------------------------------------------------------------
836 */
837 void
838 Dir_Expand(const char *word, Lst path, Lst expansions)
839 {
840 const char *cp;
841
842 assert(path != NULL);
843 assert(expansions != NULL);
844
845 DIR_DEBUG1("Expanding \"%s\"... ", word);
846
847 cp = strchr(word, '{');
848 if (cp) {
849 DirExpandCurly(word, cp, path, expansions);
850 } else {
851 cp = strchr(word, '/');
852 if (cp) {
853 /*
854 * The thing has a directory component -- find the first wildcard
855 * in the string.
856 */
857 for (cp = word; *cp; cp++) {
858 if (*cp == '?' || *cp == '[' || *cp == '*' || *cp == '{') {
859 break;
860 }
861 }
862 if (*cp == '{') {
863 /*
864 * This one will be fun.
865 */
866 DirExpandCurly(word, cp, path, expansions);
867 return;
868 } else if (*cp != '\0') {
869 /*
870 * Back up to the start of the component
871 */
872 while (cp > word && *cp != '/') {
873 cp--;
874 }
875 if (cp != word) {
876 char sc;
877 char *dirpath;
878 /*
879 * If the glob isn't in the first component, try and find
880 * all the components up to the one with a wildcard.
881 */
882 sc = cp[1];
883 ((char *)UNCONST(cp))[1] = '\0';
884 dirpath = Dir_FindFile(word, path);
885 ((char *)UNCONST(cp))[1] = sc;
886 /*
887 * dirpath is null if can't find the leading component
888 * XXX: Dir_FindFile won't find internal components.
889 * i.e. if the path contains ../Etc/Object and we're
890 * looking for Etc, it won't be found. Ah well.
891 * Probably not important.
892 */
893 if (dirpath != NULL) {
894 char *dp = &dirpath[strlen(dirpath) - 1];
895 if (*dp == '/')
896 *dp = '\0';
897 path = Lst_Init();
898 (void)Dir_AddDir(path, dirpath);
899 DirExpandInt(cp + 1, path, expansions);
900 Lst_Free(path);
901 }
902 } else {
903 /*
904 * Start the search from the local directory
905 */
906 DirExpandInt(word, path, expansions);
907 }
908 } else {
909 /*
910 * Return the file -- this should never happen.
911 */
912 DirExpandInt(word, path, expansions);
913 }
914 } else {
915 /*
916 * First the files in dot
917 */
918 DirMatchFiles(word, dot, expansions);
919
920 /*
921 * Then the files in every other directory on the path.
922 */
923 DirExpandInt(word, path, expansions);
924 }
925 }
926 if (DEBUG(DIR)) {
927 Lst_ForEach(expansions, DirPrintWord, NULL);
928 fprintf(debug_file, "\n");
929 }
930 }
931
932 /*-
933 *-----------------------------------------------------------------------
934 * DirLookup --
935 * Find if the file with the given name exists in the given path.
936 *
937 * Results:
938 * The path to the file or NULL. This path is guaranteed to be in a
939 * different part of memory than name and so may be safely free'd.
940 *
941 * Side Effects:
942 * None.
943 *-----------------------------------------------------------------------
944 */
945 static char *
946 DirLookup(Path *p, const char *name MAKE_ATTR_UNUSED, const char *cp,
947 Boolean hasSlash MAKE_ATTR_UNUSED)
948 {
949 char *file; /* the current filename to check */
950
951 DIR_DEBUG1(" %s ...\n", p->name);
952
953 if (Hash_FindEntry(&p->files, cp) == NULL)
954 return NULL;
955
956 file = str_concat3(p->name, "/", cp);
957 DIR_DEBUG1(" returning %s\n", file);
958 p->hits += 1;
959 hits += 1;
960 return file;
961 }
962
963
964 /*-
965 *-----------------------------------------------------------------------
966 * DirLookupSubdir --
967 * Find if the file with the given name exists in the given path.
968 *
969 * Results:
970 * The path to the file or NULL. This path is guaranteed to be in a
971 * different part of memory than name and so may be safely free'd.
972 *
973 * Side Effects:
974 * If the file is found, it is added in the modification times hash
975 * table.
976 *-----------------------------------------------------------------------
977 */
978 static char *
979 DirLookupSubdir(Path *p, const char *name)
980 {
981 struct stat stb; /* Buffer for stat, if necessary */
982 char *file; /* the current filename to check */
983
984 if (p != dot) {
985 file = str_concat3(p->name, "/", name);
986 } else {
987 /*
988 * Checking in dot -- DON'T put a leading ./ on the thing.
989 */
990 file = bmake_strdup(name);
991 }
992
993 DIR_DEBUG1("checking %s ...\n", file);
994
995 if (cached_stat(file, &stb) == 0) {
996 nearmisses += 1;
997 return file;
998 }
999 free(file);
1000 return NULL;
1001 }
1002
1003 /*-
1004 *-----------------------------------------------------------------------
1005 * DirLookupAbs --
1006 * Find if the file with the given name exists in the given path.
1007 *
1008 * Results:
1009 * The path to the file, the empty string or NULL. If the file is
1010 * the empty string, the search should be terminated.
1011 * This path is guaranteed to be in a different part of memory
1012 * than name and so may be safely free'd.
1013 *
1014 * Side Effects:
1015 * None.
1016 *-----------------------------------------------------------------------
1017 */
1018 static char *
1019 DirLookupAbs(Path *p, const char *name, const char *cp)
1020 {
1021 char *p1; /* pointer into p->name */
1022 const char *p2; /* pointer into name */
1023
1024 DIR_DEBUG1(" %s ...\n", p->name);
1025
1026 /*
1027 * If the file has a leading path component and that component
1028 * exactly matches the entire name of the current search
1029 * directory, we can attempt another cache lookup. And if we don't
1030 * have a hit, we can safely assume the file does not exist at all.
1031 */
1032 for (p1 = p->name, p2 = name; *p1 && *p1 == *p2; p1++, p2++) {
1033 continue;
1034 }
1035 if (*p1 != '\0' || p2 != cp - 1) {
1036 return NULL;
1037 }
1038
1039 if (Hash_FindEntry(&p->files, cp) == NULL) {
1040 DIR_DEBUG0(" must be here but isn't -- returning\n");
1041 /* Return empty string: terminates search */
1042 return bmake_strdup("");
1043 }
1044
1045 p->hits += 1;
1046 hits += 1;
1047 DIR_DEBUG1(" returning %s\n", name);
1048 return bmake_strdup(name);
1049 }
1050
1051 /*-
1052 *-----------------------------------------------------------------------
1053 * DirFindDot --
1054 * Find the file given on "." or curdir
1055 *
1056 * Results:
1057 * The path to the file or NULL. This path is guaranteed to be in a
1058 * different part of memory than name and so may be safely free'd.
1059 *
1060 * Side Effects:
1061 * Hit counts change
1062 *-----------------------------------------------------------------------
1063 */
1064 static char *
1065 DirFindDot(Boolean hasSlash MAKE_ATTR_UNUSED, const char *name, const char *cp)
1066 {
1067
1068 if (Hash_FindEntry(&dot->files, cp) != NULL) {
1069 DIR_DEBUG0(" in '.'\n");
1070 hits += 1;
1071 dot->hits += 1;
1072 return bmake_strdup(name);
1073 }
1074 if (cur && Hash_FindEntry(&cur->files, cp) != NULL) {
1075 DIR_DEBUG1(" in ${.CURDIR} = %s\n", cur->name);
1076 hits += 1;
1077 cur->hits += 1;
1078 return str_concat3(cur->name, "/", cp);
1079 }
1080
1081 return NULL;
1082 }
1083
1084 /*-
1085 *-----------------------------------------------------------------------
1086 * Dir_FindFile --
1087 * Find the file with the given name along the given search path.
1088 *
1089 * Input:
1090 * name the file to find
1091 * path the Lst of directories to search
1092 *
1093 * Results:
1094 * The path to the file or NULL. This path is guaranteed to be in a
1095 * different part of memory than name and so may be safely free'd.
1096 *
1097 * Side Effects:
1098 * If the file is found in a directory which is not on the path
1099 * already (either 'name' is absolute or it is a relative path
1100 * [ dir1/.../dirn/file ] which exists below one of the directories
1101 * already on the search path), its directory is added to the end
1102 * of the path on the assumption that there will be more files in
1103 * that directory later on. Sometimes this is true. Sometimes not.
1104 *-----------------------------------------------------------------------
1105 */
1106 char *
1107 Dir_FindFile(const char *name, Lst path)
1108 {
1109 LstNode ln; /* a list element */
1110 char *file; /* the current filename to check */
1111 Path *p; /* current path member */
1112 const char *cp; /* Terminal name of file */
1113 Boolean hasLastDot = FALSE; /* true we should search dot last */
1114 Boolean hasSlash; /* true if 'name' contains a / */
1115 struct stat stb; /* Buffer for stat, if necessary */
1116 const char *trailing_dot = ".";
1117
1118 /*
1119 * Find the final component of the name and note whether it has a
1120 * slash in it (the name, I mean)
1121 */
1122 cp = strrchr(name, '/');
1123 if (cp) {
1124 hasSlash = TRUE;
1125 cp += 1;
1126 } else {
1127 hasSlash = FALSE;
1128 cp = name;
1129 }
1130
1131 DIR_DEBUG1("Searching for %s ...", name);
1132
1133 if (path == NULL) {
1134 DIR_DEBUG0("couldn't open path, file not found\n");
1135 misses += 1;
1136 return NULL;
1137 }
1138
1139 Lst_Open(path);
1140 if ((ln = Lst_First(path)) != NULL) {
1141 p = Lst_Datum(ln);
1142 if (p == dotLast) {
1143 hasLastDot = TRUE;
1144 DIR_DEBUG0("[dot last]...");
1145 }
1146 }
1147 DIR_DEBUG0("\n");
1148
1149 /*
1150 * If there's no leading directory components or if the leading
1151 * directory component is exactly `./', consult the cached contents
1152 * of each of the directories on the search path.
1153 */
1154 if (!hasSlash || (cp - name == 2 && *name == '.')) {
1155 /*
1156 * We look through all the directories on the path seeking one which
1157 * contains the final component of the given name. If such a beast
1158 * is found, we concatenate the directory name and the final
1159 * component and return the resulting string. If we don't find any
1160 * such thing, we go on to phase two...
1161 *
1162 * No matter what, we always look for the file in the current
1163 * directory before anywhere else (unless we found the magic
1164 * DOTLAST path, in which case we search it last) and we *do not*
1165 * add the ./ to it if it exists.
1166 * This is so there are no conflicts between what the user
1167 * specifies (fish.c) and what pmake finds (./fish.c).
1168 */
1169 if (!hasLastDot && (file = DirFindDot(hasSlash, name, cp)) != NULL) {
1170 Lst_Close(path);
1171 return file;
1172 }
1173
1174 while ((ln = Lst_Next(path)) != NULL) {
1175 p = Lst_Datum(ln);
1176 if (p == dotLast)
1177 continue;
1178 if ((file = DirLookup(p, name, cp, hasSlash)) != NULL) {
1179 Lst_Close(path);
1180 return file;
1181 }
1182 }
1183
1184 if (hasLastDot && (file = DirFindDot(hasSlash, name, cp)) != NULL) {
1185 Lst_Close(path);
1186 return file;
1187 }
1188 }
1189 Lst_Close(path);
1190
1191 /*
1192 * We didn't find the file on any directory in the search path.
1193 * If the name doesn't contain a slash, that means it doesn't exist.
1194 * If it *does* contain a slash, however, there is still hope: it
1195 * could be in a subdirectory of one of the members of the search
1196 * path. (eg. /usr/include and sys/types.h. The above search would
1197 * fail to turn up types.h in /usr/include, but it *is* in
1198 * /usr/include/sys/types.h).
1199 * [ This no longer applies: If we find such a beast, we assume there
1200 * will be more (what else can we assume?) and add all but the last
1201 * component of the resulting name onto the search path (at the
1202 * end).]
1203 * This phase is only performed if the file is *not* absolute.
1204 */
1205 if (!hasSlash) {
1206 DIR_DEBUG0(" failed.\n");
1207 misses += 1;
1208 return NULL;
1209 }
1210
1211 if (*cp == '\0') {
1212 /* we were given a trailing "/" */
1213 cp = trailing_dot;
1214 }
1215
1216 if (name[0] != '/') {
1217 Boolean checkedDot = FALSE;
1218
1219 DIR_DEBUG0(" Trying subdirectories...\n");
1220
1221 if (!hasLastDot) {
1222 if (dot) {
1223 checkedDot = TRUE;
1224 if ((file = DirLookupSubdir(dot, name)) != NULL)
1225 return file;
1226 }
1227 if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
1228 return file;
1229 }
1230
1231 Lst_Open(path);
1232 while ((ln = Lst_Next(path)) != NULL) {
1233 p = Lst_Datum(ln);
1234 if (p == dotLast)
1235 continue;
1236 if (p == dot) {
1237 if (checkedDot)
1238 continue;
1239 checkedDot = TRUE;
1240 }
1241 if ((file = DirLookupSubdir(p, name)) != NULL) {
1242 Lst_Close(path);
1243 return file;
1244 }
1245 }
1246 Lst_Close(path);
1247
1248 if (hasLastDot) {
1249 if (dot && !checkedDot) {
1250 checkedDot = TRUE;
1251 if ((file = DirLookupSubdir(dot, name)) != NULL)
1252 return file;
1253 }
1254 if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
1255 return file;
1256 }
1257
1258 if (checkedDot) {
1259 /*
1260 * Already checked by the given name, since . was in the path,
1261 * so no point in proceeding...
1262 */
1263 DIR_DEBUG0(" Checked . already, returning NULL\n");
1264 return NULL;
1265 }
1266
1267 } else { /* name[0] == '/' */
1268
1269 /*
1270 * For absolute names, compare directory path prefix against the
1271 * the directory path of each member on the search path for an exact
1272 * match. If we have an exact match on any member of the search path,
1273 * use the cached contents of that member to lookup the final file
1274 * component. If that lookup fails we can safely assume that the
1275 * file does not exist at all. This is signified by DirLookupAbs()
1276 * returning an empty string.
1277 */
1278 DIR_DEBUG0(" Trying exact path matches...\n");
1279
1280 if (!hasLastDot && cur &&
1281 ((file = DirLookupAbs(cur, name, cp)) != NULL)) {
1282 if (file[0] == '\0') {
1283 free(file);
1284 return NULL;
1285 }
1286 return file;
1287 }
1288
1289 Lst_Open(path);
1290 while ((ln = Lst_Next(path)) != NULL) {
1291 p = Lst_Datum(ln);
1292 if (p == dotLast)
1293 continue;
1294 if ((file = DirLookupAbs(p, name, cp)) != NULL) {
1295 Lst_Close(path);
1296 if (file[0] == '\0') {
1297 free(file);
1298 return NULL;
1299 }
1300 return file;
1301 }
1302 }
1303 Lst_Close(path);
1304
1305 if (hasLastDot && cur &&
1306 ((file = DirLookupAbs(cur, name, cp)) != NULL)) {
1307 if (file[0] == '\0') {
1308 free(file);
1309 return NULL;
1310 }
1311 return file;
1312 }
1313 }
1314
1315 /*
1316 * Didn't find it that way, either. Sigh. Phase 3. Add its directory
1317 * onto the search path in any case, just in case, then look for the
1318 * thing in the hash table. If we find it, grand. We return a new
1319 * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
1320 * Note that if the directory holding the file doesn't exist, this will
1321 * do an extra search of the final directory on the path. Unless something
1322 * weird happens, this search won't succeed and life will be groovy.
1323 *
1324 * Sigh. We cannot add the directory onto the search path because
1325 * of this amusing case:
1326 * $(INSTALLDIR)/$(FILE): $(FILE)
1327 *
1328 * $(FILE) exists in $(INSTALLDIR) but not in the current one.
1329 * When searching for $(FILE), we will find it in $(INSTALLDIR)
1330 * b/c we added it here. This is not good...
1331 */
1332 #ifdef notdef
1333 if (cp == traling_dot) {
1334 cp = strrchr(name, '/');
1335 cp += 1;
1336 }
1337 cp[-1] = '\0';
1338 (void)Dir_AddDir(path, name);
1339 cp[-1] = '/';
1340
1341 bigmisses += 1;
1342 ln = Lst_Last(path);
1343 if (ln == NULL) {
1344 return NULL;
1345 } else {
1346 p = Lst_Datum(ln);
1347 }
1348
1349 if (Hash_FindEntry(&p->files, cp) != NULL) {
1350 return bmake_strdup(name);
1351 } else {
1352 return NULL;
1353 }
1354 #else /* !notdef */
1355 DIR_DEBUG1(" Looking for \"%s\" ...\n", name);
1356
1357 bigmisses += 1;
1358 if (cached_stat(name, &stb) == 0) {
1359 return bmake_strdup(name);
1360 }
1361
1362 DIR_DEBUG0(" failed. Returning NULL\n");
1363 return NULL;
1364 #endif /* notdef */
1365 }
1366
1367
1368 /*-
1369 *-----------------------------------------------------------------------
1370 * Dir_FindHereOrAbove --
1371 * search for a path starting at a given directory and then working
1372 * our way up towards the root.
1373 *
1374 * Input:
1375 * here starting directory
1376 * search_path the path we are looking for
1377 * result the result of a successful search is placed here
1378 * rlen the length of the result buffer
1379 * (typically MAXPATHLEN + 1)
1380 *
1381 * Results:
1382 * 0 on failure, 1 on success [in which case the found path is put
1383 * in the result buffer].
1384 *
1385 * Side Effects:
1386 *-----------------------------------------------------------------------
1387 */
1388 int
1389 Dir_FindHereOrAbove(char *here, char *search_path, char *result, int rlen)
1390 {
1391 struct stat st;
1392 char dirbase[MAXPATHLEN + 1], *db_end;
1393 char try[MAXPATHLEN + 1], *try_end;
1394
1395 /* copy out our starting point */
1396 snprintf(dirbase, sizeof(dirbase), "%s", here);
1397 db_end = dirbase + strlen(dirbase);
1398
1399 /* loop until we determine a result */
1400 while (1) {
1401
1402 /* try and stat(2) it ... */
1403 snprintf(try, sizeof(try), "%s/%s", dirbase, search_path);
1404 if (cached_stat(try, &st) != -1) {
1405 /*
1406 * success! if we found a file, chop off
1407 * the filename so we return a directory.
1408 */
1409 if ((st.st_mode & S_IFMT) != S_IFDIR) {
1410 try_end = try + strlen(try);
1411 while (try_end > try && *try_end != '/')
1412 try_end--;
1413 if (try_end > try)
1414 *try_end = 0; /* chop! */
1415 }
1416
1417 /*
1418 * done!
1419 */
1420 snprintf(result, rlen, "%s", try);
1421 return 1;
1422 }
1423
1424 /*
1425 * nope, we didn't find it. if we used up dirbase we've
1426 * reached the root and failed.
1427 */
1428 if (db_end == dirbase)
1429 break; /* failed! */
1430
1431 /*
1432 * truncate dirbase from the end to move up a dir
1433 */
1434 while (db_end > dirbase && *db_end != '/')
1435 db_end--;
1436 *db_end = 0; /* chop! */
1437
1438 } /* while (1) */
1439
1440 /*
1441 * we failed...
1442 */
1443 return 0;
1444 }
1445
1446 /*-
1447 *-----------------------------------------------------------------------
1448 * Dir_MTime --
1449 * Find the modification time of the file described by gn along the
1450 * search path dirSearchPath.
1451 *
1452 * Input:
1453 * gn the file whose modification time is desired
1454 *
1455 * Results:
1456 * The modification time or 0 if it doesn't exist
1457 *
1458 * Side Effects:
1459 * The modification time is placed in the node's mtime slot.
1460 * If the node didn't have a path entry before, and Dir_FindFile
1461 * found one for it, the full name is placed in the path slot.
1462 *-----------------------------------------------------------------------
1463 */
1464 int
1465 Dir_MTime(GNode *gn, Boolean recheck)
1466 {
1467 char *fullName; /* the full pathname of name */
1468 struct stat stb; /* buffer for finding the mod time */
1469
1470 if (gn->type & OP_ARCHV) {
1471 return Arch_MTime(gn);
1472 } else if (gn->type & OP_PHONY) {
1473 gn->mtime = 0;
1474 return 0;
1475 } else if (gn->path == NULL) {
1476 if (gn->type & OP_NOPATH)
1477 fullName = NULL;
1478 else {
1479 fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
1480 if (fullName == NULL && gn->flags & FROM_DEPEND &&
1481 !Lst_IsEmpty(gn->iParents)) {
1482 char *cp;
1483
1484 cp = strrchr(gn->name, '/');
1485 if (cp) {
1486 /*
1487 * This is an implied source, and it may have moved,
1488 * see if we can find it via the current .PATH
1489 */
1490 cp++;
1491
1492 fullName = Dir_FindFile(cp, Suff_FindPath(gn));
1493 if (fullName) {
1494 /*
1495 * Put the found file in gn->path
1496 * so that we give that to the compiler.
1497 */
1498 gn->path = bmake_strdup(fullName);
1499 if (!Job_RunTarget(".STALE", gn->fname))
1500 fprintf(stdout,
1501 "%s: %s, %d: ignoring stale %s for %s, "
1502 "found %s\n", progname, gn->fname,
1503 gn->lineno,
1504 makeDependfile, gn->name, fullName);
1505 }
1506 }
1507 }
1508 DIR_DEBUG2("Found '%s' as '%s'\n",
1509 gn->name, fullName ? fullName : "(not found)");
1510 }
1511 } else {
1512 fullName = gn->path;
1513 }
1514
1515 if (fullName == NULL) {
1516 fullName = bmake_strdup(gn->name);
1517 }
1518
1519 if (cached_stats(&mtimes, fullName, &stb, recheck ? CST_UPDATE : 0) < 0) {
1520 if (gn->type & OP_MEMBER) {
1521 if (fullName != gn->path)
1522 free(fullName);
1523 return Arch_MemMTime(gn);
1524 } else {
1525 stb.st_mtime = 0;
1526 }
1527 }
1528
1529 if (fullName && gn->path == NULL) {
1530 gn->path = fullName;
1531 }
1532
1533 gn->mtime = stb.st_mtime;
1534 return gn->mtime;
1535 }
1536
1537 /*-
1538 *-----------------------------------------------------------------------
1539 * Dir_AddDir --
1540 * Add the given name to the end of the given path. The order of
1541 * the arguments is backwards so ParseDoDependency can do a
1542 * Lst_ForEach of its list of paths...
1543 *
1544 * Input:
1545 * path the path to which the directory should be
1546 * added
1547 * XXX: Why would this ever be NULL, and what does
1548 * that mean?
1549 * name the name of the directory to add
1550 *
1551 * Results:
1552 * none
1553 *
1554 * Side Effects:
1555 * A structure is added to the list and the directory is
1556 * read and hashed.
1557 *-----------------------------------------------------------------------
1558 */
1559 Path *
1560 Dir_AddDir(Lst path, const char *name)
1561 {
1562 LstNode ln = NULL; /* node in case Path structure is found */
1563 Path *p = NULL; /* pointer to new Path structure */
1564 DIR *d; /* for reading directory */
1565 struct dirent *dp; /* entry in directory */
1566
1567 if (path != NULL && strcmp(name, ".DOTLAST") == 0) {
1568 ln = Lst_Find(path, DirFindName, name);
1569 if (ln != NULL)
1570 return Lst_Datum(ln);
1571
1572 dotLast->refCount++;
1573 Lst_Prepend(path, dotLast);
1574 }
1575
1576 if (path != NULL)
1577 ln = Lst_Find(openDirectories, DirFindName, name);
1578 if (ln != NULL) {
1579 p = Lst_Datum(ln);
1580 if (Lst_Member(path, p) == NULL) {
1581 p->refCount += 1;
1582 Lst_Append(path, p);
1583 }
1584 return p;
1585 }
1586
1587 DIR_DEBUG1("Caching %s ...", name);
1588
1589 if ((d = opendir(name)) != NULL) {
1590 p = bmake_malloc(sizeof(Path));
1591 p->name = bmake_strdup(name);
1592 p->hits = 0;
1593 p->refCount = 1;
1594 Hash_InitTable(&p->files, -1);
1595
1596 while ((dp = readdir(d)) != NULL) {
1597 #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
1598 /*
1599 * The sun directory library doesn't check for a 0 inode
1600 * (0-inode slots just take up space), so we have to do
1601 * it ourselves.
1602 */
1603 if (dp->d_fileno == 0) {
1604 continue;
1605 }
1606 #endif /* sun && d_ino */
1607 (void)Hash_CreateEntry(&p->files, dp->d_name, NULL);
1608 }
1609 (void)closedir(d);
1610 Lst_Append(openDirectories, p);
1611 if (path != NULL)
1612 Lst_Append(path, p);
1613 }
1614 DIR_DEBUG0("done\n");
1615 return p;
1616 }
1617
1618 /*-
1619 *-----------------------------------------------------------------------
1620 * Dir_CopyDir --
1621 * Callback function for duplicating a search path via Lst_Copy.
1622 * Ups the reference count for the directory.
1623 *
1624 * Results:
1625 * Returns the Path it was given.
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 (path != NULL) {
1666 Lst_Open(path);
1667 while ((ln = Lst_Next(path)) != NULL) {
1668 Path *p = Lst_Datum(ln);
1669 Buf_AddStr(&buf, " ");
1670 Buf_AddStr(&buf, flag);
1671 Buf_AddStr(&buf, p->name);
1672 }
1673 Lst_Close(path);
1674 }
1675
1676 return Buf_Destroy(&buf, FALSE);
1677 }
1678
1679 /*-
1680 *-----------------------------------------------------------------------
1681 * Dir_Destroy --
1682 * Nuke a directory descriptor, if possible. Callback procedure
1683 * for the suffixes module when destroying a search path.
1684 *
1685 * Input:
1686 * pp The directory descriptor to nuke
1687 *
1688 * Results:
1689 * None.
1690 *
1691 * Side Effects:
1692 * If no other path references this directory (refCount == 0),
1693 * the Path and all its data are freed.
1694 *
1695 *-----------------------------------------------------------------------
1696 */
1697 void
1698 Dir_Destroy(void *pp)
1699 {
1700 Path *p = (Path *)pp;
1701 p->refCount -= 1;
1702
1703 if (p->refCount == 0) {
1704 LstNode ln;
1705
1706 ln = Lst_Member(openDirectories, p);
1707 Lst_Remove(openDirectories, ln);
1708
1709 Hash_DeleteTable(&p->files);
1710 free(p->name);
1711 free(p);
1712 }
1713 }
1714
1715 /*-
1716 *-----------------------------------------------------------------------
1717 * Dir_ClearPath --
1718 * Clear out all elements of the given search path. This is different
1719 * from destroying the list, notice.
1720 *
1721 * Input:
1722 * path Path to clear
1723 *
1724 * Results:
1725 * None.
1726 *
1727 * Side Effects:
1728 * The path is set to the empty list.
1729 *
1730 *-----------------------------------------------------------------------
1731 */
1732 void
1733 Dir_ClearPath(Lst path)
1734 {
1735 while (!Lst_IsEmpty(path)) {
1736 Path *p = Lst_Dequeue(path);
1737 Dir_Destroy(p);
1738 }
1739 }
1740
1741
1742 /*-
1743 *-----------------------------------------------------------------------
1744 * Dir_Concat --
1745 * Concatenate two paths, adding the second to the end of the first.
1746 * Makes sure to avoid duplicates.
1747 *
1748 * Input:
1749 * path1 Dest
1750 * path2 Source
1751 *
1752 * Results:
1753 * None
1754 *
1755 * Side Effects:
1756 * Reference counts for added dirs are upped.
1757 *
1758 *-----------------------------------------------------------------------
1759 */
1760 void
1761 Dir_Concat(Lst path1, Lst path2)
1762 {
1763 LstNode ln;
1764 Path *p;
1765
1766 for (ln = Lst_First(path2); ln != NULL; ln = Lst_Succ(ln)) {
1767 p = Lst_Datum(ln);
1768 if (Lst_Member(path1, p) == NULL) {
1769 p->refCount += 1;
1770 Lst_Append(path1, p);
1771 }
1772 }
1773 }
1774
1775 static int
1776 percentage(int num, int den)
1777 {
1778 return den != 0 ? num * 100 / den : 0;
1779 }
1780
1781 /********** DEBUG INFO **********/
1782 void
1783 Dir_PrintDirectories(void)
1784 {
1785 LstNode ln;
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
1794 Lst_Open(openDirectories);
1795 while ((ln = Lst_Next(openDirectories)) != NULL) {
1796 Path *p = Lst_Datum(ln);
1797 fprintf(debug_file, "# %-20s %10d\t%4d\n", p->name, p->refCount,
1798 p->hits);
1799 }
1800 Lst_Close(openDirectories);
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