xref: /freebsd/usr.bin/ar/write.c (revision 02f27f1cfa619cdf9509c65366f55f7c8803de5c)
1 /*-
2  * Copyright (c) 2007 Kai Wang
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer
10  *    in this position and unchanged.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/endian.h>
31 #include <sys/mman.h>
32 #include <sys/queue.h>
33 #include <sys/stat.h>
34 #include <archive.h>
35 #include <archive_entry.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <gelf.h>
39 #include <libgen.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <sysexits.h>
44 
45 #include "ar.h"
46 
47 #define _ARMAG_LEN 8		/* length of ar magic string */
48 #define _ARHDR_LEN 60		/* length of ar header */
49 #define _INIT_AS_CAP 128	/* initial archive string table size */
50 #define _INIT_SYMOFF_CAP (256*(sizeof(uint32_t))) /* initial so table size */
51 #define _INIT_SYMNAME_CAP 1024			  /* initial sn table size */
52 #define _MAXNAMELEN_SVR4 15	/* max member name length in svr4 variant */
53 #define _TRUNCATE_LEN 15	/* number of bytes to keep for member name */
54 
55 static void	add_to_ar_str_table(struct bsdar *bsdar, const char *name);
56 static void	add_to_ar_sym_table(struct bsdar *bsdar, const char *name);
57 static struct ar_obj	*create_obj_from_file(struct bsdar *bsdar,
58 		    const char *name, time_t mtime);
59 static void	create_symtab_entry(struct bsdar *bsdar, void *maddr,
60 		    size_t size);
61 static void	insert_obj(struct bsdar *bsdar, struct ar_obj *obj,
62 		    struct ar_obj *pos);
63 static void	write_archive(struct bsdar *bsdar, char mode);
64 static void	write_cleanup(struct bsdar *bsdar);
65 static void	write_data(struct bsdar *bsdar, struct archive *a,
66 		    const void *buf, size_t s);
67 static void	write_objs(struct bsdar *bsdar);
68 
69 void
70 ar_mode_d(struct bsdar *bsdar)
71 {
72 
73 	write_archive(bsdar, 'd');
74 }
75 
76 void
77 ar_mode_m(struct bsdar *bsdar)
78 {
79 
80 	write_archive(bsdar, 'm');
81 }
82 
83 void
84 ar_mode_r(struct bsdar *bsdar)
85 {
86 
87 	write_archive(bsdar, 'r');
88 }
89 
90 void
91 ar_mode_s(struct bsdar *bsdar)
92 {
93 
94 	write_archive(bsdar, 's');
95 }
96 
97 /*
98  * Create object from file, return created obj upon success, or NULL
99  * when an error occurs or the member is not newer than existing
100  * one while -u is specifed.
101  */
102 static struct ar_obj *
103 create_obj_from_file(struct bsdar *bsdar, const char *name, time_t mtime)
104 {
105 	struct ar_obj		*obj;
106 	struct stat		 sb;
107 	const char		*bname;
108 
109 	if (name == NULL)
110 		return (NULL);
111 
112 	obj = malloc(sizeof(struct ar_obj));
113 	if (obj == NULL)
114 		bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
115 	if ((obj->fd = open(name, O_RDONLY, 0)) < 0) {
116 		bsdar_warnc(bsdar, errno, "can't open file: %s", name);
117 		free(obj);
118 		return (NULL);
119 	}
120 
121 	if ((bname = basename(name)) == NULL)
122 		bsdar_errc(bsdar, EX_SOFTWARE, errno, "basename failed");
123 	if (bsdar->options & AR_TR && strlen(bname) > _TRUNCATE_LEN) {
124 		if ((obj->name = malloc(_TRUNCATE_LEN + 1)) == NULL)
125 			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
126 		(void)strncpy(obj->name, bname, _TRUNCATE_LEN);
127 		obj->name[_TRUNCATE_LEN] = '\0';
128 	} else
129 		if ((obj->name = strdup(bname)) == NULL)
130 		    bsdar_errc(bsdar, EX_SOFTWARE, errno, "strdup failed");
131 
132 	if (fstat(obj->fd, &sb) < 0) {
133 		bsdar_warnc(bsdar, errno, "can't fstat file: %s", obj->name);
134 		goto giveup;
135 	}
136 	if (!S_ISREG(sb.st_mode)) {
137 		bsdar_warnc(bsdar, 0, "%s is not an ordinary file", obj->name);
138 		goto giveup;
139 	}
140 
141 	/*
142 	 * When option '-u' is specified and member is not newer than the
143 	 * existing one, the replace will not happen. While if mtime == 0,
144 	 * which indicates that this is to "replace a none exist member",
145 	 * the replace will proceed regardless of '-u'.
146 	 */
147 	if (mtime != 0 && bsdar->options & AR_U && sb.st_mtime <= mtime)
148 		goto giveup;
149 
150 	obj->uid = sb.st_uid;
151 	obj->gid = sb.st_gid;
152 	obj->md = sb.st_mode;
153 	obj->size = sb.st_size;
154 	obj->mtime = sb.st_mtime;
155 	obj->dev = sb.st_dev;
156 	obj->ino = sb.st_ino;
157 
158 	if (obj->size == 0) {
159 		obj->maddr = NULL;
160 		return (obj);
161 	}
162 
163 	if ((obj->maddr = mmap(NULL, obj->size, PROT_READ,
164 	    MAP_PRIVATE, obj->fd, (off_t)0)) == MAP_FAILED) {
165 		bsdar_warnc(bsdar, errno, "can't mmap file: %s", obj->name);
166 		goto giveup;
167 	}
168 	if (close(obj->fd) < 0)
169 		bsdar_errc(bsdar, EX_SOFTWARE, errno, "close failed: %s",
170 		    obj->name);
171 
172 	return (obj);
173 
174 giveup:
175 	if (close(obj->fd) < 0)
176 		bsdar_errc(bsdar, EX_SOFTWARE, errno, "close failed: %s",
177 		    obj->name);
178 	free(obj->name);
179 	free(obj);
180 	return (NULL);
181 }
182 
183 /*
184  * Insert obj to the tail, or before/after the pos obj.
185  */
186 static void
187 insert_obj(struct bsdar *bsdar, struct ar_obj *obj, struct ar_obj *pos)
188 {
189 	if (obj == NULL)
190 		bsdar_errc(bsdar, EX_SOFTWARE, 0, "try to insert a null obj");
191 
192 	if (pos == NULL || obj == pos)
193 		/*
194 		 * If the object to move happens to be the posistion obj,
195 		 * or if there is not a pos obj, move it to tail.
196 		 */
197 		goto tail;
198 
199 	if (bsdar->options & AR_B) {
200 		TAILQ_INSERT_BEFORE(pos, obj, objs);
201 		return;
202 	}
203 	if (bsdar->options & AR_A) {
204 		TAILQ_INSERT_AFTER(&bsdar->v_obj, pos, obj, objs);
205 		return;
206 	}
207 
208 tail:
209 	TAILQ_INSERT_TAIL(&bsdar->v_obj, obj, objs);
210 
211 }
212 
213 /*
214  * Determine the constitution of resulting archive.
215  */
216 static void
217 write_archive(struct bsdar *bsdar, char mode)
218 {
219 	struct archive		 *a;
220 	struct archive_entry	 *entry;
221 	struct ar_obj		 *nobj, *obj, *obj_temp, *pos;
222 	struct stat		  sb;
223 	const char		 *name;
224 	const char		 *bname;
225 	char			 *buff;
226 	char			**av;
227 	size_t			  size;
228 	int			  i, r;
229 
230 	TAILQ_INIT(&bsdar->v_obj);
231 	nobj = NULL;
232 	pos = NULL;
233 	memset(&sb, 0, sizeof(sb));
234 
235 	/* By default, no compression is assumed. */
236 	bsdar->compression = ARCHIVE_COMPRESSION_NONE;
237 
238 	/*
239 	 * Test if the specified archive exists, to figure out
240          * whether we are creating one here.
241 	 */
242 	if (stat(bsdar->filename, &sb) != 0) {
243 		if (errno != ENOENT) {
244 			bsdar_warnc(bsdar, 0, "stat %s failed",
245 			    bsdar->filename);
246 			return;
247 		}
248 
249 		/* We do not create archive in mode 'd', 'm' and 's'.  */
250 		if (mode != 'r') {
251 			bsdar_warnc(bsdar, 0, "%s: no such file",
252 			    bsdar->filename);
253 			return;
254 		}
255 
256 		/* Issue a warning if -c is not specified when creating. */
257 		if (!(bsdar->options & AR_C))
258 			bsdar_warnc(bsdar, 0, "creating %s", bsdar->filename);
259 		goto new_archive;
260 	}
261 
262 	/*
263 	 * First read members from existing archive.
264 	 */
265 	if ((a = archive_read_new()) == NULL)
266 		bsdar_errc(bsdar, EX_SOFTWARE, 0, "archive_read_new failed");
267 	archive_read_support_compression_all(a);
268 	archive_read_support_format_ar(a);
269 	AC(archive_read_open_filename(a, bsdar->filename, DEF_BLKSZ));
270 	for (;;) {
271 		r = archive_read_next_header(a, &entry);
272 		if (r == ARCHIVE_FATAL)
273 			bsdar_errc(bsdar, EX_DATAERR, 0, "%s",
274 			    archive_error_string(a));
275 		if (r == ARCHIVE_EOF)
276 			break;
277 		if (r == ARCHIVE_WARN || r == ARCHIVE_RETRY)
278 			bsdar_warnc(bsdar, 0, "%s", archive_error_string(a));
279 		if (r == ARCHIVE_RETRY) {
280 			bsdar_warnc(bsdar, 0, "Retrying...");
281 			continue;
282 		}
283 
284 		/*
285 		 * Remember the compression mode of existing archive.
286 		 * If neither -j nor -z is specified, this mode will
287 		 * be used for resulting archive.
288 		 */
289 		bsdar->compression = archive_compression(a);
290 
291 		name = archive_entry_pathname(entry);
292 
293 		/*
294 		 * skip pseudo members.
295 		 */
296 		if (strcmp(name, "/") == 0 || strcmp(name, "//") == 0)
297 			continue;
298 
299 		size = archive_entry_size(entry);
300 
301 		if (size > 0) {
302 			if ((buff = malloc(size)) == NULL)
303 				bsdar_errc(bsdar, EX_SOFTWARE, errno,
304 				    "malloc failed");
305 			if (archive_read_data(a, buff, size) != (ssize_t)size) {
306 				bsdar_warnc(bsdar, 0, "%s",
307 				    archive_error_string(a));
308 				free(buff);
309 				continue;
310 			}
311 		} else
312 			buff = NULL;
313 
314 		obj = malloc(sizeof(struct ar_obj));
315 		if (obj == NULL)
316 			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
317 		obj->maddr = buff;
318 		if ((obj->name = strdup(name)) == NULL)
319 			bsdar_errc(bsdar, EX_SOFTWARE, errno, "strdup failed");
320 		obj->size = size;
321 		obj->uid = archive_entry_uid(entry);
322 		obj->gid = archive_entry_gid(entry);
323 		obj->md = archive_entry_mode(entry);
324 		obj->mtime = archive_entry_mtime(entry);
325 		obj->dev = 0;
326 		obj->ino = 0;
327 
328 		/*
329 		 * Objects from archive have obj->fd set to -1,
330 		 * for the ease of cleaning up.
331 		 */
332 		obj->fd = -1;
333 		TAILQ_INSERT_TAIL(&bsdar->v_obj, obj, objs);
334 	}
335 	AC(archive_read_close(a));
336 	AC(archive_read_finish(a));
337 
338 	/*
339 	 * For mode 's', no member will be moved, deleted or replaced.
340 	 */
341 	if (mode == 's')
342 		goto write_objs;
343 
344 	/*
345 	 * Try to find the position member specified by user.
346 	 */
347 	if (bsdar->options & AR_A || bsdar->options & AR_B) {
348 		TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
349 			if (strcmp(obj->name, bsdar->posarg) == 0) {
350 				pos = obj;
351 				break;
352 			}
353 		}
354 
355 		/*
356 		 * If can't find `pos' specified by user,
357 		 * sliently insert objects at tail.
358 		 */
359 		if (pos == NULL)
360 			bsdar->options &= ~(AR_A | AR_B);
361 	}
362 
363 	for (i = 0; i < bsdar->argc; i++) {
364 		av = &bsdar->argv[i];
365 
366 		TAILQ_FOREACH_SAFE(obj, &bsdar->v_obj, objs, obj_temp) {
367 			if ((bname = basename(*av)) == NULL)
368 				bsdar_errc(bsdar, EX_SOFTWARE, errno,
369 				    "basename failed");
370 			if (bsdar->options & AR_TR) {
371 				if (strncmp(bname, obj->name, _TRUNCATE_LEN))
372 					continue;
373 			} else
374 				if (strcmp(bname, obj->name) != 0)
375 					continue;
376 
377 			if (mode == 'r') {
378 				/*
379 				 * if the new member is not qualified
380 				 * to replace the old one, skip it.
381 				 */
382 				nobj = create_obj_from_file(bsdar, *av,
383 				    obj->mtime);
384 				if (nobj == NULL)
385 					goto skip_obj;
386 			}
387 
388 			if (bsdar->options & AR_V)
389 				(void)fprintf(stdout, "%c - %s\n", mode,
390 				    *av);
391 
392 			TAILQ_REMOVE(&bsdar->v_obj, obj, objs);
393 			if (mode == 'd' || mode == 'r') {
394 				free(obj->maddr);
395 				free(obj->name);
396 				free(obj);
397 			}
398 
399 			if (mode == 'm')
400 				insert_obj(bsdar, obj, pos);
401 			if (mode == 'r')
402 				insert_obj(bsdar, nobj, pos);
403 
404 		skip_obj:
405 			*av = NULL;
406 			break;
407 		}
408 
409 	}
410 
411 new_archive:
412 	/*
413 	 * When operating in mode 'r', directly add those user specified
414 	 * objects which do not exist in current archive.
415 	 */
416 	for (i = 0; i < bsdar->argc; i++) {
417 		av = &bsdar->argv[i];
418 		if (*av != NULL && mode == 'r') {
419 			nobj = create_obj_from_file(bsdar, *av, 0);
420 			if (nobj != NULL)
421 				insert_obj(bsdar, nobj, pos);
422 			if (bsdar->options & AR_V && nobj != NULL)
423 				(void)fprintf(stdout, "a - %s\n", *av);
424 			*av = NULL;
425 		}
426 	}
427 
428 write_objs:
429 	write_objs(bsdar);
430 	write_cleanup(bsdar);
431 }
432 
433 /*
434  * Memory cleaning up.
435  */
436 static void
437 write_cleanup(struct bsdar *bsdar)
438 {
439 	struct ar_obj		*obj, *obj_temp;
440 
441 	TAILQ_FOREACH_SAFE(obj, &bsdar->v_obj, objs, obj_temp) {
442 		if (obj->fd == -1)
443 			free(obj->maddr);
444 		else
445 			if (obj->maddr != NULL && munmap(obj->maddr, obj->size))
446 				bsdar_warnc(bsdar, errno,
447 				    "can't munmap file: %s", obj->name);
448 		TAILQ_REMOVE(&bsdar->v_obj, obj, objs);
449 		free(obj->name);
450 		free(obj);
451 	}
452 
453 	free(bsdar->as);
454 	free(bsdar->s_so);
455 	free(bsdar->s_sn);
456 	bsdar->as = NULL;
457 	bsdar->s_so = NULL;
458 	bsdar->s_sn = NULL;
459 }
460 
461 /*
462  * Wrapper for archive_write_data().
463  */
464 static void
465 write_data(struct bsdar *bsdar, struct archive *a, const void *buf, size_t s)
466 {
467 	if (archive_write_data(a, buf, s) != (ssize_t)s)
468 		bsdar_errc(bsdar, EX_SOFTWARE, 0, "%s",
469 		    archive_error_string(a));
470 }
471 
472 /*
473  * Write the resulting archive members.
474  */
475 static void
476 write_objs(struct bsdar *bsdar)
477 {
478 	struct ar_obj		*obj;
479 	struct archive		*a;
480 	struct archive_entry	*entry;
481 	size_t s_sz;		/* size of archive symbol table. */
482 	size_t pm_sz;		/* size of pseudo members */
483 	int			 i, nr;
484 
485 	if (elf_version(EV_CURRENT) == EV_NONE)
486 		bsdar_errc(bsdar, EX_SOFTWARE, 0,
487 		    "ELF library initialization failed: %s", elf_errmsg(-1));
488 
489 	bsdar->rela_off = 0;
490 
491 	/* Create archive symbol table and archive string table, if need. */
492 	TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
493 		if (!(bsdar->options & AR_SS) && obj->maddr != NULL)
494 			create_symtab_entry(bsdar, obj->maddr, obj->size);
495 		if (strlen(obj->name) > _MAXNAMELEN_SVR4)
496 			add_to_ar_str_table(bsdar, obj->name);
497 		bsdar->rela_off += _ARHDR_LEN + obj->size + obj->size % 2;
498 	}
499 
500 	/*
501 	 * Pad the symbol name string table. It is treated specially because
502 	 * symbol name table should be padded by a '\0', not the common '\n'
503 	 * for other members. The size of sn table includes the pad bit.
504 	 */
505 	if (bsdar->s_cnt != 0 && bsdar->s_sn_sz % 2 != 0)
506 		bsdar->s_sn[bsdar->s_sn_sz++] = '\0';
507 
508 	/*
509 	 * Archive string table is padded by a "\n" as the normal members.
510 	 * The difference is that the size of archive string table counts
511 	 * in the pad bit, while normal members' size fileds do not.
512 	 */
513 	if (bsdar->as != NULL && bsdar->as_sz % 2 != 0)
514 		bsdar->as[bsdar->as_sz++] = '\n';
515 
516 	/*
517 	 * If there is a symbol table, calculate the size of pseudo members,
518 	 * convert previously stored relative offsets to absolute ones, and
519 	 * then make them Big Endian.
520 	 *
521 	 * absolute_offset = htobe32(relative_offset + size_of_pseudo_members)
522 	 */
523 
524 	if (bsdar->s_cnt != 0) {
525 		s_sz = (bsdar->s_cnt + 1) * sizeof(uint32_t) + bsdar->s_sn_sz;
526 		pm_sz = _ARMAG_LEN + (_ARHDR_LEN + s_sz);
527 		if (bsdar->as != NULL)
528 			pm_sz += _ARHDR_LEN + bsdar->as_sz;
529 		for (i = 0; (size_t)i < bsdar->s_cnt; i++)
530 			*(bsdar->s_so + i) = htobe32(*(bsdar->s_so + i) +
531 			    pm_sz);
532 	}
533 
534 	if ((a = archive_write_new()) == NULL)
535 		bsdar_errc(bsdar, EX_SOFTWARE, 0, "archive_write_new failed");
536 
537 	archive_write_set_format_ar_svr4(a);
538 
539 	/* The compression mode of the existing archive is used
540 	 * for the result archive or if creating a new archive, we
541 	 * do not compress archive by default. This default behavior can
542 	 * be overrided by compression mode specified explicitly
543 	 * through command line option `-j' or `-z'.
544 	 */
545 	if (bsdar->options & AR_J)
546 		bsdar->compression = ARCHIVE_COMPRESSION_BZIP2;
547 	if (bsdar->options & AR_Z)
548 		bsdar->compression = ARCHIVE_COMPRESSION_GZIP;
549 	if (bsdar->compression == ARCHIVE_COMPRESSION_BZIP2)
550 		archive_write_set_compression_bzip2(a);
551 	else if (bsdar->compression == ARCHIVE_COMPRESSION_GZIP)
552 		archive_write_set_compression_gzip(a);
553 	else
554 		archive_write_set_compression_none(a);
555 
556 	AC(archive_write_open_filename(a, bsdar->filename));
557 
558 	/*
559 	 * write the archive symbol table, if there is one.
560 	 * If options -s is explicitly specified or we are invoked
561 	 * as ranlib, write the symbol table even if it is empty.
562 	 */
563 	if ((bsdar->s_cnt != 0 && !(bsdar->options & AR_SS)) ||
564 	    bsdar->options & AR_S) {
565 		entry = archive_entry_new();
566 		archive_entry_copy_pathname(entry, "/");
567 		archive_entry_set_mtime(entry, time(NULL), 0);
568 		archive_entry_set_size(entry, (bsdar->s_cnt + 1) *
569 		    sizeof(uint32_t) + bsdar->s_sn_sz);
570 		AC(archive_write_header(a, entry));
571 		nr = htobe32(bsdar->s_cnt);
572 		write_data(bsdar, a, &nr, sizeof(uint32_t));
573 		write_data(bsdar, a, bsdar->s_so, sizeof(uint32_t) *
574 		    bsdar->s_cnt);
575 		write_data(bsdar, a, bsdar->s_sn, bsdar->s_sn_sz);
576 		archive_entry_free(entry);
577 	}
578 
579 	/* write the archive string table, if any. */
580 	if (bsdar->as != NULL) {
581 		entry = archive_entry_new();
582 		archive_entry_copy_pathname(entry, "//");
583 		archive_entry_set_size(entry, bsdar->as_sz);
584 		AC(archive_write_header(a, entry));
585 		write_data(bsdar, a, bsdar->as, bsdar->as_sz);
586 		archive_entry_free(entry);
587 	}
588 
589 	/* write normal members. */
590 	TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
591 		entry = archive_entry_new();
592 		archive_entry_copy_pathname(entry, obj->name);
593 		archive_entry_set_uid(entry, obj->uid);
594 		archive_entry_set_gid(entry, obj->gid);
595 		archive_entry_set_mode(entry, obj->md);
596 		archive_entry_set_size(entry, obj->size);
597 		archive_entry_set_mtime(entry, obj->mtime, 0);
598 		archive_entry_set_dev(entry, obj->dev);
599 		archive_entry_set_ino(entry, obj->ino);
600 		archive_entry_set_filetype(entry, AE_IFREG);
601 		AC(archive_write_header(a, entry));
602 		write_data(bsdar, a, obj->maddr, obj->size);
603 		archive_entry_free(entry);
604 	}
605 
606 	AC(archive_write_close(a));
607 	AC(archive_write_finish(a));
608 }
609 
610 /*
611  * Extract global symbols from ELF binary members.
612  */
613 static void
614 create_symtab_entry(struct bsdar *bsdar, void *maddr, size_t size)
615 {
616 	Elf		*e;
617 	Elf_Scn		*scn;
618 	GElf_Shdr	 shdr;
619 	GElf_Sym	 sym;
620 	Elf_Data	*data;
621 	char		*name;
622 	size_t		 n, shstrndx;
623 	int		 elferr, tabndx, len, i;
624 
625 	if ((e = elf_memory(maddr, size)) == NULL) {
626 		bsdar_warnc(bsdar, 0, "elf_memory() failed: %s",
627 		     elf_errmsg(-1));
628 		return;
629 	}
630 	if (elf_kind(e) != ELF_K_ELF) {
631 		/* Sliently ignore non-elf member. */
632 		elf_end(e);
633 		return;
634 	}
635 	if (elf_getshstrndx(e, &shstrndx) == 0) {
636 		bsdar_warnc(bsdar, EX_SOFTWARE, 0, "elf_getshstrndx failed: %s",
637 		     elf_errmsg(-1));
638 		elf_end(e);
639 		return;
640 	}
641 
642 	tabndx = -1;
643 	scn = NULL;
644 	while ((scn = elf_nextscn(e, scn)) != NULL) {
645 		if (gelf_getshdr(scn, &shdr) != &shdr) {
646 			bsdar_warnc(bsdar, 0,
647 			    "elf_getshdr failed: %s", elf_errmsg(-1));
648 			continue;
649 		}
650 		if ((name = elf_strptr(e, shstrndx, shdr.sh_name)) == NULL) {
651 			bsdar_warnc(bsdar, 0,
652 			    "elf_strptr failed: %s", elf_errmsg(-1));
653 			continue;
654 		}
655 		if (strcmp(name, ".strtab") == 0) {
656 			tabndx = elf_ndxscn(scn);
657 			break;
658 		}
659 	}
660 	elferr = elf_errno();
661 	if (elferr != 0)
662 		bsdar_warnc(bsdar, 0, "elf_nextscn failed: %s",
663 		     elf_errmsg(elferr));
664 	if (tabndx == -1) {
665 		bsdar_warnc(bsdar, 0, "can't find .strtab section");
666 		elf_end(e);
667 		return;
668 	}
669 
670 	scn = NULL;
671 	while ((scn = elf_nextscn(e, scn)) != NULL) {
672 		if (gelf_getshdr(scn, &shdr) != &shdr) {
673 			bsdar_warnc(bsdar, EX_SOFTWARE, 0,
674 			    "elf_getshdr failed: %s", elf_errmsg(-1));
675 			continue;
676 		}
677 		if (shdr.sh_type != SHT_SYMTAB)
678 			continue;
679 
680 		data = NULL;
681 		n = 0;
682 		while (n < shdr.sh_size &&
683 		    (data = elf_getdata(scn, data)) != NULL) {
684 			len = data->d_size / shdr.sh_entsize;
685 			for (i = 0; i < len; i++) {
686 				if (gelf_getsym(data, i, &sym) != &sym) {
687 					bsdar_warnc(bsdar, EX_SOFTWARE, 0,
688 					    "gelf_getsym failed: %s",
689 					     elf_errmsg(-1));
690 					continue;
691 				}
692 
693 				/* keep only global or weak symbols */
694 				if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL &&
695 				    GELF_ST_BIND(sym.st_info) != STB_WEAK)
696 					continue;
697 
698 				/* keep only defined symbols */
699 				if (sym.st_shndx == SHN_UNDEF)
700 					continue;
701 
702 				if ((name = elf_strptr(e, tabndx,
703 				    sym.st_name)) == NULL) {
704 					bsdar_warnc(bsdar, EX_SOFTWARE, 0,
705 					    "elf_strptr failed: %s",
706 					     elf_errmsg(-1));
707 					continue;
708 				}
709 
710 				add_to_ar_sym_table(bsdar, name);
711 			}
712 		}
713 	}
714 	elferr = elf_errno();
715 	if (elferr != 0)
716 		bsdar_warnc(bsdar, EX_SOFTWARE, 0, "elf_nextscn failed: %s",
717 		     elf_errmsg(elferr));
718 
719 	elf_end(e);
720 }
721 
722 /*
723  * Append to the archive string table buffer.
724  */
725 static void
726 add_to_ar_str_table(struct bsdar *bsdar, const char *name)
727 {
728 
729 	if (bsdar->as == NULL) {
730 		bsdar->as_cap = _INIT_AS_CAP;
731 		bsdar->as_sz = 0;
732 		if ((bsdar->as = malloc(bsdar->as_cap)) == NULL)
733 			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
734 	}
735 
736 	/*
737 	 * The space required for holding one member name in as table includes:
738 	 * strlen(name) + (1 for '/') + (1 for '\n') + (possibly 1 for padding).
739 	 */
740 	while (bsdar->as_sz + strlen(name) + 3 > bsdar->as_cap) {
741 		bsdar->as_cap *= 2;
742 		bsdar->as = realloc(bsdar->as, bsdar->as_cap);
743 		if (bsdar->as == NULL)
744 			bsdar_errc(bsdar, EX_SOFTWARE, errno, "realloc failed");
745 	}
746 	strncpy(&bsdar->as[bsdar->as_sz], name, strlen(name));
747 	bsdar->as_sz += strlen(name);
748 	bsdar->as[bsdar->as_sz++] = '/';
749 	bsdar->as[bsdar->as_sz++] = '\n';
750 }
751 
752 /*
753  * Append to the archive symbol table buffer.
754  */
755 static void
756 add_to_ar_sym_table(struct bsdar *bsdar, const char *name)
757 {
758 
759 	if (bsdar->s_so == NULL) {
760 		if ((bsdar->s_so = malloc(_INIT_SYMOFF_CAP)) ==
761 		    NULL)
762 			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
763 		bsdar->s_so_cap = _INIT_SYMOFF_CAP;
764 		bsdar->s_cnt = 0;
765 	}
766 
767 	if (bsdar->s_sn == NULL) {
768 		if ((bsdar->s_sn = malloc(_INIT_SYMNAME_CAP)) == NULL)
769 			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
770 		bsdar->s_sn_cap = _INIT_SYMNAME_CAP;
771 		bsdar->s_sn_sz = 0;
772 	}
773 
774 	if (bsdar->s_cnt * sizeof(uint32_t) >= bsdar->s_so_cap) {
775 		bsdar->s_so_cap *= 2;
776 		bsdar->s_so = realloc(bsdar->s_so, bsdar->s_so_cap);
777 		if (bsdar->s_so == NULL)
778 			bsdar_errc(bsdar, EX_SOFTWARE, errno, "realloc failed");
779 	}
780 	bsdar->s_so[bsdar->s_cnt] = bsdar->rela_off;
781 	bsdar->s_cnt++;
782 
783 	/*
784 	 * The space required for holding one symbol name in sn table includes:
785 	 * strlen(name) + (1 for '\n') + (possibly 1 for padding).
786 	 */
787 	while (bsdar->s_sn_sz + strlen(name) + 2 > bsdar->s_sn_cap) {
788 		bsdar->s_sn_cap *= 2;
789 		bsdar->s_sn = realloc(bsdar->s_sn, bsdar->s_sn_cap);
790 		if (bsdar->s_sn == NULL)
791 			bsdar_errc(bsdar, EX_SOFTWARE, errno, "realloc failed");
792 	}
793 	strncpy(&bsdar->s_sn[bsdar->s_sn_sz], name, strlen(name));
794 	bsdar->s_sn_sz += strlen(name);
795 	bsdar->s_sn[bsdar->s_sn_sz++] = '\0';
796 }
797