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