1 /* $NetBSD: meta.c,v 1.136 2020/10/31 12:04:24 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; /* our scope of control */
59 static char *metaBailiwickStr; /* string storage for the list */
60 static StringList *metaIgnorePaths; /* 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 Boolean comatMake;
88 extern char **environ;
90 #define MAKE_META_PREFIX ".MAKE.META.PREFIX"
93 # define N2U(n, u) (((n) + ((u) - 1)) / (u))
96 # define ROUNDUP(n, u) (N2U((n), (u)) * (u))
99 #if !defined(HAVE_STRSEP)
100 # define strsep(s, d) stresep((s), (d), 0)
104 * Filemon is a kernel module which snoops certain syscalls.
115 * See meta_oodate below - we mainly care about 'E' and 'R'.
117 * We can still use meta mode without filemon, but
118 * the benefits are more limited.
123 * Open the filemon device.
126 meta_open_filemon(BuildMon *pbm)
132 if (!useFilemon || !pbm->mfp)
135 pbm->filemon = filemon_open();
136 if (pbm->filemon == NULL) {
138 warn("Could not open filemon %s", filemon_path());
143 * We use a file outside of '.'
144 * to avoid a FreeBSD kernel bug where unlink invalidates
145 * cwd causing getcwd to do a lot more work.
146 * We only care about the descriptor.
148 pbm->mon_fd = mkTempFile("filemon.XXXXXX", NULL);
149 if ((dupfd = dup(pbm->mon_fd)) == -1) {
150 err(1, "Could not dup filemon output!");
152 (void)fcntl(dupfd, F_SETFD, FD_CLOEXEC);
153 if (filemon_setfd(pbm->filemon, dupfd) == -1) {
154 err(1, "Could not set filemon file descriptor!");
156 /* we don't need these once we exec */
157 (void)fcntl(pbm->mon_fd, F_SETFD, FD_CLOEXEC);
161 * Read the build monitor output file and write records to the target's
165 filemon_read(FILE *mfp, int fd)
170 /* Check if we're not writing to a meta data file.*/
173 close(fd); /* not interested */
177 if (lseek(fd, (off_t)0, SEEK_SET) < 0) {
179 warn("Could not rewind filemon");
185 fprintf(mfp, "\n-- filemon acquired metadata --\n");
187 while ((n = read(fd, buf, sizeof(buf))) > 0) {
188 if ((ssize_t)fwrite(buf, 1, (size_t)n, mfp) < n)
200 * when realpath() fails,
201 * we use this, to clean up ./ and ../
204 eat_dots(char *buf, size_t bufsz, int dots)
225 cp = strstr(buf, eat);
228 if (dots == 2 && cp > buf) {
231 } while (cp > buf && *cp != '/');
234 strlcpy(cp, cp2, bufsz - (size_t)(cp - buf));
236 return; /* can't happen? */
243 meta_name(char *mname, size_t mnamelen,
248 char buf[MAXPATHLEN];
256 * Weed out relative paths from the target file name.
257 * We have to be careful though since if target is a
258 * symlink, the result will be unstable.
259 * So we use realpath() just to get the dirname, and leave the
260 * basename as given to us.
262 if ((cp = strrchr(tname, '/'))) {
263 if (cached_realpath(tname, buf)) {
264 if ((rp = strrchr(buf, '/'))) {
267 if (strcmp(cp, rp) != 0)
268 strlcpy(rp, cp, sizeof buf - (size_t)(rp - buf));
273 * We likely have a directory which is about to be made.
274 * We pretend realpath() succeeded, to have a chance
275 * of generating the same meta file name that we will
278 if (tname[0] == '/') {
279 strlcpy(buf, tname, sizeof(buf));
281 snprintf(buf, sizeof(buf), "%s/%s", cwd, tname);
283 eat_dots(buf, sizeof(buf), 1); /* ./ */
284 eat_dots(buf, sizeof(buf), 2); /* ../ */
288 /* on some systems dirname may modify its arg */
289 tp = bmake_strdup(tname);
291 if (strcmp(dname, dtp) == 0)
292 snprintf(mname, mnamelen, "%s.meta", tname);
294 ldname = strlen(dname);
295 if (strncmp(dname, dtp, ldname) == 0 && dtp[ldname] == '/')
296 snprintf(mname, mnamelen, "%s/%s.meta", dname, &tname[ldname+1]);
298 snprintf(mname, mnamelen, "%s/%s.meta", dname, tname);
301 * Replace path separators in the file name after the
302 * current object directory path.
304 cp = mname + strlen(dname) + 1;
306 while (*cp != '\0') {
317 * Return true if running ${.MAKE}
318 * Bypassed if target is flagged .MAKE
321 is_submake(void *cmdp, void *gnp)
323 static const char *p_make = NULL;
330 int rc = 0; /* keep looking */
334 p_make = Var_Value(".MAKE", gn, &dontFreeIt);
335 p_len = strlen(p_make);
337 cp = strchr(cmd, '$');
339 (void)Var_Subst(cmd, gn, VARE_WANTRES, &mp);
340 /* TODO: handle errors */
343 cp2 = strstr(cmd, p_make);
345 switch (cp2[p_len]) {
353 if (cp2 > cmd && rc > 0) {
360 rc = 0; /* no match */
369 typedef struct meta_file_s {
375 printCMD(const char *cmd, meta_file_t *mfp)
377 char *cmd_freeIt = NULL;
379 if (strchr(cmd, '$')) {
380 (void)Var_Subst(cmd, mfp->gn, VARE_WANTRES, &cmd_freeIt);
381 /* TODO: handle errors */
384 fprintf(mfp->fp, "CMD %s\n", cmd);
389 printCMDs(GNode *gn, meta_file_t *mf)
393 for (ln = gn->commands->first; ln != NULL; ln = ln->next)
394 printCMD(ln->datum, mf);
398 * Certain node types never get a .meta file
400 #define SKIP_META_TYPE(_type) do { \
401 if ((gn->type & __CONCAT(OP_, _type))) { \
403 debug_printf("Skipping meta for %s: .%s\n", \
404 gn->name, __STRING(_type)); \
412 * Do we need/want a .meta file ?
415 meta_needed(GNode *gn, const char *dname,
416 char *objdir, int verbose)
418 struct make_stat mst;
421 verbose = DEBUG(META);
423 /* This may be a phony node which we don't want meta data for... */
424 /* Skip .meta for .BEGIN, .END, .ERROR etc as well. */
425 /* Or it may be explicitly flagged as .NOMETA */
426 SKIP_META_TYPE(NOMETA);
427 /* Unless it is explicitly flagged as .META */
428 if (!(gn->type & OP_META)) {
429 SKIP_META_TYPE(PHONY);
430 SKIP_META_TYPE(SPECIAL);
431 SKIP_META_TYPE(MAKE);
434 /* Check if there are no commands to execute. */
435 if (Lst_IsEmpty(gn->commands)) {
437 debug_printf("Skipping meta for %s: no commands\n", gn->name);
440 if ((gn->type & (OP_META|OP_SUBMAKE)) == OP_SUBMAKE) {
441 /* OP_SUBMAKE is a bit too aggressive */
442 if (Lst_ForEachUntil(gn->commands, is_submake, gn)) {
443 DEBUG1(META, "Skipping meta for %s: .SUBMAKE\n", gn->name);
448 /* The object directory may not exist. Check it.. */
449 if (cached_stat(dname, &mst) != 0) {
451 debug_printf("Skipping meta for %s: no .OBJDIR\n", gn->name);
455 /* make sure these are canonical */
456 if (cached_realpath(dname, objdir))
459 /* If we aren't in the object directory, don't create a meta file. */
460 if (!metaCurdirOk && strcmp(curdir, dname) == 0) {
462 debug_printf("Skipping meta for %s: .OBJDIR == .CURDIR\n",
471 meta_create(BuildMon *pbm, GNode *gn)
474 char buf[MAXPATHLEN];
475 char objdir[MAXPATHLEN];
485 dname = Var_Value(".OBJDIR", gn, &objdir_freeIt);
486 tname = GNode_VarTarget(gn);
488 /* if this succeeds objdir is realpath of dname */
489 if (!meta_needed(gn, dname, objdir, TRUE))
496 /* Describe the target we are building */
497 (void)Var_Subst("${" MAKE_META_PREFIX "}", gn, VARE_WANTRES, &mp);
498 /* TODO: handle errors */
500 fprintf(stdout, "%s\n", mp);
503 /* Get the basename of the target */
504 if ((cp = strrchr(tname, '/')) == NULL) {
513 /* Don't create meta data. */
516 fname = meta_name(pbm->meta_fname, sizeof(pbm->meta_fname),
517 dname, tname, objdir);
519 #ifdef DEBUG_META_MODE
520 DEBUG1(META, "meta_create: %s\n", fname);
523 if ((mf.fp = fopen(fname, "w")) == NULL)
524 err(1, "Could not open meta file '%s'", fname);
526 fprintf(mf.fp, "# Meta data file %s\n", fname);
532 fprintf(mf.fp, "CWD %s\n", getcwd(buf, sizeof(buf)));
533 fprintf(mf.fp, "TARGET %s\n", tname);
534 cp = GNode_VarOodate(gn);
536 fprintf(mf.fp, "OODATE %s\n", cp);
539 for (ptr = environ; *ptr != NULL; ptr++)
540 fprintf(mf.fp, "ENV %s\n", *ptr);
543 fprintf(mf.fp, "-- command output --\n");
546 Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL);
547 Var_Append(".MAKE.META.CREATED", fname, VAR_GLOBAL);
549 gn->type |= OP_META; /* in case anyone wants to know */
551 gn->type |= OP_SILENT;
554 bmake_free(objdir_freeIt);
574 * Initialization we need before reading makefiles.
580 /* this allows makefiles to test if we have filemon support */
581 Var_Set(".MAKE.PATH_FILEMON", filemon_path(), VAR_GLOBAL);
586 #define get_mode_bf(bf, token) \
587 if ((cp = strstr(make_mode, token))) \
588 bf = boolValue(&cp[sizeof(token) - 1])
591 * Initialization we need after reading makefiles.
594 meta_mode_init(const char *make_mode)
605 if (strstr(make_mode, "env"))
607 if (strstr(make_mode, "verb"))
609 if (strstr(make_mode, "read"))
611 if (strstr(make_mode, "nofilemon"))
613 if (strstr(make_mode, "ignore-cmd"))
614 metaIgnoreCMDs = TRUE;
616 get_mode_bf(filemonMissing, "missing-filemon=");
617 get_mode_bf(metaCurdirOk, "curdirok=");
618 get_mode_bf(metaMissing, "missing-meta=");
619 get_mode_bf(metaSilent, "silent=");
621 if (metaVerbose && !Var_Exists(MAKE_META_PREFIX, VAR_GLOBAL)) {
623 * The default value for MAKE_META_PREFIX
624 * prints the absolute path of the target.
625 * This works be cause :H will generate '.' if there is no /
626 * and :tA will resolve that to cwd.
628 Var_Set(MAKE_META_PREFIX, "Building ${.TARGET:H:tA}/${.TARGET:T}", VAR_GLOBAL);
633 memset(&Mybm, 0, sizeof(Mybm));
635 * We consider ourselves master of all within ${.MAKE.META.BAILIWICK}
637 metaBailiwick = Lst_New();
638 (void)Var_Subst("${.MAKE.META.BAILIWICK:O:u:tA}",
639 VAR_GLOBAL, VARE_WANTRES, &metaBailiwickStr);
640 /* TODO: handle errors */
641 str2Lst_Append(metaBailiwick, metaBailiwickStr, NULL);
643 * We ignore any paths that start with ${.MAKE.META.IGNORE_PATHS}
645 metaIgnorePaths = Lst_New();
646 Var_Append(MAKE_META_IGNORE_PATHS,
647 "/dev /etc /proc /tmp /var/run /var/tmp ${TMPDIR}", VAR_GLOBAL);
648 (void)Var_Subst("${" MAKE_META_IGNORE_PATHS ":O:u:tA}",
649 VAR_GLOBAL, VARE_WANTRES, &metaIgnorePathsStr);
650 /* TODO: handle errors */
651 str2Lst_Append(metaIgnorePaths, metaIgnorePathsStr, NULL);
654 * We ignore any paths that match ${.MAKE.META.IGNORE_PATTERNS}
657 if (Var_Value(MAKE_META_IGNORE_PATTERNS, VAR_GLOBAL, &freeIt)) {
658 metaIgnorePatterns = TRUE;
662 if (Var_Value(MAKE_META_IGNORE_FILTER, VAR_GLOBAL, &freeIt)) {
663 metaIgnoreFilter = TRUE;
669 * In each case below we allow for job==NULL
672 meta_job_start(Job *job, GNode *gn)
681 pbm->mfp = meta_create(pbm, gn);
682 #ifdef USE_FILEMON_ONCE
683 /* compat mode we open the filemon dev once per command */
688 if (pbm->mfp != NULL && useFilemon) {
689 meta_open_filemon(pbm);
698 * The child calls this before doing anything.
699 * It does not disturb our state.
702 meta_job_child(Job *job)
712 if (pbm->mfp != NULL) {
713 close(fileno(pbm->mfp));
714 if (useFilemon && pbm->filemon) {
718 if (filemon_setpid_child(pbm->filemon, pid) == -1) {
719 err(1, "Could not set filemon pid!");
727 meta_job_parent(Job *job, pid_t pid)
729 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
737 if (useFilemon && pbm->filemon) {
738 filemon_setpid_parent(pbm->filemon, pid);
744 meta_job_fd(Job *job)
746 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
754 if (useFilemon && pbm->filemon) {
755 return filemon_readfd(pbm->filemon);
762 meta_job_event(Job *job)
764 #if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
772 if (useFilemon && pbm->filemon) {
773 return filemon_process(pbm->filemon);
780 meta_job_error(Job *job, GNode *gn, int flags, int status)
782 char cwd[MAXPATHLEN];
792 if (pbm->mfp != NULL) {
793 fprintf(pbm->mfp, "\n*** Error code %d%s\n",
795 (flags & JOB_IGNERR) ?
799 Var_Set(".ERROR_TARGET", GNode_Path(gn), VAR_GLOBAL);
801 getcwd(cwd, sizeof(cwd));
802 Var_Set(".ERROR_CWD", cwd, VAR_GLOBAL);
803 if (pbm->meta_fname[0]) {
804 Var_Set(".ERROR_META_FILE", pbm->meta_fname, VAR_GLOBAL);
806 meta_job_finish(job);
810 meta_job_output(Job *job, char *cp, const char *nl)
819 if (pbm->mfp != NULL) {
821 static char *meta_prefix = NULL;
822 static size_t meta_prefix_len;
827 (void)Var_Subst("${" MAKE_META_PREFIX "}",
828 VAR_GLOBAL, VARE_WANTRES, &meta_prefix);
829 /* TODO: handle errors */
830 if ((cp2 = strchr(meta_prefix, '$')))
831 meta_prefix_len = (size_t)(cp2 - meta_prefix);
833 meta_prefix_len = strlen(meta_prefix);
835 if (strncmp(cp, meta_prefix, meta_prefix_len) == 0) {
836 cp = strchr(cp+1, '\n');
841 fprintf(pbm->mfp, "%s%s", cp, nl);
846 meta_cmd_finish(void *pbmp)
849 BuildMon *pbm = pbmp;
859 while (filemon_process(pbm->filemon) > 0)
861 if (filemon_close(pbm->filemon) == -1)
863 x = filemon_read(pbm->mfp, pbm->mon_fd);
864 if (error == 0 && x != 0)
870 fprintf(pbm->mfp, "\n"); /* ensure end with newline */
875 meta_job_finish(Job *job)
886 if (pbm->mfp != NULL) {
887 error = meta_cmd_finish(pbm);
888 x = fclose(pbm->mfp);
889 if (error == 0 && x != 0)
892 pbm->meta_fname[0] = '\0';
900 if (metaBailiwick != NULL)
901 Lst_Free(metaBailiwick);
902 free(metaBailiwickStr);
903 if (metaIgnorePaths != NULL)
904 Lst_Free(metaIgnorePaths);
905 free(metaIgnorePathsStr);
909 * Fetch a full line from fp - growing bufp if needed
910 * Return length in bufp.
913 fgetLine(char **bufp, size_t *szp, int o, FILE *fp)
920 if (fgets(&buf[o], (int)bufsz - o, fp) != NULL) {
922 x = o + (int)strlen(&buf[o]);
923 if (buf[x - 1] == '\n')
926 * We need to grow the buffer.
927 * The meta file can give us a clue.
929 if (fstat(fileno(fp), &fs) == 0) {
933 newsz = ROUNDUP(((size_t)fs.st_size / 2), BUFSIZ);
935 newsz = ROUNDUP((size_t)fs.st_size, BUFSIZ);
937 return x; /* truncated */
938 DEBUG2(META, "growing buffer %zu -> %zu\n", bufsz, newsz);
939 p = bmake_realloc(buf, newsz);
942 *szp = bufsz = newsz;
944 if (!fgets(&buf[x], (int)bufsz - x, fp))
945 return x; /* truncated! */
953 /* Lst_ForEachUntil wants 1 to stop search */
955 prefix_match(void *p, void *q)
957 const char *prefix = p;
958 const char *path = q;
959 size_t n = strlen(prefix);
961 return strncmp(path, prefix, n) == 0;
964 /* See if the path equals prefix or starts with "prefix/". */
966 path_starts_with(const char *path, const char *prefix)
968 size_t n = strlen(prefix);
970 if (strncmp(path, prefix, n) != 0)
972 return path[n] == '\0' || path[n] == '/';
976 meta_ignore(GNode *gn, const char *p)
978 char fname[MAXPATHLEN];
984 cached_realpath(p, fname); /* clean it up */
985 if (Lst_ForEachUntil(metaIgnorePaths, prefix_match, fname)) {
986 #ifdef DEBUG_META_MODE
987 DEBUG1(META, "meta_oodate: ignoring path: %s\n", p);
993 if (metaIgnorePatterns) {
997 Var_Set(".p.", p, gn);
998 expr = "${" MAKE_META_IGNORE_PATTERNS ":@m@${.p.:M$m}@}";
999 (void)Var_Subst(expr, gn, VARE_WANTRES, &pm);
1000 /* TODO: handle errors */
1002 #ifdef DEBUG_META_MODE
1003 DEBUG1(META, "meta_oodate: ignoring pattern: %s\n", p);
1011 if (metaIgnoreFilter) {
1014 /* skip if filter result is empty */
1015 snprintf(fname, sizeof(fname),
1016 "${%s:L:${%s:ts:}}",
1017 p, MAKE_META_IGNORE_FILTER);
1018 (void)Var_Subst(fname, gn, VARE_WANTRES, &fm);
1019 /* TODO: handle errors */
1021 #ifdef DEBUG_META_MODE
1022 DEBUG1(META, "meta_oodate: ignoring filtered: %s\n", p);
1033 * When running with 'meta' functionality, a target can be out-of-date
1034 * if any of the references in its meta data file is more recent.
1035 * We have to track the latestdir on a per-process basis.
1037 #define LCWD_VNAME_FMT ".meta.%d.lcwd"
1038 #define LDIR_VNAME_FMT ".meta.%d.ldir"
1041 * It is possible that a .meta file is corrupted,
1042 * if we detect this we want to reproduce it.
1043 * Setting oodate TRUE will have that effect.
1045 #define CHECK_VALID_META(p) if (!(p && *p)) { \
1046 warnx("%s: %d: malformed", fname, lineno); \
1051 #define DEQUOTE(p) if (*p == '\'') { \
1054 if ((ep = strchr(p, '\''))) \
1059 append_if_new(StringList *list, const char *str)
1063 for (ln = list->first; ln != NULL; ln = ln->next)
1064 if (strcmp(ln->datum, str) == 0)
1066 Lst_Append(list, bmake_strdup(str));
1070 meta_oodate(GNode *gn, Boolean oodate)
1072 static char *tmpdir = NULL;
1073 static char cwd[MAXPATHLEN];
1074 char lcwd_vname[64];
1075 char ldir_vname[64];
1076 char lcwd[MAXPATHLEN];
1077 char latestdir[MAXPATHLEN];
1078 char fname[MAXPATHLEN];
1079 char fname1[MAXPATHLEN];
1080 char fname2[MAXPATHLEN];
1081 char fname3[MAXPATHLEN];
1088 static size_t cwdlen = 0;
1089 static size_t tmplen = 0;
1091 Boolean needOODATE = FALSE;
1092 StringList *missingFiles;
1093 int have_filemon = FALSE;
1094 void *objdir_freeIt;
1097 return oodate; /* we're done */
1099 dname = Var_Value(".OBJDIR", gn, &objdir_freeIt);
1100 tname = GNode_VarTarget(gn);
1102 /* if this succeeds fname3 is realpath of dname */
1103 if (!meta_needed(gn, dname, fname3, FALSE))
1107 missingFiles = Lst_New();
1110 * We need to check if the target is out-of-date. This includes
1111 * checking if the expanded command has changed. This in turn
1112 * requires that all variables are set in the same way that they
1113 * would be if the target needs to be re-built.
1117 meta_name(fname, sizeof(fname), dname, tname, dname);
1119 #ifdef DEBUG_META_MODE
1120 DEBUG1(META, "meta_oodate: %s\n", fname);
1123 if ((fp = fopen(fname, "r")) != NULL) {
1124 static char *buf = NULL;
1125 static size_t bufsz;
1130 StringListNode *cmdNode;
1131 struct make_stat mst;
1135 buf = bmake_malloc(bufsz);
1139 if (getcwd(cwd, sizeof(cwd)) == NULL)
1140 err(1, "Could not get current working directory");
1141 cwdlen = strlen(cwd);
1143 strlcpy(lcwd, cwd, sizeof(lcwd));
1144 strlcpy(latestdir, cwd, sizeof(latestdir));
1147 tmpdir = getTmpdir();
1148 tmplen = strlen(tmpdir);
1151 /* we want to track all the .meta we read */
1152 Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL);
1154 cmdNode = gn->commands->first;
1155 while (!oodate && (x = fgetLine(&buf, &bufsz, 0, fp)) > 0) {
1157 if (buf[x - 1] == '\n')
1160 warnx("%s: %d: line truncated at %u", fname, lineno, x);
1166 /* Find the start of the build monitor section. */
1167 if (!have_filemon) {
1168 if (strncmp(buf, "-- filemon", 10) == 0) {
1169 have_filemon = TRUE;
1172 if (strncmp(buf, "# buildmon", 10) == 0) {
1173 have_filemon = TRUE;
1178 /* Delimit the record type. */
1180 #ifdef DEBUG_META_MODE
1181 DEBUG3(META, "%s: %d: %s\n", fname, lineno, buf);
1186 * We are in the 'filemon' output section.
1187 * Each record from filemon follows the general form:
1189 * <key> <pid> <data>
1192 * <key> is a single letter, denoting the syscall.
1193 * <pid> is the process that made the syscall.
1194 * <data> is the arguments (of interest).
1197 case '#': /* comment */
1198 case 'V': /* version */
1202 * We need to track pathnames per-process.
1204 * Each process run by make, starts off in the 'CWD'
1205 * recorded in the .meta file, if it chdirs ('C')
1206 * elsewhere we need to track that - but only for
1207 * that process. If it forks ('F'), we initialize
1208 * the child to have the same cwd as its parent.
1210 * We also need to track the 'latestdir' of
1211 * interest. This is usually the same as cwd, but
1212 * not if a process is reading directories.
1214 * Each time we spot a different process ('pid')
1215 * we save the current value of 'latestdir' in a
1216 * variable qualified by 'lastpid', and
1217 * re-initialize 'latestdir' to any pre-saved
1218 * value for the current 'pid' and 'CWD' if none.
1220 CHECK_VALID_META(p);
1222 if (pid > 0 && pid != lastpid) {
1227 /* We need to remember these. */
1228 Var_Set(lcwd_vname, lcwd, VAR_GLOBAL);
1229 Var_Set(ldir_vname, latestdir, VAR_GLOBAL);
1231 snprintf(lcwd_vname, sizeof(lcwd_vname), LCWD_VNAME_FMT, pid);
1232 snprintf(ldir_vname, sizeof(ldir_vname), LDIR_VNAME_FMT, pid);
1234 ldir = Var_Value(ldir_vname, VAR_GLOBAL, &tp);
1236 strlcpy(latestdir, ldir, sizeof(latestdir));
1239 ldir = Var_Value(lcwd_vname, VAR_GLOBAL, &tp);
1241 strlcpy(lcwd, ldir, sizeof(lcwd));
1245 /* Skip past the pid. */
1246 if (strsep(&p, " ") == NULL)
1248 #ifdef DEBUG_META_MODE
1250 debug_printf("%s: %d: %d: %c: cwd=%s lcwd=%s ldir=%s\n",
1252 pid, buf[0], cwd, lcwd, latestdir);
1257 CHECK_VALID_META(p);
1259 /* Process according to record type. */
1261 case 'X': /* eXit */
1262 Var_Delete(lcwd_vname, VAR_GLOBAL);
1263 Var_Delete(ldir_vname, VAR_GLOBAL);
1264 lastpid = 0; /* no need to save ldir_vname */
1267 case 'F': /* [v]Fork */
1274 snprintf(cldir, sizeof(cldir), LCWD_VNAME_FMT, child);
1275 Var_Set(cldir, lcwd, VAR_GLOBAL);
1276 snprintf(cldir, sizeof(cldir), LDIR_VNAME_FMT, child);
1277 Var_Set(cldir, latestdir, VAR_GLOBAL);
1278 #ifdef DEBUG_META_MODE
1281 "%s: %d: %d: cwd=%s lcwd=%s ldir=%s\n",
1283 child, cwd, lcwd, latestdir);
1289 case 'C': /* Chdir */
1290 /* Update lcwd and latest directory. */
1291 strlcpy(latestdir, p, sizeof(latestdir));
1292 strlcpy(lcwd, p, sizeof(lcwd));
1293 Var_Set(lcwd_vname, lcwd, VAR_GLOBAL);
1294 Var_Set(ldir_vname, lcwd, VAR_GLOBAL);
1295 #ifdef DEBUG_META_MODE
1296 DEBUG4(META, "%s: %d: cwd=%s ldir=%s\n",
1297 fname, lineno, cwd, lcwd);
1301 case 'M': /* renaMe */
1303 * For 'M'oves we want to check
1304 * the src as for 'R'ead
1305 * and the target as for 'W'rite.
1307 cp = p; /* save this for a second */
1308 /* now get target */
1309 if (strsep(&p, " ") == NULL)
1311 CHECK_VALID_META(p);
1314 /* 'L' and 'M' put single quotes around the args */
1316 DEQUOTE(move_target);
1318 case 'D': /* unlink */
1320 /* remove any missingFiles entries that match p */
1321 StringListNode *ln = missingFiles->first;
1322 while (ln != NULL) {
1323 StringListNode *next = ln->next;
1324 if (path_starts_with(ln->datum, p)) {
1326 Lst_Remove(missingFiles, ln);
1331 if (buf[0] == 'M') {
1332 /* the target of the mv is a file 'W'ritten */
1333 #ifdef DEBUG_META_MODE
1334 DEBUG2(META, "meta_oodate: M %s -> %s\n",
1341 case 'L': /* Link */
1344 * the src as for 'R'ead
1345 * and the target as for 'W'rite.
1348 /* now get target */
1349 if (strsep(&p, " ") == NULL)
1351 CHECK_VALID_META(p);
1352 /* 'L' and 'M' put single quotes around the args */
1355 #ifdef DEBUG_META_MODE
1356 DEBUG2(META, "meta_oodate: L %s -> %s\n", link_src, p);
1359 case 'W': /* Write */
1362 * If a file we generated within our bailiwick
1363 * but outside of .OBJDIR is missing,
1364 * we need to do it again.
1366 /* ignore non-absolute paths */
1370 if (Lst_IsEmpty(metaBailiwick))
1373 /* ignore cwd - normal dependencies handle those */
1374 if (strncmp(p, cwd, cwdlen) == 0)
1377 if (!Lst_ForEachUntil(metaBailiwick, prefix_match, p))
1380 /* tmpdir might be within */
1381 if (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0)
1384 /* ignore anything containing the string "tmp" */
1385 if ((strstr("tmp", p)))
1388 if ((link_src != NULL && cached_lstat(p, &mst) < 0) ||
1389 (link_src == NULL && cached_stat(p, &mst) < 0)) {
1390 if (!meta_ignore(gn, p))
1391 append_if_new(missingFiles, p);
1397 #ifdef DEBUG_META_MODE
1398 DEBUG1(META, "meta_oodate: L src %s\n", p);
1401 case 'R': /* Read */
1402 case 'E': /* Exec */
1404 * Check for runtime files that can't
1405 * be part of the dependencies because
1406 * they are _expected_ to change.
1408 if (meta_ignore(gn, p))
1412 * The rest of the record is the file name.
1413 * Check if it's not an absolute path.
1422 sdirs[sdx++] = p; /* done */
1424 if (strcmp(".", p) == 0)
1425 continue; /* no point */
1427 /* Check vs latestdir */
1428 snprintf(fname1, sizeof(fname1), "%s/%s", latestdir, p);
1429 sdirs[sdx++] = fname1;
1431 if (strcmp(latestdir, lcwd) != 0) {
1433 snprintf(fname2, sizeof(fname2), "%s/%s", lcwd, p);
1434 sdirs[sdx++] = fname2;
1436 if (strcmp(lcwd, cwd) != 0) {
1438 snprintf(fname3, sizeof(fname3), "%s/%s", cwd, p);
1439 sdirs[sdx++] = fname3;
1442 sdirs[sdx++] = NULL;
1444 for (sdp = sdirs; *sdp && !found; sdp++) {
1445 #ifdef DEBUG_META_MODE
1446 DEBUG3(META, "%s: %d: looking for: %s\n",
1447 fname, lineno, *sdp);
1449 if (cached_stat(*sdp, &mst) == 0) {
1455 #ifdef DEBUG_META_MODE
1456 DEBUG3(META, "%s: %d: found: %s\n",
1459 if (!S_ISDIR(mst.mst_mode) &&
1460 mst.mst_mtime > gn->mtime) {
1461 DEBUG3(META, "%s: %d: file '%s' is newer than the target...\n",
1464 } else if (S_ISDIR(mst.mst_mode)) {
1465 /* Update the latest directory. */
1466 cached_realpath(p, latestdir);
1468 } else if (errno == ENOENT && *p == '/' &&
1469 strncmp(p, cwd, cwdlen) != 0) {
1471 * A referenced file outside of CWD is missing.
1472 * We cannot catch every eventuality here...
1474 append_if_new(missingFiles, p);
1477 if (buf[0] == 'E') {
1478 /* previous latestdir is no longer relevant */
1479 strlcpy(latestdir, lcwd, sizeof(latestdir));
1485 if (!oodate && buf[0] == 'L' && link_src != NULL)
1486 goto check_link_src;
1487 } else if (strcmp(buf, "CMD") == 0) {
1489 * Compare the current command with the one in the
1492 if (cmdNode == NULL) {
1493 DEBUG2(META, "%s: %d: there were more build commands in the meta data file than there are now...\n",
1497 char *cmd = cmdNode->datum;
1498 Boolean hasOODATE = FALSE;
1500 if (strstr(cmd, "$?"))
1502 else if ((cp = strstr(cmd, ".OODATE"))) {
1503 /* check for $[{(].OODATE[:)}] */
1504 if (cp > cmd + 2 && cp[-2] == '$')
1509 DEBUG2(META, "%s: %d: cannot compare command using .OODATE\n",
1512 (void)Var_Subst(cmd, gn, VARE_WANTRES|VARE_UNDEFERR, &cmd);
1513 /* TODO: handle errors */
1515 if ((cp = strchr(cmd, '\n'))) {
1519 * This command contains newlines, we need to
1520 * fetch more from the .meta file before we
1521 * attempt a comparison.
1523 /* first put the newline back at buf[x - 1] */
1526 /* now fetch the next line */
1527 if ((n = fgetLine(&buf, &bufsz, x, fp)) <= 0)
1531 if (buf[x - 1] != '\n') {
1532 warnx("%s: %d: line truncated at %u", fname, lineno, x);
1535 cp = strchr(++cp, '\n');
1537 if (buf[x - 1] == '\n')
1542 !(gn->type & OP_NOMETA_CMP) &&
1543 strcmp(p, cmd) != 0) {
1544 DEBUG4(META, "%s: %d: a build command has changed\n%s\nvs\n%s\n",
1545 fname, lineno, p, cmd);
1546 if (!metaIgnoreCMDs)
1550 cmdNode = cmdNode->next;
1552 } else if (strcmp(buf, "CWD") == 0) {
1554 * Check if there are extra commands now
1555 * that weren't in the meta data file.
1557 if (!oodate && cmdNode != NULL) {
1558 DEBUG2(META, "%s: %d: there are extra build commands now that weren't in the meta data file\n",
1562 CHECK_VALID_META(p);
1563 if (strcmp(p, cwd) != 0) {
1564 DEBUG4(META, "%s: %d: the current working directory has changed from '%s' to '%s'\n",
1565 fname, lineno, p, curdir);
1572 if (!Lst_IsEmpty(missingFiles)) {
1573 DEBUG2(META, "%s: missing files: %s...\n",
1574 fname, (char *)missingFiles->first->datum);
1577 if (!oodate && !have_filemon && filemonMissing) {
1578 DEBUG1(META, "%s: missing filemon data\n", fname);
1582 if (writeMeta && (metaMissing || (gn->type & OP_META))) {
1585 /* if target is in .CURDIR we do not need a meta file */
1586 if (gn->path && (cp = strrchr(gn->path, '/')) && cp > gn->path) {
1587 if (strncmp(curdir, gn->path, (size_t)(cp - gn->path)) != 0) {
1588 cp = NULL; /* not in .CURDIR */
1592 DEBUG1(META, "%s: required but missing\n", fname);
1594 needOODATE = TRUE; /* assume the worst */
1599 Lst_Destroy(missingFiles, free);
1601 if (oodate && needOODATE) {
1603 * Target uses .OODATE which is empty; or we wouldn't be here.
1604 * We have decided it is oodate, so .OODATE needs to be set.
1605 * All we can sanely do is set it to .ALLSRC.
1607 Var_Delete(OODATE, gn);
1608 Var_Set(OODATE, GNode_VarAllsrc(gn), gn);
1612 bmake_free(objdir_freeIt);
1616 /* support for compat mode */
1618 static int childPipe[2];
1621 meta_compat_start(void)
1623 #ifdef USE_FILEMON_ONCE
1625 * We need to re-open filemon for each cmd.
1627 BuildMon *pbm = &Mybm;
1629 if (pbm->mfp != NULL && useFilemon) {
1630 meta_open_filemon(pbm);
1633 pbm->filemon = NULL;
1636 if (pipe(childPipe) < 0)
1637 Punt("Cannot create pipe: %s", strerror(errno));
1638 /* Set close-on-exec flag for both */
1639 (void)fcntl(childPipe[0], F_SETFD, FD_CLOEXEC);
1640 (void)fcntl(childPipe[1], F_SETFD, FD_CLOEXEC);
1644 meta_compat_child(void)
1646 meta_job_child(NULL);
1647 if (dup2(childPipe[1], 1) < 0 || dup2(1, 2) < 0)
1648 execDie("dup2", "pipe");
1652 meta_compat_parent(pid_t child)
1654 int outfd, metafd, maxfd, nfds;
1658 meta_job_parent(NULL, child);
1659 close(childPipe[1]); /* child side */
1660 outfd = childPipe[0];
1662 metafd = Mybm.filemon ? filemon_readfd(Mybm.filemon) : -1;
1672 while (outfd != -1 || metafd != -1) {
1675 FD_SET(outfd, &readfds);
1678 FD_SET(metafd, &readfds);
1680 nfds = select(maxfd + 1, &readfds, NULL, NULL, NULL);
1687 if (outfd != -1 && FD_ISSET(outfd, &readfds)) do {
1688 /* XXX this is not line-buffered */
1689 ssize_t nread = read(outfd, buf, sizeof(buf) - 1);
1697 fwrite(buf, 1, (size_t)nread, stdout);
1700 meta_job_output(NULL, buf, "");
1702 if (metafd != -1 && FD_ISSET(metafd, &readfds)) {
1703 if (meta_job_event(NULL) <= 0)
1709 #endif /* USE_META */