write.c revision 208189
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: head/usr.bin/ar/write.c 208189 2010-05-17 09:37:59Z kaiw $");
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
55static void	add_to_ar_str_table(struct bsdar *bsdar, const char *name);
56static void	add_to_ar_sym_table(struct bsdar *bsdar, const char *name);
57static struct ar_obj	*create_obj_from_file(struct bsdar *bsdar,
58		    const char *name, time_t mtime);
59static void	create_symtab_entry(struct bsdar *bsdar, void *maddr,
60		    size_t size);
61static void	insert_obj(struct bsdar *bsdar, struct ar_obj *obj,
62		    struct ar_obj *pos);
63static void	read_objs(struct bsdar *bsdar, const char *archive,
64		    int checkargv);
65static void	write_archive(struct bsdar *bsdar, char mode);
66static void	write_cleanup(struct bsdar *bsdar);
67static void	write_data(struct bsdar *bsdar, struct archive *a,
68		    const void *buf, size_t s);
69static void	write_objs(struct bsdar *bsdar);
70
71void
72ar_mode_d(struct bsdar *bsdar)
73{
74
75	write_archive(bsdar, 'd');
76}
77
78void
79ar_mode_m(struct bsdar *bsdar)
80{
81
82	write_archive(bsdar, 'm');
83}
84
85void
86ar_mode_q(struct bsdar *bsdar)
87{
88
89	write_archive(bsdar, 'q');
90}
91
92void
93ar_mode_r(struct bsdar *bsdar)
94{
95
96	write_archive(bsdar, 'r');
97}
98
99void
100ar_mode_s(struct bsdar *bsdar)
101{
102
103	write_archive(bsdar, 's');
104}
105
106void
107ar_mode_A(struct bsdar *bsdar)
108{
109
110	write_archive(bsdar, 'A');
111}
112
113/*
114 * Create object from file, return created obj upon success, or NULL
115 * when an error occurs or the member is not newer than existing
116 * one while -u is specifed.
117 */
118static struct ar_obj *
119create_obj_from_file(struct bsdar *bsdar, const char *name, time_t mtime)
120{
121	struct ar_obj		*obj;
122	struct stat		 sb;
123	const char		*bname;
124
125	if (name == NULL)
126		return (NULL);
127
128	obj = malloc(sizeof(struct ar_obj));
129	if (obj == NULL)
130		bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
131	if ((obj->fd = open(name, O_RDONLY, 0)) < 0) {
132		bsdar_warnc(bsdar, errno, "can't open file: %s", name);
133		free(obj);
134		return (NULL);
135	}
136
137	if ((bname = basename(name)) == NULL)
138		bsdar_errc(bsdar, EX_SOFTWARE, errno, "basename failed");
139	if (bsdar->options & AR_TR && strlen(bname) > _TRUNCATE_LEN) {
140		if ((obj->name = malloc(_TRUNCATE_LEN + 1)) == NULL)
141			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
142		(void)strncpy(obj->name, bname, _TRUNCATE_LEN);
143		obj->name[_TRUNCATE_LEN] = '\0';
144	} else
145		if ((obj->name = strdup(bname)) == NULL)
146		    bsdar_errc(bsdar, EX_SOFTWARE, errno, "strdup failed");
147
148	if (fstat(obj->fd, &sb) < 0) {
149		bsdar_warnc(bsdar, errno, "can't fstat file: %s", obj->name);
150		goto giveup;
151	}
152	if (!S_ISREG(sb.st_mode)) {
153		bsdar_warnc(bsdar, 0, "%s is not an ordinary file", obj->name);
154		goto giveup;
155	}
156
157	/*
158	 * When option '-u' is specified and member is not newer than the
159	 * existing one, the replace will not happen. While if mtime == 0,
160	 * which indicates that this is to "replace a none exist member",
161	 * the replace will proceed regardless of '-u'.
162	 */
163	if (mtime != 0 && bsdar->options & AR_U && sb.st_mtime <= mtime)
164		goto giveup;
165
166	obj->uid = sb.st_uid;
167	obj->gid = sb.st_gid;
168	obj->md = sb.st_mode;
169	obj->size = sb.st_size;
170	obj->mtime = sb.st_mtime;
171	obj->dev = sb.st_dev;
172	obj->ino = sb.st_ino;
173
174	if (obj->size == 0) {
175		obj->maddr = NULL;
176		return (obj);
177	}
178
179	if ((obj->maddr = mmap(NULL, obj->size, PROT_READ,
180	    MAP_PRIVATE, obj->fd, (off_t)0)) == MAP_FAILED) {
181		bsdar_warnc(bsdar, errno, "can't mmap file: %s", obj->name);
182		goto giveup;
183	}
184	if (close(obj->fd) < 0)
185		bsdar_errc(bsdar, EX_SOFTWARE, errno, "close failed: %s",
186		    obj->name);
187
188	return (obj);
189
190giveup:
191	if (close(obj->fd) < 0)
192		bsdar_errc(bsdar, EX_SOFTWARE, errno, "close failed: %s",
193		    obj->name);
194	free(obj->name);
195	free(obj);
196	return (NULL);
197}
198
199/*
200 * Insert obj to the tail, or before/after the pos obj.
201 */
202static void
203insert_obj(struct bsdar *bsdar, struct ar_obj *obj, struct ar_obj *pos)
204{
205	if (obj == NULL)
206		bsdar_errc(bsdar, EX_SOFTWARE, 0, "try to insert a null obj");
207
208	if (pos == NULL || obj == pos)
209		/*
210		 * If the object to move happens to be the posistion obj,
211		 * or if there is not a pos obj, move it to tail.
212		 */
213		goto tail;
214
215	if (bsdar->options & AR_B) {
216		TAILQ_INSERT_BEFORE(pos, obj, objs);
217		return;
218	}
219	if (bsdar->options & AR_A) {
220		TAILQ_INSERT_AFTER(&bsdar->v_obj, pos, obj, objs);
221		return;
222	}
223
224tail:
225	TAILQ_INSERT_TAIL(&bsdar->v_obj, obj, objs);
226
227}
228
229/*
230 * Read objects from archive into v_obj list. Note that checkargv is
231 * set when read_objs is used to read objects from the target of
232 * ADDLIB command (ar script mode), in this case argv array possibly
233 * specifies the members ADDLIB want.
234 */
235static void
236read_objs(struct bsdar *bsdar, const char *archive, int checkargv)
237{
238	struct archive		 *a;
239	struct archive_entry	 *entry;
240	struct ar_obj		 *obj;
241	const char		 *name;
242	const char		 *bname;
243	char			 *buff;
244	char			**av;
245	size_t			  size;
246	int			  i, r, find;
247
248	if ((a = archive_read_new()) == NULL)
249		bsdar_errc(bsdar, EX_SOFTWARE, 0, "archive_read_new failed");
250	archive_read_support_compression_none(a);
251	archive_read_support_format_ar(a);
252	AC(archive_read_open_filename(a, archive, DEF_BLKSZ));
253	for (;;) {
254		r = archive_read_next_header(a, &entry);
255		if (r == ARCHIVE_FATAL)
256			bsdar_errc(bsdar, EX_DATAERR, 0, "%s",
257			    archive_error_string(a));
258		if (r == ARCHIVE_EOF)
259			break;
260		if (r == ARCHIVE_WARN || r == ARCHIVE_RETRY)
261			bsdar_warnc(bsdar, 0, "%s", archive_error_string(a));
262		if (r == ARCHIVE_RETRY) {
263			bsdar_warnc(bsdar, 0, "Retrying...");
264			continue;
265		}
266
267		name = archive_entry_pathname(entry);
268
269		/*
270		 * skip pseudo members.
271		 */
272		if (strcmp(name, "/") == 0 || strcmp(name, "//") == 0)
273			continue;
274
275		/*
276		 * If checkargv is set, only read those members specified
277		 * in argv.
278		 */
279		if (checkargv && bsdar->argc > 0) {
280			find = 0;
281			for(i = 0; i < bsdar->argc; i++) {
282				av = &bsdar->argv[i];
283				if (*av == NULL)
284					continue;
285				if ((bname = basename(*av)) == NULL)
286					bsdar_errc(bsdar, EX_SOFTWARE, errno,
287					    "basename failed");
288				if (strcmp(bname, name) != 0)
289					continue;
290
291				*av = NULL;
292				find = 1;
293				break;
294			}
295			if (!find)
296				continue;
297		}
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/*
340 * Determine the constitution of resulting archive.
341 */
342static void
343write_archive(struct bsdar *bsdar, char mode)
344{
345	struct ar_obj		 *nobj, *obj, *obj_temp, *pos;
346	struct stat		  sb;
347	const char		 *bname;
348	char			**av;
349	int			  i;
350
351	TAILQ_INIT(&bsdar->v_obj);
352	nobj = NULL;
353	pos = NULL;
354	memset(&sb, 0, sizeof(sb));
355
356	/*
357	 * Test if the specified archive exists, to figure out
358	 * whether we are creating one here.
359	 */
360	if (stat(bsdar->filename, &sb) != 0) {
361		if (errno != ENOENT) {
362			bsdar_warnc(bsdar, 0, "stat %s failed",
363			    bsdar->filename);
364			return;
365		}
366
367		/* We do not create archive in mode 'd', 'm' and 's'.  */
368		if (mode != 'r' && mode != 'q') {
369			bsdar_warnc(bsdar, 0, "%s: no such file",
370			    bsdar->filename);
371			return;
372		}
373
374		/* Issue a warning if -c is not specified when creating. */
375		if (!(bsdar->options & AR_C))
376			bsdar_warnc(bsdar, 0, "creating %s", bsdar->filename);
377		goto new_archive;
378	}
379
380	/*
381	 * First read members from existing archive.
382	 */
383	read_objs(bsdar, bsdar->filename, 0);
384
385	/*
386	 * For mode 's', no member will be moved, deleted or replaced.
387	 */
388	if (mode == 's')
389		goto write_objs;
390
391	/*
392	 * For mode 'q', we don't need to adjust existing members either.
393	 * Also, -a, -b and -i are ignored in this mode. New members are
394	 * always inserted at tail.
395	 */
396	if (mode == 'q')
397		goto new_archive;
398
399	/*
400	 * Mode 'A' adds the contents of another archive to the tail of
401	 * current archive. Note that mode 'A' is a special mode for the
402	 * ADDLIB command of the ar script mode. Currently there is no
403	 * access to this function from the ar command line mode.
404	 */
405	if (mode == 'A') {
406		/*
407		 * Read objects from the target archive of ADDLIB command.
408		 * If there are members spcified in argv, read those members
409		 * only, otherwise the entire archive will be read.
410		 */
411		read_objs(bsdar, bsdar->addlib, 1);
412		goto write_objs;
413	}
414
415	/*
416	 * Try to find the position member specified by user.
417	 */
418	if (bsdar->options & AR_A || bsdar->options & AR_B) {
419		TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
420			if (strcmp(obj->name, bsdar->posarg) == 0) {
421				pos = obj;
422				break;
423			}
424		}
425
426		/*
427		 * If can't find `pos' specified by user,
428		 * sliently insert objects at tail.
429		 */
430		if (pos == NULL)
431			bsdar->options &= ~(AR_A | AR_B);
432	}
433
434	for (i = 0; i < bsdar->argc; i++) {
435		av = &bsdar->argv[i];
436
437		TAILQ_FOREACH_SAFE(obj, &bsdar->v_obj, objs, obj_temp) {
438			if ((bname = basename(*av)) == NULL)
439				bsdar_errc(bsdar, EX_SOFTWARE, errno,
440				    "basename failed");
441			if (bsdar->options & AR_TR) {
442				if (strncmp(bname, obj->name, _TRUNCATE_LEN))
443					continue;
444			} else
445				if (strcmp(bname, obj->name) != 0)
446					continue;
447
448			if (mode == 'r') {
449				/*
450				 * if the new member is not qualified
451				 * to replace the old one, skip it.
452				 */
453				nobj = create_obj_from_file(bsdar, *av,
454				    obj->mtime);
455				if (nobj == NULL)
456					goto skip_obj;
457			}
458
459			if (bsdar->options & AR_V)
460				(void)fprintf(stdout, "%c - %s\n", mode,
461				    *av);
462
463			TAILQ_REMOVE(&bsdar->v_obj, obj, objs);
464			if (mode == 'd' || mode == 'r') {
465				free(obj->maddr);
466				free(obj->name);
467				free(obj);
468			}
469
470			if (mode == 'm')
471				insert_obj(bsdar, obj, pos);
472			if (mode == 'r')
473				insert_obj(bsdar, nobj, pos);
474
475		skip_obj:
476			*av = NULL;
477			break;
478		}
479
480	}
481
482new_archive:
483	/*
484	 * When operating in mode 'r', directly add those user specified
485	 * objects which do not exist in current archive. When operating
486	 * in mode 'q', all objects specified in command line args are
487	 * appended to the archive, without comparing with existing ones.
488	 */
489	for (i = 0; i < bsdar->argc; i++) {
490		av = &bsdar->argv[i];
491		if (*av != NULL && (mode == 'r' || mode == 'q')) {
492			nobj = create_obj_from_file(bsdar, *av, 0);
493			if (nobj != NULL)
494				insert_obj(bsdar, nobj, pos);
495			if (bsdar->options & AR_V && nobj != NULL)
496				(void)fprintf(stdout, "a - %s\n", *av);
497			*av = NULL;
498		}
499	}
500
501write_objs:
502	write_objs(bsdar);
503	write_cleanup(bsdar);
504}
505
506/*
507 * Memory cleaning up.
508 */
509static void
510write_cleanup(struct bsdar *bsdar)
511{
512	struct ar_obj		*obj, *obj_temp;
513
514	TAILQ_FOREACH_SAFE(obj, &bsdar->v_obj, objs, obj_temp) {
515		if (obj->fd == -1)
516			free(obj->maddr);
517		else
518			if (obj->maddr != NULL && munmap(obj->maddr, obj->size))
519				bsdar_warnc(bsdar, errno,
520				    "can't munmap file: %s", obj->name);
521		TAILQ_REMOVE(&bsdar->v_obj, obj, objs);
522		free(obj->name);
523		free(obj);
524	}
525
526	free(bsdar->as);
527	free(bsdar->s_so);
528	free(bsdar->s_sn);
529	bsdar->as = NULL;
530	bsdar->s_so = NULL;
531	bsdar->s_sn = NULL;
532}
533
534/*
535 * Wrapper for archive_write_data().
536 */
537static void
538write_data(struct bsdar *bsdar, struct archive *a, const void *buf, size_t s)
539{
540	if (archive_write_data(a, buf, s) != (ssize_t)s)
541		bsdar_errc(bsdar, EX_SOFTWARE, 0, "%s",
542		    archive_error_string(a));
543}
544
545/*
546 * Write the resulting archive members.
547 */
548static void
549write_objs(struct bsdar *bsdar)
550{
551	struct ar_obj		*obj;
552	struct archive		*a;
553	struct archive_entry	*entry;
554	size_t s_sz;		/* size of archive symbol table. */
555	size_t pm_sz;		/* size of pseudo members */
556	int			 i, nr;
557
558	if (elf_version(EV_CURRENT) == EV_NONE)
559		bsdar_errc(bsdar, EX_SOFTWARE, 0,
560		    "ELF library initialization failed: %s", elf_errmsg(-1));
561
562	bsdar->rela_off = 0;
563
564	/* Create archive symbol table and archive string table, if need. */
565	TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
566		if (!(bsdar->options & AR_SS) && obj->maddr != NULL)
567			create_symtab_entry(bsdar, obj->maddr, obj->size);
568		if (strlen(obj->name) > _MAXNAMELEN_SVR4)
569			add_to_ar_str_table(bsdar, obj->name);
570		bsdar->rela_off += _ARHDR_LEN + obj->size + obj->size % 2;
571	}
572
573	/*
574	 * Pad the symbol name string table. It is treated specially because
575	 * symbol name table should be padded by a '\0', not the common '\n'
576	 * for other members. The size of sn table includes the pad bit.
577	 */
578	if (bsdar->s_cnt != 0 && bsdar->s_sn_sz % 2 != 0)
579		bsdar->s_sn[bsdar->s_sn_sz++] = '\0';
580
581	/*
582	 * Archive string table is padded by a "\n" as the normal members.
583	 * The difference is that the size of archive string table counts
584	 * in the pad bit, while normal members' size fileds do not.
585	 */
586	if (bsdar->as != NULL && bsdar->as_sz % 2 != 0)
587		bsdar->as[bsdar->as_sz++] = '\n';
588
589	/*
590	 * If there is a symbol table, calculate the size of pseudo members,
591	 * convert previously stored relative offsets to absolute ones, and
592	 * then make them Big Endian.
593	 *
594	 * absolute_offset = htobe32(relative_offset + size_of_pseudo_members)
595	 */
596
597	if (bsdar->s_cnt != 0) {
598		s_sz = (bsdar->s_cnt + 1) * sizeof(uint32_t) + bsdar->s_sn_sz;
599		pm_sz = _ARMAG_LEN + (_ARHDR_LEN + s_sz);
600		if (bsdar->as != NULL)
601			pm_sz += _ARHDR_LEN + bsdar->as_sz;
602		for (i = 0; (size_t)i < bsdar->s_cnt; i++)
603			*(bsdar->s_so + i) = htobe32(*(bsdar->s_so + i) +
604			    pm_sz);
605	}
606
607	if ((a = archive_write_new()) == NULL)
608		bsdar_errc(bsdar, EX_SOFTWARE, 0, "archive_write_new failed");
609
610	archive_write_set_format_ar_svr4(a);
611	archive_write_set_compression_none(a);
612
613	AC(archive_write_open_filename(a, bsdar->filename));
614
615	/*
616	 * write the archive symbol table, if there is one.
617	 * If options -s is explicitly specified or we are invoked
618	 * as ranlib, write the symbol table even if it is empty.
619	 */
620	if ((bsdar->s_cnt != 0 && !(bsdar->options & AR_SS)) ||
621	    bsdar->options & AR_S) {
622		entry = archive_entry_new();
623		archive_entry_copy_pathname(entry, "/");
624		archive_entry_set_mtime(entry, time(NULL), 0);
625		archive_entry_set_size(entry, (bsdar->s_cnt + 1) *
626		    sizeof(uint32_t) + bsdar->s_sn_sz);
627		AC(archive_write_header(a, entry));
628		nr = htobe32(bsdar->s_cnt);
629		write_data(bsdar, a, &nr, sizeof(uint32_t));
630		write_data(bsdar, a, bsdar->s_so, sizeof(uint32_t) *
631		    bsdar->s_cnt);
632		write_data(bsdar, a, bsdar->s_sn, bsdar->s_sn_sz);
633		archive_entry_free(entry);
634	}
635
636	/* write the archive string table, if any. */
637	if (bsdar->as != NULL) {
638		entry = archive_entry_new();
639		archive_entry_copy_pathname(entry, "//");
640		archive_entry_set_size(entry, bsdar->as_sz);
641		AC(archive_write_header(a, entry));
642		write_data(bsdar, a, bsdar->as, bsdar->as_sz);
643		archive_entry_free(entry);
644	}
645
646	/* write normal members. */
647	TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
648		entry = archive_entry_new();
649		archive_entry_copy_pathname(entry, obj->name);
650		archive_entry_set_uid(entry, obj->uid);
651		archive_entry_set_gid(entry, obj->gid);
652		archive_entry_set_mode(entry, obj->md);
653		archive_entry_set_size(entry, obj->size);
654		archive_entry_set_mtime(entry, obj->mtime, 0);
655		archive_entry_set_dev(entry, obj->dev);
656		archive_entry_set_ino(entry, obj->ino);
657		archive_entry_set_filetype(entry, AE_IFREG);
658		AC(archive_write_header(a, entry));
659		write_data(bsdar, a, obj->maddr, obj->size);
660		archive_entry_free(entry);
661	}
662
663	AC(archive_write_close(a));
664	AC(archive_write_finish(a));
665}
666
667/*
668 * Extract global symbols from ELF binary members.
669 */
670static void
671create_symtab_entry(struct bsdar *bsdar, void *maddr, size_t size)
672{
673	Elf		*e;
674	Elf_Scn		*scn;
675	GElf_Shdr	 shdr;
676	GElf_Sym	 sym;
677	Elf_Data	*data;
678	char		*name;
679	size_t		 n, shstrndx;
680	int		 elferr, tabndx, len, i;
681
682	if ((e = elf_memory(maddr, size)) == NULL) {
683		bsdar_warnc(bsdar, 0, "elf_memory() failed: %s",
684		     elf_errmsg(-1));
685		return;
686	}
687	if (elf_kind(e) != ELF_K_ELF) {
688		/* Sliently ignore non-elf member. */
689		elf_end(e);
690		return;
691	}
692	if (elf_getshstrndx(e, &shstrndx) == 0) {
693		bsdar_warnc(bsdar, EX_SOFTWARE, 0, "elf_getshstrndx failed: %s",
694		     elf_errmsg(-1));
695		elf_end(e);
696		return;
697	}
698
699	tabndx = -1;
700	scn = NULL;
701	while ((scn = elf_nextscn(e, scn)) != NULL) {
702		if (gelf_getshdr(scn, &shdr) != &shdr) {
703			bsdar_warnc(bsdar, 0,
704			    "elf_getshdr failed: %s", elf_errmsg(-1));
705			continue;
706		}
707		if ((name = elf_strptr(e, shstrndx, shdr.sh_name)) == NULL) {
708			bsdar_warnc(bsdar, 0,
709			    "elf_strptr failed: %s", elf_errmsg(-1));
710			continue;
711		}
712		if (strcmp(name, ".strtab") == 0) {
713			tabndx = elf_ndxscn(scn);
714			break;
715		}
716	}
717	elferr = elf_errno();
718	if (elferr != 0)
719		bsdar_warnc(bsdar, 0, "elf_nextscn failed: %s",
720		     elf_errmsg(elferr));
721	if (tabndx == -1) {
722		bsdar_warnc(bsdar, 0, "can't find .strtab section");
723		elf_end(e);
724		return;
725	}
726
727	scn = NULL;
728	while ((scn = elf_nextscn(e, scn)) != NULL) {
729		if (gelf_getshdr(scn, &shdr) != &shdr) {
730			bsdar_warnc(bsdar, EX_SOFTWARE, 0,
731			    "elf_getshdr failed: %s", elf_errmsg(-1));
732			continue;
733		}
734		if (shdr.sh_type != SHT_SYMTAB)
735			continue;
736
737		data = NULL;
738		n = 0;
739		while (n < shdr.sh_size &&
740		    (data = elf_getdata(scn, data)) != NULL) {
741			len = data->d_size / shdr.sh_entsize;
742			for (i = 0; i < len; i++) {
743				if (gelf_getsym(data, i, &sym) != &sym) {
744					bsdar_warnc(bsdar, EX_SOFTWARE, 0,
745					    "gelf_getsym failed: %s",
746					     elf_errmsg(-1));
747					continue;
748				}
749
750				/* keep only global or weak symbols */
751				if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL &&
752				    GELF_ST_BIND(sym.st_info) != STB_WEAK)
753					continue;
754
755				/* keep only defined symbols */
756				if (sym.st_shndx == SHN_UNDEF)
757					continue;
758
759				if ((name = elf_strptr(e, tabndx,
760				    sym.st_name)) == NULL) {
761					bsdar_warnc(bsdar, EX_SOFTWARE, 0,
762					    "elf_strptr failed: %s",
763					     elf_errmsg(-1));
764					continue;
765				}
766
767				add_to_ar_sym_table(bsdar, name);
768			}
769		}
770	}
771	elferr = elf_errno();
772	if (elferr != 0)
773		bsdar_warnc(bsdar, EX_SOFTWARE, 0, "elf_nextscn failed: %s",
774		     elf_errmsg(elferr));
775
776	elf_end(e);
777}
778
779/*
780 * Append to the archive string table buffer.
781 */
782static void
783add_to_ar_str_table(struct bsdar *bsdar, const char *name)
784{
785
786	if (bsdar->as == NULL) {
787		bsdar->as_cap = _INIT_AS_CAP;
788		bsdar->as_sz = 0;
789		if ((bsdar->as = malloc(bsdar->as_cap)) == NULL)
790			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
791	}
792
793	/*
794	 * The space required for holding one member name in as table includes:
795	 * strlen(name) + (1 for '/') + (1 for '\n') + (possibly 1 for padding).
796	 */
797	while (bsdar->as_sz + strlen(name) + 3 > bsdar->as_cap) {
798		bsdar->as_cap *= 2;
799		bsdar->as = realloc(bsdar->as, bsdar->as_cap);
800		if (bsdar->as == NULL)
801			bsdar_errc(bsdar, EX_SOFTWARE, errno, "realloc failed");
802	}
803	strncpy(&bsdar->as[bsdar->as_sz], name, strlen(name));
804	bsdar->as_sz += strlen(name);
805	bsdar->as[bsdar->as_sz++] = '/';
806	bsdar->as[bsdar->as_sz++] = '\n';
807}
808
809/*
810 * Append to the archive symbol table buffer.
811 */
812static void
813add_to_ar_sym_table(struct bsdar *bsdar, const char *name)
814{
815
816	if (bsdar->s_so == NULL) {
817		if ((bsdar->s_so = malloc(_INIT_SYMOFF_CAP)) ==
818		    NULL)
819			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
820		bsdar->s_so_cap = _INIT_SYMOFF_CAP;
821		bsdar->s_cnt = 0;
822	}
823
824	if (bsdar->s_sn == NULL) {
825		if ((bsdar->s_sn = malloc(_INIT_SYMNAME_CAP)) == NULL)
826			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
827		bsdar->s_sn_cap = _INIT_SYMNAME_CAP;
828		bsdar->s_sn_sz = 0;
829	}
830
831	if (bsdar->s_cnt * sizeof(uint32_t) >= bsdar->s_so_cap) {
832		bsdar->s_so_cap *= 2;
833		bsdar->s_so = realloc(bsdar->s_so, bsdar->s_so_cap);
834		if (bsdar->s_so == NULL)
835			bsdar_errc(bsdar, EX_SOFTWARE, errno, "realloc failed");
836	}
837	bsdar->s_so[bsdar->s_cnt] = bsdar->rela_off;
838	bsdar->s_cnt++;
839
840	/*
841	 * The space required for holding one symbol name in sn table includes:
842	 * strlen(name) + (1 for '\n') + (possibly 1 for padding).
843	 */
844	while (bsdar->s_sn_sz + strlen(name) + 2 > bsdar->s_sn_cap) {
845		bsdar->s_sn_cap *= 2;
846		bsdar->s_sn = realloc(bsdar->s_sn, bsdar->s_sn_cap);
847		if (bsdar->s_sn == NULL)
848			bsdar_errc(bsdar, EX_SOFTWARE, errno, "realloc failed");
849	}
850	strncpy(&bsdar->s_sn[bsdar->s_sn_sz], name, strlen(name));
851	bsdar->s_sn_sz += strlen(name);
852	bsdar->s_sn[bsdar->s_sn_sz++] = '\0';
853}
854