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