write.c revision 177064
1331722Seadler/*-
223661Speter * Copyright (c) 2007 Kai Wang
31573Srgrimes * All rights reserved.
41573Srgrimes *
51573Srgrimes * Redistribution and use in source and binary forms, with or without
61573Srgrimes * modification, are permitted provided that the following conditions
71573Srgrimes * are met:
81573Srgrimes * 1. Redistributions of source code must retain the above copyright
91573Srgrimes *    notice, this list of conditions and the following disclaimer
101573Srgrimes *    in this position and unchanged.
111573Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
121573Srgrimes *    notice, this list of conditions and the following disclaimer in the
131573Srgrimes *    documentation and/or other materials provided with the distribution.
141573Srgrimes *
151573Srgrimes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
161573Srgrimes * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
171573Srgrimes * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
181573Srgrimes * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
191573Srgrimes * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
201573Srgrimes * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
211573Srgrimes * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
221573Srgrimes * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
231573Srgrimes * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
241573Srgrimes * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
251573Srgrimes */
261573Srgrimes
271573Srgrimes#include <sys/cdefs.h>
281573Srgrimes__FBSDID("$FreeBSD: head/usr.bin/ar/write.c 177064 2008-03-11 18:35:51Z kaiw $");
291573Srgrimes
301573Srgrimes#include <sys/endian.h>
3123661Speter#include <sys/mman.h>
321573Srgrimes#include <sys/queue.h>
3390041Sobrien#include <sys/stat.h>
3490041Sobrien#include <archive.h>
351573Srgrimes#include <archive_entry.h>
3671579Sdeischen#include <errno.h>
371573Srgrimes#include <fcntl.h>
381573Srgrimes#include <gelf.h>
391573Srgrimes#include <libgen.h>
4023661Speter#include <stdio.h>
411573Srgrimes#include <stdlib.h>
4223661Speter#include <string.h>
431573Srgrimes#include <sysexits.h>
441573Srgrimes
451573Srgrimes#include "ar.h"
461573Srgrimes
4771579Sdeischen#define _ARMAG_LEN 8		/* length of ar magic string */
481573Srgrimes#define _ARHDR_LEN 60		/* length of ar header */
49235647Sgleb#define _INIT_AS_CAP 128	/* initial archive string table size */
50235647Sgleb#define _INIT_SYMOFF_CAP (256*(sizeof(uint32_t))) /* initial so table size */
511573Srgrimes#define _INIT_SYMNAME_CAP 1024			  /* initial sn table size */
521573Srgrimes#define _MAXNAMELEN_SVR4 15	/* max member name length in svr4 variant */
5317141Sjkh#define _TRUNCATE_LEN 15	/* number of bytes to keep for member name */
541573Srgrimes
55109039Stjrstatic void	add_to_ar_str_table(struct bsdar *bsdar, const char *name);
56109039Stjrstatic void	add_to_ar_sym_table(struct bsdar *bsdar, const char *name);
571573Srgrimesstatic struct ar_obj	*create_obj_from_file(struct bsdar *bsdar,
58288029Srodrigc		    const char *name, time_t mtime);
591573Srgrimesstatic void	create_symtab_entry(struct bsdar *bsdar, void *maddr,
6090041Sobrien		    size_t size);
6190041Sobrienstatic void	insert_obj(struct bsdar *bsdar, struct ar_obj *obj,
6290041Sobrien		    struct ar_obj *pos);
6390041Sobrienstatic void	write_archive(struct bsdar *bsdar, char mode);
6490041Sobrienstatic void	write_cleanup(struct bsdar *bsdar);
65198053Sjillesstatic void	write_data(struct bsdar *bsdar, struct archive *a,
661573Srgrimes		    const void *buf, size_t s);
671573Srgrimesstatic void	write_objs(struct bsdar *bsdar);
681573Srgrimes
69198053Sjillesvoid
701573Srgrimesar_mode_d(struct bsdar *bsdar)
71198053Sjilles{
72198053Sjilles
731573Srgrimes	write_archive(bsdar, 'd');
741573Srgrimes}
751573Srgrimes
761573Srgrimesvoid
771573Srgrimesar_mode_m(struct bsdar *bsdar)
781573Srgrimes{
791573Srgrimes
801573Srgrimes	write_archive(bsdar, 'm');
811573Srgrimes}
821573Srgrimes
831573Srgrimesvoid
841573Srgrimesar_mode_q(struct bsdar *bsdar)
855072Sbde{
865072Sbde
875072Sbde	write_archive(bsdar, 'q');
885072Sbde}
891573Srgrimes
901573Srgrimesvoid
91150172Sachear_mode_r(struct bsdar *bsdar)
921573Srgrimes{
931573Srgrimes
941573Srgrimes	write_archive(bsdar, 'r');
9565468Speter}
9665468Speter
9765468Spetervoid
9865468Speterar_mode_s(struct bsdar *bsdar)
9965468Speter{
10065468Speter
10165468Speter	write_archive(bsdar, 's');
10265468Speter}
10329476Sphk
10429392Sphk/*
10565468Speter * Create object from file, return created obj upon success, or NULL
10629392Sphk * when an error occurs or the member is not newer than existing
1071573Srgrimes * one while -u is specifed.
1081573Srgrimes */
1091573Srgrimesstatic struct ar_obj *
1101573Srgrimescreate_obj_from_file(struct bsdar *bsdar, const char *name, time_t mtime)
1111573Srgrimes{
1121573Srgrimes	struct ar_obj		*obj;
1131573Srgrimes	struct stat		 sb;
1141573Srgrimes	const char		*bname;
1151573Srgrimes
1161573Srgrimes	if (name == NULL)
1171573Srgrimes		return (NULL);
1181573Srgrimes
1191573Srgrimes	obj = malloc(sizeof(struct ar_obj));
120235647Sgleb	if (obj == NULL)
1211573Srgrimes		bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
1221573Srgrimes	if ((obj->fd = open(name, O_RDONLY, 0)) < 0) {
1231573Srgrimes		bsdar_warnc(bsdar, errno, "can't open file: %s", name);
1241573Srgrimes		free(obj);
1251573Srgrimes		return (NULL);
1261573Srgrimes	}
1271573Srgrimes
1281573Srgrimes	if ((bname = basename(name)) == NULL)
1291573Srgrimes		bsdar_errc(bsdar, EX_SOFTWARE, errno, "basename failed");
1301573Srgrimes	if (bsdar->options & AR_TR && strlen(bname) > _TRUNCATE_LEN) {
1311573Srgrimes		if ((obj->name = malloc(_TRUNCATE_LEN + 1)) == NULL)
1321573Srgrimes			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
1331573Srgrimes		(void)strncpy(obj->name, bname, _TRUNCATE_LEN);
1341573Srgrimes		obj->name[_TRUNCATE_LEN] = '\0';
1359272Shsu	} else
136198053Sjilles		if ((obj->name = strdup(bname)) == NULL)
137198053Sjilles		    bsdar_errc(bsdar, EX_SOFTWARE, errno, "strdup failed");
1381573Srgrimes
1391573Srgrimes	if (fstat(obj->fd, &sb) < 0) {
1401573Srgrimes		bsdar_warnc(bsdar, errno, "can't fstat file: %s", obj->name);
1411573Srgrimes		goto giveup;
142235647Sgleb	}
143241046Sjilles	if (!S_ISREG(sb.st_mode)) {
144198053Sjilles		bsdar_warnc(bsdar, 0, "%s is not an ordinary file", obj->name);
1451573Srgrimes		goto giveup;
146198053Sjilles	}
147198053Sjilles
148235647Sgleb	/*
149198053Sjilles	 * When option '-u' is specified and member is not newer than the
150198053Sjilles	 * existing one, the replace will not happen. While if mtime == 0,
151198053Sjilles	 * which indicates that this is to "replace a none exist member",
1521573Srgrimes	 * the replace will proceed regardless of '-u'.
1531573Srgrimes	 */
1541573Srgrimes	if (mtime != 0 && bsdar->options & AR_U && sb.st_mtime <= mtime)
1551573Srgrimes		goto giveup;
1561573Srgrimes
1571573Srgrimes	obj->uid = sb.st_uid;
1581573Srgrimes	obj->gid = sb.st_gid;
1591573Srgrimes	obj->md = sb.st_mode;
1601573Srgrimes	obj->size = sb.st_size;
1611573Srgrimes	obj->mtime = sb.st_mtime;
1621573Srgrimes	obj->dev = sb.st_dev;
1631573Srgrimes	obj->ino = sb.st_ino;
1641573Srgrimes
1651573Srgrimes	if (obj->size == 0) {
1661573Srgrimes		obj->maddr = NULL;
1671573Srgrimes		return (obj);
1681573Srgrimes	}
1691573Srgrimes
1701573Srgrimes	if ((obj->maddr = mmap(NULL, obj->size, PROT_READ,
1711573Srgrimes	    MAP_PRIVATE, obj->fd, (off_t)0)) == MAP_FAILED) {
1721573Srgrimes		bsdar_warnc(bsdar, errno, "can't mmap file: %s", obj->name);
1731573Srgrimes		goto giveup;
174235647Sgleb	}
175198053Sjilles	if (close(obj->fd) < 0)
1761573Srgrimes		bsdar_errc(bsdar, EX_SOFTWARE, errno, "close failed: %s",
1771573Srgrimes		    obj->name);
1781573Srgrimes
1791573Srgrimes	return (obj);
1801573Srgrimes
1811573Srgrimesgiveup:
1821573Srgrimes	if (close(obj->fd) < 0)
1831573Srgrimes		bsdar_errc(bsdar, EX_SOFTWARE, errno, "close failed: %s",
1841573Srgrimes		    obj->name);
1851573Srgrimes	free(obj->name);
1861573Srgrimes	free(obj);
1871573Srgrimes	return (NULL);
1881573Srgrimes}
189150297Sache
1901573Srgrimes/*
1911573Srgrimes * Insert obj to the tail, or before/after the pos obj.
1921573Srgrimes */
1931573Srgrimesstatic void
1941573Srgrimesinsert_obj(struct bsdar *bsdar, struct ar_obj *obj, struct ar_obj *pos)
1951573Srgrimes{
1961573Srgrimes	if (obj == NULL)
1971573Srgrimes		bsdar_errc(bsdar, EX_SOFTWARE, 0, "try to insert a null obj");
198109040Stjr
1991573Srgrimes	if (pos == NULL || obj == pos)
2001573Srgrimes		/*
2011573Srgrimes		 * If the object to move happens to be the posistion obj,
2029272Shsu		 * or if there is not a pos obj, move it to tail.
2031573Srgrimes		 */
2041573Srgrimes		goto tail;
2051573Srgrimes
2061573Srgrimes	if (bsdar->options & AR_B) {
2071573Srgrimes		TAILQ_INSERT_BEFORE(pos, obj, objs);
2081573Srgrimes		return;
2091573Srgrimes	}
2101573Srgrimes	if (bsdar->options & AR_A) {
2111573Srgrimes		TAILQ_INSERT_AFTER(&bsdar->v_obj, pos, obj, objs);
2121573Srgrimes		return;
2131573Srgrimes	}
2141573Srgrimes
2151573Srgrimestail:
2161573Srgrimes	TAILQ_INSERT_TAIL(&bsdar->v_obj, obj, objs);
2171573Srgrimes
2181573Srgrimes}
2191573Srgrimes
2201573Srgrimes/*
22132530Smckay * Determine the constitution of resulting archive.
22232530Smckay */
2231573Srgrimesstatic void
2241573Srgrimeswrite_archive(struct bsdar *bsdar, char mode)
22528235Sdg{
22628235Sdg	struct archive		 *a;
22732530Smckay	struct archive_entry	 *entry;
22832530Smckay	struct ar_obj		 *nobj, *obj, *obj_temp, *pos;
2291573Srgrimes	struct stat		  sb;
2301573Srgrimes	const char		 *name;
231	const char		 *bname;
232	char			 *buff;
233	char			**av;
234	size_t			  size;
235	int			  i, r;
236
237	TAILQ_INIT(&bsdar->v_obj);
238	nobj = NULL;
239	pos = NULL;
240	memset(&sb, 0, sizeof(sb));
241
242	/* By default, no compression is assumed. */
243	bsdar->compression = ARCHIVE_COMPRESSION_NONE;
244
245	/*
246	 * Test if the specified archive exists, to figure out
247         * whether we are creating one here.
248	 */
249	if (stat(bsdar->filename, &sb) != 0) {
250		if (errno != ENOENT) {
251			bsdar_warnc(bsdar, 0, "stat %s failed",
252			    bsdar->filename);
253			return;
254		}
255
256		/* We do not create archive in mode 'd', 'm' and 's'.  */
257		if (mode != 'r' && mode != 'q') {
258			bsdar_warnc(bsdar, 0, "%s: no such file",
259			    bsdar->filename);
260			return;
261		}
262
263		/* Issue a warning if -c is not specified when creating. */
264		if (!(bsdar->options & AR_C))
265			bsdar_warnc(bsdar, 0, "creating %s", bsdar->filename);
266		goto new_archive;
267	}
268
269	/*
270	 * First read members from existing archive.
271	 */
272	if ((a = archive_read_new()) == NULL)
273		bsdar_errc(bsdar, EX_SOFTWARE, 0, "archive_read_new failed");
274	archive_read_support_compression_all(a);
275	archive_read_support_format_ar(a);
276	AC(archive_read_open_filename(a, bsdar->filename, DEF_BLKSZ));
277	for (;;) {
278		r = archive_read_next_header(a, &entry);
279		if (r == ARCHIVE_FATAL)
280			bsdar_errc(bsdar, EX_DATAERR, 0, "%s",
281			    archive_error_string(a));
282		if (r == ARCHIVE_EOF)
283			break;
284		if (r == ARCHIVE_WARN || r == ARCHIVE_RETRY)
285			bsdar_warnc(bsdar, 0, "%s", archive_error_string(a));
286		if (r == ARCHIVE_RETRY) {
287			bsdar_warnc(bsdar, 0, "Retrying...");
288			continue;
289		}
290
291		/*
292		 * Remember the compression mode of existing archive.
293		 * If neither -j nor -z is specified, this mode will
294		 * be used for resulting archive.
295		 */
296		bsdar->compression = archive_compression(a);
297
298		name = archive_entry_pathname(entry);
299
300		/*
301		 * skip pseudo members.
302		 */
303		if (strcmp(name, "/") == 0 || strcmp(name, "//") == 0)
304			continue;
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	 * For mode 's', no member will be moved, deleted or replaced.
347	 */
348	if (mode == 's')
349		goto write_objs;
350
351	/*
352	 * For mode 'q', we don't need to adjust existing members either.
353	 * Also, -a, -b and -i are ignored in this mode. New members are
354	 * always inserted at tail.
355	 */
356	if (mode == 'q')
357		goto new_archive;
358
359	/*
360	 * Try to find the position member specified by user.
361	 */
362	if (bsdar->options & AR_A || bsdar->options & AR_B) {
363		TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
364			if (strcmp(obj->name, bsdar->posarg) == 0) {
365				pos = obj;
366				break;
367			}
368		}
369
370		/*
371		 * If can't find `pos' specified by user,
372		 * sliently insert objects at tail.
373		 */
374		if (pos == NULL)
375			bsdar->options &= ~(AR_A | AR_B);
376	}
377
378	for (i = 0; i < bsdar->argc; i++) {
379		av = &bsdar->argv[i];
380
381		TAILQ_FOREACH_SAFE(obj, &bsdar->v_obj, objs, obj_temp) {
382			if ((bname = basename(*av)) == NULL)
383				bsdar_errc(bsdar, EX_SOFTWARE, errno,
384				    "basename failed");
385			if (bsdar->options & AR_TR) {
386				if (strncmp(bname, obj->name, _TRUNCATE_LEN))
387					continue;
388			} else
389				if (strcmp(bname, obj->name) != 0)
390					continue;
391
392			if (mode == 'r') {
393				/*
394				 * if the new member is not qualified
395				 * to replace the old one, skip it.
396				 */
397				nobj = create_obj_from_file(bsdar, *av,
398				    obj->mtime);
399				if (nobj == NULL)
400					goto skip_obj;
401			}
402
403			if (bsdar->options & AR_V)
404				(void)fprintf(stdout, "%c - %s\n", mode,
405				    *av);
406
407			TAILQ_REMOVE(&bsdar->v_obj, obj, objs);
408			if (mode == 'd' || mode == 'r') {
409				free(obj->maddr);
410				free(obj->name);
411				free(obj);
412			}
413
414			if (mode == 'm')
415				insert_obj(bsdar, obj, pos);
416			if (mode == 'r')
417				insert_obj(bsdar, nobj, pos);
418
419		skip_obj:
420			*av = NULL;
421			break;
422		}
423
424	}
425
426new_archive:
427	/*
428	 * When operating in mode 'r', directly add those user specified
429	 * objects which do not exist in current archive. When operating
430	 * in mode 'q', all objects specified in command line args are
431	 * appended to the archive, without comparing with existing ones.
432	 */
433	for (i = 0; i < bsdar->argc; i++) {
434		av = &bsdar->argv[i];
435		if (*av != NULL && (mode == 'r' || mode == 'q')) {
436			nobj = create_obj_from_file(bsdar, *av, 0);
437			if (nobj != NULL)
438				insert_obj(bsdar, nobj, pos);
439			if (bsdar->options & AR_V && nobj != NULL)
440				(void)fprintf(stdout, "a - %s\n", *av);
441			*av = NULL;
442		}
443	}
444
445write_objs:
446	write_objs(bsdar);
447	write_cleanup(bsdar);
448}
449
450/*
451 * Memory cleaning up.
452 */
453static void
454write_cleanup(struct bsdar *bsdar)
455{
456	struct ar_obj		*obj, *obj_temp;
457
458	TAILQ_FOREACH_SAFE(obj, &bsdar->v_obj, objs, obj_temp) {
459		if (obj->fd == -1)
460			free(obj->maddr);
461		else
462			if (obj->maddr != NULL && munmap(obj->maddr, obj->size))
463				bsdar_warnc(bsdar, errno,
464				    "can't munmap file: %s", obj->name);
465		TAILQ_REMOVE(&bsdar->v_obj, obj, objs);
466		free(obj->name);
467		free(obj);
468	}
469
470	free(bsdar->as);
471	free(bsdar->s_so);
472	free(bsdar->s_sn);
473	bsdar->as = NULL;
474	bsdar->s_so = NULL;
475	bsdar->s_sn = NULL;
476}
477
478/*
479 * Wrapper for archive_write_data().
480 */
481static void
482write_data(struct bsdar *bsdar, struct archive *a, const void *buf, size_t s)
483{
484	if (archive_write_data(a, buf, s) != (ssize_t)s)
485		bsdar_errc(bsdar, EX_SOFTWARE, 0, "%s",
486		    archive_error_string(a));
487}
488
489/*
490 * Write the resulting archive members.
491 */
492static void
493write_objs(struct bsdar *bsdar)
494{
495	struct ar_obj		*obj;
496	struct archive		*a;
497	struct archive_entry	*entry;
498	size_t s_sz;		/* size of archive symbol table. */
499	size_t pm_sz;		/* size of pseudo members */
500	int			 i, nr;
501
502	if (elf_version(EV_CURRENT) == EV_NONE)
503		bsdar_errc(bsdar, EX_SOFTWARE, 0,
504		    "ELF library initialization failed: %s", elf_errmsg(-1));
505
506	bsdar->rela_off = 0;
507
508	/* Create archive symbol table and archive string table, if need. */
509	TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
510		if (!(bsdar->options & AR_SS) && obj->maddr != NULL)
511			create_symtab_entry(bsdar, obj->maddr, obj->size);
512		if (strlen(obj->name) > _MAXNAMELEN_SVR4)
513			add_to_ar_str_table(bsdar, obj->name);
514		bsdar->rela_off += _ARHDR_LEN + obj->size + obj->size % 2;
515	}
516
517	/*
518	 * Pad the symbol name string table. It is treated specially because
519	 * symbol name table should be padded by a '\0', not the common '\n'
520	 * for other members. The size of sn table includes the pad bit.
521	 */
522	if (bsdar->s_cnt != 0 && bsdar->s_sn_sz % 2 != 0)
523		bsdar->s_sn[bsdar->s_sn_sz++] = '\0';
524
525	/*
526	 * Archive string table is padded by a "\n" as the normal members.
527	 * The difference is that the size of archive string table counts
528	 * in the pad bit, while normal members' size fileds do not.
529	 */
530	if (bsdar->as != NULL && bsdar->as_sz % 2 != 0)
531		bsdar->as[bsdar->as_sz++] = '\n';
532
533	/*
534	 * If there is a symbol table, calculate the size of pseudo members,
535	 * convert previously stored relative offsets to absolute ones, and
536	 * then make them Big Endian.
537	 *
538	 * absolute_offset = htobe32(relative_offset + size_of_pseudo_members)
539	 */
540
541	if (bsdar->s_cnt != 0) {
542		s_sz = (bsdar->s_cnt + 1) * sizeof(uint32_t) + bsdar->s_sn_sz;
543		pm_sz = _ARMAG_LEN + (_ARHDR_LEN + s_sz);
544		if (bsdar->as != NULL)
545			pm_sz += _ARHDR_LEN + bsdar->as_sz;
546		for (i = 0; (size_t)i < bsdar->s_cnt; i++)
547			*(bsdar->s_so + i) = htobe32(*(bsdar->s_so + i) +
548			    pm_sz);
549	}
550
551	if ((a = archive_write_new()) == NULL)
552		bsdar_errc(bsdar, EX_SOFTWARE, 0, "archive_write_new failed");
553
554	archive_write_set_format_ar_svr4(a);
555
556	/* The compression mode of the existing archive is used
557	 * for the result archive or if creating a new archive, we
558	 * do not compress archive by default. This default behavior can
559	 * be overrided by compression mode specified explicitly
560	 * through command line option `-j' or `-z'.
561	 */
562	if (bsdar->options & AR_J)
563		bsdar->compression = ARCHIVE_COMPRESSION_BZIP2;
564	if (bsdar->options & AR_Z)
565		bsdar->compression = ARCHIVE_COMPRESSION_GZIP;
566	if (bsdar->compression == ARCHIVE_COMPRESSION_BZIP2)
567		archive_write_set_compression_bzip2(a);
568	else if (bsdar->compression == ARCHIVE_COMPRESSION_GZIP)
569		archive_write_set_compression_gzip(a);
570	else
571		archive_write_set_compression_none(a);
572
573	AC(archive_write_open_filename(a, bsdar->filename));
574
575	/*
576	 * write the archive symbol table, if there is one.
577	 * If options -s is explicitly specified or we are invoked
578	 * as ranlib, write the symbol table even if it is empty.
579	 */
580	if ((bsdar->s_cnt != 0 && !(bsdar->options & AR_SS)) ||
581	    bsdar->options & AR_S) {
582		entry = archive_entry_new();
583		archive_entry_copy_pathname(entry, "/");
584		archive_entry_set_mtime(entry, time(NULL), 0);
585		archive_entry_set_size(entry, (bsdar->s_cnt + 1) *
586		    sizeof(uint32_t) + bsdar->s_sn_sz);
587		AC(archive_write_header(a, entry));
588		nr = htobe32(bsdar->s_cnt);
589		write_data(bsdar, a, &nr, sizeof(uint32_t));
590		write_data(bsdar, a, bsdar->s_so, sizeof(uint32_t) *
591		    bsdar->s_cnt);
592		write_data(bsdar, a, bsdar->s_sn, bsdar->s_sn_sz);
593		archive_entry_free(entry);
594	}
595
596	/* write the archive string table, if any. */
597	if (bsdar->as != NULL) {
598		entry = archive_entry_new();
599		archive_entry_copy_pathname(entry, "//");
600		archive_entry_set_size(entry, bsdar->as_sz);
601		AC(archive_write_header(a, entry));
602		write_data(bsdar, a, bsdar->as, bsdar->as_sz);
603		archive_entry_free(entry);
604	}
605
606	/* write normal members. */
607	TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
608		entry = archive_entry_new();
609		archive_entry_copy_pathname(entry, obj->name);
610		archive_entry_set_uid(entry, obj->uid);
611		archive_entry_set_gid(entry, obj->gid);
612		archive_entry_set_mode(entry, obj->md);
613		archive_entry_set_size(entry, obj->size);
614		archive_entry_set_mtime(entry, obj->mtime, 0);
615		archive_entry_set_dev(entry, obj->dev);
616		archive_entry_set_ino(entry, obj->ino);
617		archive_entry_set_filetype(entry, AE_IFREG);
618		AC(archive_write_header(a, entry));
619		write_data(bsdar, a, obj->maddr, obj->size);
620		archive_entry_free(entry);
621	}
622
623	AC(archive_write_close(a));
624	AC(archive_write_finish(a));
625}
626
627/*
628 * Extract global symbols from ELF binary members.
629 */
630static void
631create_symtab_entry(struct bsdar *bsdar, void *maddr, size_t size)
632{
633	Elf		*e;
634	Elf_Scn		*scn;
635	GElf_Shdr	 shdr;
636	GElf_Sym	 sym;
637	Elf_Data	*data;
638	char		*name;
639	size_t		 n, shstrndx;
640	int		 elferr, tabndx, len, i;
641
642	if ((e = elf_memory(maddr, size)) == NULL) {
643		bsdar_warnc(bsdar, 0, "elf_memory() failed: %s",
644		     elf_errmsg(-1));
645		return;
646	}
647	if (elf_kind(e) != ELF_K_ELF) {
648		/* Sliently ignore non-elf member. */
649		elf_end(e);
650		return;
651	}
652	if (elf_getshstrndx(e, &shstrndx) == 0) {
653		bsdar_warnc(bsdar, EX_SOFTWARE, 0, "elf_getshstrndx failed: %s",
654		     elf_errmsg(-1));
655		elf_end(e);
656		return;
657	}
658
659	tabndx = -1;
660	scn = NULL;
661	while ((scn = elf_nextscn(e, scn)) != NULL) {
662		if (gelf_getshdr(scn, &shdr) != &shdr) {
663			bsdar_warnc(bsdar, 0,
664			    "elf_getshdr failed: %s", elf_errmsg(-1));
665			continue;
666		}
667		if ((name = elf_strptr(e, shstrndx, shdr.sh_name)) == NULL) {
668			bsdar_warnc(bsdar, 0,
669			    "elf_strptr failed: %s", elf_errmsg(-1));
670			continue;
671		}
672		if (strcmp(name, ".strtab") == 0) {
673			tabndx = elf_ndxscn(scn);
674			break;
675		}
676	}
677	elferr = elf_errno();
678	if (elferr != 0)
679		bsdar_warnc(bsdar, 0, "elf_nextscn failed: %s",
680		     elf_errmsg(elferr));
681	if (tabndx == -1) {
682		bsdar_warnc(bsdar, 0, "can't find .strtab section");
683		elf_end(e);
684		return;
685	}
686
687	scn = NULL;
688	while ((scn = elf_nextscn(e, scn)) != NULL) {
689		if (gelf_getshdr(scn, &shdr) != &shdr) {
690			bsdar_warnc(bsdar, EX_SOFTWARE, 0,
691			    "elf_getshdr failed: %s", elf_errmsg(-1));
692			continue;
693		}
694		if (shdr.sh_type != SHT_SYMTAB)
695			continue;
696
697		data = NULL;
698		n = 0;
699		while (n < shdr.sh_size &&
700		    (data = elf_getdata(scn, data)) != NULL) {
701			len = data->d_size / shdr.sh_entsize;
702			for (i = 0; i < len; i++) {
703				if (gelf_getsym(data, i, &sym) != &sym) {
704					bsdar_warnc(bsdar, EX_SOFTWARE, 0,
705					    "gelf_getsym failed: %s",
706					     elf_errmsg(-1));
707					continue;
708				}
709
710				/* keep only global or weak symbols */
711				if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL &&
712				    GELF_ST_BIND(sym.st_info) != STB_WEAK)
713					continue;
714
715				/* keep only defined symbols */
716				if (sym.st_shndx == SHN_UNDEF)
717					continue;
718
719				if ((name = elf_strptr(e, tabndx,
720				    sym.st_name)) == NULL) {
721					bsdar_warnc(bsdar, EX_SOFTWARE, 0,
722					    "elf_strptr failed: %s",
723					     elf_errmsg(-1));
724					continue;
725				}
726
727				add_to_ar_sym_table(bsdar, name);
728			}
729		}
730	}
731	elferr = elf_errno();
732	if (elferr != 0)
733		bsdar_warnc(bsdar, EX_SOFTWARE, 0, "elf_nextscn failed: %s",
734		     elf_errmsg(elferr));
735
736	elf_end(e);
737}
738
739/*
740 * Append to the archive string table buffer.
741 */
742static void
743add_to_ar_str_table(struct bsdar *bsdar, const char *name)
744{
745
746	if (bsdar->as == NULL) {
747		bsdar->as_cap = _INIT_AS_CAP;
748		bsdar->as_sz = 0;
749		if ((bsdar->as = malloc(bsdar->as_cap)) == NULL)
750			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
751	}
752
753	/*
754	 * The space required for holding one member name in as table includes:
755	 * strlen(name) + (1 for '/') + (1 for '\n') + (possibly 1 for padding).
756	 */
757	while (bsdar->as_sz + strlen(name) + 3 > bsdar->as_cap) {
758		bsdar->as_cap *= 2;
759		bsdar->as = realloc(bsdar->as, bsdar->as_cap);
760		if (bsdar->as == NULL)
761			bsdar_errc(bsdar, EX_SOFTWARE, errno, "realloc failed");
762	}
763	strncpy(&bsdar->as[bsdar->as_sz], name, strlen(name));
764	bsdar->as_sz += strlen(name);
765	bsdar->as[bsdar->as_sz++] = '/';
766	bsdar->as[bsdar->as_sz++] = '\n';
767}
768
769/*
770 * Append to the archive symbol table buffer.
771 */
772static void
773add_to_ar_sym_table(struct bsdar *bsdar, const char *name)
774{
775
776	if (bsdar->s_so == NULL) {
777		if ((bsdar->s_so = malloc(_INIT_SYMOFF_CAP)) ==
778		    NULL)
779			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
780		bsdar->s_so_cap = _INIT_SYMOFF_CAP;
781		bsdar->s_cnt = 0;
782	}
783
784	if (bsdar->s_sn == NULL) {
785		if ((bsdar->s_sn = malloc(_INIT_SYMNAME_CAP)) == NULL)
786			bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
787		bsdar->s_sn_cap = _INIT_SYMNAME_CAP;
788		bsdar->s_sn_sz = 0;
789	}
790
791	if (bsdar->s_cnt * sizeof(uint32_t) >= bsdar->s_so_cap) {
792		bsdar->s_so_cap *= 2;
793		bsdar->s_so = realloc(bsdar->s_so, bsdar->s_so_cap);
794		if (bsdar->s_so == NULL)
795			bsdar_errc(bsdar, EX_SOFTWARE, errno, "realloc failed");
796	}
797	bsdar->s_so[bsdar->s_cnt] = bsdar->rela_off;
798	bsdar->s_cnt++;
799
800	/*
801	 * The space required for holding one symbol name in sn table includes:
802	 * strlen(name) + (1 for '\n') + (possibly 1 for padding).
803	 */
804	while (bsdar->s_sn_sz + strlen(name) + 2 > bsdar->s_sn_cap) {
805		bsdar->s_sn_cap *= 2;
806		bsdar->s_sn = realloc(bsdar->s_sn, bsdar->s_sn_cap);
807		if (bsdar->s_sn == NULL)
808			bsdar_errc(bsdar, EX_SOFTWARE, errno, "realloc failed");
809	}
810	strncpy(&bsdar->s_sn[bsdar->s_sn_sz], name, strlen(name));
811	bsdar->s_sn_sz += strlen(name);
812	bsdar->s_sn[bsdar->s_sn_sz++] = '\0';
813}
814