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