1 /* $NetBSD: meta.c,v 1.200 2022/04/15 12:28:16 rillig 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)
54 #include "filemon/filemon.h"
57 static BuildMon Mybm; /* for compat */
58 static StringList metaBailiwick = LST_INIT; /* our scope of control */
59 static char *metaBailiwickStr; /* string storage for the list */
60 static StringList metaIgnorePaths = LST_INIT; /* paths we deliberately ignore */
61 static char *metaIgnorePathsStr; /* string storage for the list */
63 #ifndef MAKE_META_IGNORE_PATHS
64 #define MAKE_META_IGNORE_PATHS ".MAKE.META.IGNORE_PATHS"
66 #ifndef MAKE_META_IGNORE_PATTERNS
67 #define MAKE_META_IGNORE_PATTERNS ".MAKE.META.IGNORE_PATTERNS"
69 #ifndef MAKE_META_IGNORE_FILTER
70 #define MAKE_META_IGNORE_FILTER ".MAKE.META.IGNORE_FILTER"
72 #ifndef MAKE_META_CMP_FILTER
73 #define MAKE_META_CMP_FILTER ".MAKE.META.CMP_FILTER"
77 static bool useFilemon = false;
78 static bool writeMeta = false;
79 static bool metaMissing = false; /* oodate if missing */
80 static bool filemonMissing = false; /* oodate if missing */
81 static bool metaEnv = false; /* don't save env unless asked */
82 static bool metaVerbose = false;
83 static bool metaIgnoreCMDs = false; /* ignore CMDs in .meta files */
84 static bool metaIgnorePatterns = false; /* do we need to do pattern matches */
85 static bool metaIgnoreFilter = false; /* do we have more complex filtering? */
86 static bool metaCmpFilter = false; /* do we have CMP_FILTER ? */
87 static bool metaCurdirOk = false; /* write .meta in .CURDIR Ok? */
88 static bool metaSilent = false; /* if we have a .meta be SILENT */
90 extern bool forceJobs;
91 extern char **environ;
93 #define MAKE_META_PREFIX ".MAKE.META.PREFIX"
96 # define N2U(n, u) (((n) + ((u) - 1)) / (u))
99 # define ROUNDUP(n, u) (N2U((n), (u)) * (u))
102 #if !defined(HAVE_STRSEP)
103 # define strsep(s, d) stresep((s), (d), '\0')
105 #if !defined(HAVE_STRESEP)
106 char * stresep(char **, const char *, int);
110 * Filemon is a kernel module which snoops certain syscalls.
121 * See meta_oodate below - we mainly care about 'E' and 'R'.
123 * We can still use meta mode without filemon, but
124 * the benefits are more limited.
129 * Open the filemon device.
132 meta_open_filemon(BuildMon *pbm)
138 if (!useFilemon || pbm->mfp == NULL)
141 pbm->filemon = filemon_open();
142 if (pbm->filemon == NULL) {
144 warn("Could not open filemon %s", filemon_path());
149 * We use a file outside of '.'
150 * to avoid a FreeBSD kernel bug where unlink invalidates
151 * cwd causing getcwd to do a lot more work.
152 * We only care about the descriptor.
154 if (!opts.compatMake)
155 pbm->mon_fd = Job_TempFile("filemon.XXXXXX", NULL, 0);
157 pbm->mon_fd = mkTempFile("filemon.XXXXXX", NULL, 0);
158 if ((dupfd = dup(pbm->mon_fd)) == -1) {
159 Punt("Could not dup filemon output: %s", strerror(errno));
161 (void)fcntl(dupfd, F_SETFD, FD_CLOEXEC);
162 if (filemon_setfd(pbm->filemon, dupfd) == -1) {
163 Punt("Could not set filemon file descriptor: %s", strerror(errno));
165 /* we don't need these once we exec */
166 (void)fcntl(pbm->mon_fd, F_SETFD, FD_CLOEXEC);
170 * Read the build monitor output file and write records to the target's
174 filemon_read(FILE *mfp, int fd)
179 /* Check if we're not writing to a meta data file.*/
182 close(fd); /* not interested */
186 if (lseek(fd, (off_t)0, SEEK_SET) < 0) {
188 warn("Could not rewind filemon");
194 fprintf(mfp, "\n-- filemon acquired metadata --\n");
196 while ((n = read(fd, buf, sizeof buf)) > 0) {
197 if ((ssize_t)fwrite(buf, 1, (size_t)n, mfp) < n)
201 if (fflush(mfp) != 0)
202 Punt("Cannot write filemon data to meta file: %s",
211 * when realpath() fails,
212 * we use this, to clean up ./ and ../
219 while ((p = strstr(buf, "/./")) != NULL)
220 memmove(p, p + 2, strlen(p + 2) + 1);
222 while ((p = strstr(buf, "/../")) != NULL) {
227 } while (p > buf && *p != '/');
230 memmove(p, p2, strlen(p2) + 1);
232 return; /* can't happen? */
237 meta_name(char *mname, size_t mnamelen,
242 char buf[MAXPATHLEN];
244 const char *tname_base;
250 * Weed out relative paths from the target file name.
251 * We have to be careful though since if target is a
252 * symlink, the result will be unstable.
253 * So we use realpath() just to get the dirname, and leave the
254 * basename as given to us.
256 if ((tname_base = strrchr(tname, '/')) != NULL) {
257 if (cached_realpath(tname, buf) != NULL) {
258 if ((rp = strrchr(buf, '/')) != NULL) {
261 if (strcmp(tname_base, rp) != 0)
262 strlcpy(rp, tname_base, sizeof buf - (size_t)(rp - buf));
267 * We likely have a directory which is about to be made.
268 * We pretend realpath() succeeded, to have a chance
269 * of generating the same meta file name that we will
272 if (tname[0] == '/') {
273 strlcpy(buf, tname, sizeof buf);
275 snprintf(buf, sizeof buf, "%s/%s", cwd, tname);
281 /* on some systems dirname may modify its arg */
282 tp = bmake_strdup(tname);
284 if (strcmp(dname, dtp) == 0)
285 snprintf(mname, mnamelen, "%s.meta", tname);
287 ldname = strlen(dname);
288 if (strncmp(dname, dtp, ldname) == 0 && dtp[ldname] == '/')
289 snprintf(mname, mnamelen, "%s/%s.meta", dname, &tname[ldname+1]);
291 snprintf(mname, mnamelen, "%s/%s.meta", dname, tname);
294 * Replace path separators in the file name after the
295 * current object directory path.
297 cp = mname + strlen(dname) + 1;
299 while (*cp != '\0') {
310 * Return true if running ${.MAKE}
311 * Bypassed if target is flagged .MAKE
314 is_submake(const char *cmd, GNode *gn)
316 static const char *p_make = NULL;
322 if (p_make == NULL) {
323 p_make = Var_Value(gn, ".MAKE").str;
324 p_len = strlen(p_make);
326 if (strchr(cmd, '$') != NULL) {
327 (void)Var_Subst(cmd, gn, VARE_WANTRES, &mp);
328 /* TODO: handle errors */
331 cp2 = strstr(cmd, p_make);
333 switch (cp2[p_len]) {
341 if (cp2 > cmd && rc) {
348 rc = false; /* no match */
358 any_is_submake(GNode *gn)
362 for (ln = gn->commands.first; ln != NULL; ln = ln->next)
363 if (is_submake(ln->datum, gn))
369 printCMD(const char *ucmd, FILE *fp, GNode *gn)
371 FStr xcmd = FStr_InitRefer(ucmd);
373 Var_Expand(&xcmd, gn, VARE_WANTRES);
374 fprintf(fp, "CMD %s\n", xcmd.str);
379 printCMDs(GNode *gn, FILE *fp)
383 for (ln = gn->commands.first; ln != NULL; ln = ln->next)
384 printCMD(ln->datum, fp, gn);
388 * Certain node types never get a .meta file
390 #define SKIP_META_TYPE(flag, str) do { \
391 if ((gn->type & (flag))) { \
393 debug_printf("Skipping meta for %s: .%s\n", gn->name, str); \
400 * Do we need/want a .meta file ?
403 meta_needed(GNode *gn, const char *dname,
404 char *objdir_realpath, bool verbose)
406 struct cached_stat cst;
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(OP_NOMETA, "NOMETA");
415 /* Unless it is explicitly flagged as .META */
416 if (!(gn->type & OP_META)) {
417 SKIP_META_TYPE(OP_PHONY, "PHONY");
418 SKIP_META_TYPE(OP_SPECIAL, "SPECIAL");
419 SKIP_META_TYPE(OP_MAKE, "MAKE");
422 /* Check if there are no commands to execute. */
423 if (Lst_IsEmpty(&gn->commands)) {
425 debug_printf("Skipping meta for %s: no commands\n", gn->name);
428 if ((gn->type & (OP_META|OP_SUBMAKE)) == OP_SUBMAKE) {
429 /* OP_SUBMAKE is a bit too aggressive */
430 if (any_is_submake(gn)) {
431 DEBUG1(META, "Skipping meta for %s: .SUBMAKE\n", gn->name);
436 /* The object directory may not exist. Check it.. */
437 if (cached_stat(dname, &cst) != 0) {
439 debug_printf("Skipping meta for %s: no .OBJDIR\n", gn->name);
443 /* make sure these are canonical */
444 if (cached_realpath(dname, objdir_realpath) != NULL)
445 dname = objdir_realpath;
447 /* If we aren't in the object directory, don't create a meta file. */
448 if (!metaCurdirOk && strcmp(curdir, dname) == 0) {
450 debug_printf("Skipping meta for %s: .OBJDIR == .CURDIR\n",
459 meta_create(BuildMon *pbm, GNode *gn)
462 char buf[MAXPATHLEN];
463 char objdir_realpath[MAXPATHLEN];
472 dname = Var_Value(gn, ".OBJDIR");
473 tname = GNode_VarTarget(gn);
475 /* if this succeeds objdir_realpath is realpath of dname */
476 if (!meta_needed(gn, dname.str, objdir_realpath, true))
478 dname.str = objdir_realpath;
483 /* Describe the target we are building */
484 (void)Var_Subst("${" MAKE_META_PREFIX "}", gn, VARE_WANTRES, &mp);
485 /* TODO: handle errors */
487 fprintf(stdout, "%s\n", mp);
490 /* Get the basename of the target */
491 cp = str_basename(tname);
496 /* Don't create meta data. */
499 fname = meta_name(pbm->meta_fname, sizeof pbm->meta_fname,
500 dname.str, tname, objdir_realpath);
502 #ifdef DEBUG_META_MODE
503 DEBUG1(META, "meta_create: %s\n", fname);
506 if ((fp = fopen(fname, "w")) == NULL)
507 Punt("Could not open meta file '%s': %s", fname, strerror(errno));
509 fprintf(fp, "# Meta data file %s\n", fname);
513 fprintf(fp, "CWD %s\n", getcwd(buf, sizeof buf));
514 fprintf(fp, "TARGET %s\n", tname);
515 cp = GNode_VarOodate(gn);
516 if (cp != NULL && *cp != '\0') {
517 fprintf(fp, "OODATE %s\n", cp);
520 for (ptr = environ; *ptr != NULL; ptr++)
521 fprintf(fp, "ENV %s\n", *ptr);
524 fprintf(fp, "-- command output --\n");
526 Punt("Cannot write expanded command to meta file: %s",
529 Global_Append(".MAKE.META.FILES", fname);
530 Global_Append(".MAKE.META.CREATED", fname);
532 gn->type |= OP_META; /* in case anyone wants to know */
534 gn->type |= OP_SILENT;
543 boolValue(const char *s)
557 * Initialization we need before reading makefiles.
563 /* this allows makefiles to test if we have filemon support */
564 Global_Set(".MAKE.PATH_FILEMON", filemon_path());
569 #define get_mode_bf(bf, token) \
570 if ((cp = strstr(make_mode, token)) != NULL) \
571 bf = boolValue(cp + sizeof (token) - 1)
574 * Initialization we need after reading makefiles.
577 meta_mode_init(const char *make_mode)
579 static bool once = false;
586 if (make_mode != NULL) {
587 if (strstr(make_mode, "env") != NULL)
589 if (strstr(make_mode, "verb") != NULL)
591 if (strstr(make_mode, "read") != NULL)
593 if (strstr(make_mode, "nofilemon") != NULL)
595 if (strstr(make_mode, "ignore-cmd") != NULL)
596 metaIgnoreCMDs = true;
598 get_mode_bf(filemonMissing, "missing-filemon=");
599 get_mode_bf(metaCurdirOk, "curdirok=");
600 get_mode_bf(metaMissing, "missing-meta=");
601 get_mode_bf(metaSilent, "silent=");
603 if (metaVerbose && !Var_Exists(SCOPE_GLOBAL, MAKE_META_PREFIX)) {
605 * The default value for MAKE_META_PREFIX
606 * prints the absolute path of the target.
607 * This works be cause :H will generate '.' if there is no /
608 * and :tA will resolve that to cwd.
610 Global_Set(MAKE_META_PREFIX,
611 "Building ${.TARGET:H:tA}/${.TARGET:T}");
616 memset(&Mybm, 0, sizeof Mybm);
618 * We consider ourselves master of all within ${.MAKE.META.BAILIWICK}
620 (void)Var_Subst("${.MAKE.META.BAILIWICK:O:u:tA}",
621 SCOPE_GLOBAL, VARE_WANTRES, &metaBailiwickStr);
622 /* TODO: handle errors */
623 str2Lst_Append(&metaBailiwick, metaBailiwickStr);
625 * We ignore any paths that start with ${.MAKE.META.IGNORE_PATHS}
627 Global_Append(MAKE_META_IGNORE_PATHS,
628 "/dev /etc /proc /tmp /var/run /var/tmp ${TMPDIR}");
629 (void)Var_Subst("${" MAKE_META_IGNORE_PATHS ":O:u:tA}",
630 SCOPE_GLOBAL, VARE_WANTRES, &metaIgnorePathsStr);
631 /* TODO: handle errors */
632 str2Lst_Append(&metaIgnorePaths, metaIgnorePathsStr);
635 * We ignore any paths that match ${.MAKE.META.IGNORE_PATTERNS}
637 metaIgnorePatterns = Var_Exists(SCOPE_GLOBAL, MAKE_META_IGNORE_PATTERNS);
638 metaIgnoreFilter = Var_Exists(SCOPE_GLOBAL, MAKE_META_IGNORE_FILTER);
639 metaCmpFilter = Var_Exists(SCOPE_GLOBAL, MAKE_META_CMP_FILTER);
643 * In each case below we allow for job==NULL
646 meta_job_start(Job *job, GNode *gn)
655 pbm->mfp = meta_create(pbm, gn);
656 #ifdef USE_FILEMON_ONCE
657 /* compat mode we open the filemon dev once per command */
662 if (pbm->mfp != NULL && useFilemon) {
663 meta_open_filemon(pbm);
672 * The child calls this before doing anything.
673 * It does not disturb our state.
676 meta_job_child(Job *job MAKE_ATTR_UNUSED)
686 if (pbm->mfp != NULL) {
687 close(fileno(pbm->mfp));
688 if (useFilemon && pbm->filemon != NULL) {
692 if (filemon_setpid_child(pbm->filemon, pid) == -1) {
693 Punt("Could not set filemon pid: %s", strerror(errno));
701 meta_job_parent(Job *job MAKE_ATTR_UNUSED, pid_t pid MAKE_ATTR_UNUSED)
703 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
711 if (useFilemon && pbm->filemon != NULL) {
712 filemon_setpid_parent(pbm->filemon, pid);
718 meta_job_fd(Job *job MAKE_ATTR_UNUSED)
720 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
728 if (useFilemon && pbm->filemon != NULL) {
729 return filemon_readfd(pbm->filemon);
736 meta_job_event(Job *job MAKE_ATTR_UNUSED)
738 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
746 if (useFilemon && pbm->filemon != NULL) {
747 return filemon_process(pbm->filemon);
754 meta_job_error(Job *job, GNode *gn, bool ignerr, int status)
756 char cwd[MAXPATHLEN];
766 if (pbm->mfp != NULL) {
767 fprintf(pbm->mfp, "\n*** Error code %d%s\n",
768 status, ignerr ? "(ignored)" : "");
771 Global_Set(".ERROR_TARGET", GNode_Path(gn));
772 getcwd(cwd, sizeof cwd);
773 Global_Set(".ERROR_CWD", cwd);
774 if (pbm->meta_fname[0] != '\0') {
775 Global_Set(".ERROR_META_FILE", pbm->meta_fname);
777 meta_job_finish(job);
781 meta_job_output(Job *job, char *cp, const char *nl)
790 if (pbm->mfp != NULL) {
792 static char *meta_prefix = NULL;
793 static size_t meta_prefix_len;
795 if (meta_prefix == NULL) {
798 (void)Var_Subst("${" MAKE_META_PREFIX "}",
799 SCOPE_GLOBAL, VARE_WANTRES, &meta_prefix);
800 /* TODO: handle errors */
801 if ((cp2 = strchr(meta_prefix, '$')) != NULL)
802 meta_prefix_len = (size_t)(cp2 - meta_prefix);
804 meta_prefix_len = strlen(meta_prefix);
806 if (strncmp(cp, meta_prefix, meta_prefix_len) == 0) {
807 cp = strchr(cp + 1, '\n');
813 fprintf(pbm->mfp, "%s%s", cp, nl);
818 meta_cmd_finish(void *pbmp)
821 BuildMon *pbm = pbmp;
830 if (pbm->filemon != NULL) {
831 while (filemon_process(pbm->filemon) > 0)
833 if (filemon_close(pbm->filemon) == -1) {
835 Punt("filemon failed: %s", strerror(errno));
837 x = filemon_read(pbm->mfp, pbm->mon_fd);
838 if (error == 0 && x != 0)
846 fprintf(pbm->mfp, "\n"); /* ensure end with newline */
851 meta_job_finish(Job *job)
862 if (pbm->mfp != NULL) {
863 error = meta_cmd_finish(pbm);
864 x = fclose(pbm->mfp);
865 if (error == 0 && x != 0)
868 pbm->meta_fname[0] = '\0';
876 Lst_Done(&metaBailiwick);
877 free(metaBailiwickStr);
878 Lst_Done(&metaIgnorePaths);
879 free(metaIgnorePathsStr);
883 * Fetch a full line from fp - growing bufp if needed
884 * Return length in bufp.
887 fgetLine(char **bufp, size_t *szp, int o, FILE *fp)
894 if (fgets(&buf[o], (int)bufsz - o, fp) != NULL) {
896 x = o + (int)strlen(&buf[o]);
897 if (buf[x - 1] == '\n')
900 * We need to grow the buffer.
901 * The meta file can give us a clue.
903 if (fstat(fileno(fp), &fs) == 0) {
907 newsz = ROUNDUP(((size_t)fs.st_size / 2), BUFSIZ);
909 newsz = ROUNDUP((size_t)fs.st_size, BUFSIZ);
911 return x; /* truncated */
912 DEBUG2(META, "growing buffer %u -> %u\n",
913 (unsigned)bufsz, (unsigned)newsz);
914 p = bmake_realloc(buf, newsz);
916 *szp = bufsz = newsz;
918 if (fgets(&buf[x], (int)bufsz - x, fp) == NULL)
919 return x; /* truncated! */
927 prefix_match(const char *prefix, const char *path)
929 size_t n = strlen(prefix);
931 return strncmp(path, prefix, n) == 0;
935 has_any_prefix(const char *path, StringList *prefixes)
939 for (ln = prefixes->first; ln != NULL; ln = ln->next)
940 if (prefix_match(ln->datum, path))
945 /* See if the path equals prefix or starts with "prefix/". */
947 path_starts_with(const char *path, const char *prefix)
949 size_t n = strlen(prefix);
951 if (strncmp(path, prefix, n) != 0)
953 return path[n] == '\0' || path[n] == '/';
957 meta_ignore(GNode *gn, const char *p)
959 char fname[MAXPATHLEN];
965 cached_realpath(p, fname); /* clean it up */
966 if (has_any_prefix(fname, &metaIgnorePaths)) {
967 #ifdef DEBUG_META_MODE
968 DEBUG1(META, "meta_oodate: ignoring path: %s\n", p);
974 if (metaIgnorePatterns) {
979 * XXX: This variable is set on a target GNode but is not one of
980 * the usual local variables. It should be deleted afterwards.
981 * Ideally it would not be created in the first place, just like
984 Var_Set(gn, ".p.", p);
985 expr = "${" MAKE_META_IGNORE_PATTERNS ":@m@${.p.:M$m}@}";
986 (void)Var_Subst(expr, gn, VARE_WANTRES, &pm);
987 /* TODO: handle errors */
989 #ifdef DEBUG_META_MODE
990 DEBUG1(META, "meta_oodate: ignoring pattern: %s\n", p);
998 if (metaIgnoreFilter) {
1001 /* skip if filter result is empty */
1002 snprintf(fname, sizeof fname,
1003 "${%s:L:${%s:ts:}}",
1004 p, MAKE_META_IGNORE_FILTER);
1005 (void)Var_Subst(fname, gn, VARE_WANTRES, &fm);
1006 /* TODO: handle errors */
1008 #ifdef DEBUG_META_MODE
1009 DEBUG1(META, "meta_oodate: ignoring filtered: %s\n", p);
1020 * When running with 'meta' functionality, a target can be out-of-date
1021 * if any of the references in its meta data file is more recent.
1022 * We have to track the latestdir on a per-process basis.
1024 #define LCWD_VNAME_FMT ".meta.%d.lcwd"
1025 #define LDIR_VNAME_FMT ".meta.%d.ldir"
1028 * It is possible that a .meta file is corrupted,
1029 * if we detect this we want to reproduce it.
1030 * Setting oodate true will have that effect.
1032 #define CHECK_VALID_META(p) if (!(p != NULL && *p != '\0')) { \
1033 warnx("%s: %u: malformed", fname, lineno); \
1038 #define DEQUOTE(p) if (*p == '\'') { \
1041 if ((ep = strchr(p, '\'')) != NULL) \
1046 append_if_new(StringList *list, const char *str)
1050 for (ln = list->first; ln != NULL; ln = ln->next)
1051 if (strcmp(ln->datum, str) == 0)
1053 Lst_Append(list, bmake_strdup(str));
1056 /* A "reserved" variable to store the command to be filtered */
1057 #define META_CMD_FILTER_VAR ".MAKE.cmd_filtered"
1060 meta_filter_cmd(GNode *gn, char *s)
1062 Var_Set(gn, META_CMD_FILTER_VAR, s);
1063 Var_Subst("${" META_CMD_FILTER_VAR ":${" MAKE_META_CMP_FILTER ":ts:}}", gn, VARE_WANTRES, &s);
1068 meta_cmd_cmp(GNode *gn, char *a, char *b, bool filter)
1073 if (rc == 0 || !filter)
1075 a = meta_filter_cmd(gn, a);
1076 b = meta_filter_cmd(gn, b);
1080 Var_Delete(gn, META_CMD_FILTER_VAR);
1085 meta_oodate(GNode *gn, bool 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];
1102 static size_t cwdlen = 0;
1103 static size_t tmplen = 0;
1105 bool needOODATE = false;
1106 StringList missingFiles;
1107 bool have_filemon = false;
1111 return oodate; /* we're done */
1113 dname = Var_Value(gn, ".OBJDIR");
1114 tname = GNode_VarTarget(gn);
1116 /* if this succeeds fname3 is realpath of dname */
1117 if (!meta_needed(gn, dname.str, fname3, false))
1121 Lst_Init(&missingFiles);
1124 * We need to check if the target is out-of-date. This includes
1125 * checking if the expanded command has changed. This in turn
1126 * requires that all variables are set in the same way that they
1127 * would be if the target needs to be re-built.
1129 GNode_SetLocalVars(gn);
1131 meta_name(fname, sizeof fname, dname.str, tname, dname.str);
1133 #ifdef DEBUG_META_MODE
1134 DEBUG1(META, "meta_oodate: %s\n", fname);
1137 if ((fp = fopen(fname, "r")) != NULL) {
1138 static char *buf = NULL;
1139 static size_t bufsz;
1140 unsigned lineno = 0;
1144 StringListNode *cmdNode;
1145 struct cached_stat cst;
1149 buf = bmake_malloc(bufsz);
1153 if (getcwd(cwd, sizeof cwd) == NULL)
1154 err(1, "Could not get current working directory");
1155 cwdlen = strlen(cwd);
1157 strlcpy(lcwd, cwd, sizeof lcwd);
1158 strlcpy(latestdir, cwd, sizeof latestdir);
1160 if (tmpdir == NULL) {
1161 tmpdir = getTmpdir();
1162 tmplen = strlen(tmpdir);
1165 /* we want to track all the .meta we read */
1166 Global_Append(".MAKE.META.FILES", fname);
1168 cmp_filter = metaCmpFilter || Var_Exists(gn, MAKE_META_CMP_FILTER);
1170 cmdNode = gn->commands.first;
1171 while (!oodate && (x = fgetLine(&buf, &bufsz, 0, fp)) > 0) {
1173 if (buf[x - 1] == '\n')
1176 warnx("%s: %u: line truncated at %u", fname, lineno, x);
1182 /* Find the start of the build monitor section. */
1183 if (!have_filemon) {
1184 if (strncmp(buf, "-- filemon", 10) == 0) {
1185 have_filemon = true;
1188 if (strncmp(buf, "# buildmon", 10) == 0) {
1189 have_filemon = true;
1194 /* Delimit the record type. */
1196 #ifdef DEBUG_META_MODE
1197 DEBUG3(META, "%s: %u: %s\n", fname, lineno, buf);
1202 * We are in the 'filemon' output section.
1203 * Each record from filemon follows the general form:
1205 * <key> <pid> <data>
1208 * <key> is a single letter, denoting the syscall.
1209 * <pid> is the process that made the syscall.
1210 * <data> is the arguments (of interest).
1213 case '#': /* comment */
1214 case 'V': /* version */
1218 * We need to track pathnames per-process.
1220 * Each process run by make starts off in the 'CWD'
1221 * recorded in the .meta file, if it chdirs ('C')
1222 * elsewhere we need to track that - but only for
1223 * that process. If it forks ('F'), we initialize
1224 * the child to have the same cwd as its parent.
1226 * We also need to track the 'latestdir' of
1227 * interest. This is usually the same as cwd, but
1228 * not if a process is reading directories.
1230 * Each time we spot a different process ('pid')
1231 * we save the current value of 'latestdir' in a
1232 * variable qualified by 'lastpid', and
1233 * re-initialize 'latestdir' to any pre-saved
1234 * value for the current 'pid' and 'CWD' if none.
1236 CHECK_VALID_META(p);
1238 if (pid > 0 && pid != lastpid) {
1242 /* We need to remember these. */
1243 Global_Set(lcwd_vname, lcwd);
1244 Global_Set(ldir_vname, latestdir);
1246 snprintf(lcwd_vname, sizeof lcwd_vname, LCWD_VNAME_FMT, pid);
1247 snprintf(ldir_vname, sizeof ldir_vname, LDIR_VNAME_FMT, pid);
1249 ldir = Var_Value(SCOPE_GLOBAL, ldir_vname);
1250 if (ldir.str != NULL) {
1251 strlcpy(latestdir, ldir.str, sizeof latestdir);
1254 ldir = Var_Value(SCOPE_GLOBAL, lcwd_vname);
1255 if (ldir.str != NULL) {
1256 strlcpy(lcwd, ldir.str, sizeof lcwd);
1260 /* Skip past the pid. */
1261 if (strsep(&p, " ") == NULL)
1263 #ifdef DEBUG_META_MODE
1265 debug_printf("%s: %u: %d: %c: cwd=%s lcwd=%s ldir=%s\n",
1267 pid, buf[0], cwd, lcwd, latestdir);
1272 CHECK_VALID_META(p);
1274 /* Process according to record type. */
1276 case 'X': /* eXit */
1277 Var_Delete(SCOPE_GLOBAL, lcwd_vname);
1278 Var_Delete(SCOPE_GLOBAL, ldir_vname);
1279 lastpid = 0; /* no need to save ldir_vname */
1282 case 'F': /* [v]Fork */
1289 snprintf(cldir, sizeof cldir, LCWD_VNAME_FMT, child);
1290 Global_Set(cldir, lcwd);
1291 snprintf(cldir, sizeof cldir, LDIR_VNAME_FMT, child);
1292 Global_Set(cldir, latestdir);
1293 #ifdef DEBUG_META_MODE
1296 "%s: %u: %d: cwd=%s lcwd=%s ldir=%s\n",
1298 child, cwd, lcwd, latestdir);
1304 case 'C': /* Chdir */
1305 /* Update lcwd and latest directory. */
1306 strlcpy(latestdir, p, sizeof latestdir);
1307 strlcpy(lcwd, p, sizeof lcwd);
1308 Global_Set(lcwd_vname, lcwd);
1309 Global_Set(ldir_vname, lcwd);
1310 #ifdef DEBUG_META_MODE
1311 DEBUG4(META, "%s: %u: cwd=%s ldir=%s\n",
1312 fname, lineno, cwd, lcwd);
1316 case 'M': /* renaMe */
1318 * For 'M'oves we want to check
1319 * the src as for 'R'ead
1320 * and the target as for 'W'rite.
1323 char *cp = p; /* save this for a second */
1324 /* now get target */
1325 if (strsep(&p, " ") == NULL)
1327 CHECK_VALID_META(p);
1331 /* 'L' and 'M' put single quotes around the args */
1333 DEQUOTE(move_target);
1335 case 'D': /* unlink */
1337 /* remove any missingFiles entries that match p */
1338 StringListNode *ln = missingFiles.first;
1339 while (ln != NULL) {
1340 StringListNode *next = ln->next;
1341 if (path_starts_with(ln->datum, p)) {
1343 Lst_Remove(&missingFiles, ln);
1348 if (buf[0] == 'M') {
1349 /* the target of the mv is a file 'W'ritten */
1350 #ifdef DEBUG_META_MODE
1351 DEBUG2(META, "meta_oodate: M %s -> %s\n",
1358 case 'L': /* Link */
1361 * the src as for 'R'ead
1362 * and the target as for 'W'rite.
1365 /* now get target */
1366 if (strsep(&p, " ") == NULL)
1368 CHECK_VALID_META(p);
1369 /* 'L' and 'M' put single quotes around the args */
1372 #ifdef DEBUG_META_MODE
1373 DEBUG2(META, "meta_oodate: L %s -> %s\n", link_src, p);
1376 case 'W': /* Write */
1379 * If a file we generated within our bailiwick
1380 * but outside of .OBJDIR is missing,
1381 * we need to do it again.
1383 /* ignore non-absolute paths */
1387 if (Lst_IsEmpty(&metaBailiwick))
1390 /* ignore cwd - normal dependencies handle those */
1391 if (strncmp(p, cwd, cwdlen) == 0)
1394 if (!has_any_prefix(p, &metaBailiwick))
1397 /* tmpdir might be within */
1398 if (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0)
1401 /* ignore anything containing the string "tmp" */
1402 /* XXX: The arguments to strstr must be swapped. */
1403 if (strstr("tmp", p) != NULL)
1406 if ((link_src != NULL && cached_lstat(p, &cst) < 0) ||
1407 (link_src == NULL && cached_stat(p, &cst) < 0)) {
1408 if (!meta_ignore(gn, p))
1409 append_if_new(&missingFiles, p);
1415 #ifdef DEBUG_META_MODE
1416 DEBUG1(META, "meta_oodate: L src %s\n", p);
1419 case 'R': /* Read */
1420 case 'E': /* Exec */
1422 * Check for runtime files that can't
1423 * be part of the dependencies because
1424 * they are _expected_ to change.
1426 if (meta_ignore(gn, p))
1430 * The rest of the record is the file name.
1431 * Check if it's not an absolute path.
1440 sdirs[sdx++] = p; /* done */
1442 if (strcmp(".", p) == 0)
1443 continue; /* no point */
1445 /* Check vs latestdir */
1446 snprintf(fname1, sizeof fname1, "%s/%s", latestdir, p);
1447 sdirs[sdx++] = fname1;
1449 if (strcmp(latestdir, lcwd) != 0) {
1451 snprintf(fname2, sizeof fname2, "%s/%s", lcwd, p);
1452 sdirs[sdx++] = fname2;
1454 if (strcmp(lcwd, cwd) != 0) {
1456 snprintf(fname3, sizeof fname3, "%s/%s", cwd, p);
1457 sdirs[sdx++] = fname3;
1460 sdirs[sdx++] = NULL;
1462 for (sdp = sdirs; *sdp != NULL && !found; sdp++) {
1463 #ifdef DEBUG_META_MODE
1464 DEBUG3(META, "%s: %u: looking for: %s\n",
1465 fname, lineno, *sdp);
1467 if (cached_stat(*sdp, &cst) == 0) {
1473 #ifdef DEBUG_META_MODE
1474 DEBUG3(META, "%s: %u: found: %s\n",
1477 if (!S_ISDIR(cst.cst_mode) &&
1478 cst.cst_mtime > gn->mtime) {
1479 DEBUG3(META, "%s: %u: file '%s' is newer than the target...\n",
1482 } else if (S_ISDIR(cst.cst_mode)) {
1483 /* Update the latest directory. */
1484 cached_realpath(p, latestdir);
1486 } else if (errno == ENOENT && *p == '/' &&
1487 strncmp(p, cwd, cwdlen) != 0) {
1489 * A referenced file outside of CWD is missing.
1490 * We cannot catch every eventuality here...
1492 append_if_new(&missingFiles, p);
1495 if (buf[0] == 'E') {
1496 /* previous latestdir is no longer relevant */
1497 strlcpy(latestdir, lcwd, sizeof latestdir);
1503 if (!oodate && buf[0] == 'L' && link_src != NULL)
1504 goto check_link_src;
1505 } else if (strcmp(buf, "CMD") == 0) {
1507 * Compare the current command with the one in the
1510 if (cmdNode == NULL) {
1511 DEBUG2(META, "%s: %u: there were more build commands in the meta data file than there are now...\n",
1516 char *cmd = cmdNode->datum;
1517 bool hasOODATE = false;
1519 if (strstr(cmd, "$?") != NULL)
1521 else if ((cp = strstr(cmd, ".OODATE")) != NULL) {
1522 /* check for $[{(].OODATE[:)}] */
1523 if (cp > cmd + 2 && cp[-2] == '$')
1528 DEBUG2(META, "%s: %u: cannot compare command using .OODATE\n",
1531 (void)Var_Subst(cmd, gn, VARE_UNDEFERR, &cmd);
1532 /* TODO: handle errors */
1534 if ((cp = strchr(cmd, '\n')) != NULL) {
1538 * This command contains newlines, we need to
1539 * fetch more from the .meta file before we
1540 * attempt a comparison.
1542 /* first put the newline back at buf[x - 1] */
1545 /* now fetch the next line */
1546 if ((n = fgetLine(&buf, &bufsz, x, fp)) <= 0)
1550 if (buf[x - 1] != '\n') {
1551 warnx("%s: %u: line truncated at %u", fname, lineno, x);
1554 cp = strchr(cp + 1, '\n');
1555 } while (cp != NULL);
1556 if (buf[x - 1] == '\n')
1561 !(gn->type & OP_NOMETA_CMP) &&
1562 (meta_cmd_cmp(gn, p, cmd, cmp_filter) != 0)) {
1563 DEBUG4(META, "%s: %u: a build command has changed\n%s\nvs\n%s\n",
1564 fname, lineno, p, cmd);
1565 if (!metaIgnoreCMDs)
1569 cmdNode = cmdNode->next;
1571 } else if (strcmp(buf, "CWD") == 0) {
1573 * Check if there are extra commands now
1574 * that weren't in the meta data file.
1576 if (!oodate && cmdNode != NULL) {
1577 DEBUG2(META, "%s: %u: there are extra build commands now that weren't in the meta data file\n",
1581 CHECK_VALID_META(p);
1582 if (strcmp(p, cwd) != 0) {
1583 DEBUG4(META, "%s: %u: the current working directory has changed from '%s' to '%s'\n",
1584 fname, lineno, p, curdir);
1591 if (!Lst_IsEmpty(&missingFiles)) {
1592 DEBUG2(META, "%s: missing files: %s...\n",
1593 fname, (char *)missingFiles.first->datum);
1596 if (!oodate && !have_filemon && filemonMissing) {
1597 DEBUG1(META, "%s: missing filemon data\n", fname);
1601 if (writeMeta && (metaMissing || (gn->type & OP_META))) {
1602 const char *cp = NULL;
1604 /* if target is in .CURDIR we do not need a meta file */
1605 if (gn->path != NULL && (cp = strrchr(gn->path, '/')) != NULL &&
1607 if (strncmp(curdir, gn->path, (size_t)(cp - gn->path)) != 0) {
1608 cp = NULL; /* not in .CURDIR */
1612 DEBUG1(META, "%s: required but missing\n", fname);
1614 needOODATE = true; /* assume the worst */
1619 Lst_DoneCall(&missingFiles, free);
1621 if (oodate && needOODATE) {
1623 * Target uses .OODATE which is empty; or we wouldn't be here.
1624 * We have decided it is oodate, so .OODATE needs to be set.
1625 * All we can sanely do is set it to .ALLSRC.
1627 Var_Delete(gn, OODATE);
1628 Var_Set(gn, OODATE, GNode_VarAllsrc(gn));
1636 /* support for compat mode */
1638 static int childPipe[2];
1641 meta_compat_start(void)
1643 #ifdef USE_FILEMON_ONCE
1645 * We need to re-open filemon for each cmd.
1647 BuildMon *pbm = &Mybm;
1649 if (pbm->mfp != NULL && useFilemon) {
1650 meta_open_filemon(pbm);
1653 pbm->filemon = NULL;
1656 if (pipe(childPipe) < 0)
1657 Punt("Cannot create pipe: %s", strerror(errno));
1658 /* Set close-on-exec flag for both */
1659 (void)fcntl(childPipe[0], F_SETFD, FD_CLOEXEC);
1660 (void)fcntl(childPipe[1], F_SETFD, FD_CLOEXEC);
1664 meta_compat_child(void)
1666 meta_job_child(NULL);
1667 if (dup2(childPipe[1], 1) < 0 || dup2(1, 2) < 0)
1668 execDie("dup2", "pipe");
1672 meta_compat_parent(pid_t child)
1674 int outfd, metafd, maxfd, nfds;
1678 meta_job_parent(NULL, child);
1679 close(childPipe[1]); /* child side */
1680 outfd = childPipe[0];
1682 metafd = Mybm.filemon != NULL ? filemon_readfd(Mybm.filemon) : -1;
1692 while (outfd != -1 || metafd != -1) {
1695 FD_SET(outfd, &readfds);
1698 FD_SET(metafd, &readfds);
1700 nfds = select(maxfd + 1, &readfds, NULL, NULL, NULL);
1707 if (outfd != -1 && FD_ISSET(outfd, &readfds) != 0) do {
1708 /* XXX this is not line-buffered */
1709 ssize_t nread = read(outfd, buf, sizeof buf - 1);
1717 fwrite(buf, 1, (size_t)nread, stdout);
1720 meta_job_output(NULL, buf, "");
1722 if (metafd != -1 && FD_ISSET(metafd, &readfds) != 0) {
1723 if (meta_job_event(NULL) <= 0)
1729 #endif /* USE_META */