1 /**	$MirOS: src/usr.bin/make/arch.c,v 1.3 2007/06/21 14:17:06 tg Exp $ */
2 /*	$OpenPackages$ */
3 /*	$OpenBSD: arch.c,v 1.56 2007/03/20 03:50:39 tedu Exp $ */
4 /*	$NetBSD: arch.c,v 1.17 1996/11/06 17:58:59 christos Exp $	*/
5 
6 /*
7  * Copyright (c) 1999,2000 Marc Espie.
8  *
9  * Extensive code changes for the OpenBSD project.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE OPENBSD PROJECT AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OPENBSD
24  * PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 /*
33  * Copyright (c) 1988, 1989, 1990, 1993
34  *	The Regents of the University of California.  All rights reserved.
35  * Copyright (c) 1989 by Berkeley Softworks
36  * All rights reserved.
37  *
38  * This code is derived from software contributed to Berkeley by
39  * Adam de Boor.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  * 3. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  */
65 
66 /*
67  *	Once again, cacheing/hashing comes into play in the manipulation
68  * of archives. The first time an archive is referenced, all of its members'
69  * headers are read and hashed and the archive closed again. All hashed
70  * archives are kept in a hash (archives) which is searched each time
71  * an archive member is referenced.
72  *
73  */
74 
75 #include <sys/param.h>
76 #include <ar.h>
77 #include <assert.h>
78 #include <ctype.h>
79 #include <fcntl.h>
80 #include <limits.h>
81 #include <stddef.h>
82 #include <stdio.h>
83 #include <stdint.h>
84 #include <stdlib.h>
85 #include <string.h>
86 #include <unistd.h>
87 #include "ohash.h"
88 #include "config.h"
89 #include "defines.h"
90 #include "dir.h"
91 #include "arch.h"
92 #include "var.h"
93 #include "targ.h"
94 #include "memory.h"
95 #include "gnode.h"
96 #include "timestamp.h"
97 #include "lst.h"
98 
99 #ifndef PATH_MAX
100 # ifdef MAXPATHLEN
101 #  define PATH_MAX (MAXPATHLEN+1)
102 # else
103 #  define PATH_MAX	1024
104 # endif
105 #endif
106 
107 __RCSID("$MirOS: src/usr.bin/make/arch.c,v 1.3 2007/06/21 14:17:06 tg Exp $");
108 
109 static struct ohash	  archives;   /* Archives we've already examined.  */
110 
111 typedef struct Arch_ {
112     struct ohash   members;    /* All the members of this archive, as
113 			       * struct arch_member entries.  */
114     char	  name[1];    /* Archive name.	*/
115 } Arch;
116 
117 /* Used to get to ar's field sizes.  */
118 static struct ar_hdr *dummy;
119 #define AR_NAME_SIZE		(sizeof(dummy->ar_name))
120 #define AR_DATE_SIZE		(sizeof(dummy->ar_date))
121 
122 /* Each archive member is tied to an arch_member structure,
123  * suitable for hashing.  */
124 struct arch_member {
125     TIMESTAMP	  mtime;	/* Member modification date.  */
126     char	  date[AR_DATE_SIZE+1];
127 				/* Same, before conversion to numeric value.  */
128     char	  name[1];	/* Member name.  */
129 };
130 
131 static struct ohash_info members_info = {
132     offsetof(struct arch_member, name), NULL,
133     hash_alloc, hash_free, element_alloc
134 };
135 
136 static struct ohash_info arch_info = {
137     offsetof(Arch, name), NULL, hash_alloc, hash_free, element_alloc
138 };
139 
140 
141 
142 static struct arch_member *new_arch_member(struct ar_hdr *, const char *);
143 static TIMESTAMP mtime_of_member(struct arch_member *);
144 static long field2long(const char *, size_t);
145 static Arch *read_archive(const char *, const char *);
146 
147 #ifdef CLEANUP
148 static void ArchFree(Arch *);
149 #endif
150 static TIMESTAMP ArchMTimeMember(const char *, const char *, bool);
151 static FILE *ArchFindMember(const char *, const char *, struct ar_hdr *, const char *);
152 static void ArchTouch(const char *, const char *);
153 #if defined(__svr4__) || defined(__SVR4) || \
154     (defined(__Linux__) && defined(__ELF__)) || \
155     (defined(__OpenBSD__) && defined(__ELF__))
156 #define SVR4ARCHIVES
157 #endif
158 
159 #ifdef SVR4ARCHIVES
160 struct SVR4namelist {
161     char	  *fnametab;  /* Extended name table strings */
162     size_t	  fnamesize;  /* Size of the string table */
163 };
164 
165 static const char *svr4list = "Archive list";
166 
167 static char *ArchSVR4Entry(struct SVR4namelist *, const char *, size_t, FILE *);
168 #endif
169 
170 static struct arch_member *
new_arch_member(struct ar_hdr * hdr,const char * name)171 new_arch_member(struct ar_hdr *hdr, const char *name)
172 {
173     const char *end = NULL;
174     struct arch_member *n;
175 
176     n = ohash_create_entry(&members_info, name, &end);
177     /* XXX ar entries are NOT null terminated.	*/
178     memcpy(n->date, &(hdr->ar_date), AR_DATE_SIZE);
179     n->date[AR_DATE_SIZE] = '\0';
180     /* Don't compute mtime before it is needed. */
181     ts_set_out_of_date(n->mtime);
182     return n;
183 }
184 
185 static TIMESTAMP
mtime_of_member(struct arch_member * m)186 mtime_of_member(struct arch_member *m)
187 {
188     if (is_out_of_date(m->mtime))
189 	ts_set_from_time_t((time_t) strtol(m->date, NULL, 10), m->mtime);
190     return m->mtime;
191 }
192 
193 #ifdef CLEANUP
194 /*-
195  *-----------------------------------------------------------------------
196  * ArchFree --
197  *	Free memory used by an archive
198  *-----------------------------------------------------------------------
199  */
200 static void
ArchFree(Arch * a)201 ArchFree(Arch *a)
202 {
203     struct arch_member *mem;
204     unsigned int i;
205 
206     /* Free memory from hash entries */
207     for (mem = ohash_first(&a->members, &i); mem != NULL;
208 	mem = ohash_next(&a->members, &i))
209 	free(mem);
210 
211     ohash_delete(&a->members);
212     free(a);
213 }
214 #endif
215 
216 
217 
218 /* Side-effects: Some nodes may be created.  */
219 bool
Arch_ParseArchive(char ** linePtr,Lst nodeLst,SymTable * ctxt)220 Arch_ParseArchive(char **linePtr,   /* Pointer to start of specification */
221     Lst nodeLst, 		    /* Lst on which to place the nodes */
222     SymTable *ctxt)		    /* Context in which to expand variables */
223 {
224     char	    *cp;	    /* Pointer into line */
225     GNode	    *gn;	    /* New node */
226     char	    *libName;	    /* Library-part of specification */
227     char	    *memberName;    /* Member-part of specification */
228     char	    nameBuf[MAKE_BSIZE]; /* temporary place for node name */
229     char	    saveChar;	    /* Ending delimiter of member-name */
230     bool	    subLibName;     /* true if libName should have/had
231 				     * variable substitution performed on it */
232 
233     libName = *linePtr;
234 
235     subLibName = false;
236 
237     for (cp = libName; *cp != '(' && *cp != '\0';) {
238 	if (*cp == '$') {
239 	    bool ok;
240 
241 	    cp += Var_ParseSkip(cp, ctxt, &ok);
242 	    if (ok == false)
243 		return false;
244 	    subLibName = true;
245 	} else
246 	    cp++;
247     }
248 
249     *cp++ = '\0';
250     if (subLibName)
251 	libName = Var_Subst(libName, ctxt, true);
252 
253     for (;;) {
254 	/* First skip to the start of the member's name, mark that
255 	 * place and skip to the end of it (either white-space or
256 	 * a close paren).  */
257 	bool doSubst = false; /* true if need to substitute in memberName */
258 
259 	while (isspace(*cp))
260 	    cp++;
261 	memberName = cp;
262 	while (*cp != '\0' && *cp != ')' && !isspace(*cp)) {
263 	    if (*cp == '$') {
264 		bool ok;
265 		cp += Var_ParseSkip(cp, ctxt, &ok);
266 		if (ok == false)
267 		    return false;
268 		doSubst = true;
269 	    } else
270 		cp++;
271 	}
272 
273 	/* If the specification ends without a closing parenthesis,
274 	 * chances are there's something wrong (like a missing backslash),
275 	 * so it's better to return failure than allow such things to
276 	 * happen.  */
277 	if (*cp == '\0') {
278 	    printf("No closing parenthesis in archive specification\n");
279 	    return false;
280 	}
281 
282 	/* If we didn't move anywhere, we must be done.  */
283 	if (cp == memberName)
284 	    break;
285 
286 	saveChar = *cp;
287 	*cp = '\0';
288 
289 	/* XXX: This should be taken care of intelligently by
290 	 * SuffExpandChildren, both for the archive and the member portions.  */
291 
292 	/* If member contains variables, try and substitute for them.
293 	 * This will slow down archive specs with dynamic sources, of course,
294 	 * since we'll be (non-)substituting them three times, but them's
295 	 * the breaks -- we need to do this since SuffExpandChildren calls
296 	 * us, otherwise we could assume the thing would be taken care of
297 	 * later.  */
298 	if (doSubst) {
299 	    char    *buf;
300 	    char    *sacrifice;
301 	    char    *oldMemberName = memberName;
302 	    size_t  length;
303 
304 	    memberName = Var_Subst(memberName, ctxt, true);
305 
306 	    /* Now form an archive spec and recurse to deal with nested
307 	     * variables and multi-word variable values.... The results
308 	     * are just placed at the end of the nodeLst we're returning.  */
309 	    length = strlen(memberName)+strlen(libName)+3;
310 	    buf = sacrifice = emalloc(length);
311 
312 	    snprintf(buf, length, "%s(%s)", libName, memberName);
313 
314 	    if (strchr(memberName, '$') &&
315 	    	strcmp(memberName, oldMemberName) == 0) {
316 		/* Must contain dynamic sources, so we can't deal with it now.
317 		 * Just create an ARCHV node for the thing and let
318 		 * SuffExpandChildren handle it...  */
319 		gn = Targ_FindNode(buf, TARG_CREATE);
320 
321 		if (gn == NULL) {
322 		    free(buf);
323 		    return false;
324 		} else {
325 		    gn->type |= OP_ARCHV;
326 		    Lst_AtEnd(nodeLst, gn);
327 		}
328 	    } else if (!Arch_ParseArchive(&sacrifice, nodeLst, ctxt)) {
329 		/* Error in nested call -- free buffer and return false
330 		 * ourselves.  */
331 		free(buf);
332 		return false;
333 	    }
334 	    /* Free buffer and continue with our work.	*/
335 	    free(buf);
336 	} else if (Dir_HasWildcards(memberName)) {
337 	    LIST  members;
338 	    char  *member;
339 
340 	    Lst_Init(&members);
341 
342 	    Dir_Expand(memberName, dirSearchPath, &members);
343 	    while ((member = (char *)Lst_DeQueue(&members)) != NULL) {
344 		snprintf(nameBuf, MAKE_BSIZE, "%s(%s)", libName, member);
345 		free(member);
346 		gn = Targ_FindNode(nameBuf, TARG_CREATE);
347 		/* We've found the node, but have to make sure the rest of
348 		 * the world knows it's an archive member, without having
349 		 * to constantly check for parentheses, so we type the
350 		 * thing with the OP_ARCHV bit before we place it on the
351 		 * end of the provided list.  */
352 		gn->type |= OP_ARCHV;
353 		Lst_AtEnd(nodeLst, gn);
354 	    }
355 	} else {
356 	    snprintf(nameBuf, MAKE_BSIZE, "%s(%s)", libName, memberName);
357 	    gn = Targ_FindNode(nameBuf, TARG_CREATE);
358 	    /* We've found the node, but have to make sure the rest of the
359 	     * world knows it's an archive member, without having to
360 	     * constantly check for parentheses, so we type the thing with
361 	     * the OP_ARCHV bit before we place it on the end of the
362 	     * provided list.  */
363 	    gn->type |= OP_ARCHV;
364 	    Lst_AtEnd(nodeLst, gn);
365 	}
366 	if (doSubst)
367 	    free(memberName);
368 
369 	*cp = saveChar;
370     }
371 
372     /* If substituted libName, free it now, since we need it no longer.  */
373     if (subLibName)
374 	free(libName);
375 
376     /* We promised the pointer would be set up at the next non-space, so
377      * we must advance cp there before setting *linePtr... (note that on
378      * entrance to the loop, cp is guaranteed to point at a ')') */
379     do {
380 	cp++;
381     } while (isspace(*cp));
382 
383     *linePtr = cp;
384     return true;
385 }
386 
387 /* Helper function: ar fields are not null terminated.	*/
388 static long
field2long(const char * field,size_t length)389 field2long(const char *field, size_t length)
390 {
391     static char enough[32];
392 
393     assert(length < sizeof(enough));
394     memcpy(enough, field, length);
395     enough[length] = '\0';
396     return strtol(enough, NULL, 10);
397 }
398 
399 static Arch *
read_archive(const char * archive,const char * earchive)400 read_archive(const char *archive, const char *earchive)
401 {
402     FILE *	  arch;       /* Stream to archive */
403     char	  magic[SARMAG];
404     Arch	  *ar;
405 #ifdef SVR4ARCHIVES
406     struct SVR4namelist list;
407 
408     list.fnametab = NULL;
409 #endif
410 
411     /* When we encounter an archive for the first time, we read its
412      * whole contents, to place it in the cache.  */
413     arch = fopen(archive, "r");
414     if (arch == NULL)
415 	return NULL;
416 
417     /* Make sure this is an archive we can handle.  */
418     if ((fread(magic, SARMAG, 1, arch) != 1) ||
419 	(strncmp(magic, ARMAG, SARMAG) != 0)) {
420 	    fclose(arch);
421 	    return NULL;
422     }
423 
424     ar = ohash_create_entry(&arch_info, archive, &earchive);
425     ohash_init(&ar->members, 8, &members_info);
426 
427     for (;;) {
428 	size_t		n;
429 	struct ar_hdr	arHeader;/* Archive-member header for reading archive */
430 	off_t		size;	/* Size of archive member */
431 	char		buffer[PATH_MAX];
432 	char		*memberName;
433 				/* Current member name while hashing. */
434 	char		*cp;	/* Useful character pointer */
435 
436 	memberName = buffer;
437 	n = fread(&arHeader, 1, sizeof(struct ar_hdr), arch);
438 
439 	/*  Whole archive read ok.  */
440 	if (n == 0 && feof(arch)) {
441 #ifdef SVR4ARCHIVES
442 	    efree(list.fnametab);
443 #endif
444 	    fclose(arch);
445 	    return ar;
446 	}
447 	if (n < sizeof(struct ar_hdr))
448 	    break;
449 
450 	if (memcmp(arHeader.ar_fmag, ARFMAG, sizeof(arHeader.ar_fmag)) != 0) {
451 	    /* The header is bogus.  */
452 	    break;
453 	} else {
454 	    /* We need to advance the stream's pointer to the start of the
455 	     * next header.  Records are padded with newlines to an even-byte
456 	     * boundary, so we need to extract the size of the record and
457 	     * round it up during the seek.  */
458 	    size = (off_t) field2long(arHeader.ar_size,
459 	    	sizeof(arHeader.ar_size));
460 
461 	    (void)memcpy(memberName, arHeader.ar_name, AR_NAME_SIZE);
462 	    /* Find real end of name (strip extranous ' ')  */
463 	    for (cp = memberName + AR_NAME_SIZE - 1; *cp == ' ';)
464 		cp--;
465 	    cp[1] = '\0';
466 
467 #ifdef SVR4ARCHIVES
468 	    /* SVR4 names are slash terminated.  Also svr4 extended AR format.
469 	     */
470 	    if (memberName[0] == '/') {
471 		/* SVR4 magic mode.  */
472 		memberName = ArchSVR4Entry(&list, memberName, size, arch);
473 		if (memberName == NULL)		/* Invalid data */
474 		    break;
475 		else if (memberName == svr4list)/* List of files entry */
476 		    continue;
477 		/* Got the entry.  */
478 		/* XXX this assumes further processing, such as AR_EFMT1,
479 		 * also applies to SVR4ARCHIVES.  */
480 	    }
481 	    else {
482 		if (cp[0] == '/')
483 		    cp[0] = '\0';
484 	    }
485 #endif
486 
487 #ifdef AR_EFMT1
488 	    /* BSD 4.4 extended AR format: #1/<namelen>, with name as the
489 	     * first <namelen> bytes of the file.  */
490 	    if (memcmp(memberName, AR_EFMT1, sizeof(AR_EFMT1) - 1) == 0 &&
491 		isdigit(memberName[sizeof(AR_EFMT1) - 1])) {
492 
493 		int elen = atoi(memberName + sizeof(AR_EFMT1)-1);
494 
495 		if (elen <= 0 || elen >= PATH_MAX)
496 			break;
497 		memberName = buffer;
498 		if (fread(memberName, elen, 1, arch) != 1)
499 			break;
500 		memberName[elen] = '\0';
501 		if (fseek(arch, -elen, SEEK_CUR) != 0)
502 			break;
503 		if (DEBUG(ARCH) || DEBUG(MAKE))
504 		    printf("ArchStat: Extended format entry for %s\n",
505 		    	memberName);
506 	    }
507 #endif
508 
509 	    ohash_insert(&ar->members,
510 		ohash_qlookup(&ar->members, memberName),
511 		    new_arch_member(&arHeader, memberName));
512 	}
513 	if (fseek(arch, (size + 1) & ~1, SEEK_CUR) != 0)
514 	    break;
515     }
516 
517     fclose(arch);
518     ohash_delete(&ar->members);
519 #ifdef SVR4ARCHIVES
520     efree(list.fnametab);
521 #endif
522     free(ar);
523     return NULL;
524 }
525 
526 /*-
527  *-----------------------------------------------------------------------
528  * ArchMTimeMember --
529  *	Find the modification time of an archive's member, given the
530  *	path to the archive and the path to the desired member.
531  *
532  * Results:
533  *	The archive member's modification time, or OUT_OF_DATE if member
534  *	was not found (convenient, so that missing members are always
535  *	out of date).
536  *
537  * Side Effects:
538  *	Cache the whole archive contents if hash is true.
539  *-----------------------------------------------------------------------
540  */
541 static TIMESTAMP
ArchMTimeMember(const char * archive,const char * member,bool hash)542 ArchMTimeMember(
543     const char	  *archive,   /* Path to the archive */
544     const char	  *member,    /* Name of member. If it is a path, only the
545 			       * last component is used. */
546     bool	  hash)       /* true if archive should be hashed if not
547 			       * already so. */
548 {
549     FILE *	  arch;       /* Stream to archive */
550     Arch	  *ar;	      /* Archive descriptor */
551     unsigned int  slot;       /* Place of archive in the archives hash */
552     const char	  *end = NULL;
553     const char	  *cp;
554     TIMESTAMP	  result;
555 
556     ts_set_out_of_date(result);
557     /* Because of space constraints and similar things, files are archived
558      * using their final path components, not the entire thing, so we need
559      * to point 'member' to the final component, if there is one, to make
560      * the comparisons easier...  */
561     cp = strrchr(member, '/');
562     if (cp != NULL)
563 	member = cp + 1;
564 
565     /* Try to find archive in cache.  */
566     slot = ohash_qlookupi(&archives, archive, &end);
567     ar = ohash_find(&archives, slot);
568 
569     /* If not found, get it now.  */
570     if (ar == NULL) {
571 	if (!hash) {
572 	    /* Quick path:  no need to hash the whole archive, just use
573 	     * ArchFindMember to get the member's header and close the stream
574 	     * again.  */
575 	    struct ar_hdr	arHeader;
576 
577 	    arch = ArchFindMember(archive, member, &arHeader, "r");
578 
579 	    if (arch != NULL) {
580 		fclose(arch);
581 		ts_set_from_time_t( (time_t)strtol(arHeader.ar_date, NULL, 10),
582 		    result);
583 	    }
584 	    return result;
585 	}
586 	ar = read_archive(archive, end);
587 	if (ar != NULL)
588 	    ohash_insert(&archives, slot, ar);
589     }
590 
591     /* If archive was found, get entry we seek.  */
592     if (ar != NULL) {
593 	struct arch_member *he;
594 	end = NULL;
595 
596 	he = ohash_find(&ar->members, ohash_qlookupi(&ar->members, member, &end));
597 	if (he != NULL)
598 	    return mtime_of_member(he);
599 	else {
600 	    if ((size_t)(end - member) > AR_NAME_SIZE) {
601 		/* Try truncated name.	*/
602 		end = member + AR_NAME_SIZE;
603 		he = ohash_find(&ar->members,
604 		    ohash_qlookupi(&ar->members, member, &end));
605 		if (he != NULL)
606 		    return mtime_of_member(he);
607 	    }
608 	}
609     }
610     return result;
611 }
612 
613 #ifdef SVR4ARCHIVES
614 /*-
615  *-----------------------------------------------------------------------
616  * ArchSVR4Entry --
617  *	Parse an SVR4 style entry that begins with a slash.
618  *	If it is "//", then load the table of filenames
619  *	If it is "/<offset>", then try to substitute the long file name
620  *	from offset of a table previously read.
621  *
622  * Results:
623  *	svr4list: just read a list of names
624  *	NULL:	  error occurred
625  *	extended name
626  *
627  * Side-effect:
628  *	For a list of names, store the list in l.
629  *-----------------------------------------------------------------------
630  */
631 
632 static char *
ArchSVR4Entry(struct SVR4namelist * l,const char * name,size_t size,FILE * arch)633 ArchSVR4Entry(struct SVR4namelist *l, const char *name, size_t size, FILE *arch)
634 {
635 #define ARLONGNAMES1 "/"
636 #define ARLONGNAMES2 "ARFILENAMES"
637     size_t entry;
638     char *ptr, *eptr;
639 
640     assert(name[0] == '/');
641     name++;
642     /* First comes a table of archive names, to be used by subsequent calls.  */
643     if (memcmp(name, ARLONGNAMES1, sizeof(ARLONGNAMES1) - 1) == 0 ||
644 	memcmp(name, ARLONGNAMES2, sizeof(ARLONGNAMES2) - 1) == 0) {
645 
646 	if (l->fnametab != NULL) {
647 	    if (DEBUG(ARCH))
648 		printf("Attempted to redefine an SVR4 name table\n");
649 	    return NULL;
650 	}
651 
652 	l->fnametab = emalloc(size);
653 	l->fnamesize = size;
654 
655 	if (fread(l->fnametab, size, 1, arch) != 1) {
656 	    if (DEBUG(ARCH))
657 		printf("Reading an SVR4 name table failed\n");
658 	    return NULL;
659 	}
660 
661 	eptr = l->fnametab + size;
662 	for (entry = 0, ptr = l->fnametab; ptr < eptr; ptr++)
663 	    switch (*ptr) {
664 	    case '/':
665 		entry++;
666 		*ptr = '\0';
667 		break;
668 
669 	    case '\n':
670 		break;
671 
672 	    default:
673 		break;
674 	    }
675 	if (DEBUG(ARCH))
676 	    printf("Found svr4 archive name table with %lu entries\n",
677 			(u_long)entry);
678 	return (char *)svr4list;
679     }
680     /* Then the names themselves are given as offsets in this table.  */
681     if (*name == ' ' || *name == '\0')
682 	return NULL;
683 
684     entry = (size_t) strtol(name, &eptr, 0);
685     if ((*eptr != ' ' && *eptr != '\0') || eptr == name) {
686 	if (DEBUG(ARCH))
687 	    printf("Could not parse SVR4 name /%s\n", name);
688 	return NULL;
689     }
690     if (entry >= l->fnamesize) {
691 	if (DEBUG(ARCH))
692 	    printf("SVR4 entry offset /%s is greater than %lu\n",
693 		   name, (u_long)l->fnamesize);
694 	return NULL;
695     }
696 
697     if (DEBUG(ARCH))
698 	printf("Replaced /%s with %s\n", name, l->fnametab + entry);
699 
700     return l->fnametab + entry;
701 }
702 #endif
703 
704 
705 /*-
706  *-----------------------------------------------------------------------
707  * ArchFindMember --
708  *	Locate a member of an archive, given the path of the archive and
709  *	the path of the desired member. If the archive is to be modified,
710  *	the mode should be "r+", if not, it should be "r".
711  *
712  * Results:
713  *	A FILE *, opened for reading and writing, positioned right after
714  *	the member's header, or NULL if the member was nonexistent.
715  *
716  * Side Effects:
717  *	Fill the struct ar_hdr pointed by arHeaderPtr.
718  *-----------------------------------------------------------------------
719  */
720 static FILE *
ArchFindMember(const char * archive,const char * member,struct ar_hdr * arHeaderPtr,const char * mode)721 ArchFindMember(
722     const char	  *archive,   /* Path to the archive */
723     const char	  *member,    /* Name of member. If it is a path, only the
724 			       * last component is used. */
725     struct ar_hdr *arHeaderPtr,/* Pointer to header structure to be filled in */
726     const char	  *mode)      /* mode for opening the stream */
727 {
728     FILE *	  arch;       /* Stream to archive */
729     char	  *cp;
730     char	  magic[SARMAG];
731     size_t	  length;
732 #ifdef SVR4ARCHIVES
733     struct SVR4namelist list;
734 
735     list.fnametab = NULL;
736 #endif
737 
738     arch = fopen(archive, mode);
739     if (arch == NULL)
740 	return NULL;
741 
742     /* Make sure this is an archive we can handle.  */
743     if (fread(magic, SARMAG, 1, arch) != 1 ||
744 	strncmp(magic, ARMAG, SARMAG) != 0) {
745 	    fclose(arch);
746 	    return NULL;
747     }
748 
749     /* Because of space constraints and similar things, files are archived
750      * using their final path components, not the entire thing, so we need
751      * to point 'member' to the final component, if there is one, to make
752      * the comparisons easier...  */
753     cp = strrchr(member, '/');
754     if (cp != NULL)
755 	member = cp + 1;
756 
757     length = strlen(member);
758     if (length >= AR_NAME_SIZE)
759 	length = AR_NAME_SIZE;
760 
761     /* Error handling is simpler than for read_archive, since we just
762      * look for a given member.  */
763     while (fread(arHeaderPtr, sizeof(struct ar_hdr), 1, arch) == 1) {
764 	off_t		  size;       /* Size of archive member */
765 	char		  *memberName;
766 
767 	if (memcmp(arHeaderPtr->ar_fmag, ARFMAG, sizeof(arHeaderPtr->ar_fmag) )
768 	    != 0)
769 	     /* The header is bogus, so the archive is bad.  */
770 	     break;
771 
772 	memberName = arHeaderPtr->ar_name;
773 	if (memcmp(member, memberName, length) == 0) {
774 	    /* If the member's name doesn't take up the entire 'name' field,
775 	     * we have to be careful of matching prefixes. Names are space-
776 	     * padded to the right, so if the character in 'name' at the end
777 	     * of the matched string is anything but a space, this isn't the
778 	     * member we sought.  */
779 #ifdef SVR4ARCHIVES
780 	    if (length < sizeof(arHeaderPtr->ar_name) &&
781 	    	memberName[length] == '/')
782 		length++;
783 #endif
784 	    if (length == sizeof(arHeaderPtr->ar_name) ||
785 		memberName[length] == ' ') {
786 #ifdef SVR4ARCHIVES
787 		efree(list.fnametab);
788 #endif
789 		return arch;
790 	    }
791 	}
792 
793 	size = (off_t) field2long(arHeaderPtr->ar_size,
794 	    sizeof(arHeaderPtr->ar_size));
795 
796 #ifdef SVR4ARCHIVES
797 	    /* svr4 names are slash terminated. Also svr4 extended AR format.
798 	     */
799 	    if (memberName[0] == '/') {
800 		/* svr4 magic mode.  */
801 		memberName = ArchSVR4Entry(&list, arHeaderPtr->ar_name, size,
802 		    arch);
803 		if (memberName == NULL)		/* Invalid data */
804 		    break;
805 		else if (memberName == svr4list)/* List of files entry */
806 		    continue;
807 		/* Got the entry.  */
808 		if (strcmp(memberName, member) == 0) {
809 		    efree(list.fnametab);
810 		    return arch;
811 		}
812 	    }
813 #endif
814 
815 #ifdef AR_EFMT1
816 	/* BSD 4.4 extended AR format: #1/<namelen>, with name as the
817 	 * first <namelen> bytes of the file.  */
818 	if (memcmp(memberName, AR_EFMT1, sizeof(AR_EFMT1) - 1) == 0 &&
819 	    isdigit(memberName[sizeof(AR_EFMT1) - 1])) {
820 	    char	  ename[PATH_MAX];
821 
822 	    int elength = atoi(memberName + sizeof(AR_EFMT1)-1);
823 
824 	    if (elength <= 0 || elength >= PATH_MAX)
825 		break;
826 	    if (fread(ename, elength, 1, arch) != 1)
827 		break;
828 	    if (fseek(arch, -elength, SEEK_CUR) != 0)
829 		break;
830 	    ename[elength] = '\0';
831 	    if (DEBUG(ARCH) || DEBUG(MAKE))
832 		printf("ArchFind: Extended format entry for %s\n", ename);
833 	    /* Found as extended name.	*/
834 	    if (strcmp(ename, member) == 0) {
835 #ifdef SVR4ARCHIVES
836 		efree(list.fnametab);
837 #endif
838 		return arch;
839 		}
840 	}
841 #endif
842 	/* This isn't the member we're after, so we need to advance the
843 	 * stream's pointer to the start of the next header.  */
844 	if (fseek(arch, (size + 1) & ~1, SEEK_CUR) != 0)
845 	    break;
846     }
847 
848     /* We did not find the member, or we ran into an error while reading
849      * the archive.  */
850 #ifdef SVRARCHIVES
851     efree(list.fnametab);
852 #endif
853     fclose(arch);
854     return NULL;
855 }
856 
857 static void
ArchTouch(const char * archive,const char * member)858 ArchTouch(const char *archive, const char *member)
859 {
860     FILE *arch;
861     struct ar_hdr arHeader;
862 
863     arch = ArchFindMember(archive, member, &arHeader, "r+");
864     if (arch != NULL) {
865 	snprintf(arHeader.ar_date, sizeof(arHeader.ar_date), "%-12ld", (long)
866 	    timestamp2time_t(now));
867 	if (fseek(arch, -sizeof(struct ar_hdr), SEEK_CUR) == 0)
868 	    (void)fwrite(&arHeader, sizeof(struct ar_hdr), 1, arch);
869 	fclose(arch);
870     }
871 }
872 
873 /*
874  * Side Effects:
875  *	The modification time of the entire archive is also changed.
876  *	For a library, this could necessitate the re-ranlib'ing of the
877  *	whole thing.
878  */
879 void
Arch_Touch(GNode * gn)880 Arch_Touch(GNode *gn)
881 {
882     ArchTouch(Varq_Value(ARCHIVE_INDEX, gn), Varq_Value(MEMBER_INDEX, gn));
883 }
884 
885 /*ARGSUSED*/
886 void
Arch_TouchLib(GNode * gn UNUSED)887 Arch_TouchLib(GNode *gn UNUSED)
888                      /* ^          Non RANLIBMAG does nothing with it */
889 {
890 #ifdef RANLIBMAG
891     if (gn->path != NULL) {
892 	ArchTouch(gn->path, RANLIBMAG);
893 	set_times(gn->path);
894     }
895 #endif
896 }
897 
898 TIMESTAMP
Arch_MTime(GNode * gn)899 Arch_MTime(GNode *gn)
900 {
901     gn->mtime = ArchMTimeMember(Varq_Value(ARCHIVE_INDEX, gn),
902 	     Varq_Value(MEMBER_INDEX, gn),
903 	     true);
904 
905     return gn->mtime;
906 }
907 
908 TIMESTAMP
Arch_MemMTime(GNode * gn)909 Arch_MemMTime(GNode *gn)
910 {
911     LstNode	  ln;
912 
913     for (ln = Lst_First(&gn->parents); ln != NULL; ln = Lst_Adv(ln)) {
914 	GNode	*pgn;
915 	char	*nameStart,
916 		*nameEnd;
917 
918 	pgn = (GNode *)Lst_Datum(ln);
919 
920 	if (pgn->type & OP_ARCHV) {
921 	    /* If the parent is an archive specification and is being made
922 	     * and its member's name matches the name of the node we were
923 	     * given, record the modification time of the parent in the
924 	     * child. We keep searching its parents in case some other
925 	     * parent requires this child to exist...  */
926 	    if ((nameStart = strchr(pgn->name, '(') ) != NULL) {
927 		nameStart++;
928 		nameEnd = strchr(nameStart, ')');
929 	    } else
930 		nameEnd = NULL;
931 
932 	    if (pgn->make && nameEnd != NULL &&
933 		strncmp(nameStart, gn->name, nameEnd - nameStart) == 0 &&
934 		gn->name[nameEnd-nameStart] == '\0')
935 		    gn->mtime = Arch_MTime(pgn);
936 	} else if (pgn->make) {
937 	    /* Something which isn't a library depends on the existence of
938 	     * this target, so it needs to exist.  */
939 	    ts_set_out_of_date(gn->mtime);
940 	    break;
941 	}
942     }
943     return gn->mtime;
944 }
945 
946 /* If the system can handle the -L flag when linking (or we cannot find
947  * the library), we assume that the user has placed the .LIBRARIES variable
948  * in the final linking command (or the linker will know where to find it)
949  * and set the TARGET variable for this node to be the node's name. Otherwise,
950  * we set the TARGET variable to be the full path of the library,
951  * as returned by Dir_FindFile.
952  */
953 void
Arch_FindLib(GNode * gn,Lst path)954 Arch_FindLib(GNode *gn, Lst path)
955 {
956     char	    *libName;	/* file name for archive */
957     size_t	    length = strlen(gn->name) + 6 - 2;
958 
959     libName = emalloc(length);
960     snprintf(libName, length, "lib%s.a", &gn->name[2]);
961 
962     gn->path = Dir_FindFile(libName, path);
963 
964     free(libName);
965 
966 #ifdef LIBRARIES
967     Varq_Set(TARGET_INDEX, gn->name, gn);
968 #else
969     Varq_Set(TARGET_INDEX, gn->path == NULL ? gn->name : gn->path, gn);
970 #endif /* LIBRARIES */
971 }
972 
973 /*-
974  *-----------------------------------------------------------------------
975  * Arch_LibOODate --
976  *	Decide if a node with the OP_LIB attribute is out-of-date. Called
977  *	from Make_OODate to make its life easier.
978  *
979  *	There are several ways for a library to be out-of-date that are
980  *	not available to ordinary files. In addition, there are ways
981  *	that are open to regular files that are not available to
982  *	libraries. A library that is only used as a source is never
983  *	considered out-of-date by itself. This does not preclude the
984  *	library's modification time from making its parent be out-of-date.
985  *	A library will be considered out-of-date for any of these reasons,
986  *	given that it is a target on a dependency line somewhere:
987  *	    Its modification time is less than that of one of its
988  *		  sources (gn->mtime < gn->cmtime).
989  *	    Its modification time is greater than the time at which the
990  *		  make began (i.e. it's been modified in the course
991  *		  of the make, probably by archiving).
992  *	    The modification time of one of its sources is greater than
993  *		  the one of its RANLIBMAG member (i.e. its table of contents
994  *		  is out-of-date). We don't compare of the archive time
995  *		  vs. TOC time because they can be too close. In my
996  *		  opinion we should not bother with the TOC at all since
997  *		  this is used by 'ar' rules that affect the data contents
998  *		  of the archive, not by ranlib rules, which affect the
999  *		  TOC.
1000  *
1001  * Results:
1002  *	true if the library is out-of-date. false otherwise.
1003  *
1004  * Side Effects:
1005  *	The library will be hashed if it hasn't been already.
1006  *-----------------------------------------------------------------------
1007  */
1008 bool
Arch_LibOODate(GNode * gn)1009 Arch_LibOODate(GNode *gn)
1010 {
1011 #ifdef RANLIBMAG
1012     TIMESTAMP	  modTimeTOC;	/* mod time of __.SYMDEF */
1013 #endif
1014 
1015     if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->children))
1016 	return false;
1017     if (is_strictly_before(now, gn->mtime) || is_strictly_before(gn->mtime, gn->cmtime) ||
1018 	is_out_of_date(gn->mtime))
1019 	return true;
1020 #ifdef RANLIBMAG
1021     /* non existent libraries are always out-of-date.  */
1022     if (gn->path == NULL)
1023 	return true;
1024     modTimeTOC = ArchMTimeMember(gn->path, RANLIBMAG, false);
1025 
1026     if (!is_out_of_date(modTimeTOC)) {
1027 	if (DEBUG(ARCH) || DEBUG(MAKE))
1028 	    printf("%s modified %s...", RANLIBMAG, Targ_FmtTime(modTimeTOC));
1029 	return is_strictly_before(modTimeTOC, gn->cmtime);
1030     }
1031     /* A library w/o a table of contents is out-of-date.  */
1032     if (DEBUG(ARCH) || DEBUG(MAKE))
1033 	printf("No t.o.c....");
1034     return true;
1035 #else
1036     return false;
1037 #endif
1038 }
1039 
1040 void
Arch_Init(void)1041 Arch_Init(void)
1042 {
1043     ohash_init(&archives, 4, &arch_info);
1044 }
1045 
1046 #ifdef CLEANUP
1047 void
Arch_End(void)1048 Arch_End(void)
1049 {
1050     Arch *e;
1051     unsigned int i;
1052 
1053     for (e = ohash_first(&archives, &i); e != NULL;
1054 	e = ohash_next(&archives, &i))
1055 	    ArchFree(e);
1056     ohash_delete(&archives);
1057 }
1058 #endif
1059 
1060 bool
Arch_IsLib(GNode * gn)1061 Arch_IsLib(GNode *gn)
1062 {
1063     char buf[SARMAG];
1064     int fd;
1065 
1066     if (gn->path == NULL || (fd = open(gn->path, O_RDONLY)) == -1)
1067 	return false;
1068 
1069     if (read(fd, buf, SARMAG) != SARMAG) {
1070 	(void)close(fd);
1071 	return false;
1072     }
1073 
1074     (void)close(fd);
1075 
1076     return memcmp(buf, ARMAG, SARMAG) == 0;
1077 }
1078