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