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