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