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