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