xref: /freebsd/contrib/bmake/meta.c (revision d30a1689f5b37e78ea189232a8b94a7011dc0dc8)
1 /*      $NetBSD: meta.c,v 1.200 2022/04/15 12:28:16 rillig Exp $ */
2 
3 /*
4  * Implement 'meta' mode.
5  * Adapted from John Birrell's patches to FreeBSD make.
6  * --sjg
7  */
8 /*
9  * Copyright (c) 2009-2016, Juniper Networks, Inc.
10  * Portions Copyright (c) 2009, John Birrell.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 #if defined(USE_META)
34 
35 #ifdef HAVE_CONFIG_H
36 # include "config.h"
37 #endif
38 #include <sys/stat.h>
39 #ifdef HAVE_LIBGEN_H
40 #include <libgen.h>
41 #elif !defined(HAVE_DIRNAME)
42 char * dirname(char *);
43 #endif
44 #include <errno.h>
45 #if !defined(HAVE_CONFIG_H) || defined(HAVE_ERR_H)
46 #include <err.h>
47 #endif
48 
49 #include "make.h"
50 #include "dir.h"
51 #include "job.h"
52 
53 #ifdef USE_FILEMON
54 #include "filemon/filemon.h"
55 #endif
56 
57 static BuildMon Mybm;			/* for compat */
58 static StringList metaBailiwick = LST_INIT; /* our scope of control */
59 static char *metaBailiwickStr;		/* string storage for the list */
60 static StringList metaIgnorePaths = LST_INIT; /* paths we deliberately ignore */
61 static char *metaIgnorePathsStr;	/* string storage for the list */
62 
63 #ifndef MAKE_META_IGNORE_PATHS
64 #define MAKE_META_IGNORE_PATHS ".MAKE.META.IGNORE_PATHS"
65 #endif
66 #ifndef MAKE_META_IGNORE_PATTERNS
67 #define MAKE_META_IGNORE_PATTERNS ".MAKE.META.IGNORE_PATTERNS"
68 #endif
69 #ifndef MAKE_META_IGNORE_FILTER
70 #define MAKE_META_IGNORE_FILTER ".MAKE.META.IGNORE_FILTER"
71 #endif
72 #ifndef MAKE_META_CMP_FILTER
73 #define MAKE_META_CMP_FILTER ".MAKE.META.CMP_FILTER"
74 #endif
75 
76 bool useMeta = false;
77 static bool useFilemon = false;
78 static bool writeMeta = false;
79 static bool metaMissing = false;	/* oodate if missing */
80 static bool filemonMissing = false;	/* oodate if missing */
81 static bool metaEnv = false;		/* don't save env unless asked */
82 static bool metaVerbose = false;
83 static bool metaIgnoreCMDs = false;	/* ignore CMDs in .meta files */
84 static bool metaIgnorePatterns = false; /* do we need to do pattern matches */
85 static bool metaIgnoreFilter = false;	/* do we have more complex filtering? */
86 static bool metaCmpFilter = false;	/* do we have CMP_FILTER ? */
87 static bool metaCurdirOk = false;	/* write .meta in .CURDIR Ok? */
88 static bool metaSilent = false;		/* if we have a .meta be SILENT */
89 
90 extern bool forceJobs;
91 extern char    **environ;
92 
93 #define MAKE_META_PREFIX	".MAKE.META.PREFIX"
94 
95 #ifndef N2U
96 # define N2U(n, u)   (((n) + ((u) - 1)) / (u))
97 #endif
98 #ifndef ROUNDUP
99 # define ROUNDUP(n, u)   (N2U((n), (u)) * (u))
100 #endif
101 
102 #if !defined(HAVE_STRSEP)
103 # define strsep(s, d) stresep((s), (d), '\0')
104 #endif
105 #if !defined(HAVE_STRESEP)
106 char * stresep(char **, const char *, int);
107 #endif
108 
109 /*
110  * Filemon is a kernel module which snoops certain syscalls.
111  *
112  * C chdir
113  * E exec
114  * F [v]fork
115  * L [sym]link
116  * M rename
117  * R read
118  * W write
119  * S stat
120  *
121  * See meta_oodate below - we mainly care about 'E' and 'R'.
122  *
123  * We can still use meta mode without filemon, but
124  * the benefits are more limited.
125  */
126 #ifdef USE_FILEMON
127 
128 /*
129  * Open the filemon device.
130  */
131 static void
132 meta_open_filemon(BuildMon *pbm)
133 {
134     int dupfd;
135 
136     pbm->mon_fd = -1;
137     pbm->filemon = NULL;
138     if (!useFilemon || pbm->mfp == NULL)
139 	return;
140 
141     pbm->filemon = filemon_open();
142     if (pbm->filemon == NULL) {
143 	useFilemon = false;
144 	warn("Could not open filemon %s", filemon_path());
145 	return;
146     }
147 
148     /*
149      * We use a file outside of '.'
150      * to avoid a FreeBSD kernel bug where unlink invalidates
151      * cwd causing getcwd to do a lot more work.
152      * We only care about the descriptor.
153      */
154     if (!opts.compatMake)
155 	pbm->mon_fd = Job_TempFile("filemon.XXXXXX", NULL, 0);
156     else
157 	pbm->mon_fd = mkTempFile("filemon.XXXXXX", NULL, 0);
158     if ((dupfd = dup(pbm->mon_fd)) == -1) {
159 	Punt("Could not dup filemon output: %s", strerror(errno));
160     }
161     (void)fcntl(dupfd, F_SETFD, FD_CLOEXEC);
162     if (filemon_setfd(pbm->filemon, dupfd) == -1) {
163 	Punt("Could not set filemon file descriptor: %s", strerror(errno));
164     }
165     /* we don't need these once we exec */
166     (void)fcntl(pbm->mon_fd, F_SETFD, FD_CLOEXEC);
167 }
168 
169 /*
170  * Read the build monitor output file and write records to the target's
171  * metadata file.
172  */
173 static int
174 filemon_read(FILE *mfp, int fd)
175 {
176     char buf[BUFSIZ];
177     int error;
178 
179     /* Check if we're not writing to a meta data file.*/
180     if (mfp == NULL) {
181 	if (fd >= 0)
182 	    close(fd);			/* not interested */
183 	return 0;
184     }
185     /* rewind */
186     if (lseek(fd, (off_t)0, SEEK_SET) < 0) {
187 	error = errno;
188 	warn("Could not rewind filemon");
189 	fprintf(mfp, "\n");
190     } else {
191 	ssize_t n;
192 
193 	error = 0;
194 	fprintf(mfp, "\n-- filemon acquired metadata --\n");
195 
196 	while ((n = read(fd, buf, sizeof buf)) > 0) {
197 	    if ((ssize_t)fwrite(buf, 1, (size_t)n, mfp) < n)
198 		error = EIO;
199 	}
200     }
201     if (fflush(mfp) != 0)
202 	Punt("Cannot write filemon data to meta file: %s",
203 	    strerror(errno));
204     if (close(fd) < 0)
205 	error = errno;
206     return error;
207 }
208 #endif
209 
210 /*
211  * when realpath() fails,
212  * we use this, to clean up ./ and ../
213  */
214 static void
215 eat_dots(char *buf)
216 {
217     char *p;
218 
219     while ((p = strstr(buf, "/./")) != NULL)
220 	memmove(p, p + 2, strlen(p + 2) + 1);
221 
222     while ((p = strstr(buf, "/../")) != NULL) {
223 	char *p2 = p + 3;
224 	if (p > buf) {
225 	    do {
226 		p--;
227 	    } while (p > buf && *p != '/');
228 	}
229 	if (*p == '/')
230 	    memmove(p, p2, strlen(p2) + 1);
231 	else
232 	    return;		/* can't happen? */
233     }
234 }
235 
236 static char *
237 meta_name(char *mname, size_t mnamelen,
238 	  const char *dname,
239 	  const char *tname,
240 	  const char *cwd)
241 {
242     char buf[MAXPATHLEN];
243     char *rp, *cp;
244     const char *tname_base;
245     char *tp;
246     char *dtp;
247     size_t ldname;
248 
249     /*
250      * Weed out relative paths from the target file name.
251      * We have to be careful though since if target is a
252      * symlink, the result will be unstable.
253      * So we use realpath() just to get the dirname, and leave the
254      * basename as given to us.
255      */
256     if ((tname_base = strrchr(tname, '/')) != NULL) {
257 	if (cached_realpath(tname, buf) != NULL) {
258 	    if ((rp = strrchr(buf, '/')) != NULL) {
259 		rp++;
260 		tname_base++;
261 		if (strcmp(tname_base, rp) != 0)
262 		    strlcpy(rp, tname_base, sizeof buf - (size_t)(rp - buf));
263 	    }
264 	    tname = buf;
265 	} else {
266 	    /*
267 	     * We likely have a directory which is about to be made.
268 	     * We pretend realpath() succeeded, to have a chance
269 	     * of generating the same meta file name that we will
270 	     * next time through.
271 	     */
272 	    if (tname[0] == '/') {
273 		strlcpy(buf, tname, sizeof buf);
274 	    } else {
275 		snprintf(buf, sizeof buf, "%s/%s", cwd, tname);
276 	    }
277 	    eat_dots(buf);
278 	    tname = buf;
279 	}
280     }
281     /* on some systems dirname may modify its arg */
282     tp = bmake_strdup(tname);
283     dtp = dirname(tp);
284     if (strcmp(dname, dtp) == 0)
285 	snprintf(mname, mnamelen, "%s.meta", tname);
286     else {
287 	ldname = strlen(dname);
288 	if (strncmp(dname, dtp, ldname) == 0 && dtp[ldname] == '/')
289 	    snprintf(mname, mnamelen, "%s/%s.meta", dname, &tname[ldname+1]);
290 	else
291 	    snprintf(mname, mnamelen, "%s/%s.meta", dname, tname);
292 
293 	/*
294 	 * Replace path separators in the file name after the
295 	 * current object directory path.
296 	 */
297 	cp = mname + strlen(dname) + 1;
298 
299 	while (*cp != '\0') {
300 	    if (*cp == '/')
301 		*cp = '_';
302 	    cp++;
303 	}
304     }
305     free(tp);
306     return mname;
307 }
308 
309 /*
310  * Return true if running ${.MAKE}
311  * Bypassed if target is flagged .MAKE
312  */
313 static bool
314 is_submake(const char *cmd, GNode *gn)
315 {
316     static const char *p_make = NULL;
317     static size_t p_len;
318     char *mp = NULL;
319     const char *cp2;
320     bool rc = false;
321 
322     if (p_make == NULL) {
323 	p_make = Var_Value(gn, ".MAKE").str;
324 	p_len = strlen(p_make);
325     }
326     if (strchr(cmd, '$') != NULL) {
327 	(void)Var_Subst(cmd, gn, VARE_WANTRES, &mp);
328 	/* TODO: handle errors */
329 	cmd = mp;
330     }
331     cp2 = strstr(cmd, p_make);
332     if (cp2 != NULL) {
333 	switch (cp2[p_len]) {
334 	case '\0':
335 	case ' ':
336 	case '\t':
337 	case '\n':
338 	    rc = true;
339 	    break;
340 	}
341 	if (cp2 > cmd && rc) {
342 	    switch (cp2[-1]) {
343 	    case ' ':
344 	    case '\t':
345 	    case '\n':
346 		break;
347 	    default:
348 		rc = false;		/* no match */
349 		break;
350 	    }
351 	}
352     }
353     free(mp);
354     return rc;
355 }
356 
357 static bool
358 any_is_submake(GNode *gn)
359 {
360     StringListNode *ln;
361 
362     for (ln = gn->commands.first; ln != NULL; ln = ln->next)
363 	if (is_submake(ln->datum, gn))
364 	    return true;
365     return false;
366 }
367 
368 static void
369 printCMD(const char *ucmd, FILE *fp, GNode *gn)
370 {
371     FStr xcmd = FStr_InitRefer(ucmd);
372 
373     Var_Expand(&xcmd, gn, VARE_WANTRES);
374     fprintf(fp, "CMD %s\n", xcmd.str);
375     FStr_Done(&xcmd);
376 }
377 
378 static void
379 printCMDs(GNode *gn, FILE *fp)
380 {
381     StringListNode *ln;
382 
383     for (ln = gn->commands.first; ln != NULL; ln = ln->next)
384 	printCMD(ln->datum, fp, gn);
385 }
386 
387 /*
388  * Certain node types never get a .meta file
389  */
390 #define SKIP_META_TYPE(flag, str) do { \
391     if ((gn->type & (flag))) { \
392 	if (verbose) \
393 	    debug_printf("Skipping meta for %s: .%s\n", gn->name, str); \
394 	return false; \
395     } \
396 } while (false)
397 
398 
399 /*
400  * Do we need/want a .meta file ?
401  */
402 static bool
403 meta_needed(GNode *gn, const char *dname,
404 	    char *objdir_realpath, bool verbose)
405 {
406     struct cached_stat cst;
407 
408     if (verbose)
409 	verbose = DEBUG(META);
410 
411     /* This may be a phony node which we don't want meta data for... */
412     /* Skip .meta for .BEGIN, .END, .ERROR etc as well. */
413     /* Or it may be explicitly flagged as .NOMETA */
414     SKIP_META_TYPE(OP_NOMETA, "NOMETA");
415     /* Unless it is explicitly flagged as .META */
416     if (!(gn->type & OP_META)) {
417 	SKIP_META_TYPE(OP_PHONY, "PHONY");
418 	SKIP_META_TYPE(OP_SPECIAL, "SPECIAL");
419 	SKIP_META_TYPE(OP_MAKE, "MAKE");
420     }
421 
422     /* Check if there are no commands to execute. */
423     if (Lst_IsEmpty(&gn->commands)) {
424 	if (verbose)
425 	    debug_printf("Skipping meta for %s: no commands\n", gn->name);
426 	return false;
427     }
428     if ((gn->type & (OP_META|OP_SUBMAKE)) == OP_SUBMAKE) {
429 	/* OP_SUBMAKE is a bit too aggressive */
430 	if (any_is_submake(gn)) {
431 	    DEBUG1(META, "Skipping meta for %s: .SUBMAKE\n", gn->name);
432 	    return false;
433 	}
434     }
435 
436     /* The object directory may not exist. Check it.. */
437     if (cached_stat(dname, &cst) != 0) {
438 	if (verbose)
439 	    debug_printf("Skipping meta for %s: no .OBJDIR\n", gn->name);
440 	return false;
441     }
442 
443     /* make sure these are canonical */
444     if (cached_realpath(dname, objdir_realpath) != NULL)
445 	dname = objdir_realpath;
446 
447     /* If we aren't in the object directory, don't create a meta file. */
448     if (!metaCurdirOk && strcmp(curdir, dname) == 0) {
449 	if (verbose)
450 	    debug_printf("Skipping meta for %s: .OBJDIR == .CURDIR\n",
451 			 gn->name);
452 	return false;
453     }
454     return true;
455 }
456 
457 
458 static FILE *
459 meta_create(BuildMon *pbm, GNode *gn)
460 {
461     FILE *fp;
462     char buf[MAXPATHLEN];
463     char objdir_realpath[MAXPATHLEN];
464     char **ptr;
465     FStr dname;
466     const char *tname;
467     char *fname;
468     const char *cp;
469 
470     fp = NULL;
471 
472     dname = Var_Value(gn, ".OBJDIR");
473     tname = GNode_VarTarget(gn);
474 
475     /* if this succeeds objdir_realpath is realpath of dname */
476     if (!meta_needed(gn, dname.str, objdir_realpath, true))
477 	goto out;
478     dname.str = objdir_realpath;
479 
480     if (metaVerbose) {
481 	char *mp;
482 
483 	/* Describe the target we are building */
484 	(void)Var_Subst("${" MAKE_META_PREFIX "}", gn, VARE_WANTRES, &mp);
485 	/* TODO: handle errors */
486 	if (mp[0] != '\0')
487 	    fprintf(stdout, "%s\n", mp);
488 	free(mp);
489     }
490     /* Get the basename of the target */
491     cp = str_basename(tname);
492 
493     fflush(stdout);
494 
495     if (!writeMeta)
496 	/* Don't create meta data. */
497 	goto out;
498 
499     fname = meta_name(pbm->meta_fname, sizeof pbm->meta_fname,
500 		      dname.str, tname, objdir_realpath);
501 
502 #ifdef DEBUG_META_MODE
503     DEBUG1(META, "meta_create: %s\n", fname);
504 #endif
505 
506     if ((fp = fopen(fname, "w")) == NULL)
507 	Punt("Could not open meta file '%s': %s", fname, strerror(errno));
508 
509     fprintf(fp, "# Meta data file %s\n", fname);
510 
511     printCMDs(gn, fp);
512 
513     fprintf(fp, "CWD %s\n", getcwd(buf, sizeof buf));
514     fprintf(fp, "TARGET %s\n", tname);
515     cp = GNode_VarOodate(gn);
516     if (cp != NULL && *cp != '\0') {
517 	fprintf(fp, "OODATE %s\n", cp);
518     }
519     if (metaEnv) {
520 	for (ptr = environ; *ptr != NULL; ptr++)
521 	    fprintf(fp, "ENV %s\n", *ptr);
522     }
523 
524     fprintf(fp, "-- command output --\n");
525     if (fflush(fp) != 0)
526 	Punt("Cannot write expanded command to meta file: %s",
527 	    strerror(errno));
528 
529     Global_Append(".MAKE.META.FILES", fname);
530     Global_Append(".MAKE.META.CREATED", fname);
531 
532     gn->type |= OP_META;		/* in case anyone wants to know */
533     if (metaSilent) {
534 	    gn->type |= OP_SILENT;
535     }
536  out:
537     FStr_Done(&dname);
538 
539     return fp;
540 }
541 
542 static bool
543 boolValue(const char *s)
544 {
545     switch (*s) {
546     case '0':
547     case 'N':
548     case 'n':
549     case 'F':
550     case 'f':
551 	return false;
552     }
553     return true;
554 }
555 
556 /*
557  * Initialization we need before reading makefiles.
558  */
559 void
560 meta_init(void)
561 {
562 #ifdef USE_FILEMON
563 	/* this allows makefiles to test if we have filemon support */
564 	Global_Set(".MAKE.PATH_FILEMON", filemon_path());
565 #endif
566 }
567 
568 
569 #define get_mode_bf(bf, token) \
570     if ((cp = strstr(make_mode, token)) != NULL) \
571 	bf = boolValue(cp + sizeof (token) - 1)
572 
573 /*
574  * Initialization we need after reading makefiles.
575  */
576 void
577 meta_mode_init(const char *make_mode)
578 {
579     static bool once = false;
580     const char *cp;
581 
582     useMeta = true;
583     useFilemon = true;
584     writeMeta = true;
585 
586     if (make_mode != NULL) {
587 	if (strstr(make_mode, "env") != NULL)
588 	    metaEnv = true;
589 	if (strstr(make_mode, "verb") != NULL)
590 	    metaVerbose = true;
591 	if (strstr(make_mode, "read") != NULL)
592 	    writeMeta = false;
593 	if (strstr(make_mode, "nofilemon") != NULL)
594 	    useFilemon = false;
595 	if (strstr(make_mode, "ignore-cmd") != NULL)
596 	    metaIgnoreCMDs = true;
597 	if (useFilemon)
598 	    get_mode_bf(filemonMissing, "missing-filemon=");
599 	get_mode_bf(metaCurdirOk, "curdirok=");
600 	get_mode_bf(metaMissing, "missing-meta=");
601 	get_mode_bf(metaSilent, "silent=");
602     }
603     if (metaVerbose && !Var_Exists(SCOPE_GLOBAL, MAKE_META_PREFIX)) {
604 	/*
605 	 * The default value for MAKE_META_PREFIX
606 	 * prints the absolute path of the target.
607 	 * This works be cause :H will generate '.' if there is no /
608 	 * and :tA will resolve that to cwd.
609 	 */
610 	Global_Set(MAKE_META_PREFIX,
611 	    "Building ${.TARGET:H:tA}/${.TARGET:T}");
612     }
613     if (once)
614 	return;
615     once = true;
616     memset(&Mybm, 0, sizeof Mybm);
617     /*
618      * We consider ourselves master of all within ${.MAKE.META.BAILIWICK}
619      */
620     (void)Var_Subst("${.MAKE.META.BAILIWICK:O:u:tA}",
621 		    SCOPE_GLOBAL, VARE_WANTRES, &metaBailiwickStr);
622     /* TODO: handle errors */
623     str2Lst_Append(&metaBailiwick, metaBailiwickStr);
624     /*
625      * We ignore any paths that start with ${.MAKE.META.IGNORE_PATHS}
626      */
627     Global_Append(MAKE_META_IGNORE_PATHS,
628 	       "/dev /etc /proc /tmp /var/run /var/tmp ${TMPDIR}");
629     (void)Var_Subst("${" MAKE_META_IGNORE_PATHS ":O:u:tA}",
630 		    SCOPE_GLOBAL, VARE_WANTRES, &metaIgnorePathsStr);
631     /* TODO: handle errors */
632     str2Lst_Append(&metaIgnorePaths, metaIgnorePathsStr);
633 
634     /*
635      * We ignore any paths that match ${.MAKE.META.IGNORE_PATTERNS}
636      */
637     metaIgnorePatterns = Var_Exists(SCOPE_GLOBAL, MAKE_META_IGNORE_PATTERNS);
638     metaIgnoreFilter = Var_Exists(SCOPE_GLOBAL, MAKE_META_IGNORE_FILTER);
639     metaCmpFilter = Var_Exists(SCOPE_GLOBAL, MAKE_META_CMP_FILTER);
640 }
641 
642 /*
643  * In each case below we allow for job==NULL
644  */
645 void
646 meta_job_start(Job *job, GNode *gn)
647 {
648     BuildMon *pbm;
649 
650     if (job != NULL) {
651 	pbm = &job->bm;
652     } else {
653 	pbm = &Mybm;
654     }
655     pbm->mfp = meta_create(pbm, gn);
656 #ifdef USE_FILEMON_ONCE
657     /* compat mode we open the filemon dev once per command */
658     if (job == NULL)
659 	return;
660 #endif
661 #ifdef USE_FILEMON
662     if (pbm->mfp != NULL && useFilemon) {
663 	meta_open_filemon(pbm);
664     } else {
665 	pbm->mon_fd = -1;
666 	pbm->filemon = NULL;
667     }
668 #endif
669 }
670 
671 /*
672  * The child calls this before doing anything.
673  * It does not disturb our state.
674  */
675 void
676 meta_job_child(Job *job MAKE_ATTR_UNUSED)
677 {
678 #ifdef USE_FILEMON
679     BuildMon *pbm;
680 
681     if (job != NULL) {
682 	pbm = &job->bm;
683     } else {
684 	pbm = &Mybm;
685     }
686     if (pbm->mfp != NULL) {
687 	close(fileno(pbm->mfp));
688 	if (useFilemon && pbm->filemon != NULL) {
689 	    pid_t pid;
690 
691 	    pid = getpid();
692 	    if (filemon_setpid_child(pbm->filemon, pid) == -1) {
693 		Punt("Could not set filemon pid: %s", strerror(errno));
694 	    }
695 	}
696     }
697 #endif
698 }
699 
700 void
701 meta_job_parent(Job *job MAKE_ATTR_UNUSED, pid_t pid MAKE_ATTR_UNUSED)
702 {
703 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
704     BuildMon *pbm;
705 
706     if (job != NULL) {
707 	pbm = &job->bm;
708     } else {
709 	pbm = &Mybm;
710     }
711     if (useFilemon && pbm->filemon != NULL) {
712 	filemon_setpid_parent(pbm->filemon, pid);
713     }
714 #endif
715 }
716 
717 int
718 meta_job_fd(Job *job MAKE_ATTR_UNUSED)
719 {
720 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
721     BuildMon *pbm;
722 
723     if (job != NULL) {
724 	pbm = &job->bm;
725     } else {
726 	pbm = &Mybm;
727     }
728     if (useFilemon && pbm->filemon != NULL) {
729 	return filemon_readfd(pbm->filemon);
730     }
731 #endif
732     return -1;
733 }
734 
735 int
736 meta_job_event(Job *job MAKE_ATTR_UNUSED)
737 {
738 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
739     BuildMon *pbm;
740 
741     if (job != NULL) {
742 	pbm = &job->bm;
743     } else {
744 	pbm = &Mybm;
745     }
746     if (useFilemon && pbm->filemon != NULL) {
747 	return filemon_process(pbm->filemon);
748     }
749 #endif
750     return 0;
751 }
752 
753 void
754 meta_job_error(Job *job, GNode *gn, bool ignerr, int status)
755 {
756     char cwd[MAXPATHLEN];
757     BuildMon *pbm;
758 
759     if (job != NULL) {
760 	pbm = &job->bm;
761 	if (gn == NULL)
762 	    gn = job->node;
763     } else {
764 	pbm = &Mybm;
765     }
766     if (pbm->mfp != NULL) {
767 	fprintf(pbm->mfp, "\n*** Error code %d%s\n",
768 		status, ignerr ? "(ignored)" : "");
769     }
770     if (gn != NULL)
771 	Global_Set(".ERROR_TARGET", GNode_Path(gn));
772     getcwd(cwd, sizeof cwd);
773     Global_Set(".ERROR_CWD", cwd);
774     if (pbm->meta_fname[0] != '\0') {
775 	Global_Set(".ERROR_META_FILE", pbm->meta_fname);
776     }
777     meta_job_finish(job);
778 }
779 
780 void
781 meta_job_output(Job *job, char *cp, const char *nl)
782 {
783     BuildMon *pbm;
784 
785     if (job != NULL) {
786 	pbm = &job->bm;
787     } else {
788 	pbm = &Mybm;
789     }
790     if (pbm->mfp != NULL) {
791 	if (metaVerbose) {
792 	    static char *meta_prefix = NULL;
793 	    static size_t meta_prefix_len;
794 
795 	    if (meta_prefix == NULL) {
796 		char *cp2;
797 
798 		(void)Var_Subst("${" MAKE_META_PREFIX "}",
799 				SCOPE_GLOBAL, VARE_WANTRES, &meta_prefix);
800 		/* TODO: handle errors */
801 		if ((cp2 = strchr(meta_prefix, '$')) != NULL)
802 		    meta_prefix_len = (size_t)(cp2 - meta_prefix);
803 		else
804 		    meta_prefix_len = strlen(meta_prefix);
805 	    }
806 	    if (strncmp(cp, meta_prefix, meta_prefix_len) == 0) {
807 		cp = strchr(cp + 1, '\n');
808 		if (cp == NULL)
809 		    return;
810 		cp++;
811 	    }
812 	}
813 	fprintf(pbm->mfp, "%s%s", cp, nl);
814     }
815 }
816 
817 int
818 meta_cmd_finish(void *pbmp)
819 {
820     int error = 0;
821     BuildMon *pbm = pbmp;
822 #ifdef USE_FILEMON
823     int x;
824 #endif
825 
826     if (pbm == NULL)
827 	pbm = &Mybm;
828 
829 #ifdef USE_FILEMON
830     if (pbm->filemon != NULL) {
831 	while (filemon_process(pbm->filemon) > 0)
832 	    continue;
833 	if (filemon_close(pbm->filemon) == -1) {
834 	    error = errno;
835 	    Punt("filemon failed: %s", strerror(errno));
836 	}
837 	x = filemon_read(pbm->mfp, pbm->mon_fd);
838 	if (error == 0 && x != 0)
839 	    error = x;
840 	pbm->mon_fd = -1;
841 	pbm->filemon = NULL;
842 	return error;
843     }
844 #endif
845 
846     fprintf(pbm->mfp, "\n");	/* ensure end with newline */
847     return error;
848 }
849 
850 int
851 meta_job_finish(Job *job)
852 {
853     BuildMon *pbm;
854     int error = 0;
855     int x;
856 
857     if (job != NULL) {
858 	pbm = &job->bm;
859     } else {
860 	pbm = &Mybm;
861     }
862     if (pbm->mfp != NULL) {
863 	error = meta_cmd_finish(pbm);
864 	x = fclose(pbm->mfp);
865 	if (error == 0 && x != 0)
866 	    error = errno;
867 	pbm->mfp = NULL;
868 	pbm->meta_fname[0] = '\0';
869     }
870     return error;
871 }
872 
873 void
874 meta_finish(void)
875 {
876     Lst_Done(&metaBailiwick);
877     free(metaBailiwickStr);
878     Lst_Done(&metaIgnorePaths);
879     free(metaIgnorePathsStr);
880 }
881 
882 /*
883  * Fetch a full line from fp - growing bufp if needed
884  * Return length in bufp.
885  */
886 static int
887 fgetLine(char **bufp, size_t *szp, int o, FILE *fp)
888 {
889     char *buf = *bufp;
890     size_t bufsz = *szp;
891     struct stat fs;
892     int x;
893 
894     if (fgets(&buf[o], (int)bufsz - o, fp) != NULL) {
895     check_newline:
896 	x = o + (int)strlen(&buf[o]);
897 	if (buf[x - 1] == '\n')
898 	    return x;
899 	/*
900 	 * We need to grow the buffer.
901 	 * The meta file can give us a clue.
902 	 */
903 	if (fstat(fileno(fp), &fs) == 0) {
904 	    size_t newsz;
905 	    char *p;
906 
907 	    newsz = ROUNDUP(((size_t)fs.st_size / 2), BUFSIZ);
908 	    if (newsz <= bufsz)
909 		newsz = ROUNDUP((size_t)fs.st_size, BUFSIZ);
910 	    if (newsz <= bufsz)
911 		return x;		/* truncated */
912 	    DEBUG2(META, "growing buffer %u -> %u\n",
913 		   (unsigned)bufsz, (unsigned)newsz);
914 	    p = bmake_realloc(buf, newsz);
915 	    *bufp = buf = p;
916 	    *szp = bufsz = newsz;
917 	    /* fetch the rest */
918 	    if (fgets(&buf[x], (int)bufsz - x, fp) == NULL)
919 		return x;		/* truncated! */
920 	    goto check_newline;
921 	}
922     }
923     return 0;
924 }
925 
926 static bool
927 prefix_match(const char *prefix, const char *path)
928 {
929     size_t n = strlen(prefix);
930 
931     return strncmp(path, prefix, n) == 0;
932 }
933 
934 static bool
935 has_any_prefix(const char *path, StringList *prefixes)
936 {
937     StringListNode *ln;
938 
939     for (ln = prefixes->first; ln != NULL; ln = ln->next)
940 	if (prefix_match(ln->datum, path))
941 	    return true;
942     return false;
943 }
944 
945 /* See if the path equals prefix or starts with "prefix/". */
946 static bool
947 path_starts_with(const char *path, const char *prefix)
948 {
949     size_t n = strlen(prefix);
950 
951     if (strncmp(path, prefix, n) != 0)
952 	return false;
953     return path[n] == '\0' || path[n] == '/';
954 }
955 
956 static bool
957 meta_ignore(GNode *gn, const char *p)
958 {
959     char fname[MAXPATHLEN];
960 
961     if (p == NULL)
962 	return true;
963 
964     if (*p == '/') {
965 	cached_realpath(p, fname); /* clean it up */
966 	if (has_any_prefix(fname, &metaIgnorePaths)) {
967 #ifdef DEBUG_META_MODE
968 	    DEBUG1(META, "meta_oodate: ignoring path: %s\n", p);
969 #endif
970 	    return true;
971 	}
972     }
973 
974     if (metaIgnorePatterns) {
975 	const char *expr;
976 	char *pm;
977 
978 	/*
979 	 * XXX: This variable is set on a target GNode but is not one of
980 	 * the usual local variables.  It should be deleted afterwards.
981 	 * Ideally it would not be created in the first place, just like
982 	 * in a .for loop.
983 	 */
984 	Var_Set(gn, ".p.", p);
985 	expr = "${" MAKE_META_IGNORE_PATTERNS ":@m@${.p.:M$m}@}";
986 	(void)Var_Subst(expr, gn, VARE_WANTRES, &pm);
987 	/* TODO: handle errors */
988 	if (pm[0] != '\0') {
989 #ifdef DEBUG_META_MODE
990 	    DEBUG1(META, "meta_oodate: ignoring pattern: %s\n", p);
991 #endif
992 	    free(pm);
993 	    return true;
994 	}
995 	free(pm);
996     }
997 
998     if (metaIgnoreFilter) {
999 	char *fm;
1000 
1001 	/* skip if filter result is empty */
1002 	snprintf(fname, sizeof fname,
1003 		 "${%s:L:${%s:ts:}}",
1004 		 p, MAKE_META_IGNORE_FILTER);
1005 	(void)Var_Subst(fname, gn, VARE_WANTRES, &fm);
1006 	/* TODO: handle errors */
1007 	if (*fm == '\0') {
1008 #ifdef DEBUG_META_MODE
1009 	    DEBUG1(META, "meta_oodate: ignoring filtered: %s\n", p);
1010 #endif
1011 	    free(fm);
1012 	    return true;
1013 	}
1014 	free(fm);
1015     }
1016     return false;
1017 }
1018 
1019 /*
1020  * When running with 'meta' functionality, a target can be out-of-date
1021  * if any of the references in its meta data file is more recent.
1022  * We have to track the latestdir on a per-process basis.
1023  */
1024 #define LCWD_VNAME_FMT ".meta.%d.lcwd"
1025 #define LDIR_VNAME_FMT ".meta.%d.ldir"
1026 
1027 /*
1028  * It is possible that a .meta file is corrupted,
1029  * if we detect this we want to reproduce it.
1030  * Setting oodate true will have that effect.
1031  */
1032 #define CHECK_VALID_META(p) if (!(p != NULL && *p != '\0')) { \
1033     warnx("%s: %u: malformed", fname, lineno); \
1034     oodate = true; \
1035     continue; \
1036     }
1037 
1038 #define DEQUOTE(p) if (*p == '\'') {	\
1039     char *ep; \
1040     p++; \
1041     if ((ep = strchr(p, '\'')) != NULL) \
1042 	*ep = '\0'; \
1043     }
1044 
1045 static void
1046 append_if_new(StringList *list, const char *str)
1047 {
1048     StringListNode *ln;
1049 
1050     for (ln = list->first; ln != NULL; ln = ln->next)
1051 	if (strcmp(ln->datum, str) == 0)
1052 	    return;
1053     Lst_Append(list, bmake_strdup(str));
1054 }
1055 
1056 /* A "reserved" variable to store the command to be filtered */
1057 #define META_CMD_FILTER_VAR ".MAKE.cmd_filtered"
1058 
1059 static char *
1060 meta_filter_cmd(GNode *gn, char *s)
1061 {
1062     Var_Set(gn, META_CMD_FILTER_VAR, s);
1063     Var_Subst("${" META_CMD_FILTER_VAR ":${" MAKE_META_CMP_FILTER ":ts:}}", gn, VARE_WANTRES, &s);
1064     return s;
1065 }
1066 
1067 static int
1068 meta_cmd_cmp(GNode *gn, char *a, char *b, bool filter)
1069 {
1070     int rc;
1071 
1072     rc = strcmp(a, b);
1073     if (rc == 0 || !filter)
1074 	return rc;
1075     a = meta_filter_cmd(gn, a);
1076     b = meta_filter_cmd(gn, b);
1077     rc = strcmp(a, b);
1078     free(a);
1079     free(b);
1080     Var_Delete(gn, META_CMD_FILTER_VAR);
1081     return rc;
1082 }
1083 
1084 bool
1085 meta_oodate(GNode *gn, bool oodate)
1086 {
1087     static char *tmpdir = NULL;
1088     static char cwd[MAXPATHLEN];
1089     char lcwd_vname[64];
1090     char ldir_vname[64];
1091     char lcwd[MAXPATHLEN];
1092     char latestdir[MAXPATHLEN];
1093     char fname[MAXPATHLEN];
1094     char fname1[MAXPATHLEN];
1095     char fname2[MAXPATHLEN];
1096     char fname3[MAXPATHLEN];
1097     FStr dname;
1098     const char *tname;
1099     char *p;
1100     char *link_src;
1101     char *move_target;
1102     static size_t cwdlen = 0;
1103     static size_t tmplen = 0;
1104     FILE *fp;
1105     bool needOODATE = false;
1106     StringList missingFiles;
1107     bool have_filemon = false;
1108     bool cmp_filter;
1109 
1110     if (oodate)
1111 	return oodate;		/* we're done */
1112 
1113     dname = Var_Value(gn, ".OBJDIR");
1114     tname = GNode_VarTarget(gn);
1115 
1116     /* if this succeeds fname3 is realpath of dname */
1117     if (!meta_needed(gn, dname.str, fname3, false))
1118 	goto oodate_out;
1119     dname.str = fname3;
1120 
1121     Lst_Init(&missingFiles);
1122 
1123     /*
1124      * We need to check if the target is out-of-date. This includes
1125      * checking if the expanded command has changed. This in turn
1126      * requires that all variables are set in the same way that they
1127      * would be if the target needs to be re-built.
1128      */
1129     GNode_SetLocalVars(gn);
1130 
1131     meta_name(fname, sizeof fname, dname.str, tname, dname.str);
1132 
1133 #ifdef DEBUG_META_MODE
1134     DEBUG1(META, "meta_oodate: %s\n", fname);
1135 #endif
1136 
1137     if ((fp = fopen(fname, "r")) != NULL) {
1138 	static char *buf = NULL;
1139 	static size_t bufsz;
1140 	unsigned lineno = 0;
1141 	int lastpid = 0;
1142 	int pid;
1143 	int x;
1144 	StringListNode *cmdNode;
1145 	struct cached_stat cst;
1146 
1147 	if (buf == NULL) {
1148 	    bufsz = 8 * BUFSIZ;
1149 	    buf = bmake_malloc(bufsz);
1150 	}
1151 
1152 	if (cwdlen == 0) {
1153 	    if (getcwd(cwd, sizeof cwd) == NULL)
1154 		err(1, "Could not get current working directory");
1155 	    cwdlen = strlen(cwd);
1156 	}
1157 	strlcpy(lcwd, cwd, sizeof lcwd);
1158 	strlcpy(latestdir, cwd, sizeof latestdir);
1159 
1160 	if (tmpdir == NULL) {
1161 	    tmpdir = getTmpdir();
1162 	    tmplen = strlen(tmpdir);
1163 	}
1164 
1165 	/* we want to track all the .meta we read */
1166 	Global_Append(".MAKE.META.FILES", fname);
1167 
1168 	cmp_filter = metaCmpFilter || Var_Exists(gn, MAKE_META_CMP_FILTER);
1169 
1170 	cmdNode = gn->commands.first;
1171 	while (!oodate && (x = fgetLine(&buf, &bufsz, 0, fp)) > 0) {
1172 	    lineno++;
1173 	    if (buf[x - 1] == '\n')
1174 		buf[x - 1] = '\0';
1175 	    else {
1176 		warnx("%s: %u: line truncated at %u", fname, lineno, x);
1177 		oodate = true;
1178 		break;
1179 	    }
1180 	    link_src = NULL;
1181 	    move_target = NULL;
1182 	    /* Find the start of the build monitor section. */
1183 	    if (!have_filemon) {
1184 		if (strncmp(buf, "-- filemon", 10) == 0) {
1185 		    have_filemon = true;
1186 		    continue;
1187 		}
1188 		if (strncmp(buf, "# buildmon", 10) == 0) {
1189 		    have_filemon = true;
1190 		    continue;
1191 		}
1192 	    }
1193 
1194 	    /* Delimit the record type. */
1195 	    p = buf;
1196 #ifdef DEBUG_META_MODE
1197 	    DEBUG3(META, "%s: %u: %s\n", fname, lineno, buf);
1198 #endif
1199 	    strsep(&p, " ");
1200 	    if (have_filemon) {
1201 		/*
1202 		 * We are in the 'filemon' output section.
1203 		 * Each record from filemon follows the general form:
1204 		 *
1205 		 * <key> <pid> <data>
1206 		 *
1207 		 * Where:
1208 		 * <key> is a single letter, denoting the syscall.
1209 		 * <pid> is the process that made the syscall.
1210 		 * <data> is the arguments (of interest).
1211 		 */
1212 		switch(buf[0]) {
1213 		case '#':		/* comment */
1214 		case 'V':		/* version */
1215 		    break;
1216 		default:
1217 		    /*
1218 		     * We need to track pathnames per-process.
1219 		     *
1220 		     * Each process run by make starts off in the 'CWD'
1221 		     * recorded in the .meta file, if it chdirs ('C')
1222 		     * elsewhere we need to track that - but only for
1223 		     * that process.  If it forks ('F'), we initialize
1224 		     * the child to have the same cwd as its parent.
1225 		     *
1226 		     * We also need to track the 'latestdir' of
1227 		     * interest.  This is usually the same as cwd, but
1228 		     * not if a process is reading directories.
1229 		     *
1230 		     * Each time we spot a different process ('pid')
1231 		     * we save the current value of 'latestdir' in a
1232 		     * variable qualified by 'lastpid', and
1233 		     * re-initialize 'latestdir' to any pre-saved
1234 		     * value for the current 'pid' and 'CWD' if none.
1235 		     */
1236 		    CHECK_VALID_META(p);
1237 		    pid = atoi(p);
1238 		    if (pid > 0 && pid != lastpid) {
1239 			FStr ldir;
1240 
1241 			if (lastpid > 0) {
1242 			    /* We need to remember these. */
1243 			    Global_Set(lcwd_vname, lcwd);
1244 			    Global_Set(ldir_vname, latestdir);
1245 			}
1246 			snprintf(lcwd_vname, sizeof lcwd_vname, LCWD_VNAME_FMT, pid);
1247 			snprintf(ldir_vname, sizeof ldir_vname, LDIR_VNAME_FMT, pid);
1248 			lastpid = pid;
1249 			ldir = Var_Value(SCOPE_GLOBAL, ldir_vname);
1250 			if (ldir.str != NULL) {
1251 			    strlcpy(latestdir, ldir.str, sizeof latestdir);
1252 			    FStr_Done(&ldir);
1253 			}
1254 			ldir = Var_Value(SCOPE_GLOBAL, lcwd_vname);
1255 			if (ldir.str != NULL) {
1256 			    strlcpy(lcwd, ldir.str, sizeof lcwd);
1257 			    FStr_Done(&ldir);
1258 			}
1259 		    }
1260 		    /* Skip past the pid. */
1261 		    if (strsep(&p, " ") == NULL)
1262 			continue;
1263 #ifdef DEBUG_META_MODE
1264 		    if (DEBUG(META))
1265 			debug_printf("%s: %u: %d: %c: cwd=%s lcwd=%s ldir=%s\n",
1266 				     fname, lineno,
1267 				     pid, buf[0], cwd, lcwd, latestdir);
1268 #endif
1269 		    break;
1270 		}
1271 
1272 		CHECK_VALID_META(p);
1273 
1274 		/* Process according to record type. */
1275 		switch (buf[0]) {
1276 		case 'X':		/* eXit */
1277 		    Var_Delete(SCOPE_GLOBAL, lcwd_vname);
1278 		    Var_Delete(SCOPE_GLOBAL, ldir_vname);
1279 		    lastpid = 0;	/* no need to save ldir_vname */
1280 		    break;
1281 
1282 		case 'F':		/* [v]Fork */
1283 		    {
1284 			char cldir[64];
1285 			int child;
1286 
1287 			child = atoi(p);
1288 			if (child > 0) {
1289 			    snprintf(cldir, sizeof cldir, LCWD_VNAME_FMT, child);
1290 			    Global_Set(cldir, lcwd);
1291 			    snprintf(cldir, sizeof cldir, LDIR_VNAME_FMT, child);
1292 			    Global_Set(cldir, latestdir);
1293 #ifdef DEBUG_META_MODE
1294 			    if (DEBUG(META))
1295 				debug_printf(
1296 					"%s: %u: %d: cwd=%s lcwd=%s ldir=%s\n",
1297 					fname, lineno,
1298 					child, cwd, lcwd, latestdir);
1299 #endif
1300 			}
1301 		    }
1302 		    break;
1303 
1304 		case 'C':		/* Chdir */
1305 		    /* Update lcwd and latest directory. */
1306 		    strlcpy(latestdir, p, sizeof latestdir);
1307 		    strlcpy(lcwd, p, sizeof lcwd);
1308 		    Global_Set(lcwd_vname, lcwd);
1309 		    Global_Set(ldir_vname, lcwd);
1310 #ifdef DEBUG_META_MODE
1311 		    DEBUG4(META, "%s: %u: cwd=%s ldir=%s\n",
1312 			   fname, lineno, cwd, lcwd);
1313 #endif
1314 		    break;
1315 
1316 		case 'M':		/* renaMe */
1317 		    /*
1318 		     * For 'M'oves we want to check
1319 		     * the src as for 'R'ead
1320 		     * and the target as for 'W'rite.
1321 		     */
1322 		    {
1323 			char *cp = p;	/* save this for a second */
1324 			/* now get target */
1325 			if (strsep(&p, " ") == NULL)
1326 			    continue;
1327 			CHECK_VALID_META(p);
1328 			move_target = p;
1329 			p = cp;
1330 		    }
1331 		    /* 'L' and 'M' put single quotes around the args */
1332 		    DEQUOTE(p);
1333 		    DEQUOTE(move_target);
1334 		    /* FALLTHROUGH */
1335 		case 'D':		/* unlink */
1336 		    if (*p == '/') {
1337 			/* remove any missingFiles entries that match p */
1338 			StringListNode *ln = missingFiles.first;
1339 			while (ln != NULL) {
1340 			    StringListNode *next = ln->next;
1341 			    if (path_starts_with(ln->datum, p)) {
1342 				free(ln->datum);
1343 				Lst_Remove(&missingFiles, ln);
1344 			    }
1345 			    ln = next;
1346 			}
1347 		    }
1348 		    if (buf[0] == 'M') {
1349 			/* the target of the mv is a file 'W'ritten */
1350 #ifdef DEBUG_META_MODE
1351 			DEBUG2(META, "meta_oodate: M %s -> %s\n",
1352 			       p, move_target);
1353 #endif
1354 			p = move_target;
1355 			goto check_write;
1356 		    }
1357 		    break;
1358 		case 'L':		/* Link */
1359 		    /*
1360 		     * For 'L'inks check
1361 		     * the src as for 'R'ead
1362 		     * and the target as for 'W'rite.
1363 		     */
1364 		    link_src = p;
1365 		    /* now get target */
1366 		    if (strsep(&p, " ") == NULL)
1367 			continue;
1368 		    CHECK_VALID_META(p);
1369 		    /* 'L' and 'M' put single quotes around the args */
1370 		    DEQUOTE(p);
1371 		    DEQUOTE(link_src);
1372 #ifdef DEBUG_META_MODE
1373 		    DEBUG2(META, "meta_oodate: L %s -> %s\n", link_src, p);
1374 #endif
1375 		    /* FALLTHROUGH */
1376 		case 'W':		/* Write */
1377 		check_write:
1378 		    /*
1379 		     * If a file we generated within our bailiwick
1380 		     * but outside of .OBJDIR is missing,
1381 		     * we need to do it again.
1382 		     */
1383 		    /* ignore non-absolute paths */
1384 		    if (*p != '/')
1385 			break;
1386 
1387 		    if (Lst_IsEmpty(&metaBailiwick))
1388 			break;
1389 
1390 		    /* ignore cwd - normal dependencies handle those */
1391 		    if (strncmp(p, cwd, cwdlen) == 0)
1392 			break;
1393 
1394 		    if (!has_any_prefix(p, &metaBailiwick))
1395 			break;
1396 
1397 		    /* tmpdir might be within */
1398 		    if (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0)
1399 			break;
1400 
1401 		    /* ignore anything containing the string "tmp" */
1402 		    /* XXX: The arguments to strstr must be swapped. */
1403 		    if (strstr("tmp", p) != NULL)
1404 			break;
1405 
1406 		    if ((link_src != NULL && cached_lstat(p, &cst) < 0) ||
1407 			(link_src == NULL && cached_stat(p, &cst) < 0)) {
1408 			if (!meta_ignore(gn, p))
1409 			    append_if_new(&missingFiles, p);
1410 		    }
1411 		    break;
1412 		check_link_src:
1413 		    p = link_src;
1414 		    link_src = NULL;
1415 #ifdef DEBUG_META_MODE
1416 		    DEBUG1(META, "meta_oodate: L src %s\n", p);
1417 #endif
1418 		    /* FALLTHROUGH */
1419 		case 'R':		/* Read */
1420 		case 'E':		/* Exec */
1421 		    /*
1422 		     * Check for runtime files that can't
1423 		     * be part of the dependencies because
1424 		     * they are _expected_ to change.
1425 		     */
1426 		    if (meta_ignore(gn, p))
1427 			break;
1428 
1429 		    /*
1430 		     * The rest of the record is the file name.
1431 		     * Check if it's not an absolute path.
1432 		     */
1433 		    {
1434 			char *sdirs[4];
1435 			char **sdp;
1436 			int sdx = 0;
1437 			bool found = false;
1438 
1439 			if (*p == '/') {
1440 			    sdirs[sdx++] = p; /* done */
1441 			} else {
1442 			    if (strcmp(".", p) == 0)
1443 				continue; /* no point */
1444 
1445 			    /* Check vs latestdir */
1446 			    snprintf(fname1, sizeof fname1, "%s/%s", latestdir, p);
1447 			    sdirs[sdx++] = fname1;
1448 
1449 			    if (strcmp(latestdir, lcwd) != 0) {
1450 				/* Check vs lcwd */
1451 				snprintf(fname2, sizeof fname2, "%s/%s", lcwd, p);
1452 				sdirs[sdx++] = fname2;
1453 			    }
1454 			    if (strcmp(lcwd, cwd) != 0) {
1455 				/* Check vs cwd */
1456 				snprintf(fname3, sizeof fname3, "%s/%s", cwd, p);
1457 				sdirs[sdx++] = fname3;
1458 			    }
1459 			}
1460 			sdirs[sdx++] = NULL;
1461 
1462 			for (sdp = sdirs; *sdp != NULL && !found; sdp++) {
1463 #ifdef DEBUG_META_MODE
1464 			    DEBUG3(META, "%s: %u: looking for: %s\n",
1465 				   fname, lineno, *sdp);
1466 #endif
1467 			    if (cached_stat(*sdp, &cst) == 0) {
1468 				found = true;
1469 				p = *sdp;
1470 			    }
1471 			}
1472 			if (found) {
1473 #ifdef DEBUG_META_MODE
1474 			    DEBUG3(META, "%s: %u: found: %s\n",
1475 				   fname, lineno, p);
1476 #endif
1477 			    if (!S_ISDIR(cst.cst_mode) &&
1478 				cst.cst_mtime > gn->mtime) {
1479 				DEBUG3(META, "%s: %u: file '%s' is newer than the target...\n",
1480 				       fname, lineno, p);
1481 				oodate = true;
1482 			    } else if (S_ISDIR(cst.cst_mode)) {
1483 				/* Update the latest directory. */
1484 				cached_realpath(p, latestdir);
1485 			    }
1486 			} else if (errno == ENOENT && *p == '/' &&
1487 				   strncmp(p, cwd, cwdlen) != 0) {
1488 			    /*
1489 			     * A referenced file outside of CWD is missing.
1490 			     * We cannot catch every eventuality here...
1491 			     */
1492 			    append_if_new(&missingFiles, p);
1493 			}
1494 		    }
1495 		    if (buf[0] == 'E') {
1496 			/* previous latestdir is no longer relevant */
1497 			strlcpy(latestdir, lcwd, sizeof latestdir);
1498 		    }
1499 		    break;
1500 		default:
1501 		    break;
1502 		}
1503 		if (!oodate && buf[0] == 'L' && link_src != NULL)
1504 		    goto check_link_src;
1505 	    } else if (strcmp(buf, "CMD") == 0) {
1506 		/*
1507 		 * Compare the current command with the one in the
1508 		 * meta data file.
1509 		 */
1510 		if (cmdNode == NULL) {
1511 		    DEBUG2(META, "%s: %u: there were more build commands in the meta data file than there are now...\n",
1512 			   fname, lineno);
1513 		    oodate = true;
1514 		} else {
1515 		    const char *cp;
1516 		    char *cmd = cmdNode->datum;
1517 		    bool hasOODATE = false;
1518 
1519 		    if (strstr(cmd, "$?") != NULL)
1520 			hasOODATE = true;
1521 		    else if ((cp = strstr(cmd, ".OODATE")) != NULL) {
1522 			/* check for $[{(].OODATE[:)}] */
1523 			if (cp > cmd + 2 && cp[-2] == '$')
1524 			    hasOODATE = true;
1525 		    }
1526 		    if (hasOODATE) {
1527 			needOODATE = true;
1528 			DEBUG2(META, "%s: %u: cannot compare command using .OODATE\n",
1529 			       fname, lineno);
1530 		    }
1531 		    (void)Var_Subst(cmd, gn, VARE_UNDEFERR, &cmd);
1532 		    /* TODO: handle errors */
1533 
1534 		    if ((cp = strchr(cmd, '\n')) != NULL) {
1535 			int n;
1536 
1537 			/*
1538 			 * This command contains newlines, we need to
1539 			 * fetch more from the .meta file before we
1540 			 * attempt a comparison.
1541 			 */
1542 			/* first put the newline back at buf[x - 1] */
1543 			buf[x - 1] = '\n';
1544 			do {
1545 			    /* now fetch the next line */
1546 			    if ((n = fgetLine(&buf, &bufsz, x, fp)) <= 0)
1547 				break;
1548 			    x = n;
1549 			    lineno++;
1550 			    if (buf[x - 1] != '\n') {
1551 				warnx("%s: %u: line truncated at %u", fname, lineno, x);
1552 				break;
1553 			    }
1554 			    cp = strchr(cp + 1, '\n');
1555 			} while (cp != NULL);
1556 			if (buf[x - 1] == '\n')
1557 			    buf[x - 1] = '\0';
1558 		    }
1559 		    if (p != NULL &&
1560 			!hasOODATE &&
1561 			!(gn->type & OP_NOMETA_CMP) &&
1562 			(meta_cmd_cmp(gn, p, cmd, cmp_filter) != 0)) {
1563 			DEBUG4(META, "%s: %u: a build command has changed\n%s\nvs\n%s\n",
1564 			       fname, lineno, p, cmd);
1565 			if (!metaIgnoreCMDs)
1566 			    oodate = true;
1567 		    }
1568 		    free(cmd);
1569 		    cmdNode = cmdNode->next;
1570 		}
1571 	    } else if (strcmp(buf, "CWD") == 0) {
1572 		/*
1573 		 * Check if there are extra commands now
1574 		 * that weren't in the meta data file.
1575 		 */
1576 		if (!oodate && cmdNode != NULL) {
1577 		    DEBUG2(META, "%s: %u: there are extra build commands now that weren't in the meta data file\n",
1578 			   fname, lineno);
1579 		    oodate = true;
1580 		}
1581 		CHECK_VALID_META(p);
1582 		if (strcmp(p, cwd) != 0) {
1583 		    DEBUG4(META, "%s: %u: the current working directory has changed from '%s' to '%s'\n",
1584 			   fname, lineno, p, curdir);
1585 		    oodate = true;
1586 		}
1587 	    }
1588 	}
1589 
1590 	fclose(fp);
1591 	if (!Lst_IsEmpty(&missingFiles)) {
1592 	    DEBUG2(META, "%s: missing files: %s...\n",
1593 		   fname, (char *)missingFiles.first->datum);
1594 	    oodate = true;
1595 	}
1596 	if (!oodate && !have_filemon && filemonMissing) {
1597 	    DEBUG1(META, "%s: missing filemon data\n", fname);
1598 	    oodate = true;
1599 	}
1600     } else {
1601 	if (writeMeta && (metaMissing || (gn->type & OP_META))) {
1602 	    const char *cp = NULL;
1603 
1604 	    /* if target is in .CURDIR we do not need a meta file */
1605 	    if (gn->path != NULL && (cp = strrchr(gn->path, '/')) != NULL &&
1606 		(cp > gn->path)) {
1607 		if (strncmp(curdir, gn->path, (size_t)(cp - gn->path)) != 0) {
1608 		    cp = NULL;		/* not in .CURDIR */
1609 		}
1610 	    }
1611 	    if (cp == NULL) {
1612 		DEBUG1(META, "%s: required but missing\n", fname);
1613 		oodate = true;
1614 		needOODATE = true;	/* assume the worst */
1615 	    }
1616 	}
1617     }
1618 
1619     Lst_DoneCall(&missingFiles, free);
1620 
1621     if (oodate && needOODATE) {
1622 	/*
1623 	 * Target uses .OODATE which is empty; or we wouldn't be here.
1624 	 * We have decided it is oodate, so .OODATE needs to be set.
1625 	 * All we can sanely do is set it to .ALLSRC.
1626 	 */
1627 	Var_Delete(gn, OODATE);
1628 	Var_Set(gn, OODATE, GNode_VarAllsrc(gn));
1629     }
1630 
1631  oodate_out:
1632     FStr_Done(&dname);
1633     return oodate;
1634 }
1635 
1636 /* support for compat mode */
1637 
1638 static int childPipe[2];
1639 
1640 void
1641 meta_compat_start(void)
1642 {
1643 #ifdef USE_FILEMON_ONCE
1644     /*
1645      * We need to re-open filemon for each cmd.
1646      */
1647     BuildMon *pbm = &Mybm;
1648 
1649     if (pbm->mfp != NULL && useFilemon) {
1650 	meta_open_filemon(pbm);
1651     } else {
1652 	pbm->mon_fd = -1;
1653 	pbm->filemon = NULL;
1654     }
1655 #endif
1656     if (pipe(childPipe) < 0)
1657 	Punt("Cannot create pipe: %s", strerror(errno));
1658     /* Set close-on-exec flag for both */
1659     (void)fcntl(childPipe[0], F_SETFD, FD_CLOEXEC);
1660     (void)fcntl(childPipe[1], F_SETFD, FD_CLOEXEC);
1661 }
1662 
1663 void
1664 meta_compat_child(void)
1665 {
1666     meta_job_child(NULL);
1667     if (dup2(childPipe[1], 1) < 0 || dup2(1, 2) < 0)
1668 	execDie("dup2", "pipe");
1669 }
1670 
1671 void
1672 meta_compat_parent(pid_t child)
1673 {
1674     int outfd, metafd, maxfd, nfds;
1675     char buf[BUFSIZ+1];
1676     fd_set readfds;
1677 
1678     meta_job_parent(NULL, child);
1679     close(childPipe[1]);			/* child side */
1680     outfd = childPipe[0];
1681 #ifdef USE_FILEMON
1682     metafd = Mybm.filemon != NULL ? filemon_readfd(Mybm.filemon) : -1;
1683 #else
1684     metafd = -1;
1685 #endif
1686     maxfd = -1;
1687     if (outfd > maxfd)
1688 	    maxfd = outfd;
1689     if (metafd > maxfd)
1690 	    maxfd = metafd;
1691 
1692     while (outfd != -1 || metafd != -1) {
1693 	FD_ZERO(&readfds);
1694 	if (outfd != -1) {
1695 	    FD_SET(outfd, &readfds);
1696 	}
1697 	if (metafd != -1) {
1698 	    FD_SET(metafd, &readfds);
1699 	}
1700 	nfds = select(maxfd + 1, &readfds, NULL, NULL, NULL);
1701 	if (nfds == -1) {
1702 	    if (errno == EINTR)
1703 		continue;
1704 	    err(1, "select");
1705 	}
1706 
1707 	if (outfd != -1 && FD_ISSET(outfd, &readfds) != 0) do {
1708 	    /* XXX this is not line-buffered */
1709 	    ssize_t nread = read(outfd, buf, sizeof buf - 1);
1710 	    if (nread == -1)
1711 		err(1, "read");
1712 	    if (nread == 0) {
1713 		close(outfd);
1714 		outfd = -1;
1715 		break;
1716 	    }
1717 	    fwrite(buf, 1, (size_t)nread, stdout);
1718 	    fflush(stdout);
1719 	    buf[nread] = '\0';
1720 	    meta_job_output(NULL, buf, "");
1721 	} while (false);
1722 	if (metafd != -1 && FD_ISSET(metafd, &readfds) != 0) {
1723 	    if (meta_job_event(NULL) <= 0)
1724 		metafd = -1;
1725 	}
1726     }
1727 }
1728 
1729 #endif /* USE_META */
1730