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