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