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