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