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