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