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