arch.c revision 1.173 1 /* $NetBSD: arch.c,v 1.173 2020/11/08 09:06:22 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_UpdateMemberMTime
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.173 2020/11/08 09:06:22 rillig Exp $");
129
130 typedef struct List ArchList;
131 typedef struct ListNode ArchListNode;
132
133 static ArchList *archives; /* The archives we've already examined */
134
135 typedef struct Arch {
136 char *name; /* Name of archive */
137 HashTable members; /* All the members of the archive described
138 * by <name, struct ar_hdr *> key/value pairs */
139 char *fnametab; /* Extended name table strings */
140 size_t fnamesize; /* Size of the string table */
141 } Arch;
142
143 static FILE *ArchFindMember(const char *, const char *,
144 struct ar_hdr *, const char *);
145 #if defined(__svr4__) || defined(__SVR4) || defined(__ELF__)
146 #define SVR4ARCHIVES
147 static int ArchSVR4Entry(Arch *, char *, size_t, FILE *);
148 #endif
149
150 #ifdef CLEANUP
151 static void
152 ArchFree(void *ap)
153 {
154 Arch *a = ap;
155 HashIter hi;
156
157 /* Free memory from hash entries */
158 HashIter_Init(&hi, &a->members);
159 while (HashIter_Next(&hi) != NULL)
160 free(hi.entry->value);
161
162 free(a->name);
163 free(a->fnametab);
164 HashTable_Done(&a->members);
165 free(a);
166 }
167 #endif
168
169
170 /*
171 * Parse an archive specification such as "archive.a(member1 member2.${EXT})",
172 * adding nodes for the expanded members to nodeLst. Nodes are created as
173 * necessary.
174 *
175 * Input:
176 * pp The start of the specification.
177 * nodeLst The list on which to place the nodes.
178 * ctxt The context in which to expand variables.
179 *
180 * Output:
181 * return TRUE if it was a valid specification.
182 * *pp Points to the first non-space after the archive spec.
183 * *nodeLst Nodes for the members have been added.
184 */
185 Boolean
186 Arch_ParseArchive(char **pp, GNodeList *nodeLst, GNode *ctxt)
187 {
188 char *cp; /* Pointer into line */
189 GNode *gn; /* New node */
190 char *libName; /* Library-part of specification */
191 char *libName_freeIt = NULL;
192 char *memName; /* Member-part of specification */
193 char saveChar; /* Ending delimiter of member-name */
194 Boolean expandLibName; /* Whether the parsed libName contains
195 * variable expressions that need to be
196 * expanded */
197
198 libName = *pp;
199 expandLibName = FALSE;
200
201 for (cp = libName; *cp != '(' && *cp != '\0';) {
202 if (*cp == '$') {
203 /*
204 * Variable spec, so call the Var module to parse the puppy
205 * so we can safely advance beyond it...
206 */
207 const char *nested_p = cp;
208 void *result_freeIt;
209 const char *result;
210 Boolean isError;
211
212 /* XXX: is expanded twice: once here and once below */
213 (void)Var_Parse(&nested_p, ctxt, VARE_UNDEFERR|VARE_WANTRES,
214 &result, &result_freeIt);
215 /* TODO: handle errors */
216 isError = result == var_Error;
217 free(result_freeIt);
218 if (isError)
219 return FALSE;
220
221 expandLibName = TRUE;
222 cp += nested_p - cp;
223 } else
224 cp++;
225 }
226
227 *cp++ = '\0';
228 if (expandLibName) {
229 (void)Var_Subst(libName, ctxt, VARE_UNDEFERR|VARE_WANTRES, &libName);
230 /* TODO: handle errors */
231 libName_freeIt = libName;
232 }
233
234
235 for (;;) {
236 /*
237 * First skip to the start of the member's name, mark that
238 * place and skip to the end of it (either white-space or
239 * a close paren).
240 */
241 Boolean doSubst = FALSE; /* TRUE if need to substitute in memName */
242
243 pp_skip_whitespace(&cp);
244
245 memName = cp;
246 while (*cp != '\0' && *cp != ')' && !ch_isspace(*cp)) {
247 if (*cp == '$') {
248 /*
249 * Variable spec, so call the Var module to parse the puppy
250 * so we can safely advance beyond it...
251 */
252 void *freeIt;
253 const char *result;
254 Boolean isError;
255 const char *nested_p = cp;
256
257 (void)Var_Parse(&nested_p, ctxt, VARE_UNDEFERR|VARE_WANTRES,
258 &result, &freeIt);
259 /* TODO: handle errors */
260 isError = result == var_Error;
261 free(freeIt);
262
263 if (isError)
264 return FALSE;
265
266 doSubst = TRUE;
267 cp += nested_p - cp;
268 } else {
269 cp++;
270 }
271 }
272
273 /*
274 * If the specification ends without a closing parenthesis,
275 * chances are there's something wrong (like a missing backslash),
276 * so it's better to return failure than allow such things to happen
277 */
278 if (*cp == '\0') {
279 Parse_Error(PARSE_FATAL, "No closing parenthesis in archive specification");
280 return FALSE;
281 }
282
283 /*
284 * If we didn't move anywhere, we must be done
285 */
286 if (cp == memName) {
287 break;
288 }
289
290 saveChar = *cp;
291 *cp = '\0';
292
293 /*
294 * XXX: This should be taken care of intelligently by
295 * SuffExpandChildren, both for the archive and the member portions.
296 */
297 /*
298 * If member contains variables, try and substitute for them.
299 * This will slow down archive specs with dynamic sources, of course,
300 * since we'll be (non-)substituting them three times, but them's
301 * the breaks -- we need to do this since SuffExpandChildren calls
302 * us, otherwise we could assume the thing would be taken care of
303 * later.
304 */
305 if (doSubst) {
306 char *buf;
307 char *sacrifice;
308 char *oldMemName = memName;
309
310 (void)Var_Subst(memName, ctxt, VARE_UNDEFERR|VARE_WANTRES,
311 &memName);
312 /* TODO: handle errors */
313
314 /*
315 * Now form an archive spec and recurse to deal with nested
316 * variables and multi-word variable values.... The results
317 * are just placed at the end of the nodeLst we're returning.
318 */
319 buf = sacrifice = str_concat4(libName, "(", memName, ")");
320
321 if (strchr(memName, '$') != NULL &&
322 strcmp(memName, oldMemName) == 0) {
323 /*
324 * Must contain dynamic sources, so we can't deal with it now.
325 * Just create an ARCHV node for the thing and let
326 * SuffExpandChildren handle it...
327 */
328 gn = Targ_GetNode(buf);
329 gn->type |= OP_ARCHV;
330 Lst_Append(nodeLst, gn);
331
332 } else if (!Arch_ParseArchive(&sacrifice, nodeLst, ctxt)) {
333 /* Error in nested call. */
334 free(buf);
335 return FALSE;
336 }
337 free(buf);
338
339 } else if (Dir_HasWildcards(memName)) {
340 StringList *members = Lst_New();
341 Dir_Expand(memName, dirSearchPath, members);
342
343 while (!Lst_IsEmpty(members)) {
344 char *member = Lst_Dequeue(members);
345 char *fullname = str_concat4(libName, "(", member, ")");
346 free(member);
347
348 gn = Targ_GetNode(fullname);
349 free(fullname);
350
351 gn->type |= OP_ARCHV;
352 Lst_Append(nodeLst, gn);
353 }
354 Lst_Free(members);
355
356 } else {
357 char *fullname = str_concat4(libName, "(", memName, ")");
358 gn = Targ_GetNode(fullname);
359 free(fullname);
360
361 /*
362 * We've found the node, but have to make sure the rest of the
363 * world knows it's an archive member, without having to
364 * constantly check for parentheses, so we type the thing with
365 * the OP_ARCHV bit before we place it on the end of the
366 * provided list.
367 */
368 gn->type |= OP_ARCHV;
369 Lst_Append(nodeLst, gn);
370 }
371 if (doSubst) {
372 free(memName);
373 }
374
375 *cp = saveChar;
376 }
377
378 free(libName_freeIt);
379
380 cp++; /* skip the ')' */
381 /* We promised that pp would be set up at the next non-space. */
382 pp_skip_whitespace(&cp);
383 *pp = cp;
384 return TRUE;
385 }
386
387 /* Locate a member of an archive, given the path of the archive and the path
388 * of the desired member.
389 *
390 * Input:
391 * archive Path to the archive
392 * member Name of member; only its basename is used.
393 * addToCache TRUE if archive should be cached if not already so.
394 *
395 * Results:
396 * The ar_hdr for the member, or NULL.
397 *
398 * See ArchFindMember for an almost identical copy of this code.
399 */
400 static struct ar_hdr *
401 ArchStatMember(const char *archive, const char *member, Boolean addToCache)
402 {
403 #define AR_MAX_NAME_LEN (sizeof arh.ar_name - 1)
404 FILE *arch; /* Stream to archive */
405 size_t size; /* Size of archive member */
406 char magic[SARMAG];
407 ArchListNode *ln;
408 Arch *ar; /* Archive descriptor */
409 struct ar_hdr arh; /* archive-member header for reading archive */
410 char memName[MAXPATHLEN + 1];
411 /* Current member name while hashing. */
412
413 /*
414 * Because of space constraints and similar things, files are archived
415 * using their basename, not the entire path.
416 */
417 const char *lastSlash = strrchr(member, '/');
418 if (lastSlash != NULL)
419 member = lastSlash + 1;
420
421 for (ln = archives->first; ln != NULL; ln = ln->next) {
422 const Arch *a = ln->datum;
423 if (strcmp(a->name, archive) == 0)
424 break;
425 }
426
427 if (ln != NULL) {
428 struct ar_hdr *hdr;
429
430 ar = ln->datum;
431 hdr = HashTable_FindValue(&ar->members, member);
432 if (hdr != NULL)
433 return hdr;
434
435 {
436 /* Try truncated name */
437 char copy[AR_MAX_NAME_LEN + 1];
438 size_t len = strlen(member);
439
440 if (len > AR_MAX_NAME_LEN) {
441 len = AR_MAX_NAME_LEN;
442 snprintf(copy, sizeof copy, "%s", member);
443 hdr = HashTable_FindValue(&ar->members, copy);
444 }
445 return hdr;
446 }
447 }
448
449 if (!addToCache) {
450 /*
451 * Caller doesn't want the thing cached, just use ArchFindMember
452 * to read the header for the member out and close down the stream
453 * again. Since the archive is not to be cached, we assume there's
454 * no need to allocate extra room for the header we're returning,
455 * so just declare it static.
456 */
457 static struct ar_hdr sarh;
458
459 arch = ArchFindMember(archive, member, &sarh, "r");
460 if (arch == NULL)
461 return NULL;
462
463 fclose(arch);
464 return &sarh;
465 }
466
467 /*
468 * We don't have this archive on the list yet, so we want to find out
469 * everything that's in it and cache it so we can get at it quickly.
470 */
471 arch = fopen(archive, "r");
472 if (arch == NULL)
473 return NULL;
474
475 /*
476 * We use the ARMAG string to make sure this is an archive we
477 * can handle...
478 */
479 if (fread(magic, SARMAG, 1, arch) != 1 ||
480 strncmp(magic, ARMAG, SARMAG) != 0) {
481 (void)fclose(arch);
482 return NULL;
483 }
484
485 ar = bmake_malloc(sizeof *ar);
486 ar->name = bmake_strdup(archive);
487 ar->fnametab = NULL;
488 ar->fnamesize = 0;
489 HashTable_Init(&ar->members);
490 memName[AR_MAX_NAME_LEN] = '\0';
491
492 while (fread(&arh, sizeof arh, 1, arch) == 1) {
493 char *nameend;
494
495 /* If the header is bogus, there's no way we can recover. */
496 if (strncmp(arh.ar_fmag, ARFMAG, sizeof arh.ar_fmag) != 0)
497 goto badarch;
498
499 /*
500 * We need to advance the stream's pointer to the start of the
501 * next header. Files are padded with newlines to an even-byte
502 * boundary, so we need to extract the size of the file from the
503 * 'size' field of the header and round it up during the seek.
504 */
505 arh.ar_size[sizeof arh.ar_size - 1] = '\0';
506 size = (size_t)strtol(arh.ar_size, NULL, 10);
507
508 memcpy(memName, arh.ar_name, sizeof arh.ar_name);
509 nameend = memName + AR_MAX_NAME_LEN;
510 while (nameend > memName && *nameend == ' ')
511 nameend--;
512 nameend[1] = '\0';
513
514 #ifdef SVR4ARCHIVES
515 /*
516 * svr4 names are slash terminated. Also svr4 extended AR format.
517 */
518 if (memName[0] == '/') {
519 /*
520 * svr4 magic mode; handle it
521 */
522 switch (ArchSVR4Entry(ar, memName, size, arch)) {
523 case -1: /* Invalid data */
524 goto badarch;
525 case 0: /* List of files entry */
526 continue;
527 default: /* Got the entry */
528 break;
529 }
530 } else {
531 if (nameend[0] == '/')
532 nameend[0] = '\0';
533 }
534 #endif
535
536 #ifdef AR_EFMT1
537 /*
538 * BSD 4.4 extended AR format: #1/<namelen>, with name as the
539 * first <namelen> bytes of the file
540 */
541 if (strncmp(memName, AR_EFMT1, sizeof AR_EFMT1 - 1) == 0 &&
542 ch_isdigit(memName[sizeof AR_EFMT1 - 1])) {
543
544 int elen = atoi(memName + sizeof AR_EFMT1 - 1);
545
546 if ((unsigned int)elen > MAXPATHLEN)
547 goto badarch;
548 if (fread(memName, (size_t)elen, 1, arch) != 1)
549 goto badarch;
550 memName[elen] = '\0';
551 if (fseek(arch, -elen, SEEK_CUR) != 0)
552 goto badarch;
553 if (DEBUG(ARCH) || DEBUG(MAKE))
554 debug_printf("ArchStatMember: Extended format entry for %s\n",
555 memName);
556 }
557 #endif
558
559 {
560 HashEntry *he;
561 he = HashTable_CreateEntry(&ar->members, memName, NULL);
562 HashEntry_Set(he, bmake_malloc(sizeof arh));
563 memcpy(HashEntry_Get(he), &arh, sizeof arh);
564 }
565
566 if (fseek(arch, ((long)size + 1) & ~1, SEEK_CUR) != 0)
567 goto badarch;
568 }
569
570 fclose(arch);
571
572 Lst_Append(archives, ar);
573
574 /*
575 * Now that the archive has been read and cached, we can look into
576 * the addToCache table to find the desired member's header.
577 */
578 return HashTable_FindValue(&ar->members, member);
579
580 badarch:
581 fclose(arch);
582 HashTable_Done(&ar->members);
583 free(ar->fnametab);
584 free(ar);
585 return NULL;
586 }
587
588 #ifdef SVR4ARCHIVES
589 /*-
590 *-----------------------------------------------------------------------
591 * ArchSVR4Entry --
592 * Parse an SVR4 style entry that begins with a slash.
593 * If it is "//", then load the table of filenames
594 * If it is "/<offset>", then try to substitute the long file name
595 * from offset of a table previously read.
596 * If a table is read, the file pointer is moved to the next archive
597 * member.
598 *
599 * Results:
600 * -1: Bad data in archive
601 * 0: A table was loaded from the file
602 * 1: Name was successfully substituted from table
603 * 2: Name was not successfully substituted from table
604 *-----------------------------------------------------------------------
605 */
606 static int
607 ArchSVR4Entry(Arch *ar, char *inout_name, size_t size, FILE *arch)
608 {
609 #define ARLONGNAMES1 "//"
610 #define ARLONGNAMES2 "/ARFILENAMES"
611 size_t entry;
612 char *ptr, *eptr;
613
614 if (strncmp(inout_name, ARLONGNAMES1, sizeof ARLONGNAMES1 - 1) == 0 ||
615 strncmp(inout_name, ARLONGNAMES2, sizeof ARLONGNAMES2 - 1) == 0) {
616
617 if (ar->fnametab != NULL) {
618 DEBUG0(ARCH, "Attempted to redefine an SVR4 name table\n");
619 return -1;
620 }
621
622 /*
623 * This is a table of archive names, so we build one for
624 * ourselves
625 */
626 ar->fnametab = bmake_malloc(size);
627 ar->fnamesize = size;
628
629 if (fread(ar->fnametab, size, 1, arch) != 1) {
630 DEBUG0(ARCH, "Reading an SVR4 name table failed\n");
631 return -1;
632 }
633 eptr = ar->fnametab + size;
634 for (entry = 0, ptr = ar->fnametab; ptr < eptr; ptr++)
635 if (*ptr == '/') {
636 entry++;
637 *ptr = '\0';
638 }
639 DEBUG1(ARCH, "Found svr4 archive name table with %lu entries\n",
640 (unsigned long)entry);
641 return 0;
642 }
643
644 if (inout_name[1] == ' ' || inout_name[1] == '\0')
645 return 2;
646
647 entry = (size_t)strtol(&inout_name[1], &eptr, 0);
648 if ((*eptr != ' ' && *eptr != '\0') || eptr == &inout_name[1]) {
649 DEBUG1(ARCH, "Could not parse SVR4 name %s\n", inout_name);
650 return 2;
651 }
652 if (entry >= ar->fnamesize) {
653 DEBUG2(ARCH, "SVR4 entry offset %s is greater than %lu\n",
654 inout_name, (unsigned long)ar->fnamesize);
655 return 2;
656 }
657
658 DEBUG2(ARCH, "Replaced %s with %s\n", inout_name, &ar->fnametab[entry]);
659
660 snprintf(inout_name, MAXPATHLEN + 1, "%s", &ar->fnametab[entry]);
661 return 1;
662 }
663 #endif
664
665
666 static Boolean
667 ArchiveMember_HasName(const struct ar_hdr *hdr,
668 const char *name, size_t namelen)
669 {
670 const size_t ar_name_len = sizeof hdr->ar_name;
671 const char *ar_name = hdr->ar_name;
672
673 if (strncmp(ar_name, name, namelen) != 0)
674 return FALSE;
675
676 if (namelen >= ar_name_len)
677 return namelen == ar_name_len;
678
679 /* hdr->ar_name is space-padded to the right. */
680 if (ar_name[namelen] == ' ')
681 return TRUE;
682
683 /* In archives created by GNU binutils 2.27, the member names end with
684 * a slash. */
685 if (ar_name[namelen] == '/' &&
686 (namelen == ar_name_len || ar_name[namelen + 1] == ' '))
687 return TRUE;
688
689 return FALSE;
690 }
691
692 /* Locate a member of an archive, given the path of the archive and the path
693 * of the desired member.
694 *
695 * Input:
696 * archive Path to the archive
697 * member Name of member. If it is a path, only the last
698 * component is used.
699 * out_arh Archive header to be filled in
700 * mode "r" for read-only access, "r+" for read-write access
701 *
702 * Output:
703 * return The archive file, positioned at the start of the
704 * member's struct ar_hdr, or NULL if the member doesn't
705 * exist.
706 * *out_arh The current struct ar_hdr for member.
707 *
708 * See ArchStatMember for an almost identical copy of this code.
709 */
710 static FILE *
711 ArchFindMember(const char *archive, const char *member, struct ar_hdr *out_arh,
712 const char *mode)
713 {
714 FILE *arch; /* Stream to archive */
715 int size; /* Size of archive member */
716 char magic[SARMAG];
717 size_t len, tlen;
718 const char *lastSlash;
719
720 arch = fopen(archive, mode);
721 if (arch == NULL)
722 return NULL;
723
724 /*
725 * We use the ARMAG string to make sure this is an archive we
726 * can handle...
727 */
728 if (fread(magic, SARMAG, 1, arch) != 1 ||
729 strncmp(magic, ARMAG, SARMAG) != 0) {
730 fclose(arch);
731 return NULL;
732 }
733
734 /*
735 * Because of space constraints and similar things, files are archived
736 * using their basename, not the entire path.
737 */
738 lastSlash = strrchr(member, '/');
739 if (lastSlash != NULL)
740 member = lastSlash + 1;
741
742 len = tlen = strlen(member);
743 if (len > sizeof out_arh->ar_name) {
744 tlen = sizeof out_arh->ar_name;
745 }
746
747 while (fread(out_arh, sizeof *out_arh, 1, arch) == 1) {
748
749 if (strncmp(out_arh->ar_fmag, ARFMAG, sizeof out_arh->ar_fmag) != 0) {
750 /*
751 * The header is bogus, so the archive is bad
752 * and there's no way we can recover...
753 */
754 fclose(arch);
755 return NULL;
756 }
757
758 DEBUG5(ARCH, "Reading archive %s member %.*s mtime %.*s\n",
759 archive,
760 (int)sizeof out_arh->ar_name, out_arh->ar_name,
761 (int)sizeof out_arh->ar_date, out_arh->ar_date);
762
763 if (ArchiveMember_HasName(out_arh, member, len)) {
764 /*
765 * To make life easier for callers that want to update the
766 * archive, we reposition the file at the start
767 * of the header we just read before we return the stream.
768 * In a more general situation, it might be better to leave
769 * the file at the actual member, rather than its header, but
770 * not here.
771 */
772 if (fseek(arch, -(long)sizeof *out_arh, SEEK_CUR) != 0) {
773 fclose(arch);
774 return NULL;
775 }
776 return arch;
777 }
778
779 #ifdef AR_EFMT1
780 /*
781 * BSD 4.4 extended AR format: #1/<namelen>, with name as the
782 * first <namelen> bytes of the file
783 */
784 if (strncmp(out_arh->ar_name, AR_EFMT1, sizeof AR_EFMT1 - 1) == 0 &&
785 ch_isdigit(out_arh->ar_name[sizeof AR_EFMT1 - 1]))
786 {
787 int elen = atoi(&out_arh->ar_name[sizeof AR_EFMT1 - 1]);
788 char ename[MAXPATHLEN + 1];
789
790 if ((unsigned int)elen > MAXPATHLEN) {
791 fclose(arch);
792 return NULL;
793 }
794 if (fread(ename, (size_t)elen, 1, arch) != 1) {
795 fclose(arch);
796 return NULL;
797 }
798 ename[elen] = '\0';
799 if (DEBUG(ARCH) || DEBUG(MAKE))
800 debug_printf("ArchFindMember: Extended format entry for %s\n",
801 ename);
802 if (strncmp(ename, member, len) == 0) {
803 /* Found as extended name */
804 if (fseek(arch, -(long)sizeof(struct ar_hdr) - elen,
805 SEEK_CUR) != 0) {
806 fclose(arch);
807 return NULL;
808 }
809 return arch;
810 }
811 if (fseek(arch, -elen, SEEK_CUR) != 0) {
812 fclose(arch);
813 return NULL;
814 }
815 }
816 #endif
817
818 /*
819 * This isn't the member we're after, so we need to advance the
820 * stream's pointer to the start of the next header. Files are
821 * padded with newlines to an even-byte boundary, so we need to
822 * extract the size of the file from the 'size' field of the
823 * header and round it up during the seek.
824 */
825 out_arh->ar_size[sizeof out_arh->ar_size - 1] = '\0';
826 size = (int)strtol(out_arh->ar_size, NULL, 10);
827 if (fseek(arch, (size + 1) & ~1, SEEK_CUR) != 0) {
828 fclose(arch);
829 return NULL;
830 }
831 }
832
833 fclose(arch);
834 return NULL;
835 }
836
837 /* Touch a member of an archive, on disk.
838 * The GNode's modification time is left as-is.
839 *
840 * The st_mtime of the entire archive is also changed.
841 * For a library, it may be required to run ranlib after this.
842 *
843 * Input:
844 * gn Node of member to touch
845 *
846 * Results:
847 * The 'time' field of the member's header is updated.
848 */
849 void
850 Arch_Touch(GNode *gn)
851 {
852 FILE *f;
853 struct ar_hdr arh;
854
855 f = ArchFindMember(GNode_VarArchive(gn), GNode_VarMember(gn), &arh, "r+");
856 if (f == NULL)
857 return;
858
859 snprintf(arh.ar_date, sizeof arh.ar_date, "%-ld", (unsigned long)now);
860 (void)fwrite(&arh, sizeof arh, 1, f);
861 fclose(f); /* TODO: handle errors */
862 }
863
864 /* Given a node which represents a library, touch the thing, making sure that
865 * the table of contents is also touched.
866 *
867 * Both the modification time of the library and of the RANLIBMAG member are
868 * set to 'now'. */
869 void
870 Arch_TouchLib(GNode *gn MAKE_ATTR_UNUSED)
871 {
872 #ifdef RANLIBMAG
873 FILE *f;
874 struct ar_hdr arh; /* Header describing table of contents */
875 struct utimbuf times;
876
877 f = ArchFindMember(gn->path, RANLIBMAG, &arh, "r+");
878 if (f == NULL)
879 return;
880
881 snprintf(arh.ar_date, sizeof arh.ar_date, "%-ld", (unsigned long)now);
882 (void)fwrite(&arh, sizeof arh, 1, f);
883 fclose(f); /* TODO: handle errors */
884
885 times.actime = times.modtime = now;
886 utime(gn->path, ×); /* TODO: handle errors */
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, update gn->mtime from its
910 * archived form, if it exists. */
911 void
912 Arch_UpdateMemberMTime(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
946 /* Search for a library along the given search path.
947 *
948 * The node's 'path' field is set to the found path (including the
949 * actual file name, not -l...). If the system can handle the -L
950 * flag when linking (or we cannot find the library), we assume that
951 * the user has placed the .LIBS variable in the final linking
952 * command (or the linker will know where to find it) and set the
953 * TARGET variable for this node to be the node's name. Otherwise,
954 * we set the TARGET variable to be the full path of the library,
955 * as returned by Dir_FindFile.
956 *
957 * Input:
958 * gn Node of library to find
959 */
960 void
961 Arch_FindLib(GNode *gn, SearchPath *path)
962 {
963 char *libName = str_concat3("lib", gn->name + 2, ".a");
964 gn->path = Dir_FindFile(libName, path);
965 free(libName);
966
967 #ifdef LIBRARIES
968 Var_Set(TARGET, gn->name, gn);
969 #else
970 Var_Set(TARGET, gn->path == NULL ? gn->name : gn->path, gn);
971 #endif
972 }
973
974 /* Decide if a node with the OP_LIB attribute is out-of-date. Called from
975 * GNode_IsOODate to make its life easier.
976 * The library is cached if it hasn't been already.
977 *
978 * There are several ways for a library to be out-of-date that are
979 * not available to ordinary files. In addition, there are ways
980 * that are open to regular files that are not available to
981 * libraries.
982 *
983 * 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 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 Boolean
1004 Arch_LibOODate(GNode *gn)
1005 {
1006 Boolean oodate;
1007
1008 if (gn->type & OP_PHONY) {
1009 oodate = TRUE;
1010 } else if (!GNode_IsTarget(gn) && Lst_IsEmpty(gn->children)) {
1011 oodate = FALSE;
1012 } else if ((!Lst_IsEmpty(gn->children) && gn->youngestChild == NULL) ||
1013 (gn->mtime > now) ||
1014 (gn->youngestChild != NULL &&
1015 gn->mtime < gn->youngestChild->mtime)) {
1016 oodate = TRUE;
1017 } else {
1018 #ifdef RANLIBMAG
1019 struct ar_hdr *arh; /* Header for __.SYMDEF */
1020 int modTimeTOC; /* The table-of-contents's mod time */
1021
1022 arh = ArchStatMember(gn->path, RANLIBMAG, FALSE);
1023
1024 if (arh != NULL) {
1025 modTimeTOC = (int)strtol(arh->ar_date, NULL, 10);
1026
1027 if (DEBUG(ARCH) || DEBUG(MAKE))
1028 debug_printf("%s modified %s...",
1029 RANLIBMAG, Targ_FmtTime(modTimeTOC));
1030 oodate = gn->youngestChild == NULL ||
1031 gn->youngestChild->mtime > modTimeTOC;
1032 } else {
1033 /* A library without a table of contents is out-of-date. */
1034 if (DEBUG(ARCH) || DEBUG(MAKE))
1035 debug_printf("no toc...");
1036 oodate = TRUE;
1037 }
1038 #else
1039 oodate = FALSE;
1040 #endif
1041 }
1042 return oodate;
1043 }
1044
1045 /* Initialize the archives module. */
1046 void
1047 Arch_Init(void)
1048 {
1049 archives = Lst_New();
1050 }
1051
1052 /* Clean up the archives module. */
1053 void
1054 Arch_End(void)
1055 {
1056 #ifdef CLEANUP
1057 Lst_Destroy(archives, ArchFree);
1058 #endif
1059 }
1060
1061 Boolean
1062 Arch_IsLib(GNode *gn)
1063 {
1064 static const char armag[] = "!<arch>\n";
1065 char buf[sizeof armag - 1];
1066 int fd;
1067
1068 if ((fd = open(gn->path, O_RDONLY)) == -1)
1069 return FALSE;
1070
1071 if (read(fd, buf, sizeof buf) != sizeof buf) {
1072 (void)close(fd);
1073 return FALSE;
1074 }
1075
1076 (void)close(fd);
1077
1078 return memcmp(buf, armag, sizeof buf) == 0;
1079 }
1080