arch.c revision 1.158 1 /* $NetBSD: arch.c,v 1.158 2020/11/07 12:34:49 rillig Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 /*
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
38 *
39 * This code is derived from software contributed to Berkeley by
40 * Adam de Boor.
41 *
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement:
52 * This product includes software developed by the University of
53 * California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission.
57 *
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE.
69 */
70
71 /* Manipulate libraries, archives and their members.
72 *
73 * The first time an archive is referenced, all of its members' headers are
74 * read and cashed and the archive closed again. All cashed archives are kept
75 * on a list which is searched each time an archive member is referenced.
76 *
77 * The interface to this module is:
78 *
79 * Arch_Init Initialize this module.
80 *
81 * Arch_End Clean up this module.
82 *
83 * Arch_ParseArchive
84 * Parse an archive specification such as
85 * "archive.a(member1 member2)".
86 *
87 * Arch_Touch Alter the modification time of the archive
88 * member described by the given node to be
89 * the time when make was started.
90 *
91 * Arch_TouchLib Update the modification time of the library
92 * described by the given node. This is special
93 * because it also updates the modification time
94 * of the library's table of contents.
95 *
96 * Arch_MTime Find the modification time of a member of
97 * an archive *in the archive*. The time is also
98 * placed in the member's GNode. Returns the
99 * modification time.
100 *
101 * Arch_MemberMTime
102 * Find the modification time of a member of
103 * an archive. Called when the member doesn't
104 * already exist. Looks in the archive for the
105 * modification time. Returns the modification
106 * time.
107 *
108 * Arch_FindLib Search for a library along a path. The
109 * library name in the GNode should be in
110 * -l<name> format.
111 *
112 * Arch_LibOODate Decide if a library node is out-of-date.
113 */
114
115 #include <sys/types.h>
116 #include <sys/stat.h>
117 #include <sys/time.h>
118 #include <sys/param.h>
119
120 #include <ar.h>
121 #include <utime.h>
122
123 #include "make.h"
124 #include "dir.h"
125 #include "config.h"
126
127 /* "@(#)arch.c 8.2 (Berkeley) 1/2/94" */
128 MAKE_RCSID("$NetBSD: arch.c,v 1.158 2020/11/07 12:34:49 rillig Exp $");
129
130 #ifdef TARGET_MACHINE
131 #undef MAKE_MACHINE
132 #define MAKE_MACHINE TARGET_MACHINE
133 #endif
134 #ifdef TARGET_MACHINE_ARCH
135 #undef MAKE_MACHINE_ARCH
136 #define MAKE_MACHINE_ARCH TARGET_MACHINE_ARCH
137 #endif
138
139 typedef struct List ArchList;
140 typedef struct ListNode ArchListNode;
141
142 static ArchList *archives; /* The archives we've already examined */
143
144 typedef struct Arch {
145 char *name; /* Name of archive */
146 HashTable members; /* All the members of the archive described
147 * by <name, struct ar_hdr *> key/value pairs */
148 char *fnametab; /* Extended name table strings */
149 size_t fnamesize; /* Size of the string table */
150 } Arch;
151
152 static FILE *ArchFindMember(const char *, const char *,
153 struct ar_hdr *, const char *);
154 #if defined(__svr4__) || defined(__SVR4) || defined(__ELF__)
155 #define SVR4ARCHIVES
156 static int ArchSVR4Entry(Arch *, char *, size_t, FILE *);
157 #endif
158
159 #ifdef CLEANUP
160 static void
161 ArchFree(void *ap)
162 {
163 Arch *a = ap;
164 HashIter hi;
165
166 /* Free memory from hash entries */
167 HashIter_Init(&hi, &a->members);
168 while (HashIter_Next(&hi) != NULL)
169 free(hi.entry->value);
170
171 free(a->name);
172 free(a->fnametab);
173 HashTable_Done(&a->members);
174 free(a);
175 }
176 #endif
177
178
179 /*
180 * Parse an archive specification such as "archive.a(member1 member2.${EXT})",
181 * adding nodes for the expanded members to nodeLst. Nodes are created as
182 * necessary.
183 *
184 * Input:
185 * pp The start of the specification.
186 * nodeLst The list on which to place the nodes.
187 * ctxt The context in which to expand variables.
188 *
189 * Output:
190 * return TRUE if it was a valid specification.
191 * *pp Points to the first non-space after the archive spec.
192 * *nodeLst Nodes for the members have been added.
193 */
194 Boolean
195 Arch_ParseArchive(char **pp, GNodeList *nodeLst, GNode *ctxt)
196 {
197 char *cp; /* Pointer into line */
198 GNode *gn; /* New node */
199 char *libName; /* Library-part of specification */
200 char *libName_freeIt = NULL;
201 char *memName; /* Member-part of specification */
202 char saveChar; /* Ending delimiter of member-name */
203 Boolean subLibName; /* TRUE if libName should have/had
204 * variable substitution performed on it */
205
206 libName = *pp;
207
208 subLibName = FALSE;
209
210 for (cp = libName; *cp != '(' && *cp != '\0';) {
211 if (*cp == '$') {
212 /*
213 * Variable spec, so call the Var module to parse the puppy
214 * so we can safely advance beyond it...
215 */
216 const char *nested_p = cp;
217 void *result_freeIt;
218 const char *result;
219 Boolean isError;
220
221 /* XXX: is expanded twice: once here and once below */
222 (void)Var_Parse(&nested_p, ctxt, VARE_UNDEFERR|VARE_WANTRES,
223 &result, &result_freeIt);
224 /* TODO: handle errors */
225 isError = result == var_Error;
226 free(result_freeIt);
227 if (isError)
228 return FALSE;
229
230 subLibName = TRUE;
231 cp += nested_p - cp;
232 } else
233 cp++;
234 }
235
236 *cp++ = '\0';
237 if (subLibName) {
238 (void)Var_Subst(libName, ctxt, VARE_UNDEFERR|VARE_WANTRES, &libName);
239 /* TODO: handle errors */
240 libName_freeIt = libName;
241 }
242
243
244 for (;;) {
245 /*
246 * First skip to the start of the member's name, mark that
247 * place and skip to the end of it (either white-space or
248 * a close paren).
249 */
250 Boolean doSubst = FALSE; /* TRUE if need to substitute in memName */
251
252 pp_skip_whitespace(&cp);
253
254 memName = cp;
255 while (*cp != '\0' && *cp != ')' && !ch_isspace(*cp)) {
256 if (*cp == '$') {
257 /*
258 * Variable spec, so call the Var module to parse the puppy
259 * so we can safely advance beyond it...
260 */
261 void *freeIt;
262 const char *result;
263 Boolean isError;
264 const char *nested_p = cp;
265
266 (void)Var_Parse(&nested_p, ctxt, VARE_UNDEFERR|VARE_WANTRES,
267 &result, &freeIt);
268 /* TODO: handle errors */
269 isError = result == var_Error;
270 free(freeIt);
271
272 if (isError)
273 return FALSE;
274
275 doSubst = TRUE;
276 cp += nested_p - cp;
277 } else {
278 cp++;
279 }
280 }
281
282 /*
283 * If the specification ends without a closing parenthesis,
284 * chances are there's something wrong (like a missing backslash),
285 * so it's better to return failure than allow such things to happen
286 */
287 if (*cp == '\0') {
288 printf("No closing parenthesis in archive specification\n");
289 return FALSE;
290 }
291
292 /*
293 * If we didn't move anywhere, we must be done
294 */
295 if (cp == memName) {
296 break;
297 }
298
299 saveChar = *cp;
300 *cp = '\0';
301
302 /*
303 * XXX: This should be taken care of intelligently by
304 * SuffExpandChildren, both for the archive and the member portions.
305 */
306 /*
307 * If member contains variables, try and substitute for them.
308 * This will slow down archive specs with dynamic sources, of course,
309 * since we'll be (non-)substituting them three times, but them's
310 * the breaks -- we need to do this since SuffExpandChildren calls
311 * us, otherwise we could assume the thing would be taken care of
312 * later.
313 */
314 if (doSubst) {
315 char *buf;
316 char *sacrifice;
317 char *oldMemName = memName;
318
319 (void)Var_Subst(memName, ctxt, VARE_UNDEFERR|VARE_WANTRES,
320 &memName);
321 /* TODO: handle errors */
322
323 /*
324 * Now form an archive spec and recurse to deal with nested
325 * variables and multi-word variable values.... The results
326 * are just placed at the end of the nodeLst we're returning.
327 */
328 buf = sacrifice = str_concat4(libName, "(", memName, ")");
329
330 if (strchr(memName, '$') != NULL &&
331 strcmp(memName, oldMemName) == 0) {
332 /*
333 * Must contain dynamic sources, so we can't deal with it now.
334 * Just create an ARCHV node for the thing and let
335 * SuffExpandChildren handle it...
336 */
337 gn = Targ_GetNode(buf);
338 gn->type |= OP_ARCHV;
339 Lst_Append(nodeLst, gn);
340
341 } else if (!Arch_ParseArchive(&sacrifice, nodeLst, ctxt)) {
342 /* Error in nested call. */
343 free(buf);
344 return FALSE;
345 }
346 free(buf);
347
348 } else if (Dir_HasWildcards(memName)) {
349 StringList *members = Lst_New();
350 Dir_Expand(memName, dirSearchPath, members);
351
352 while (!Lst_IsEmpty(members)) {
353 char *member = Lst_Dequeue(members);
354 char *fullname = str_concat4(libName, "(", member, ")");
355 free(member);
356
357 gn = Targ_GetNode(fullname);
358 free(fullname);
359
360 gn->type |= OP_ARCHV;
361 Lst_Append(nodeLst, gn);
362 }
363 Lst_Free(members);
364
365 } else {
366 char *fullname = str_concat4(libName, "(", memName, ")");
367 gn = Targ_GetNode(fullname);
368 free(fullname);
369
370 /*
371 * We've found the node, but have to make sure the rest of the
372 * world knows it's an archive member, without having to
373 * constantly check for parentheses, so we type the thing with
374 * the OP_ARCHV bit before we place it on the end of the
375 * provided list.
376 */
377 gn->type |= OP_ARCHV;
378 Lst_Append(nodeLst, gn);
379 }
380 if (doSubst) {
381 free(memName);
382 }
383
384 *cp = saveChar;
385 }
386
387 free(libName_freeIt);
388
389 cp++; /* skip the ')' */
390 /* We promised that pp would be set up at the next non-space. */
391 pp_skip_whitespace(&cp);
392 *pp = cp;
393 return TRUE;
394 }
395
396 /* Locate a member of an archive, given the path of the archive and the path
397 * of the desired member.
398 *
399 * Input:
400 * archive Path to the archive
401 * member Name of member; only its basename is used.
402 * hash TRUE if archive should be hashed if not already so.
403 *
404 * Results:
405 * The ar_hdr for the member.
406 */
407 static struct ar_hdr *
408 ArchStatMember(const char *archive, const char *member, Boolean hash)
409 {
410 #define AR_MAX_NAME_LEN (sizeof arh.ar_name - 1)
411 FILE *arch; /* Stream to archive */
412 size_t size; /* Size of archive member */
413 char magic[SARMAG];
414 ArchListNode *ln;
415 Arch *ar; /* Archive descriptor */
416 struct ar_hdr arh; /* archive-member header for reading archive */
417 char memName[MAXPATHLEN + 1];
418 /* Current member name while hashing. */
419
420 /*
421 * Because of space constraints and similar things, files are archived
422 * using their basename, not the entire path.
423 */
424 const char *lastSlash = strrchr(member, '/');
425 if (lastSlash != NULL)
426 member = lastSlash + 1;
427
428 for (ln = archives->first; ln != NULL; ln = ln->next) {
429 const Arch *a = ln->datum;
430 if (strcmp(a->name, archive) == 0)
431 break;
432 }
433
434 if (ln != NULL) {
435 struct ar_hdr *hdr;
436
437 ar = ln->datum;
438 hdr = HashTable_FindValue(&ar->members, member);
439 if (hdr != NULL)
440 return hdr;
441
442 {
443 /* Try truncated name */
444 char copy[AR_MAX_NAME_LEN + 1];
445 size_t len = strlen(member);
446
447 if (len > AR_MAX_NAME_LEN) {
448 len = AR_MAX_NAME_LEN;
449 snprintf(copy, sizeof copy, "%s", member);
450 }
451 hdr = HashTable_FindValue(&ar->members, copy);
452 return hdr;
453 }
454 }
455
456 if (!hash) {
457 /*
458 * Caller doesn't want the thing hashed, just use ArchFindMember
459 * to read the header for the member out and close down the stream
460 * again. Since the archive is not to be hashed, we assume there's
461 * no need to allocate extra room for the header we're returning,
462 * so just declare it static.
463 */
464 static struct ar_hdr sarh;
465
466 arch = ArchFindMember(archive, member, &sarh, "r");
467 if (arch == NULL)
468 return NULL;
469
470 fclose(arch);
471 return &sarh;
472 }
473
474 /*
475 * We don't have this archive on the list yet, so we want to find out
476 * everything that's in it and cache it so we can get at it quickly.
477 */
478 arch = fopen(archive, "r");
479 if (arch == NULL)
480 return NULL;
481
482 /*
483 * We use the ARMAG string to make sure this is an archive we
484 * can handle...
485 */
486 if (fread(magic, SARMAG, 1, arch) != 1 ||
487 strncmp(magic, ARMAG, SARMAG) != 0) {
488 fclose(arch);
489 return NULL;
490 }
491
492 ar = bmake_malloc(sizeof *ar);
493 ar->name = bmake_strdup(archive);
494 ar->fnametab = NULL;
495 ar->fnamesize = 0;
496 HashTable_Init(&ar->members);
497 memName[AR_MAX_NAME_LEN] = '\0';
498
499 while (fread(&arh, sizeof arh, 1, arch) == 1) {
500 if (strncmp(arh.ar_fmag, ARFMAG, sizeof arh.ar_fmag) != 0) {
501 /*
502 * The header is bogus, so the archive is bad
503 * and there's no way we can recover...
504 */
505 goto badarch;
506 } else {
507 char *nameend;
508
509 /*
510 * We need to advance the stream's pointer to the start of the
511 * next header. Files are padded with newlines to an even-byte
512 * boundary, so we need to extract the size of the file from the
513 * 'size' field of the header and round it up during the seek.
514 */
515 arh.ar_size[sizeof arh.ar_size - 1] = '\0';
516 size = (size_t)strtol(arh.ar_size, NULL, 10);
517
518 memcpy(memName, arh.ar_name, sizeof arh.ar_name);
519 nameend = memName + AR_MAX_NAME_LEN;
520 while (*nameend == ' ') {
521 nameend--;
522 }
523 nameend[1] = '\0';
524
525 #ifdef SVR4ARCHIVES
526 /*
527 * svr4 names are slash terminated. Also svr4 extended AR format.
528 */
529 if (memName[0] == '/') {
530 /*
531 * svr4 magic mode; handle it
532 */
533 switch (ArchSVR4Entry(ar, memName, size, arch)) {
534 case -1: /* Invalid data */
535 goto badarch;
536 case 0: /* List of files entry */
537 continue;
538 default: /* Got the entry */
539 break;
540 }
541 } else {
542 if (nameend[0] == '/')
543 nameend[0] = '\0';
544 }
545 #endif
546
547 #ifdef AR_EFMT1
548 /*
549 * BSD 4.4 extended AR format: #1/<namelen>, with name as the
550 * first <namelen> bytes of the file
551 */
552 if (strncmp(memName, AR_EFMT1, sizeof AR_EFMT1 - 1) == 0 &&
553 ch_isdigit(memName[sizeof AR_EFMT1 - 1])) {
554
555 int elen = atoi(memName + sizeof AR_EFMT1 - 1);
556
557 if ((unsigned int)elen > MAXPATHLEN)
558 goto badarch;
559 if (fread(memName, (size_t)elen, 1, arch) != 1)
560 goto badarch;
561 memName[elen] = '\0';
562 if (fseek(arch, -elen, SEEK_CUR) != 0)
563 goto badarch;
564 if (DEBUG(ARCH) || DEBUG(MAKE)) {
565 debug_printf("ArchStat: Extended format entry for %s\n",
566 memName);
567 }
568 }
569 #endif
570
571 {
572 HashEntry *he;
573 he = HashTable_CreateEntry(&ar->members, memName, NULL);
574 HashEntry_Set(he, bmake_malloc(sizeof arh));
575 memcpy(HashEntry_Get(he), &arh, sizeof arh);
576 }
577 }
578 if (fseek(arch, ((long)size + 1) & ~1, SEEK_CUR) != 0)
579 goto badarch;
580 }
581
582 fclose(arch);
583
584 Lst_Append(archives, ar);
585
586 /*
587 * Now that the archive has been read and cached, we can look into
588 * the hash table to find the desired member's header.
589 */
590 return HashTable_FindValue(&ar->members, member);
591
592 badarch:
593 fclose(arch);
594 HashTable_Done(&ar->members);
595 free(ar->fnametab);
596 free(ar);
597 return NULL;
598 }
599
600 #ifdef SVR4ARCHIVES
601 /*-
602 *-----------------------------------------------------------------------
603 * ArchSVR4Entry --
604 * Parse an SVR4 style entry that begins with a slash.
605 * If it is "//", then load the table of filenames
606 * If it is "/<offset>", then try to substitute the long file name
607 * from offset of a table previously read.
608 * If a table is read, the file pointer is moved to the next archive
609 * member.
610 *
611 * Results:
612 * -1: Bad data in archive
613 * 0: A table was loaded from the file
614 * 1: Name was successfully substituted from table
615 * 2: Name was not successfully substituted from table
616 *-----------------------------------------------------------------------
617 */
618 static int
619 ArchSVR4Entry(Arch *ar, char *name, size_t size, FILE *arch)
620 {
621 #define ARLONGNAMES1 "//"
622 #define ARLONGNAMES2 "/ARFILENAMES"
623 size_t entry;
624 char *ptr, *eptr;
625
626 if (strncmp(name, ARLONGNAMES1, sizeof ARLONGNAMES1 - 1) == 0 ||
627 strncmp(name, ARLONGNAMES2, sizeof ARLONGNAMES2 - 1) == 0) {
628
629 if (ar->fnametab != NULL) {
630 DEBUG0(ARCH, "Attempted to redefine an SVR4 name table\n");
631 return -1;
632 }
633
634 /*
635 * This is a table of archive names, so we build one for
636 * ourselves
637 */
638 ar->fnametab = bmake_malloc(size);
639 ar->fnamesize = size;
640
641 if (fread(ar->fnametab, size, 1, arch) != 1) {
642 DEBUG0(ARCH, "Reading an SVR4 name table failed\n");
643 return -1;
644 }
645 eptr = ar->fnametab + size;
646 for (entry = 0, ptr = ar->fnametab; ptr < eptr; ptr++)
647 if (*ptr == '/') {
648 entry++;
649 *ptr = '\0';
650 }
651 DEBUG1(ARCH, "Found svr4 archive name table with %lu entries\n",
652 (unsigned long)entry);
653 return 0;
654 }
655
656 if (name[1] == ' ' || name[1] == '\0')
657 return 2;
658
659 entry = (size_t)strtol(&name[1], &eptr, 0);
660 if ((*eptr != ' ' && *eptr != '\0') || eptr == &name[1]) {
661 DEBUG1(ARCH, "Could not parse SVR4 name %s\n", name);
662 return 2;
663 }
664 if (entry >= ar->fnamesize) {
665 DEBUG2(ARCH, "SVR4 entry offset %s is greater than %lu\n",
666 name, (unsigned long)ar->fnamesize);
667 return 2;
668 }
669
670 DEBUG2(ARCH, "Replaced %s with %s\n", name, &ar->fnametab[entry]);
671
672 snprintf(name, MAXPATHLEN + 1, "%s", &ar->fnametab[entry]);
673 return 1;
674 }
675 #endif
676
677
678 static Boolean
679 ArchiveMember_HasName(const struct ar_hdr *hdr,
680 const char *name, size_t namelen)
681 {
682 const size_t ar_name_len = sizeof hdr->ar_name;
683 const char *ar_name = hdr->ar_name;
684
685 if (strncmp(ar_name, name, namelen) != 0)
686 return FALSE;
687
688 if (namelen >= ar_name_len)
689 return namelen == ar_name_len;
690
691 /* hdr->ar_name is space-padded to the right. */
692 return ar_name[namelen] == ' ';
693 }
694
695 /* Locate a member of an archive, given the path of the archive and the path
696 * of the desired member.
697 *
698 * Input:
699 * archive Path to the archive
700 * member Name of member. If it is a path, only the last
701 * component is used.
702 * out_arh Archive header to be filled in
703 * mode "r" for read-only access, "r+" for read-write access
704 *
705 * Output:
706 * return The archive file, positioned at the start of the
707 * member's struct ar_hdr, or NULL if the member doesn't
708 * exist.
709 * *out_arh The current struct ar_hdr for member.
710 */
711 static FILE *
712 ArchFindMember(const char *archive, const char *member, struct ar_hdr *out_arh,
713 const char *mode)
714 {
715 FILE *arch; /* Stream to archive */
716 int size; /* Size of archive member */
717 char magic[SARMAG];
718 size_t len, tlen;
719 const char *lastSlash;
720
721 arch = fopen(archive, mode);
722 if (arch == NULL)
723 return NULL;
724
725 /*
726 * We use the ARMAG string to make sure this is an archive we
727 * can handle...
728 */
729 if (fread(magic, SARMAG, 1, arch) != 1 ||
730 strncmp(magic, ARMAG, SARMAG) != 0) {
731 fclose(arch);
732 return NULL;
733 }
734
735 /*
736 * Because of space constraints and similar things, files are archived
737 * using their basename, not the entire path.
738 */
739 lastSlash = strrchr(member, '/');
740 if (lastSlash != NULL)
741 member = lastSlash + 1;
742
743 len = tlen = strlen(member);
744 if (len > sizeof out_arh->ar_name) {
745 tlen = sizeof out_arh->ar_name;
746 }
747
748 while (fread(out_arh, sizeof *out_arh, 1, arch) == 1) {
749
750 if (strncmp(out_arh->ar_fmag, ARFMAG, sizeof out_arh->ar_fmag) != 0) {
751 /*
752 * The header is bogus, so the archive is bad
753 * and there's no way we can recover...
754 */
755 fclose(arch);
756 return NULL;
757 }
758
759 if (ArchiveMember_HasName(out_arh, member, len)) {
760 /*
761 * To make life easier for callers that want to update the
762 * archive, we reposition the file at the start
763 * of the header we just read before we return the stream.
764 * In a more general situation, it might be better to leave
765 * the file at the actual member, rather than its header, but
766 * not here.
767 */
768 if (fseek(arch, -(long)sizeof *out_arh, SEEK_CUR) != 0) {
769 fclose(arch);
770 return NULL;
771 }
772 return arch;
773 }
774
775 #ifdef AR_EFMT1
776 /*
777 * BSD 4.4 extended AR format: #1/<namelen>, with name as the
778 * first <namelen> bytes of the file
779 */
780 if (strncmp(out_arh->ar_name, AR_EFMT1, sizeof AR_EFMT1 - 1) == 0 &&
781 ch_isdigit(out_arh->ar_name[sizeof AR_EFMT1 - 1]))
782 {
783 int elen = atoi(&out_arh->ar_name[sizeof AR_EFMT1 - 1]);
784 char ename[MAXPATHLEN + 1];
785
786 if ((unsigned int)elen > MAXPATHLEN) {
787 fclose(arch);
788 return NULL;
789 }
790 if (fread(ename, (size_t)elen, 1, arch) != 1) {
791 fclose(arch);
792 return NULL;
793 }
794 ename[elen] = '\0';
795 if (DEBUG(ARCH) || DEBUG(MAKE)) {
796 debug_printf("ArchFind: Extended format entry for %s\n", ename);
797 }
798 if (strncmp(ename, member, len) == 0) {
799 /* Found as extended name */
800 if (fseek(arch, -(long)sizeof(struct ar_hdr) - elen,
801 SEEK_CUR) != 0) {
802 fclose(arch);
803 return NULL;
804 }
805 return arch;
806 }
807 if (fseek(arch, -elen, SEEK_CUR) != 0) {
808 fclose(arch);
809 return NULL;
810 }
811 }
812 #endif
813
814 /*
815 * This isn't the member we're after, so we need to advance the
816 * stream's pointer to the start of the next header. Files are
817 * padded with newlines to an even-byte boundary, so we need to
818 * extract the size of the file from the 'size' field of the
819 * header and round it up during the seek.
820 */
821 out_arh->ar_size[sizeof out_arh->ar_size - 1] = '\0';
822 size = (int)strtol(out_arh->ar_size, NULL, 10);
823 if (fseek(arch, (size + 1) & ~1, SEEK_CUR) != 0) {
824 fclose(arch);
825 return NULL;
826 }
827 }
828
829 fclose(arch);
830 return NULL;
831 }
832
833 /* Touch a member of an archive, on disk.
834 * The GNode's modification time is left as-is.
835 *
836 * The st_mtime of the entire archive is also changed.
837 * For a library, it may be required to run ranlib after this.
838 *
839 * Input:
840 * gn Node of member to touch
841 *
842 * Results:
843 * The 'time' field of the member's header is updated.
844 */
845 void
846 Arch_Touch(GNode *gn)
847 {
848 FILE *arch;
849 struct ar_hdr arh;
850
851 arch = ArchFindMember(GNode_VarArchive(gn), GNode_VarMember(gn),
852 &arh, "r+");
853
854 snprintf(arh.ar_date, sizeof arh.ar_date, "%-12ld", (long)now);
855
856 if (arch != NULL) {
857 (void)fwrite(&arh, sizeof arh, 1, arch);
858 fclose(arch);
859 }
860 }
861
862 /* Given a node which represents a library, touch the thing, making sure that
863 * the table of contents also is touched.
864 *
865 * Both the modification time of the library and of the RANLIBMAG member are
866 * set to 'now'. */
867 void
868 Arch_TouchLib(GNode *gn)
869 {
870 #ifdef RANLIBMAG
871 FILE *arch;
872 struct ar_hdr arh; /* Header describing table of contents */
873 struct utimbuf times;
874
875 arch = ArchFindMember(gn->path, RANLIBMAG, &arh, "r+");
876 snprintf(arh.ar_date, sizeof arh.ar_date, "%-12ld", (long) now);
877
878 if (arch != NULL) {
879 (void)fwrite(&arh, sizeof arh, 1, arch);
880 fclose(arch);
881
882 times.actime = times.modtime = now;
883 utime(gn->path, ×);
884 }
885 #else
886 (void)gn;
887 #endif
888 }
889
890 /* Update the mtime of the GNode with the mtime from the archive member on
891 * disk (or in the cache). */
892 time_t
893 Arch_MTime(GNode *gn)
894 {
895 struct ar_hdr *arh;
896 time_t modTime;
897
898 arh = ArchStatMember(GNode_VarArchive(gn), GNode_VarMember(gn), TRUE);
899 if (arh != NULL) {
900 modTime = (time_t)strtol(arh->ar_date, NULL, 10);
901 } else {
902 modTime = 0;
903 }
904
905 gn->mtime = modTime;
906 return modTime;
907 }
908
909 /* Given a non-existent archive member's node, get its modification time from
910 * its archived form, if it exists. gn->mtime is filled in as well. */
911 time_t
912 Arch_MemberMTime(GNode *gn)
913 {
914 GNodeListNode *ln;
915
916 for (ln = gn->parents->first; ln != NULL; ln = ln->next) {
917 GNode *pgn = ln->datum;
918
919 if (pgn->type & OP_ARCHV) {
920 /*
921 * If the parent is an archive specification and is being made
922 * and its member's name matches the name of the node we were
923 * given, record the modification time of the parent in the
924 * child. We keep searching its parents in case some other
925 * parent requires this child to exist...
926 */
927 const char *nameStart = strchr(pgn->name, '(') + 1;
928 const char *nameEnd = strchr(nameStart, ')');
929 size_t nameLen = (size_t)(nameEnd - nameStart);
930
931 if ((pgn->flags & REMAKE) &&
932 strncmp(nameStart, gn->name, nameLen) == 0) {
933 gn->mtime = Arch_MTime(pgn);
934 }
935 } else if (pgn->flags & REMAKE) {
936 /*
937 * Something which isn't a library depends on the existence of
938 * this target, so it needs to exist.
939 */
940 gn->mtime = 0;
941 break;
942 }
943 }
944
945 return gn->mtime;
946 }
947
948 /* Search for a library along the given search path.
949 *
950 * The node's 'path' field is set to the found path (including the
951 * actual file name, not -l...). If the system can handle the -L
952 * flag when linking (or we cannot find the library), we assume that
953 * the user has placed the .LIBS variable in the final linking
954 * command (or the linker will know where to find it) and set the
955 * TARGET variable for this node to be the node's name. Otherwise,
956 * we set the TARGET variable to be the full path of the library,
957 * as returned by Dir_FindFile.
958 *
959 * Input:
960 * gn Node of library to find
961 */
962 void
963 Arch_FindLib(GNode *gn, SearchPath *path)
964 {
965 char *libName = str_concat3("lib", gn->name + 2, ".a");
966 gn->path = Dir_FindFile(libName, path);
967 free(libName);
968
969 #ifdef LIBRARIES
970 Var_Set(TARGET, gn->name, gn);
971 #else
972 Var_Set(TARGET, gn->path == NULL ? gn->name : gn->path, gn);
973 #endif
974 }
975
976 /* Decide if a node with the OP_LIB attribute is out-of-date. Called from
977 * Make_OODate to make its life easier.
978 * The library is cached if it hasn't been already.
979 *
980 * There are several ways for a library to be out-of-date that are
981 * not available to ordinary files. In addition, there are ways
982 * that are open to regular files that are not available to
983 * libraries. A library that is only used as a source is never
984 * considered out-of-date by itself. This does not preclude the
985 * library's modification time from making its parent be out-of-date.
986 * A library will be considered out-of-date for any of these reasons,
987 * given that it is a target on a dependency line somewhere:
988 *
989 * Its modification time is less than that of one of its sources
990 * (gn->mtime < gn->youngestChild->mtime).
991 *
992 * Its modification time is greater than the time at which the make
993 * began (i.e. it's been modified in the course of the make, probably
994 * by archiving).
995 *
996 * The modification time of one of its sources is greater than the one
997 * of its RANLIBMAG member (i.e. its table of contents is out-of-date).
998 * We don't compare of the archive time vs. TOC time because they can be
999 * too close. In my opinion we should not bother with the TOC at all
1000 * since this is used by 'ar' rules that affect the data contents of the
1001 * archive, not by ranlib rules, which affect the TOC.
1002 *
1003 * Input:
1004 * gn The library's graph node
1005 *
1006 * Results:
1007 * TRUE if the library is out-of-date. FALSE otherwise.
1008 */
1009 Boolean
1010 Arch_LibOODate(GNode *gn)
1011 {
1012 Boolean oodate;
1013
1014 if (gn->type & OP_PHONY) {
1015 oodate = TRUE;
1016 } else if (!GNode_IsTarget(gn) && Lst_IsEmpty(gn->children)) {
1017 oodate = FALSE;
1018 } else if ((!Lst_IsEmpty(gn->children) && gn->youngestChild == NULL) ||
1019 (gn->mtime > now) ||
1020 (gn->youngestChild != NULL &&
1021 gn->mtime < gn->youngestChild->mtime)) {
1022 oodate = TRUE;
1023 } else {
1024 #ifdef RANLIBMAG
1025 struct ar_hdr *arh; /* Header for __.SYMDEF */
1026 int modTimeTOC; /* The table-of-contents's mod time */
1027
1028 arh = ArchStatMember(gn->path, RANLIBMAG, FALSE);
1029
1030 if (arh != NULL) {
1031 modTimeTOC = (int)strtol(arh->ar_date, NULL, 10);
1032
1033 if (DEBUG(ARCH) || DEBUG(MAKE)) {
1034 debug_printf("%s modified %s...", RANLIBMAG, Targ_FmtTime(modTimeTOC));
1035 }
1036 oodate = (gn->youngestChild == NULL || gn->youngestChild->mtime > modTimeTOC);
1037 } else {
1038 /*
1039 * A library w/o a table of contents is out-of-date
1040 */
1041 if (DEBUG(ARCH) || DEBUG(MAKE)) {
1042 debug_printf("No t.o.c....");
1043 }
1044 oodate = TRUE;
1045 }
1046 #else
1047 oodate = FALSE;
1048 #endif
1049 }
1050 return oodate;
1051 }
1052
1053 /* Initialize the archives module. */
1054 void
1055 Arch_Init(void)
1056 {
1057 archives = Lst_New();
1058 }
1059
1060 /* Clean up the archives module. */
1061 void
1062 Arch_End(void)
1063 {
1064 #ifdef CLEANUP
1065 Lst_Destroy(archives, ArchFree);
1066 #endif
1067 }
1068
1069 Boolean
1070 Arch_IsLib(GNode *gn)
1071 {
1072 static const char armag[] = "!<arch>\n";
1073 char buf[sizeof armag - 1];
1074 int fd;
1075
1076 if ((fd = open(gn->path, O_RDONLY)) == -1)
1077 return FALSE;
1078
1079 if (read(fd, buf, sizeof buf) != sizeof buf) {
1080 (void)close(fd);
1081 return FALSE;
1082 }
1083
1084 (void)close(fd);
1085
1086 return memcmp(buf, armag, sizeof buf) == 0;
1087 }
1088