meta.c revision 1.12 1 /*
2 * Implement 'meta' mode.
3 * Adapted from John Birrell's patches to FreeBSD make.
4 * --sjg
5 */
6 /*
7 * Copyright (c) 2009-2010, Juniper Networks, Inc.
8 * Portions Copyright (c) 2009, John Birrell.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31 #if defined(USE_META)
32
33 #ifdef HAVE_CONFIG_H
34 # include "config.h"
35 #endif
36 #include <sys/stat.h>
37 #include <sys/ioctl.h>
38 #include <fcntl.h>
39 #include <libgen.h>
40 #include <errno.h>
41 #if !defined(HAVE_CONFIG_H) || defined(HAVE_ERR_H)
42 #include <err.h>
43 #endif
44
45 #include "make.h"
46 #include "job.h"
47
48 #ifdef HAVE_FILEMON_H
49 # include <filemon.h>
50 #endif
51 #if !defined(USE_FILEMON) && defined(FILEMON_SET_FD)
52 # define USE_FILEMON
53 #endif
54
55 static BuildMon Mybm; /* for compat */
56
57 Boolean useMeta = FALSE;
58 static Boolean useFilemon = FALSE;
59 static Boolean writeMeta = FALSE;
60 static Boolean metaEnv = FALSE; /* don't save env unless asked */
61 static Boolean metaVerbose = FALSE;
62 static Boolean metaIgnoreCMDs = FALSE; /* ignore CMDs in .meta files */
63 static Boolean metaCurdirOk = FALSE; /* write .meta in .CURDIR Ok? */
64
65 extern Boolean forceJobs;
66 extern Boolean comatMake;
67
68 #define MAKE_META_PREFIX ".MAKE.META.PREFIX"
69
70 #ifndef N2U
71 # define N2U(n, u) (((n) + ((u) - 1)) / (u))
72 #endif
73 #ifndef ROUNDUP
74 # define ROUNDUP(n, u) (N2U((n), (u)) * (u))
75 #endif
76
77 #if !defined(HAVE_STRSEP)
78 # define strsep(s, d) stresep((s), (d), 0)
79 #endif
80
81 /*
82 * Filemon is a kernel module which snoops certain syscalls.
83 *
84 * C chdir
85 * E exec
86 * F [v]fork
87 * L [sym]link
88 * M rename
89 * R read
90 * W write
91 * S stat
92 *
93 * See meta_oodate below - we mainly care about 'E' and 'R'.
94 *
95 * We can still use meta mode without filemon, but
96 * the benefits are more limited.
97 */
98 #ifdef USE_FILEMON
99 # ifndef _PATH_FILEMON
100 # define _PATH_FILEMON "/dev/filemon"
101 # endif
102
103 /*
104 * Open the filemon device.
105 */
106 static void
107 filemon_open(BuildMon *pbm)
108 {
109 int retry;
110
111 pbm->mon_fd = pbm->filemon_fd = -1;
112 if (!useFilemon)
113 return;
114
115 for (retry = 5; retry >= 0; retry--) {
116 if ((pbm->filemon_fd = open(_PATH_FILEMON, O_RDWR)) >= 0)
117 break;
118 }
119
120 if (pbm->filemon_fd < 0) {
121 useFilemon = FALSE;
122 warn("Could not open %s", _PATH_FILEMON);
123 return;
124 }
125
126 /*
127 * We use a file outside of '.'
128 * to avoid a FreeBSD kernel bug where unlink invalidates
129 * cwd causing getcwd to do a lot more work.
130 * We only care about the descriptor.
131 */
132 pbm->mon_fd = mkTempFile("filemon.XXXXXX", NULL);
133 if (ioctl(pbm->filemon_fd, FILEMON_SET_FD, &pbm->mon_fd) < 0) {
134 err(1, "Could not set filemon file descriptor!");
135 }
136 /* we don't need these once we exec */
137 (void)fcntl(pbm->mon_fd, F_SETFD, 1);
138 (void)fcntl(pbm->filemon_fd, F_SETFD, 1);
139 }
140
141 /*
142 * Read the build monitor output file and write records to the target's
143 * metadata file.
144 */
145 static void
146 filemon_read(FILE *mfp, int fd)
147 {
148 FILE *fp;
149 char buf[BUFSIZ];
150
151 /* Check if we're not writing to a meta data file.*/
152 if (mfp == NULL) {
153 if (fd >= 0)
154 close(fd); /* not interested */
155 return;
156 }
157 /* rewind */
158 lseek(fd, SEEK_SET, 0);
159 if ((fp = fdopen(fd, "r")) == NULL)
160 err(1, "Could not read build monitor file '%d'", fd);
161
162 fprintf(mfp, "-- filemon acquired metadata --\n");
163
164 while (fgets(buf, sizeof(buf), fp)) {
165 fprintf(mfp, "%s", buf);
166 }
167 fflush(mfp);
168 clearerr(fp);
169 fclose(fp);
170 }
171 #endif
172
173 /*
174 * when realpath() fails,
175 * we use this, to clean up ./ and ../
176 */
177 static void
178 eat_dots(char *buf, size_t bufsz, int dots)
179 {
180 char *cp;
181 char *cp2;
182 const char *eat;
183 size_t eatlen;
184
185 switch (dots) {
186 case 1:
187 eat = "/./";
188 eatlen = 2;
189 break;
190 case 2:
191 eat = "/../";
192 eatlen = 3;
193 break;
194 default:
195 return;
196 }
197
198 do {
199 cp = strstr(buf, eat);
200 if (cp) {
201 cp2 = cp + eatlen;
202 if (dots == 2 && cp > buf) {
203 do {
204 cp--;
205 } while (cp > buf && *cp != '/');
206 }
207 if (*cp == '/') {
208 strlcpy(cp, cp2, bufsz - (cp - buf));
209 } else {
210 return; /* can't happen? */
211 }
212 }
213 } while (cp);
214 }
215
216 static char *
217 meta_name(struct GNode *gn, char *mname, size_t mnamelen,
218 const char *dname,
219 const char *tname)
220 {
221 char buf[MAXPATHLEN];
222 char cwd[MAXPATHLEN];
223 char *rp;
224 char *cp;
225 char *tp;
226 char *p[4]; /* >= number of possible uses */
227 int i;
228
229 i = 0;
230 if (!dname)
231 dname = Var_Value(".OBJDIR", gn, &p[i++]);
232 if (!tname)
233 tname = Var_Value(TARGET, gn, &p[i++]);
234
235 if (realpath(dname, cwd))
236 dname = cwd;
237
238 /*
239 * Weed out relative paths from the target file name.
240 * We have to be careful though since if target is a
241 * symlink, the result will be unstable.
242 * So we use realpath() just to get the dirname, and leave the
243 * basename as given to us.
244 */
245 if ((cp = strrchr(tname, '/'))) {
246 if (realpath(tname, buf)) {
247 if ((rp = strrchr(buf, '/'))) {
248 rp++;
249 cp++;
250 if (strcmp(cp, rp) != 0)
251 strlcpy(rp, cp, sizeof(buf) - (rp - buf));
252 }
253 tname = buf;
254 } else {
255 /*
256 * We likely have a directory which is about to be made.
257 * We pretend realpath() succeeded, to have a chance
258 * of generating the same meta file name that we will
259 * next time through.
260 */
261 if (tname[0] == '/') {
262 strlcpy(buf, tname, sizeof(buf));
263 } else {
264 snprintf(buf, sizeof(buf), "%s/%s", cwd, tname);
265 }
266 eat_dots(buf, sizeof(buf), 1); /* ./ */
267 eat_dots(buf, sizeof(buf), 2); /* ../ */
268 tname = buf;
269 }
270 }
271 /* on some systems dirname may modify its arg */
272 tp = bmake_strdup(tname);
273 if (strcmp(dname, dirname(tp)) == 0)
274 snprintf(mname, mnamelen, "%s.meta", tname);
275 else {
276 snprintf(mname, mnamelen, "%s/%s.meta", dname, tname);
277
278 /*
279 * Replace path separators in the file name after the
280 * current object directory path.
281 */
282 cp = mname + strlen(dname) + 1;
283
284 while (*cp != '\0') {
285 if (*cp == '/')
286 *cp = '_';
287 cp++;
288 }
289 }
290 free(tp);
291 for (i--; i >= 0; i--) {
292 if (p[i])
293 free(p[i]);
294 }
295 return (mname);
296 }
297
298 /*
299 * Return true if running ${.MAKE}
300 * Bypassed if target is flagged .MAKE
301 */
302 static int
303 is_submake(void *cmdp, void *gnp)
304 {
305 static char *p_make = NULL;
306 static int p_len;
307 char *cmd = cmdp;
308 GNode *gn = gnp;
309 char *mp = NULL;
310 char *cp;
311 char *cp2;
312 int rc = 0; /* keep looking */
313
314 if (!p_make) {
315 p_make = Var_Value(".MAKE", gn, &cp);
316 p_len = strlen(p_make);
317 }
318 cp = strchr(cmd, '$');
319 if ((cp)) {
320 mp = Var_Subst(NULL, cmd, gn, FALSE);
321 cmd = mp;
322 }
323 cp2 = strstr(cmd, p_make);
324 if ((cp2)) {
325 switch (cp2[p_len]) {
326 case '\0':
327 case ' ':
328 case '\t':
329 case '\n':
330 rc = 1;
331 break;
332 }
333 if (cp2 > cmd && rc > 0) {
334 switch (cp2[-1]) {
335 case ' ':
336 case '\t':
337 case '\n':
338 break;
339 default:
340 rc = 0; /* no match */
341 break;
342 }
343 }
344 }
345 if (mp)
346 free(mp);
347 return (rc);
348 }
349
350 typedef struct meta_file_s {
351 FILE *fp;
352 GNode *gn;
353 } meta_file_t;
354
355 static int
356 printCMD(void *cmdp, void *mfpp)
357 {
358 meta_file_t *mfp = mfpp;
359 char *cmd = cmdp;
360 char *cp = NULL;
361
362 if (strchr(cmd, '$')) {
363 cmd = cp = Var_Subst(NULL, cmd, mfp->gn, FALSE);
364 }
365 fprintf(mfp->fp, "CMD %s\n", cmd);
366 if (cp)
367 free(cp);
368 return 0;
369 }
370
371 /*
372 * Certain node types never get a .meta file
373 */
374 #define SKIP_META_TYPE(_type) do { \
375 if ((gn->type & __CONCAT(OP_, _type))) { \
376 if (DEBUG(META)) { \
377 fprintf(debug_file, "Skipping meta for %s: .%s\n", \
378 gn->name, __STRING(_type)); \
379 } \
380 return (NULL); \
381 } \
382 } while (0)
383
384 static FILE *
385 meta_create(BuildMon *pbm, GNode *gn)
386 {
387 extern char **environ;
388 meta_file_t mf;
389 char buf[MAXPATHLEN];
390 char objdir[MAXPATHLEN];
391 char **ptr;
392 const char *dname;
393 const char *tname;
394 char *fname;
395 const char *cp;
396 char *p[4]; /* >= possible uses */
397 int i;
398 struct stat fs;
399
400
401 /* This may be a phony node which we don't want meta data for... */
402 /* Skip .meta for .BEGIN, .END, .ERROR etc as well. */
403 /* Or it may be explicitly flagged as .NOMETA */
404 SKIP_META_TYPE(NOMETA);
405 /* Unless it is explicitly flagged as .META */
406 if (!(gn->type & OP_META)) {
407 SKIP_META_TYPE(PHONY);
408 SKIP_META_TYPE(SPECIAL);
409 SKIP_META_TYPE(MAKE);
410 }
411
412 mf.fp = NULL;
413
414 i = 0;
415
416 dname = Var_Value(".OBJDIR", gn, &p[i++]);
417 tname = Var_Value(TARGET, gn, &p[i++]);
418
419 /* The object directory may not exist. Check it.. */
420 if (stat(dname, &fs) != 0) {
421 if (DEBUG(META))
422 fprintf(debug_file, "Skipping meta for %s: no .OBJDIR\n",
423 gn->name);
424 goto out;
425 }
426 /* Check if there are no commands to execute. */
427 if (Lst_IsEmpty(gn->commands)) {
428 if (DEBUG(META))
429 fprintf(debug_file, "Skipping meta for %s: no commands\n",
430 gn->name);
431 goto out;
432 }
433
434 /* make sure these are canonical */
435 if (realpath(dname, objdir))
436 dname = objdir;
437
438 /* If we aren't in the object directory, don't create a meta file. */
439 if (!metaCurdirOk && strcmp(curdir, dname) == 0) {
440 if (DEBUG(META))
441 fprintf(debug_file, "Skipping meta for %s: .OBJDIR == .CURDIR\n",
442 gn->name);
443 goto out;
444 }
445 if (!(gn->type & OP_META)) {
446 /* We do not generate .meta files for sub-makes */
447 if (Lst_ForEach(gn->commands, is_submake, gn)) {
448 if (DEBUG(META))
449 fprintf(debug_file, "Skipping meta for %s: .MAKE\n",
450 gn->name);
451 goto out;
452 }
453 }
454
455 if (metaVerbose) {
456 char *mp;
457
458 /* Describe the target we are building */
459 mp = Var_Subst(NULL, "${" MAKE_META_PREFIX "}", gn, 0);
460 if (*mp)
461 fprintf(stdout, "%s\n", mp);
462 free(mp);
463 }
464 /* Get the basename of the target */
465 if ((cp = strrchr(tname, '/')) == NULL) {
466 cp = tname;
467 } else {
468 cp++;
469 }
470
471 fflush(stdout);
472
473 if (strcmp(cp, makeDependfile) == 0)
474 goto out;
475
476 if (!writeMeta)
477 /* Don't create meta data. */
478 goto out;
479
480 fname = meta_name(gn, pbm->meta_fname, sizeof(pbm->meta_fname),
481 dname, tname);
482
483 #ifdef DEBUG_META_MODE
484 if (DEBUG(META))
485 fprintf(debug_file, "meta_create: %s\n", fname);
486 #endif
487
488 if ((mf.fp = fopen(fname, "w")) == NULL)
489 err(1, "Could not open meta file '%s'", fname);
490
491 fprintf(mf.fp, "# Meta data file %s\n", fname);
492
493 mf.gn = gn;
494
495 Lst_ForEach(gn->commands, printCMD, &mf);
496
497 fprintf(mf.fp, "CWD %s\n", getcwd(buf, sizeof(buf)));
498 fprintf(mf.fp, "TARGET %s\n", tname);
499
500 if (metaEnv) {
501 for (ptr = environ; *ptr != NULL; ptr++)
502 fprintf(mf.fp, "ENV %s\n", *ptr);
503 }
504
505 fprintf(mf.fp, "-- command output --\n");
506 fflush(mf.fp);
507
508 Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL);
509 Var_Append(".MAKE.META.CREATED", fname, VAR_GLOBAL);
510
511 out:
512 for (i--; i >= 0; i--) {
513 if (p[i])
514 free(p[i]);
515 }
516
517 return (mf.fp);
518 }
519
520 static Boolean
521 boolValue(char *s)
522 {
523 switch(*s) {
524 case '0':
525 case 'N':
526 case 'n':
527 case 'F':
528 case 'f':
529 return FALSE;
530 }
531 return TRUE;
532 }
533
534 void
535 meta_init(const char *make_mode)
536 {
537 static int once = 0;
538 char *cp;
539
540 useMeta = TRUE;
541 useFilemon = TRUE;
542 writeMeta = TRUE;
543
544 if (make_mode) {
545 if (strstr(make_mode, "env"))
546 metaEnv = TRUE;
547 if (strstr(make_mode, "verb"))
548 metaVerbose = TRUE;
549 if (strstr(make_mode, "read"))
550 writeMeta = FALSE;
551 if (strstr(make_mode, "nofilemon"))
552 useFilemon = FALSE;
553 if ((cp = strstr(make_mode, "curdir="))) {
554 metaCurdirOk = boolValue(&cp[7]);
555 }
556 if (strstr(make_mode, "ignore-cmd"))
557 metaIgnoreCMDs = TRUE;
558 /* for backwards compatability */
559 Var_Set(".MAKE.META_CREATED", "${.MAKE.META.CREATED}", VAR_GLOBAL, 0);
560 Var_Set(".MAKE.META_FILES", "${.MAKE.META.FILES}", VAR_GLOBAL, 0);
561 }
562 if (metaVerbose && !Var_Exists(MAKE_META_PREFIX, VAR_GLOBAL)) {
563 /*
564 * The default value for MAKE_META_PREFIX
565 * prints the absolute path of the target.
566 * This works be cause :H will generate '.' if there is no /
567 * and :tA will resolve that to cwd.
568 */
569 Var_Set(MAKE_META_PREFIX, "Building ${.TARGET:H:tA}/${.TARGET:T}", VAR_GLOBAL, 0);
570 }
571 if (once)
572 return;
573 once = 1;
574 memset(&Mybm, 0, sizeof(Mybm));
575 }
576
577 /*
578 * In each case below we allow for job==NULL
579 */
580 void
581 meta_job_start(Job *job, GNode *gn)
582 {
583 BuildMon *pbm;
584
585 if (job != NULL) {
586 pbm = &job->bm;
587 } else {
588 pbm = &Mybm;
589 }
590 pbm->mfp = meta_create(pbm, gn);
591 #ifdef USE_FILEMON_ONCE
592 /* compat mode we open the filemon dev once per command */
593 if (job == NULL)
594 return;
595 #endif
596 #ifdef USE_FILEMON
597 if (pbm->mfp != NULL && useFilemon) {
598 filemon_open(pbm);
599 } else {
600 pbm->mon_fd = pbm->filemon_fd = -1;
601 }
602 #endif
603 }
604
605 /*
606 * The child calls this before doing anything.
607 * It does not disturb our state.
608 */
609 void
610 meta_job_child(Job *job)
611 {
612 #ifdef USE_FILEMON
613 BuildMon *pbm;
614 pid_t pid;
615
616 if (job != NULL) {
617 pbm = &job->bm;
618 } else {
619 pbm = &Mybm;
620 }
621 pid = getpid();
622 if (pbm->mfp != NULL && useFilemon) {
623 if (ioctl(pbm->filemon_fd, FILEMON_SET_PID, &pid) < 0) {
624 err(1, "Could not set filemon pid!");
625 }
626 }
627 #endif
628 }
629
630 void
631 meta_job_error(Job *job, GNode *gn, int flags, int status)
632 {
633 char cwd[MAXPATHLEN];
634 BuildMon *pbm;
635
636 if (job != NULL) {
637 pbm = &job->bm;
638 } else {
639 if (!gn)
640 gn = job->node;
641 pbm = &Mybm;
642 }
643 if (pbm->mfp != NULL) {
644 fprintf(pbm->mfp, "*** Error code %d%s\n",
645 status,
646 (flags & JOB_IGNERR) ?
647 "(ignored)" : "");
648 }
649 if (gn) {
650 Var_Set(".ERROR_TARGET", gn->path ? gn->path : gn->name, VAR_GLOBAL, 0);
651 }
652 getcwd(cwd, sizeof(cwd));
653 Var_Set(".ERROR_CWD", cwd, VAR_GLOBAL, 0);
654 if (pbm && pbm->meta_fname[0]) {
655 Var_Set(".ERROR_META_FILE", pbm->meta_fname, VAR_GLOBAL, 0);
656 }
657 }
658
659 void
660 meta_job_output(Job *job, char *cp, const char *nl)
661 {
662 BuildMon *pbm;
663
664 if (job != NULL) {
665 pbm = &job->bm;
666 } else {
667 pbm = &Mybm;
668 }
669 if (pbm->mfp != NULL) {
670 if (metaVerbose) {
671 static char *meta_prefix = NULL;
672 static int meta_prefix_len;
673
674 if (!meta_prefix) {
675 char *cp2;
676
677 meta_prefix = Var_Subst(NULL, "${" MAKE_META_PREFIX "}", VAR_GLOBAL, 0);
678 if ((cp2 = strchr(meta_prefix, '$')))
679 meta_prefix_len = cp2 - meta_prefix;
680 else
681 meta_prefix_len = strlen(meta_prefix);
682 }
683 if (strncmp(cp, meta_prefix, meta_prefix_len) == 0) {
684 cp = strchr(cp+1, '\n');
685 if (!cp++)
686 return;
687 }
688 }
689 fprintf(pbm->mfp, "%s%s", cp, nl);
690 }
691 }
692
693 void
694 meta_cmd_finish(void *pbmp)
695 {
696 #ifdef USE_FILEMON
697 BuildMon *pbm = pbmp;
698
699 if (!pbm)
700 pbm = &Mybm;
701
702 if (pbm->filemon_fd >= 0) {
703 close(pbm->filemon_fd);
704 filemon_read(pbm->mfp, pbm->mon_fd);
705 pbm->filemon_fd = pbm->mon_fd = -1;
706 }
707 #endif
708 }
709
710 void
711 meta_job_finish(Job *job)
712 {
713 BuildMon *pbm;
714
715 if (job != NULL) {
716 pbm = &job->bm;
717 } else {
718 pbm = &Mybm;
719 }
720 if (pbm->mfp != NULL) {
721 meta_cmd_finish(pbm);
722 fclose(pbm->mfp);
723 pbm->mfp = NULL;
724 pbm->meta_fname[0] = '\0';
725 }
726 }
727
728 /*
729 * Fetch a full line from fp - growing bufp if needed
730 * Return length in bufp.
731 */
732 static int
733 fgetLine(char **bufp, size_t *szp, int o, FILE *fp)
734 {
735 char *buf = *bufp;
736 size_t bufsz = *szp;
737 struct stat fs;
738 int x;
739
740 if (fgets(&buf[o], bufsz - o, fp) != NULL) {
741 check_newline:
742 x = o + strlen(&buf[o]);
743 if (buf[x - 1] == '\n')
744 return x;
745 /*
746 * We need to grow the buffer.
747 * The meta file can give us a clue.
748 */
749 if (fstat(fileno(fp), &fs) == 0) {
750 size_t newsz;
751 char *p;
752
753 newsz = ROUNDUP((fs.st_size / 2), BUFSIZ);
754 if (newsz <= bufsz)
755 newsz = ROUNDUP(fs.st_size, BUFSIZ);
756 if (DEBUG(META))
757 fprintf(debug_file, "growing buffer %u -> %u\n",
758 bufsz, newsz);
759 p = bmake_realloc(buf, newsz);
760 if (p) {
761 *bufp = buf = p;
762 *szp = bufsz = newsz;
763 /* fetch the rest */
764 if (!fgets(&buf[x], bufsz - x, fp))
765 return x; /* truncated! */
766 goto check_newline;
767 }
768 }
769 }
770 return 0;
771 }
772
773 /*
774 * When running with 'meta' functionality, a target can be out-of-date
775 * if any of the references in it's meta data file is more recent.
776 * We have to track the latestdir on a per-process basis.
777 */
778 #define LDIR_VNAME_FMT ".meta.%d.ldir"
779
780 Boolean
781 meta_oodate(GNode *gn, Boolean oodate)
782 {
783 static char *tmpdir = NULL;
784 static char cwd[MAXPATHLEN];
785 char ldir_vname[64];
786 char latestdir[MAXPATHLEN];
787 char fname[MAXPATHLEN];
788 char fname1[MAXPATHLEN];
789 char fname2[MAXPATHLEN];
790 char *p;
791 char *cp;
792 static size_t cwdlen = 0;
793 static size_t tmplen = 0;
794 FILE *fp;
795 Boolean ignoreOODATE = FALSE;
796
797 if (oodate)
798 return oodate; /* we're done */
799
800 /*
801 * We need to check if the target is out-of-date. This includes
802 * checking if the expanded command has changed. This in turn
803 * requires that all variables are set in the same way that they
804 * would be if the target needs to be re-built.
805 */
806 Make_DoAllVar(gn);
807
808 meta_name(gn, fname, sizeof(fname), NULL, NULL);
809
810 #ifdef DEBUG_META_MODE
811 if (DEBUG(META))
812 fprintf(debug_file, "meta_oodate: %s\n", fname);
813 #endif
814
815 if ((fp = fopen(fname, "r")) != NULL) {
816 static char *buf = NULL;
817 static size_t bufsz;
818 int lineno = 0;
819 int lastpid = 0;
820 int pid;
821 int f = 0;
822 int x;
823 LstNode ln;
824 struct stat fs;
825
826 if (!buf) {
827 bufsz = 8 * BUFSIZ;
828 buf = bmake_malloc(bufsz);
829 }
830
831 if (!cwdlen) {
832 if (getcwd(cwd, sizeof(cwd)) == NULL)
833 err(1, "Could not get current working directory");
834 cwdlen = strlen(cwd);
835 }
836
837 if (!tmpdir) {
838 tmpdir = getTmpdir();
839 tmplen = strlen(tmpdir);
840 }
841
842 /* we want to track all the .meta we read */
843 Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL);
844
845 ln = Lst_First(gn->commands);
846 while (!oodate && (x = fgetLine(&buf, &bufsz, 0, fp)) > 0) {
847 lineno++;
848 if (buf[x - 1] == '\n')
849 buf[x - 1] = '\0';
850 else
851 warnx("%s: %d: line truncated at %u", fname, lineno, x);
852
853 /* Find the start of the build monitor section. */
854 if (!f) {
855 if (strncmp(buf, "-- filemon", 10) == 0) {
856 f = 1;
857 continue;
858 }
859 if (strncmp(buf, "# buildmon", 10) == 0) {
860 f = 1;
861 continue;
862 }
863 }
864
865 /* Delimit the record type. */
866 p = buf;
867 #ifdef DEBUG_META_MODE
868 if (DEBUG(META))
869 fprintf(debug_file, "%s: %d: %s\n", fname, lineno, buf);
870 #endif
871 strsep(&p, " ");
872 if (f) {
873 /*
874 * We are in the 'filemon' output section.
875 * Each record from filemon follows the general form:
876 *
877 * <key> <pid> <data>
878 *
879 * Where:
880 * <key> is a single letter, denoting the syscall.
881 * <pid> is the process that made the syscall.
882 * <data> is the arguments (of interest).
883 */
884 switch(buf[0]) {
885 case '#': /* comment */
886 case 'V': /* version */
887 break;
888 default:
889 /*
890 * We need to track pathnames per-process.
891 *
892 * Each process run by make, starts off in the 'CWD'
893 * recorded in the .meta file, if it chdirs ('C')
894 * elsewhere we need to track that - but only for
895 * that process. If it forks ('F'), we initialize
896 * the child to have the same cwd as its parent.
897 *
898 * We also need to track the 'latestdir' of
899 * interest. This is usually the same as cwd, but
900 * not if a process is reading directories.
901 *
902 * Each time we spot a different process ('pid')
903 * we save the current value of 'latestdir' in a
904 * variable qualified by 'lastpid', and
905 * re-initialize 'latestdir' to any pre-saved
906 * value for the current 'pid' and 'CWD' if none.
907 */
908 pid = atoi(p);
909 if (pid > 0 && pid != lastpid) {
910 char *ldir;
911 char *tp;
912
913 if (lastpid > 0) {
914 /* We need to remember this. */
915 Var_Set(ldir_vname, latestdir, VAR_GLOBAL, 0);
916 }
917 snprintf(ldir_vname, sizeof(ldir_vname), LDIR_VNAME_FMT, pid);
918 lastpid = pid;
919 ldir = Var_Value(ldir_vname, VAR_GLOBAL, &tp);
920 if (ldir) {
921 strlcpy(latestdir, ldir, sizeof(latestdir));
922 if (tp)
923 free(tp);
924 } else
925 strlcpy(latestdir, cwd, sizeof(latestdir));
926 }
927 /* Skip past the pid. */
928 if (strsep(&p, " ") == NULL)
929 continue;
930 #ifdef DEBUG_META_MODE
931 if (DEBUG(META))
932 fprintf(debug_file, "%s: %d: cwd=%s ldir=%s\n", fname, lineno, cwd, latestdir);
933 #endif
934 break;
935 }
936
937 /* Process according to record type. */
938 switch (buf[0]) {
939 case 'X': /* eXit */
940 Var_Delete(ldir_vname, VAR_GLOBAL);
941 lastpid = 0; /* no need to save ldir_vname */
942 break;
943
944 case 'F': /* [v]Fork */
945 {
946 char cldir[64];
947 int child;
948
949 child = atoi(p);
950 if (child > 0) {
951 snprintf(cldir, sizeof(cldir), LDIR_VNAME_FMT, child);
952 Var_Set(cldir, latestdir, VAR_GLOBAL, 0);
953 }
954 }
955 break;
956
957 case 'C': /* Chdir */
958 /* Update the latest directory. */
959 strlcpy(latestdir, p, sizeof(latestdir));
960 break;
961
962 case 'R': /* Read */
963 case 'E': /* Exec */
964 /*
965 * Check for runtime files that can't
966 * be part of the dependencies because
967 * they are _expected_ to change.
968 */
969 if (strncmp(p, "/tmp/", 5) == 0 ||
970 (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0))
971 break;
972
973 if (strncmp(p, "/var/", 5) == 0)
974 break;
975
976 /* Ignore device files. */
977 if (strncmp(p, "/dev/", 5) == 0)
978 break;
979
980 /* Ignore /etc/ files. */
981 if (strncmp(p, "/etc/", 5) == 0)
982 break;
983
984 /*
985 * The rest of the record is the file name.
986 * Check if it's not an absolute path.
987 */
988 {
989 char *sdirs[4];
990 char **sdp;
991 int sdx = 0;
992 int found = 0;
993
994 if (*p == '/') {
995 sdirs[sdx++] = p; /* done */
996 } else {
997 if (strcmp(".", p) == 0)
998 continue; /* no point */
999
1000 /* Check vs latestdir */
1001 snprintf(fname1, sizeof(fname1), "%s/%s", latestdir, p);
1002 sdirs[sdx++] = fname1;
1003
1004 if (strcmp(latestdir, cwd) != 0) {
1005 /* Check vs cwd */
1006 snprintf(fname2, sizeof(fname2), "%s/%s", cwd, p);
1007 sdirs[sdx++] = fname2;
1008 }
1009 }
1010 sdirs[sdx++] = NULL;
1011
1012 for (sdp = sdirs; *sdp && !found; sdp++) {
1013 #ifdef DEBUG_META_MODE
1014 if (DEBUG(META))
1015 fprintf(debug_file, "%s: %d: looking for: %s\n", fname, lineno, *sdp);
1016 #endif
1017 if (stat(*sdp, &fs) == 0) {
1018 found = 1;
1019 p = *sdp;
1020 }
1021 }
1022 if (found) {
1023 #ifdef DEBUG_META_MODE
1024 if (DEBUG(META))
1025 fprintf(debug_file, "%s: %d: found: %s\n", fname, lineno, p);
1026 #endif
1027 if (!S_ISDIR(fs.st_mode) &&
1028 fs.st_mtime > gn->mtime) {
1029 if (DEBUG(META))
1030 fprintf(debug_file, "%s: %d: file '%s' is newer than the target...\n", fname, lineno, p);
1031 oodate = TRUE;
1032 } else if (S_ISDIR(fs.st_mode)) {
1033 /* Update the latest directory. */
1034 realpath(p, latestdir);
1035 }
1036 } else if (errno == ENOENT && *p == '/' &&
1037 strncmp(p, cwd, cwdlen) != 0) {
1038 /*
1039 * A referenced file outside of CWD is missing.
1040 * We cannot catch every eventuality here...
1041 */
1042 if (DEBUG(META))
1043 fprintf(debug_file, "%s: %d: file '%s' may have moved?...\n", fname, lineno, p);
1044 oodate = TRUE;
1045 }
1046 }
1047 break;
1048 default:
1049 break;
1050 }
1051 } else if (strcmp(buf, "CMD") == 0) {
1052 /*
1053 * Compare the current command with the one in the
1054 * meta data file.
1055 */
1056 if (ln == NULL) {
1057 if (DEBUG(META))
1058 fprintf(debug_file, "%s: %d: there were more build commands in the meta data file than there are now...\n", fname, lineno);
1059 oodate = TRUE;
1060 } else {
1061 char *cmd = (char *)Lst_Datum(ln);
1062
1063 if (!ignoreOODATE) {
1064 if (strstr(cmd, "$?"))
1065 ignoreOODATE = TRUE;
1066 else if ((cp = strstr(cmd, ".OODATE"))) {
1067 /* check for $[{(].OODATE[)}] */
1068 if (cp > cmd + 2 && cp[-2] == '$')
1069 ignoreOODATE = TRUE;
1070 }
1071 if (ignoreOODATE && DEBUG(META))
1072 fprintf(debug_file, "%s: %d: cannot compare commands using .OODATE\n", fname, lineno);
1073 }
1074 cmd = Var_Subst(NULL, cmd, gn, TRUE);
1075
1076 if ((cp = strchr(cmd, '\n'))) {
1077 int n;
1078
1079 /*
1080 * This command contains newlines, we need to
1081 * fetch more from the .meta file before we
1082 * attempt a comparison.
1083 */
1084 /* first put the newline back at buf[x - 1] */
1085 buf[x - 1] = '\n';
1086 do {
1087 /* now fetch the next line */
1088 if ((n = fgetLine(&buf, &bufsz, x, fp)) <= 0)
1089 break;
1090 x = n;
1091 lineno++;
1092 if (buf[x - 1] != '\n') {
1093 warnx("%s: %d: line truncated at %u", fname, lineno, x);
1094 break;
1095 }
1096 cp = strchr(++cp, '\n');
1097 } while (cp);
1098 if (buf[x - 1] == '\n')
1099 buf[x - 1] = '\0';
1100 }
1101 if (!ignoreOODATE &&
1102 !(gn->type & OP_NOMETA_CMP) &&
1103 strcmp(p, cmd) != 0) {
1104 if (DEBUG(META))
1105 fprintf(debug_file, "%s: %d: a build command has changed\n%s\nvs\n%s\n", fname, lineno, p, cmd);
1106 if (!metaIgnoreCMDs)
1107 oodate = TRUE;
1108 }
1109 free(cmd);
1110 ln = Lst_Succ(ln);
1111 }
1112 } else if (strcmp(buf, "CWD") == 0) {
1113 if (strcmp(p, cwd) != 0) {
1114 if (DEBUG(META))
1115 fprintf(debug_file, "%s: %d: the current working directory has changed from '%s' to '%s'\n", fname, lineno, p, curdir);
1116 oodate = TRUE;
1117 }
1118 }
1119 }
1120
1121 /*
1122 * Check if there are extra commands now
1123 * that weren't in the meta data file.
1124 */
1125 if (!oodate && ln != NULL) {
1126 if (DEBUG(META))
1127 fprintf(debug_file, "%s: %d: there are extra build commands now that weren't in the meta data file\n", fname, lineno);
1128 oodate = TRUE;
1129 }
1130
1131 fclose(fp);
1132 }
1133 if (oodate && ignoreOODATE) {
1134 /*
1135 * Target uses .OODATE, so we need to re-compute it.
1136 * We need to clean up what Make_DoAllVar() did.
1137 */
1138 Var_Delete(ALLSRC, gn);
1139 Var_Delete(OODATE, gn);
1140 gn->flags &= ~DONE_ALLSRC;
1141 }
1142 return oodate;
1143 }
1144
1145 /* support for compat mode */
1146
1147 static int childPipe[2];
1148
1149 void
1150 meta_compat_start(void)
1151 {
1152 #ifdef USE_FILEMON_ONCE
1153 /*
1154 * We need to re-open filemon for each cmd.
1155 */
1156 BuildMon *pbm = &Mybm;
1157
1158 if (pbm->mfp != NULL && useFilemon) {
1159 filemon_open(pbm);
1160 } else {
1161 pbm->mon_fd = pbm->filemon_fd = -1;
1162 }
1163 #endif
1164 if (pipe(childPipe) < 0)
1165 Punt("Cannot create pipe: %s", strerror(errno));
1166 /* Set close-on-exec flag for both */
1167 (void)fcntl(childPipe[0], F_SETFD, 1);
1168 (void)fcntl(childPipe[1], F_SETFD, 1);
1169 }
1170
1171 void
1172 meta_compat_child(void)
1173 {
1174 meta_job_child(NULL);
1175 if (dup2(childPipe[1], 1) < 0 ||
1176 dup2(1, 2) < 0) {
1177 execError("dup2", "pipe");
1178 _exit(1);
1179 }
1180 }
1181
1182 void
1183 meta_compat_parent(void)
1184 {
1185 FILE *fp;
1186 char buf[BUFSIZ];
1187
1188 close(childPipe[1]); /* child side */
1189 fp = fdopen(childPipe[0], "r");
1190 while (fgets(buf, sizeof(buf), fp)) {
1191 meta_job_output(NULL, buf, "");
1192 printf("%s", buf);
1193 }
1194 fclose(fp);
1195 }
1196
1197 #endif /* USE_META */
1198