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