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