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