1 /* $NetBSD: meta.c,v 1.201 2022/09/28 16:34:47 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)
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 if (snprintf(mname, mnamelen, "%s.meta", tname) >= (int)mnamelen)
286 mname[mnamelen - 1] = '\0';
290 ldname = strlen(dname);
291 if (strncmp(dname, dtp, ldname) == 0 && dtp[ldname] == '/')
292 x = snprintf(mname, mnamelen, "%s/%s.meta", dname, &tname[ldname+1]);
294 x = snprintf(mname, mnamelen, "%s/%s.meta", dname, tname);
295 if (x >= (int)mnamelen)
296 mname[mnamelen - 1] = '\0';
298 * Replace path separators in the file name after the
299 * current object directory path.
301 cp = mname + strlen(dname) + 1;
303 while (*cp != '\0') {
314 * Return true if running ${.MAKE}
315 * Bypassed if target is flagged .MAKE
318 is_submake(const char *cmd, GNode *gn)
320 static const char *p_make = NULL;
326 if (p_make == NULL) {
327 p_make = Var_Value(gn, ".MAKE").str;
328 p_len = strlen(p_make);
330 if (strchr(cmd, '$') != NULL) {
331 (void)Var_Subst(cmd, gn, VARE_WANTRES, &mp);
332 /* TODO: handle errors */
335 cp2 = strstr(cmd, p_make);
337 switch (cp2[p_len]) {
345 if (cp2 > cmd && rc) {
352 rc = false; /* no match */
362 any_is_submake(GNode *gn)
366 for (ln = gn->commands.first; ln != NULL; ln = ln->next)
367 if (is_submake(ln->datum, gn))
373 printCMD(const char *ucmd, FILE *fp, GNode *gn)
375 FStr xcmd = FStr_InitRefer(ucmd);
377 Var_Expand(&xcmd, gn, VARE_WANTRES);
378 fprintf(fp, "CMD %s\n", xcmd.str);
383 printCMDs(GNode *gn, FILE *fp)
387 for (ln = gn->commands.first; ln != NULL; ln = ln->next)
388 printCMD(ln->datum, fp, gn);
392 * Certain node types never get a .meta file
394 #define SKIP_META_TYPE(flag, str) do { \
395 if ((gn->type & (flag))) { \
397 debug_printf("Skipping meta for %s: .%s\n", gn->name, str); \
404 * Do we need/want a .meta file ?
407 meta_needed(GNode *gn, const char *dname,
408 char *objdir_realpath, bool verbose)
410 struct cached_stat cst;
413 verbose = DEBUG(META);
415 /* This may be a phony node which we don't want meta data for... */
416 /* Skip .meta for .BEGIN, .END, .ERROR etc as well. */
417 /* Or it may be explicitly flagged as .NOMETA */
418 SKIP_META_TYPE(OP_NOMETA, "NOMETA");
419 /* Unless it is explicitly flagged as .META */
420 if (!(gn->type & OP_META)) {
421 SKIP_META_TYPE(OP_PHONY, "PHONY");
422 SKIP_META_TYPE(OP_SPECIAL, "SPECIAL");
423 SKIP_META_TYPE(OP_MAKE, "MAKE");
426 /* Check if there are no commands to execute. */
427 if (Lst_IsEmpty(&gn->commands)) {
429 debug_printf("Skipping meta for %s: no commands\n", gn->name);
432 if ((gn->type & (OP_META|OP_SUBMAKE)) == OP_SUBMAKE) {
433 /* OP_SUBMAKE is a bit too aggressive */
434 if (any_is_submake(gn)) {
435 DEBUG1(META, "Skipping meta for %s: .SUBMAKE\n", gn->name);
440 /* The object directory may not exist. Check it.. */
441 if (cached_stat(dname, &cst) != 0) {
443 debug_printf("Skipping meta for %s: no .OBJDIR\n", gn->name);
447 /* make sure these are canonical */
448 if (cached_realpath(dname, objdir_realpath) != NULL)
449 dname = objdir_realpath;
451 /* If we aren't in the object directory, don't create a meta file. */
452 if (!metaCurdirOk && strcmp(curdir, dname) == 0) {
454 debug_printf("Skipping meta for %s: .OBJDIR == .CURDIR\n",
463 meta_create(BuildMon *pbm, GNode *gn)
466 char buf[MAXPATHLEN];
467 char objdir_realpath[MAXPATHLEN];
476 dname = Var_Value(gn, ".OBJDIR");
477 tname = GNode_VarTarget(gn);
479 /* if this succeeds objdir_realpath is realpath of dname */
480 if (!meta_needed(gn, dname.str, objdir_realpath, true))
482 dname.str = objdir_realpath;
487 /* Describe the target we are building */
488 (void)Var_Subst("${" MAKE_META_PREFIX "}", gn, VARE_WANTRES, &mp);
489 /* TODO: handle errors */
491 fprintf(stdout, "%s\n", mp);
494 /* Get the basename of the target */
495 cp = str_basename(tname);
500 /* Don't create meta data. */
503 fname = meta_name(pbm->meta_fname, sizeof pbm->meta_fname,
504 dname.str, tname, objdir_realpath);
506 #ifdef DEBUG_META_MODE
507 DEBUG1(META, "meta_create: %s\n", fname);
510 if ((fp = fopen(fname, "w")) == NULL)
511 Punt("Could not open meta file '%s': %s", fname, strerror(errno));
513 fprintf(fp, "# Meta data file %s\n", fname);
517 fprintf(fp, "CWD %s\n", getcwd(buf, sizeof buf));
518 fprintf(fp, "TARGET %s\n", tname);
519 cp = GNode_VarOodate(gn);
520 if (cp != NULL && *cp != '\0') {
521 fprintf(fp, "OODATE %s\n", cp);
524 for (ptr = environ; *ptr != NULL; ptr++)
525 fprintf(fp, "ENV %s\n", *ptr);
528 fprintf(fp, "-- command output --\n");
530 Punt("Cannot write expanded command to meta file: %s",
533 Global_Append(".MAKE.META.FILES", fname);
534 Global_Append(".MAKE.META.CREATED", fname);
536 gn->type |= OP_META; /* in case anyone wants to know */
538 gn->type |= OP_SILENT;
547 boolValue(const char *s)
561 * Initialization we need before reading makefiles.
567 /* this allows makefiles to test if we have filemon support */
568 Global_Set(".MAKE.PATH_FILEMON", filemon_path());
573 #define get_mode_bf(bf, token) \
574 if ((cp = strstr(make_mode, token)) != NULL) \
575 bf = boolValue(cp + sizeof (token) - 1)
578 * Initialization we need after reading makefiles.
581 meta_mode_init(const char *make_mode)
583 static bool once = false;
590 if (make_mode != NULL) {
591 if (strstr(make_mode, "env") != NULL)
593 if (strstr(make_mode, "verb") != NULL)
595 if (strstr(make_mode, "read") != NULL)
597 if (strstr(make_mode, "nofilemon") != NULL)
599 if (strstr(make_mode, "ignore-cmd") != NULL)
600 metaIgnoreCMDs = true;
602 get_mode_bf(filemonMissing, "missing-filemon=");
603 get_mode_bf(metaCurdirOk, "curdirok=");
604 get_mode_bf(metaMissing, "missing-meta=");
605 get_mode_bf(metaSilent, "silent=");
607 if (metaVerbose && !Var_Exists(SCOPE_GLOBAL, MAKE_META_PREFIX)) {
609 * The default value for MAKE_META_PREFIX
610 * prints the absolute path of the target.
611 * This works be cause :H will generate '.' if there is no /
612 * and :tA will resolve that to cwd.
614 Global_Set(MAKE_META_PREFIX,
615 "Building ${.TARGET:H:tA}/${.TARGET:T}");
620 memset(&Mybm, 0, sizeof Mybm);
622 * We consider ourselves master of all within ${.MAKE.META.BAILIWICK}
624 (void)Var_Subst("${.MAKE.META.BAILIWICK:O:u:tA}",
625 SCOPE_GLOBAL, VARE_WANTRES, &metaBailiwickStr);
626 /* TODO: handle errors */
627 str2Lst_Append(&metaBailiwick, metaBailiwickStr);
629 * We ignore any paths that start with ${.MAKE.META.IGNORE_PATHS}
631 Global_Append(MAKE_META_IGNORE_PATHS,
632 "/dev /etc /proc /tmp /var/run /var/tmp ${TMPDIR}");
633 (void)Var_Subst("${" MAKE_META_IGNORE_PATHS ":O:u:tA}",
634 SCOPE_GLOBAL, VARE_WANTRES, &metaIgnorePathsStr);
635 /* TODO: handle errors */
636 str2Lst_Append(&metaIgnorePaths, metaIgnorePathsStr);
639 * We ignore any paths that match ${.MAKE.META.IGNORE_PATTERNS}
641 metaIgnorePatterns = Var_Exists(SCOPE_GLOBAL, MAKE_META_IGNORE_PATTERNS);
642 metaIgnoreFilter = Var_Exists(SCOPE_GLOBAL, MAKE_META_IGNORE_FILTER);
643 metaCmpFilter = Var_Exists(SCOPE_GLOBAL, MAKE_META_CMP_FILTER);
647 * In each case below we allow for job==NULL
650 meta_job_start(Job *job, GNode *gn)
659 pbm->mfp = meta_create(pbm, gn);
660 #ifdef USE_FILEMON_ONCE
661 /* compat mode we open the filemon dev once per command */
666 if (pbm->mfp != NULL && useFilemon) {
667 meta_open_filemon(pbm);
676 * The child calls this before doing anything.
677 * It does not disturb our state.
680 meta_job_child(Job *job MAKE_ATTR_UNUSED)
690 if (pbm->mfp != NULL) {
691 close(fileno(pbm->mfp));
692 if (useFilemon && pbm->filemon != NULL) {
696 if (filemon_setpid_child(pbm->filemon, pid) == -1) {
697 Punt("Could not set filemon pid: %s", strerror(errno));
705 meta_job_parent(Job *job MAKE_ATTR_UNUSED, pid_t pid MAKE_ATTR_UNUSED)
707 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
715 if (useFilemon && pbm->filemon != NULL) {
716 filemon_setpid_parent(pbm->filemon, pid);
722 meta_job_fd(Job *job MAKE_ATTR_UNUSED)
724 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
732 if (useFilemon && pbm->filemon != NULL) {
733 return filemon_readfd(pbm->filemon);
740 meta_job_event(Job *job MAKE_ATTR_UNUSED)
742 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
750 if (useFilemon && pbm->filemon != NULL) {
751 return filemon_process(pbm->filemon);
758 meta_job_error(Job *job, GNode *gn, bool ignerr, int status)
760 char cwd[MAXPATHLEN];
770 if (pbm->mfp != NULL) {
771 fprintf(pbm->mfp, "\n*** Error code %d%s\n",
772 status, ignerr ? "(ignored)" : "");
775 Global_Set(".ERROR_TARGET", GNode_Path(gn));
776 if (getcwd(cwd, sizeof cwd) == NULL)
777 Punt("Cannot get cwd: %s", strerror(errno));
779 Global_Set(".ERROR_CWD", cwd);
780 if (pbm->meta_fname[0] != '\0') {
781 Global_Set(".ERROR_META_FILE", pbm->meta_fname);
783 meta_job_finish(job);
787 meta_job_output(Job *job, char *cp, const char *nl)
796 if (pbm->mfp != NULL) {
798 static char *meta_prefix = NULL;
799 static size_t meta_prefix_len;
801 if (meta_prefix == NULL) {
804 (void)Var_Subst("${" MAKE_META_PREFIX "}",
805 SCOPE_GLOBAL, VARE_WANTRES, &meta_prefix);
806 /* TODO: handle errors */
807 if ((cp2 = strchr(meta_prefix, '$')) != NULL)
808 meta_prefix_len = (size_t)(cp2 - meta_prefix);
810 meta_prefix_len = strlen(meta_prefix);
812 if (strncmp(cp, meta_prefix, meta_prefix_len) == 0) {
813 cp = strchr(cp + 1, '\n');
819 fprintf(pbm->mfp, "%s%s", cp, nl);
824 meta_cmd_finish(void *pbmp)
827 BuildMon *pbm = pbmp;
836 if (pbm->filemon != NULL) {
837 while (filemon_process(pbm->filemon) > 0)
839 if (filemon_close(pbm->filemon) == -1) {
841 Punt("filemon failed: %s", strerror(errno));
843 x = filemon_read(pbm->mfp, pbm->mon_fd);
844 if (error == 0 && x != 0)
852 fprintf(pbm->mfp, "\n"); /* ensure end with newline */
857 meta_job_finish(Job *job)
868 if (pbm->mfp != NULL) {
869 error = meta_cmd_finish(pbm);
870 x = fclose(pbm->mfp);
871 if (error == 0 && x != 0)
874 pbm->meta_fname[0] = '\0';
882 Lst_Done(&metaBailiwick);
883 free(metaBailiwickStr);
884 Lst_Done(&metaIgnorePaths);
885 free(metaIgnorePathsStr);
889 * Fetch a full line from fp - growing bufp if needed
890 * Return length in bufp.
893 fgetLine(char **bufp, size_t *szp, int o, FILE *fp)
900 if (fgets(&buf[o], (int)bufsz - o, fp) != NULL) {
902 x = o + (int)strlen(&buf[o]);
903 if (buf[x - 1] == '\n')
906 * We need to grow the buffer.
907 * The meta file can give us a clue.
909 if (fstat(fileno(fp), &fs) == 0) {
913 newsz = ROUNDUP(((size_t)fs.st_size / 2), BUFSIZ);
915 newsz = ROUNDUP((size_t)fs.st_size, BUFSIZ);
917 return x; /* truncated */
918 DEBUG2(META, "growing buffer %u -> %u\n",
919 (unsigned)bufsz, (unsigned)newsz);
920 p = bmake_realloc(buf, newsz);
922 *szp = bufsz = newsz;
924 if (fgets(&buf[x], (int)bufsz - x, fp) == NULL)
925 return x; /* truncated! */
933 prefix_match(const char *prefix, const char *path)
935 size_t n = strlen(prefix);
937 return strncmp(path, prefix, n) == 0;
941 has_any_prefix(const char *path, StringList *prefixes)
945 for (ln = prefixes->first; ln != NULL; ln = ln->next)
946 if (prefix_match(ln->datum, path))
951 /* See if the path equals prefix or starts with "prefix/". */
953 path_starts_with(const char *path, const char *prefix)
955 size_t n = strlen(prefix);
957 if (strncmp(path, prefix, n) != 0)
959 return path[n] == '\0' || path[n] == '/';
963 meta_ignore(GNode *gn, const char *p)
965 char fname[MAXPATHLEN];
971 cached_realpath(p, fname); /* clean it up */
972 if (has_any_prefix(fname, &metaIgnorePaths)) {
973 #ifdef DEBUG_META_MODE
974 DEBUG1(META, "meta_oodate: ignoring path: %s\n", p);
980 if (metaIgnorePatterns) {
985 * XXX: This variable is set on a target GNode but is not one of
986 * the usual local variables. It should be deleted afterwards.
987 * Ideally it would not be created in the first place, just like
990 Var_Set(gn, ".p.", p);
991 expr = "${" MAKE_META_IGNORE_PATTERNS ":@m@${.p.:M$m}@}";
992 (void)Var_Subst(expr, gn, VARE_WANTRES, &pm);
993 /* TODO: handle errors */
995 #ifdef DEBUG_META_MODE
996 DEBUG1(META, "meta_oodate: ignoring pattern: %s\n", p);
1004 if (metaIgnoreFilter) {
1007 /* skip if filter result is empty */
1008 snprintf(fname, sizeof fname,
1009 "${%s:L:${%s:ts:}}",
1010 p, MAKE_META_IGNORE_FILTER);
1011 (void)Var_Subst(fname, gn, VARE_WANTRES, &fm);
1012 /* TODO: handle errors */
1014 #ifdef DEBUG_META_MODE
1015 DEBUG1(META, "meta_oodate: ignoring filtered: %s\n", p);
1026 * When running with 'meta' functionality, a target can be out-of-date
1027 * if any of the references in its meta data file is more recent.
1028 * We have to track the latestdir on a per-process basis.
1030 #define LCWD_VNAME_FMT ".meta.%d.lcwd"
1031 #define LDIR_VNAME_FMT ".meta.%d.ldir"
1034 * It is possible that a .meta file is corrupted,
1035 * if we detect this we want to reproduce it.
1036 * Setting oodate true will have that effect.
1038 #define CHECK_VALID_META(p) if (!(p != NULL && *p != '\0')) { \
1039 warnx("%s: %u: malformed", fname, lineno); \
1044 #define DEQUOTE(p) if (*p == '\'') { \
1047 if ((ep = strchr(p, '\'')) != NULL) \
1052 append_if_new(StringList *list, const char *str)
1056 for (ln = list->first; ln != NULL; ln = ln->next)
1057 if (strcmp(ln->datum, str) == 0)
1059 Lst_Append(list, bmake_strdup(str));
1062 /* A "reserved" variable to store the command to be filtered */
1063 #define META_CMD_FILTER_VAR ".MAKE.cmd_filtered"
1066 meta_filter_cmd(GNode *gn, char *s)
1068 Var_Set(gn, META_CMD_FILTER_VAR, s);
1069 Var_Subst("${" META_CMD_FILTER_VAR ":${" MAKE_META_CMP_FILTER ":ts:}}", gn, VARE_WANTRES, &s);
1074 meta_cmd_cmp(GNode *gn, char *a, char *b, bool filter)
1079 if (rc == 0 || !filter)
1081 a = meta_filter_cmd(gn, a);
1082 b = meta_filter_cmd(gn, b);
1086 Var_Delete(gn, META_CMD_FILTER_VAR);
1091 meta_oodate(GNode *gn, bool oodate)
1093 static char *tmpdir = NULL;
1094 static char cwd[MAXPATHLEN];
1095 char lcwd_vname[64];
1096 char ldir_vname[64];
1097 char lcwd[MAXPATHLEN];
1098 char latestdir[MAXPATHLEN];
1099 char fname[MAXPATHLEN];
1100 char fname1[MAXPATHLEN];
1101 char fname2[MAXPATHLEN];
1102 char fname3[MAXPATHLEN];
1108 static size_t cwdlen = 0;
1109 static size_t tmplen = 0;
1111 bool needOODATE = false;
1112 StringList missingFiles;
1113 bool have_filemon = false;
1117 return oodate; /* we're done */
1119 dname = Var_Value(gn, ".OBJDIR");
1120 tname = GNode_VarTarget(gn);
1122 /* if this succeeds fname3 is realpath of dname */
1123 if (!meta_needed(gn, dname.str, fname3, false))
1127 Lst_Init(&missingFiles);
1130 * We need to check if the target is out-of-date. This includes
1131 * checking if the expanded command has changed. This in turn
1132 * requires that all variables are set in the same way that they
1133 * would be if the target needs to be re-built.
1135 GNode_SetLocalVars(gn);
1137 meta_name(fname, sizeof fname, dname.str, tname, dname.str);
1139 #ifdef DEBUG_META_MODE
1140 DEBUG1(META, "meta_oodate: %s\n", fname);
1143 if ((fp = fopen(fname, "r")) != NULL) {
1144 static char *buf = NULL;
1145 static size_t bufsz;
1146 unsigned lineno = 0;
1150 StringListNode *cmdNode;
1151 struct cached_stat cst;
1155 buf = bmake_malloc(bufsz);
1159 if (getcwd(cwd, sizeof cwd) == NULL)
1160 err(1, "Could not get current working directory");
1161 cwdlen = strlen(cwd);
1163 strlcpy(lcwd, cwd, sizeof lcwd);
1164 strlcpy(latestdir, cwd, sizeof latestdir);
1166 if (tmpdir == NULL) {
1167 tmpdir = getTmpdir();
1168 tmplen = strlen(tmpdir);
1171 /* we want to track all the .meta we read */
1172 Global_Append(".MAKE.META.FILES", fname);
1174 cmp_filter = metaCmpFilter || Var_Exists(gn, MAKE_META_CMP_FILTER);
1176 cmdNode = gn->commands.first;
1177 while (!oodate && (x = fgetLine(&buf, &bufsz, 0, fp)) > 0) {
1179 if (buf[x - 1] == '\n')
1182 warnx("%s: %u: line truncated at %u", fname, lineno, x);
1188 /* Find the start of the build monitor section. */
1189 if (!have_filemon) {
1190 if (strncmp(buf, "-- filemon", 10) == 0) {
1191 have_filemon = true;
1194 if (strncmp(buf, "# buildmon", 10) == 0) {
1195 have_filemon = true;
1200 /* Delimit the record type. */
1202 #ifdef DEBUG_META_MODE
1203 DEBUG3(META, "%s: %u: %s\n", fname, lineno, buf);
1208 * We are in the 'filemon' output section.
1209 * Each record from filemon follows the general form:
1211 * <key> <pid> <data>
1214 * <key> is a single letter, denoting the syscall.
1215 * <pid> is the process that made the syscall.
1216 * <data> is the arguments (of interest).
1219 case '#': /* comment */
1220 case 'V': /* version */
1224 * We need to track pathnames per-process.
1226 * Each process run by make starts off in the 'CWD'
1227 * recorded in the .meta file, if it chdirs ('C')
1228 * elsewhere we need to track that - but only for
1229 * that process. If it forks ('F'), we initialize
1230 * the child to have the same cwd as its parent.
1232 * We also need to track the 'latestdir' of
1233 * interest. This is usually the same as cwd, but
1234 * not if a process is reading directories.
1236 * Each time we spot a different process ('pid')
1237 * we save the current value of 'latestdir' in a
1238 * variable qualified by 'lastpid', and
1239 * re-initialize 'latestdir' to any pre-saved
1240 * value for the current 'pid' and 'CWD' if none.
1242 CHECK_VALID_META(p);
1244 if (pid > 0 && pid != lastpid) {
1248 /* We need to remember these. */
1249 Global_Set(lcwd_vname, lcwd);
1250 Global_Set(ldir_vname, latestdir);
1252 snprintf(lcwd_vname, sizeof lcwd_vname, LCWD_VNAME_FMT, pid);
1253 snprintf(ldir_vname, sizeof ldir_vname, LDIR_VNAME_FMT, pid);
1255 ldir = Var_Value(SCOPE_GLOBAL, ldir_vname);
1256 if (ldir.str != NULL) {
1257 strlcpy(latestdir, ldir.str, sizeof latestdir);
1260 ldir = Var_Value(SCOPE_GLOBAL, lcwd_vname);
1261 if (ldir.str != NULL) {
1262 strlcpy(lcwd, ldir.str, sizeof lcwd);
1266 /* Skip past the pid. */
1267 if (strsep(&p, " ") == NULL)
1269 #ifdef DEBUG_META_MODE
1271 debug_printf("%s: %u: %d: %c: cwd=%s lcwd=%s ldir=%s\n",
1273 pid, buf[0], cwd, lcwd, latestdir);
1278 CHECK_VALID_META(p);
1280 /* Process according to record type. */
1282 case 'X': /* eXit */
1283 Var_Delete(SCOPE_GLOBAL, lcwd_vname);
1284 Var_Delete(SCOPE_GLOBAL, ldir_vname);
1285 lastpid = 0; /* no need to save ldir_vname */
1288 case 'F': /* [v]Fork */
1295 snprintf(cldir, sizeof cldir, LCWD_VNAME_FMT, child);
1296 Global_Set(cldir, lcwd);
1297 snprintf(cldir, sizeof cldir, LDIR_VNAME_FMT, child);
1298 Global_Set(cldir, latestdir);
1299 #ifdef DEBUG_META_MODE
1302 "%s: %u: %d: cwd=%s lcwd=%s ldir=%s\n",
1304 child, cwd, lcwd, latestdir);
1310 case 'C': /* Chdir */
1311 /* Update lcwd and latest directory. */
1312 strlcpy(latestdir, p, sizeof latestdir);
1313 strlcpy(lcwd, p, sizeof lcwd);
1314 Global_Set(lcwd_vname, lcwd);
1315 Global_Set(ldir_vname, lcwd);
1316 #ifdef DEBUG_META_MODE
1317 DEBUG4(META, "%s: %u: cwd=%s ldir=%s\n",
1318 fname, lineno, cwd, lcwd);
1322 case 'M': /* renaMe */
1324 * For 'M'oves we want to check
1325 * the src as for 'R'ead
1326 * and the target as for 'W'rite.
1329 char *cp = p; /* save this for a second */
1330 /* now get target */
1331 if (strsep(&p, " ") == NULL)
1333 CHECK_VALID_META(p);
1337 /* 'L' and 'M' put single quotes around the args */
1339 DEQUOTE(move_target);
1341 case 'D': /* unlink */
1343 /* remove any missingFiles entries that match p */
1344 StringListNode *ln = missingFiles.first;
1345 while (ln != NULL) {
1346 StringListNode *next = ln->next;
1347 if (path_starts_with(ln->datum, p)) {
1349 Lst_Remove(&missingFiles, ln);
1354 if (buf[0] == 'M') {
1355 /* the target of the mv is a file 'W'ritten */
1356 #ifdef DEBUG_META_MODE
1357 DEBUG2(META, "meta_oodate: M %s -> %s\n",
1364 case 'L': /* Link */
1367 * the src as for 'R'ead
1368 * and the target as for 'W'rite.
1371 /* now get target */
1372 if (strsep(&p, " ") == NULL)
1374 CHECK_VALID_META(p);
1375 /* 'L' and 'M' put single quotes around the args */
1378 #ifdef DEBUG_META_MODE
1379 DEBUG2(META, "meta_oodate: L %s -> %s\n", link_src, p);
1382 case 'W': /* Write */
1385 * If a file we generated within our bailiwick
1386 * but outside of .OBJDIR is missing,
1387 * we need to do it again.
1389 /* ignore non-absolute paths */
1393 if (Lst_IsEmpty(&metaBailiwick))
1396 /* ignore cwd - normal dependencies handle those */
1397 if (strncmp(p, cwd, cwdlen) == 0)
1400 if (!has_any_prefix(p, &metaBailiwick))
1403 /* tmpdir might be within */
1404 if (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0)
1407 /* ignore anything containing the string "tmp" */
1408 /* XXX: The arguments to strstr must be swapped. */
1409 if (strstr("tmp", p) != NULL)
1412 if ((link_src != NULL && cached_lstat(p, &cst) < 0) ||
1413 (link_src == NULL && cached_stat(p, &cst) < 0)) {
1414 if (!meta_ignore(gn, p))
1415 append_if_new(&missingFiles, p);
1421 #ifdef DEBUG_META_MODE
1422 DEBUG1(META, "meta_oodate: L src %s\n", p);
1425 case 'R': /* Read */
1426 case 'E': /* Exec */
1428 * Check for runtime files that can't
1429 * be part of the dependencies because
1430 * they are _expected_ to change.
1432 if (meta_ignore(gn, p))
1436 * The rest of the record is the file name.
1437 * Check if it's not an absolute path.
1446 sdirs[sdx++] = p; /* done */
1448 if (strcmp(".", p) == 0)
1449 continue; /* no point */
1451 /* Check vs latestdir */
1452 if (snprintf(fname1, sizeof fname1, "%s/%s", latestdir, p) < (int)(sizeof fname1))
1453 sdirs[sdx++] = fname1;
1455 if (strcmp(latestdir, lcwd) != 0) {
1457 if (snprintf(fname2, sizeof fname2, "%s/%s", lcwd, p) < (int)(sizeof fname2))
1458 sdirs[sdx++] = fname2;
1460 if (strcmp(lcwd, cwd) != 0) {
1462 if (snprintf(fname3, sizeof fname3, "%s/%s", cwd, p) < (int)(sizeof fname3))
1463 sdirs[sdx++] = fname3;
1466 sdirs[sdx++] = NULL;
1468 for (sdp = sdirs; *sdp != NULL && !found; sdp++) {
1469 #ifdef DEBUG_META_MODE
1470 DEBUG3(META, "%s: %u: looking for: %s\n",
1471 fname, lineno, *sdp);
1473 if (cached_stat(*sdp, &cst) == 0) {
1479 #ifdef DEBUG_META_MODE
1480 DEBUG3(META, "%s: %u: found: %s\n",
1483 if (!S_ISDIR(cst.cst_mode) &&
1484 cst.cst_mtime > gn->mtime) {
1485 DEBUG3(META, "%s: %u: file '%s' is newer than the target...\n",
1488 } else if (S_ISDIR(cst.cst_mode)) {
1489 /* Update the latest directory. */
1490 cached_realpath(p, latestdir);
1492 } else if (errno == ENOENT && *p == '/' &&
1493 strncmp(p, cwd, cwdlen) != 0) {
1495 * A referenced file outside of CWD is missing.
1496 * We cannot catch every eventuality here...
1498 append_if_new(&missingFiles, p);
1501 if (buf[0] == 'E') {
1502 /* previous latestdir is no longer relevant */
1503 strlcpy(latestdir, lcwd, sizeof latestdir);
1509 if (!oodate && buf[0] == 'L' && link_src != NULL)
1510 goto check_link_src;
1511 } else if (strcmp(buf, "CMD") == 0) {
1513 * Compare the current command with the one in the
1516 if (cmdNode == NULL) {
1517 DEBUG2(META, "%s: %u: there were more build commands in the meta data file than there are now...\n",
1522 char *cmd = cmdNode->datum;
1523 bool hasOODATE = false;
1525 if (strstr(cmd, "$?") != NULL)
1527 else if ((cp = strstr(cmd, ".OODATE")) != NULL) {
1528 /* check for $[{(].OODATE[:)}] */
1529 if (cp > cmd + 2 && cp[-2] == '$')
1534 DEBUG2(META, "%s: %u: cannot compare command using .OODATE\n",
1537 (void)Var_Subst(cmd, gn, VARE_UNDEFERR, &cmd);
1538 /* TODO: handle errors */
1540 if ((cp = strchr(cmd, '\n')) != NULL) {
1544 * This command contains newlines, we need to
1545 * fetch more from the .meta file before we
1546 * attempt a comparison.
1548 /* first put the newline back at buf[x - 1] */
1551 /* now fetch the next line */
1552 if ((n = fgetLine(&buf, &bufsz, x, fp)) <= 0)
1556 if (buf[x - 1] != '\n') {
1557 warnx("%s: %u: line truncated at %u", fname, lineno, x);
1560 cp = strchr(cp + 1, '\n');
1561 } while (cp != NULL);
1562 if (buf[x - 1] == '\n')
1567 !(gn->type & OP_NOMETA_CMP) &&
1568 (meta_cmd_cmp(gn, p, cmd, cmp_filter) != 0)) {
1569 DEBUG4(META, "%s: %u: a build command has changed\n%s\nvs\n%s\n",
1570 fname, lineno, p, cmd);
1571 if (!metaIgnoreCMDs)
1575 cmdNode = cmdNode->next;
1577 } else if (strcmp(buf, "CWD") == 0) {
1579 * Check if there are extra commands now
1580 * that weren't in the meta data file.
1582 if (!oodate && cmdNode != NULL) {
1583 DEBUG2(META, "%s: %u: there are extra build commands now that weren't in the meta data file\n",
1587 CHECK_VALID_META(p);
1588 if (strcmp(p, cwd) != 0) {
1589 DEBUG4(META, "%s: %u: the current working directory has changed from '%s' to '%s'\n",
1590 fname, lineno, p, curdir);
1597 if (!Lst_IsEmpty(&missingFiles)) {
1598 DEBUG2(META, "%s: missing files: %s...\n",
1599 fname, (char *)missingFiles.first->datum);
1602 if (!oodate && !have_filemon && filemonMissing) {
1603 DEBUG1(META, "%s: missing filemon data\n", fname);
1607 if (writeMeta && (metaMissing || (gn->type & OP_META))) {
1608 const char *cp = NULL;
1610 /* if target is in .CURDIR we do not need a meta file */
1611 if (gn->path != NULL && (cp = strrchr(gn->path, '/')) != NULL &&
1613 if (strncmp(curdir, gn->path, (size_t)(cp - gn->path)) != 0) {
1614 cp = NULL; /* not in .CURDIR */
1618 DEBUG1(META, "%s: required but missing\n", fname);
1620 needOODATE = true; /* assume the worst */
1625 Lst_DoneCall(&missingFiles, free);
1627 if (oodate && needOODATE) {
1629 * Target uses .OODATE which is empty; or we wouldn't be here.
1630 * We have decided it is oodate, so .OODATE needs to be set.
1631 * All we can sanely do is set it to .ALLSRC.
1633 Var_Delete(gn, OODATE);
1634 Var_Set(gn, OODATE, GNode_VarAllsrc(gn));
1642 /* support for compat mode */
1644 static int childPipe[2];
1647 meta_compat_start(void)
1649 #ifdef USE_FILEMON_ONCE
1651 * We need to re-open filemon for each cmd.
1653 BuildMon *pbm = &Mybm;
1655 if (pbm->mfp != NULL && useFilemon) {
1656 meta_open_filemon(pbm);
1659 pbm->filemon = NULL;
1662 if (pipe(childPipe) < 0)
1663 Punt("Cannot create pipe: %s", strerror(errno));
1664 /* Set close-on-exec flag for both */
1665 (void)fcntl(childPipe[0], F_SETFD, FD_CLOEXEC);
1666 (void)fcntl(childPipe[1], F_SETFD, FD_CLOEXEC);
1670 meta_compat_child(void)
1672 meta_job_child(NULL);
1673 if (dup2(childPipe[1], 1) < 0 || dup2(1, 2) < 0)
1674 execDie("dup2", "pipe");
1678 meta_compat_parent(pid_t child)
1680 int outfd, metafd, maxfd, nfds;
1684 meta_job_parent(NULL, child);
1685 close(childPipe[1]); /* child side */
1686 outfd = childPipe[0];
1688 metafd = Mybm.filemon != NULL ? filemon_readfd(Mybm.filemon) : -1;
1698 while (outfd != -1 || metafd != -1) {
1701 FD_SET(outfd, &readfds);
1704 FD_SET(metafd, &readfds);
1706 nfds = select(maxfd + 1, &readfds, NULL, NULL, NULL);
1713 if (outfd != -1 && FD_ISSET(outfd, &readfds) != 0) do {
1714 /* XXX this is not line-buffered */
1715 ssize_t nread = read(outfd, buf, sizeof buf - 1);
1723 fwrite(buf, 1, (size_t)nread, stdout);
1726 meta_job_output(NULL, buf, "");
1728 if (metafd != -1 && FD_ISSET(metafd, &readfds) != 0) {
1729 if (meta_job_event(NULL) <= 0)
1735 #endif /* USE_META */