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