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