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