1 /* $NetBSD: meta.c,v 1.177 2021/02/05 19:19:17 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"
73 Boolean useMeta = FALSE;
74 static Boolean useFilemon = FALSE;
75 static Boolean writeMeta = FALSE;
76 static Boolean metaMissing = FALSE; /* oodate if missing */
77 static Boolean filemonMissing = FALSE; /* oodate if missing */
78 static Boolean metaEnv = FALSE; /* don't save env unless asked */
79 static Boolean metaVerbose = FALSE;
80 static Boolean metaIgnoreCMDs = FALSE; /* ignore CMDs in .meta files */
81 static Boolean metaIgnorePatterns = FALSE; /* do we need to do pattern matches */
82 static Boolean metaIgnoreFilter = FALSE; /* do we have more complex filtering? */
83 static Boolean metaCurdirOk = FALSE; /* write .meta in .CURDIR Ok? */
84 static Boolean metaSilent = FALSE; /* if we have a .meta be SILENT */
86 extern Boolean forceJobs;
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 == NULL)
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 if (!opts.compatMake)
148 pbm->mon_fd = Job_TempFile("filemon.XXXXXX", NULL, 0);
150 pbm->mon_fd = mkTempFile("filemon.XXXXXX", NULL, 0);
151 if ((dupfd = dup(pbm->mon_fd)) == -1) {
152 err(1, "Could not dup filemon output!");
154 (void)fcntl(dupfd, F_SETFD, FD_CLOEXEC);
155 if (filemon_setfd(pbm->filemon, dupfd) == -1) {
156 err(1, "Could not set filemon file descriptor!");
158 /* we don't need these once we exec */
159 (void)fcntl(pbm->mon_fd, F_SETFD, FD_CLOEXEC);
163 * Read the build monitor output file and write records to the target's
167 filemon_read(FILE *mfp, int fd)
172 /* Check if we're not writing to a meta data file.*/
175 close(fd); /* not interested */
179 if (lseek(fd, (off_t)0, SEEK_SET) < 0) {
181 warn("Could not rewind filemon");
187 fprintf(mfp, "\n-- filemon acquired metadata --\n");
189 while ((n = read(fd, buf, sizeof buf)) > 0) {
190 if ((ssize_t)fwrite(buf, 1, (size_t)n, mfp) < n)
202 * when realpath() fails,
203 * we use this, to clean up ./ and ../
206 eat_dots(char *buf, size_t bufsz, int dots)
227 cp = strstr(buf, eat);
230 if (dots == 2 && cp > buf) {
233 } while (cp > buf && *cp != '/');
236 strlcpy(cp, cp2, bufsz - (size_t)(cp - buf));
238 return; /* can't happen? */
241 } while (cp != NULL);
245 meta_name(char *mname, size_t mnamelen,
250 char buf[MAXPATHLEN];
258 * Weed out relative paths from the target file name.
259 * We have to be careful though since if target is a
260 * symlink, the result will be unstable.
261 * So we use realpath() just to get the dirname, and leave the
262 * basename as given to us.
264 if ((cp = strrchr(tname, '/')) != NULL) {
265 if (cached_realpath(tname, buf) != NULL) {
266 if ((rp = strrchr(buf, '/')) != NULL) {
269 if (strcmp(cp, rp) != 0)
270 strlcpy(rp, cp, sizeof buf - (size_t)(rp - buf));
275 * We likely have a directory which is about to be made.
276 * We pretend realpath() succeeded, to have a chance
277 * of generating the same meta file name that we will
280 if (tname[0] == '/') {
281 strlcpy(buf, tname, sizeof buf);
283 snprintf(buf, sizeof buf, "%s/%s", cwd, tname);
285 eat_dots(buf, sizeof buf, 1); /* ./ */
286 eat_dots(buf, sizeof buf, 2); /* ../ */
290 /* on some systems dirname may modify its arg */
291 tp = bmake_strdup(tname);
293 if (strcmp(dname, dtp) == 0)
294 snprintf(mname, mnamelen, "%s.meta", tname);
296 ldname = strlen(dname);
297 if (strncmp(dname, dtp, ldname) == 0 && dtp[ldname] == '/')
298 snprintf(mname, mnamelen, "%s/%s.meta", dname, &tname[ldname+1]);
300 snprintf(mname, mnamelen, "%s/%s.meta", dname, tname);
303 * Replace path separators in the file name after the
304 * current object directory path.
306 cp = mname + strlen(dname) + 1;
308 while (*cp != '\0') {
319 * Return true if running ${.MAKE}
320 * Bypassed if target is flagged .MAKE
323 is_submake(const char *cmd, GNode *gn)
325 static const char *p_make = NULL;
332 if (p_make == NULL) {
333 p_make = Var_Value(gn, ".MAKE").str;
334 p_len = strlen(p_make);
336 cp = strchr(cmd, '$');
338 (void)Var_Subst(cmd, gn, VARE_WANTRES, &mp);
339 /* TODO: handle errors */
342 cp2 = strstr(cmd, p_make);
344 switch (cp2[p_len]) {
352 if (cp2 > cmd && rc) {
359 rc = FALSE; /* no match */
369 any_is_submake(GNode *gn)
373 for (ln = gn->commands.first; ln != NULL; ln = ln->next)
374 if (is_submake(ln->datum, gn))
380 printCMD(const char *cmd, FILE *fp, GNode *gn)
382 char *cmd_freeIt = NULL;
384 if (strchr(cmd, '$') != NULL) {
385 (void)Var_Subst(cmd, gn, VARE_WANTRES, &cmd_freeIt);
386 /* TODO: handle errors */
389 fprintf(fp, "CMD %s\n", cmd);
394 printCMDs(GNode *gn, FILE *fp)
398 for (ln = gn->commands.first; ln != NULL; ln = ln->next)
399 printCMD(ln->datum, fp, gn);
403 * Certain node types never get a .meta file
405 #define SKIP_META_TYPE(_type) do { \
406 if ((gn->type & __CONCAT(OP_, _type))) { \
408 debug_printf("Skipping meta for %s: .%s\n", \
409 gn->name, __STRING(_type)); \
413 } while (/*CONSTCOND*/FALSE)
417 * Do we need/want a .meta file ?
420 meta_needed(GNode *gn, const char *dname,
421 char *objdir_realpath, Boolean verbose)
423 struct cached_stat cst;
426 verbose = DEBUG(META);
428 /* This may be a phony node which we don't want meta data for... */
429 /* Skip .meta for .BEGIN, .END, .ERROR etc as well. */
430 /* Or it may be explicitly flagged as .NOMETA */
431 SKIP_META_TYPE(NOMETA);
432 /* Unless it is explicitly flagged as .META */
433 if (!(gn->type & OP_META)) {
434 SKIP_META_TYPE(PHONY);
435 SKIP_META_TYPE(SPECIAL);
436 SKIP_META_TYPE(MAKE);
439 /* Check if there are no commands to execute. */
440 if (Lst_IsEmpty(&gn->commands)) {
442 debug_printf("Skipping meta for %s: no commands\n", gn->name);
445 if ((gn->type & (OP_META|OP_SUBMAKE)) == OP_SUBMAKE) {
446 /* OP_SUBMAKE is a bit too aggressive */
447 if (any_is_submake(gn)) {
448 DEBUG1(META, "Skipping meta for %s: .SUBMAKE\n", gn->name);
453 /* The object directory may not exist. Check it.. */
454 if (cached_stat(dname, &cst) != 0) {
456 debug_printf("Skipping meta for %s: no .OBJDIR\n", gn->name);
460 /* make sure these are canonical */
461 if (cached_realpath(dname, objdir_realpath) != NULL)
462 dname = objdir_realpath;
464 /* If we aren't in the object directory, don't create a meta file. */
465 if (!metaCurdirOk && strcmp(curdir, dname) == 0) {
467 debug_printf("Skipping meta for %s: .OBJDIR == .CURDIR\n",
476 meta_create(BuildMon *pbm, GNode *gn)
479 char buf[MAXPATHLEN];
480 char objdir_realpath[MAXPATHLEN];
489 dname = Var_Value(gn, ".OBJDIR");
490 tname = GNode_VarTarget(gn);
492 /* if this succeeds objdir_realpath is realpath of dname */
493 if (!meta_needed(gn, dname.str, objdir_realpath, TRUE))
495 dname.str = objdir_realpath;
500 /* Describe the target we are building */
501 (void)Var_Subst("${" MAKE_META_PREFIX "}", gn, VARE_WANTRES, &mp);
502 /* TODO: handle errors */
504 fprintf(stdout, "%s\n", mp);
507 /* Get the basename of the target */
508 cp = str_basename(tname);
513 /* Don't create meta data. */
516 fname = meta_name(pbm->meta_fname, sizeof pbm->meta_fname,
517 dname.str, tname, objdir_realpath);
519 #ifdef DEBUG_META_MODE
520 DEBUG1(META, "meta_create: %s\n", fname);
523 if ((fp = fopen(fname, "w")) == NULL)
524 err(1, "Could not open meta file '%s'", fname);
526 fprintf(fp, "# Meta data file %s\n", fname);
530 fprintf(fp, "CWD %s\n", getcwd(buf, sizeof buf));
531 fprintf(fp, "TARGET %s\n", tname);
532 cp = GNode_VarOodate(gn);
533 if (cp != NULL && *cp != '\0') {
534 fprintf(fp, "OODATE %s\n", cp);
537 for (ptr = environ; *ptr != NULL; ptr++)
538 fprintf(fp, "ENV %s\n", *ptr);
541 fprintf(fp, "-- command output --\n");
544 Global_Append(".MAKE.META.FILES", fname);
545 Global_Append(".MAKE.META.CREATED", fname);
547 gn->type |= OP_META; /* in case anyone wants to know */
549 gn->type |= OP_SILENT;
572 * Initialization we need before reading makefiles.
578 /* this allows makefiles to test if we have filemon support */
579 Global_Set(".MAKE.PATH_FILEMON", filemon_path());
584 #define get_mode_bf(bf, token) \
585 if ((cp = strstr(make_mode, token)) != NULL) \
586 bf = boolValue(cp + sizeof (token) - 1)
589 * Initialization we need after reading makefiles.
592 meta_mode_init(const char *make_mode)
594 static Boolean once = FALSE;
602 if (make_mode != NULL) {
603 if (strstr(make_mode, "env") != NULL)
605 if (strstr(make_mode, "verb") != NULL)
607 if (strstr(make_mode, "read") != NULL)
609 if (strstr(make_mode, "nofilemon") != NULL)
611 if (strstr(make_mode, "ignore-cmd") != NULL)
612 metaIgnoreCMDs = TRUE;
614 get_mode_bf(filemonMissing, "missing-filemon=");
615 get_mode_bf(metaCurdirOk, "curdirok=");
616 get_mode_bf(metaMissing, "missing-meta=");
617 get_mode_bf(metaSilent, "silent=");
619 if (metaVerbose && !Var_Exists(SCOPE_GLOBAL, MAKE_META_PREFIX)) {
621 * The default value for MAKE_META_PREFIX
622 * prints the absolute path of the target.
623 * This works be cause :H will generate '.' if there is no /
624 * and :tA will resolve that to cwd.
626 Global_Set(MAKE_META_PREFIX,
627 "Building ${.TARGET:H:tA}/${.TARGET:T}");
632 memset(&Mybm, 0, sizeof Mybm);
634 * We consider ourselves master of all within ${.MAKE.META.BAILIWICK}
636 (void)Var_Subst("${.MAKE.META.BAILIWICK:O:u:tA}",
637 SCOPE_GLOBAL, VARE_WANTRES, &metaBailiwickStr);
638 /* TODO: handle errors */
639 str2Lst_Append(&metaBailiwick, metaBailiwickStr);
641 * We ignore any paths that start with ${.MAKE.META.IGNORE_PATHS}
643 Global_Append(MAKE_META_IGNORE_PATHS,
644 "/dev /etc /proc /tmp /var/run /var/tmp ${TMPDIR}");
645 (void)Var_Subst("${" MAKE_META_IGNORE_PATHS ":O:u:tA}",
646 SCOPE_GLOBAL, VARE_WANTRES, &metaIgnorePathsStr);
647 /* TODO: handle errors */
648 str2Lst_Append(&metaIgnorePaths, metaIgnorePathsStr);
651 * We ignore any paths that match ${.MAKE.META.IGNORE_PATTERNS}
653 value = Var_Value(SCOPE_GLOBAL, MAKE_META_IGNORE_PATTERNS);
654 if (value.str != NULL) {
655 metaIgnorePatterns = TRUE;
658 value = Var_Value(SCOPE_GLOBAL, MAKE_META_IGNORE_FILTER);
659 if (value.str != NULL) {
660 metaIgnoreFilter = TRUE;
666 * In each case below we allow for job==NULL
669 meta_job_start(Job *job, GNode *gn)
678 pbm->mfp = meta_create(pbm, gn);
679 #ifdef USE_FILEMON_ONCE
680 /* compat mode we open the filemon dev once per command */
685 if (pbm->mfp != NULL && useFilemon) {
686 meta_open_filemon(pbm);
695 * The child calls this before doing anything.
696 * It does not disturb our state.
699 meta_job_child(Job *job)
709 if (pbm->mfp != NULL) {
710 close(fileno(pbm->mfp));
711 if (useFilemon && pbm->filemon != NULL) {
715 if (filemon_setpid_child(pbm->filemon, pid) == -1) {
716 err(1, "Could not set filemon pid!");
724 meta_job_parent(Job *job, pid_t pid)
726 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
734 if (useFilemon && pbm->filemon != NULL) {
735 filemon_setpid_parent(pbm->filemon, pid);
741 meta_job_fd(Job *job)
743 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
751 if (useFilemon && pbm->filemon != NULL) {
752 return filemon_readfd(pbm->filemon);
759 meta_job_event(Job *job)
761 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
769 if (useFilemon && pbm->filemon != NULL) {
770 return filemon_process(pbm->filemon);
777 meta_job_error(Job *job, GNode *gn, Boolean ignerr, int status)
779 char cwd[MAXPATHLEN];
789 if (pbm->mfp != NULL) {
790 fprintf(pbm->mfp, "\n*** Error code %d%s\n",
791 status, ignerr ? "(ignored)" : "");
794 Global_Set(".ERROR_TARGET", GNode_Path(gn));
795 getcwd(cwd, sizeof cwd);
796 Global_Set(".ERROR_CWD", cwd);
797 if (pbm->meta_fname[0] != '\0') {
798 Global_Set(".ERROR_META_FILE", pbm->meta_fname);
800 meta_job_finish(job);
804 meta_job_output(Job *job, char *cp, const char *nl)
813 if (pbm->mfp != NULL) {
815 static char *meta_prefix = NULL;
816 static size_t meta_prefix_len;
818 if (meta_prefix == NULL) {
821 (void)Var_Subst("${" MAKE_META_PREFIX "}",
822 SCOPE_GLOBAL, VARE_WANTRES, &meta_prefix);
823 /* TODO: handle errors */
824 if ((cp2 = strchr(meta_prefix, '$')) != NULL)
825 meta_prefix_len = (size_t)(cp2 - meta_prefix);
827 meta_prefix_len = strlen(meta_prefix);
829 if (strncmp(cp, meta_prefix, meta_prefix_len) == 0) {
830 cp = strchr(cp + 1, '\n');
836 fprintf(pbm->mfp, "%s%s", cp, nl);
841 meta_cmd_finish(void *pbmp)
844 BuildMon *pbm = pbmp;
853 if (pbm->filemon != NULL) {
854 while (filemon_process(pbm->filemon) > 0)
856 if (filemon_close(pbm->filemon) == -1)
858 x = filemon_read(pbm->mfp, pbm->mon_fd);
859 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_Done(&metaBailiwick);
898 free(metaBailiwickStr);
899 Lst_Done(&metaIgnorePaths);
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], (int)bufsz - o, fp) != NULL) {
917 x = o + (int)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(((size_t)fs.st_size / 2), BUFSIZ);
930 newsz = ROUNDUP((size_t)fs.st_size, BUFSIZ);
932 return x; /* truncated */
933 DEBUG2(META, "growing buffer %u -> %u\n",
934 (unsigned)bufsz, (unsigned)newsz);
935 p = bmake_realloc(buf, newsz);
937 *szp = bufsz = newsz;
939 if (fgets(&buf[x], (int)bufsz - x, fp) == NULL)
940 return x; /* truncated! */
948 prefix_match(const char *prefix, const char *path)
950 size_t n = strlen(prefix);
952 return strncmp(path, prefix, n) == 0;
956 has_any_prefix(const char *path, StringList *prefixes)
960 for (ln = prefixes->first; ln != NULL; ln = ln->next)
961 if (prefix_match(ln->datum, path))
966 /* See if the path equals prefix or starts with "prefix/". */
968 path_starts_with(const char *path, const char *prefix)
970 size_t n = strlen(prefix);
972 if (strncmp(path, prefix, n) != 0)
974 return path[n] == '\0' || path[n] == '/';
978 meta_ignore(GNode *gn, const char *p)
980 char fname[MAXPATHLEN];
986 cached_realpath(p, fname); /* clean it up */
987 if (has_any_prefix(fname, &metaIgnorePaths)) {
988 #ifdef DEBUG_META_MODE
989 DEBUG1(META, "meta_oodate: ignoring path: %s\n", p);
995 if (metaIgnorePatterns) {
1000 * XXX: This variable is set on a target GNode but is not one of
1001 * the usual local variables. It should be deleted afterwards.
1002 * Ideally it would not be created in the first place, just like
1005 Var_Set(gn, ".p.", p);
1006 expr = "${" MAKE_META_IGNORE_PATTERNS ":@m@${.p.:M$m}@}";
1007 (void)Var_Subst(expr, gn, VARE_WANTRES, &pm);
1008 /* TODO: handle errors */
1009 if (pm[0] != '\0') {
1010 #ifdef DEBUG_META_MODE
1011 DEBUG1(META, "meta_oodate: ignoring pattern: %s\n", p);
1019 if (metaIgnoreFilter) {
1022 /* skip if filter result is empty */
1023 snprintf(fname, sizeof fname,
1024 "${%s:L:${%s:ts:}}",
1025 p, MAKE_META_IGNORE_FILTER);
1026 (void)Var_Subst(fname, gn, VARE_WANTRES, &fm);
1027 /* TODO: handle errors */
1029 #ifdef DEBUG_META_MODE
1030 DEBUG1(META, "meta_oodate: ignoring filtered: %s\n", p);
1041 * When running with 'meta' functionality, a target can be out-of-date
1042 * if any of the references in its meta data file is more recent.
1043 * We have to track the latestdir on a per-process basis.
1045 #define LCWD_VNAME_FMT ".meta.%d.lcwd"
1046 #define LDIR_VNAME_FMT ".meta.%d.ldir"
1049 * It is possible that a .meta file is corrupted,
1050 * if we detect this we want to reproduce it.
1051 * Setting oodate TRUE will have that effect.
1053 #define CHECK_VALID_META(p) if (!(p != NULL && *p != '\0')) { \
1054 warnx("%s: %d: malformed", fname, lineno); \
1059 #define DEQUOTE(p) if (*p == '\'') { \
1062 if ((ep = strchr(p, '\'')) != NULL) \
1067 append_if_new(StringList *list, const char *str)
1071 for (ln = list->first; ln != NULL; ln = ln->next)
1072 if (strcmp(ln->datum, str) == 0)
1074 Lst_Append(list, bmake_strdup(str));
1078 meta_oodate(GNode *gn, Boolean oodate)
1080 static char *tmpdir = NULL;
1081 static char cwd[MAXPATHLEN];
1082 char lcwd_vname[64];
1083 char ldir_vname[64];
1084 char lcwd[MAXPATHLEN];
1085 char latestdir[MAXPATHLEN];
1086 char fname[MAXPATHLEN];
1087 char fname1[MAXPATHLEN];
1088 char fname2[MAXPATHLEN];
1089 char fname3[MAXPATHLEN];
1095 static size_t cwdlen = 0;
1096 static size_t tmplen = 0;
1098 Boolean needOODATE = FALSE;
1099 StringList missingFiles;
1100 Boolean have_filemon = FALSE;
1103 return oodate; /* we're done */
1105 dname = Var_Value(gn, ".OBJDIR");
1106 tname = GNode_VarTarget(gn);
1108 /* if this succeeds fname3 is realpath of dname */
1109 if (!meta_needed(gn, dname.str, fname3, FALSE))
1113 Lst_Init(&missingFiles);
1116 * We need to check if the target is out-of-date. This includes
1117 * checking if the expanded command has changed. This in turn
1118 * requires that all variables are set in the same way that they
1119 * would be if the target needs to be re-built.
1123 meta_name(fname, sizeof fname, dname.str, tname, dname.str);
1125 #ifdef DEBUG_META_MODE
1126 DEBUG1(META, "meta_oodate: %s\n", fname);
1129 if ((fp = fopen(fname, "r")) != NULL) {
1130 static char *buf = NULL;
1131 static size_t bufsz;
1136 StringListNode *cmdNode;
1137 struct cached_stat cst;
1141 buf = bmake_malloc(bufsz);
1145 if (getcwd(cwd, sizeof cwd) == NULL)
1146 err(1, "Could not get current working directory");
1147 cwdlen = strlen(cwd);
1149 strlcpy(lcwd, cwd, sizeof lcwd);
1150 strlcpy(latestdir, cwd, sizeof latestdir);
1152 if (tmpdir == NULL) {
1153 tmpdir = getTmpdir();
1154 tmplen = strlen(tmpdir);
1157 /* we want to track all the .meta we read */
1158 Global_Append(".MAKE.META.FILES", fname);
1160 cmdNode = gn->commands.first;
1161 while (!oodate && (x = fgetLine(&buf, &bufsz, 0, fp)) > 0) {
1163 if (buf[x - 1] == '\n')
1166 warnx("%s: %d: line truncated at %u", fname, lineno, x);
1172 /* Find the start of the build monitor section. */
1173 if (!have_filemon) {
1174 if (strncmp(buf, "-- filemon", 10) == 0) {
1175 have_filemon = TRUE;
1178 if (strncmp(buf, "# buildmon", 10) == 0) {
1179 have_filemon = TRUE;
1184 /* Delimit the record type. */
1186 #ifdef DEBUG_META_MODE
1187 DEBUG3(META, "%s: %d: %s\n", fname, lineno, buf);
1192 * We are in the 'filemon' output section.
1193 * Each record from filemon follows the general form:
1195 * <key> <pid> <data>
1198 * <key> is a single letter, denoting the syscall.
1199 * <pid> is the process that made the syscall.
1200 * <data> is the arguments (of interest).
1203 case '#': /* comment */
1204 case 'V': /* version */
1208 * We need to track pathnames per-process.
1210 * Each process run by make starts off in the 'CWD'
1211 * recorded in the .meta file, if it chdirs ('C')
1212 * elsewhere we need to track that - but only for
1213 * that process. If it forks ('F'), we initialize
1214 * the child to have the same cwd as its parent.
1216 * We also need to track the 'latestdir' of
1217 * interest. This is usually the same as cwd, but
1218 * not if a process is reading directories.
1220 * Each time we spot a different process ('pid')
1221 * we save the current value of 'latestdir' in a
1222 * variable qualified by 'lastpid', and
1223 * re-initialize 'latestdir' to any pre-saved
1224 * value for the current 'pid' and 'CWD' if none.
1226 CHECK_VALID_META(p);
1228 if (pid > 0 && pid != lastpid) {
1232 /* We need to remember these. */
1233 Global_SetExpand(lcwd_vname, lcwd);
1234 Global_SetExpand(ldir_vname, latestdir);
1236 snprintf(lcwd_vname, sizeof lcwd_vname, LCWD_VNAME_FMT, pid);
1237 snprintf(ldir_vname, sizeof ldir_vname, LDIR_VNAME_FMT, pid);
1239 ldir = Var_Value(SCOPE_GLOBAL, ldir_vname);
1240 if (ldir.str != NULL) {
1241 strlcpy(latestdir, ldir.str, sizeof latestdir);
1244 ldir = Var_Value(SCOPE_GLOBAL, lcwd_vname);
1245 if (ldir.str != NULL) {
1246 strlcpy(lcwd, ldir.str, sizeof lcwd);
1250 /* Skip past the pid. */
1251 if (strsep(&p, " ") == NULL)
1253 #ifdef DEBUG_META_MODE
1255 debug_printf("%s: %d: %d: %c: cwd=%s lcwd=%s ldir=%s\n",
1257 pid, buf[0], cwd, lcwd, latestdir);
1262 CHECK_VALID_META(p);
1264 /* Process according to record type. */
1266 case 'X': /* eXit */
1267 Var_DeleteExpand(SCOPE_GLOBAL, lcwd_vname);
1268 Var_DeleteExpand(SCOPE_GLOBAL, ldir_vname);
1269 lastpid = 0; /* no need to save ldir_vname */
1272 case 'F': /* [v]Fork */
1279 snprintf(cldir, sizeof cldir, LCWD_VNAME_FMT, child);
1280 Global_SetExpand(cldir, lcwd);
1281 snprintf(cldir, sizeof cldir, LDIR_VNAME_FMT, child);
1282 Global_SetExpand(cldir, latestdir);
1283 #ifdef DEBUG_META_MODE
1286 "%s: %d: %d: cwd=%s lcwd=%s ldir=%s\n",
1288 child, cwd, lcwd, latestdir);
1294 case 'C': /* Chdir */
1295 /* Update lcwd and latest directory. */
1296 strlcpy(latestdir, p, sizeof latestdir);
1297 strlcpy(lcwd, p, sizeof lcwd);
1298 Global_SetExpand(lcwd_vname, lcwd);
1299 Global_SetExpand(ldir_vname, lcwd);
1300 #ifdef DEBUG_META_MODE
1301 DEBUG4(META, "%s: %d: cwd=%s ldir=%s\n",
1302 fname, lineno, cwd, lcwd);
1306 case 'M': /* renaMe */
1308 * For 'M'oves we want to check
1309 * the src as for 'R'ead
1310 * and the target as for 'W'rite.
1313 char *cp = p; /* save this for a second */
1314 /* now get target */
1315 if (strsep(&p, " ") == NULL)
1317 CHECK_VALID_META(p);
1321 /* 'L' and 'M' put single quotes around the args */
1323 DEQUOTE(move_target);
1325 case 'D': /* unlink */
1327 /* remove any missingFiles entries that match p */
1328 StringListNode *ln = missingFiles.first;
1329 while (ln != NULL) {
1330 StringListNode *next = ln->next;
1331 if (path_starts_with(ln->datum, p)) {
1333 Lst_Remove(&missingFiles, ln);
1338 if (buf[0] == 'M') {
1339 /* the target of the mv is a file 'W'ritten */
1340 #ifdef DEBUG_META_MODE
1341 DEBUG2(META, "meta_oodate: M %s -> %s\n",
1348 case 'L': /* Link */
1351 * the src as for 'R'ead
1352 * and the target as for 'W'rite.
1355 /* now get target */
1356 if (strsep(&p, " ") == NULL)
1358 CHECK_VALID_META(p);
1359 /* 'L' and 'M' put single quotes around the args */
1362 #ifdef DEBUG_META_MODE
1363 DEBUG2(META, "meta_oodate: L %s -> %s\n", link_src, p);
1366 case 'W': /* Write */
1369 * If a file we generated within our bailiwick
1370 * but outside of .OBJDIR is missing,
1371 * we need to do it again.
1373 /* ignore non-absolute paths */
1377 if (Lst_IsEmpty(&metaBailiwick))
1380 /* ignore cwd - normal dependencies handle those */
1381 if (strncmp(p, cwd, cwdlen) == 0)
1384 if (!has_any_prefix(p, &metaBailiwick))
1387 /* tmpdir might be within */
1388 if (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0)
1391 /* ignore anything containing the string "tmp" */
1392 /* XXX: The arguments to strstr must be swapped. */
1393 if (strstr("tmp", p) != NULL)
1396 if ((link_src != NULL && cached_lstat(p, &cst) < 0) ||
1397 (link_src == NULL && cached_stat(p, &cst) < 0)) {
1398 if (!meta_ignore(gn, p))
1399 append_if_new(&missingFiles, p);
1405 #ifdef DEBUG_META_MODE
1406 DEBUG1(META, "meta_oodate: L src %s\n", p);
1409 case 'R': /* Read */
1410 case 'E': /* Exec */
1412 * Check for runtime files that can't
1413 * be part of the dependencies because
1414 * they are _expected_ to change.
1416 if (meta_ignore(gn, p))
1420 * The rest of the record is the file name.
1421 * Check if it's not an absolute path.
1427 Boolean found = FALSE;
1430 sdirs[sdx++] = p; /* done */
1432 if (strcmp(".", p) == 0)
1433 continue; /* no point */
1435 /* Check vs latestdir */
1436 snprintf(fname1, sizeof fname1, "%s/%s", latestdir, p);
1437 sdirs[sdx++] = fname1;
1439 if (strcmp(latestdir, lcwd) != 0) {
1441 snprintf(fname2, sizeof fname2, "%s/%s", lcwd, p);
1442 sdirs[sdx++] = fname2;
1444 if (strcmp(lcwd, cwd) != 0) {
1446 snprintf(fname3, sizeof fname3, "%s/%s", cwd, p);
1447 sdirs[sdx++] = fname3;
1450 sdirs[sdx++] = NULL;
1452 for (sdp = sdirs; *sdp != NULL && !found; sdp++) {
1453 #ifdef DEBUG_META_MODE
1454 DEBUG3(META, "%s: %d: looking for: %s\n",
1455 fname, lineno, *sdp);
1457 if (cached_stat(*sdp, &cst) == 0) {
1463 #ifdef DEBUG_META_MODE
1464 DEBUG3(META, "%s: %d: found: %s\n",
1467 if (!S_ISDIR(cst.cst_mode) &&
1468 cst.cst_mtime > gn->mtime) {
1469 DEBUG3(META, "%s: %d: file '%s' is newer than the target...\n",
1472 } else if (S_ISDIR(cst.cst_mode)) {
1473 /* Update the latest directory. */
1474 cached_realpath(p, latestdir);
1476 } else if (errno == ENOENT && *p == '/' &&
1477 strncmp(p, cwd, cwdlen) != 0) {
1479 * A referenced file outside of CWD is missing.
1480 * We cannot catch every eventuality here...
1482 append_if_new(&missingFiles, p);
1485 if (buf[0] == 'E') {
1486 /* previous latestdir is no longer relevant */
1487 strlcpy(latestdir, lcwd, sizeof latestdir);
1493 if (!oodate && buf[0] == 'L' && link_src != NULL)
1494 goto check_link_src;
1495 } else if (strcmp(buf, "CMD") == 0) {
1497 * Compare the current command with the one in the
1500 if (cmdNode == NULL) {
1501 DEBUG2(META, "%s: %d: there were more build commands in the meta data file than there are now...\n",
1506 char *cmd = cmdNode->datum;
1507 Boolean hasOODATE = FALSE;
1509 if (strstr(cmd, "$?") != NULL)
1511 else if ((cp = strstr(cmd, ".OODATE")) != NULL) {
1512 /* check for $[{(].OODATE[:)}] */
1513 if (cp > cmd + 2 && cp[-2] == '$')
1518 DEBUG2(META, "%s: %d: cannot compare command using .OODATE\n",
1521 (void)Var_Subst(cmd, gn, VARE_WANTRES|VARE_UNDEFERR, &cmd);
1522 /* TODO: handle errors */
1524 if ((cp = strchr(cmd, '\n')) != NULL) {
1528 * This command contains newlines, we need to
1529 * fetch more from the .meta file before we
1530 * attempt a comparison.
1532 /* first put the newline back at buf[x - 1] */
1535 /* now fetch the next line */
1536 if ((n = fgetLine(&buf, &bufsz, x, fp)) <= 0)
1540 if (buf[x - 1] != '\n') {
1541 warnx("%s: %d: line truncated at %u", fname, lineno, x);
1544 cp = strchr(cp + 1, '\n');
1545 } while (cp != NULL);
1546 if (buf[x - 1] == '\n')
1551 !(gn->type & OP_NOMETA_CMP) &&
1552 (strcmp(p, cmd) != 0)) {
1553 DEBUG4(META, "%s: %d: a build command has changed\n%s\nvs\n%s\n",
1554 fname, lineno, p, cmd);
1555 if (!metaIgnoreCMDs)
1559 cmdNode = cmdNode->next;
1561 } else if (strcmp(buf, "CWD") == 0) {
1563 * Check if there are extra commands now
1564 * that weren't in the meta data file.
1566 if (!oodate && cmdNode != NULL) {
1567 DEBUG2(META, "%s: %d: there are extra build commands now that weren't in the meta data file\n",
1571 CHECK_VALID_META(p);
1572 if (strcmp(p, cwd) != 0) {
1573 DEBUG4(META, "%s: %d: the current working directory has changed from '%s' to '%s'\n",
1574 fname, lineno, p, curdir);
1581 if (!Lst_IsEmpty(&missingFiles)) {
1582 DEBUG2(META, "%s: missing files: %s...\n",
1583 fname, (char *)missingFiles.first->datum);
1586 if (!oodate && !have_filemon && filemonMissing) {
1587 DEBUG1(META, "%s: missing filemon data\n", fname);
1591 if (writeMeta && (metaMissing || (gn->type & OP_META))) {
1592 const char *cp = NULL;
1594 /* if target is in .CURDIR we do not need a meta file */
1595 if (gn->path != NULL && (cp = strrchr(gn->path, '/')) != NULL &&
1597 if (strncmp(curdir, gn->path, (size_t)(cp - gn->path)) != 0) {
1598 cp = NULL; /* not in .CURDIR */
1602 DEBUG1(META, "%s: required but missing\n", fname);
1604 needOODATE = TRUE; /* assume the worst */
1609 Lst_DoneCall(&missingFiles, free);
1611 if (oodate && needOODATE) {
1613 * Target uses .OODATE which is empty; or we wouldn't be here.
1614 * We have decided it is oodate, so .OODATE needs to be set.
1615 * All we can sanely do is set it to .ALLSRC.
1617 Var_Delete(gn, OODATE);
1618 Var_Set(gn, OODATE, GNode_VarAllsrc(gn));
1626 /* support for compat mode */
1628 static int childPipe[2];
1631 meta_compat_start(void)
1633 #ifdef USE_FILEMON_ONCE
1635 * We need to re-open filemon for each cmd.
1637 BuildMon *pbm = &Mybm;
1639 if (pbm->mfp != NULL && useFilemon) {
1640 meta_open_filemon(pbm);
1643 pbm->filemon = NULL;
1646 if (pipe(childPipe) < 0)
1647 Punt("Cannot create pipe: %s", strerror(errno));
1648 /* Set close-on-exec flag for both */
1649 (void)fcntl(childPipe[0], F_SETFD, FD_CLOEXEC);
1650 (void)fcntl(childPipe[1], F_SETFD, FD_CLOEXEC);
1654 meta_compat_child(void)
1656 meta_job_child(NULL);
1657 if (dup2(childPipe[1], 1) < 0 || dup2(1, 2) < 0)
1658 execDie("dup2", "pipe");
1662 meta_compat_parent(pid_t child)
1664 int outfd, metafd, maxfd, nfds;
1668 meta_job_parent(NULL, child);
1669 close(childPipe[1]); /* child side */
1670 outfd = childPipe[0];
1672 metafd = Mybm.filemon != NULL ? filemon_readfd(Mybm.filemon) : -1;
1682 while (outfd != -1 || metafd != -1) {
1685 FD_SET(outfd, &readfds);
1688 FD_SET(metafd, &readfds);
1690 nfds = select(maxfd + 1, &readfds, NULL, NULL, NULL);
1697 if (outfd != -1 && FD_ISSET(outfd, &readfds) != 0) do {
1698 /* XXX this is not line-buffered */
1699 ssize_t nread = read(outfd, buf, sizeof buf - 1);
1707 fwrite(buf, 1, (size_t)nread, stdout);
1710 meta_job_output(NULL, buf, "");
1711 } while (/*CONSTCOND*/FALSE);
1712 if (metafd != -1 && FD_ISSET(metafd, &readfds) != 0) {
1713 if (meta_job_event(NULL) <= 0)
1719 #endif /* USE_META */