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