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