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