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