xref: /freebsd/contrib/bmake/meta.c (revision 34a3834eadd03bec7703b8fbf9123f27b1114986)
1 /*      $NetBSD: meta.c,v 1.220 2026/02/10 18:53:34 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 #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     /* Get the basename of the target */
462     cp = str_basename(tname);
463 
464     fflush(stdout);
465 
466     if (!writeMeta)
467 	/* Don't create meta data. */
468 	goto out;
469 
470     fname = meta_name(pbm->meta_fname, sizeof pbm->meta_fname,
471 		      dname.str, tname, objdir_realpath);
472 
473 #ifdef DEBUG_META_MODE
474     DEBUG1(META, "meta_create: %s\n", fname);
475 #endif
476 
477     if ((fp = fopen(fname, "w")) == NULL)
478 	Punt("Could not open meta file '%s': %s", fname, strerror(errno));
479 
480     fprintf(fp, "# Meta data file %s\n", fname);
481 
482     printCMDs(gn, fp);
483 
484     fprintf(fp, "CWD %s\n", getcwd(buf, sizeof buf));
485     fprintf(fp, "TARGET %s\n", tname);
486     cp = GNode_VarOodate(gn);
487     if (cp != NULL && *cp != '\0') {
488 	fprintf(fp, "OODATE %s\n", cp);
489     }
490     if (metaEnv) {
491 	for (ptr = environ; *ptr != NULL; ptr++)
492 	    fprintf(fp, "ENV %s\n", *ptr);
493     }
494 
495     fprintf(fp, "-- command output --\n");
496     if (fflush(fp) != 0)
497 	Punt("Cannot write expanded command to meta file: %s",
498 	    strerror(errno));
499 
500     Global_Append(".MAKE.META.FILES", fname);
501     Global_Append(".MAKE.META.CREATED", fname);
502 
503     gn->type |= OP_META;		/* in case anyone wants to know */
504     if (metaSilent) {
505 	    gn->type |= OP_SILENT;
506     }
507  out:
508     FStr_Done(&dname);
509 
510     return fp;
511 }
512 
513 static bool
boolValue(const char * s)514 boolValue(const char *s)
515 {
516     switch (*s) {
517     case '0':
518     case 'N':
519     case 'n':
520     case 'F':
521     case 'f':
522 	return false;
523     }
524     return true;
525 }
526 
527 /*
528  * Initialization we need before reading makefiles.
529  */
530 void
meta_init(void)531 meta_init(void)
532 {
533 #ifdef USE_FILEMON
534 	/* this allows makefiles to test if we have filemon support */
535 	Global_Set(".MAKE.PATH_FILEMON", filemon_path());
536 #endif
537 }
538 
539 
540 #define get_mode_bf(bf, token) \
541     if ((cp = strstr(make_mode, token)) != NULL) \
542 	bf = boolValue(cp + sizeof (token) - 1)
543 
544 /*
545  * Initialization we need after reading makefiles.
546  */
547 void
meta_mode_init(const char * make_mode)548 meta_mode_init(const char *make_mode)
549 {
550     static bool once = false;
551     const char *cp;
552 
553     useMeta = true;
554     useFilemon = true;
555     writeMeta = true;
556 
557     if (make_mode != NULL) {
558 	if (strstr(make_mode, "env") != NULL)
559 	    metaEnv = true;
560 	if (strstr(make_mode, "verb") != NULL)
561 	    metaVerbose = true;
562 	if (strstr(make_mode, "read") != NULL)
563 	    writeMeta = false;
564 	if (strstr(make_mode, "nofilemon") != NULL)
565 	    useFilemon = false;
566 	if (strstr(make_mode, "ignore-cmd") != NULL)
567 	    metaIgnoreCMDs = true;
568 	if (useFilemon)
569 	    get_mode_bf(filemonMissing, "missing-filemon=");
570 	get_mode_bf(metaCurdirOk, "curdirok=");
571 	get_mode_bf(metaMissing, "missing-meta=");
572 	get_mode_bf(metaSilent, "silent=");
573     }
574     if (metaVerbose && !Var_Exists(SCOPE_GLOBAL, MAKE_META_PREFIX)) {
575 	/*
576 	 * The default value for MAKE_META_PREFIX
577 	 * prints the absolute path of the target.
578 	 * This works be cause :H will generate '.' if there is no /
579 	 * and :tA will resolve that to cwd.
580 	 */
581 	Global_Set(MAKE_META_PREFIX,
582 	    "Building ${.TARGET:H:tA}/${.TARGET:T}");
583     }
584     if (once)
585 	return;
586     once = true;
587     memset(&Mybm, 0, sizeof Mybm);
588     /*
589      * We consider ourselves master of all within ${.MAKE.META.BAILIWICK}
590      */
591     metaBailiwickStr = Var_Subst("${.MAKE.META.BAILIWICK:O:u:tA}",
592 				 SCOPE_GLOBAL, VARE_EVAL);
593     /* TODO: handle errors */
594     AppendWords(&metaBailiwick, metaBailiwickStr);
595     /*
596      * We ignore any paths that start with ${.MAKE.META.IGNORE_PATHS}
597      */
598     Global_Append(MAKE_META_IGNORE_PATHS,
599 	       "/dev /etc /proc /tmp /var/run /var/tmp ${TMPDIR}");
600     metaIgnorePathsStr = Var_Subst("${" MAKE_META_IGNORE_PATHS ":O:u:tA}",
601 				   SCOPE_GLOBAL, VARE_EVAL);
602     /* TODO: handle errors */
603     AppendWords(&metaIgnorePaths, metaIgnorePathsStr);
604 
605     /*
606      * We ignore any paths that match ${.MAKE.META.IGNORE_PATTERNS}
607      */
608     metaIgnorePatterns = Var_Exists(SCOPE_GLOBAL, MAKE_META_IGNORE_PATTERNS);
609     metaIgnoreFilter = Var_Exists(SCOPE_GLOBAL, MAKE_META_IGNORE_FILTER);
610     metaCmpFilter = Var_Exists(SCOPE_GLOBAL, MAKE_META_CMP_FILTER);
611 }
612 
613 MAKE_INLINE BuildMon *
BM(Job * job)614 BM(Job *job)
615 {
616 
617 	return job != NULL ? Job_BuildMon(job) : &Mybm;
618 }
619 
620 /*
621  * In each case below we allow for job==NULL
622  */
623 void
meta_job_start(Job * job,GNode * gn)624 meta_job_start(Job *job, GNode *gn)
625 {
626     BuildMon *pbm;
627 
628     pbm = BM(job);
629     pbm->mfp = meta_create(pbm, gn);
630 #ifdef USE_FILEMON_ONCE
631     /* compat mode we open the filemon dev once per command */
632     if (job == NULL)
633 	return;
634 #endif
635 #ifdef USE_FILEMON
636     if (pbm->mfp != NULL && useFilemon) {
637 	meta_open_filemon(pbm);
638     } else {
639 	pbm->mon_fd = -1;
640 	pbm->filemon = NULL;
641     }
642 #endif
643 }
644 
645 /*
646  * The child calls this before doing anything.
647  * It does not disturb our state.
648  */
649 void
meta_job_child(Job * job MAKE_ATTR_UNUSED)650 meta_job_child(Job *job MAKE_ATTR_UNUSED)
651 {
652 #ifdef USE_FILEMON
653     BuildMon *pbm;
654 
655     pbm = BM(job);
656     if (pbm->mfp != NULL) {
657 	close(fileno(pbm->mfp));
658 	if (useFilemon && pbm->filemon != NULL) {
659 	    pid_t pid;
660 
661 	    pid = getpid();
662 	    if (filemon_setpid_child(pbm->filemon, pid) == -1) {
663 		Punt("Could not set filemon pid: %s", strerror(errno));
664 	    }
665 	}
666     }
667 #endif
668 }
669 
670 void
meta_job_parent(Job * job MAKE_ATTR_UNUSED,pid_t pid MAKE_ATTR_UNUSED)671 meta_job_parent(Job *job MAKE_ATTR_UNUSED, pid_t pid MAKE_ATTR_UNUSED)
672 {
673 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
674     BuildMon *pbm;
675 
676     pbm = BM(job);
677     if (useFilemon && pbm->filemon != NULL) {
678 	filemon_setpid_parent(pbm->filemon, pid);
679     }
680 #endif
681 }
682 
683 int
meta_job_fd(Job * job MAKE_ATTR_UNUSED)684 meta_job_fd(Job *job MAKE_ATTR_UNUSED)
685 {
686 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
687     BuildMon *pbm;
688 
689     pbm = BM(job);
690     if (useFilemon && pbm->filemon != NULL) {
691 	return filemon_readfd(pbm->filemon);
692     }
693 #endif
694     return -1;
695 }
696 
697 int
meta_job_event(Job * job MAKE_ATTR_UNUSED)698 meta_job_event(Job *job MAKE_ATTR_UNUSED)
699 {
700 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
701     BuildMon *pbm;
702 
703     pbm = BM(job);
704     if (useFilemon && pbm->filemon != NULL) {
705 	return filemon_process(pbm->filemon);
706     }
707 #endif
708     return 0;
709 }
710 
711 void
meta_job_error(Job * job,GNode * gn,bool ignerr,int status)712 meta_job_error(Job *job, GNode *gn, bool ignerr, int status)
713 {
714     char cwd[MAXPATHLEN];
715     BuildMon *pbm;
716 
717     pbm = BM(job);
718     if (job != NULL && gn == NULL)
719 	    gn = Job_Node(job);
720     if (pbm->mfp != NULL) {
721 	fprintf(pbm->mfp, "\n*** Error code %d%s\n",
722 		status, ignerr ? "(ignored)" : "");
723     }
724     if (gn != NULL)
725 	Global_Set(".ERROR_TARGET", GNode_Path(gn));
726     if (getcwd(cwd, sizeof cwd) == NULL)
727 	Punt("getcwd: %s", strerror(errno));
728 
729     Global_Set(".ERROR_CWD", cwd);
730     if (pbm->meta_fname[0] != '\0') {
731 	Global_Set(".ERROR_META_FILE", pbm->meta_fname);
732     }
733     meta_job_finish(job);
734 }
735 
736 void
meta_job_output(Job * job,const char * cp,size_t len)737 meta_job_output(Job *job, const char *cp, size_t len)
738 {
739     BuildMon *pbm;
740 
741     pbm = BM(job);
742     if (pbm->mfp != NULL) {
743 	if (metaVerbose) {
744 	    static char *meta_prefix = NULL;
745 	    static size_t meta_prefix_len;
746 
747 	    if (meta_prefix == NULL) {
748 		meta_prefix = Var_Subst("${" MAKE_META_PREFIX "}",
749 					SCOPE_GLOBAL, VARE_EVAL);
750 		/* TODO: handle errors */
751 		meta_prefix_len = strcspn(meta_prefix, "$");
752 	    }
753 	    if (strncmp(cp, meta_prefix, meta_prefix_len) == 0) {
754 		cp = strchr(cp + 1, '\n');
755 		if (cp == NULL)
756 		    return;
757 		cp++;
758 	    }
759 	}
760 	fprintf(pbm->mfp, "%.*s", (int)len, cp);
761     }
762 }
763 
764 int
meta_cmd_finish(void * pbmp)765 meta_cmd_finish(void *pbmp)
766 {
767     int error = 0;
768     BuildMon *pbm = pbmp;
769 #ifdef USE_FILEMON
770     int x;
771 #endif
772 
773     if (pbm == NULL)
774 	pbm = &Mybm;
775 
776 #ifdef USE_FILEMON
777     if (pbm->filemon != NULL) {
778 	while (filemon_process(pbm->filemon) > 0)
779 	    continue;
780 	if (filemon_close(pbm->filemon) == -1) {
781 	    error = errno;
782 	    Punt("filemon failed: %s", strerror(errno));
783 	}
784 	x = filemon_read(pbm->mfp, pbm->mon_fd);
785 	if (error == 0 && x != 0)
786 	    error = x;
787 	pbm->mon_fd = -1;
788 	pbm->filemon = NULL;
789 	return error;
790     }
791 #endif
792 
793     fprintf(pbm->mfp, "\n");	/* ensure end with newline */
794     return error;
795 }
796 
797 int
meta_job_finish(Job * job)798 meta_job_finish(Job *job)
799 {
800     BuildMon *pbm;
801     int error = 0;
802     int x;
803 
804     pbm = BM(job);
805     if (pbm->mfp != NULL) {
806 	error = meta_cmd_finish(pbm);
807 	x = fclose(pbm->mfp);
808 	if (error == 0 && x != 0)
809 	    error = errno;
810 	pbm->mfp = NULL;
811 	pbm->meta_fname[0] = '\0';
812     }
813     return error;
814 }
815 
816 void
meta_finish(void)817 meta_finish(void)
818 {
819     Lst_Done(&metaBailiwick);
820     free(metaBailiwickStr);
821     Lst_Done(&metaIgnorePaths);
822     free(metaIgnorePathsStr);
823 }
824 
825 /*
826  * Fetch a full line from fp - growing bufp if needed
827  * Return length in bufp.
828  */
829 static int
fgetLine(char ** bufp,size_t * szp,int o,FILE * fp)830 fgetLine(char **bufp, size_t *szp, int o, FILE *fp)
831 {
832     char *buf = *bufp;
833     size_t bufsz = *szp;
834     struct stat fs;
835     int x;
836 
837     if (fgets(&buf[o], (int)bufsz - o, fp) != NULL) {
838     check_newline:
839 	x = o + (int)strlen(&buf[o]);
840 	if (buf[x - 1] == '\n')
841 	    return x;
842 	/*
843 	 * We need to grow the buffer.
844 	 * The meta file can give us a clue.
845 	 */
846 	if (fstat(fileno(fp), &fs) == 0) {
847 	    size_t newsz;
848 	    char *p;
849 
850 	    newsz = ROUNDUP(((size_t)fs.st_size / 2), BUFSIZ);
851 	    if (newsz <= bufsz)
852 		newsz = ROUNDUP((size_t)fs.st_size, BUFSIZ);
853 	    if (newsz <= bufsz)
854 		return x;		/* truncated */
855 	    DEBUG2(META, "growing buffer %u -> %u\n",
856 		   (unsigned)bufsz, (unsigned)newsz);
857 	    p = bmake_realloc(buf, newsz);
858 	    *bufp = buf = p;
859 	    *szp = bufsz = newsz;
860 	    /* fetch the rest */
861 	    if (fgets(&buf[x], (int)bufsz - x, fp) == NULL)
862 		return x;		/* truncated! */
863 	    goto check_newline;
864 	}
865     }
866     return 0;
867 }
868 
869 static bool
prefix_match(const char * prefix,const char * path)870 prefix_match(const char *prefix, const char *path)
871 {
872     size_t n = strlen(prefix);
873 
874     return strncmp(path, prefix, n) == 0;
875 }
876 
877 static bool
has_any_prefix(const char * path,StringList * prefixes)878 has_any_prefix(const char *path, StringList *prefixes)
879 {
880     StringListNode *ln;
881 
882     for (ln = prefixes->first; ln != NULL; ln = ln->next)
883 	if (prefix_match(ln->datum, path))
884 	    return true;
885     return false;
886 }
887 
888 /* See if the path equals prefix or starts with "prefix/". */
889 static bool
path_starts_with(const char * path,const char * prefix)890 path_starts_with(const char *path, const char *prefix)
891 {
892     size_t n = strlen(prefix);
893 
894     if (strncmp(path, prefix, n) != 0)
895 	return false;
896     return path[n] == '\0' || path[n] == '/';
897 }
898 
899 static bool
meta_ignore(GNode * gn,const char * p)900 meta_ignore(GNode *gn, const char *p)
901 {
902     char fname[MAXPATHLEN];
903 
904     if (p == NULL)
905 	return true;
906 
907     if (*p == '/') {
908 	/* first try the raw path "as is" */
909 	if (has_any_prefix(p, &metaIgnorePaths)) {
910 #ifdef DEBUG_META_MODE
911 	    DEBUG1(META, "meta_oodate: ignoring path: %s\n", p);
912 #endif
913 	    return true;
914 	}
915 	cached_realpath(p, fname); /* clean it up */
916 	if (has_any_prefix(fname, &metaIgnorePaths)) {
917 #ifdef DEBUG_META_MODE
918 	    DEBUG1(META, "meta_oodate: ignoring path: %s\n", p);
919 #endif
920 	    return true;
921 	}
922     }
923 
924     if (metaIgnorePatterns) {
925 	const char *expr;
926 	char *pm;
927 
928 	/*
929 	 * XXX: This variable is set on a target GNode but is not one of
930 	 * the usual local variables.  It should be deleted afterwards.
931 	 * Ideally it would not be created in the first place, just like
932 	 * in a .for loop.
933 	 */
934 	Var_Set(gn, ".p.", p);
935 	expr = "${" MAKE_META_IGNORE_PATTERNS ":@m@${.p.:M$m}@}";
936 	pm = Var_Subst(expr, gn, VARE_EVAL);
937 	/* TODO: handle errors */
938 	if (pm[0] != '\0') {
939 #ifdef DEBUG_META_MODE
940 	    DEBUG1(META, "meta_oodate: ignoring pattern: %s\n", p);
941 #endif
942 	    free(pm);
943 	    return true;
944 	}
945 	free(pm);
946     }
947 
948     if (metaIgnoreFilter) {
949 	char *fm;
950 
951 	/* skip if filter result is empty */
952 	snprintf(fname, sizeof fname,
953 		 "${%s:L:${%s:ts:}}",
954 		 p, MAKE_META_IGNORE_FILTER);
955 	fm = Var_Subst(fname, gn, VARE_EVAL);
956 	/* TODO: handle errors */
957 	if (*fm == '\0') {
958 #ifdef DEBUG_META_MODE
959 	    DEBUG1(META, "meta_oodate: ignoring filtered: %s\n", p);
960 #endif
961 	    free(fm);
962 	    return true;
963 	}
964 	free(fm);
965     }
966     return false;
967 }
968 
969 /*
970  * When running with 'meta' functionality, a target can be out-of-date
971  * if any of the references in its meta data file is more recent.
972  * We have to track the latestdir on a per-process basis.
973  */
974 #define LCWD_VNAME_FMT ".meta.%d.lcwd"
975 #define LDIR_VNAME_FMT ".meta.%d.ldir"
976 
977 /*
978  * It is possible that a .meta file is corrupted,
979  * if we detect this we want to reproduce it.
980  * Setting oodate true will have that effect.
981  */
982 #define CHECK_VALID_META(p) if (!(p != NULL && *p != '\0')) { \
983     warnx("%s:%u: malformed", fname, lineno); \
984     oodate = true; \
985     continue; \
986     }
987 
988 #define DEQUOTE(p) if (*p == '\'') {	\
989     char *ep; \
990     p++; \
991     if ((ep = strchr(p, '\'')) != NULL) \
992 	*ep = '\0'; \
993     }
994 
995 static void
append_if_new(StringList * list,const char * str)996 append_if_new(StringList *list, const char *str)
997 {
998     StringListNode *ln;
999 
1000     for (ln = list->first; ln != NULL; ln = ln->next)
1001 	if (strcmp(ln->datum, str) == 0)
1002 	    return;
1003     Lst_Append(list, bmake_strdup(str));
1004 }
1005 
1006 /* A "reserved" variable to store the command to be filtered */
1007 #define META_CMD_FILTER_VAR ".MAKE.cmd_filtered"
1008 
1009 static char *
meta_filter_cmd(GNode * gn,char * s)1010 meta_filter_cmd(GNode *gn, char *s)
1011 {
1012     Var_Set(gn, META_CMD_FILTER_VAR, s);
1013     s = Var_Subst(
1014 	"${" META_CMD_FILTER_VAR ":${" MAKE_META_CMP_FILTER ":ts:}}",
1015 	gn, VARE_EVAL);
1016     return s;
1017 }
1018 
1019 static int
meta_cmd_cmp(GNode * gn,char * a,char * b,bool filter)1020 meta_cmd_cmp(GNode *gn, char *a, char *b, bool filter)
1021 {
1022     int rc;
1023 
1024     rc = strcmp(a, b);
1025     if (rc == 0 || !filter)
1026 	return rc;
1027     a = meta_filter_cmd(gn, a);
1028     b = meta_filter_cmd(gn, b);
1029     rc = strcmp(a, b);
1030     free(a);
1031     free(b);
1032     Var_Delete(gn, META_CMD_FILTER_VAR);
1033     return rc;
1034 }
1035 
1036 bool
meta_oodate(GNode * gn,bool oodate)1037 meta_oodate(GNode *gn, bool oodate)
1038 {
1039     static char *tmpdir = NULL;
1040     static char cwd[MAXPATHLEN];
1041     char lcwd_vname[64];
1042     char ldir_vname[64];
1043     char lcwd[MAXPATHLEN];
1044     char latestdir[MAXPATHLEN];
1045     char fname[MAXPATHLEN];
1046     char fname1[MAXPATHLEN];
1047     char fname2[MAXPATHLEN];
1048     char fname3[MAXPATHLEN];
1049     FStr dname;
1050     const char *tname;
1051     char *p;
1052     char *link_src;
1053     char *move_target;
1054     static size_t cwdlen = 0;
1055     static size_t tmplen = 0;
1056     FILE *fp;
1057     bool needOODATE = false;
1058     StringList missingFiles;
1059     bool have_filemon = false;
1060     bool cmp_filter;
1061 
1062     if (oodate)
1063 	return oodate;		/* we're done */
1064 
1065     dname = Var_Value(gn, ".OBJDIR");
1066     tname = GNode_VarTarget(gn);
1067 
1068     /* if this succeeds fname3 is realpath of dname */
1069     if (!meta_needed(gn, dname.str, fname3, false))
1070 	goto oodate_out;
1071     dname.str = fname3;
1072 
1073     Lst_Init(&missingFiles);
1074 
1075     /*
1076      * We need to check if the target is out-of-date. This includes
1077      * checking if the expanded command has changed. This in turn
1078      * requires that all variables are set in the same way that they
1079      * would be if the target needs to be re-built.
1080      */
1081     GNode_SetLocalVars(gn);
1082 
1083     meta_name(fname, sizeof fname, dname.str, tname, dname.str);
1084 
1085 #ifdef DEBUG_META_MODE
1086     DEBUG1(META, "meta_oodate: %s\n", fname);
1087 #endif
1088 
1089     if ((fp = fopen(fname, "r")) != NULL) {
1090 	static char *buf = NULL;
1091 	static size_t bufsz;
1092 	unsigned lineno = 0;
1093 	int lastpid = 0;
1094 	int pid;
1095 	int x;
1096 	StringListNode *cmdNode;
1097 	struct cached_stat cst;
1098 
1099 	if (buf == NULL) {
1100 	    bufsz = 8 * BUFSIZ;
1101 	    buf = bmake_malloc(bufsz);
1102 	}
1103 
1104 	if (cwdlen == 0) {
1105 	    if (getcwd(cwd, sizeof cwd) == NULL)
1106 		err(1, "Could not get current working directory");
1107 	    cwdlen = strlen(cwd);
1108 	}
1109 	strlcpy(lcwd, cwd, sizeof lcwd);
1110 	strlcpy(latestdir, cwd, sizeof latestdir);
1111 
1112 	if (tmpdir == NULL) {
1113 	    tmpdir = getTmpdir();
1114 	    tmplen = strlen(tmpdir);
1115 	}
1116 
1117 	/* we want to track all the .meta we read */
1118 	Global_Append(".MAKE.META.FILES", fname);
1119 
1120 	cmp_filter = metaCmpFilter || Var_Exists(gn, MAKE_META_CMP_FILTER);
1121 
1122 	cmdNode = gn->commands.first;
1123 	while (!oodate && (x = fgetLine(&buf, &bufsz, 0, fp)) > 0) {
1124 	    lineno++;
1125 	    if (buf[x - 1] == '\n')
1126 		buf[x - 1] = '\0';
1127 	    else {
1128 		warnx("%s:%u: line truncated at %u", fname, lineno, x);
1129 		oodate = true;
1130 		break;
1131 	    }
1132 	    link_src = NULL;
1133 	    move_target = NULL;
1134 	    /* Find the start of the build monitor section. */
1135 	    if (!have_filemon) {
1136 		if (strncmp(buf, "-- filemon", 10) == 0) {
1137 		    have_filemon = true;
1138 		    continue;
1139 		}
1140 		if (strncmp(buf, "# buildmon", 10) == 0) {
1141 		    have_filemon = true;
1142 		    continue;
1143 		}
1144 	    }
1145 
1146 	    /* Delimit the record type. */
1147 	    p = buf;
1148 #ifdef DEBUG_META_MODE
1149 	    DEBUG3(META, "%s:%u: %s\n", fname, lineno, buf);
1150 #endif
1151 	    strsep(&p, " ");
1152 	    if (have_filemon) {
1153 		/*
1154 		 * We are in the 'filemon' output section.
1155 		 * Each record from filemon follows the general form:
1156 		 *
1157 		 * <key> <pid> <data>
1158 		 *
1159 		 * Where:
1160 		 * <key> is a single letter, denoting the syscall.
1161 		 * <pid> is the process that made the syscall.
1162 		 * <data> is the arguments (of interest).
1163 		 */
1164 		switch(buf[0]) {
1165 		case '#':		/* comment */
1166 		case 'V':		/* version */
1167 		    break;
1168 		default:
1169 		    /*
1170 		     * We need to track pathnames per-process.
1171 		     *
1172 		     * Each process run by make starts off in the 'CWD'
1173 		     * recorded in the .meta file, if it chdirs ('C')
1174 		     * elsewhere we need to track that - but only for
1175 		     * that process.  If it forks ('F'), we initialize
1176 		     * the child to have the same cwd as its parent.
1177 		     *
1178 		     * We also need to track the 'latestdir' of
1179 		     * interest.  This is usually the same as cwd, but
1180 		     * not if a process is reading directories.
1181 		     *
1182 		     * Each time we spot a different process ('pid')
1183 		     * we save the current value of 'latestdir' in a
1184 		     * variable qualified by 'lastpid', and
1185 		     * re-initialize 'latestdir' to any pre-saved
1186 		     * value for the current 'pid' and 'CWD' if none.
1187 		     */
1188 		    CHECK_VALID_META(p);
1189 		    pid = atoi(p);
1190 		    if (pid > 0 && pid != lastpid) {
1191 			FStr ldir;
1192 
1193 			if (lastpid > 0) {
1194 			    /* We need to remember these. */
1195 			    Global_Set(lcwd_vname, lcwd);
1196 			    Global_Set(ldir_vname, latestdir);
1197 			}
1198 			snprintf(lcwd_vname, sizeof lcwd_vname, LCWD_VNAME_FMT, pid);
1199 			snprintf(ldir_vname, sizeof ldir_vname, LDIR_VNAME_FMT, pid);
1200 			lastpid = pid;
1201 			ldir = Var_Value(SCOPE_GLOBAL, ldir_vname);
1202 			if (ldir.str != NULL) {
1203 			    strlcpy(latestdir, ldir.str, sizeof latestdir);
1204 			    FStr_Done(&ldir);
1205 			}
1206 			ldir = Var_Value(SCOPE_GLOBAL, lcwd_vname);
1207 			if (ldir.str != NULL) {
1208 			    strlcpy(lcwd, ldir.str, sizeof lcwd);
1209 			    FStr_Done(&ldir);
1210 			}
1211 		    }
1212 		    /* Skip past the pid. */
1213 		    if (strsep(&p, " ") == NULL)
1214 			continue;
1215 #ifdef DEBUG_META_MODE
1216 		    if (DEBUG(META))
1217 			debug_printf("%s:%u: %d: %c: cwd=%s lcwd=%s ldir=%s\n",
1218 				     fname, lineno,
1219 				     pid, buf[0], cwd, lcwd, latestdir);
1220 #endif
1221 		    break;
1222 		}
1223 
1224 		CHECK_VALID_META(p);
1225 
1226 		/* Process according to record type. */
1227 		switch (buf[0]) {
1228 		case 'X':		/* eXit */
1229 		    Var_Delete(SCOPE_GLOBAL, lcwd_vname);
1230 		    Var_Delete(SCOPE_GLOBAL, ldir_vname);
1231 		    lastpid = 0;	/* no need to save ldir_vname */
1232 		    break;
1233 
1234 		case 'F':		/* [v]Fork */
1235 		    {
1236 			char cldir[64];
1237 			int child;
1238 
1239 			child = atoi(p);
1240 			if (child > 0) {
1241 			    snprintf(cldir, sizeof cldir, LCWD_VNAME_FMT, child);
1242 			    Global_Set(cldir, lcwd);
1243 			    snprintf(cldir, sizeof cldir, LDIR_VNAME_FMT, child);
1244 			    Global_Set(cldir, latestdir);
1245 #ifdef DEBUG_META_MODE
1246 			    if (DEBUG(META))
1247 				debug_printf(
1248 					"%s:%u: %d: cwd=%s lcwd=%s ldir=%s\n",
1249 					fname, lineno,
1250 					child, cwd, lcwd, latestdir);
1251 #endif
1252 			}
1253 		    }
1254 		    break;
1255 
1256 		case 'C':		/* Chdir */
1257 		    /* Update lcwd and latest directory. */
1258 		    strlcpy(latestdir, p, sizeof latestdir);
1259 		    strlcpy(lcwd, p, sizeof lcwd);
1260 		    Global_Set(lcwd_vname, lcwd);
1261 		    Global_Set(ldir_vname, lcwd);
1262 #ifdef DEBUG_META_MODE
1263 		    DEBUG4(META, "%s:%u: cwd=%s ldir=%s\n",
1264 			   fname, lineno, cwd, lcwd);
1265 #endif
1266 		    break;
1267 
1268 		case 'M':		/* renaMe */
1269 		    /*
1270 		     * For 'M'oves we want to check
1271 		     * the src as for 'R'ead
1272 		     * and the target as for 'W'rite.
1273 		     */
1274 		    {
1275 			char *cp = p;	/* save this for a second */
1276 			/* now get target */
1277 			if (strsep(&p, " ") == NULL)
1278 			    continue;
1279 			CHECK_VALID_META(p);
1280 			move_target = p;
1281 			p = cp;
1282 		    }
1283 		    /* 'L' and 'M' put single quotes around the args */
1284 		    DEQUOTE(p);
1285 		    DEQUOTE(move_target);
1286 		    /* FALLTHROUGH */
1287 		case 'D':		/* unlink */
1288 		    if (*p == '/') {
1289 			/* remove any missingFiles entries that match p */
1290 			StringListNode *ln = missingFiles.first;
1291 			while (ln != NULL) {
1292 			    StringListNode *next = ln->next;
1293 			    if (path_starts_with(ln->datum, p)) {
1294 				free(ln->datum);
1295 				Lst_Remove(&missingFiles, ln);
1296 			    }
1297 			    ln = next;
1298 			}
1299 		    }
1300 		    if (buf[0] == 'M') {
1301 			/* the target of the mv is a file 'W'ritten */
1302 #ifdef DEBUG_META_MODE
1303 			DEBUG2(META, "meta_oodate: M %s -> %s\n",
1304 			       p, move_target);
1305 #endif
1306 			p = move_target;
1307 			goto check_write;
1308 		    }
1309 		    break;
1310 		case 'L':		/* Link */
1311 		    /*
1312 		     * For 'L'inks check
1313 		     * the src as for 'R'ead
1314 		     * and the target as for 'W'rite.
1315 		     */
1316 		    link_src = p;
1317 		    /* now get target */
1318 		    if (strsep(&p, " ") == NULL)
1319 			continue;
1320 		    CHECK_VALID_META(p);
1321 		    /* 'L' and 'M' put single quotes around the args */
1322 		    DEQUOTE(p);
1323 		    DEQUOTE(link_src);
1324 #ifdef DEBUG_META_MODE
1325 		    DEBUG2(META, "meta_oodate: L %s -> %s\n", link_src, p);
1326 #endif
1327 		    /* FALLTHROUGH */
1328 		case 'W':		/* Write */
1329 		check_write:
1330 		    /*
1331 		     * If a file we generated within our bailiwick
1332 		     * but outside of .OBJDIR is missing,
1333 		     * we need to do it again.
1334 		     */
1335 		    /* ignore non-absolute paths */
1336 		    if (*p != '/')
1337 			break;
1338 
1339 		    if (Lst_IsEmpty(&metaBailiwick))
1340 			break;
1341 
1342 		    /* ignore cwd - normal dependencies handle those */
1343 		    if (strncmp(p, cwd, cwdlen) == 0)
1344 			break;
1345 
1346 		    if (!has_any_prefix(p, &metaBailiwick))
1347 			break;
1348 
1349 		    /* tmpdir might be within */
1350 		    if (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0)
1351 			break;
1352 
1353 		    /* ignore anything containing the string "tmp" */
1354 		    /* XXX: The arguments to strstr must be swapped. */
1355 		    if (strstr("tmp", p) != NULL)
1356 			break;
1357 
1358 		    if ((link_src != NULL && cached_lstat(p, &cst) < 0) ||
1359 			(link_src == NULL && cached_stat(p, &cst) < 0)) {
1360 			if (!meta_ignore(gn, p))
1361 			    append_if_new(&missingFiles, p);
1362 		    }
1363 		    break;
1364 		check_link_src:
1365 		    p = link_src;
1366 		    link_src = NULL;
1367 #ifdef DEBUG_META_MODE
1368 		    DEBUG1(META, "meta_oodate: L src %s\n", p);
1369 #endif
1370 		    /* FALLTHROUGH */
1371 		case 'R':		/* Read */
1372 		case 'E':		/* Exec */
1373 		    /*
1374 		     * Check for runtime files that can't
1375 		     * be part of the dependencies because
1376 		     * they are _expected_ to change.
1377 		     */
1378 		    if (meta_ignore(gn, p))
1379 			break;
1380 
1381 		    /*
1382 		     * The rest of the record is the file name.
1383 		     * Check if it's not an absolute path.
1384 		     */
1385 		    {
1386 			char *sdirs[4];
1387 			char **sdp;
1388 			int sdx = 0;
1389 			bool found = false;
1390 
1391 			if (*p == '/') {
1392 			    sdirs[sdx++] = p; /* done */
1393 			} else {
1394 			    if (strcmp(".", p) == 0)
1395 				continue; /* no point */
1396 
1397 			    /* Check vs latestdir */
1398 			    if (snprintf(fname1, sizeof fname1, "%s/%s", latestdir, p) < (int)(sizeof fname1))
1399 				sdirs[sdx++] = fname1;
1400 
1401 			    if (strcmp(latestdir, lcwd) != 0) {
1402 				/* Check vs lcwd */
1403 				if (snprintf(fname2, sizeof fname2, "%s/%s", lcwd, p) < (int)(sizeof fname2))
1404 				    sdirs[sdx++] = fname2;
1405 			    }
1406 			    if (strcmp(lcwd, cwd) != 0) {
1407 				/* Check vs cwd */
1408 				if (snprintf(fname3, sizeof fname3, "%s/%s", cwd, p) < (int)(sizeof fname3))
1409 				    sdirs[sdx++] = fname3;
1410 			    }
1411 			}
1412 			sdirs[sdx++] = NULL;
1413 
1414 			for (sdp = sdirs; *sdp != NULL && !found; sdp++) {
1415 #ifdef DEBUG_META_MODE
1416 			    DEBUG3(META, "%s:%u: looking for: %s\n",
1417 				   fname, lineno, *sdp);
1418 #endif
1419 			    if (cached_stat(*sdp, &cst) == 0) {
1420 				found = true;
1421 				p = *sdp;
1422 			    }
1423 			}
1424 			if (found) {
1425 #ifdef DEBUG_META_MODE
1426 			    DEBUG3(META, "%s:%u: found: %s\n",
1427 				   fname, lineno, p);
1428 #endif
1429 			    if (!S_ISDIR(cst.cst_mode) &&
1430 				cst.cst_mtime > gn->mtime) {
1431 				DEBUG3(META, "%s:%u: file '%s' is newer than the target...\n",
1432 				       fname, lineno, p);
1433 				oodate = true;
1434 			    } else if (S_ISDIR(cst.cst_mode)) {
1435 				/* Update the latest directory. */
1436 				cached_realpath(p, latestdir);
1437 			    }
1438 			} else if (errno == ENOENT && *p == '/' &&
1439 				   strncmp(p, cwd, cwdlen) != 0) {
1440 			    /*
1441 			     * A referenced file outside of CWD is missing.
1442 			     * We cannot catch every eventuality here...
1443 			     */
1444 			    append_if_new(&missingFiles, p);
1445 			}
1446 		    }
1447 		    if (buf[0] == 'E') {
1448 			/* previous latestdir is no longer relevant */
1449 			strlcpy(latestdir, lcwd, sizeof latestdir);
1450 		    }
1451 		    break;
1452 		default:
1453 		    break;
1454 		}
1455 		if (!oodate && buf[0] == 'L' && link_src != NULL)
1456 		    goto check_link_src;
1457 	    } else if (strcmp(buf, "CMD") == 0) {
1458 		/*
1459 		 * Compare the current command with the one in the
1460 		 * meta data file.
1461 		 */
1462 		if (cmdNode == NULL) {
1463 		    DEBUG2(META, "%s:%u: there were more build commands in the meta data file than there are now...\n",
1464 			   fname, lineno);
1465 		    oodate = true;
1466 		} else {
1467 		    const char *cp;
1468 		    char *cmd = cmdNode->datum;
1469 		    bool hasOODATE = false;
1470 
1471 		    if (strstr(cmd, "$?") != NULL)
1472 			hasOODATE = true;
1473 		    else if ((cp = strstr(cmd, ".OODATE")) != NULL) {
1474 			/* check for $[{(].OODATE[:)}] */
1475 			if (cp > cmd + 2 && cp[-2] == '$')
1476 			    hasOODATE = true;
1477 		    }
1478 		    if (hasOODATE) {
1479 			needOODATE = true;
1480 			DEBUG2(META, "%s:%u: cannot compare command using .OODATE\n",
1481 			       fname, lineno);
1482 		    }
1483 		    cmd = Var_Subst(cmd, gn, VARE_EVAL_DEFINED);
1484 		    /* TODO: handle errors */
1485 
1486 		    if ((cp = strchr(cmd, '\n')) != NULL) {
1487 			int n;
1488 
1489 			/*
1490 			 * This command contains newlines, we need to
1491 			 * fetch more from the .meta file before we
1492 			 * attempt a comparison.
1493 			 */
1494 			/* first put the newline back at buf[x - 1] */
1495 			buf[x - 1] = '\n';
1496 			do {
1497 			    /* now fetch the next line */
1498 			    if ((n = fgetLine(&buf, &bufsz, x, fp)) <= 0)
1499 				break;
1500 			    x = n;
1501 			    lineno++;
1502 			    if (buf[x - 1] != '\n') {
1503 				warnx("%s:%u: line truncated at %u", fname, lineno, x);
1504 				break;
1505 			    }
1506 			    cp = strchr(cp + 1, '\n');
1507 			} while (cp != NULL);
1508 			if (buf[x - 1] == '\n')
1509 			    buf[x - 1] = '\0';
1510 		    }
1511 		    if (p != NULL &&
1512 			!hasOODATE &&
1513 			!(gn->type & OP_NOMETA_CMP) &&
1514 			(meta_cmd_cmp(gn, p, cmd, cmp_filter) != 0)) {
1515 			DEBUG4(META, "%s:%u: a build command has changed\n%s\nvs\n%s\n",
1516 			       fname, lineno, p, cmd);
1517 			if (!metaIgnoreCMDs)
1518 			    oodate = true;
1519 		    }
1520 		    free(cmd);
1521 		    cmdNode = cmdNode->next;
1522 		}
1523 	    } else if (strcmp(buf, "CWD") == 0) {
1524 		/*
1525 		 * Check if there are extra commands now
1526 		 * that weren't in the meta data file.
1527 		 */
1528 		if (!oodate && cmdNode != NULL) {
1529 		    DEBUG2(META, "%s:%u: there are extra build commands now that weren't in the meta data file\n",
1530 			   fname, lineno);
1531 		    oodate = true;
1532 		}
1533 		CHECK_VALID_META(p);
1534 		if (strcmp(p, cwd) != 0) {
1535 		    DEBUG4(META, "%s:%u: the current working directory has changed from '%s' to '%s'\n",
1536 			   fname, lineno, p, curdir);
1537 		    oodate = true;
1538 		}
1539 	    }
1540 	}
1541 
1542 	fclose(fp);
1543 	if (!Lst_IsEmpty(&missingFiles)) {
1544 	    DEBUG2(META, "%s: missing files: %s...\n",
1545 		   fname, (char *)missingFiles.first->datum);
1546 	    oodate = true;
1547 	}
1548 	if (!oodate && !have_filemon && filemonMissing) {
1549 	    DEBUG1(META, "%s: missing filemon data\n", fname);
1550 	    oodate = true;
1551 	}
1552     } else {
1553 	if (writeMeta && (metaMissing || (gn->type & OP_META))) {
1554 	    const char *cp = NULL;
1555 
1556 	    /* if target is in .CURDIR we do not need a meta file */
1557 	    if (gn->path != NULL && (cp = strrchr(gn->path, '/')) != NULL &&
1558 		(cp > gn->path)) {
1559 		if (strncmp(curdir, gn->path, (size_t)(cp - gn->path)) != 0) {
1560 		    cp = NULL;		/* not in .CURDIR */
1561 		}
1562 	    }
1563 	    if (cp == NULL) {
1564 		DEBUG1(META, "%s: required but missing\n", fname);
1565 		oodate = true;
1566 		needOODATE = true;	/* assume the worst */
1567 	    }
1568 	}
1569     }
1570 
1571     Lst_DoneFree(&missingFiles);
1572 
1573     if (oodate && needOODATE) {
1574 	/*
1575 	 * Target uses .OODATE which is empty; or we wouldn't be here.
1576 	 * We have decided it is oodate, so .OODATE needs to be set.
1577 	 * All we can sanely do is set it to .ALLSRC.
1578 	 */
1579 	Var_Delete(gn, OODATE);
1580 	Var_Set(gn, OODATE, GNode_VarAllsrc(gn));
1581     }
1582 
1583  oodate_out:
1584     FStr_Done(&dname);
1585     return oodate;
1586 }
1587 
1588 /* support for compat mode */
1589 
1590 static int childPipe[2];
1591 
1592 void
meta_compat_start(void)1593 meta_compat_start(void)
1594 {
1595 #ifdef USE_FILEMON_ONCE
1596     /*
1597      * We need to re-open filemon for each cmd.
1598      */
1599     BuildMon *pbm = &Mybm;
1600 
1601     if (pbm->mfp != NULL && useFilemon) {
1602 	meta_open_filemon(pbm);
1603     } else {
1604 	pbm->mon_fd = -1;
1605 	pbm->filemon = NULL;
1606     }
1607 #endif
1608     if (pipe(childPipe) < 0)
1609 	Punt("pipe: %s", strerror(errno));
1610     /* Set close-on-exec flag for both */
1611     (void)fcntl(childPipe[0], F_SETFD, FD_CLOEXEC);
1612     (void)fcntl(childPipe[1], F_SETFD, FD_CLOEXEC);
1613 }
1614 
1615 void
meta_compat_child(void)1616 meta_compat_child(void)
1617 {
1618     meta_job_child(NULL);
1619     if (dup2(childPipe[1], STDOUT_FILENO) < 0
1620 	    || dup2(STDOUT_FILENO, STDERR_FILENO) < 0)
1621 	execDie("dup2", "pipe");
1622 }
1623 
1624 void
meta_compat_parent(pid_t child)1625 meta_compat_parent(pid_t child)
1626 {
1627     int outfd, metafd, maxfd, nfds;
1628     char buf[BUFSIZ+1];
1629     fd_set readfds;
1630 
1631     meta_job_parent(NULL, child);
1632     close(childPipe[1]);			/* child side */
1633     outfd = childPipe[0];
1634 #ifdef USE_FILEMON
1635     metafd = Mybm.filemon != NULL ? filemon_readfd(Mybm.filemon) : -1;
1636 #else
1637     metafd = -1;
1638 #endif
1639     maxfd = -1;
1640     if (outfd > maxfd)
1641 	    maxfd = outfd;
1642     if (metafd > maxfd)
1643 	    maxfd = metafd;
1644 
1645     while (outfd != -1 || metafd != -1) {
1646 	FD_ZERO(&readfds);
1647 	if (outfd != -1) {
1648 	    FD_SET(outfd, &readfds);
1649 	}
1650 	if (metafd != -1) {
1651 	    FD_SET(metafd, &readfds);
1652 	}
1653 	nfds = select(maxfd + 1, &readfds, NULL, NULL, NULL);
1654 	if (nfds == -1) {
1655 	    if (errno == EINTR)
1656 		continue;
1657 	    err(1, "select");
1658 	}
1659 
1660 	if (outfd != -1 && FD_ISSET(outfd, &readfds) != 0) do {
1661 	    /* XXX this is not line-buffered */
1662 	    ssize_t nread = read(outfd, buf, sizeof buf - 1);
1663 	    if (nread == -1)
1664 		err(1, "read");
1665 	    if (nread == 0) {
1666 		close(outfd);
1667 		outfd = -1;
1668 		break;
1669 	    }
1670 	    fwrite(buf, 1, (size_t)nread, stdout);
1671 	    fflush(stdout);
1672 	    buf[nread] = '\0';
1673 	    meta_job_output(NULL, buf, (size_t)nread);
1674 	} while (false);
1675 	if (metafd != -1 && FD_ISSET(metafd, &readfds) != 0) {
1676 	    if (meta_job_event(NULL) <= 0)
1677 		metafd = -1;
1678 	}
1679     }
1680 }
1681 
1682 #endif /* USE_META */
1683