meta.c revision 1.159 1 /* $NetBSD: meta.c,v 1.159 2020/12/13 20:14:48 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 void *dontFreeIt;
327 p_make = Var_Value(".MAKE", gn, &dontFreeIt);
328 p_len = strlen(p_make);
329 }
330 cp = strchr(cmd, '$');
331 if ((cp)) {
332 (void)Var_Subst(cmd, gn, VARE_WANTRES, &mp);
333 /* TODO: handle errors */
334 cmd = mp;
335 }
336 cp2 = strstr(cmd, p_make);
337 if (cp2 != NULL) {
338 switch (cp2[p_len]) {
339 case '\0':
340 case ' ':
341 case '\t':
342 case '\n':
343 rc = TRUE;
344 break;
345 }
346 if (cp2 > cmd && rc) {
347 switch (cp2[-1]) {
348 case ' ':
349 case '\t':
350 case '\n':
351 break;
352 default:
353 rc = FALSE; /* no match */
354 break;
355 }
356 }
357 }
358 free(mp);
359 return rc;
360 }
361
362 static Boolean
363 any_is_submake(GNode *gn)
364 {
365 StringListNode *ln;
366
367 for (ln = gn->commands.first; ln != NULL; ln = ln->next)
368 if (is_submake(ln->datum, gn))
369 return TRUE;
370 return FALSE;
371 }
372
373 static void
374 printCMD(const char *cmd, FILE *fp, GNode *gn)
375 {
376 char *cmd_freeIt = NULL;
377
378 if (strchr(cmd, '$')) {
379 (void)Var_Subst(cmd, gn, VARE_WANTRES, &cmd_freeIt);
380 /* TODO: handle errors */
381 cmd = cmd_freeIt;
382 }
383 fprintf(fp, "CMD %s\n", cmd);
384 free(cmd_freeIt);
385 }
386
387 static void
388 printCMDs(GNode *gn, FILE *fp)
389 {
390 GNodeListNode *ln;
391
392 for (ln = gn->commands.first; ln != NULL; ln = ln->next)
393 printCMD(ln->datum, fp, gn);
394 }
395
396 /*
397 * Certain node types never get a .meta file
398 */
399 #define SKIP_META_TYPE(_type) do { \
400 if ((gn->type & __CONCAT(OP_, _type))) { \
401 if (verbose) { \
402 debug_printf("Skipping meta for %s: .%s\n", \
403 gn->name, __STRING(_type)); \
404 } \
405 return FALSE; \
406 } \
407 } while (0)
408
409
410 /*
411 * Do we need/want a .meta file ?
412 */
413 static Boolean
414 meta_needed(GNode *gn, const char *dname,
415 char *objdir_realpath, Boolean verbose)
416 {
417 struct cached_stat cst;
418
419 if (verbose)
420 verbose = DEBUG(META) != 0;
421
422 /* This may be a phony node which we don't want meta data for... */
423 /* Skip .meta for .BEGIN, .END, .ERROR etc as well. */
424 /* Or it may be explicitly flagged as .NOMETA */
425 SKIP_META_TYPE(NOMETA);
426 /* Unless it is explicitly flagged as .META */
427 if (!(gn->type & OP_META)) {
428 SKIP_META_TYPE(PHONY);
429 SKIP_META_TYPE(SPECIAL);
430 SKIP_META_TYPE(MAKE);
431 }
432
433 /* Check if there are no commands to execute. */
434 if (Lst_IsEmpty(&gn->commands)) {
435 if (verbose)
436 debug_printf("Skipping meta for %s: no commands\n", gn->name);
437 return FALSE;
438 }
439 if ((gn->type & (OP_META|OP_SUBMAKE)) == OP_SUBMAKE) {
440 /* OP_SUBMAKE is a bit too aggressive */
441 if (any_is_submake(gn)) {
442 DEBUG1(META, "Skipping meta for %s: .SUBMAKE\n", gn->name);
443 return FALSE;
444 }
445 }
446
447 /* The object directory may not exist. Check it.. */
448 if (cached_stat(dname, &cst) != 0) {
449 if (verbose)
450 debug_printf("Skipping meta for %s: no .OBJDIR\n", gn->name);
451 return FALSE;
452 }
453
454 /* make sure these are canonical */
455 if (cached_realpath(dname, objdir_realpath))
456 dname = objdir_realpath;
457
458 /* If we aren't in the object directory, don't create a meta file. */
459 if (!metaCurdirOk && strcmp(curdir, dname) == 0) {
460 if (verbose)
461 debug_printf("Skipping meta for %s: .OBJDIR == .CURDIR\n",
462 gn->name);
463 return FALSE;
464 }
465 return TRUE;
466 }
467
468
469 static FILE *
470 meta_create(BuildMon *pbm, GNode *gn)
471 {
472 FILE *fp;
473 char buf[MAXPATHLEN];
474 char objdir_realpath[MAXPATHLEN];
475 char **ptr;
476 const char *dname;
477 const char *tname;
478 char *fname;
479 const char *cp;
480 void *dname_freeIt;
481
482 fp = NULL;
483
484 dname = Var_Value(".OBJDIR", gn, &dname_freeIt);
485 tname = GNode_VarTarget(gn);
486
487 /* if this succeeds objdir_realpath is realpath of dname */
488 if (!meta_needed(gn, dname, objdir_realpath, TRUE))
489 goto out;
490 dname = objdir_realpath;
491
492 if (metaVerbose) {
493 char *mp;
494
495 /* Describe the target we are building */
496 (void)Var_Subst("${" MAKE_META_PREFIX "}", gn, VARE_WANTRES, &mp);
497 /* TODO: handle errors */
498 if (mp[0] != '\0')
499 fprintf(stdout, "%s\n", mp);
500 free(mp);
501 }
502 /* Get the basename of the target */
503 cp = str_basename(tname);
504
505 fflush(stdout);
506
507 if (!writeMeta)
508 /* Don't create meta data. */
509 goto out;
510
511 fname = meta_name(pbm->meta_fname, sizeof pbm->meta_fname,
512 dname, tname, objdir_realpath);
513
514 #ifdef DEBUG_META_MODE
515 DEBUG1(META, "meta_create: %s\n", fname);
516 #endif
517
518 if ((fp = fopen(fname, "w")) == NULL)
519 err(1, "Could not open meta file '%s'", fname);
520
521 fprintf(fp, "# Meta data file %s\n", fname);
522
523 printCMDs(gn, fp);
524
525 fprintf(fp, "CWD %s\n", getcwd(buf, sizeof buf));
526 fprintf(fp, "TARGET %s\n", tname);
527 cp = GNode_VarOodate(gn);
528 if (cp && *cp) {
529 fprintf(fp, "OODATE %s\n", cp);
530 }
531 if (metaEnv) {
532 for (ptr = environ; *ptr != NULL; ptr++)
533 fprintf(fp, "ENV %s\n", *ptr);
534 }
535
536 fprintf(fp, "-- command output --\n");
537 fflush(fp);
538
539 Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL);
540 Var_Append(".MAKE.META.CREATED", fname, VAR_GLOBAL);
541
542 gn->type |= OP_META; /* in case anyone wants to know */
543 if (metaSilent) {
544 gn->type |= OP_SILENT;
545 }
546 out:
547 bmake_free(dname_freeIt);
548
549 return fp;
550 }
551
552 static Boolean
553 boolValue(char *s)
554 {
555 switch(*s) {
556 case '0':
557 case 'N':
558 case 'n':
559 case 'F':
560 case 'f':
561 return FALSE;
562 }
563 return TRUE;
564 }
565
566 /*
567 * Initialization we need before reading makefiles.
568 */
569 void
570 meta_init(void)
571 {
572 #ifdef USE_FILEMON
573 /* this allows makefiles to test if we have filemon support */
574 Var_Set(".MAKE.PATH_FILEMON", filemon_path(), VAR_GLOBAL);
575 #endif
576 }
577
578
579 #define get_mode_bf(bf, token) \
580 if ((cp = strstr(make_mode, token))) \
581 bf = boolValue(cp + sizeof (token) - 1)
582
583 /*
584 * Initialization we need after reading makefiles.
585 */
586 void
587 meta_mode_init(const char *make_mode)
588 {
589 static Boolean once = FALSE;
590 char *cp;
591 void *freeIt;
592
593 useMeta = TRUE;
594 useFilemon = TRUE;
595 writeMeta = TRUE;
596
597 if (make_mode != NULL) {
598 if (strstr(make_mode, "env"))
599 metaEnv = TRUE;
600 if (strstr(make_mode, "verb"))
601 metaVerbose = TRUE;
602 if (strstr(make_mode, "read"))
603 writeMeta = FALSE;
604 if (strstr(make_mode, "nofilemon"))
605 useFilemon = FALSE;
606 if (strstr(make_mode, "ignore-cmd"))
607 metaIgnoreCMDs = TRUE;
608 if (useFilemon)
609 get_mode_bf(filemonMissing, "missing-filemon=");
610 get_mode_bf(metaCurdirOk, "curdirok=");
611 get_mode_bf(metaMissing, "missing-meta=");
612 get_mode_bf(metaSilent, "silent=");
613 }
614 if (metaVerbose && !Var_Exists(MAKE_META_PREFIX, VAR_GLOBAL)) {
615 /*
616 * The default value for MAKE_META_PREFIX
617 * prints the absolute path of the target.
618 * This works be cause :H will generate '.' if there is no /
619 * and :tA will resolve that to cwd.
620 */
621 Var_Set(MAKE_META_PREFIX, "Building ${.TARGET:H:tA}/${.TARGET:T}", VAR_GLOBAL);
622 }
623 if (once)
624 return;
625 once = TRUE;
626 memset(&Mybm, 0, sizeof Mybm);
627 /*
628 * We consider ourselves master of all within ${.MAKE.META.BAILIWICK}
629 */
630 (void)Var_Subst("${.MAKE.META.BAILIWICK:O:u:tA}",
631 VAR_GLOBAL, VARE_WANTRES, &metaBailiwickStr);
632 /* TODO: handle errors */
633 str2Lst_Append(&metaBailiwick, metaBailiwickStr);
634 /*
635 * We ignore any paths that start with ${.MAKE.META.IGNORE_PATHS}
636 */
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);
643
644 /*
645 * We ignore any paths that match ${.MAKE.META.IGNORE_PATTERNS}
646 */
647 freeIt = NULL;
648 if (Var_Value(MAKE_META_IGNORE_PATTERNS, VAR_GLOBAL, &freeIt)) {
649 metaIgnorePatterns = TRUE;
650 bmake_free(freeIt);
651 }
652 freeIt = NULL;
653 if (Var_Value(MAKE_META_IGNORE_FILTER, VAR_GLOBAL, &freeIt)) {
654 metaIgnoreFilter = TRUE;
655 bmake_free(freeIt);
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, Boolean ignerr, int status)
772 {
773 char cwd[MAXPATHLEN];
774 BuildMon *pbm;
775
776 if (job != NULL) {
777 pbm = &job->bm;
778 if (gn == NULL)
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, ignerr ? "(ignored)" : "");
786 }
787 if (gn != NULL) {
788 Var_Set(".ERROR_TARGET", GNode_Path(gn), VAR_GLOBAL);
789 }
790 getcwd(cwd, sizeof cwd);
791 Var_Set(".ERROR_CWD", cwd, VAR_GLOBAL);
792 if (pbm->meta_fname[0] != '\0') {
793 Var_Set(".ERROR_META_FILE", pbm->meta_fname, VAR_GLOBAL);
794 }
795 meta_job_finish(job);
796 }
797
798 void
799 meta_job_output(Job *job, char *cp, const char *nl)
800 {
801 BuildMon *pbm;
802
803 if (job != NULL) {
804 pbm = &job->bm;
805 } else {
806 pbm = &Mybm;
807 }
808 if (pbm->mfp != NULL) {
809 if (metaVerbose) {
810 static char *meta_prefix = NULL;
811 static size_t meta_prefix_len;
812
813 if (meta_prefix == NULL) {
814 char *cp2;
815
816 (void)Var_Subst("${" MAKE_META_PREFIX "}",
817 VAR_GLOBAL, VARE_WANTRES, &meta_prefix);
818 /* TODO: handle errors */
819 if ((cp2 = strchr(meta_prefix, '$')))
820 meta_prefix_len = (size_t)(cp2 - meta_prefix);
821 else
822 meta_prefix_len = strlen(meta_prefix);
823 }
824 if (strncmp(cp, meta_prefix, meta_prefix_len) == 0) {
825 cp = strchr(cp+1, '\n');
826 if (!cp++)
827 return;
828 }
829 }
830 fprintf(pbm->mfp, "%s%s", cp, nl);
831 }
832 }
833
834 int
835 meta_cmd_finish(void *pbmp)
836 {
837 int error = 0;
838 BuildMon *pbm = pbmp;
839 #ifdef USE_FILEMON
840 int x;
841 #endif
842
843 if (pbm == NULL)
844 pbm = &Mybm;
845
846 #ifdef USE_FILEMON
847 if (pbm->filemon) {
848 while (filemon_process(pbm->filemon) > 0)
849 continue;
850 if (filemon_close(pbm->filemon) == -1)
851 error = errno;
852 x = filemon_read(pbm->mfp, pbm->mon_fd);
853 if (error == 0 && x != 0)
854 error = x;
855 pbm->mon_fd = -1;
856 pbm->filemon = NULL;
857 return error;
858 }
859 #endif
860
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 Lst_Done(&metaBailiwick);
892 free(metaBailiwickStr);
893 Lst_Done(&metaIgnorePaths);
894 free(metaIgnorePathsStr);
895 }
896
897 /*
898 * Fetch a full line from fp - growing bufp if needed
899 * Return length in bufp.
900 */
901 static int
902 fgetLine(char **bufp, size_t *szp, int o, FILE *fp)
903 {
904 char *buf = *bufp;
905 size_t bufsz = *szp;
906 struct stat fs;
907 int x;
908
909 if (fgets(&buf[o], (int)bufsz - o, fp) != NULL) {
910 check_newline:
911 x = o + (int)strlen(&buf[o]);
912 if (buf[x - 1] == '\n')
913 return x;
914 /*
915 * We need to grow the buffer.
916 * The meta file can give us a clue.
917 */
918 if (fstat(fileno(fp), &fs) == 0) {
919 size_t newsz;
920 char *p;
921
922 newsz = ROUNDUP(((size_t)fs.st_size / 2), BUFSIZ);
923 if (newsz <= bufsz)
924 newsz = ROUNDUP((size_t)fs.st_size, BUFSIZ);
925 if (newsz <= bufsz)
926 return x; /* truncated */
927 DEBUG2(META, "growing buffer %zu -> %zu\n", bufsz, newsz);
928 p = bmake_realloc(buf, newsz);
929 *bufp = buf = p;
930 *szp = bufsz = newsz;
931 /* fetch the rest */
932 if (fgets(&buf[x], (int)bufsz - x, fp) == NULL)
933 return x; /* truncated! */
934 goto check_newline;
935 }
936 }
937 return 0;
938 }
939
940 static Boolean
941 prefix_match(const char *prefix, const char *path)
942 {
943 size_t n = strlen(prefix);
944
945 return strncmp(path, prefix, n) == 0;
946 }
947
948 static Boolean
949 has_any_prefix(const char *path, StringList *prefixes)
950 {
951 StringListNode *ln;
952
953 for (ln = prefixes->first; ln != NULL; ln = ln->next)
954 if (prefix_match(ln->datum, path))
955 return TRUE;
956 return FALSE;
957 }
958
959 /* See if the path equals prefix or starts with "prefix/". */
960 static Boolean
961 path_starts_with(const char *path, const char *prefix)
962 {
963 size_t n = strlen(prefix);
964
965 if (strncmp(path, prefix, n) != 0)
966 return FALSE;
967 return path[n] == '\0' || path[n] == '/';
968 }
969
970 static int
971 meta_ignore(GNode *gn, const char *p)
972 {
973 char fname[MAXPATHLEN];
974
975 if (p == NULL)
976 return TRUE;
977
978 if (*p == '/') {
979 cached_realpath(p, fname); /* clean it up */
980 if (has_any_prefix(fname, &metaIgnorePaths)) {
981 #ifdef DEBUG_META_MODE
982 DEBUG1(META, "meta_oodate: ignoring path: %s\n", p);
983 #endif
984 return TRUE;
985 }
986 }
987
988 if (metaIgnorePatterns) {
989 const char *expr;
990 char *pm;
991
992 Var_Set(".p.", p, gn);
993 expr = "${" MAKE_META_IGNORE_PATTERNS ":@m@${.p.:M$m}@}";
994 (void)Var_Subst(expr, gn, VARE_WANTRES, &pm);
995 /* TODO: handle errors */
996 if (pm[0] != '\0') {
997 #ifdef DEBUG_META_MODE
998 DEBUG1(META, "meta_oodate: ignoring pattern: %s\n", p);
999 #endif
1000 free(pm);
1001 return TRUE;
1002 }
1003 free(pm);
1004 }
1005
1006 if (metaIgnoreFilter) {
1007 char *fm;
1008
1009 /* skip if filter result is empty */
1010 snprintf(fname, sizeof fname,
1011 "${%s:L:${%s:ts:}}",
1012 p, MAKE_META_IGNORE_FILTER);
1013 (void)Var_Subst(fname, gn, VARE_WANTRES, &fm);
1014 /* TODO: handle errors */
1015 if (*fm == '\0') {
1016 #ifdef DEBUG_META_MODE
1017 DEBUG1(META, "meta_oodate: ignoring filtered: %s\n", p);
1018 #endif
1019 free(fm);
1020 return TRUE;
1021 }
1022 free(fm);
1023 }
1024 return FALSE;
1025 }
1026
1027 /*
1028 * When running with 'meta' functionality, a target can be out-of-date
1029 * if any of the references in its meta data file is more recent.
1030 * We have to track the latestdir on a per-process basis.
1031 */
1032 #define LCWD_VNAME_FMT ".meta.%d.lcwd"
1033 #define LDIR_VNAME_FMT ".meta.%d.ldir"
1034
1035 /*
1036 * It is possible that a .meta file is corrupted,
1037 * if we detect this we want to reproduce it.
1038 * Setting oodate TRUE will have that effect.
1039 */
1040 #define CHECK_VALID_META(p) if (!(p && *p)) { \
1041 warnx("%s: %d: malformed", fname, lineno); \
1042 oodate = TRUE; \
1043 continue; \
1044 }
1045
1046 #define DEQUOTE(p) if (*p == '\'') { \
1047 char *ep; \
1048 p++; \
1049 if ((ep = strchr(p, '\''))) \
1050 *ep = '\0'; \
1051 }
1052
1053 static void
1054 append_if_new(StringList *list, const char *str)
1055 {
1056 StringListNode *ln;
1057
1058 for (ln = list->first; ln != NULL; ln = ln->next)
1059 if (strcmp(ln->datum, str) == 0)
1060 return;
1061 Lst_Append(list, bmake_strdup(str));
1062 }
1063
1064 Boolean
1065 meta_oodate(GNode *gn, Boolean oodate)
1066 {
1067 static char *tmpdir = NULL;
1068 static char cwd[MAXPATHLEN];
1069 char lcwd_vname[64];
1070 char ldir_vname[64];
1071 char lcwd[MAXPATHLEN];
1072 char latestdir[MAXPATHLEN];
1073 char fname[MAXPATHLEN];
1074 char fname1[MAXPATHLEN];
1075 char fname2[MAXPATHLEN];
1076 char fname3[MAXPATHLEN];
1077 const char *dname;
1078 const char *tname;
1079 char *p;
1080 char *cp;
1081 char *link_src;
1082 char *move_target;
1083 static size_t cwdlen = 0;
1084 static size_t tmplen = 0;
1085 FILE *fp;
1086 Boolean needOODATE = FALSE;
1087 StringList missingFiles;
1088 Boolean have_filemon = FALSE;
1089 void *objdir_freeIt;
1090
1091 if (oodate)
1092 return oodate; /* we're done */
1093
1094 dname = Var_Value(".OBJDIR", gn, &objdir_freeIt);
1095 tname = GNode_VarTarget(gn);
1096
1097 /* if this succeeds fname3 is realpath of dname */
1098 if (!meta_needed(gn, dname, fname3, FALSE))
1099 goto oodate_out;
1100 dname = fname3;
1101
1102 Lst_Init(&missingFiles);
1103
1104 /*
1105 * We need to check if the target is out-of-date. This includes
1106 * checking if the expanded command has changed. This in turn
1107 * requires that all variables are set in the same way that they
1108 * would be if the target needs to be re-built.
1109 */
1110 Make_DoAllVar(gn);
1111
1112 meta_name(fname, sizeof fname, dname, tname, dname);
1113
1114 #ifdef DEBUG_META_MODE
1115 DEBUG1(META, "meta_oodate: %s\n", fname);
1116 #endif
1117
1118 if ((fp = fopen(fname, "r")) != NULL) {
1119 static char *buf = NULL;
1120 static size_t bufsz;
1121 int lineno = 0;
1122 int lastpid = 0;
1123 int pid;
1124 int x;
1125 StringListNode *cmdNode;
1126 struct cached_stat cst;
1127
1128 if (buf == NULL) {
1129 bufsz = 8 * BUFSIZ;
1130 buf = bmake_malloc(bufsz);
1131 }
1132
1133 if (cwdlen == 0) {
1134 if (getcwd(cwd, sizeof cwd) == NULL)
1135 err(1, "Could not get current working directory");
1136 cwdlen = strlen(cwd);
1137 }
1138 strlcpy(lcwd, cwd, sizeof lcwd);
1139 strlcpy(latestdir, cwd, sizeof latestdir);
1140
1141 if (tmpdir == NULL) {
1142 tmpdir = getTmpdir();
1143 tmplen = strlen(tmpdir);
1144 }
1145
1146 /* we want to track all the .meta we read */
1147 Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL);
1148
1149 cmdNode = gn->commands.first;
1150 while (!oodate && (x = fgetLine(&buf, &bufsz, 0, fp)) > 0) {
1151 lineno++;
1152 if (buf[x - 1] == '\n')
1153 buf[x - 1] = '\0';
1154 else {
1155 warnx("%s: %d: line truncated at %u", fname, lineno, x);
1156 oodate = TRUE;
1157 break;
1158 }
1159 link_src = NULL;
1160 move_target = NULL;
1161 /* Find the start of the build monitor section. */
1162 if (!have_filemon) {
1163 if (strncmp(buf, "-- filemon", 10) == 0) {
1164 have_filemon = TRUE;
1165 continue;
1166 }
1167 if (strncmp(buf, "# buildmon", 10) == 0) {
1168 have_filemon = TRUE;
1169 continue;
1170 }
1171 }
1172
1173 /* Delimit the record type. */
1174 p = buf;
1175 #ifdef DEBUG_META_MODE
1176 DEBUG3(META, "%s: %d: %s\n", fname, lineno, buf);
1177 #endif
1178 strsep(&p, " ");
1179 if (have_filemon) {
1180 /*
1181 * We are in the 'filemon' output section.
1182 * Each record from filemon follows the general form:
1183 *
1184 * <key> <pid> <data>
1185 *
1186 * Where:
1187 * <key> is a single letter, denoting the syscall.
1188 * <pid> is the process that made the syscall.
1189 * <data> is the arguments (of interest).
1190 */
1191 switch(buf[0]) {
1192 case '#': /* comment */
1193 case 'V': /* version */
1194 break;
1195 default:
1196 /*
1197 * We need to track pathnames per-process.
1198 *
1199 * Each process run by make, starts off in the 'CWD'
1200 * recorded in the .meta file, if it chdirs ('C')
1201 * elsewhere we need to track that - but only for
1202 * that process. If it forks ('F'), we initialize
1203 * the child to have the same cwd as its parent.
1204 *
1205 * We also need to track the 'latestdir' of
1206 * interest. This is usually the same as cwd, but
1207 * not if a process is reading directories.
1208 *
1209 * Each time we spot a different process ('pid')
1210 * we save the current value of 'latestdir' in a
1211 * variable qualified by 'lastpid', and
1212 * re-initialize 'latestdir' to any pre-saved
1213 * value for the current 'pid' and 'CWD' if none.
1214 */
1215 CHECK_VALID_META(p);
1216 pid = atoi(p);
1217 if (pid > 0 && pid != lastpid) {
1218 const char *ldir;
1219 void *tp;
1220
1221 if (lastpid > 0) {
1222 /* We need to remember these. */
1223 Var_Set(lcwd_vname, lcwd, VAR_GLOBAL);
1224 Var_Set(ldir_vname, latestdir, VAR_GLOBAL);
1225 }
1226 snprintf(lcwd_vname, sizeof lcwd_vname, LCWD_VNAME_FMT, pid);
1227 snprintf(ldir_vname, sizeof ldir_vname, LDIR_VNAME_FMT, pid);
1228 lastpid = pid;
1229 ldir = Var_Value(ldir_vname, VAR_GLOBAL, &tp);
1230 if (ldir != NULL) {
1231 strlcpy(latestdir, ldir, sizeof latestdir);
1232 bmake_free(tp);
1233 }
1234 ldir = Var_Value(lcwd_vname, VAR_GLOBAL, &tp);
1235 if (ldir != NULL) {
1236 strlcpy(lcwd, ldir, sizeof lcwd);
1237 bmake_free(tp);
1238 }
1239 }
1240 /* Skip past the pid. */
1241 if (strsep(&p, " ") == NULL)
1242 continue;
1243 #ifdef DEBUG_META_MODE
1244 if (DEBUG(META))
1245 debug_printf("%s: %d: %d: %c: cwd=%s lcwd=%s ldir=%s\n",
1246 fname, lineno,
1247 pid, buf[0], cwd, lcwd, latestdir);
1248 #endif
1249 break;
1250 }
1251
1252 CHECK_VALID_META(p);
1253
1254 /* Process according to record type. */
1255 switch (buf[0]) {
1256 case 'X': /* eXit */
1257 Var_Delete(lcwd_vname, VAR_GLOBAL);
1258 Var_Delete(ldir_vname, VAR_GLOBAL);
1259 lastpid = 0; /* no need to save ldir_vname */
1260 break;
1261
1262 case 'F': /* [v]Fork */
1263 {
1264 char cldir[64];
1265 int child;
1266
1267 child = atoi(p);
1268 if (child > 0) {
1269 snprintf(cldir, sizeof cldir, LCWD_VNAME_FMT, child);
1270 Var_Set(cldir, lcwd, VAR_GLOBAL);
1271 snprintf(cldir, sizeof cldir, LDIR_VNAME_FMT, child);
1272 Var_Set(cldir, latestdir, VAR_GLOBAL);
1273 #ifdef DEBUG_META_MODE
1274 if (DEBUG(META))
1275 debug_printf(
1276 "%s: %d: %d: cwd=%s lcwd=%s ldir=%s\n",
1277 fname, lineno,
1278 child, cwd, lcwd, latestdir);
1279 #endif
1280 }
1281 }
1282 break;
1283
1284 case 'C': /* Chdir */
1285 /* Update lcwd and latest directory. */
1286 strlcpy(latestdir, p, sizeof latestdir);
1287 strlcpy(lcwd, p, sizeof lcwd);
1288 Var_Set(lcwd_vname, lcwd, VAR_GLOBAL);
1289 Var_Set(ldir_vname, lcwd, VAR_GLOBAL);
1290 #ifdef DEBUG_META_MODE
1291 DEBUG4(META, "%s: %d: cwd=%s ldir=%s\n",
1292 fname, lineno, cwd, lcwd);
1293 #endif
1294 break;
1295
1296 case 'M': /* renaMe */
1297 /*
1298 * For 'M'oves we want to check
1299 * the src as for 'R'ead
1300 * and the target as for 'W'rite.
1301 */
1302 cp = p; /* save this for a second */
1303 /* now get target */
1304 if (strsep(&p, " ") == NULL)
1305 continue;
1306 CHECK_VALID_META(p);
1307 move_target = p;
1308 p = cp;
1309 /* 'L' and 'M' put single quotes around the args */
1310 DEQUOTE(p);
1311 DEQUOTE(move_target);
1312 /* FALLTHROUGH */
1313 case 'D': /* unlink */
1314 if (*p == '/') {
1315 /* remove any missingFiles entries that match p */
1316 StringListNode *ln = missingFiles.first;
1317 while (ln != NULL) {
1318 StringListNode *next = ln->next;
1319 if (path_starts_with(ln->datum, p)) {
1320 free(ln->datum);
1321 Lst_Remove(&missingFiles, ln);
1322 }
1323 ln = next;
1324 }
1325 }
1326 if (buf[0] == 'M') {
1327 /* the target of the mv is a file 'W'ritten */
1328 #ifdef DEBUG_META_MODE
1329 DEBUG2(META, "meta_oodate: M %s -> %s\n",
1330 p, move_target);
1331 #endif
1332 p = move_target;
1333 goto check_write;
1334 }
1335 break;
1336 case 'L': /* Link */
1337 /*
1338 * For 'L'inks check
1339 * the src as for 'R'ead
1340 * and the target as for 'W'rite.
1341 */
1342 link_src = p;
1343 /* now get target */
1344 if (strsep(&p, " ") == NULL)
1345 continue;
1346 CHECK_VALID_META(p);
1347 /* 'L' and 'M' put single quotes around the args */
1348 DEQUOTE(p);
1349 DEQUOTE(link_src);
1350 #ifdef DEBUG_META_MODE
1351 DEBUG2(META, "meta_oodate: L %s -> %s\n", link_src, p);
1352 #endif
1353 /* FALLTHROUGH */
1354 case 'W': /* Write */
1355 check_write:
1356 /*
1357 * If a file we generated within our bailiwick
1358 * but outside of .OBJDIR is missing,
1359 * we need to do it again.
1360 */
1361 /* ignore non-absolute paths */
1362 if (*p != '/')
1363 break;
1364
1365 if (Lst_IsEmpty(&metaBailiwick))
1366 break;
1367
1368 /* ignore cwd - normal dependencies handle those */
1369 if (strncmp(p, cwd, cwdlen) == 0)
1370 break;
1371
1372 if (!has_any_prefix(p, &metaBailiwick))
1373 break;
1374
1375 /* tmpdir might be within */
1376 if (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0)
1377 break;
1378
1379 /* ignore anything containing the string "tmp" */
1380 /* XXX: The arguments to strstr must be swapped. */
1381 if ((strstr("tmp", p)))
1382 break;
1383
1384 if ((link_src != NULL && cached_lstat(p, &cst) < 0) ||
1385 (link_src == NULL && cached_stat(p, &cst) < 0)) {
1386 if (!meta_ignore(gn, p))
1387 append_if_new(&missingFiles, p);
1388 }
1389 break;
1390 check_link_src:
1391 p = link_src;
1392 link_src = NULL;
1393 #ifdef DEBUG_META_MODE
1394 DEBUG1(META, "meta_oodate: L src %s\n", p);
1395 #endif
1396 /* FALLTHROUGH */
1397 case 'R': /* Read */
1398 case 'E': /* Exec */
1399 /*
1400 * Check for runtime files that can't
1401 * be part of the dependencies because
1402 * they are _expected_ to change.
1403 */
1404 if (meta_ignore(gn, p))
1405 break;
1406
1407 /*
1408 * The rest of the record is the file name.
1409 * Check if it's not an absolute path.
1410 */
1411 {
1412 char *sdirs[4];
1413 char **sdp;
1414 int sdx = 0;
1415 Boolean found = FALSE;
1416
1417 if (*p == '/') {
1418 sdirs[sdx++] = p; /* done */
1419 } else {
1420 if (strcmp(".", p) == 0)
1421 continue; /* no point */
1422
1423 /* Check vs latestdir */
1424 snprintf(fname1, sizeof fname1, "%s/%s", latestdir, p);
1425 sdirs[sdx++] = fname1;
1426
1427 if (strcmp(latestdir, lcwd) != 0) {
1428 /* Check vs lcwd */
1429 snprintf(fname2, sizeof fname2, "%s/%s", lcwd, p);
1430 sdirs[sdx++] = fname2;
1431 }
1432 if (strcmp(lcwd, cwd) != 0) {
1433 /* Check vs cwd */
1434 snprintf(fname3, sizeof fname3, "%s/%s", cwd, p);
1435 sdirs[sdx++] = fname3;
1436 }
1437 }
1438 sdirs[sdx++] = NULL;
1439
1440 for (sdp = sdirs; *sdp && !found; sdp++) {
1441 #ifdef DEBUG_META_MODE
1442 DEBUG3(META, "%s: %d: looking for: %s\n",
1443 fname, lineno, *sdp);
1444 #endif
1445 if (cached_stat(*sdp, &cst) == 0) {
1446 found = TRUE;
1447 p = *sdp;
1448 }
1449 }
1450 if (found) {
1451 #ifdef DEBUG_META_MODE
1452 DEBUG3(META, "%s: %d: found: %s\n",
1453 fname, lineno, p);
1454 #endif
1455 if (!S_ISDIR(cst.cst_mode) &&
1456 cst.cst_mtime > gn->mtime) {
1457 DEBUG3(META, "%s: %d: file '%s' is newer than the target...\n",
1458 fname, lineno, p);
1459 oodate = TRUE;
1460 } else if (S_ISDIR(cst.cst_mode)) {
1461 /* Update the latest directory. */
1462 cached_realpath(p, latestdir);
1463 }
1464 } else if (errno == ENOENT && *p == '/' &&
1465 strncmp(p, cwd, cwdlen) != 0) {
1466 /*
1467 * A referenced file outside of CWD is missing.
1468 * We cannot catch every eventuality here...
1469 */
1470 append_if_new(&missingFiles, p);
1471 }
1472 }
1473 if (buf[0] == 'E') {
1474 /* previous latestdir is no longer relevant */
1475 strlcpy(latestdir, lcwd, sizeof latestdir);
1476 }
1477 break;
1478 default:
1479 break;
1480 }
1481 if (!oodate && buf[0] == 'L' && link_src != NULL)
1482 goto check_link_src;
1483 } else if (strcmp(buf, "CMD") == 0) {
1484 /*
1485 * Compare the current command with the one in the
1486 * meta data file.
1487 */
1488 if (cmdNode == NULL) {
1489 DEBUG2(META, "%s: %d: there were more build commands in the meta data file than there are now...\n",
1490 fname, lineno);
1491 oodate = TRUE;
1492 } else {
1493 char *cmd = cmdNode->datum;
1494 Boolean hasOODATE = FALSE;
1495
1496 if (strstr(cmd, "$?"))
1497 hasOODATE = TRUE;
1498 else if ((cp = strstr(cmd, ".OODATE"))) {
1499 /* check for $[{(].OODATE[:)}] */
1500 if (cp > cmd + 2 && cp[-2] == '$')
1501 hasOODATE = TRUE;
1502 }
1503 if (hasOODATE) {
1504 needOODATE = TRUE;
1505 DEBUG2(META, "%s: %d: cannot compare command using .OODATE\n",
1506 fname, lineno);
1507 }
1508 (void)Var_Subst(cmd, gn, VARE_WANTRES|VARE_UNDEFERR, &cmd);
1509 /* TODO: handle errors */
1510
1511 if ((cp = strchr(cmd, '\n'))) {
1512 int n;
1513
1514 /*
1515 * This command contains newlines, we need to
1516 * fetch more from the .meta file before we
1517 * attempt a comparison.
1518 */
1519 /* first put the newline back at buf[x - 1] */
1520 buf[x - 1] = '\n';
1521 do {
1522 /* now fetch the next line */
1523 if ((n = fgetLine(&buf, &bufsz, x, fp)) <= 0)
1524 break;
1525 x = n;
1526 lineno++;
1527 if (buf[x - 1] != '\n') {
1528 warnx("%s: %d: line truncated at %u", fname, lineno, x);
1529 break;
1530 }
1531 cp = strchr(++cp, '\n');
1532 } while (cp != NULL);
1533 if (buf[x - 1] == '\n')
1534 buf[x - 1] = '\0';
1535 }
1536 if (p != NULL &&
1537 !hasOODATE &&
1538 !(gn->type & OP_NOMETA_CMP) &&
1539 (strcmp(p, cmd) != 0)) {
1540 DEBUG4(META, "%s: %d: a build command has changed\n%s\nvs\n%s\n",
1541 fname, lineno, p, cmd);
1542 if (!metaIgnoreCMDs)
1543 oodate = TRUE;
1544 }
1545 free(cmd);
1546 cmdNode = cmdNode->next;
1547 }
1548 } else if (strcmp(buf, "CWD") == 0) {
1549 /*
1550 * Check if there are extra commands now
1551 * that weren't in the meta data file.
1552 */
1553 if (!oodate && cmdNode != NULL) {
1554 DEBUG2(META, "%s: %d: there are extra build commands now that weren't in the meta data file\n",
1555 fname, lineno);
1556 oodate = TRUE;
1557 }
1558 CHECK_VALID_META(p);
1559 if (strcmp(p, cwd) != 0) {
1560 DEBUG4(META, "%s: %d: the current working directory has changed from '%s' to '%s'\n",
1561 fname, lineno, p, curdir);
1562 oodate = TRUE;
1563 }
1564 }
1565 }
1566
1567 fclose(fp);
1568 if (!Lst_IsEmpty(&missingFiles)) {
1569 DEBUG2(META, "%s: missing files: %s...\n",
1570 fname, (char *)missingFiles.first->datum);
1571 oodate = TRUE;
1572 }
1573 if (!oodate && !have_filemon && filemonMissing) {
1574 DEBUG1(META, "%s: missing filemon data\n", fname);
1575 oodate = TRUE;
1576 }
1577 } else {
1578 if (writeMeta && (metaMissing || (gn->type & OP_META))) {
1579 cp = NULL;
1580
1581 /* if target is in .CURDIR we do not need a meta file */
1582 if (gn->path && (cp = strrchr(gn->path, '/')) && cp > gn->path) {
1583 if (strncmp(curdir, gn->path, (size_t)(cp - gn->path)) != 0) {
1584 cp = NULL; /* not in .CURDIR */
1585 }
1586 }
1587 if (cp == NULL) {
1588 DEBUG1(META, "%s: required but missing\n", fname);
1589 oodate = TRUE;
1590 needOODATE = TRUE; /* assume the worst */
1591 }
1592 }
1593 }
1594
1595 Lst_DoneCall(&missingFiles, free);
1596
1597 if (oodate && needOODATE) {
1598 /*
1599 * Target uses .OODATE which is empty; or we wouldn't be here.
1600 * We have decided it is oodate, so .OODATE needs to be set.
1601 * All we can sanely do is set it to .ALLSRC.
1602 */
1603 Var_Delete(OODATE, gn);
1604 Var_Set(OODATE, GNode_VarAllsrc(gn), gn);
1605 }
1606
1607 oodate_out:
1608 bmake_free(objdir_freeIt);
1609 return oodate;
1610 }
1611
1612 /* support for compat mode */
1613
1614 static int childPipe[2];
1615
1616 void
1617 meta_compat_start(void)
1618 {
1619 #ifdef USE_FILEMON_ONCE
1620 /*
1621 * We need to re-open filemon for each cmd.
1622 */
1623 BuildMon *pbm = &Mybm;
1624
1625 if (pbm->mfp != NULL && useFilemon) {
1626 meta_open_filemon(pbm);
1627 } else {
1628 pbm->mon_fd = -1;
1629 pbm->filemon = NULL;
1630 }
1631 #endif
1632 if (pipe(childPipe) < 0)
1633 Punt("Cannot create pipe: %s", strerror(errno));
1634 /* Set close-on-exec flag for both */
1635 (void)fcntl(childPipe[0], F_SETFD, FD_CLOEXEC);
1636 (void)fcntl(childPipe[1], F_SETFD, FD_CLOEXEC);
1637 }
1638
1639 void
1640 meta_compat_child(void)
1641 {
1642 meta_job_child(NULL);
1643 if (dup2(childPipe[1], 1) < 0 || dup2(1, 2) < 0)
1644 execDie("dup2", "pipe");
1645 }
1646
1647 void
1648 meta_compat_parent(pid_t child)
1649 {
1650 int outfd, metafd, maxfd, nfds;
1651 char buf[BUFSIZ+1];
1652 fd_set readfds;
1653
1654 meta_job_parent(NULL, child);
1655 close(childPipe[1]); /* child side */
1656 outfd = childPipe[0];
1657 #ifdef USE_FILEMON
1658 metafd = Mybm.filemon ? filemon_readfd(Mybm.filemon) : -1;
1659 #else
1660 metafd = -1;
1661 #endif
1662 maxfd = -1;
1663 if (outfd > maxfd)
1664 maxfd = outfd;
1665 if (metafd > maxfd)
1666 maxfd = metafd;
1667
1668 while (outfd != -1 || metafd != -1) {
1669 FD_ZERO(&readfds);
1670 if (outfd != -1) {
1671 FD_SET(outfd, &readfds);
1672 }
1673 if (metafd != -1) {
1674 FD_SET(metafd, &readfds);
1675 }
1676 nfds = select(maxfd + 1, &readfds, NULL, NULL, NULL);
1677 if (nfds == -1) {
1678 if (errno == EINTR)
1679 continue;
1680 err(1, "select");
1681 }
1682
1683 if (outfd != -1 && FD_ISSET(outfd, &readfds)) do {
1684 /* XXX this is not line-buffered */
1685 ssize_t nread = read(outfd, buf, sizeof buf - 1);
1686 if (nread == -1)
1687 err(1, "read");
1688 if (nread == 0) {
1689 close(outfd);
1690 outfd = -1;
1691 break;
1692 }
1693 fwrite(buf, 1, (size_t)nread, stdout);
1694 fflush(stdout);
1695 buf[nread] = '\0';
1696 meta_job_output(NULL, buf, "");
1697 } while (0);
1698 if (metafd != -1 && FD_ISSET(metafd, &readfds)) {
1699 if (meta_job_event(NULL) <= 0)
1700 metafd = -1;
1701 }
1702 }
1703 }
1704
1705 #endif /* USE_META */
1706