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