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