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