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