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