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