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