xref: /freebsd/contrib/elftoolchain/ar/write.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
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 3629 2018-09-30 19:26:28Z jkoshy $");
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  * Returns EXIT_SUCCESS if the write succeeded or EXIT_FAILURE otherwise.
357  */
358 int
359 ar_write_archive(struct bsdar *bsdar, int mode)
360 {
361 	struct ar_obj		 *nobj, *obj, *obj_temp, *pos;
362 	struct stat		  sb;
363 	const char		 *bname;
364 	char			**av;
365 	int			  exitcode, i;
366 
367 	TAILQ_INIT(&bsdar->v_obj);
368 	exitcode = EXIT_SUCCESS;
369 	nobj = NULL;
370 	pos = NULL;
371 	memset(&sb, 0, sizeof(sb));
372 
373 	assert(mode == 'A' || mode == 'd' || mode == 'm' || mode == 'q' ||
374 	    mode == 'r' || mode == 's');
375 
376 	/*
377 	 * Test if the specified archive exists, to determine
378 	 * whether we are creating a new archive.
379 	 */
380 	if (stat(bsdar->filename, &sb) != 0) {
381 		if (errno != ENOENT) {
382 			bsdar_warnc(bsdar, errno, "stat %s failed",
383 			    bsdar->filename);
384 			return (EXIT_FAILURE);
385 		}
386 
387 		/* We do not create archive in mode 'd', 'm' and 's'.  */
388 		if (mode != 'r' && mode != 'q') {
389 			bsdar_warnc(bsdar, 0, "%s: no such file",
390 			    bsdar->filename);
391 			return (EXIT_FAILURE);
392 		}
393 
394 		/* Issue a message if the '-c' option was not specified. */
395 		if (!(bsdar->options & AR_C))
396 			bsdar_warnc(bsdar, 0, "creating %s", bsdar->filename);
397 		goto new_archive;
398 	}
399 
400 	bsdar->ar_dev = sb.st_dev;
401 	bsdar->ar_ino = sb.st_ino;
402 
403 	/*
404 	 * First read members from the existing archive.
405 	 */
406 	read_objs(bsdar, bsdar->filename, 0);
407 
408 	/*
409 	 * For mode 's', no member will be moved, deleted or replaced.
410 	 */
411 	if (mode == 's')
412 		goto write_objs;
413 
414 	/*
415 	 * For mode 'q', we don't need to adjust existing members either.
416 	 * Also, -a, -b and -i are ignored in this mode. New members are
417 	 * always inserted at tail.
418 	 */
419 	if (mode == 'q')
420 		goto new_archive;
421 
422 	/*
423 	 * Mode 'A' adds the contents of another archive to the tail
424 	 * of current archive. Note that mode 'A' is a special mode
425 	 * for the 'ADDLIB' command in ar's script mode. Currently
426 	 * there is no option that invokes this function from ar's
427 	 * command line.
428 	 */
429 	if (mode == 'A') {
430 		/*
431 		 * Read objects from the target archive of the
432 		 * 'ADDLIB' command.  If there are members specified in
433 		 * 'argv', read those members only, otherwise the
434 		 * entire archive will be read.
435 		 */
436 		read_objs(bsdar, bsdar->addlib, 1);
437 		goto write_objs;
438 	}
439 
440 	/*
441 	 * Try to find the position member specified by user.
442 	 */
443 	if (bsdar->options & AR_A || bsdar->options & AR_B) {
444 		TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
445 			if (strcmp(obj->name, bsdar->posarg) == 0) {
446 				pos = obj;
447 				break;
448 			}
449 		}
450 
451 		/*
452 		 * If we cannot find the position specified by the
453 		 * user, silently insert objects at the tail of the
454 		 * list.
455 		 */
456 		if (pos == NULL)
457 			bsdar->options &= ~(AR_A | AR_B);
458 	}
459 
460 	for (i = 0; i < bsdar->argc; i++) {
461 		av = &bsdar->argv[i];
462 
463 		TAILQ_FOREACH_SAFE(obj, &bsdar->v_obj, objs, obj_temp) {
464 			if ((bname = basename(*av)) == NULL)
465 				bsdar_errc(bsdar, errno, "basename failed");
466 			if (bsdar->options & AR_TR) {
467 				if (strncmp(bname, obj->name, _TRUNCATE_LEN))
468 					continue;
469 			} else
470 				if (strcmp(bname, obj->name) != 0)
471 					continue;
472 
473 			if (mode == 'r') {
474 				/*
475 				 * If the new member should not
476 				 * replace the old one, skip it.
477 				 */
478 				nobj = create_obj_from_file(bsdar, *av,
479 				    obj->mtime);
480 				if (nobj == NULL) {
481 					exitcode = EXIT_FAILURE;
482 					goto skip_obj;
483 				}
484 			}
485 
486 			if (bsdar->options & AR_V)
487 				(void)fprintf(bsdar->output, "%c - %s\n",
488 				    mode, *av);
489 
490 			TAILQ_REMOVE(&bsdar->v_obj, obj, objs);
491 			if (mode == 'd' || mode == 'r')
492 				free_obj(obj);
493 
494 			if (mode == 'm')
495 				insert_obj(bsdar, obj, pos);
496 			if (mode == 'r')
497 				insert_obj(bsdar, nobj, pos);
498 
499 		skip_obj:
500 			*av = NULL;
501 			break;
502 		}
503 
504 	}
505 
506 new_archive:
507 	/*
508 	 * When operating in mode 'r', directly add the specified
509 	 * objects which do not exist in current archive. When
510 	 * operating in mode 'q', all objects specified by the command
511 	 * line args are appended to the archive, without checking
512 	 * existing members in the archive.
513 	 */
514 	for (i = 0; i < bsdar->argc; i++) {
515 		av = &bsdar->argv[i];
516 		if (*av != NULL && (mode == 'r' || mode == 'q')) {
517 			nobj = create_obj_from_file(bsdar, *av, 0);
518 			if (nobj == NULL) {
519 				exitcode = EXIT_FAILURE;
520 				*av = NULL;
521 				continue;
522 			}
523 			insert_obj(bsdar, nobj, pos);
524 			if (bsdar->options & AR_V)
525 				(void)fprintf(bsdar->output, "a - %s\n", *av);
526 			*av = NULL;
527 		}
528 	}
529 
530 write_objs:
531 	write_objs(bsdar);
532 	write_cleanup(bsdar);
533 
534 	return (exitcode);
535 }
536 
537 /*
538  * Release memory.
539  */
540 static void
541 write_cleanup(struct bsdar *bsdar)
542 {
543 	struct ar_obj		*obj, *obj_temp;
544 
545 	TAILQ_FOREACH_SAFE(obj, &bsdar->v_obj, objs, obj_temp) {
546 		TAILQ_REMOVE(&bsdar->v_obj, obj, objs);
547 		free_obj(obj);
548 	}
549 
550 	free(bsdar->as);
551 	free(bsdar->s_so);
552 	free(bsdar->s_sn);
553 	bsdar->as = NULL;
554 	bsdar->s_so = NULL;
555 	bsdar->s_sn = NULL;
556 }
557 
558 /*
559  * Wrapper for archive_write_data().
560  */
561 static void
562 write_data(struct bsdar *bsdar, struct archive *a, const void *buf, size_t s)
563 {
564 	if (archive_write_data(a, buf, s) != (ssize_t)s)
565 		bsdar_errc(bsdar, 0, "%s", archive_error_string(a));
566 }
567 
568 /*
569  * Compute the size of the symbol table for an archive.
570  */
571 static size_t
572 bsdar_symtab_size(struct bsdar *bsdar)
573 {
574 	size_t sz;
575 
576 	if (bsdar->options & AR_BSD) {
577 		/*
578 		 * A BSD style symbol table has two parts.
579 		 * Each part is preceded by its size in bytes,
580 		 * encoded as a C 'long'.  In the first part,
581 		 * there are 's_cnt' entries, each entry being
582 		 * 2 'long's in size.  The second part
583 		 * contains a string table.
584 		 */
585 		sz = 2 * sizeof(long) + (bsdar->s_cnt * 2 * sizeof(long)) +
586 		    bsdar->s_sn_sz;
587 	} else {
588 		/*
589 		 * An SVR4 style symbol table comprises of a 32 bit
590 		 * number holding the number of entries, followed by
591 		 * that many 32-bit offsets, followed by a string
592 		 * table.
593 		 */
594 		sz = sizeof(uint32_t) + bsdar->s_cnt * sizeof(uint32_t) +
595 		    bsdar->s_sn_sz;
596 	}
597 
598 	return (sz);
599 }
600 
601 static void
602 write_svr4_symtab_entry(struct bsdar *bsdar, struct archive *a)
603 {
604 	int		nr;
605 	uint32_t	i;
606 
607 	/* Translate offsets to big-endian form. */
608 	for (i = 0; i < bsdar->s_cnt; i++)
609 		bsdar->s_so[i] = htobe32(bsdar->s_so[i]);
610 
611 	nr = htobe32(bsdar->s_cnt);
612 	write_data(bsdar, a, &nr, sizeof(uint32_t));
613 	write_data(bsdar, a, bsdar->s_so, sizeof(uint32_t) *
614 	    bsdar->s_cnt);
615 	write_data(bsdar, a, bsdar->s_sn, bsdar->s_sn_sz);
616 }
617 
618 static void
619 write_bsd_symtab_entry(struct bsdar *bsdar, struct archive *a)
620 {
621 	long br_sz, br_off, br_strx;
622 	char *s;
623 	uint32_t i;
624 
625 	/*
626 	 * Write out the size in the byte of the array of 'ranlib'
627 	 * descriptors to follow.
628 	 */
629 
630 	br_sz = (long) (bsdar->s_cnt * 2 * sizeof(long));
631 	write_data(bsdar, a, &br_sz, sizeof(long));
632 
633 	/*
634 	 * Write out the array of 'ranlib' descriptors.  Each
635 	 * descriptor comprises of (a) an offset into the following
636 	 * string table and (b) a file offset to the relevant member.
637 	 */
638 	for (i = 0, s = bsdar->s_sn; i < bsdar->s_cnt; i++) {
639 		br_strx = (long) (s - bsdar->s_sn);
640 		br_off = (long) bsdar->s_so[i];
641 		write_data(bsdar, a, &br_strx, sizeof(long));
642 		write_data(bsdar, a, &br_off, sizeof(long));
643 
644 		/* Find the start of the next symbol in the string table. */
645 		while (*s++ != '\0')
646 			;
647 	}
648 
649 	/*
650 	 * Write out the size of the string table as a 'long',
651 	 * followed by the string table itself.
652 	 */
653 	br_sz = (long) bsdar->s_sn_sz;
654 	write_data(bsdar, a, &br_sz, sizeof(long));
655 	write_data(bsdar, a, bsdar->s_sn, bsdar->s_sn_sz);
656 }
657 
658 
659 /*
660  * Write the resulting archive members.
661  */
662 static void
663 write_objs(struct bsdar *bsdar)
664 {
665 	struct ar_obj		*obj;
666 	struct archive		*a;
667 	struct archive_entry	*entry;
668 	size_t s_sz;		/* size of archive symbol table. */
669 	size_t pm_sz;		/* size of pseudo members */
670 	size_t namelen;		/* size of member name. */
671 	size_t obj_sz;		/* size of object + extended header. */
672 	int			 i;
673 	char			*buf;
674 	const char		*entry_name;
675 
676 	bsdar->rela_off = 0;
677 
678 	/*
679 	 * Create the archive symbol table and the archive string
680 	 * table, if needed.
681 	 */
682 	TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
683 		if (!(bsdar->options & AR_SS) && obj->elf != NULL)
684 			create_symtab_entry(bsdar, obj->elf);
685 
686 		obj_sz = 0;
687 		namelen = strlen(obj->name);
688 		if (bsdar->options & AR_BSD) {
689 			/* Account for the space used by the file name. */
690 			if (namelen > _MAXNAMELEN_BSD ||
691 			    strchr(obj->name, ' '))
692 				obj_sz += namelen;
693 		} else if (namelen > _MAXNAMELEN_SVR4)
694 			add_to_ar_str_table(bsdar, obj->name);
695 
696 		obj_sz += obj->size; /* add the actual object size  */
697 
698 		/* Roundup the final size and add the header length. */
699 		bsdar->rela_off += _ARHDR_LEN + obj_sz + (obj_sz & 1);
700 	}
701 
702 	/*
703 	 * Pad the symbol name string table. It is treated specially
704 	 * because symbol name table should be padded by a '\0', and
705 	 * not '\n' as for normal members. The size of the 'sn' table
706 	 * includes the pad byte.
707 	 */
708 	if (bsdar->s_cnt != 0 && bsdar->s_sn_sz % 2 != 0)
709 		bsdar->s_sn[bsdar->s_sn_sz++] = '\0';
710 
711 	/*
712 	 * The archive string table is padded by a "\n" like a normal
713 	 * member.  The difference is that the size of archive string
714 	 * table includes the pad byte, while normal members' size
715 	 * fields do not.
716 	 */
717 	if (bsdar->as != NULL && bsdar->as_sz % 2 != 0)
718 		bsdar->as[bsdar->as_sz++] = '\n';
719 
720 	/*
721 	 * If there is a symbol table, calculate the size of pseudo
722 	 * members, and convert previously stored relative offsets to
723 	 * absolute ones.
724 	 *
725 	 * absolute_offset = relative_offset + size_of_pseudo_members)
726 	 */
727 
728 	s_sz = bsdar_symtab_size(bsdar);
729 	if (bsdar->s_cnt != 0) {
730 		pm_sz = _ARMAG_LEN + (_ARHDR_LEN + s_sz);
731 		if (bsdar->as != NULL) /* SVR4 archives only */
732 			pm_sz += _ARHDR_LEN + bsdar->as_sz;
733 		for (i = 0; (size_t) i < bsdar->s_cnt; i++)
734 			bsdar->s_so[i] = bsdar->s_so[i] + pm_sz;
735 	}
736 
737 	if ((a = archive_write_new()) == NULL)
738 		bsdar_errc(bsdar, 0, "archive_write_new failed");
739 
740 	if (bsdar->options & AR_BSD)
741 		archive_write_set_format_ar_bsd(a);
742 	else
743 		archive_write_set_format_ar_svr4(a);
744 
745 	AC(archive_write_open_filename(a, bsdar->filename));
746 
747 	/*
748 	 * Write the archive symbol table, if there is one.  If
749 	 * options '-s' was explicitly specified or if we were invoked
750 	 * as 'ranlib', write the symbol table even if it is empty.
751 	 */
752 	if ((bsdar->s_cnt != 0 && !(bsdar->options & AR_SS)) ||
753 	    bsdar->options & AR_S) {
754 		if (bsdar->options & AR_BSD)
755 			entry_name = AR_SYMTAB_NAME_BSD;
756 		else
757 			entry_name = AR_SYMTAB_NAME_SVR4;
758 
759 		entry = archive_entry_new();
760 		archive_entry_copy_pathname(entry, entry_name);
761 		if ((bsdar->options & AR_D) == 0)
762 			archive_entry_set_mtime(entry, time(NULL), 0);
763 		archive_entry_set_size(entry, s_sz);
764 		AC(archive_write_header(a, entry));
765 		if (bsdar->options & AR_BSD)
766 			write_bsd_symtab_entry(bsdar, a);
767 		else
768 			write_svr4_symtab_entry(bsdar, a);
769 		archive_entry_free(entry);
770 	}
771 
772 	/* Write the archive string table, if any. */
773 	if (bsdar->as != NULL) {
774 		entry = archive_entry_new();
775 		archive_entry_copy_pathname(entry, AR_STRINGTAB_NAME_SVR4);
776 		archive_entry_set_size(entry, bsdar->as_sz);
777 		AC(archive_write_header(a, entry));
778 		write_data(bsdar, a, bsdar->as, bsdar->as_sz);
779 		archive_entry_free(entry);
780 	}
781 
782 	/* Write normal members. */
783 	TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
784 		if ((buf = elf_rawfile(obj->elf, NULL)) == NULL) {
785 			bsdar_warnc(bsdar, 0, "elf_rawfile() failed: %s",
786 			    elf_errmsg(-1));
787 			continue;
788 		}
789 
790 		entry = archive_entry_new();
791 		archive_entry_copy_pathname(entry, obj->name);
792 		archive_entry_set_uid(entry, obj->uid);
793 		archive_entry_set_gid(entry, obj->gid);
794 		archive_entry_set_mode(entry, obj->md);
795 		archive_entry_set_size(entry, obj->size);
796 		archive_entry_set_mtime(entry, obj->mtime, 0);
797 		archive_entry_set_dev(entry, obj->dev);
798 		archive_entry_set_ino(entry, obj->ino);
799 		archive_entry_set_filetype(entry, AE_IFREG);
800 		AC(archive_write_header(a, entry));
801 		write_data(bsdar, a, buf, obj->size);
802 		archive_entry_free(entry);
803 	}
804 
805 	AC(archive_write_close(a));
806 	ACV(archive_write_free(a));
807 }
808 
809 /*
810  * Extract global symbols from ELF binary members.
811  */
812 static void
813 create_symtab_entry(struct bsdar *bsdar, Elf *e)
814 {
815 	Elf_Scn		*scn;
816 	GElf_Shdr	 shdr;
817 	GElf_Sym	 sym;
818 	Elf_Data	*data;
819 	char		*name;
820 	size_t		 n, shstrndx;
821 	int		 elferr, tabndx, len, i;
822 
823 	if (elf_kind(e) != ELF_K_ELF) {
824 		/* Silently a ignore non-ELF member. */
825 		return;
826 	}
827 	if (elf_getshstrndx(e, &shstrndx) == 0) {
828 		bsdar_warnc(bsdar, 0, "elf_getshstrndx failed: %s",
829 		     elf_errmsg(-1));
830 		return;
831 	}
832 
833 	tabndx = -1;
834 	scn = NULL;
835 	while ((scn = elf_nextscn(e, scn)) != NULL) {
836 		if (gelf_getshdr(scn, &shdr) != &shdr) {
837 			bsdar_warnc(bsdar, 0,
838 			    "elf_getshdr failed: %s", elf_errmsg(-1));
839 			continue;
840 		}
841 		if ((name = elf_strptr(e, shstrndx, shdr.sh_name)) == NULL) {
842 			bsdar_warnc(bsdar, 0,
843 			    "elf_strptr failed: %s", elf_errmsg(-1));
844 			continue;
845 		}
846 		if (strcmp(name, ".strtab") == 0) {
847 			tabndx = elf_ndxscn(scn);
848 			break;
849 		}
850 	}
851 	elferr = elf_errno();
852 	if (elferr != 0)
853 		bsdar_warnc(bsdar, 0, "elf_nextscn failed: %s",
854 		     elf_errmsg(elferr));
855 	if (tabndx == -1) {
856 		bsdar_warnc(bsdar, 0, "can't find .strtab section");
857 		return;
858 	}
859 
860 	scn = NULL;
861 	while ((scn = elf_nextscn(e, scn)) != NULL) {
862 		if (gelf_getshdr(scn, &shdr) != &shdr) {
863 			bsdar_warnc(bsdar, 0, "elf_getshdr failed: %s",
864 			    elf_errmsg(-1));
865 			continue;
866 		}
867 		if (shdr.sh_type != SHT_SYMTAB)
868 			continue;
869 
870 		data = NULL;
871 		n = 0;
872 		while (n < shdr.sh_size &&
873 		    (data = elf_getdata(scn, data)) != NULL) {
874 			len = data->d_size / shdr.sh_entsize;
875 			for (i = 0; i < len; i++) {
876 				if (gelf_getsym(data, i, &sym) != &sym) {
877 					bsdar_warnc(bsdar, 0,
878 					    "gelf_getsym failed: %s",
879 					     elf_errmsg(-1));
880 					continue;
881 				}
882 
883 				/* Keep only global and weak symbols. */
884 				if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL &&
885 				    GELF_ST_BIND(sym.st_info) != STB_WEAK)
886 					continue;
887 
888 				/* Keep only defined symbols. */
889 				if (sym.st_shndx == SHN_UNDEF)
890 					continue;
891 
892 				if ((name = elf_strptr(e, tabndx,
893 				    sym.st_name)) == NULL) {
894 					bsdar_warnc(bsdar, 0,
895 					    "elf_strptr failed: %s",
896 					     elf_errmsg(-1));
897 					continue;
898 				}
899 
900 				add_to_ar_sym_table(bsdar, name);
901 			}
902 		}
903 	}
904 	elferr = elf_errno();
905 	if (elferr != 0)
906 		bsdar_warnc(bsdar, 0, "elf_nextscn failed: %s",
907 		     elf_errmsg(elferr));
908 }
909 
910 /*
911  * Append to the archive string table buffer.
912  */
913 static void
914 add_to_ar_str_table(struct bsdar *bsdar, const char *name)
915 {
916 
917 	if (bsdar->as == NULL) {
918 		bsdar->as_cap = _INIT_AS_CAP;
919 		bsdar->as_sz = 0;
920 		if ((bsdar->as = malloc(bsdar->as_cap)) == NULL)
921 			bsdar_errc(bsdar, errno, "malloc failed");
922 	}
923 
924 	/*
925 	 * The space required for holding one member name in the 'as'
926 	 * table includes: strlen(name) + (1 for '/') + (1 for '\n') +
927 	 * (possibly 1 for padding).
928 	 */
929 	while (bsdar->as_sz + strlen(name) + 3 > bsdar->as_cap) {
930 		bsdar->as_cap *= 2;
931 		bsdar->as = realloc(bsdar->as, bsdar->as_cap);
932 		if (bsdar->as == NULL)
933 			bsdar_errc(bsdar, errno, "realloc failed");
934 	}
935 	strncpy(&bsdar->as[bsdar->as_sz], name, strlen(name));
936 	bsdar->as_sz += strlen(name);
937 	bsdar->as[bsdar->as_sz++] = '/';
938 	bsdar->as[bsdar->as_sz++] = '\n';
939 }
940 
941 /*
942  * Append to the archive symbol table buffer.
943  */
944 static void
945 add_to_ar_sym_table(struct bsdar *bsdar, const char *name)
946 {
947 
948 	if (bsdar->s_so == NULL) {
949 		if ((bsdar->s_so = malloc(_INIT_SYMOFF_CAP)) ==
950 		    NULL)
951 			bsdar_errc(bsdar, errno, "malloc failed");
952 		bsdar->s_so_cap = _INIT_SYMOFF_CAP;
953 		bsdar->s_cnt = 0;
954 	}
955 
956 	if (bsdar->s_sn == NULL) {
957 		if ((bsdar->s_sn = malloc(_INIT_SYMNAME_CAP)) == NULL)
958 			bsdar_errc(bsdar, errno, "malloc failed");
959 		bsdar->s_sn_cap = _INIT_SYMNAME_CAP;
960 		bsdar->s_sn_sz = 0;
961 	}
962 
963 	if (bsdar->s_cnt * sizeof(uint32_t) >= bsdar->s_so_cap) {
964 		bsdar->s_so_cap *= 2;
965 		bsdar->s_so = realloc(bsdar->s_so, bsdar->s_so_cap);
966 		if (bsdar->s_so == NULL)
967 			bsdar_errc(bsdar, errno, "realloc failed");
968 	}
969 	bsdar->s_so[bsdar->s_cnt] = bsdar->rela_off;
970 	bsdar->s_cnt++;
971 
972 	/*
973 	 * The space required for holding one symbol name in the 'sn'
974 	 * table includes: strlen(name) + (1 for '\n') + (possibly 1
975 	 * for padding).
976 	 */
977 	while (bsdar->s_sn_sz + strlen(name) + 2 > bsdar->s_sn_cap) {
978 		bsdar->s_sn_cap *= 2;
979 		bsdar->s_sn = realloc(bsdar->s_sn, bsdar->s_sn_cap);
980 		if (bsdar->s_sn == NULL)
981 			bsdar_errc(bsdar, errno, "realloc failed");
982 	}
983 	strncpy(&bsdar->s_sn[bsdar->s_sn_sz], name, strlen(name));
984 	bsdar->s_sn_sz += strlen(name);
985 	bsdar->s_sn[bsdar->s_sn_sz++] = '\0';
986 }
987