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