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