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