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