Path: blob/main/contrib/elftoolchain/elfcopy/archive.c
39563 views
/*-1* Copyright (c) 2007-2009 Kai Wang2* All rights reserved.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7* 1. Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9* 2. Redistributions in binary form must reproduce the above copyright10* notice, this list of conditions and the following disclaimer in the11* documentation and/or other materials provided with the distribution.12*13* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND14* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE15* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE16* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE17* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL18* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS19* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)20* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT21* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY22* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF23* SUCH DAMAGE.24*/2526#include <sys/param.h>27#include <sys/stat.h>28#include <err.h>29#include <stdlib.h>30#include <string.h>31#include <unistd.h>3233#ifndef LIBELF_AR34#include <archive.h>35#include <archive_entry.h>36#endif /* ! LIBELF_AR */3738#include "elfcopy.h"3940ELFTC_VCSID("$Id: archive.c 3490 2016-08-31 00:12:22Z emaste $");4142#define _ARMAG_LEN 8 /* length of ar magic string */43#define _ARHDR_LEN 60 /* length of ar header */44#define _INIT_AS_CAP 128 /* initial archive string table size */45#define _INIT_SYMOFF_CAP (256*(sizeof(uint32_t))) /* initial so table size */46#define _INIT_SYMNAME_CAP 1024 /* initial sn table size */47#define _MAXNAMELEN_SVR4 15 /* max member name length in svr4 variant */4849#ifndef LIBELF_AR50static void ac_read_objs(struct elfcopy *ecp, int ifd);51static void ac_write_cleanup(struct elfcopy *ecp);52static void ac_write_data(struct archive *a, const void *buf, size_t s);53static void ac_write_objs(struct elfcopy *ecp, int ofd);54#endif /* ! LIBELF_AR */55static void add_to_ar_str_table(struct elfcopy *elfcopy, const char *name);56static void add_to_ar_sym_table(struct elfcopy *ecp, const char *name);57static void extract_arsym(struct elfcopy *ecp);58static void process_ar_obj(struct elfcopy *ecp, struct ar_obj *obj);59static void sync_ar(struct elfcopy *ecp);606162static void63process_ar_obj(struct elfcopy *ecp, struct ar_obj *obj)64{65struct stat sb;66char *tempfile;67int fd;6869/* Output to a temporary file. */70create_tempfile(NULL, &tempfile, &fd);71if ((ecp->eout = elf_begin(fd, ELF_C_WRITE, NULL)) == NULL) {72cleanup_tempfile(tempfile);73errx(EXIT_FAILURE, "elf_begin() failed: %s",74elf_errmsg(-1));75}76elf_flagelf(ecp->eout, ELF_C_SET, ELF_F_LAYOUT);77create_elf(ecp);78elf_end(ecp->ein);79elf_end(ecp->eout);80free(obj->buf);81obj->buf = NULL;8283/* Extract archive symbols. */84if (lseek(fd, 0, SEEK_SET) < 0) {85cleanup_tempfile(tempfile);86err(EXIT_FAILURE, "lseek failed for '%s'", tempfile);87}88if ((ecp->eout = elf_begin(fd, ELF_C_READ, NULL)) == NULL) {89cleanup_tempfile(tempfile);90errx(EXIT_FAILURE, "elf_begin() failed: %s",91elf_errmsg(-1));92}93extract_arsym(ecp);94elf_end(ecp->eout);9596if (fstat(fd, &sb) == -1) {97cleanup_tempfile(tempfile);98err(EXIT_FAILURE, "fstat %s failed", tempfile);99}100if (lseek(fd, 0, SEEK_SET) < 0) {101cleanup_tempfile(tempfile);102err(EXIT_FAILURE, "lseek %s failed", tempfile);103}104obj->size = sb.st_size;105if ((obj->maddr = malloc(obj->size)) == NULL) {106cleanup_tempfile(tempfile);107err(EXIT_FAILURE, "memory allocation failed for '%s'",108tempfile);109}110if ((size_t) read(fd, obj->maddr, obj->size) != obj->size) {111cleanup_tempfile(tempfile);112err(EXIT_FAILURE, "read failed for '%s'", tempfile);113}114if (cleanup_tempfile(tempfile) < 0)115err(EXIT_FAILURE, "unlink %s failed", tempfile);116free(tempfile);117tempfile = NULL;118close(fd);119if (strlen(obj->name) > _MAXNAMELEN_SVR4)120add_to_ar_str_table(ecp, obj->name);121ecp->rela_off += _ARHDR_LEN + obj->size + obj->size % 2;122STAILQ_INSERT_TAIL(&ecp->v_arobj, obj, objs);123}124125/*126* Append to the archive string table buffer.127*/128static void129add_to_ar_str_table(struct elfcopy *ecp, const char *name)130{131132if (ecp->as == NULL) {133ecp->as_cap = _INIT_AS_CAP;134ecp->as_sz = 0;135if ((ecp->as = malloc(ecp->as_cap)) == NULL)136err(EXIT_FAILURE, "malloc failed");137}138139/*140* The space required for holding one member name in as table includes:141* strlen(name) + (1 for '/') + (1 for '\n') + (possibly 1 for padding).142*/143while (ecp->as_sz + strlen(name) + 3 > ecp->as_cap) {144ecp->as_cap *= 2;145ecp->as = realloc(ecp->as, ecp->as_cap);146if (ecp->as == NULL)147err(EXIT_FAILURE, "realloc failed");148}149strncpy(&ecp->as[ecp->as_sz], name, strlen(name));150ecp->as_sz += strlen(name);151ecp->as[ecp->as_sz++] = '/';152ecp->as[ecp->as_sz++] = '\n';153}154155/*156* Append to the archive symbol table buffer.157*/158static void159add_to_ar_sym_table(struct elfcopy *ecp, const char *name)160{161162if (ecp->s_so == NULL) {163if ((ecp->s_so = malloc(_INIT_SYMOFF_CAP)) == NULL)164err(EXIT_FAILURE, "malloc failed");165ecp->s_so_cap = _INIT_SYMOFF_CAP;166ecp->s_cnt = 0;167}168169if (ecp->s_sn == NULL) {170if ((ecp->s_sn = malloc(_INIT_SYMNAME_CAP)) == NULL)171err(EXIT_FAILURE, "malloc failed");172ecp->s_sn_cap = _INIT_SYMNAME_CAP;173ecp->s_sn_sz = 0;174}175176if (ecp->s_cnt * sizeof(uint32_t) >= ecp->s_so_cap) {177ecp->s_so_cap *= 2;178ecp->s_so = realloc(ecp->s_so, ecp->s_so_cap);179if (ecp->s_so == NULL)180err(EXIT_FAILURE, "realloc failed");181}182ecp->s_so[ecp->s_cnt] = ecp->rela_off;183ecp->s_cnt++;184185/*186* The space required for holding one symbol name in sn table includes:187* strlen(name) + (1 for '\n') + (possibly 1 for padding).188*/189while (ecp->s_sn_sz + strlen(name) + 2 > ecp->s_sn_cap) {190ecp->s_sn_cap *= 2;191ecp->s_sn = realloc(ecp->s_sn, ecp->s_sn_cap);192if (ecp->s_sn == NULL)193err(EXIT_FAILURE, "realloc failed");194}195strncpy(&ecp->s_sn[ecp->s_sn_sz], name, strlen(name));196ecp->s_sn_sz += strlen(name);197ecp->s_sn[ecp->s_sn_sz++] = '\0';198}199200static void201sync_ar(struct elfcopy *ecp)202{203size_t s_sz; /* size of archive symbol table. */204size_t pm_sz; /* size of pseudo members */205int i;206207/*208* Pad the symbol name string table. It is treated specially because209* symbol name table should be padded by a '\0', not the common '\n'210* for other members. The size of sn table includes the pad bit.211*/212if (ecp->s_cnt != 0 && ecp->s_sn_sz % 2 != 0)213ecp->s_sn[ecp->s_sn_sz++] = '\0';214215/*216* Archive string table is padded by a "\n" as the normal members.217* The difference is that the size of archive string table counts218* in the pad bit, while normal members' size fileds do not.219*/220if (ecp->as != NULL && ecp->as_sz % 2 != 0)221ecp->as[ecp->as_sz++] = '\n';222223/*224* If there is a symbol table, calculate the size of pseudo members,225* convert previously stored relative offsets to absolute ones, and226* then make them Big Endian.227*228* absolute_offset = htobe32(relative_offset + size_of_pseudo_members)229*/230231if (ecp->s_cnt != 0) {232s_sz = (ecp->s_cnt + 1) * sizeof(uint32_t) + ecp->s_sn_sz;233pm_sz = _ARMAG_LEN + (_ARHDR_LEN + s_sz);234if (ecp->as != NULL)235pm_sz += _ARHDR_LEN + ecp->as_sz;236for (i = 0; (size_t)i < ecp->s_cnt; i++)237*(ecp->s_so + i) = htobe32(*(ecp->s_so + i) +238pm_sz);239}240}241242/*243* Extract global symbols from archive members.244*/245static void246extract_arsym(struct elfcopy *ecp)247{248Elf_Scn *scn;249GElf_Shdr shdr;250GElf_Sym sym;251Elf_Data *data;252char *name;253size_t n, shstrndx;254int elferr, tabndx, len, i;255256if (elf_kind(ecp->eout) != ELF_K_ELF) {257warnx("internal: cannot extract symbols from non-elf object");258return;259}260if (elf_getshstrndx(ecp->eout, &shstrndx) == 0) {261warnx("elf_getshstrndx failed: %s", elf_errmsg(-1));262return;263}264265tabndx = -1;266scn = NULL;267while ((scn = elf_nextscn(ecp->eout, scn)) != NULL) {268if (gelf_getshdr(scn, &shdr) != &shdr) {269warnx("elf_getshdr failed: %s", elf_errmsg(-1));270continue;271}272if ((name = elf_strptr(ecp->eout, shstrndx, shdr.sh_name)) ==273NULL) {274warnx("elf_strptr failed: %s", elf_errmsg(-1));275continue;276}277if (strcmp(name, ".strtab") == 0) {278tabndx = elf_ndxscn(scn);279break;280}281}282elferr = elf_errno();283if (elferr != 0)284warnx("elf_nextscn failed: %s", elf_errmsg(elferr));285286/* Ignore members without symbol table. */287if (tabndx == -1)288return;289290scn = NULL;291while ((scn = elf_nextscn(ecp->eout, scn)) != NULL) {292if (gelf_getshdr(scn, &shdr) != &shdr) {293warnx("elf_getshdr failed: %s", elf_errmsg(-1));294continue;295}296if (shdr.sh_type != SHT_SYMTAB)297continue;298299data = NULL;300n = 0;301while (n < shdr.sh_size &&302(data = elf_getdata(scn, data)) != NULL) {303len = data->d_size / shdr.sh_entsize;304for (i = 0; i < len; i++) {305if (gelf_getsym(data, i, &sym) != &sym) {306warnx("gelf_getsym failed: %s",307elf_errmsg(-1));308continue;309}310311/* keep only global or weak symbols */312if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL &&313GELF_ST_BIND(sym.st_info) != STB_WEAK)314continue;315316/* keep only defined symbols */317if (sym.st_shndx == SHN_UNDEF)318continue;319320if ((name = elf_strptr(ecp->eout, tabndx,321sym.st_name)) == NULL) {322warnx("elf_strptr failed: %s",323elf_errmsg(-1));324continue;325}326327add_to_ar_sym_table(ecp, name);328}329}330}331elferr = elf_errno();332if (elferr != 0)333warnx("elf_nextscn failed: %s", elf_errmsg(elferr));334}335336#ifndef LIBELF_AR337338/*339* Convenient wrapper for general libarchive error handling.340*/341#define AC(CALL) do { \342if ((CALL)) \343errx(EXIT_FAILURE, "%s", archive_error_string(a)); \344} while (0)345346/* Earlier versions of libarchive had some functions that returned 'void'. */347#if ARCHIVE_VERSION_NUMBER >= 2000000348#define ACV(CALL) AC(CALL)349#else350#define ACV(CALL) do { \351(CALL); \352} while (0)353#endif354355int356ac_detect_ar(int ifd)357{358struct archive *a;359struct archive_entry *entry;360int r;361362r = -1;363if ((a = archive_read_new()) == NULL)364return (0);365archive_read_support_format_ar(a);366if (archive_read_open_fd(a, ifd, 10240) == ARCHIVE_OK)367r = archive_read_next_header(a, &entry);368archive_read_close(a);369archive_read_free(a);370371return (r == ARCHIVE_OK);372}373374void375ac_create_ar(struct elfcopy *ecp, int ifd, int ofd)376{377378ac_read_objs(ecp, ifd);379sync_ar(ecp);380ac_write_objs(ecp, ofd);381ac_write_cleanup(ecp);382}383384static void385ac_read_objs(struct elfcopy *ecp, int ifd)386{387struct archive *a;388struct archive_entry *entry;389struct ar_obj *obj;390const char *name;391char *buff;392size_t size;393int r;394395ecp->rela_off = 0;396if (lseek(ifd, 0, SEEK_SET) == -1)397err(EXIT_FAILURE, "lseek failed");398if ((a = archive_read_new()) == NULL)399errx(EXIT_FAILURE, "archive_read_new failed");400archive_read_support_format_ar(a);401AC(archive_read_open_fd(a, ifd, 10240));402for(;;) {403r = archive_read_next_header(a, &entry);404if (r == ARCHIVE_FATAL)405errx(EXIT_FAILURE, "%s", archive_error_string(a));406if (r == ARCHIVE_EOF)407break;408if (r == ARCHIVE_WARN || r == ARCHIVE_RETRY)409warnx("%s", archive_error_string(a));410if (r == ARCHIVE_RETRY)411continue;412413name = archive_entry_pathname(entry);414415/* skip pseudo members. */416if (strcmp(name, "/") == 0 || strcmp(name, "//") == 0)417continue;418419size = archive_entry_size(entry);420421if (size > 0) {422if ((buff = malloc(size)) == NULL)423err(EXIT_FAILURE, "malloc failed");424if (archive_read_data(a, buff, size) != (ssize_t)size) {425warnx("%s", archive_error_string(a));426free(buff);427continue;428}429if ((obj = malloc(sizeof(*obj))) == NULL)430err(EXIT_FAILURE, "malloc failed");431if ((obj->name = strdup(name)) == NULL)432err(EXIT_FAILURE, "strdup failed");433obj->buf = buff;434obj->uid = archive_entry_uid(entry);435obj->gid = archive_entry_gid(entry);436obj->md = archive_entry_mode(entry);437obj->mtime = archive_entry_mtime(entry);438if ((ecp->ein = elf_memory(buff, size)) == NULL)439errx(EXIT_FAILURE, "elf_memory() failed: %s",440elf_errmsg(-1));441if (elf_kind(ecp->ein) != ELF_K_ELF)442errx(EXIT_FAILURE,443"file format not recognized");444process_ar_obj(ecp, obj);445}446}447AC(archive_read_close(a));448ACV(archive_read_free(a));449}450451static void452ac_write_objs(struct elfcopy *ecp, int ofd)453{454struct archive *a;455struct archive_entry *entry;456struct ar_obj *obj;457time_t timestamp;458int nr;459460if ((a = archive_write_new()) == NULL)461errx(EXIT_FAILURE, "archive_write_new failed");462archive_write_set_format_ar_svr4(a);463AC(archive_write_open_fd(a, ofd));464465/* Write the archive symbol table, even if it's empty. */466entry = archive_entry_new();467archive_entry_copy_pathname(entry, "/");468if (elftc_timestamp(×tamp) != 0)469err(EXIT_FAILURE, "elftc_timestamp");470archive_entry_set_mtime(entry, timestamp, 0);471archive_entry_set_size(entry, (ecp->s_cnt + 1) * sizeof(uint32_t) +472ecp->s_sn_sz);473AC(archive_write_header(a, entry));474nr = htobe32(ecp->s_cnt);475ac_write_data(a, &nr, sizeof(uint32_t));476ac_write_data(a, ecp->s_so, sizeof(uint32_t) * ecp->s_cnt);477ac_write_data(a, ecp->s_sn, ecp->s_sn_sz);478archive_entry_free(entry);479480/* Write the archive string table, if exist. */481if (ecp->as != NULL) {482entry = archive_entry_new();483archive_entry_copy_pathname(entry, "//");484archive_entry_set_size(entry, ecp->as_sz);485AC(archive_write_header(a, entry));486ac_write_data(a, ecp->as, ecp->as_sz);487archive_entry_free(entry);488}489490/* Write normal members. */491STAILQ_FOREACH(obj, &ecp->v_arobj, objs) {492entry = archive_entry_new();493archive_entry_copy_pathname(entry, obj->name);494archive_entry_set_uid(entry, obj->uid);495archive_entry_set_gid(entry, obj->gid);496archive_entry_set_mode(entry, obj->md);497archive_entry_set_size(entry, obj->size);498archive_entry_set_mtime(entry, obj->mtime, 0);499archive_entry_set_filetype(entry, AE_IFREG);500AC(archive_write_header(a, entry));501ac_write_data(a, obj->maddr, obj->size);502archive_entry_free(entry);503}504505AC(archive_write_close(a));506ACV(archive_write_free(a));507}508509static void510ac_write_cleanup(struct elfcopy *ecp)511{512struct ar_obj *obj, *obj_temp;513514STAILQ_FOREACH_SAFE(obj, &ecp->v_arobj, objs, obj_temp) {515STAILQ_REMOVE(&ecp->v_arobj, obj, ar_obj, objs);516if (obj->maddr != NULL)517free(obj->maddr);518free(obj->name);519free(obj);520}521522free(ecp->as);523free(ecp->s_so);524free(ecp->s_sn);525ecp->as = NULL;526ecp->s_so = NULL;527ecp->s_sn = NULL;528}529530/*531* Wrapper for archive_write_data().532*/533static void534ac_write_data(struct archive *a, const void *buf, size_t s)535{536if (archive_write_data(a, buf, s) != (ssize_t)s)537errx(EXIT_FAILURE, "%s", archive_error_string(a));538}539540#endif /* ! LIBELF_AR */541542543