xref: /freebsd/contrib/bmake/arch.c (revision 77013d11e6483b970af25e13c9b892075742f7e5)
1 /*	$NetBSD: arch.c,v 1.200 2021/05/30 21:16:54 rillig Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * Copyright (c) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *	This product includes software developed by the University of
53  *	California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 /*
72  * Manipulate libraries, archives and their members.
73  *
74  * The first time an archive is referenced, all of its members' headers are
75  * read and cached and the archive closed again.  All cached archives are kept
76  * on a list which is searched each time an archive member is referenced.
77  *
78  * The interface to this module is:
79  *
80  *	Arch_Init	Initialize this module.
81  *
82  *	Arch_End	Clean up this module.
83  *
84  *	Arch_ParseArchive
85  *			Parse an archive specification such as
86  *			"archive.a(member1 member2)".
87  *
88  *	Arch_Touch	Alter the modification time of the archive
89  *			member described by the given node to be
90  *			the time when make was started.
91  *
92  *	Arch_TouchLib	Update the modification time of the library
93  *			described by the given node. This is special
94  *			because it also updates the modification time
95  *			of the library's table of contents.
96  *
97  *	Arch_UpdateMTime
98  *			Find the modification time of a member of
99  *			an archive *in the archive* and place it in the
100  *			member's GNode.
101  *
102  *	Arch_UpdateMemberMTime
103  *			Find the modification time of a member of
104  *			an archive. Called when the member doesn't
105  *			already exist. Looks in the archive for the
106  *			modification time. Returns the modification
107  *			time.
108  *
109  *	Arch_FindLib	Search for a library along a path. The
110  *			library name in the GNode should be in
111  *			-l<name> format.
112  *
113  *	Arch_LibOODate	Decide if a library node is out-of-date.
114  */
115 
116 #ifdef HAVE_CONFIG_H
117 # include "config.h"
118 #endif
119 #include <sys/types.h>
120 #include <sys/stat.h>
121 #include <sys/time.h>
122 #include <sys/param.h>
123 #ifdef HAVE_AR_H
124 #include <ar.h>
125 #else
126 struct ar_hdr {
127         char ar_name[16];               /* name */
128         char ar_date[12];               /* modification time */
129         char ar_uid[6];                 /* user id */
130         char ar_gid[6];                 /* group id */
131         char ar_mode[8];                /* octal file permissions */
132         char ar_size[10];               /* size in bytes */
133 #ifndef ARFMAG
134 #define ARFMAG  "`\n"
135 #endif
136         char ar_fmag[2];                /* consistency check */
137 };
138 #endif
139 #if defined(HAVE_RANLIB_H) && !(defined(__ELF__) || defined(NO_RANLIB))
140 #include <ranlib.h>
141 #endif
142 #ifdef HAVE_UTIME_H
143 #include <utime.h>
144 #endif
145 
146 #include "make.h"
147 #include "dir.h"
148 
149 /*	"@(#)arch.c	8.2 (Berkeley) 1/2/94"	*/
150 MAKE_RCSID("$NetBSD: arch.c,v 1.200 2021/05/30 21:16:54 rillig Exp $");
151 
152 typedef struct List ArchList;
153 typedef struct ListNode ArchListNode;
154 
155 static ArchList archives;	/* The archives we've already examined */
156 
157 typedef struct Arch {
158 	char *name;		/* Name of archive */
159 	HashTable members;	/* All the members of the archive described
160 				 * by <name, struct ar_hdr *> key/value pairs */
161 	char *fnametab;		/* Extended name table strings */
162 	size_t fnamesize;	/* Size of the string table */
163 } Arch;
164 
165 static FILE *ArchFindMember(const char *, const char *,
166 			    struct ar_hdr *, const char *);
167 #if defined(__svr4__) || defined(__SVR4) || defined(__ELF__)
168 #define SVR4ARCHIVES
169 static int ArchSVR4Entry(Arch *, char *, size_t, FILE *);
170 #endif
171 
172 
173 #if defined(_AIX)
174 # define AR_NAME _ar_name.ar_name
175 # define AR_FMAG _ar_name.ar_fmag
176 # define SARMAG  SAIAMAG
177 # define ARMAG   AIAMAG
178 # define ARFMAG  AIAFMAG
179 #endif
180 #ifndef  AR_NAME
181 # define AR_NAME ar_name
182 #endif
183 #ifndef  AR_DATE
184 # define AR_DATE ar_date
185 #endif
186 #ifndef  AR_SIZE
187 # define AR_SIZE ar_size
188 #endif
189 #ifndef  AR_FMAG
190 # define AR_FMAG ar_fmag
191 #endif
192 #ifndef ARMAG
193 # define ARMAG	"!<arch>\n"
194 #endif
195 #ifndef SARMAG
196 # define SARMAG	8
197 #endif
198 
199 
200 #ifdef CLEANUP
201 static void
202 ArchFree(void *ap)
203 {
204 	Arch *a = ap;
205 	HashIter hi;
206 
207 	/* Free memory from hash entries */
208 	HashIter_Init(&hi, &a->members);
209 	while (HashIter_Next(&hi) != NULL)
210 		free(hi.entry->value);
211 
212 	free(a->name);
213 	free(a->fnametab);
214 	HashTable_Done(&a->members);
215 	free(a);
216 }
217 #endif
218 
219 /* Return "archive(member)". */
220 static char *
221 FullName(const char *archive, const char *member)
222 {
223 	size_t len1 = strlen(archive);
224 	size_t len3 = strlen(member);
225 	char *result = bmake_malloc(len1 + 1 + len3 + 1 + 1);
226 	memcpy(result, archive, len1);
227 	memcpy(result + len1, "(", 1);
228 	memcpy(result + len1 + 1, member, len3);
229 	memcpy(result + len1 + 1 + len3, ")", 1 + 1);
230 	return result;
231 }
232 
233 /*
234  * Parse an archive specification such as "archive.a(member1 member2.${EXT})",
235  * adding nodes for the expanded members to gns.  Nodes are created as
236  * necessary.
237  *
238  * Input:
239  *	pp		The start of the specification.
240  *	gns		The list on which to place the nodes.
241  *	scope		The scope in which to expand variables.
242  *
243  * Output:
244  *	return		True if it was a valid specification.
245  *	*pp		Points to the first non-space after the archive spec.
246  */
247 bool
248 Arch_ParseArchive(char **pp, GNodeList *gns, GNode *scope)
249 {
250 	char *cp;		/* Pointer into line */
251 	GNode *gn;		/* New node */
252 	MFStr libName;		/* Library-part of specification */
253 	char *memName;		/* Member-part of specification */
254 	char saveChar;		/* Ending delimiter of member-name */
255 	bool expandLibName;	/* Whether the parsed libName contains
256 				 * variable expressions that need to be
257 				 * expanded */
258 
259 	libName = MFStr_InitRefer(*pp);
260 	expandLibName = false;
261 
262 	for (cp = libName.str; *cp != '(' && *cp != '\0';) {
263 		if (*cp == '$') {
264 			/* Expand nested variable expressions. */
265 			/* XXX: This code can probably be shortened. */
266 			const char *nested_p = cp;
267 			FStr result;
268 			bool isError;
269 
270 			/* XXX: is expanded twice: once here and once below */
271 			(void)Var_Parse(&nested_p, scope,
272 			    VARE_UNDEFERR, &result);
273 			/* TODO: handle errors */
274 			isError = result.str == var_Error;
275 			FStr_Done(&result);
276 			if (isError)
277 				return false;
278 
279 			expandLibName = true;
280 			cp += nested_p - cp;
281 		} else
282 			cp++;
283 	}
284 
285 	*cp++ = '\0';
286 	if (expandLibName) {
287 		char *expanded;
288 		(void)Var_Subst(libName.str, scope, VARE_UNDEFERR, &expanded);
289 		/* TODO: handle errors */
290 		libName = MFStr_InitOwn(expanded);
291 	}
292 
293 
294 	for (;;) {
295 		/*
296 		 * First skip to the start of the member's name, mark that
297 		 * place and skip to the end of it (either white-space or
298 		 * a close paren).
299 		 */
300 		bool doSubst = false;
301 
302 		pp_skip_whitespace(&cp);
303 
304 		memName = cp;
305 		while (*cp != '\0' && *cp != ')' && !ch_isspace(*cp)) {
306 			if (*cp == '$') {
307 				/* Expand nested variable expressions. */
308 				/* XXX: This code can probably be shortened. */
309 				FStr result;
310 				bool isError;
311 				const char *nested_p = cp;
312 
313 				(void)Var_Parse(&nested_p, scope,
314 				    VARE_UNDEFERR, &result);
315 				/* TODO: handle errors */
316 				isError = result.str == var_Error;
317 				FStr_Done(&result);
318 
319 				if (isError)
320 					return false;
321 
322 				doSubst = true;
323 				cp += nested_p - cp;
324 			} else {
325 				cp++;
326 			}
327 		}
328 
329 		/*
330 		 * If the specification ends without a closing parenthesis,
331 		 * chances are there's something wrong (like a missing
332 		 * backslash), so it's better to return failure than allow
333 		 * such things to happen
334 		 */
335 		if (*cp == '\0') {
336 			Parse_Error(PARSE_FATAL,
337 				    "No closing parenthesis "
338 				    "in archive specification");
339 			return false;
340 		}
341 
342 		/*
343 		 * If we didn't move anywhere, we must be done
344 		 */
345 		if (cp == memName)
346 			break;
347 
348 		saveChar = *cp;
349 		*cp = '\0';
350 
351 		/*
352 		 * XXX: This should be taken care of intelligently by
353 		 * SuffExpandChildren, both for the archive and the member
354 		 * portions.
355 		 */
356 		/*
357 		 * If member contains variables, try and substitute for them.
358 		 * This will slow down archive specs with dynamic sources, of
359 		 * course, since we'll be (non-)substituting them three
360 		 * times, but them's the breaks -- we need to do this since
361 		 * SuffExpandChildren calls us, otherwise we could assume the
362 		 * thing would be taken care of later.
363 		 */
364 		if (doSubst) {
365 			char *fullName;
366 			char *p;
367 			char *unexpandedMemName = memName;
368 
369 			(void)Var_Subst(memName, scope, VARE_UNDEFERR,
370 			    &memName);
371 			/* TODO: handle errors */
372 
373 			/*
374 			 * Now form an archive spec and recurse to deal with
375 			 * nested variables and multi-word variable values.
376 			 */
377 			fullName = FullName(libName.str, memName);
378 			p = fullName;
379 
380 			if (strchr(memName, '$') != NULL &&
381 			    strcmp(memName, unexpandedMemName) == 0) {
382 				/*
383 				 * Must contain dynamic sources, so we can't
384 				 * deal with it now. Just create an ARCHV node
385 				 * for the thing and let SuffExpandChildren
386 				 * handle it.
387 				 */
388 				gn = Targ_GetNode(fullName);
389 				gn->type |= OP_ARCHV;
390 				Lst_Append(gns, gn);
391 
392 			} else if (!Arch_ParseArchive(&p, gns, scope)) {
393 				/* Error in nested call. */
394 				free(fullName);
395 				/* XXX: does unexpandedMemName leak? */
396 				return false;
397 			}
398 			free(fullName);
399 			/* XXX: does unexpandedMemName leak? */
400 
401 		} else if (Dir_HasWildcards(memName)) {
402 			StringList members = LST_INIT;
403 			SearchPath_Expand(&dirSearchPath, memName, &members);
404 
405 			while (!Lst_IsEmpty(&members)) {
406 				char *member = Lst_Dequeue(&members);
407 				char *fullname = FullName(libName.str, member);
408 				free(member);
409 
410 				gn = Targ_GetNode(fullname);
411 				free(fullname);
412 
413 				gn->type |= OP_ARCHV;
414 				Lst_Append(gns, gn);
415 			}
416 			Lst_Done(&members);
417 
418 		} else {
419 			char *fullname = FullName(libName.str, memName);
420 			gn = Targ_GetNode(fullname);
421 			free(fullname);
422 
423 			/*
424 			 * We've found the node, but have to make sure the
425 			 * rest of the world knows it's an archive member,
426 			 * without having to constantly check for parentheses,
427 			 * so we type the thing with the OP_ARCHV bit before
428 			 * we place it on the end of the provided list.
429 			 */
430 			gn->type |= OP_ARCHV;
431 			Lst_Append(gns, gn);
432 		}
433 		if (doSubst)
434 			free(memName);
435 
436 		*cp = saveChar;
437 	}
438 
439 	MFStr_Done(&libName);
440 
441 	cp++;			/* skip the ')' */
442 	/* We promised that pp would be set up at the next non-space. */
443 	pp_skip_whitespace(&cp);
444 	*pp = cp;
445 	return true;
446 }
447 
448 /*
449  * Locate a member of an archive, given the path of the archive and the path
450  * of the desired member.
451  *
452  * Input:
453  *	archive		Path to the archive
454  *	member		Name of member; only its basename is used.
455  *	addToCache	True if archive should be cached if not already so.
456  *
457  * Results:
458  *	The ar_hdr for the member, or NULL.
459  *
460  * See ArchFindMember for an almost identical copy of this code.
461  */
462 static struct ar_hdr *
463 ArchStatMember(const char *archive, const char *member, bool addToCache)
464 {
465 #define AR_MAX_NAME_LEN (sizeof arh.ar_name - 1)
466 	FILE *arch;
467 	size_t size;		/* Size of archive member */
468 	char magic[SARMAG];
469 	ArchListNode *ln;
470 	Arch *ar;		/* Archive descriptor */
471 	struct ar_hdr arh;	/* archive-member header for reading archive */
472 	char memName[MAXPATHLEN + 1];
473 	/* Current member name while hashing. */
474 
475 	/*
476 	 * Because of space constraints and similar things, files are archived
477 	 * using their basename, not the entire path.
478 	 */
479 	member = str_basename(member);
480 
481 	for (ln = archives.first; ln != NULL; ln = ln->next) {
482 		const Arch *a = ln->datum;
483 		if (strcmp(a->name, archive) == 0)
484 			break;
485 	}
486 
487 	if (ln != NULL) {
488 		struct ar_hdr *hdr;
489 
490 		ar = ln->datum;
491 		hdr = HashTable_FindValue(&ar->members, member);
492 		if (hdr != NULL)
493 			return hdr;
494 
495 		{
496 			/* Try truncated name */
497 			char copy[AR_MAX_NAME_LEN + 1];
498 			size_t len = strlen(member);
499 
500 			if (len > AR_MAX_NAME_LEN) {
501 				snprintf(copy, sizeof copy, "%s", member);
502 				hdr = HashTable_FindValue(&ar->members, copy);
503 			}
504 			return hdr;
505 		}
506 	}
507 
508 	if (!addToCache) {
509 		/*
510 		 * Caller doesn't want the thing cached, just use
511 		 * ArchFindMember to read the header for the member out and
512 		 * close down the stream again. Since the archive is not to be
513 		 * cached, we assume there's no need to allocate extra room
514 		 * for the header we're returning, so just declare it static.
515 		 */
516 		static struct ar_hdr sarh;
517 
518 		arch = ArchFindMember(archive, member, &sarh, "r");
519 		if (arch == NULL)
520 			return NULL;
521 
522 		fclose(arch);
523 		return &sarh;
524 	}
525 
526 	/*
527 	 * We don't have this archive on the list yet, so we want to find out
528 	 * everything that's in it and cache it so we can get at it quickly.
529 	 */
530 	arch = fopen(archive, "r");
531 	if (arch == NULL)
532 		return NULL;
533 
534 	/*
535 	 * We use the ARMAG string to make sure this is an archive we
536 	 * can handle...
537 	 */
538 	if (fread(magic, SARMAG, 1, arch) != 1 ||
539 	    strncmp(magic, ARMAG, SARMAG) != 0) {
540 		(void)fclose(arch);
541 		return NULL;
542 	}
543 
544 	ar = bmake_malloc(sizeof *ar);
545 	ar->name = bmake_strdup(archive);
546 	ar->fnametab = NULL;
547 	ar->fnamesize = 0;
548 	HashTable_Init(&ar->members);
549 	memName[AR_MAX_NAME_LEN] = '\0';
550 
551 	while (fread(&arh, sizeof arh, 1, arch) == 1) {
552 		char *nameend;
553 
554 		/* If the header is bogus, there's no way we can recover. */
555 		if (strncmp(arh.AR_FMAG, ARFMAG, sizeof arh.AR_FMAG) != 0)
556 			goto badarch;
557 
558 		/*
559 		 * We need to advance the stream's pointer to the start of the
560 		 * next header. Files are padded with newlines to an even-byte
561 		 * boundary, so we need to extract the size of the file from
562 		 * the 'size' field of the header and round it up during the
563 		 * seek.
564 		 */
565 		arh.AR_SIZE[sizeof arh.AR_SIZE - 1] = '\0';
566 		size = (size_t)strtol(arh.AR_SIZE, NULL, 10);
567 
568 		memcpy(memName, arh.AR_NAME, sizeof arh.AR_NAME);
569 		nameend = memName + AR_MAX_NAME_LEN;
570 		while (nameend > memName && *nameend == ' ')
571 			nameend--;
572 		nameend[1] = '\0';
573 
574 #ifdef SVR4ARCHIVES
575 		/*
576 		 * svr4 names are slash-terminated.
577 		 * Also svr4 extended the AR format.
578 		 */
579 		if (memName[0] == '/') {
580 			/* svr4 magic mode; handle it */
581 			switch (ArchSVR4Entry(ar, memName, size, arch)) {
582 			case -1:	/* Invalid data */
583 				goto badarch;
584 			case 0:		/* List of files entry */
585 				continue;
586 			default:	/* Got the entry */
587 				break;
588 			}
589 		} else {
590 			if (nameend[0] == '/')
591 				nameend[0] = '\0';
592 		}
593 #endif
594 
595 #ifdef AR_EFMT1
596 		/*
597 		 * BSD 4.4 extended AR format: #1/<namelen>, with name as the
598 		 * first <namelen> bytes of the file
599 		 */
600 		if (strncmp(memName, AR_EFMT1, sizeof AR_EFMT1 - 1) == 0 &&
601 		    ch_isdigit(memName[sizeof AR_EFMT1 - 1])) {
602 
603 			int elen = atoi(memName + sizeof AR_EFMT1 - 1);
604 
605 			if ((unsigned int)elen > MAXPATHLEN)
606 				goto badarch;
607 			if (fread(memName, (size_t)elen, 1, arch) != 1)
608 				goto badarch;
609 			memName[elen] = '\0';
610 			if (fseek(arch, -elen, SEEK_CUR) != 0)
611 				goto badarch;
612 			if (DEBUG(ARCH) || DEBUG(MAKE))
613 				debug_printf(
614 				    "ArchStatMember: "
615 				    "Extended format entry for %s\n",
616 				    memName);
617 		}
618 #endif
619 
620 		{
621 			struct ar_hdr *cached_hdr = bmake_malloc(
622 			    sizeof *cached_hdr);
623 			memcpy(cached_hdr, &arh, sizeof arh);
624 			HashTable_Set(&ar->members, memName, cached_hdr);
625 		}
626 
627 		if (fseek(arch, ((long)size + 1) & ~1, SEEK_CUR) != 0)
628 			goto badarch;
629 	}
630 
631 	fclose(arch);
632 
633 	Lst_Append(&archives, ar);
634 
635 	/*
636 	 * Now that the archive has been read and cached, we can look into
637 	 * the addToCache table to find the desired member's header.
638 	 */
639 	return HashTable_FindValue(&ar->members, member);
640 
641 badarch:
642 	fclose(arch);
643 	HashTable_Done(&ar->members);
644 	free(ar->fnametab);
645 	free(ar);
646 	return NULL;
647 }
648 
649 #ifdef SVR4ARCHIVES
650 /*
651  * Parse an SVR4 style entry that begins with a slash.
652  * If it is "//", then load the table of filenames.
653  * If it is "/<offset>", then try to substitute the long file name
654  * from offset of a table previously read.
655  * If a table is read, the file pointer is moved to the next archive member.
656  *
657  * Results:
658  *	-1: Bad data in archive
659  *	 0: A table was loaded from the file
660  *	 1: Name was successfully substituted from table
661  *	 2: Name was not successfully substituted from table
662  */
663 static int
664 ArchSVR4Entry(Arch *ar, char *inout_name, size_t size, FILE *arch)
665 {
666 #define ARLONGNAMES1 "//"
667 #define ARLONGNAMES2 "/ARFILENAMES"
668 	size_t entry;
669 	char *ptr, *eptr;
670 
671 	if (strncmp(inout_name, ARLONGNAMES1, sizeof ARLONGNAMES1 - 1) == 0 ||
672 	    strncmp(inout_name, ARLONGNAMES2, sizeof ARLONGNAMES2 - 1) == 0) {
673 
674 		if (ar->fnametab != NULL) {
675 			DEBUG0(ARCH,
676 			       "Attempted to redefine an SVR4 name table\n");
677 			return -1;
678 		}
679 
680 		/*
681 		 * This is a table of archive names, so we build one for
682 		 * ourselves
683 		 */
684 		ar->fnametab = bmake_malloc(size);
685 		ar->fnamesize = size;
686 
687 		if (fread(ar->fnametab, size, 1, arch) != 1) {
688 			DEBUG0(ARCH, "Reading an SVR4 name table failed\n");
689 			return -1;
690 		}
691 		eptr = ar->fnametab + size;
692 		for (entry = 0, ptr = ar->fnametab; ptr < eptr; ptr++)
693 			if (*ptr == '/') {
694 				entry++;
695 				*ptr = '\0';
696 			}
697 		DEBUG1(ARCH, "Found svr4 archive name table with %lu entries\n",
698 		       (unsigned long)entry);
699 		return 0;
700 	}
701 
702 	if (inout_name[1] == ' ' || inout_name[1] == '\0')
703 		return 2;
704 
705 	entry = (size_t)strtol(&inout_name[1], &eptr, 0);
706 	if ((*eptr != ' ' && *eptr != '\0') || eptr == &inout_name[1]) {
707 		DEBUG1(ARCH, "Could not parse SVR4 name %s\n", inout_name);
708 		return 2;
709 	}
710 	if (entry >= ar->fnamesize) {
711 		DEBUG2(ARCH, "SVR4 entry offset %s is greater than %lu\n",
712 		       inout_name, (unsigned long)ar->fnamesize);
713 		return 2;
714 	}
715 
716 	DEBUG2(ARCH, "Replaced %s with %s\n", inout_name, &ar->fnametab[entry]);
717 
718 	snprintf(inout_name, MAXPATHLEN + 1, "%s", &ar->fnametab[entry]);
719 	return 1;
720 }
721 #endif
722 
723 
724 static bool
725 ArchiveMember_HasName(const struct ar_hdr *hdr,
726 		      const char *name, size_t namelen)
727 {
728 	const size_t ar_name_len = sizeof hdr->AR_NAME;
729 	const char *ar_name = hdr->AR_NAME;
730 
731 	if (strncmp(ar_name, name, namelen) != 0)
732 		return false;
733 
734 	if (namelen >= ar_name_len)
735 		return namelen == ar_name_len;
736 
737 	/* hdr->AR_NAME is space-padded to the right. */
738 	if (ar_name[namelen] == ' ')
739 		return true;
740 
741 	/* In archives created by GNU binutils 2.27, the member names end with
742 	 * a slash. */
743 	if (ar_name[namelen] == '/' &&
744 	    (namelen == ar_name_len || ar_name[namelen + 1] == ' '))
745 		return true;
746 
747 	return false;
748 }
749 
750 /*
751  * Locate a member of an archive, given the path of the archive and the path
752  * of the desired member.
753  *
754  * Input:
755  *	archive		Path to the archive
756  *	member		Name of member. If it is a path, only the last
757  *			component is used.
758  *	out_arh		Archive header to be filled in
759  *	mode		"r" for read-only access, "r+" for read-write access
760  *
761  * Output:
762  *	return		The archive file, positioned at the start of the
763  *			member's struct ar_hdr, or NULL if the member doesn't
764  *			exist.
765  *	*out_arh	The current struct ar_hdr for member.
766  *
767  * See ArchStatMember for an almost identical copy of this code.
768  */
769 static FILE *
770 ArchFindMember(const char *archive, const char *member, struct ar_hdr *out_arh,
771 	       const char *mode)
772 {
773 	FILE *arch;		/* Stream to archive */
774 	int size;		/* Size of archive member */
775 	char magic[SARMAG];
776 	size_t len;
777 
778 	arch = fopen(archive, mode);
779 	if (arch == NULL)
780 		return NULL;
781 
782 	/*
783 	 * We use the ARMAG string to make sure this is an archive we
784 	 * can handle...
785 	 */
786 	if (fread(magic, SARMAG, 1, arch) != 1 ||
787 	    strncmp(magic, ARMAG, SARMAG) != 0) {
788 		fclose(arch);
789 		return NULL;
790 	}
791 
792 	/*
793 	 * Because of space constraints and similar things, files are archived
794 	 * using their basename, not the entire path.
795 	 */
796 	member = str_basename(member);
797 
798 	len = strlen(member);
799 
800 	while (fread(out_arh, sizeof *out_arh, 1, arch) == 1) {
801 
802 		if (strncmp(out_arh->AR_FMAG, ARFMAG,
803 			    sizeof out_arh->AR_FMAG) != 0) {
804 			/*
805 			 * The header is bogus, so the archive is bad
806 			 * and there's no way we can recover...
807 			 */
808 			fclose(arch);
809 			return NULL;
810 		}
811 
812 		DEBUG5(ARCH, "Reading archive %s member %.*s mtime %.*s\n",
813 		       archive,
814 		       (int)sizeof out_arh->AR_NAME, out_arh->AR_NAME,
815 		       (int)sizeof out_arh->ar_date, out_arh->ar_date);
816 
817 		if (ArchiveMember_HasName(out_arh, member, len)) {
818 			/*
819 			 * To make life easier for callers that want to update
820 			 * the archive, we reposition the file at the start of
821 			 * the header we just read before we return the
822 			 * stream. In a more general situation, it might be
823 			 * better to leave the file at the actual member,
824 			 * rather than its header, but not here.
825 			 */
826 			if (fseek(arch, -(long)sizeof *out_arh, SEEK_CUR) !=
827 			    0) {
828 				fclose(arch);
829 				return NULL;
830 			}
831 			return arch;
832 		}
833 
834 #ifdef AR_EFMT1
835 		/*
836 		 * BSD 4.4 extended AR format: #1/<namelen>, with name as the
837 		 * first <namelen> bytes of the file
838 		 */
839 		if (strncmp(out_arh->AR_NAME, AR_EFMT1, sizeof AR_EFMT1 - 1) ==
840 		    0 &&
841 		    (ch_isdigit(out_arh->AR_NAME[sizeof AR_EFMT1 - 1]))) {
842 			int elen = atoi(&out_arh->AR_NAME[sizeof AR_EFMT1 - 1]);
843 			char ename[MAXPATHLEN + 1];
844 
845 			if ((unsigned int)elen > MAXPATHLEN) {
846 				fclose(arch);
847 				return NULL;
848 			}
849 			if (fread(ename, (size_t)elen, 1, arch) != 1) {
850 				fclose(arch);
851 				return NULL;
852 			}
853 			ename[elen] = '\0';
854 			if (DEBUG(ARCH) || DEBUG(MAKE))
855 				debug_printf(
856 				    "ArchFindMember: "
857 				    "Extended format entry for %s\n",
858 				    ename);
859 			if (strncmp(ename, member, len) == 0) {
860 				/* Found as extended name */
861 				if (fseek(arch,
862 					  -(long)sizeof(struct ar_hdr) - elen,
863 					  SEEK_CUR) != 0) {
864 					fclose(arch);
865 					return NULL;
866 				}
867 				return arch;
868 			}
869 			if (fseek(arch, -elen, SEEK_CUR) != 0) {
870 				fclose(arch);
871 				return NULL;
872 			}
873 		}
874 #endif
875 
876 		/*
877 		 * This isn't the member we're after, so we need to advance the
878 		 * stream's pointer to the start of the next header. Files are
879 		 * padded with newlines to an even-byte boundary, so we need to
880 		 * extract the size of the file from the 'size' field of the
881 		 * header and round it up during the seek.
882 		 */
883 		out_arh->AR_SIZE[sizeof out_arh->AR_SIZE - 1] = '\0';
884 		size = (int)strtol(out_arh->AR_SIZE, NULL, 10);
885 		if (fseek(arch, (size + 1) & ~1, SEEK_CUR) != 0) {
886 			fclose(arch);
887 			return NULL;
888 		}
889 	}
890 
891 	fclose(arch);
892 	return NULL;
893 }
894 
895 /*
896  * Touch a member of an archive, on disk.
897  * The GNode's modification time is left as-is.
898  *
899  * The st_mtime of the entire archive is also changed.
900  * For a library, it may be required to run ranlib after this.
901  *
902  * Input:
903  *	gn		Node of member to touch
904  *
905  * Results:
906  *	The 'time' field of the member's header is updated.
907  */
908 void
909 Arch_Touch(GNode *gn)
910 {
911 	FILE *f;
912 	struct ar_hdr arh;
913 
914 	f = ArchFindMember(GNode_VarArchive(gn), GNode_VarMember(gn), &arh,
915 			   "r+");
916 	if (f == NULL)
917 		return;
918 
919 	snprintf(arh.ar_date, sizeof arh.ar_date, "%-ld", (unsigned long)now);
920 	(void)fwrite(&arh, sizeof arh, 1, f);
921 	fclose(f);		/* TODO: handle errors */
922 }
923 
924 /*
925  * Given a node which represents a library, touch the thing, making sure that
926  * the table of contents is also touched.
927  *
928  * Both the modification time of the library and of the RANLIBMAG member are
929  * set to 'now'.
930  */
931 /*ARGSUSED*/
932 void
933 Arch_TouchLib(GNode *gn MAKE_ATTR_UNUSED)
934 {
935 #ifdef RANLIBMAG
936 	FILE *f;
937 	struct ar_hdr arh;	/* Header describing table of contents */
938 	struct utimbuf times;
939 
940 	f = ArchFindMember(gn->path, RANLIBMAG, &arh, "r+");
941 	if (f == NULL)
942 		return;
943 
944 	snprintf(arh.ar_date, sizeof arh.ar_date, "%-ld", (unsigned long)now);
945 	(void)fwrite(&arh, sizeof arh, 1, f);
946 	fclose(f);		/* TODO: handle errors */
947 
948 	times.actime = times.modtime = now;
949 	utime(gn->path, &times);	/* TODO: handle errors */
950 #endif
951 }
952 
953 /*
954  * Update the mtime of the GNode with the mtime from the archive member on
955  * disk (or in the cache).
956  */
957 void
958 Arch_UpdateMTime(GNode *gn)
959 {
960 	struct ar_hdr *arh;
961 
962 	arh = ArchStatMember(GNode_VarArchive(gn), GNode_VarMember(gn), true);
963 	if (arh != NULL)
964 		gn->mtime = (time_t)strtol(arh->ar_date, NULL, 10);
965 	else
966 		gn->mtime = 0;
967 }
968 
969 /*
970  * Given a nonexistent archive member's node, update gn->mtime from its
971  * archived form, if it exists.
972  */
973 void
974 Arch_UpdateMemberMTime(GNode *gn)
975 {
976 	GNodeListNode *ln;
977 
978 	for (ln = gn->parents.first; ln != NULL; ln = ln->next) {
979 		GNode *pgn = ln->datum;
980 
981 		if (pgn->type & OP_ARCHV) {
982 			/*
983 			 * If the parent is an archive specification and is
984 			 * being made and its member's name matches the name
985 			 * of the node we were given, record the modification
986 			 * time of the parent in the child. We keep searching
987 			 * its parents in case some other parent requires this
988 			 * child to exist.
989 			 */
990 			const char *nameStart = strchr(pgn->name, '(') + 1;
991 			const char *nameEnd = strchr(nameStart, ')');
992 			size_t nameLen = (size_t)(nameEnd - nameStart);
993 
994 			if ((pgn->flags & REMAKE) &&
995 			    strncmp(nameStart, gn->name, nameLen) == 0) {
996 				Arch_UpdateMTime(pgn);
997 				gn->mtime = pgn->mtime;
998 			}
999 		} else if (pgn->flags & REMAKE) {
1000 			/*
1001 			 * Something which isn't a library depends on the
1002 			 * existence of this target, so it needs to exist.
1003 			 */
1004 			gn->mtime = 0;
1005 			break;
1006 		}
1007 	}
1008 }
1009 
1010 /*
1011  * Search for a library along the given search path.
1012  *
1013  * The node's 'path' field is set to the found path (including the
1014  * actual file name, not -l...). If the system can handle the -L
1015  * flag when linking (or we cannot find the library), we assume that
1016  * the user has placed the .LIBS variable in the final linking
1017  * command (or the linker will know where to find it) and set the
1018  * TARGET variable for this node to be the node's name. Otherwise,
1019  * we set the TARGET variable to be the full path of the library,
1020  * as returned by Dir_FindFile.
1021  *
1022  * Input:
1023  *	gn		Node of library to find
1024  */
1025 void
1026 Arch_FindLib(GNode *gn, SearchPath *path)
1027 {
1028 	char *libName = str_concat3("lib", gn->name + 2, ".a");
1029 	gn->path = Dir_FindFile(libName, path);
1030 	free(libName);
1031 
1032 #ifdef LIBRARIES
1033 	Var_Set(gn, TARGET, gn->name);
1034 #else
1035 	Var_Set(gn, TARGET, GNode_Path(gn));
1036 #endif
1037 }
1038 
1039 /*
1040  * Decide if a node with the OP_LIB attribute is out-of-date. Called from
1041  * GNode_IsOODate to make its life easier.
1042  * The library is cached if it hasn't been already.
1043  *
1044  * There are several ways for a library to be out-of-date that are
1045  * not available to ordinary files. In addition, there are ways
1046  * that are open to regular files that are not available to
1047  * libraries.
1048  *
1049  * A library that is only used as a source is never
1050  * considered out-of-date by itself. This does not preclude the
1051  * library's modification time from making its parent be out-of-date.
1052  * A library will be considered out-of-date for any of these reasons,
1053  * given that it is a target on a dependency line somewhere:
1054  *
1055  *	Its modification time is less than that of one of its sources
1056  *	(gn->mtime < gn->youngestChild->mtime).
1057  *
1058  *	Its modification time is greater than the time at which the make
1059  *	began (i.e. it's been modified in the course of the make, probably
1060  *	by archiving).
1061  *
1062  *	The modification time of one of its sources is greater than the one
1063  *	of its RANLIBMAG member (i.e. its table of contents is out-of-date).
1064  *	We don't compare the archive time vs. TOC time because they can be
1065  *	too close. In my opinion we should not bother with the TOC at all
1066  *	since this is used by 'ar' rules that affect the data contents of the
1067  *	archive, not by ranlib rules, which affect the TOC.
1068  */
1069 bool
1070 Arch_LibOODate(GNode *gn)
1071 {
1072 	bool oodate;
1073 
1074 	if (gn->type & OP_PHONY) {
1075 		oodate = true;
1076 	} else if (!GNode_IsTarget(gn) && Lst_IsEmpty(&gn->children)) {
1077 		oodate = false;
1078 	} else if ((!Lst_IsEmpty(&gn->children) && gn->youngestChild == NULL) ||
1079 		   (gn->mtime > now) ||
1080 		   (gn->youngestChild != NULL &&
1081 		    gn->mtime < gn->youngestChild->mtime)) {
1082 		oodate = true;
1083 	} else {
1084 #ifdef RANLIBMAG
1085 		struct ar_hdr *arh;	/* Header for __.SYMDEF */
1086 		int modTimeTOC;		/* The table-of-contents' mod time */
1087 
1088 		arh = ArchStatMember(gn->path, RANLIBMAG, false);
1089 
1090 		if (arh != NULL) {
1091 			modTimeTOC = (int)strtol(arh->ar_date, NULL, 10);
1092 
1093 			if (DEBUG(ARCH) || DEBUG(MAKE))
1094 				debug_printf("%s modified %s...",
1095 					     RANLIBMAG,
1096 					     Targ_FmtTime(modTimeTOC));
1097 			oodate = gn->youngestChild == NULL ||
1098 				 gn->youngestChild->mtime > modTimeTOC;
1099 		} else {
1100 			/*
1101 			 * A library without a table of contents is out-of-date.
1102 			 */
1103 			if (DEBUG(ARCH) || DEBUG(MAKE))
1104 				debug_printf("no toc...");
1105 			oodate = true;
1106 		}
1107 #else
1108 		oodate = false;
1109 #endif
1110 	}
1111 	return oodate;
1112 }
1113 
1114 /* Initialize the archives module. */
1115 void
1116 Arch_Init(void)
1117 {
1118 	Lst_Init(&archives);
1119 }
1120 
1121 /* Clean up the archives module. */
1122 void
1123 Arch_End(void)
1124 {
1125 #ifdef CLEANUP
1126 	Lst_DoneCall(&archives, ArchFree);
1127 #endif
1128 }
1129 
1130 bool
1131 Arch_IsLib(GNode *gn)
1132 {
1133 	static const char armag[] = "!<arch>\n";
1134 	char buf[sizeof armag - 1];
1135 	int fd;
1136 
1137 	if ((fd = open(gn->path, O_RDONLY)) == -1)
1138 		return false;
1139 
1140 	if (read(fd, buf, sizeof buf) != sizeof buf) {
1141 		(void)close(fd);
1142 		return false;
1143 	}
1144 
1145 	(void)close(fd);
1146 
1147 	return memcmp(buf, armag, sizeof buf) == 0;
1148 }
1149