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