1 /* $NetBSD: meta.c,v 1.86 2020/07/11 00:39:53 sjg Exp $ */
4 * Implement 'meta' mode.
5 * Adapted from John Birrell's patches to FreeBSD make.
9 * Copyright (c) 2009-2016, Juniper Networks, Inc.
10 * Portions Copyright (c) 2009, John Birrell.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
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.
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.
41 #elif !defined(HAVE_DIRNAME)
42 char * dirname(char *);
45 #if !defined(HAVE_CONFIG_H) || defined(HAVE_ERR_H)
53 #include "filemon/filemon.h"
56 static BuildMon Mybm; /* for compat */
57 static Lst metaBailiwick; /* our scope of control */
58 static char *metaBailiwickStr; /* string storage for the list */
59 static Lst metaIgnorePaths; /* paths we deliberately ignore */
60 static char *metaIgnorePathsStr; /* string storage for the list */
62 #ifndef MAKE_META_IGNORE_PATHS
63 #define MAKE_META_IGNORE_PATHS ".MAKE.META.IGNORE_PATHS"
65 #ifndef MAKE_META_IGNORE_PATTERNS
66 #define MAKE_META_IGNORE_PATTERNS ".MAKE.META.IGNORE_PATTERNS"
68 #ifndef MAKE_META_IGNORE_FILTER
69 #define MAKE_META_IGNORE_FILTER ".MAKE.META.IGNORE_FILTER"
72 Boolean useMeta = FALSE;
73 static Boolean useFilemon = FALSE;
74 static Boolean writeMeta = FALSE;
75 static Boolean metaMissing = FALSE; /* oodate if missing */
76 static Boolean filemonMissing = FALSE; /* oodate if missing */
77 static Boolean metaEnv = FALSE; /* don't save env unless asked */
78 static Boolean metaVerbose = FALSE;
79 static Boolean metaIgnoreCMDs = FALSE; /* ignore CMDs in .meta files */
80 static Boolean metaIgnorePatterns = FALSE; /* do we need to do pattern matches */
81 static Boolean metaIgnoreFilter = FALSE; /* do we have more complex filtering? */
82 static Boolean metaCurdirOk = FALSE; /* write .meta in .CURDIR Ok? */
83 static Boolean metaSilent = FALSE; /* if we have a .meta be SILENT */
85 extern Boolean forceJobs;
86 extern Boolean comatMake;
87 extern char **environ;
89 #define MAKE_META_PREFIX ".MAKE.META.PREFIX"
92 # define N2U(n, u) (((n) + ((u) - 1)) / (u))
95 # define ROUNDUP(n, u) (N2U((n), (u)) * (u))
98 #if !defined(HAVE_STRSEP)
99 # define strsep(s, d) stresep((s), (d), 0)
103 * Filemon is a kernel module which snoops certain syscalls.
114 * See meta_oodate below - we mainly care about 'E' and 'R'.
116 * We can still use meta mode without filemon, but
117 * the benefits are more limited.
122 * Open the filemon device.
125 meta_open_filemon(BuildMon *pbm)
131 if (!useFilemon || !pbm->mfp)
134 pbm->filemon = filemon_open();
135 if (pbm->filemon == NULL) {
137 warn("Could not open filemon %s", filemon_path());
142 * We use a file outside of '.'
143 * to avoid a FreeBSD kernel bug where unlink invalidates
144 * cwd causing getcwd to do a lot more work.
145 * We only care about the descriptor.
147 pbm->mon_fd = mkTempFile("filemon.XXXXXX", NULL);
148 if ((dupfd = dup(pbm->mon_fd)) == -1) {
149 err(1, "Could not dup filemon output!");
151 (void)fcntl(dupfd, F_SETFD, FD_CLOEXEC);
152 if (filemon_setfd(pbm->filemon, dupfd) == -1) {
153 err(1, "Could not set filemon file descriptor!");
155 /* we don't need these once we exec */
156 (void)fcntl(pbm->mon_fd, F_SETFD, FD_CLOEXEC);
160 * Read the build monitor output file and write records to the target's
164 filemon_read(FILE *mfp, int fd)
170 /* Check if we're not writing to a meta data file.*/
173 close(fd); /* not interested */
177 if (lseek(fd, (off_t)0, SEEK_SET) < 0) {
179 warn("Could not rewind filemon");
183 fprintf(mfp, "\n-- filemon acquired metadata --\n");
185 while ((n = read(fd, buf, sizeof(buf))) > 0) {
186 if ((int)fwrite(buf, 1, n, mfp) < n)
198 * when realpath() fails,
199 * we use this, to clean up ./ and ../
202 eat_dots(char *buf, size_t bufsz, int dots)
223 cp = strstr(buf, eat);
226 if (dots == 2 && cp > buf) {
229 } while (cp > buf && *cp != '/');
232 strlcpy(cp, cp2, bufsz - (cp - buf));
234 return; /* can't happen? */
241 meta_name(char *mname, size_t mnamelen,
246 char buf[MAXPATHLEN];
254 * Weed out relative paths from the target file name.
255 * We have to be careful though since if target is a
256 * symlink, the result will be unstable.
257 * So we use realpath() just to get the dirname, and leave the
258 * basename as given to us.
260 if ((cp = strrchr(tname, '/'))) {
261 if (cached_realpath(tname, buf)) {
262 if ((rp = strrchr(buf, '/'))) {
265 if (strcmp(cp, rp) != 0)
266 strlcpy(rp, cp, sizeof(buf) - (rp - buf));
271 * We likely have a directory which is about to be made.
272 * We pretend realpath() succeeded, to have a chance
273 * of generating the same meta file name that we will
276 if (tname[0] == '/') {
277 strlcpy(buf, tname, sizeof(buf));
279 snprintf(buf, sizeof(buf), "%s/%s", cwd, tname);
281 eat_dots(buf, sizeof(buf), 1); /* ./ */
282 eat_dots(buf, sizeof(buf), 2); /* ../ */
286 /* on some systems dirname may modify its arg */
287 tp = bmake_strdup(tname);
289 if (strcmp(dname, dtp) == 0)
290 snprintf(mname, mnamelen, "%s.meta", tname);
292 ldname = strlen(dname);
293 if (strncmp(dname, dtp, ldname) == 0 && dtp[ldname] == '/')
294 snprintf(mname, mnamelen, "%s/%s.meta", dname, &tname[ldname+1]);
296 snprintf(mname, mnamelen, "%s/%s.meta", dname, tname);
299 * Replace path separators in the file name after the
300 * current object directory path.
302 cp = mname + strlen(dname) + 1;
304 while (*cp != '\0') {
315 * Return true if running ${.MAKE}
316 * Bypassed if target is flagged .MAKE
319 is_submake(void *cmdp, void *gnp)
321 static char *p_make = NULL;
328 int rc = 0; /* keep looking */
331 p_make = Var_Value(".MAKE", gn, &cp);
332 p_len = strlen(p_make);
334 cp = strchr(cmd, '$');
336 mp = Var_Subst(NULL, cmd, gn, VARF_WANTRES);
339 cp2 = strstr(cmd, p_make);
341 switch (cp2[p_len]) {
349 if (cp2 > cmd && rc > 0) {
356 rc = 0; /* no match */
365 typedef struct meta_file_s {
371 printCMD(void *cmdp, void *mfpp)
373 meta_file_t *mfp = mfpp;
377 if (strchr(cmd, '$')) {
378 cmd = cp = Var_Subst(NULL, cmd, mfp->gn, VARF_WANTRES);
380 fprintf(mfp->fp, "CMD %s\n", cmd);
386 * Certain node types never get a .meta file
388 #define SKIP_META_TYPE(_type) do { \
389 if ((gn->type & __CONCAT(OP_, _type))) { \
391 fprintf(debug_file, "Skipping meta for %s: .%s\n", \
392 gn->name, __STRING(_type)); \
400 * Do we need/want a .meta file ?
403 meta_needed(GNode *gn, const char *dname,
404 char *objdir, int verbose)
409 verbose = DEBUG(META);
411 /* This may be a phony node which we don't want meta data for... */
412 /* Skip .meta for .BEGIN, .END, .ERROR etc as well. */
413 /* Or it may be explicitly flagged as .NOMETA */
414 SKIP_META_TYPE(NOMETA);
415 /* Unless it is explicitly flagged as .META */
416 if (!(gn->type & OP_META)) {
417 SKIP_META_TYPE(PHONY);
418 SKIP_META_TYPE(SPECIAL);
419 SKIP_META_TYPE(MAKE);
422 /* Check if there are no commands to execute. */
423 if (Lst_IsEmpty(gn->commands)) {
425 fprintf(debug_file, "Skipping meta for %s: no commands\n",
429 if ((gn->type & (OP_META|OP_SUBMAKE)) == OP_SUBMAKE) {
430 /* OP_SUBMAKE is a bit too aggressive */
431 if (Lst_ForEach(gn->commands, is_submake, gn)) {
433 fprintf(debug_file, "Skipping meta for %s: .SUBMAKE\n",
439 /* The object directory may not exist. Check it.. */
440 if (cached_stat(dname, &fs) != 0) {
442 fprintf(debug_file, "Skipping meta for %s: no .OBJDIR\n",
447 /* make sure these are canonical */
448 if (cached_realpath(dname, objdir))
451 /* If we aren't in the object directory, don't create a meta file. */
452 if (!metaCurdirOk && strcmp(curdir, dname) == 0) {
454 fprintf(debug_file, "Skipping meta for %s: .OBJDIR == .CURDIR\n",
463 meta_create(BuildMon *pbm, GNode *gn)
466 char buf[MAXPATHLEN];
467 char objdir[MAXPATHLEN];
473 char *p[5]; /* >= possible uses */
479 dname = Var_Value(".OBJDIR", gn, &p[i++]);
480 tname = Var_Value(TARGET, gn, &p[i++]);
482 /* if this succeeds objdir is realpath of dname */
483 if (!meta_needed(gn, dname, objdir, TRUE))
490 /* Describe the target we are building */
491 mp = Var_Subst(NULL, "${" MAKE_META_PREFIX "}", gn, VARF_WANTRES);
493 fprintf(stdout, "%s\n", mp);
496 /* Get the basename of the target */
497 if ((cp = strrchr(tname, '/')) == NULL) {
506 /* Don't create meta data. */
509 fname = meta_name(pbm->meta_fname, sizeof(pbm->meta_fname),
510 dname, tname, objdir);
512 #ifdef DEBUG_META_MODE
514 fprintf(debug_file, "meta_create: %s\n", fname);
517 if ((mf.fp = fopen(fname, "w")) == NULL)
518 err(1, "Could not open meta file '%s'", fname);
520 fprintf(mf.fp, "# Meta data file %s\n", fname);
524 Lst_ForEach(gn->commands, printCMD, &mf);
526 fprintf(mf.fp, "CWD %s\n", getcwd(buf, sizeof(buf)));
527 fprintf(mf.fp, "TARGET %s\n", tname);
528 cp = Var_Value(".OODATE", gn, &p[i++]);
530 fprintf(mf.fp, "OODATE %s\n", cp);
533 for (ptr = environ; *ptr != NULL; ptr++)
534 fprintf(mf.fp, "ENV %s\n", *ptr);
537 fprintf(mf.fp, "-- command output --\n");
540 Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL);
541 Var_Append(".MAKE.META.CREATED", fname, VAR_GLOBAL);
543 gn->type |= OP_META; /* in case anyone wants to know */
545 gn->type |= OP_SILENT;
548 for (i--; i >= 0; i--) {
570 * Initialization we need before reading makefiles.
576 /* this allows makefiles to test if we have filemon support */
577 Var_Set(".MAKE.PATH_FILEMON", filemon_path(), VAR_GLOBAL);
582 #define get_mode_bf(bf, token) \
583 if ((cp = strstr(make_mode, token))) \
584 bf = boolValue(&cp[sizeof(token) - 1])
587 * Initialization we need after reading makefiles.
590 meta_mode_init(const char *make_mode)
600 if (strstr(make_mode, "env"))
602 if (strstr(make_mode, "verb"))
604 if (strstr(make_mode, "read"))
606 if (strstr(make_mode, "nofilemon"))
608 if (strstr(make_mode, "ignore-cmd"))
609 metaIgnoreCMDs = TRUE;
611 get_mode_bf(filemonMissing, "missing-filemon=");
612 get_mode_bf(metaCurdirOk, "curdirok=");
613 get_mode_bf(metaMissing, "missing-meta=");
614 get_mode_bf(metaSilent, "silent=");
616 if (metaVerbose && !Var_Exists(MAKE_META_PREFIX, VAR_GLOBAL)) {
618 * The default value for MAKE_META_PREFIX
619 * prints the absolute path of the target.
620 * This works be cause :H will generate '.' if there is no /
621 * and :tA will resolve that to cwd.
623 Var_Set(MAKE_META_PREFIX, "Building ${.TARGET:H:tA}/${.TARGET:T}", VAR_GLOBAL);
628 memset(&Mybm, 0, sizeof(Mybm));
630 * We consider ourselves master of all within ${.MAKE.META.BAILIWICK}
632 metaBailiwick = Lst_Init(FALSE);
633 metaBailiwickStr = Var_Subst(NULL, "${.MAKE.META.BAILIWICK:O:u:tA}",
634 VAR_GLOBAL, VARF_WANTRES);
635 if (metaBailiwickStr) {
636 str2Lst_Append(metaBailiwick, metaBailiwickStr, NULL);
639 * We ignore any paths that start with ${.MAKE.META.IGNORE_PATHS}
641 metaIgnorePaths = Lst_Init(FALSE);
642 Var_Append(MAKE_META_IGNORE_PATHS,
643 "/dev /etc /proc /tmp /var/run /var/tmp ${TMPDIR}", VAR_GLOBAL);
644 metaIgnorePathsStr = Var_Subst(NULL,
645 "${" MAKE_META_IGNORE_PATHS ":O:u:tA}", VAR_GLOBAL,
647 if (metaIgnorePathsStr) {
648 str2Lst_Append(metaIgnorePaths, metaIgnorePathsStr, NULL);
652 * We ignore any paths that match ${.MAKE.META.IGNORE_PATTERNS}
655 if (Var_Value(MAKE_META_IGNORE_PATTERNS, VAR_GLOBAL, &cp)) {
656 metaIgnorePatterns = TRUE;
660 if (Var_Value(MAKE_META_IGNORE_FILTER, VAR_GLOBAL, &cp)) {
661 metaIgnoreFilter = TRUE;
667 * In each case below we allow for job==NULL
670 meta_job_start(Job *job, GNode *gn)
679 pbm->mfp = meta_create(pbm, gn);
680 #ifdef USE_FILEMON_ONCE
681 /* compat mode we open the filemon dev once per command */
686 if (pbm->mfp != NULL && useFilemon) {
687 meta_open_filemon(pbm);
696 * The child calls this before doing anything.
697 * It does not disturb our state.
700 meta_job_child(Job *job)
710 if (pbm->mfp != NULL) {
711 close(fileno(pbm->mfp));
712 if (useFilemon && pbm->filemon) {
716 if (filemon_setpid_child(pbm->filemon, pid) == -1) {
717 err(1, "Could not set filemon pid!");
725 meta_job_parent(Job *job, pid_t pid)
727 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
735 if (useFilemon && pbm->filemon) {
736 filemon_setpid_parent(pbm->filemon, pid);
742 meta_job_fd(Job *job)
744 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
752 if (useFilemon && pbm->filemon) {
753 return filemon_readfd(pbm->filemon);
760 meta_job_event(Job *job)
762 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
770 if (useFilemon && pbm->filemon) {
771 return filemon_process(pbm->filemon);
778 meta_job_error(Job *job, GNode *gn, int flags, int status)
780 char cwd[MAXPATHLEN];
790 if (pbm->mfp != NULL) {
791 fprintf(pbm->mfp, "\n*** Error code %d%s\n",
793 (flags & JOB_IGNERR) ?
797 Var_Set(".ERROR_TARGET", gn->path ? gn->path : gn->name, VAR_GLOBAL);
799 getcwd(cwd, sizeof(cwd));
800 Var_Set(".ERROR_CWD", cwd, VAR_GLOBAL);
801 if (pbm->meta_fname[0]) {
802 Var_Set(".ERROR_META_FILE", pbm->meta_fname, VAR_GLOBAL);
804 meta_job_finish(job);
808 meta_job_output(Job *job, char *cp, const char *nl)
817 if (pbm->mfp != NULL) {
819 static char *meta_prefix = NULL;
820 static int meta_prefix_len;
825 meta_prefix = Var_Subst(NULL, "${" MAKE_META_PREFIX "}",
826 VAR_GLOBAL, VARF_WANTRES);
827 if ((cp2 = strchr(meta_prefix, '$')))
828 meta_prefix_len = cp2 - meta_prefix;
830 meta_prefix_len = strlen(meta_prefix);
832 if (strncmp(cp, meta_prefix, meta_prefix_len) == 0) {
833 cp = strchr(cp+1, '\n');
838 fprintf(pbm->mfp, "%s%s", cp, nl);
843 meta_cmd_finish(void *pbmp)
846 BuildMon *pbm = pbmp;
856 while (filemon_process(pbm->filemon) > 0)
858 if (filemon_close(pbm->filemon) == -1)
860 x = filemon_read(pbm->mfp, pbm->mon_fd);
861 if (error == 0 && x != 0)
867 fprintf(pbm->mfp, "\n"); /* ensure end with newline */
872 meta_job_finish(Job *job)
883 if (pbm->mfp != NULL) {
884 error = meta_cmd_finish(pbm);
885 x = fclose(pbm->mfp);
886 if (error == 0 && x != 0)
889 pbm->meta_fname[0] = '\0';
897 Lst_Destroy(metaBailiwick, NULL);
898 free(metaBailiwickStr);
899 Lst_Destroy(metaIgnorePaths, NULL);
900 free(metaIgnorePathsStr);
904 * Fetch a full line from fp - growing bufp if needed
905 * Return length in bufp.
908 fgetLine(char **bufp, size_t *szp, int o, FILE *fp)
915 if (fgets(&buf[o], bufsz - o, fp) != NULL) {
917 x = o + strlen(&buf[o]);
918 if (buf[x - 1] == '\n')
921 * We need to grow the buffer.
922 * The meta file can give us a clue.
924 if (fstat(fileno(fp), &fs) == 0) {
928 newsz = ROUNDUP((fs.st_size / 2), BUFSIZ);
930 newsz = ROUNDUP(fs.st_size, BUFSIZ);
932 return x; /* truncated */
934 fprintf(debug_file, "growing buffer %u -> %u\n",
935 (unsigned)bufsz, (unsigned)newsz);
936 p = bmake_realloc(buf, newsz);
939 *szp = bufsz = newsz;
941 if (!fgets(&buf[x], bufsz - x, fp))
942 return x; /* truncated! */
950 /* Lst_ForEach wants 1 to stop search */
952 prefix_match(void *p, void *q)
954 const char *prefix = p;
955 const char *path = q;
956 size_t n = strlen(prefix);
958 return strncmp(path, prefix, n) == 0;
962 * looking for exact or prefix/ match to
963 * Lst_Find wants 0 to stop search
966 path_match(const void *p, const void *q)
968 const char *prefix = q;
969 const char *path = p;
970 size_t n = strlen(prefix);
973 if ((rc = strncmp(path, prefix, n)) == 0) {
986 /* Lst_Find wants 0 to stop search */
988 string_match(const void *p, const void *q)
993 return strcmp(p1, p2);
998 meta_ignore(GNode *gn, const char *p)
1000 char fname[MAXPATHLEN];
1006 cached_realpath(p, fname); /* clean it up */
1007 if (Lst_ForEach(metaIgnorePaths, prefix_match, fname)) {
1008 #ifdef DEBUG_META_MODE
1010 fprintf(debug_file, "meta_oodate: ignoring path: %s\n",
1017 if (metaIgnorePatterns) {
1020 Var_Set(".p.", p, gn);
1021 pm = Var_Subst(NULL,
1022 "${" MAKE_META_IGNORE_PATTERNS ":@m@${.p.:M$m}@}",
1025 #ifdef DEBUG_META_MODE
1027 fprintf(debug_file, "meta_oodate: ignoring pattern: %s\n",
1036 if (metaIgnoreFilter) {
1039 /* skip if filter result is empty */
1040 snprintf(fname, sizeof(fname),
1041 "${%s:L:${%s:ts:}}",
1042 p, MAKE_META_IGNORE_FILTER);
1043 fm = Var_Subst(NULL, fname, gn, VARF_WANTRES);
1045 #ifdef DEBUG_META_MODE
1047 fprintf(debug_file, "meta_oodate: ignoring filtered: %s\n",
1059 * When running with 'meta' functionality, a target can be out-of-date
1060 * if any of the references in its meta data file is more recent.
1061 * We have to track the latestdir on a per-process basis.
1063 #define LCWD_VNAME_FMT ".meta.%d.lcwd"
1064 #define LDIR_VNAME_FMT ".meta.%d.ldir"
1067 * It is possible that a .meta file is corrupted,
1068 * if we detect this we want to reproduce it.
1069 * Setting oodate TRUE will have that effect.
1071 #define CHECK_VALID_META(p) if (!(p && *p)) { \
1072 warnx("%s: %d: malformed", fname, lineno); \
1077 #define DEQUOTE(p) if (*p == '\'') { \
1080 if ((ep = strchr(p, '\''))) \
1085 meta_oodate(GNode *gn, Boolean oodate)
1087 static char *tmpdir = NULL;
1088 static char cwd[MAXPATHLEN];
1089 char lcwd_vname[64];
1090 char ldir_vname[64];
1091 char lcwd[MAXPATHLEN];
1092 char latestdir[MAXPATHLEN];
1093 char fname[MAXPATHLEN];
1094 char fname1[MAXPATHLEN];
1095 char fname2[MAXPATHLEN];
1096 char fname3[MAXPATHLEN];
1103 static size_t cwdlen = 0;
1104 static size_t tmplen = 0;
1106 Boolean needOODATE = FALSE;
1108 char *pa[4]; /* >= possible uses */
1110 int have_filemon = FALSE;
1113 return oodate; /* we're done */
1117 dname = Var_Value(".OBJDIR", gn, &pa[i++]);
1118 tname = Var_Value(TARGET, gn, &pa[i++]);
1120 /* if this succeeds fname3 is realpath of dname */
1121 if (!meta_needed(gn, dname, fname3, FALSE))
1125 missingFiles = Lst_Init(FALSE);
1128 * We need to check if the target is out-of-date. This includes
1129 * checking if the expanded command has changed. This in turn
1130 * requires that all variables are set in the same way that they
1131 * would be if the target needs to be re-built.
1135 meta_name(fname, sizeof(fname), dname, tname, dname);
1137 #ifdef DEBUG_META_MODE
1139 fprintf(debug_file, "meta_oodate: %s\n", fname);
1142 if ((fp = fopen(fname, "r")) != NULL) {
1143 static char *buf = NULL;
1144 static size_t bufsz;
1154 buf = bmake_malloc(bufsz);
1158 if (getcwd(cwd, sizeof(cwd)) == NULL)
1159 err(1, "Could not get current working directory");
1160 cwdlen = strlen(cwd);
1162 strlcpy(lcwd, cwd, sizeof(lcwd));
1163 strlcpy(latestdir, cwd, sizeof(latestdir));
1166 tmpdir = getTmpdir();
1167 tmplen = strlen(tmpdir);
1170 /* we want to track all the .meta we read */
1171 Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL);
1173 ln = Lst_First(gn->commands);
1174 while (!oodate && (x = fgetLine(&buf, &bufsz, 0, fp)) > 0) {
1176 if (buf[x - 1] == '\n')
1179 warnx("%s: %d: line truncated at %u", fname, lineno, x);
1185 /* Find the start of the build monitor section. */
1186 if (!have_filemon) {
1187 if (strncmp(buf, "-- filemon", 10) == 0) {
1188 have_filemon = TRUE;
1191 if (strncmp(buf, "# buildmon", 10) == 0) {
1192 have_filemon = TRUE;
1197 /* Delimit the record type. */
1199 #ifdef DEBUG_META_MODE
1201 fprintf(debug_file, "%s: %d: %s\n", fname, lineno, buf);
1206 * We are in the 'filemon' output section.
1207 * Each record from filemon follows the general form:
1209 * <key> <pid> <data>
1212 * <key> is a single letter, denoting the syscall.
1213 * <pid> is the process that made the syscall.
1214 * <data> is the arguments (of interest).
1217 case '#': /* comment */
1218 case 'V': /* version */
1222 * We need to track pathnames per-process.
1224 * Each process run by make, starts off in the 'CWD'
1225 * recorded in the .meta file, if it chdirs ('C')
1226 * elsewhere we need to track that - but only for
1227 * that process. If it forks ('F'), we initialize
1228 * the child to have the same cwd as its parent.
1230 * We also need to track the 'latestdir' of
1231 * interest. This is usually the same as cwd, but
1232 * not if a process is reading directories.
1234 * Each time we spot a different process ('pid')
1235 * we save the current value of 'latestdir' in a
1236 * variable qualified by 'lastpid', and
1237 * re-initialize 'latestdir' to any pre-saved
1238 * value for the current 'pid' and 'CWD' if none.
1240 CHECK_VALID_META(p);
1242 if (pid > 0 && pid != lastpid) {
1247 /* We need to remember these. */
1248 Var_Set(lcwd_vname, lcwd, VAR_GLOBAL);
1249 Var_Set(ldir_vname, latestdir, VAR_GLOBAL);
1251 snprintf(lcwd_vname, sizeof(lcwd_vname), LCWD_VNAME_FMT, pid);
1252 snprintf(ldir_vname, sizeof(ldir_vname), LDIR_VNAME_FMT, pid);
1254 ldir = Var_Value(ldir_vname, VAR_GLOBAL, &tp);
1256 strlcpy(latestdir, ldir, sizeof(latestdir));
1259 ldir = Var_Value(lcwd_vname, VAR_GLOBAL, &tp);
1261 strlcpy(lcwd, ldir, sizeof(lcwd));
1265 /* Skip past the pid. */
1266 if (strsep(&p, " ") == NULL)
1268 #ifdef DEBUG_META_MODE
1270 fprintf(debug_file, "%s: %d: %d: %c: cwd=%s lcwd=%s ldir=%s\n",
1272 pid, buf[0], cwd, lcwd, latestdir);
1277 CHECK_VALID_META(p);
1279 /* Process according to record type. */
1281 case 'X': /* eXit */
1282 Var_Delete(lcwd_vname, VAR_GLOBAL);
1283 Var_Delete(ldir_vname, VAR_GLOBAL);
1284 lastpid = 0; /* no need to save ldir_vname */
1287 case 'F': /* [v]Fork */
1294 snprintf(cldir, sizeof(cldir), LCWD_VNAME_FMT, child);
1295 Var_Set(cldir, lcwd, VAR_GLOBAL);
1296 snprintf(cldir, sizeof(cldir), LDIR_VNAME_FMT, child);
1297 Var_Set(cldir, latestdir, VAR_GLOBAL);
1298 #ifdef DEBUG_META_MODE
1300 fprintf(debug_file, "%s: %d: %d: cwd=%s lcwd=%s ldir=%s\n",
1302 child, cwd, lcwd, latestdir);
1308 case 'C': /* Chdir */
1309 /* Update lcwd and latest directory. */
1310 strlcpy(latestdir, p, sizeof(latestdir));
1311 strlcpy(lcwd, p, sizeof(lcwd));
1312 Var_Set(lcwd_vname, lcwd, VAR_GLOBAL);
1313 Var_Set(ldir_vname, lcwd, VAR_GLOBAL);
1314 #ifdef DEBUG_META_MODE
1316 fprintf(debug_file, "%s: %d: cwd=%s ldir=%s\n", fname, lineno, cwd, lcwd);
1320 case 'M': /* renaMe */
1322 * For 'M'oves we want to check
1323 * the src as for 'R'ead
1324 * and the target as for 'W'rite.
1326 cp = p; /* save this for a second */
1327 /* now get target */
1328 if (strsep(&p, " ") == NULL)
1330 CHECK_VALID_META(p);
1333 /* 'L' and 'M' put single quotes around the args */
1335 DEQUOTE(move_target);
1337 case 'D': /* unlink */
1338 if (*p == '/' && !Lst_IsEmpty(missingFiles)) {
1339 /* remove any missingFiles entries that match p */
1340 if ((ln = Lst_Find(missingFiles, p,
1341 path_match)) != NULL) {
1346 nln = Lst_FindFrom(missingFiles, Lst_Succ(ln),
1349 Lst_Remove(missingFiles, ln);
1351 } while ((ln = nln) != NULL);
1354 if (buf[0] == 'M') {
1355 /* the target of the mv is a file 'W'ritten */
1356 #ifdef DEBUG_META_MODE
1358 fprintf(debug_file, "meta_oodate: M %s -> %s\n",
1365 case 'L': /* Link */
1368 * the src as for 'R'ead
1369 * and the target as for 'W'rite.
1372 /* now get target */
1373 if (strsep(&p, " ") == NULL)
1375 CHECK_VALID_META(p);
1376 /* 'L' and 'M' put single quotes around the args */
1379 #ifdef DEBUG_META_MODE
1381 fprintf(debug_file, "meta_oodate: L %s -> %s\n",
1385 case 'W': /* Write */
1388 * If a file we generated within our bailiwick
1389 * but outside of .OBJDIR is missing,
1390 * we need to do it again.
1392 /* ignore non-absolute paths */
1396 if (Lst_IsEmpty(metaBailiwick))
1399 /* ignore cwd - normal dependencies handle those */
1400 if (strncmp(p, cwd, cwdlen) == 0)
1403 if (!Lst_ForEach(metaBailiwick, prefix_match, p))
1406 /* tmpdir might be within */
1407 if (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0)
1410 /* ignore anything containing the string "tmp" */
1411 if ((strstr("tmp", p)))
1414 if ((link_src != NULL && cached_lstat(p, &fs) < 0) ||
1415 (link_src == NULL && cached_stat(p, &fs) < 0)) {
1416 if (!meta_ignore(gn, p)) {
1417 if (Lst_Find(missingFiles, p, string_match) == NULL)
1418 Lst_AtEnd(missingFiles, bmake_strdup(p));
1425 #ifdef DEBUG_META_MODE
1427 fprintf(debug_file, "meta_oodate: L src %s\n", p);
1430 case 'R': /* Read */
1431 case 'E': /* Exec */
1433 * Check for runtime files that can't
1434 * be part of the dependencies because
1435 * they are _expected_ to change.
1437 if (meta_ignore(gn, p))
1441 * The rest of the record is the file name.
1442 * Check if it's not an absolute path.
1451 sdirs[sdx++] = p; /* done */
1453 if (strcmp(".", p) == 0)
1454 continue; /* no point */
1456 /* Check vs latestdir */
1457 snprintf(fname1, sizeof(fname1), "%s/%s", latestdir, p);
1458 sdirs[sdx++] = fname1;
1460 if (strcmp(latestdir, lcwd) != 0) {
1462 snprintf(fname2, sizeof(fname2), "%s/%s", lcwd, p);
1463 sdirs[sdx++] = fname2;
1465 if (strcmp(lcwd, cwd) != 0) {
1467 snprintf(fname3, sizeof(fname3), "%s/%s", cwd, p);
1468 sdirs[sdx++] = fname3;
1471 sdirs[sdx++] = NULL;
1473 for (sdp = sdirs; *sdp && !found; sdp++) {
1474 #ifdef DEBUG_META_MODE
1476 fprintf(debug_file, "%s: %d: looking for: %s\n", fname, lineno, *sdp);
1478 if (cached_stat(*sdp, &fs) == 0) {
1484 #ifdef DEBUG_META_MODE
1486 fprintf(debug_file, "%s: %d: found: %s\n", fname, lineno, p);
1488 if (!S_ISDIR(fs.st_mode) &&
1489 fs.st_mtime > gn->mtime) {
1491 fprintf(debug_file, "%s: %d: file '%s' is newer than the target...\n", fname, lineno, p);
1493 } else if (S_ISDIR(fs.st_mode)) {
1494 /* Update the latest directory. */
1495 cached_realpath(p, latestdir);
1497 } else if (errno == ENOENT && *p == '/' &&
1498 strncmp(p, cwd, cwdlen) != 0) {
1500 * A referenced file outside of CWD is missing.
1501 * We cannot catch every eventuality here...
1503 if (Lst_Find(missingFiles, p, string_match) == NULL)
1504 Lst_AtEnd(missingFiles, bmake_strdup(p));
1507 if (buf[0] == 'E') {
1508 /* previous latestdir is no longer relevant */
1509 strlcpy(latestdir, lcwd, sizeof(latestdir));
1515 if (!oodate && buf[0] == 'L' && link_src != NULL)
1516 goto check_link_src;
1517 } else if (strcmp(buf, "CMD") == 0) {
1519 * Compare the current command with the one in the
1524 fprintf(debug_file, "%s: %d: there were more build commands in the meta data file than there are now...\n", fname, lineno);
1527 char *cmd = (char *)Lst_Datum(ln);
1528 Boolean hasOODATE = FALSE;
1530 if (strstr(cmd, "$?"))
1532 else if ((cp = strstr(cmd, ".OODATE"))) {
1533 /* check for $[{(].OODATE[:)}] */
1534 if (cp > cmd + 2 && cp[-2] == '$')
1540 fprintf(debug_file, "%s: %d: cannot compare command using .OODATE\n", fname, lineno);
1542 cmd = Var_Subst(NULL, cmd, gn, VARF_WANTRES|VARF_UNDEFERR);
1544 if ((cp = strchr(cmd, '\n'))) {
1548 * This command contains newlines, we need to
1549 * fetch more from the .meta file before we
1550 * attempt a comparison.
1552 /* first put the newline back at buf[x - 1] */
1555 /* now fetch the next line */
1556 if ((n = fgetLine(&buf, &bufsz, x, fp)) <= 0)
1560 if (buf[x - 1] != '\n') {
1561 warnx("%s: %d: line truncated at %u", fname, lineno, x);
1564 cp = strchr(++cp, '\n');
1566 if (buf[x - 1] == '\n')
1571 !(gn->type & OP_NOMETA_CMP) &&
1572 strcmp(p, cmd) != 0) {
1574 fprintf(debug_file, "%s: %d: a build command has changed\n%s\nvs\n%s\n", fname, lineno, p, cmd);
1575 if (!metaIgnoreCMDs)
1581 } else if (strcmp(buf, "CWD") == 0) {
1583 * Check if there are extra commands now
1584 * that weren't in the meta data file.
1586 if (!oodate && ln != NULL) {
1588 fprintf(debug_file, "%s: %d: there are extra build commands now that weren't in the meta data file\n", fname, lineno);
1591 CHECK_VALID_META(p);
1592 if (strcmp(p, cwd) != 0) {
1594 fprintf(debug_file, "%s: %d: the current working directory has changed from '%s' to '%s'\n", fname, lineno, p, curdir);
1601 if (!Lst_IsEmpty(missingFiles)) {
1603 fprintf(debug_file, "%s: missing files: %s...\n",
1604 fname, (char *)Lst_Datum(Lst_First(missingFiles)));
1607 if (!oodate && !have_filemon && filemonMissing) {
1609 fprintf(debug_file, "%s: missing filemon data\n", fname);
1613 if (writeMeta && (metaMissing || (gn->type & OP_META))) {
1616 /* if target is in .CURDIR we do not need a meta file */
1617 if (gn->path && (cp = strrchr(gn->path, '/')) && cp > gn->path) {
1618 if (strncmp(curdir, gn->path, (cp - gn->path)) != 0) {
1619 cp = NULL; /* not in .CURDIR */
1624 fprintf(debug_file, "%s: required but missing\n", fname);
1626 needOODATE = TRUE; /* assume the worst */
1631 Lst_Destroy(missingFiles, (FreeProc *)free);
1633 if (oodate && needOODATE) {
1635 * Target uses .OODATE which is empty; or we wouldn't be here.
1636 * We have decided it is oodate, so .OODATE needs to be set.
1637 * All we can sanely do is set it to .ALLSRC.
1639 Var_Delete(OODATE, gn);
1640 Var_Set(OODATE, Var_Value(ALLSRC, gn, &cp), gn);
1645 for (i--; i >= 0; i--) {
1651 /* support for compat mode */
1653 static int childPipe[2];
1656 meta_compat_start(void)
1658 #ifdef USE_FILEMON_ONCE
1660 * We need to re-open filemon for each cmd.
1662 BuildMon *pbm = &Mybm;
1664 if (pbm->mfp != NULL && useFilemon) {
1665 meta_open_filemon(pbm);
1668 pbm->filemon = NULL;
1671 if (pipe(childPipe) < 0)
1672 Punt("Cannot create pipe: %s", strerror(errno));
1673 /* Set close-on-exec flag for both */
1674 (void)fcntl(childPipe[0], F_SETFD, FD_CLOEXEC);
1675 (void)fcntl(childPipe[1], F_SETFD, FD_CLOEXEC);
1679 meta_compat_child(void)
1681 meta_job_child(NULL);
1682 if (dup2(childPipe[1], 1) < 0 ||
1684 execError("dup2", "pipe");
1690 meta_compat_parent(pid_t child)
1692 int outfd, metafd, maxfd, nfds;
1696 meta_job_parent(NULL, child);
1697 close(childPipe[1]); /* child side */
1698 outfd = childPipe[0];
1700 metafd = Mybm.filemon ? filemon_readfd(Mybm.filemon) : -1;
1710 while (outfd != -1 || metafd != -1) {
1713 FD_SET(outfd, &readfds);
1716 FD_SET(metafd, &readfds);
1718 nfds = select(maxfd + 1, &readfds, NULL, NULL, NULL);
1725 if (outfd != -1 && FD_ISSET(outfd, &readfds)) do {
1726 /* XXX this is not line-buffered */
1727 ssize_t nread = read(outfd, buf, sizeof(buf) - 1);
1735 fwrite(buf, 1, (size_t)nread, stdout);
1738 meta_job_output(NULL, buf, "");
1740 if (metafd != -1 && FD_ISSET(metafd, &readfds)) {
1741 if (meta_job_event(NULL) <= 0)
1747 #endif /* USE_META */