Update to bmake-20141111 on the vendor branch
[dragonfly.git] / contrib / bmake / meta.c
blob4b9add76c38b28222b013d6f55cb3cfb0a010a02
1 /* $NetBSD: meta.c,v 1.36 2014/11/06 01:36:57 sjg Exp $ */
3 /*
4 * Implement 'meta' mode.
5 * Adapted from John Birrell's patches to FreeBSD make.
6 * --sjg
7 */
8 /*
9 * Copyright (c) 2009-2010, 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
14 * are met:
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.
33 #if defined(USE_META)
35 #ifdef HAVE_CONFIG_H
36 # include "config.h"
37 #endif
38 #include <sys/stat.h>
39 #include <sys/ioctl.h>
40 #include <fcntl.h>
41 #include <libgen.h>
42 #include <errno.h>
43 #if !defined(HAVE_CONFIG_H) || defined(HAVE_ERR_H)
44 #include <err.h>
45 #endif
47 #include "make.h"
48 #include "job.h"
50 #ifdef HAVE_FILEMON_H
51 # include <filemon.h>
52 #endif
53 #if !defined(USE_FILEMON) && defined(FILEMON_SET_FD)
54 # define USE_FILEMON
55 #endif
57 static BuildMon Mybm; /* for compat */
58 static Lst metaBailiwick; /* our scope of control */
59 static Lst metaIgnorePaths; /* paths we deliberately ignore */
61 #ifndef MAKE_META_IGNORE_PATHS
62 #define MAKE_META_IGNORE_PATHS ".MAKE.META.IGNORE_PATHS"
63 #endif
65 Boolean useMeta = FALSE;
66 static Boolean useFilemon = FALSE;
67 static Boolean writeMeta = FALSE;
68 static Boolean metaEnv = FALSE; /* don't save env unless asked */
69 static Boolean metaVerbose = FALSE;
70 static Boolean metaIgnoreCMDs = FALSE; /* ignore CMDs in .meta files */
71 static Boolean metaCurdirOk = FALSE; /* write .meta in .CURDIR Ok? */
72 static Boolean metaSilent = FALSE; /* if we have a .meta be SILENT */
74 extern Boolean forceJobs;
75 extern Boolean comatMake;
76 extern char **environ;
78 #define MAKE_META_PREFIX ".MAKE.META.PREFIX"
80 #ifndef N2U
81 # define N2U(n, u) (((n) + ((u) - 1)) / (u))
82 #endif
83 #ifndef ROUNDUP
84 # define ROUNDUP(n, u) (N2U((n), (u)) * (u))
85 #endif
87 #if !defined(HAVE_STRSEP)
88 # define strsep(s, d) stresep((s), (d), 0)
89 #endif
92 * Filemon is a kernel module which snoops certain syscalls.
94 * C chdir
95 * E exec
96 * F [v]fork
97 * L [sym]link
98 * M rename
99 * R read
100 * W write
101 * S stat
103 * See meta_oodate below - we mainly care about 'E' and 'R'.
105 * We can still use meta mode without filemon, but
106 * the benefits are more limited.
108 #ifdef USE_FILEMON
109 # ifndef _PATH_FILEMON
110 # define _PATH_FILEMON "/dev/filemon"
111 # endif
114 * Open the filemon device.
116 static void
117 filemon_open(BuildMon *pbm)
119 int retry;
121 pbm->mon_fd = pbm->filemon_fd = -1;
122 if (!useFilemon)
123 return;
125 for (retry = 5; retry >= 0; retry--) {
126 if ((pbm->filemon_fd = open(_PATH_FILEMON, O_RDWR)) >= 0)
127 break;
130 if (pbm->filemon_fd < 0) {
131 useFilemon = FALSE;
132 warn("Could not open %s", _PATH_FILEMON);
133 return;
137 * We use a file outside of '.'
138 * to avoid a FreeBSD kernel bug where unlink invalidates
139 * cwd causing getcwd to do a lot more work.
140 * We only care about the descriptor.
142 pbm->mon_fd = mkTempFile("filemon.XXXXXX", NULL);
143 if (ioctl(pbm->filemon_fd, FILEMON_SET_FD, &pbm->mon_fd) < 0) {
144 err(1, "Could not set filemon file descriptor!");
146 /* we don't need these once we exec */
147 (void)fcntl(pbm->mon_fd, F_SETFD, 1);
148 (void)fcntl(pbm->filemon_fd, F_SETFD, 1);
152 * Read the build monitor output file and write records to the target's
153 * metadata file.
155 static void
156 filemon_read(FILE *mfp, int fd)
158 char buf[BUFSIZ];
159 int n;
161 /* Check if we're not writing to a meta data file.*/
162 if (mfp == NULL) {
163 if (fd >= 0)
164 close(fd); /* not interested */
165 return;
167 /* rewind */
168 (void)lseek(fd, (off_t)0, SEEK_SET);
170 fprintf(mfp, "\n-- filemon acquired metadata --\n");
172 while ((n = read(fd, buf, sizeof(buf))) > 0) {
173 fwrite(buf, 1, n, mfp);
175 fflush(mfp);
176 close(fd);
178 #endif
181 * when realpath() fails,
182 * we use this, to clean up ./ and ../
184 static void
185 eat_dots(char *buf, size_t bufsz, int dots)
187 char *cp;
188 char *cp2;
189 const char *eat;
190 size_t eatlen;
192 switch (dots) {
193 case 1:
194 eat = "/./";
195 eatlen = 2;
196 break;
197 case 2:
198 eat = "/../";
199 eatlen = 3;
200 break;
201 default:
202 return;
205 do {
206 cp = strstr(buf, eat);
207 if (cp) {
208 cp2 = cp + eatlen;
209 if (dots == 2 && cp > buf) {
210 do {
211 cp--;
212 } while (cp > buf && *cp != '/');
214 if (*cp == '/') {
215 strlcpy(cp, cp2, bufsz - (cp - buf));
216 } else {
217 return; /* can't happen? */
220 } while (cp);
223 static char *
224 meta_name(struct GNode *gn, char *mname, size_t mnamelen,
225 const char *dname,
226 const char *tname)
228 char buf[MAXPATHLEN];
229 char cwd[MAXPATHLEN];
230 char *rp;
231 char *cp;
232 char *tp;
233 char *p[4]; /* >= number of possible uses */
234 int i;
236 i = 0;
237 if (!dname)
238 dname = Var_Value(".OBJDIR", gn, &p[i++]);
239 if (!tname)
240 tname = Var_Value(TARGET, gn, &p[i++]);
242 if (realpath(dname, cwd))
243 dname = cwd;
246 * Weed out relative paths from the target file name.
247 * We have to be careful though since if target is a
248 * symlink, the result will be unstable.
249 * So we use realpath() just to get the dirname, and leave the
250 * basename as given to us.
252 if ((cp = strrchr(tname, '/'))) {
253 if (realpath(tname, buf)) {
254 if ((rp = strrchr(buf, '/'))) {
255 rp++;
256 cp++;
257 if (strcmp(cp, rp) != 0)
258 strlcpy(rp, cp, sizeof(buf) - (rp - buf));
260 tname = buf;
261 } else {
263 * We likely have a directory which is about to be made.
264 * We pretend realpath() succeeded, to have a chance
265 * of generating the same meta file name that we will
266 * next time through.
268 if (tname[0] == '/') {
269 strlcpy(buf, tname, sizeof(buf));
270 } else {
271 snprintf(buf, sizeof(buf), "%s/%s", cwd, tname);
273 eat_dots(buf, sizeof(buf), 1); /* ./ */
274 eat_dots(buf, sizeof(buf), 2); /* ../ */
275 tname = buf;
278 /* on some systems dirname may modify its arg */
279 tp = bmake_strdup(tname);
280 if (strcmp(dname, dirname(tp)) == 0)
281 snprintf(mname, mnamelen, "%s.meta", tname);
282 else {
283 snprintf(mname, mnamelen, "%s/%s.meta", dname, tname);
286 * Replace path separators in the file name after the
287 * current object directory path.
289 cp = mname + strlen(dname) + 1;
291 while (*cp != '\0') {
292 if (*cp == '/')
293 *cp = '_';
294 cp++;
297 free(tp);
298 for (i--; i >= 0; i--) {
299 if (p[i])
300 free(p[i]);
302 return (mname);
306 * Return true if running ${.MAKE}
307 * Bypassed if target is flagged .MAKE
309 static int
310 is_submake(void *cmdp, void *gnp)
312 static char *p_make = NULL;
313 static int p_len;
314 char *cmd = cmdp;
315 GNode *gn = gnp;
316 char *mp = NULL;
317 char *cp;
318 char *cp2;
319 int rc = 0; /* keep looking */
321 if (!p_make) {
322 p_make = Var_Value(".MAKE", gn, &cp);
323 p_len = strlen(p_make);
325 cp = strchr(cmd, '$');
326 if ((cp)) {
327 mp = Var_Subst(NULL, cmd, gn, FALSE);
328 cmd = mp;
330 cp2 = strstr(cmd, p_make);
331 if ((cp2)) {
332 switch (cp2[p_len]) {
333 case '\0':
334 case ' ':
335 case '\t':
336 case '\n':
337 rc = 1;
338 break;
340 if (cp2 > cmd && rc > 0) {
341 switch (cp2[-1]) {
342 case ' ':
343 case '\t':
344 case '\n':
345 break;
346 default:
347 rc = 0; /* no match */
348 break;
352 if (mp)
353 free(mp);
354 return (rc);
357 typedef struct meta_file_s {
358 FILE *fp;
359 GNode *gn;
360 } meta_file_t;
362 static int
363 printCMD(void *cmdp, void *mfpp)
365 meta_file_t *mfp = mfpp;
366 char *cmd = cmdp;
367 char *cp = NULL;
369 if (strchr(cmd, '$')) {
370 cmd = cp = Var_Subst(NULL, cmd, mfp->gn, FALSE);
372 fprintf(mfp->fp, "CMD %s\n", cmd);
373 if (cp)
374 free(cp);
375 return 0;
379 * Certain node types never get a .meta file
381 #define SKIP_META_TYPE(_type) do { \
382 if ((gn->type & __CONCAT(OP_, _type))) { \
383 if (DEBUG(META)) { \
384 fprintf(debug_file, "Skipping meta for %s: .%s\n", \
385 gn->name, __STRING(_type)); \
387 return (NULL); \
389 } while (0)
391 static FILE *
392 meta_create(BuildMon *pbm, GNode *gn)
394 meta_file_t mf;
395 char buf[MAXPATHLEN];
396 char objdir[MAXPATHLEN];
397 char **ptr;
398 const char *dname;
399 const char *tname;
400 char *fname;
401 const char *cp;
402 char *p[4]; /* >= possible uses */
403 int i;
404 struct stat fs;
407 /* This may be a phony node which we don't want meta data for... */
408 /* Skip .meta for .BEGIN, .END, .ERROR etc as well. */
409 /* Or it may be explicitly flagged as .NOMETA */
410 SKIP_META_TYPE(NOMETA);
411 /* Unless it is explicitly flagged as .META */
412 if (!(gn->type & OP_META)) {
413 SKIP_META_TYPE(PHONY);
414 SKIP_META_TYPE(SPECIAL);
415 SKIP_META_TYPE(MAKE);
418 mf.fp = NULL;
420 i = 0;
422 dname = Var_Value(".OBJDIR", gn, &p[i++]);
423 tname = Var_Value(TARGET, gn, &p[i++]);
425 /* The object directory may not exist. Check it.. */
426 if (stat(dname, &fs) != 0) {
427 if (DEBUG(META))
428 fprintf(debug_file, "Skipping meta for %s: no .OBJDIR\n",
429 gn->name);
430 goto out;
432 /* Check if there are no commands to execute. */
433 if (Lst_IsEmpty(gn->commands)) {
434 if (DEBUG(META))
435 fprintf(debug_file, "Skipping meta for %s: no commands\n",
436 gn->name);
437 goto out;
440 /* make sure these are canonical */
441 if (realpath(dname, objdir))
442 dname = objdir;
444 /* If we aren't in the object directory, don't create a meta file. */
445 if (!metaCurdirOk && strcmp(curdir, dname) == 0) {
446 if (DEBUG(META))
447 fprintf(debug_file, "Skipping meta for %s: .OBJDIR == .CURDIR\n",
448 gn->name);
449 goto out;
451 if (!(gn->type & OP_META)) {
452 /* We do not generate .meta files for sub-makes */
453 if (Lst_ForEach(gn->commands, is_submake, gn)) {
454 if (DEBUG(META))
455 fprintf(debug_file, "Skipping meta for %s: .MAKE\n",
456 gn->name);
457 goto out;
461 if (metaVerbose) {
462 char *mp;
464 /* Describe the target we are building */
465 mp = Var_Subst(NULL, "${" MAKE_META_PREFIX "}", gn, 0);
466 if (*mp)
467 fprintf(stdout, "%s\n", mp);
468 free(mp);
470 /* Get the basename of the target */
471 if ((cp = strrchr(tname, '/')) == NULL) {
472 cp = tname;
473 } else {
474 cp++;
477 fflush(stdout);
479 if (strcmp(cp, makeDependfile) == 0)
480 goto out;
482 if (!writeMeta)
483 /* Don't create meta data. */
484 goto out;
486 fname = meta_name(gn, pbm->meta_fname, sizeof(pbm->meta_fname),
487 dname, tname);
489 #ifdef DEBUG_META_MODE
490 if (DEBUG(META))
491 fprintf(debug_file, "meta_create: %s\n", fname);
492 #endif
494 if ((mf.fp = fopen(fname, "w")) == NULL)
495 err(1, "Could not open meta file '%s'", fname);
497 fprintf(mf.fp, "# Meta data file %s\n", fname);
499 mf.gn = gn;
501 Lst_ForEach(gn->commands, printCMD, &mf);
503 fprintf(mf.fp, "CWD %s\n", getcwd(buf, sizeof(buf)));
504 fprintf(mf.fp, "TARGET %s\n", tname);
506 if (metaEnv) {
507 for (ptr = environ; *ptr != NULL; ptr++)
508 fprintf(mf.fp, "ENV %s\n", *ptr);
511 fprintf(mf.fp, "-- command output --\n");
512 fflush(mf.fp);
514 Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL);
515 Var_Append(".MAKE.META.CREATED", fname, VAR_GLOBAL);
517 gn->type |= OP_META; /* in case anyone wants to know */
518 if (metaSilent) {
519 gn->type |= OP_SILENT;
521 out:
522 for (i--; i >= 0; i--) {
523 if (p[i])
524 free(p[i]);
527 return (mf.fp);
530 static Boolean
531 boolValue(char *s)
533 switch(*s) {
534 case '0':
535 case 'N':
536 case 'n':
537 case 'F':
538 case 'f':
539 return FALSE;
541 return TRUE;
545 * Initialization we need before reading makefiles.
547 void
548 meta_init(void)
550 #ifdef USE_FILEMON
551 /* this allows makefiles to test if we have filemon support */
552 Var_Set(".MAKE.PATH_FILEMON", _PATH_FILEMON, VAR_GLOBAL, 0);
553 #endif
558 * Initialization we need after reading makefiles.
560 void
561 meta_mode_init(const char *make_mode)
563 static int once = 0;
564 char *cp;
566 useMeta = TRUE;
567 useFilemon = TRUE;
568 writeMeta = TRUE;
570 if (make_mode) {
571 if (strstr(make_mode, "env"))
572 metaEnv = TRUE;
573 if (strstr(make_mode, "verb"))
574 metaVerbose = TRUE;
575 if (strstr(make_mode, "read"))
576 writeMeta = FALSE;
577 if (strstr(make_mode, "nofilemon"))
578 useFilemon = FALSE;
579 if ((cp = strstr(make_mode, "curdirok="))) {
580 metaCurdirOk = boolValue(&cp[9]);
582 if ((cp = strstr(make_mode, "silent="))) {
583 metaSilent = boolValue(&cp[7]);
585 if (strstr(make_mode, "ignore-cmd"))
586 metaIgnoreCMDs = TRUE;
587 /* for backwards compatability */
588 Var_Set(".MAKE.META_CREATED", "${.MAKE.META.CREATED}", VAR_GLOBAL, 0);
589 Var_Set(".MAKE.META_FILES", "${.MAKE.META.FILES}", VAR_GLOBAL, 0);
591 if (metaVerbose && !Var_Exists(MAKE_META_PREFIX, VAR_GLOBAL)) {
593 * The default value for MAKE_META_PREFIX
594 * prints the absolute path of the target.
595 * This works be cause :H will generate '.' if there is no /
596 * and :tA will resolve that to cwd.
598 Var_Set(MAKE_META_PREFIX, "Building ${.TARGET:H:tA}/${.TARGET:T}", VAR_GLOBAL, 0);
600 if (once)
601 return;
602 once = 1;
603 memset(&Mybm, 0, sizeof(Mybm));
605 * We consider ourselves master of all within ${.MAKE.META.BAILIWICK}
607 metaBailiwick = Lst_Init(FALSE);
608 cp = Var_Subst(NULL, "${.MAKE.META.BAILIWICK:O:u:tA}", VAR_GLOBAL, 0);
609 if (cp) {
610 str2Lst_Append(metaBailiwick, cp, NULL);
613 * We ignore any paths that start with ${.MAKE.META.IGNORE_PATHS}
615 metaIgnorePaths = Lst_Init(FALSE);
616 Var_Append(MAKE_META_IGNORE_PATHS,
617 "/dev /etc /proc /tmp /var/run /var/tmp ${TMPDIR}", VAR_GLOBAL);
618 cp = Var_Subst(NULL,
619 "${" MAKE_META_IGNORE_PATHS ":O:u:tA}", VAR_GLOBAL, 0);
620 if (cp) {
621 str2Lst_Append(metaIgnorePaths, cp, NULL);
626 * In each case below we allow for job==NULL
628 void
629 meta_job_start(Job *job, GNode *gn)
631 BuildMon *pbm;
633 if (job != NULL) {
634 pbm = &job->bm;
635 } else {
636 pbm = &Mybm;
638 pbm->mfp = meta_create(pbm, gn);
639 #ifdef USE_FILEMON_ONCE
640 /* compat mode we open the filemon dev once per command */
641 if (job == NULL)
642 return;
643 #endif
644 #ifdef USE_FILEMON
645 if (pbm->mfp != NULL && useFilemon) {
646 filemon_open(pbm);
647 } else {
648 pbm->mon_fd = pbm->filemon_fd = -1;
650 #endif
654 * The child calls this before doing anything.
655 * It does not disturb our state.
657 void
658 meta_job_child(Job *job)
660 #ifdef USE_FILEMON
661 BuildMon *pbm;
662 pid_t pid;
664 if (job != NULL) {
665 pbm = &job->bm;
666 } else {
667 pbm = &Mybm;
669 pid = getpid();
670 if (pbm->mfp != NULL && useFilemon) {
671 if (ioctl(pbm->filemon_fd, FILEMON_SET_PID, &pid) < 0) {
672 err(1, "Could not set filemon pid!");
675 #endif
678 void
679 meta_job_error(Job *job, GNode *gn, int flags, int status)
681 char cwd[MAXPATHLEN];
682 BuildMon *pbm;
684 if (job != NULL) {
685 pbm = &job->bm;
686 } else {
687 if (!gn)
688 gn = job->node;
689 pbm = &Mybm;
691 if (pbm->mfp != NULL) {
692 fprintf(pbm->mfp, "*** Error code %d%s\n",
693 status,
694 (flags & JOB_IGNERR) ?
695 "(ignored)" : "");
697 if (gn) {
698 Var_Set(".ERROR_TARGET", gn->path ? gn->path : gn->name, VAR_GLOBAL, 0);
700 getcwd(cwd, sizeof(cwd));
701 Var_Set(".ERROR_CWD", cwd, VAR_GLOBAL, 0);
702 if (pbm && pbm->meta_fname[0]) {
703 Var_Set(".ERROR_META_FILE", pbm->meta_fname, VAR_GLOBAL, 0);
705 meta_job_finish(job);
708 void
709 meta_job_output(Job *job, char *cp, const char *nl)
711 BuildMon *pbm;
713 if (job != NULL) {
714 pbm = &job->bm;
715 } else {
716 pbm = &Mybm;
718 if (pbm->mfp != NULL) {
719 if (metaVerbose) {
720 static char *meta_prefix = NULL;
721 static int meta_prefix_len;
723 if (!meta_prefix) {
724 char *cp2;
726 meta_prefix = Var_Subst(NULL, "${" MAKE_META_PREFIX "}", VAR_GLOBAL, 0);
727 if ((cp2 = strchr(meta_prefix, '$')))
728 meta_prefix_len = cp2 - meta_prefix;
729 else
730 meta_prefix_len = strlen(meta_prefix);
732 if (strncmp(cp, meta_prefix, meta_prefix_len) == 0) {
733 cp = strchr(cp+1, '\n');
734 if (!cp++)
735 return;
738 fprintf(pbm->mfp, "%s%s", cp, nl);
742 void
743 meta_cmd_finish(void *pbmp)
745 #ifdef USE_FILEMON
746 BuildMon *pbm = pbmp;
748 if (!pbm)
749 pbm = &Mybm;
751 if (pbm->filemon_fd >= 0) {
752 close(pbm->filemon_fd);
753 filemon_read(pbm->mfp, pbm->mon_fd);
754 pbm->filemon_fd = pbm->mon_fd = -1;
756 #endif
759 void
760 meta_job_finish(Job *job)
762 BuildMon *pbm;
764 if (job != NULL) {
765 pbm = &job->bm;
766 } else {
767 pbm = &Mybm;
769 if (pbm->mfp != NULL) {
770 meta_cmd_finish(pbm);
771 fclose(pbm->mfp);
772 pbm->mfp = NULL;
773 pbm->meta_fname[0] = '\0';
778 * Fetch a full line from fp - growing bufp if needed
779 * Return length in bufp.
781 static int
782 fgetLine(char **bufp, size_t *szp, int o, FILE *fp)
784 char *buf = *bufp;
785 size_t bufsz = *szp;
786 struct stat fs;
787 int x;
789 if (fgets(&buf[o], bufsz - o, fp) != NULL) {
790 check_newline:
791 x = o + strlen(&buf[o]);
792 if (buf[x - 1] == '\n')
793 return x;
795 * We need to grow the buffer.
796 * The meta file can give us a clue.
798 if (fstat(fileno(fp), &fs) == 0) {
799 size_t newsz;
800 char *p;
802 newsz = ROUNDUP((fs.st_size / 2), BUFSIZ);
803 if (newsz <= bufsz)
804 newsz = ROUNDUP(fs.st_size, BUFSIZ);
805 if (DEBUG(META))
806 fprintf(debug_file, "growing buffer %u -> %u\n",
807 (unsigned)bufsz, (unsigned)newsz);
808 p = bmake_realloc(buf, newsz);
809 if (p) {
810 *bufp = buf = p;
811 *szp = bufsz = newsz;
812 /* fetch the rest */
813 if (!fgets(&buf[x], bufsz - x, fp))
814 return x; /* truncated! */
815 goto check_newline;
819 return 0;
822 static int
823 prefix_match(void *p, void *q)
825 const char *prefix = p;
826 const char *path = q;
827 size_t n = strlen(prefix);
829 return (0 == strncmp(path, prefix, n));
832 static int
833 string_match(const void *p, const void *q)
835 const char *p1 = p;
836 const char *p2 = q;
838 return strcmp(p1, p2);
843 * When running with 'meta' functionality, a target can be out-of-date
844 * if any of the references in its meta data file is more recent.
845 * We have to track the latestdir on a per-process basis.
847 #define LDIR_VNAME_FMT ".meta.%d.ldir"
850 * It is possible that a .meta file is corrupted,
851 * if we detect this we want to reproduce it.
852 * Setting oodate TRUE will have that effect.
854 #define CHECK_VALID_META(p) if (!(p && *p)) { \
855 warnx("%s: %d: malformed", fname, lineno); \
856 oodate = TRUE; \
857 continue; \
860 #define DEQUOTE(p) if (*p == '\'') { \
861 char *ep; \
862 p++; \
863 if ((ep = strchr(p, '\''))) \
864 *ep = '\0'; \
867 Boolean
868 meta_oodate(GNode *gn, Boolean oodate)
870 static char *tmpdir = NULL;
871 static char cwd[MAXPATHLEN];
872 char ldir_vname[64];
873 char latestdir[MAXPATHLEN];
874 char fname[MAXPATHLEN];
875 char fname1[MAXPATHLEN];
876 char fname2[MAXPATHLEN];
877 char *p;
878 char *cp;
879 char *link_src;
880 char *move_target;
881 static size_t cwdlen = 0;
882 static size_t tmplen = 0;
883 FILE *fp;
884 Boolean needOODATE = FALSE;
885 Lst missingFiles;
887 if (oodate)
888 return oodate; /* we're done */
890 missingFiles = Lst_Init(FALSE);
893 * We need to check if the target is out-of-date. This includes
894 * checking if the expanded command has changed. This in turn
895 * requires that all variables are set in the same way that they
896 * would be if the target needs to be re-built.
898 Make_DoAllVar(gn);
900 meta_name(gn, fname, sizeof(fname), NULL, NULL);
902 #ifdef DEBUG_META_MODE
903 if (DEBUG(META))
904 fprintf(debug_file, "meta_oodate: %s\n", fname);
905 #endif
907 if ((fp = fopen(fname, "r")) != NULL) {
908 static char *buf = NULL;
909 static size_t bufsz;
910 int lineno = 0;
911 int lastpid = 0;
912 int pid;
913 int f = 0;
914 int x;
915 LstNode ln;
916 struct stat fs;
918 if (!buf) {
919 bufsz = 8 * BUFSIZ;
920 buf = bmake_malloc(bufsz);
923 if (!cwdlen) {
924 if (getcwd(cwd, sizeof(cwd)) == NULL)
925 err(1, "Could not get current working directory");
926 cwdlen = strlen(cwd);
929 if (!tmpdir) {
930 tmpdir = getTmpdir();
931 tmplen = strlen(tmpdir);
934 /* we want to track all the .meta we read */
935 Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL);
937 ln = Lst_First(gn->commands);
938 while (!oodate && (x = fgetLine(&buf, &bufsz, 0, fp)) > 0) {
939 lineno++;
940 if (buf[x - 1] == '\n')
941 buf[x - 1] = '\0';
942 else {
943 warnx("%s: %d: line truncated at %u", fname, lineno, x);
944 oodate = TRUE;
945 break;
947 link_src = NULL;
948 move_target = NULL;
949 /* Find the start of the build monitor section. */
950 if (!f) {
951 if (strncmp(buf, "-- filemon", 10) == 0) {
952 f = 1;
953 continue;
955 if (strncmp(buf, "# buildmon", 10) == 0) {
956 f = 1;
957 continue;
961 /* Delimit the record type. */
962 p = buf;
963 #ifdef DEBUG_META_MODE
964 if (DEBUG(META))
965 fprintf(debug_file, "%s: %d: %s\n", fname, lineno, buf);
966 #endif
967 strsep(&p, " ");
968 if (f) {
970 * We are in the 'filemon' output section.
971 * Each record from filemon follows the general form:
973 * <key> <pid> <data>
975 * Where:
976 * <key> is a single letter, denoting the syscall.
977 * <pid> is the process that made the syscall.
978 * <data> is the arguments (of interest).
980 switch(buf[0]) {
981 case '#': /* comment */
982 case 'V': /* version */
983 break;
984 default:
986 * We need to track pathnames per-process.
988 * Each process run by make, starts off in the 'CWD'
989 * recorded in the .meta file, if it chdirs ('C')
990 * elsewhere we need to track that - but only for
991 * that process. If it forks ('F'), we initialize
992 * the child to have the same cwd as its parent.
994 * We also need to track the 'latestdir' of
995 * interest. This is usually the same as cwd, but
996 * not if a process is reading directories.
998 * Each time we spot a different process ('pid')
999 * we save the current value of 'latestdir' in a
1000 * variable qualified by 'lastpid', and
1001 * re-initialize 'latestdir' to any pre-saved
1002 * value for the current 'pid' and 'CWD' if none.
1004 CHECK_VALID_META(p);
1005 pid = atoi(p);
1006 if (pid > 0 && pid != lastpid) {
1007 char *ldir;
1008 char *tp;
1010 if (lastpid > 0) {
1011 /* We need to remember this. */
1012 Var_Set(ldir_vname, latestdir, VAR_GLOBAL, 0);
1014 snprintf(ldir_vname, sizeof(ldir_vname), LDIR_VNAME_FMT, pid);
1015 lastpid = pid;
1016 ldir = Var_Value(ldir_vname, VAR_GLOBAL, &tp);
1017 if (ldir) {
1018 strlcpy(latestdir, ldir, sizeof(latestdir));
1019 if (tp)
1020 free(tp);
1021 } else
1022 strlcpy(latestdir, cwd, sizeof(latestdir));
1024 /* Skip past the pid. */
1025 if (strsep(&p, " ") == NULL)
1026 continue;
1027 #ifdef DEBUG_META_MODE
1028 if (DEBUG(META))
1029 fprintf(debug_file, "%s: %d: cwd=%s ldir=%s\n", fname, lineno, cwd, latestdir);
1030 #endif
1031 break;
1034 CHECK_VALID_META(p);
1036 /* Process according to record type. */
1037 switch (buf[0]) {
1038 case 'X': /* eXit */
1039 Var_Delete(ldir_vname, VAR_GLOBAL);
1040 lastpid = 0; /* no need to save ldir_vname */
1041 break;
1043 case 'F': /* [v]Fork */
1045 char cldir[64];
1046 int child;
1048 child = atoi(p);
1049 if (child > 0) {
1050 snprintf(cldir, sizeof(cldir), LDIR_VNAME_FMT, child);
1051 Var_Set(cldir, latestdir, VAR_GLOBAL, 0);
1054 break;
1056 case 'C': /* Chdir */
1057 /* Update the latest directory. */
1058 strlcpy(latestdir, p, sizeof(latestdir));
1059 break;
1061 case 'M': /* renaMe */
1063 * For 'M'oves we want to check
1064 * the src as for 'R'ead
1065 * and the target as for 'W'rite.
1067 cp = p; /* save this for a second */
1068 /* now get target */
1069 if (strsep(&p, " ") == NULL)
1070 continue;
1071 CHECK_VALID_META(p);
1072 move_target = p;
1073 p = cp;
1074 /* 'L' and 'M' put single quotes around the args */
1075 DEQUOTE(p);
1076 DEQUOTE(move_target);
1077 /* FALLTHROUGH */
1078 case 'D': /* unlink */
1079 if (*p == '/' && !Lst_IsEmpty(missingFiles)) {
1080 /* remove p from the missingFiles list if present */
1081 if ((ln = Lst_Find(missingFiles, p, string_match)) != NULL) {
1082 char *tp = Lst_Datum(ln);
1083 Lst_Remove(missingFiles, ln);
1084 free(tp);
1085 ln = NULL; /* we're done with it */
1088 if (buf[0] == 'M') {
1089 /* the target of the mv is a file 'W'ritten */
1090 #ifdef DEBUG_META_MODE
1091 if (DEBUG(META))
1092 fprintf(debug_file, "meta_oodate: M %s -> %s\n",
1093 p, move_target);
1094 #endif
1095 p = move_target;
1096 goto check_write;
1098 break;
1099 case 'L': /* Link */
1101 * For 'L'inks check
1102 * the src as for 'R'ead
1103 * and the target as for 'W'rite.
1105 link_src = p;
1106 /* now get target */
1107 if (strsep(&p, " ") == NULL)
1108 continue;
1109 CHECK_VALID_META(p);
1110 /* 'L' and 'M' put single quotes around the args */
1111 DEQUOTE(p);
1112 DEQUOTE(link_src);
1113 #ifdef DEBUG_META_MODE
1114 if (DEBUG(META))
1115 fprintf(debug_file, "meta_oodate: L %s -> %s\n",
1116 link_src, p);
1117 #endif
1118 /* FALLTHROUGH */
1119 case 'W': /* Write */
1120 check_write:
1122 * If a file we generated within our bailiwick
1123 * but outside of .OBJDIR is missing,
1124 * we need to do it again.
1126 /* ignore non-absolute paths */
1127 if (*p != '/')
1128 break;
1130 if (Lst_IsEmpty(metaBailiwick))
1131 break;
1133 /* ignore cwd - normal dependencies handle those */
1134 if (strncmp(p, cwd, cwdlen) == 0)
1135 break;
1137 if (!Lst_ForEach(metaBailiwick, prefix_match, p))
1138 break;
1140 /* tmpdir might be within */
1141 if (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0)
1142 break;
1144 /* ignore anything containing the string "tmp" */
1145 if ((strstr("tmp", p)))
1146 break;
1148 if (stat(p, &fs) < 0) {
1149 Lst_AtEnd(missingFiles, bmake_strdup(p));
1151 break;
1152 check_link_src:
1153 p = link_src;
1154 link_src = NULL;
1155 #ifdef DEBUG_META_MODE
1156 if (DEBUG(META))
1157 fprintf(debug_file, "meta_oodate: L src %s\n", p);
1158 #endif
1159 /* FALLTHROUGH */
1160 case 'R': /* Read */
1161 case 'E': /* Exec */
1163 * Check for runtime files that can't
1164 * be part of the dependencies because
1165 * they are _expected_ to change.
1167 if (*p == '/' &&
1168 Lst_ForEach(metaIgnorePaths, prefix_match, p)) {
1169 #ifdef DEBUG_META_MODE
1170 if (DEBUG(META))
1171 fprintf(debug_file, "meta_oodate: ignoring: %s\n",
1173 #endif
1174 break;
1177 if ((cp = strrchr(p, '/'))) {
1178 cp++;
1180 * We don't normally expect to see this,
1181 * but we do expect it to change.
1183 if (strcmp(cp, makeDependfile) == 0)
1184 break;
1188 * The rest of the record is the file name.
1189 * Check if it's not an absolute path.
1192 char *sdirs[4];
1193 char **sdp;
1194 int sdx = 0;
1195 int found = 0;
1197 if (*p == '/') {
1198 sdirs[sdx++] = p; /* done */
1199 } else {
1200 if (strcmp(".", p) == 0)
1201 continue; /* no point */
1203 /* Check vs latestdir */
1204 snprintf(fname1, sizeof(fname1), "%s/%s", latestdir, p);
1205 sdirs[sdx++] = fname1;
1207 if (strcmp(latestdir, cwd) != 0) {
1208 /* Check vs cwd */
1209 snprintf(fname2, sizeof(fname2), "%s/%s", cwd, p);
1210 sdirs[sdx++] = fname2;
1213 sdirs[sdx++] = NULL;
1215 for (sdp = sdirs; *sdp && !found; sdp++) {
1216 #ifdef DEBUG_META_MODE
1217 if (DEBUG(META))
1218 fprintf(debug_file, "%s: %d: looking for: %s\n", fname, lineno, *sdp);
1219 #endif
1220 if (stat(*sdp, &fs) == 0) {
1221 found = 1;
1222 p = *sdp;
1225 if (found) {
1226 #ifdef DEBUG_META_MODE
1227 if (DEBUG(META))
1228 fprintf(debug_file, "%s: %d: found: %s\n", fname, lineno, p);
1229 #endif
1230 if (!S_ISDIR(fs.st_mode) &&
1231 fs.st_mtime > gn->mtime) {
1232 if (DEBUG(META))
1233 fprintf(debug_file, "%s: %d: file '%s' is newer than the target...\n", fname, lineno, p);
1234 oodate = TRUE;
1235 } else if (S_ISDIR(fs.st_mode)) {
1236 /* Update the latest directory. */
1237 realpath(p, latestdir);
1239 } else if (errno == ENOENT && *p == '/' &&
1240 strncmp(p, cwd, cwdlen) != 0) {
1242 * A referenced file outside of CWD is missing.
1243 * We cannot catch every eventuality here...
1245 if (DEBUG(META))
1246 fprintf(debug_file, "%s: %d: file '%s' may have moved?...\n", fname, lineno, p);
1247 oodate = TRUE;
1250 break;
1251 default:
1252 break;
1254 if (!oodate && buf[0] == 'L' && link_src != NULL)
1255 goto check_link_src;
1256 } else if (strcmp(buf, "CMD") == 0) {
1258 * Compare the current command with the one in the
1259 * meta data file.
1261 if (ln == NULL) {
1262 if (DEBUG(META))
1263 fprintf(debug_file, "%s: %d: there were more build commands in the meta data file than there are now...\n", fname, lineno);
1264 oodate = TRUE;
1265 } else {
1266 char *cmd = (char *)Lst_Datum(ln);
1267 Boolean hasOODATE = FALSE;
1269 if (strstr(cmd, "$?"))
1270 hasOODATE = TRUE;
1271 else if ((cp = strstr(cmd, ".OODATE"))) {
1272 /* check for $[{(].OODATE[:)}] */
1273 if (cp > cmd + 2 && cp[-2] == '$')
1274 hasOODATE = TRUE;
1276 if (hasOODATE) {
1277 needOODATE = TRUE;
1278 if (DEBUG(META))
1279 fprintf(debug_file, "%s: %d: cannot compare command using .OODATE\n", fname, lineno);
1281 cmd = Var_Subst(NULL, cmd, gn, TRUE);
1283 if ((cp = strchr(cmd, '\n'))) {
1284 int n;
1287 * This command contains newlines, we need to
1288 * fetch more from the .meta file before we
1289 * attempt a comparison.
1291 /* first put the newline back at buf[x - 1] */
1292 buf[x - 1] = '\n';
1293 do {
1294 /* now fetch the next line */
1295 if ((n = fgetLine(&buf, &bufsz, x, fp)) <= 0)
1296 break;
1297 x = n;
1298 lineno++;
1299 if (buf[x - 1] != '\n') {
1300 warnx("%s: %d: line truncated at %u", fname, lineno, x);
1301 break;
1303 cp = strchr(++cp, '\n');
1304 } while (cp);
1305 if (buf[x - 1] == '\n')
1306 buf[x - 1] = '\0';
1308 if (!hasOODATE &&
1309 !(gn->type & OP_NOMETA_CMP) &&
1310 strcmp(p, cmd) != 0) {
1311 if (DEBUG(META))
1312 fprintf(debug_file, "%s: %d: a build command has changed\n%s\nvs\n%s\n", fname, lineno, p, cmd);
1313 if (!metaIgnoreCMDs)
1314 oodate = TRUE;
1316 free(cmd);
1317 ln = Lst_Succ(ln);
1319 } else if (strcmp(buf, "CWD") == 0) {
1321 * Check if there are extra commands now
1322 * that weren't in the meta data file.
1324 if (!oodate && ln != NULL) {
1325 if (DEBUG(META))
1326 fprintf(debug_file, "%s: %d: there are extra build commands now that weren't in the meta data file\n", fname, lineno);
1327 oodate = TRUE;
1329 if (strcmp(p, cwd) != 0) {
1330 if (DEBUG(META))
1331 fprintf(debug_file, "%s: %d: the current working directory has changed from '%s' to '%s'\n", fname, lineno, p, curdir);
1332 oodate = TRUE;
1337 fclose(fp);
1338 if (!Lst_IsEmpty(missingFiles)) {
1339 if (DEBUG(META))
1340 fprintf(debug_file, "%s: missing files: %s...\n",
1341 fname, (char *)Lst_Datum(Lst_First(missingFiles)));
1342 oodate = TRUE;
1343 Lst_Destroy(missingFiles, (FreeProc *)free);
1345 } else {
1346 if ((gn->type & OP_META)) {
1347 if (DEBUG(META))
1348 fprintf(debug_file, "%s: required but missing\n", fname);
1349 oodate = TRUE;
1352 if (oodate && needOODATE) {
1354 * Target uses .OODATE which is empty; or we wouldn't be here.
1355 * We have decided it is oodate, so .OODATE needs to be set.
1356 * All we can sanely do is set it to .ALLSRC.
1358 Var_Delete(OODATE, gn);
1359 Var_Set(OODATE, Var_Value(ALLSRC, gn, &cp), gn, 0);
1360 if (cp)
1361 free(cp);
1363 return oodate;
1366 /* support for compat mode */
1368 static int childPipe[2];
1370 void
1371 meta_compat_start(void)
1373 #ifdef USE_FILEMON_ONCE
1375 * We need to re-open filemon for each cmd.
1377 BuildMon *pbm = &Mybm;
1379 if (pbm->mfp != NULL && useFilemon) {
1380 filemon_open(pbm);
1381 } else {
1382 pbm->mon_fd = pbm->filemon_fd = -1;
1384 #endif
1385 if (pipe(childPipe) < 0)
1386 Punt("Cannot create pipe: %s", strerror(errno));
1387 /* Set close-on-exec flag for both */
1388 (void)fcntl(childPipe[0], F_SETFD, 1);
1389 (void)fcntl(childPipe[1], F_SETFD, 1);
1392 void
1393 meta_compat_child(void)
1395 meta_job_child(NULL);
1396 if (dup2(childPipe[1], 1) < 0 ||
1397 dup2(1, 2) < 0) {
1398 execError("dup2", "pipe");
1399 _exit(1);
1403 void
1404 meta_compat_parent(void)
1406 FILE *fp;
1407 char buf[BUFSIZ];
1409 close(childPipe[1]); /* child side */
1410 fp = fdopen(childPipe[0], "r");
1411 while (fgets(buf, sizeof(buf), fp)) {
1412 meta_job_output(NULL, buf, "");
1413 printf("%s", buf);
1415 fclose(fp);
1418 #endif /* USE_META */