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