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