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