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