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