meta.c revision 1.169 1 /* $NetBSD: meta.c,v 1.169 2021/01/16 20:49:31 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 == NULL)
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, '/')) != NULL) {
258 if (cached_realpath(tname, buf) != NULL) {
259 if ((rp = strrchr(buf, '/')) != NULL) {
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 != NULL) {
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, '$') != NULL) {
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 StringListNode *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 (/*CONSTCOND*/FALSE)
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);
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) != NULL)
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 != NULL && *cp != '\0') {
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)) != NULL) \
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") != NULL)
597 metaEnv = TRUE;
598 if (strstr(make_mode, "verb") != NULL)
599 metaVerbose = TRUE;
600 if (strstr(make_mode, "read") != NULL)
601 writeMeta = FALSE;
602 if (strstr(make_mode, "nofilemon") != NULL)
603 useFilemon = FALSE;
604 if (strstr(make_mode, "ignore-cmd") != NULL)
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 != NULL) {
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 != NULL) {
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 != NULL) {
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 != NULL) {
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, '$')) != NULL)
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 == NULL)
825 return;
826 cp++;
827 }
828 }
829 fprintf(pbm->mfp, "%s%s", cp, nl);
830 }
831 }
832
833 int
834 meta_cmd_finish(void *pbmp)
835 {
836 int error = 0;
837 BuildMon *pbm = pbmp;
838 #ifdef USE_FILEMON
839 int x;
840 #endif
841
842 if (pbm == NULL)
843 pbm = &Mybm;
844
845 #ifdef USE_FILEMON
846 if (pbm->filemon != NULL) {
847 while (filemon_process(pbm->filemon) > 0)
848 continue;
849 if (filemon_close(pbm->filemon) == -1)
850 error = errno;
851 x = filemon_read(pbm->mfp, pbm->mon_fd);
852 if (error == 0 && x != 0)
853 error = x;
854 pbm->mon_fd = -1;
855 pbm->filemon = NULL;
856 return error;
857 }
858 #endif
859
860 fprintf(pbm->mfp, "\n"); /* ensure end with newline */
861 return error;
862 }
863
864 int
865 meta_job_finish(Job *job)
866 {
867 BuildMon *pbm;
868 int error = 0;
869 int x;
870
871 if (job != NULL) {
872 pbm = &job->bm;
873 } else {
874 pbm = &Mybm;
875 }
876 if (pbm->mfp != NULL) {
877 error = meta_cmd_finish(pbm);
878 x = fclose(pbm->mfp);
879 if (error == 0 && x != 0)
880 error = errno;
881 pbm->mfp = NULL;
882 pbm->meta_fname[0] = '\0';
883 }
884 return error;
885 }
886
887 void
888 meta_finish(void)
889 {
890 Lst_Done(&metaBailiwick);
891 free(metaBailiwickStr);
892 Lst_Done(&metaIgnorePaths);
893 free(metaIgnorePathsStr);
894 }
895
896 /*
897 * Fetch a full line from fp - growing bufp if needed
898 * Return length in bufp.
899 */
900 static int
901 fgetLine(char **bufp, size_t *szp, int o, FILE *fp)
902 {
903 char *buf = *bufp;
904 size_t bufsz = *szp;
905 struct stat fs;
906 int x;
907
908 if (fgets(&buf[o], (int)bufsz - o, fp) != NULL) {
909 check_newline:
910 x = o + (int)strlen(&buf[o]);
911 if (buf[x - 1] == '\n')
912 return x;
913 /*
914 * We need to grow the buffer.
915 * The meta file can give us a clue.
916 */
917 if (fstat(fileno(fp), &fs) == 0) {
918 size_t newsz;
919 char *p;
920
921 newsz = ROUNDUP(((size_t)fs.st_size / 2), BUFSIZ);
922 if (newsz <= bufsz)
923 newsz = ROUNDUP((size_t)fs.st_size, BUFSIZ);
924 if (newsz <= bufsz)
925 return x; /* truncated */
926 DEBUG2(META, "growing buffer %u -> %u\n",
927 (unsigned)bufsz, (unsigned)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 Boolean
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 != NULL && *p != '\0')) { \
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, '\'')) != NULL) \
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 FStr dname;
1078 const char *tname;
1079 char *p;
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 {
1300 char *cp = p; /* save this for a second */
1301 /* now get target */
1302 if (strsep(&p, " ") == NULL)
1303 continue;
1304 CHECK_VALID_META(p);
1305 move_target = p;
1306 p = cp;
1307 }
1308 /* 'L' and 'M' put single quotes around the args */
1309 DEQUOTE(p);
1310 DEQUOTE(move_target);
1311 /* FALLTHROUGH */
1312 case 'D': /* unlink */
1313 if (*p == '/') {
1314 /* remove any missingFiles entries that match p */
1315 StringListNode *ln = missingFiles.first;
1316 while (ln != NULL) {
1317 StringListNode *next = ln->next;
1318 if (path_starts_with(ln->datum, p)) {
1319 free(ln->datum);
1320 Lst_Remove(&missingFiles, ln);
1321 }
1322 ln = next;
1323 }
1324 }
1325 if (buf[0] == 'M') {
1326 /* the target of the mv is a file 'W'ritten */
1327 #ifdef DEBUG_META_MODE
1328 DEBUG2(META, "meta_oodate: M %s -> %s\n",
1329 p, move_target);
1330 #endif
1331 p = move_target;
1332 goto check_write;
1333 }
1334 break;
1335 case 'L': /* Link */
1336 /*
1337 * For 'L'inks check
1338 * the src as for 'R'ead
1339 * and the target as for 'W'rite.
1340 */
1341 link_src = p;
1342 /* now get target */
1343 if (strsep(&p, " ") == NULL)
1344 continue;
1345 CHECK_VALID_META(p);
1346 /* 'L' and 'M' put single quotes around the args */
1347 DEQUOTE(p);
1348 DEQUOTE(link_src);
1349 #ifdef DEBUG_META_MODE
1350 DEBUG2(META, "meta_oodate: L %s -> %s\n", link_src, p);
1351 #endif
1352 /* FALLTHROUGH */
1353 case 'W': /* Write */
1354 check_write:
1355 /*
1356 * If a file we generated within our bailiwick
1357 * but outside of .OBJDIR is missing,
1358 * we need to do it again.
1359 */
1360 /* ignore non-absolute paths */
1361 if (*p != '/')
1362 break;
1363
1364 if (Lst_IsEmpty(&metaBailiwick))
1365 break;
1366
1367 /* ignore cwd - normal dependencies handle those */
1368 if (strncmp(p, cwd, cwdlen) == 0)
1369 break;
1370
1371 if (!has_any_prefix(p, &metaBailiwick))
1372 break;
1373
1374 /* tmpdir might be within */
1375 if (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0)
1376 break;
1377
1378 /* ignore anything containing the string "tmp" */
1379 /* XXX: The arguments to strstr must be swapped. */
1380 if (strstr("tmp", p) != NULL)
1381 break;
1382
1383 if ((link_src != NULL && cached_lstat(p, &cst) < 0) ||
1384 (link_src == NULL && cached_stat(p, &cst) < 0)) {
1385 if (!meta_ignore(gn, p))
1386 append_if_new(&missingFiles, p);
1387 }
1388 break;
1389 check_link_src:
1390 p = link_src;
1391 link_src = NULL;
1392 #ifdef DEBUG_META_MODE
1393 DEBUG1(META, "meta_oodate: L src %s\n", p);
1394 #endif
1395 /* FALLTHROUGH */
1396 case 'R': /* Read */
1397 case 'E': /* Exec */
1398 /*
1399 * Check for runtime files that can't
1400 * be part of the dependencies because
1401 * they are _expected_ to change.
1402 */
1403 if (meta_ignore(gn, p))
1404 break;
1405
1406 /*
1407 * The rest of the record is the file name.
1408 * Check if it's not an absolute path.
1409 */
1410 {
1411 char *sdirs[4];
1412 char **sdp;
1413 int sdx = 0;
1414 Boolean found = FALSE;
1415
1416 if (*p == '/') {
1417 sdirs[sdx++] = p; /* done */
1418 } else {
1419 if (strcmp(".", p) == 0)
1420 continue; /* no point */
1421
1422 /* Check vs latestdir */
1423 snprintf(fname1, sizeof fname1, "%s/%s", latestdir, p);
1424 sdirs[sdx++] = fname1;
1425
1426 if (strcmp(latestdir, lcwd) != 0) {
1427 /* Check vs lcwd */
1428 snprintf(fname2, sizeof fname2, "%s/%s", lcwd, p);
1429 sdirs[sdx++] = fname2;
1430 }
1431 if (strcmp(lcwd, cwd) != 0) {
1432 /* Check vs cwd */
1433 snprintf(fname3, sizeof fname3, "%s/%s", cwd, p);
1434 sdirs[sdx++] = fname3;
1435 }
1436 }
1437 sdirs[sdx++] = NULL;
1438
1439 for (sdp = sdirs; *sdp != NULL && !found; sdp++) {
1440 #ifdef DEBUG_META_MODE
1441 DEBUG3(META, "%s: %d: looking for: %s\n",
1442 fname, lineno, *sdp);
1443 #endif
1444 if (cached_stat(*sdp, &cst) == 0) {
1445 found = TRUE;
1446 p = *sdp;
1447 }
1448 }
1449 if (found) {
1450 #ifdef DEBUG_META_MODE
1451 DEBUG3(META, "%s: %d: found: %s\n",
1452 fname, lineno, p);
1453 #endif
1454 if (!S_ISDIR(cst.cst_mode) &&
1455 cst.cst_mtime > gn->mtime) {
1456 DEBUG3(META, "%s: %d: file '%s' is newer than the target...\n",
1457 fname, lineno, p);
1458 oodate = TRUE;
1459 } else if (S_ISDIR(cst.cst_mode)) {
1460 /* Update the latest directory. */
1461 cached_realpath(p, latestdir);
1462 }
1463 } else if (errno == ENOENT && *p == '/' &&
1464 strncmp(p, cwd, cwdlen) != 0) {
1465 /*
1466 * A referenced file outside of CWD is missing.
1467 * We cannot catch every eventuality here...
1468 */
1469 append_if_new(&missingFiles, p);
1470 }
1471 }
1472 if (buf[0] == 'E') {
1473 /* previous latestdir is no longer relevant */
1474 strlcpy(latestdir, lcwd, sizeof latestdir);
1475 }
1476 break;
1477 default:
1478 break;
1479 }
1480 if (!oodate && buf[0] == 'L' && link_src != NULL)
1481 goto check_link_src;
1482 } else if (strcmp(buf, "CMD") == 0) {
1483 /*
1484 * Compare the current command with the one in the
1485 * meta data file.
1486 */
1487 if (cmdNode == NULL) {
1488 DEBUG2(META, "%s: %d: there were more build commands in the meta data file than there are now...\n",
1489 fname, lineno);
1490 oodate = TRUE;
1491 } else {
1492 const char *cp;
1493 char *cmd = cmdNode->datum;
1494 Boolean hasOODATE = FALSE;
1495
1496 if (strstr(cmd, "$?") != NULL)
1497 hasOODATE = TRUE;
1498 else if ((cp = strstr(cmd, ".OODATE")) != NULL) {
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')) != NULL) {
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 + 1, '\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 const char *cp = NULL;
1580
1581 /* if target is in .CURDIR we do not need a meta file */
1582 if (gn->path != NULL && (cp = strrchr(gn->path, '/')) != NULL &&
1583 (cp > gn->path)) {
1584 if (strncmp(curdir, gn->path, (size_t)(cp - gn->path)) != 0) {
1585 cp = NULL; /* not in .CURDIR */
1586 }
1587 }
1588 if (cp == NULL) {
1589 DEBUG1(META, "%s: required but missing\n", fname);
1590 oodate = TRUE;
1591 needOODATE = TRUE; /* assume the worst */
1592 }
1593 }
1594 }
1595
1596 Lst_DoneCall(&missingFiles, free);
1597
1598 if (oodate && needOODATE) {
1599 /*
1600 * Target uses .OODATE which is empty; or we wouldn't be here.
1601 * We have decided it is oodate, so .OODATE needs to be set.
1602 * All we can sanely do is set it to .ALLSRC.
1603 */
1604 Var_Delete(OODATE, gn);
1605 Var_Set(OODATE, GNode_VarAllsrc(gn), gn);
1606 }
1607
1608 oodate_out:
1609 FStr_Done(&dname);
1610 return oodate;
1611 }
1612
1613 /* support for compat mode */
1614
1615 static int childPipe[2];
1616
1617 void
1618 meta_compat_start(void)
1619 {
1620 #ifdef USE_FILEMON_ONCE
1621 /*
1622 * We need to re-open filemon for each cmd.
1623 */
1624 BuildMon *pbm = &Mybm;
1625
1626 if (pbm->mfp != NULL && useFilemon) {
1627 meta_open_filemon(pbm);
1628 } else {
1629 pbm->mon_fd = -1;
1630 pbm->filemon = NULL;
1631 }
1632 #endif
1633 if (pipe(childPipe) < 0)
1634 Punt("Cannot create pipe: %s", strerror(errno));
1635 /* Set close-on-exec flag for both */
1636 (void)fcntl(childPipe[0], F_SETFD, FD_CLOEXEC);
1637 (void)fcntl(childPipe[1], F_SETFD, FD_CLOEXEC);
1638 }
1639
1640 void
1641 meta_compat_child(void)
1642 {
1643 meta_job_child(NULL);
1644 if (dup2(childPipe[1], 1) < 0 || dup2(1, 2) < 0)
1645 execDie("dup2", "pipe");
1646 }
1647
1648 void
1649 meta_compat_parent(pid_t child)
1650 {
1651 int outfd, metafd, maxfd, nfds;
1652 char buf[BUFSIZ+1];
1653 fd_set readfds;
1654
1655 meta_job_parent(NULL, child);
1656 close(childPipe[1]); /* child side */
1657 outfd = childPipe[0];
1658 #ifdef USE_FILEMON
1659 metafd = Mybm.filemon != NULL ? filemon_readfd(Mybm.filemon) : -1;
1660 #else
1661 metafd = -1;
1662 #endif
1663 maxfd = -1;
1664 if (outfd > maxfd)
1665 maxfd = outfd;
1666 if (metafd > maxfd)
1667 maxfd = metafd;
1668
1669 while (outfd != -1 || metafd != -1) {
1670 FD_ZERO(&readfds);
1671 if (outfd != -1) {
1672 FD_SET(outfd, &readfds);
1673 }
1674 if (metafd != -1) {
1675 FD_SET(metafd, &readfds);
1676 }
1677 nfds = select(maxfd + 1, &readfds, NULL, NULL, NULL);
1678 if (nfds == -1) {
1679 if (errno == EINTR)
1680 continue;
1681 err(1, "select");
1682 }
1683
1684 if (outfd != -1 && FD_ISSET(outfd, &readfds) != 0) do {
1685 /* XXX this is not line-buffered */
1686 ssize_t nread = read(outfd, buf, sizeof buf - 1);
1687 if (nread == -1)
1688 err(1, "read");
1689 if (nread == 0) {
1690 close(outfd);
1691 outfd = -1;
1692 break;
1693 }
1694 fwrite(buf, 1, (size_t)nread, stdout);
1695 fflush(stdout);
1696 buf[nread] = '\0';
1697 meta_job_output(NULL, buf, "");
1698 } while (/*CONSTCOND*/FALSE);
1699 if (metafd != -1 && FD_ISSET(metafd, &readfds) != 0) {
1700 if (meta_job_event(NULL) <= 0)
1701 metafd = -1;
1702 }
1703 }
1704 }
1705
1706 #endif /* USE_META */
1707