meta.c revision 1.123 1 /* $NetBSD: meta.c,v 1.123 2020/10/18 07:46:04 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 n;
165 int error;
166
167 /* Check if we're not writing to a meta data file.*/
168 if (mfp == NULL) {
169 if (fd >= 0)
170 close(fd); /* not interested */
171 return 0;
172 }
173 /* rewind */
174 if (lseek(fd, (off_t)0, SEEK_SET) < 0) {
175 error = errno;
176 warn("Could not rewind filemon");
177 fprintf(mfp, "\n");
178 } else {
179 error = 0;
180 fprintf(mfp, "\n-- filemon acquired metadata --\n");
181
182 while ((n = read(fd, buf, sizeof(buf))) > 0) {
183 if ((int)fwrite(buf, 1, 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) {
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 - (cp - buf));
230 } else {
231 return; /* can't happen? */
232 }
233 }
234 } while (cp);
235 }
236
237 static char *
238 meta_name(struct GNode *gn, 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, '/'))) {
258 if (cached_realpath(tname, buf)) {
259 if ((rp = strrchr(buf, '/'))) {
260 rp++;
261 cp++;
262 if (strcmp(cp, rp) != 0)
263 strlcpy(rp, cp, sizeof(buf) - (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 int
316 is_submake(void *cmdp, void *gnp)
317 {
318 static const char *p_make = NULL;
319 static int p_len;
320 char *cmd = cmdp;
321 GNode *gn = gnp;
322 char *mp = NULL;
323 char *cp;
324 char *cp2;
325 int rc = 0; /* keep looking */
326
327 if (!p_make) {
328 p_make = Var_Value(".MAKE", gn, &cp);
329 p_len = strlen(p_make);
330 }
331 cp = strchr(cmd, '$');
332 if ((cp)) {
333 (void)Var_Subst(cmd, gn, VARE_WANTRES, &mp);
334 /* TODO: handle errors */
335 cmd = mp;
336 }
337 cp2 = strstr(cmd, p_make);
338 if ((cp2)) {
339 switch (cp2[p_len]) {
340 case '\0':
341 case ' ':
342 case '\t':
343 case '\n':
344 rc = 1;
345 break;
346 }
347 if (cp2 > cmd && rc > 0) {
348 switch (cp2[-1]) {
349 case ' ':
350 case '\t':
351 case '\n':
352 break;
353 default:
354 rc = 0; /* no match */
355 break;
356 }
357 }
358 }
359 free(mp);
360 return rc;
361 }
362
363 typedef struct meta_file_s {
364 FILE *fp;
365 GNode *gn;
366 } meta_file_t;
367
368 static void
369 printCMD(void *cmdp, void *mfpp)
370 {
371 meta_file_t *mfp = mfpp;
372 char *cmd = cmdp;
373 char *cmd_freeIt = NULL;
374
375 if (strchr(cmd, '$')) {
376 (void)Var_Subst(cmd, mfp->gn, VARE_WANTRES, &cmd_freeIt);
377 /* TODO: handle errors */
378 cmd = cmd_freeIt;
379 }
380 fprintf(mfp->fp, "CMD %s\n", cmd);
381 free(cmd_freeIt);
382 }
383
384 /*
385 * Certain node types never get a .meta file
386 */
387 #define SKIP_META_TYPE(_type) do { \
388 if ((gn->type & __CONCAT(OP_, _type))) { \
389 if (verbose) { \
390 debug_printf("Skipping meta for %s: .%s\n", \
391 gn->name, __STRING(_type)); \
392 } \
393 return FALSE; \
394 } \
395 } while (0)
396
397
398 /*
399 * Do we need/want a .meta file ?
400 */
401 static Boolean
402 meta_needed(GNode *gn, const char *dname, const char *tname,
403 char *objdir, int verbose)
404 {
405 struct make_stat mst;
406
407 if (verbose)
408 verbose = DEBUG(META);
409
410 /* This may be a phony node which we don't want meta data for... */
411 /* Skip .meta for .BEGIN, .END, .ERROR etc as well. */
412 /* Or it may be explicitly flagged as .NOMETA */
413 SKIP_META_TYPE(NOMETA);
414 /* Unless it is explicitly flagged as .META */
415 if (!(gn->type & OP_META)) {
416 SKIP_META_TYPE(PHONY);
417 SKIP_META_TYPE(SPECIAL);
418 SKIP_META_TYPE(MAKE);
419 }
420
421 /* Check if there are no commands to execute. */
422 if (Lst_IsEmpty(gn->commands)) {
423 if (verbose)
424 debug_printf("Skipping meta for %s: no commands\n", gn->name);
425 return FALSE;
426 }
427 if ((gn->type & (OP_META|OP_SUBMAKE)) == OP_SUBMAKE) {
428 /* OP_SUBMAKE is a bit too aggressive */
429 if (Lst_ForEachUntil(gn->commands, is_submake, gn)) {
430 DEBUG1(META, "Skipping meta for %s: .SUBMAKE\n", gn->name);
431 return FALSE;
432 }
433 }
434
435 /* The object directory may not exist. Check it.. */
436 if (cached_stat(dname, &mst) != 0) {
437 if (verbose)
438 debug_printf("Skipping meta for %s: no .OBJDIR\n", gn->name);
439 return FALSE;
440 }
441
442 /* make sure these are canonical */
443 if (cached_realpath(dname, objdir))
444 dname = objdir;
445
446 /* If we aren't in the object directory, don't create a meta file. */
447 if (!metaCurdirOk && strcmp(curdir, dname) == 0) {
448 if (verbose)
449 debug_printf("Skipping meta for %s: .OBJDIR == .CURDIR\n",
450 gn->name);
451 return FALSE;
452 }
453 return TRUE;
454 }
455
456
457 static FILE *
458 meta_create(BuildMon *pbm, GNode *gn)
459 {
460 meta_file_t mf;
461 char buf[MAXPATHLEN];
462 char objdir[MAXPATHLEN];
463 char **ptr;
464 const char *dname;
465 const char *tname;
466 char *fname;
467 const char *cp;
468 char *p[5]; /* >= possible uses */
469 int i;
470
471 mf.fp = NULL;
472 i = 0;
473
474 dname = Var_Value(".OBJDIR", gn, &p[i++]);
475 tname = Var_Value(TARGET, gn, &p[i++]);
476
477 /* if this succeeds objdir is realpath of dname */
478 if (!meta_needed(gn, dname, tname, objdir, TRUE))
479 goto out;
480 dname = objdir;
481
482 if (metaVerbose) {
483 char *mp;
484
485 /* Describe the target we are building */
486 (void)Var_Subst("${" MAKE_META_PREFIX "}", gn, VARE_WANTRES, &mp);
487 /* TODO: handle errors */
488 if (*mp)
489 fprintf(stdout, "%s\n", mp);
490 free(mp);
491 }
492 /* Get the basename of the target */
493 if ((cp = strrchr(tname, '/')) == NULL) {
494 cp = tname;
495 } else {
496 cp++;
497 }
498
499 fflush(stdout);
500
501 if (!writeMeta)
502 /* Don't create meta data. */
503 goto out;
504
505 fname = meta_name(gn, pbm->meta_fname, sizeof(pbm->meta_fname),
506 dname, tname, objdir);
507
508 #ifdef DEBUG_META_MODE
509 DEBUG1(META, "meta_create: %s\n", fname);
510 #endif
511
512 if ((mf.fp = fopen(fname, "w")) == NULL)
513 err(1, "Could not open meta file '%s'", fname);
514
515 fprintf(mf.fp, "# Meta data file %s\n", fname);
516
517 mf.gn = gn;
518
519 Lst_ForEach(gn->commands, printCMD, &mf);
520
521 fprintf(mf.fp, "CWD %s\n", getcwd(buf, sizeof(buf)));
522 fprintf(mf.fp, "TARGET %s\n", tname);
523 cp = Var_Value(".OODATE", gn, &p[i++]);
524 if (cp && *cp) {
525 fprintf(mf.fp, "OODATE %s\n", cp);
526 }
527 if (metaEnv) {
528 for (ptr = environ; *ptr != NULL; ptr++)
529 fprintf(mf.fp, "ENV %s\n", *ptr);
530 }
531
532 fprintf(mf.fp, "-- command output --\n");
533 fflush(mf.fp);
534
535 Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL);
536 Var_Append(".MAKE.META.CREATED", fname, VAR_GLOBAL);
537
538 gn->type |= OP_META; /* in case anyone wants to know */
539 if (metaSilent) {
540 gn->type |= OP_SILENT;
541 }
542 out:
543 for (i--; i >= 0; i--) {
544 bmake_free(p[i]);
545 }
546
547 return mf.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 Var_Set(".MAKE.PATH_FILEMON", filemon_path(), VAR_GLOBAL);
573 #endif
574 }
575
576
577 #define get_mode_bf(bf, token) \
578 if ((cp = strstr(make_mode, token))) \
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 int once = 0;
588 char *cp;
589
590 useMeta = TRUE;
591 useFilemon = TRUE;
592 writeMeta = TRUE;
593
594 if (make_mode) {
595 if (strstr(make_mode, "env"))
596 metaEnv = TRUE;
597 if (strstr(make_mode, "verb"))
598 metaVerbose = TRUE;
599 if (strstr(make_mode, "read"))
600 writeMeta = FALSE;
601 if (strstr(make_mode, "nofilemon"))
602 useFilemon = FALSE;
603 if (strstr(make_mode, "ignore-cmd"))
604 metaIgnoreCMDs = TRUE;
605 if (useFilemon)
606 get_mode_bf(filemonMissing, "missing-filemon=");
607 get_mode_bf(metaCurdirOk, "curdirok=");
608 get_mode_bf(metaMissing, "missing-meta=");
609 get_mode_bf(metaSilent, "silent=");
610 }
611 if (metaVerbose && !Var_Exists(MAKE_META_PREFIX, VAR_GLOBAL)) {
612 /*
613 * The default value for MAKE_META_PREFIX
614 * prints the absolute path of the target.
615 * This works be cause :H will generate '.' if there is no /
616 * and :tA will resolve that to cwd.
617 */
618 Var_Set(MAKE_META_PREFIX, "Building ${.TARGET:H:tA}/${.TARGET:T}", VAR_GLOBAL);
619 }
620 if (once)
621 return;
622 once = 1;
623 memset(&Mybm, 0, sizeof(Mybm));
624 /*
625 * We consider ourselves master of all within ${.MAKE.META.BAILIWICK}
626 */
627 metaBailiwick = Lst_Init();
628 (void)Var_Subst("${.MAKE.META.BAILIWICK:O:u:tA}",
629 VAR_GLOBAL, VARE_WANTRES, &metaBailiwickStr);
630 /* TODO: handle errors */
631 str2Lst_Append(metaBailiwick, metaBailiwickStr, NULL);
632 /*
633 * We ignore any paths that start with ${.MAKE.META.IGNORE_PATHS}
634 */
635 metaIgnorePaths = Lst_Init();
636 Var_Append(MAKE_META_IGNORE_PATHS,
637 "/dev /etc /proc /tmp /var/run /var/tmp ${TMPDIR}", VAR_GLOBAL);
638 (void)Var_Subst("${" MAKE_META_IGNORE_PATHS ":O:u:tA}",
639 VAR_GLOBAL, VARE_WANTRES, &metaIgnorePathsStr);
640 /* TODO: handle errors */
641 str2Lst_Append(metaIgnorePaths, metaIgnorePathsStr, NULL);
642
643 /*
644 * We ignore any paths that match ${.MAKE.META.IGNORE_PATTERNS}
645 */
646 cp = NULL;
647 if (Var_Value(MAKE_META_IGNORE_PATTERNS, VAR_GLOBAL, &cp)) {
648 metaIgnorePatterns = TRUE;
649 bmake_free(cp);
650 }
651 cp = NULL;
652 if (Var_Value(MAKE_META_IGNORE_FILTER, VAR_GLOBAL, &cp)) {
653 metaIgnoreFilter = TRUE;
654 bmake_free(cp);
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) {
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) {
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) {
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) {
763 return filemon_process(pbm->filemon);
764 }
765 #endif
766 return 0;
767 }
768
769 void
770 meta_job_error(Job *job, GNode *gn, int flags, int status)
771 {
772 char cwd[MAXPATHLEN];
773 BuildMon *pbm;
774
775 if (job != NULL) {
776 pbm = &job->bm;
777 if (!gn)
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,
785 (flags & JOB_IGNERR) ?
786 "(ignored)" : "");
787 }
788 if (gn) {
789 Var_Set(".ERROR_TARGET", gn->path ? gn->path : gn->name, VAR_GLOBAL);
790 }
791 getcwd(cwd, sizeof(cwd));
792 Var_Set(".ERROR_CWD", cwd, VAR_GLOBAL);
793 if (pbm->meta_fname[0]) {
794 Var_Set(".ERROR_META_FILE", pbm->meta_fname, VAR_GLOBAL);
795 }
796 meta_job_finish(job);
797 }
798
799 void
800 meta_job_output(Job *job, char *cp, const char *nl)
801 {
802 BuildMon *pbm;
803
804 if (job != NULL) {
805 pbm = &job->bm;
806 } else {
807 pbm = &Mybm;
808 }
809 if (pbm->mfp != NULL) {
810 if (metaVerbose) {
811 static char *meta_prefix = NULL;
812 static int meta_prefix_len;
813
814 if (!meta_prefix) {
815 char *cp2;
816
817 (void)Var_Subst("${" MAKE_META_PREFIX "}",
818 VAR_GLOBAL, VARE_WANTRES, &meta_prefix);
819 /* TODO: handle errors */
820 if ((cp2 = strchr(meta_prefix, '$')))
821 meta_prefix_len = cp2 - meta_prefix;
822 else
823 meta_prefix_len = strlen(meta_prefix);
824 }
825 if (strncmp(cp, meta_prefix, meta_prefix_len) == 0) {
826 cp = strchr(cp+1, '\n');
827 if (!cp++)
828 return;
829 }
830 }
831 fprintf(pbm->mfp, "%s%s", cp, nl);
832 }
833 }
834
835 int
836 meta_cmd_finish(void *pbmp)
837 {
838 int error = 0;
839 BuildMon *pbm = pbmp;
840 #ifdef USE_FILEMON
841 int x;
842 #endif
843
844 if (!pbm)
845 pbm = &Mybm;
846
847 #ifdef USE_FILEMON
848 if (pbm->filemon) {
849 while (filemon_process(pbm->filemon) > 0)
850 continue;
851 if (filemon_close(pbm->filemon) == -1)
852 error = errno;
853 x = filemon_read(pbm->mfp, pbm->mon_fd);
854 if (error == 0 && x != 0)
855 error = x;
856 pbm->mon_fd = -1;
857 pbm->filemon = NULL;
858 } else
859 #endif
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 if (metaBailiwick != NULL)
891 Lst_Free(metaBailiwick);
892 free(metaBailiwickStr);
893 if (metaIgnorePaths != NULL)
894 Lst_Free(metaIgnorePaths);
895 free(metaIgnorePathsStr);
896 }
897
898 /*
899 * Fetch a full line from fp - growing bufp if needed
900 * Return length in bufp.
901 */
902 static int
903 fgetLine(char **bufp, size_t *szp, int o, FILE *fp)
904 {
905 char *buf = *bufp;
906 size_t bufsz = *szp;
907 struct stat fs;
908 int x;
909
910 if (fgets(&buf[o], bufsz - o, fp) != NULL) {
911 check_newline:
912 x = o + strlen(&buf[o]);
913 if (buf[x - 1] == '\n')
914 return x;
915 /*
916 * We need to grow the buffer.
917 * The meta file can give us a clue.
918 */
919 if (fstat(fileno(fp), &fs) == 0) {
920 size_t newsz;
921 char *p;
922
923 newsz = ROUNDUP((fs.st_size / 2), BUFSIZ);
924 if (newsz <= bufsz)
925 newsz = ROUNDUP(fs.st_size, BUFSIZ);
926 if (newsz <= bufsz)
927 return x; /* truncated */
928 DEBUG2(META, "growing buffer %zu -> %zu\n", bufsz, newsz);
929 p = bmake_realloc(buf, newsz);
930 if (p) {
931 *bufp = buf = p;
932 *szp = bufsz = newsz;
933 /* fetch the rest */
934 if (!fgets(&buf[x], bufsz - x, fp))
935 return x; /* truncated! */
936 goto check_newline;
937 }
938 }
939 }
940 return 0;
941 }
942
943 /* Lst_ForEachUntil wants 1 to stop search */
944 static int
945 prefix_match(void *p, void *q)
946 {
947 const char *prefix = p;
948 const char *path = q;
949 size_t n = strlen(prefix);
950
951 return strncmp(path, prefix, n) == 0;
952 }
953
954 /* See if the path equals prefix or starts with "prefix/". */
955 static Boolean
956 path_match(const void *p, const void *q)
957 {
958 const char *path = p;
959 const char *prefix = q;
960 size_t n = strlen(prefix);
961
962 if (strncmp(path, prefix, n) != 0)
963 return FALSE;
964 return path[n] == '\0' || path[n] == '/';
965 }
966
967 static Boolean
968 string_match(const void *p, const void *q)
969 {
970 return strcmp(p, q) == 0;
971 }
972
973
974 static int
975 meta_ignore(GNode *gn, const char *p)
976 {
977 char fname[MAXPATHLEN];
978
979 if (p == NULL)
980 return TRUE;
981
982 if (*p == '/') {
983 cached_realpath(p, fname); /* clean it up */
984 if (Lst_ForEachUntil(metaIgnorePaths, prefix_match, fname)) {
985 #ifdef DEBUG_META_MODE
986 DEBUG1(META, "meta_oodate: ignoring path: %s\n", p);
987 #endif
988 return TRUE;
989 }
990 }
991
992 if (metaIgnorePatterns) {
993 const char *expr;
994 char *pm;
995
996 Var_Set(".p.", p, gn);
997 expr = "${" MAKE_META_IGNORE_PATTERNS ":@m@${.p.:M$m}@}";
998 (void)Var_Subst(expr, gn, VARE_WANTRES, &pm);
999 /* TODO: handle errors */
1000 if (*pm) {
1001 #ifdef DEBUG_META_MODE
1002 DEBUG1(META, "meta_oodate: ignoring pattern: %s\n", p);
1003 #endif
1004 free(pm);
1005 return TRUE;
1006 }
1007 free(pm);
1008 }
1009
1010 if (metaIgnoreFilter) {
1011 char *fm;
1012
1013 /* skip if filter result is empty */
1014 snprintf(fname, sizeof(fname),
1015 "${%s:L:${%s:ts:}}",
1016 p, MAKE_META_IGNORE_FILTER);
1017 (void)Var_Subst(fname, gn, VARE_WANTRES, &fm);
1018 /* TODO: handle errors */
1019 if (*fm == '\0') {
1020 #ifdef DEBUG_META_MODE
1021 DEBUG1(META, "meta_oodate: ignoring filtered: %s\n", p);
1022 #endif
1023 free(fm);
1024 return TRUE;
1025 }
1026 free(fm);
1027 }
1028 return FALSE;
1029 }
1030
1031 /*
1032 * When running with 'meta' functionality, a target can be out-of-date
1033 * if any of the references in its meta data file is more recent.
1034 * We have to track the latestdir on a per-process basis.
1035 */
1036 #define LCWD_VNAME_FMT ".meta.%d.lcwd"
1037 #define LDIR_VNAME_FMT ".meta.%d.ldir"
1038
1039 /*
1040 * It is possible that a .meta file is corrupted,
1041 * if we detect this we want to reproduce it.
1042 * Setting oodate TRUE will have that effect.
1043 */
1044 #define CHECK_VALID_META(p) if (!(p && *p)) { \
1045 warnx("%s: %d: malformed", fname, lineno); \
1046 oodate = TRUE; \
1047 continue; \
1048 }
1049
1050 #define DEQUOTE(p) if (*p == '\'') { \
1051 char *ep; \
1052 p++; \
1053 if ((ep = strchr(p, '\''))) \
1054 *ep = '\0'; \
1055 }
1056
1057 Boolean
1058 meta_oodate(GNode *gn, Boolean oodate)
1059 {
1060 static char *tmpdir = NULL;
1061 static char cwd[MAXPATHLEN];
1062 char lcwd_vname[64];
1063 char ldir_vname[64];
1064 char lcwd[MAXPATHLEN];
1065 char latestdir[MAXPATHLEN];
1066 char fname[MAXPATHLEN];
1067 char fname1[MAXPATHLEN];
1068 char fname2[MAXPATHLEN];
1069 char fname3[MAXPATHLEN];
1070 const char *dname;
1071 const char *tname;
1072 char *p;
1073 char *cp;
1074 char *link_src;
1075 char *move_target;
1076 static size_t cwdlen = 0;
1077 static size_t tmplen = 0;
1078 FILE *fp;
1079 Boolean needOODATE = FALSE;
1080 StringList *missingFiles;
1081 char *pa[4]; /* >= possible uses */
1082 int i;
1083 int have_filemon = FALSE;
1084
1085 if (oodate)
1086 return oodate; /* we're done */
1087
1088 i = 0;
1089
1090 dname = Var_Value(".OBJDIR", gn, &pa[i++]);
1091 tname = Var_Value(TARGET, gn, &pa[i++]);
1092
1093 /* if this succeeds fname3 is realpath of dname */
1094 if (!meta_needed(gn, dname, tname, fname3, FALSE))
1095 goto oodate_out;
1096 dname = fname3;
1097
1098 missingFiles = Lst_Init();
1099
1100 /*
1101 * We need to check if the target is out-of-date. This includes
1102 * checking if the expanded command has changed. This in turn
1103 * requires that all variables are set in the same way that they
1104 * would be if the target needs to be re-built.
1105 */
1106 Make_DoAllVar(gn);
1107
1108 meta_name(gn, fname, sizeof(fname), dname, tname, dname);
1109
1110 #ifdef DEBUG_META_MODE
1111 DEBUG1(META, "meta_oodate: %s\n", fname);
1112 #endif
1113
1114 if ((fp = fopen(fname, "r")) != NULL) {
1115 static char *buf = NULL;
1116 static size_t bufsz;
1117 int lineno = 0;
1118 int lastpid = 0;
1119 int pid;
1120 int x;
1121 StringListNode *cmdNode;
1122 struct make_stat mst;
1123
1124 if (!buf) {
1125 bufsz = 8 * BUFSIZ;
1126 buf = bmake_malloc(bufsz);
1127 }
1128
1129 if (!cwdlen) {
1130 if (getcwd(cwd, sizeof(cwd)) == NULL)
1131 err(1, "Could not get current working directory");
1132 cwdlen = strlen(cwd);
1133 }
1134 strlcpy(lcwd, cwd, sizeof(lcwd));
1135 strlcpy(latestdir, cwd, sizeof(latestdir));
1136
1137 if (!tmpdir) {
1138 tmpdir = getTmpdir();
1139 tmplen = strlen(tmpdir);
1140 }
1141
1142 /* we want to track all the .meta we read */
1143 Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL);
1144
1145 cmdNode = Lst_First(gn->commands);
1146 while (!oodate && (x = fgetLine(&buf, &bufsz, 0, fp)) > 0) {
1147 lineno++;
1148 if (buf[x - 1] == '\n')
1149 buf[x - 1] = '\0';
1150 else {
1151 warnx("%s: %d: line truncated at %u", fname, lineno, x);
1152 oodate = TRUE;
1153 break;
1154 }
1155 link_src = NULL;
1156 move_target = NULL;
1157 /* Find the start of the build monitor section. */
1158 if (!have_filemon) {
1159 if (strncmp(buf, "-- filemon", 10) == 0) {
1160 have_filemon = TRUE;
1161 continue;
1162 }
1163 if (strncmp(buf, "# buildmon", 10) == 0) {
1164 have_filemon = TRUE;
1165 continue;
1166 }
1167 }
1168
1169 /* Delimit the record type. */
1170 p = buf;
1171 #ifdef DEBUG_META_MODE
1172 DEBUG3(META, "%s: %d: %s\n", fname, lineno, buf);
1173 #endif
1174 strsep(&p, " ");
1175 if (have_filemon) {
1176 /*
1177 * We are in the 'filemon' output section.
1178 * Each record from filemon follows the general form:
1179 *
1180 * <key> <pid> <data>
1181 *
1182 * Where:
1183 * <key> is a single letter, denoting the syscall.
1184 * <pid> is the process that made the syscall.
1185 * <data> is the arguments (of interest).
1186 */
1187 switch(buf[0]) {
1188 case '#': /* comment */
1189 case 'V': /* version */
1190 break;
1191 default:
1192 /*
1193 * We need to track pathnames per-process.
1194 *
1195 * Each process run by make, starts off in the 'CWD'
1196 * recorded in the .meta file, if it chdirs ('C')
1197 * elsewhere we need to track that - but only for
1198 * that process. If it forks ('F'), we initialize
1199 * the child to have the same cwd as its parent.
1200 *
1201 * We also need to track the 'latestdir' of
1202 * interest. This is usually the same as cwd, but
1203 * not if a process is reading directories.
1204 *
1205 * Each time we spot a different process ('pid')
1206 * we save the current value of 'latestdir' in a
1207 * variable qualified by 'lastpid', and
1208 * re-initialize 'latestdir' to any pre-saved
1209 * value for the current 'pid' and 'CWD' if none.
1210 */
1211 CHECK_VALID_META(p);
1212 pid = atoi(p);
1213 if (pid > 0 && pid != lastpid) {
1214 const char *ldir;
1215 char *tp;
1216
1217 if (lastpid > 0) {
1218 /* We need to remember these. */
1219 Var_Set(lcwd_vname, lcwd, VAR_GLOBAL);
1220 Var_Set(ldir_vname, latestdir, VAR_GLOBAL);
1221 }
1222 snprintf(lcwd_vname, sizeof(lcwd_vname), LCWD_VNAME_FMT, pid);
1223 snprintf(ldir_vname, sizeof(ldir_vname), LDIR_VNAME_FMT, pid);
1224 lastpid = pid;
1225 ldir = Var_Value(ldir_vname, VAR_GLOBAL, &tp);
1226 if (ldir) {
1227 strlcpy(latestdir, ldir, sizeof(latestdir));
1228 bmake_free(tp);
1229 }
1230 ldir = Var_Value(lcwd_vname, VAR_GLOBAL, &tp);
1231 if (ldir) {
1232 strlcpy(lcwd, ldir, sizeof(lcwd));
1233 bmake_free(tp);
1234 }
1235 }
1236 /* Skip past the pid. */
1237 if (strsep(&p, " ") == NULL)
1238 continue;
1239 #ifdef DEBUG_META_MODE
1240 if (DEBUG(META))
1241 debug_printf("%s: %d: %d: %c: cwd=%s lcwd=%s ldir=%s\n",
1242 fname, lineno,
1243 pid, buf[0], cwd, lcwd, latestdir);
1244 #endif
1245 break;
1246 }
1247
1248 CHECK_VALID_META(p);
1249
1250 /* Process according to record type. */
1251 switch (buf[0]) {
1252 case 'X': /* eXit */
1253 Var_Delete(lcwd_vname, VAR_GLOBAL);
1254 Var_Delete(ldir_vname, VAR_GLOBAL);
1255 lastpid = 0; /* no need to save ldir_vname */
1256 break;
1257
1258 case 'F': /* [v]Fork */
1259 {
1260 char cldir[64];
1261 int child;
1262
1263 child = atoi(p);
1264 if (child > 0) {
1265 snprintf(cldir, sizeof(cldir), LCWD_VNAME_FMT, child);
1266 Var_Set(cldir, lcwd, VAR_GLOBAL);
1267 snprintf(cldir, sizeof(cldir), LDIR_VNAME_FMT, child);
1268 Var_Set(cldir, latestdir, VAR_GLOBAL);
1269 #ifdef DEBUG_META_MODE
1270 if (DEBUG(META))
1271 debug_printf(
1272 "%s: %d: %d: cwd=%s lcwd=%s ldir=%s\n",
1273 fname, lineno,
1274 child, cwd, lcwd, latestdir);
1275 #endif
1276 }
1277 }
1278 break;
1279
1280 case 'C': /* Chdir */
1281 /* Update lcwd and latest directory. */
1282 strlcpy(latestdir, p, sizeof(latestdir));
1283 strlcpy(lcwd, p, sizeof(lcwd));
1284 Var_Set(lcwd_vname, lcwd, VAR_GLOBAL);
1285 Var_Set(ldir_vname, lcwd, VAR_GLOBAL);
1286 #ifdef DEBUG_META_MODE
1287 DEBUG4(META, "%s: %d: cwd=%s ldir=%s\n",
1288 fname, lineno, cwd, lcwd);
1289 #endif
1290 break;
1291
1292 case 'M': /* renaMe */
1293 /*
1294 * For 'M'oves we want to check
1295 * the src as for 'R'ead
1296 * and the target as for 'W'rite.
1297 */
1298 cp = p; /* save this for a second */
1299 /* now get target */
1300 if (strsep(&p, " ") == NULL)
1301 continue;
1302 CHECK_VALID_META(p);
1303 move_target = p;
1304 p = cp;
1305 /* 'L' and 'M' put single quotes around the args */
1306 DEQUOTE(p);
1307 DEQUOTE(move_target);
1308 /* FALLTHROUGH */
1309 case 'D': /* unlink */
1310 if (*p == '/' && !Lst_IsEmpty(missingFiles)) {
1311 /* remove any missingFiles entries that match p */
1312 StringListNode *missingNode =
1313 Lst_Find(missingFiles, path_match, p);
1314 if (missingNode != NULL) {
1315 StringListNode *nln;
1316
1317 do {
1318 char *tp;
1319 nln = Lst_FindFrom(missingFiles,
1320 missingNode->next,
1321 path_match, p);
1322 tp = LstNode_Datum(missingNode);
1323 Lst_Remove(missingFiles, missingNode);
1324 free(tp);
1325 } while ((missingNode = nln) != NULL);
1326 }
1327 }
1328 if (buf[0] == 'M') {
1329 /* the target of the mv is a file 'W'ritten */
1330 #ifdef DEBUG_META_MODE
1331 DEBUG2(META, "meta_oodate: M %s -> %s\n",
1332 p, move_target);
1333 #endif
1334 p = move_target;
1335 goto check_write;
1336 }
1337 break;
1338 case 'L': /* Link */
1339 /*
1340 * For 'L'inks check
1341 * the src as for 'R'ead
1342 * and the target as for 'W'rite.
1343 */
1344 link_src = p;
1345 /* now get target */
1346 if (strsep(&p, " ") == NULL)
1347 continue;
1348 CHECK_VALID_META(p);
1349 /* 'L' and 'M' put single quotes around the args */
1350 DEQUOTE(p);
1351 DEQUOTE(link_src);
1352 #ifdef DEBUG_META_MODE
1353 DEBUG2(META, "meta_oodate: L %s -> %s\n", link_src, p);
1354 #endif
1355 /* FALLTHROUGH */
1356 case 'W': /* Write */
1357 check_write:
1358 /*
1359 * If a file we generated within our bailiwick
1360 * but outside of .OBJDIR is missing,
1361 * we need to do it again.
1362 */
1363 /* ignore non-absolute paths */
1364 if (*p != '/')
1365 break;
1366
1367 if (Lst_IsEmpty(metaBailiwick))
1368 break;
1369
1370 /* ignore cwd - normal dependencies handle those */
1371 if (strncmp(p, cwd, cwdlen) == 0)
1372 break;
1373
1374 if (!Lst_ForEachUntil(metaBailiwick, prefix_match, p))
1375 break;
1376
1377 /* tmpdir might be within */
1378 if (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0)
1379 break;
1380
1381 /* ignore anything containing the string "tmp" */
1382 if ((strstr("tmp", p)))
1383 break;
1384
1385 if ((link_src != NULL && cached_lstat(p, &mst) < 0) ||
1386 (link_src == NULL && cached_stat(p, &mst) < 0)) {
1387 if (!meta_ignore(gn, p)) {
1388 if (Lst_Find(missingFiles, string_match, p) == NULL)
1389 Lst_Append(missingFiles, bmake_strdup(p));
1390 }
1391 }
1392 break;
1393 check_link_src:
1394 p = link_src;
1395 link_src = NULL;
1396 #ifdef DEBUG_META_MODE
1397 DEBUG1(META, "meta_oodate: L src %s\n", p);
1398 #endif
1399 /* FALLTHROUGH */
1400 case 'R': /* Read */
1401 case 'E': /* Exec */
1402 /*
1403 * Check for runtime files that can't
1404 * be part of the dependencies because
1405 * they are _expected_ to change.
1406 */
1407 if (meta_ignore(gn, p))
1408 break;
1409
1410 /*
1411 * The rest of the record is the file name.
1412 * Check if it's not an absolute path.
1413 */
1414 {
1415 char *sdirs[4];
1416 char **sdp;
1417 int sdx = 0;
1418 int found = 0;
1419
1420 if (*p == '/') {
1421 sdirs[sdx++] = p; /* done */
1422 } else {
1423 if (strcmp(".", p) == 0)
1424 continue; /* no point */
1425
1426 /* Check vs latestdir */
1427 snprintf(fname1, sizeof(fname1), "%s/%s", latestdir, p);
1428 sdirs[sdx++] = fname1;
1429
1430 if (strcmp(latestdir, lcwd) != 0) {
1431 /* Check vs lcwd */
1432 snprintf(fname2, sizeof(fname2), "%s/%s", lcwd, p);
1433 sdirs[sdx++] = fname2;
1434 }
1435 if (strcmp(lcwd, cwd) != 0) {
1436 /* Check vs cwd */
1437 snprintf(fname3, sizeof(fname3), "%s/%s", cwd, p);
1438 sdirs[sdx++] = fname3;
1439 }
1440 }
1441 sdirs[sdx++] = NULL;
1442
1443 for (sdp = sdirs; *sdp && !found; sdp++) {
1444 #ifdef DEBUG_META_MODE
1445 DEBUG3(META, "%s: %d: looking for: %s\n",
1446 fname, lineno, *sdp);
1447 #endif
1448 if (cached_stat(*sdp, &mst) == 0) {
1449 found = 1;
1450 p = *sdp;
1451 }
1452 }
1453 if (found) {
1454 #ifdef DEBUG_META_MODE
1455 DEBUG3(META, "%s: %d: found: %s\n",
1456 fname, lineno, p);
1457 #endif
1458 if (!S_ISDIR(mst.mst_mode) &&
1459 mst.mst_mtime > gn->mtime) {
1460 DEBUG3(META, "%s: %d: file '%s' is newer than the target...\n",
1461 fname, lineno, p);
1462 oodate = TRUE;
1463 } else if (S_ISDIR(mst.mst_mode)) {
1464 /* Update the latest directory. */
1465 cached_realpath(p, latestdir);
1466 }
1467 } else if (errno == ENOENT && *p == '/' &&
1468 strncmp(p, cwd, cwdlen) != 0) {
1469 /*
1470 * A referenced file outside of CWD is missing.
1471 * We cannot catch every eventuality here...
1472 */
1473 if (Lst_Find(missingFiles, string_match, p) == NULL)
1474 Lst_Append(missingFiles, bmake_strdup(p));
1475 }
1476 }
1477 if (buf[0] == 'E') {
1478 /* previous latestdir is no longer relevant */
1479 strlcpy(latestdir, lcwd, sizeof(latestdir));
1480 }
1481 break;
1482 default:
1483 break;
1484 }
1485 if (!oodate && buf[0] == 'L' && link_src != NULL)
1486 goto check_link_src;
1487 } else if (strcmp(buf, "CMD") == 0) {
1488 /*
1489 * Compare the current command with the one in the
1490 * meta data file.
1491 */
1492 if (cmdNode == NULL) {
1493 DEBUG2(META, "%s: %d: there were more build commands in the meta data file than there are now...\n",
1494 fname, lineno);
1495 oodate = TRUE;
1496 } else {
1497 char *cmd = LstNode_Datum(cmdNode);
1498 Boolean hasOODATE = FALSE;
1499
1500 if (strstr(cmd, "$?"))
1501 hasOODATE = TRUE;
1502 else if ((cp = strstr(cmd, ".OODATE"))) {
1503 /* check for $[{(].OODATE[:)}] */
1504 if (cp > cmd + 2 && cp[-2] == '$')
1505 hasOODATE = TRUE;
1506 }
1507 if (hasOODATE) {
1508 needOODATE = TRUE;
1509 DEBUG2(META, "%s: %d: cannot compare command using .OODATE\n",
1510 fname, lineno);
1511 }
1512 (void)Var_Subst(cmd, gn, VARE_WANTRES|VARE_UNDEFERR, &cmd);
1513 /* TODO: handle errors */
1514
1515 if ((cp = strchr(cmd, '\n'))) {
1516 int n;
1517
1518 /*
1519 * This command contains newlines, we need to
1520 * fetch more from the .meta file before we
1521 * attempt a comparison.
1522 */
1523 /* first put the newline back at buf[x - 1] */
1524 buf[x - 1] = '\n';
1525 do {
1526 /* now fetch the next line */
1527 if ((n = fgetLine(&buf, &bufsz, x, fp)) <= 0)
1528 break;
1529 x = n;
1530 lineno++;
1531 if (buf[x - 1] != '\n') {
1532 warnx("%s: %d: line truncated at %u", fname, lineno, x);
1533 break;
1534 }
1535 cp = strchr(++cp, '\n');
1536 } while (cp);
1537 if (buf[x - 1] == '\n')
1538 buf[x - 1] = '\0';
1539 }
1540 if (p &&
1541 !hasOODATE &&
1542 !(gn->type & OP_NOMETA_CMP) &&
1543 strcmp(p, cmd) != 0) {
1544 DEBUG4(META, "%s: %d: a build command has changed\n%s\nvs\n%s\n",
1545 fname, lineno, p, cmd);
1546 if (!metaIgnoreCMDs)
1547 oodate = TRUE;
1548 }
1549 free(cmd);
1550 cmdNode = cmdNode->next;
1551 }
1552 } else if (strcmp(buf, "CWD") == 0) {
1553 /*
1554 * Check if there are extra commands now
1555 * that weren't in the meta data file.
1556 */
1557 if (!oodate && cmdNode != NULL) {
1558 DEBUG2(META, "%s: %d: there are extra build commands now that weren't in the meta data file\n",
1559 fname, lineno);
1560 oodate = TRUE;
1561 }
1562 CHECK_VALID_META(p);
1563 if (strcmp(p, cwd) != 0) {
1564 DEBUG4(META, "%s: %d: the current working directory has changed from '%s' to '%s'\n",
1565 fname, lineno, p, curdir);
1566 oodate = TRUE;
1567 }
1568 }
1569 }
1570
1571 fclose(fp);
1572 if (!Lst_IsEmpty(missingFiles)) {
1573 DEBUG2(META, "%s: missing files: %s...\n",
1574 fname, (char *)LstNode_Datum(Lst_First(missingFiles)));
1575 oodate = TRUE;
1576 }
1577 if (!oodate && !have_filemon && filemonMissing) {
1578 DEBUG1(META, "%s: missing filemon data\n", fname);
1579 oodate = TRUE;
1580 }
1581 } else {
1582 if (writeMeta && (metaMissing || (gn->type & OP_META))) {
1583 cp = NULL;
1584
1585 /* if target is in .CURDIR we do not need a meta file */
1586 if (gn->path && (cp = strrchr(gn->path, '/')) && cp > gn->path) {
1587 if (strncmp(curdir, gn->path, (cp - gn->path)) != 0) {
1588 cp = NULL; /* not in .CURDIR */
1589 }
1590 }
1591 if (!cp) {
1592 DEBUG1(META, "%s: required but missing\n", fname);
1593 oodate = TRUE;
1594 needOODATE = TRUE; /* assume the worst */
1595 }
1596 }
1597 }
1598
1599 Lst_Destroy(missingFiles, free);
1600
1601 if (oodate && needOODATE) {
1602 /*
1603 * Target uses .OODATE which is empty; or we wouldn't be here.
1604 * We have decided it is oodate, so .OODATE needs to be set.
1605 * All we can sanely do is set it to .ALLSRC.
1606 */
1607 Var_Delete(OODATE, gn);
1608 Var_Set(OODATE, Var_Value(ALLSRC, gn, &cp), gn);
1609 bmake_free(cp);
1610 }
1611
1612 oodate_out:
1613 for (i--; i >= 0; i--) {
1614 bmake_free(pa[i]);
1615 }
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 ? 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)) 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 (0);
1705 if (metafd != -1 && FD_ISSET(metafd, &readfds)) {
1706 if (meta_job_event(NULL) <= 0)
1707 metafd = -1;
1708 }
1709 }
1710 }
1711
1712 #endif /* USE_META */
1713