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