如何合并两个二进制可执行文件?

Mik*_*wan 8 c linux linker elf bfd

这个问题是我之前提出的另一个问题.简而言之,这是我尝试将两个完全链接的可执行文件合并为一个完全链接的可执行文件的尝试之一.区别在于前一个问题涉及将目标文件合并到一个完整的链接可执行文件,这更难,因为这意味着我需要手动处理重定位.

我所拥有的是以下文件:

example-target.c:

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
    puts("1234");
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

example-embed.c:

#include <stdlib.h>
#include <stdio.h>

/*
 * Fake main. Never used, just there so we can perform a full link.
 */
int main(void)
{
    return EXIT_SUCCESS;
}

void func1(void)
{
    puts("asdf");
}
Run Code Online (Sandbox Code Playgroud)

我的目标是合并这两个可执行文件以生成一个最终的可执行文件,它与之相同example-target,但另外还有另一个mainfunc1.

从BFD库的角度来看,每个二进制文件由一组部分组成(以及其他内容).我遇到的第一个问题之一是这些部分具有冲突的加载地址(这样,如果我要合并它们,这些部分将重叠).

我解决这个问题的方法是以example-target编程方式分析,以获取每个部分的加载地址和大小的列表.然后,我做了同样的事情,example-embed并使用此信息动态生成链接器命令,example-embed.c以确保其所有部分链接在不与任何部分重叠的地址example-target.因此example-embed,在这个过程中实际上完全链接了两次:一次确定它们有多少部分和大小,并再次与保证没有部分冲突相关联example-target.

在我的系统上,生成的链接器命令是:

-Wl,--section-start=.new.interp=0x1004238,--section-start=.new.note.ABI-tag=0x1004254,
--section-start=.new.note.gnu.build-id=0x1004274,--section-start=.new.gnu.hash=0x1004298,
--section-start=.new.dynsym=0x10042B8,--section-start=.new.dynstr=0x1004318,
--section-start=.new.gnu.version=0x1004356,--section-start=.new.gnu.version_r=0x1004360,
--section-start=.new.rela.dyn=0x1004380,--section-start=.new.rela.plt=0x1004398,
--section-start=.new.init=0x10043C8,--section-start=.new.plt=0x10043E0,
--section-start=.new.text=0x1004410,--section-start=.new.fini=0x10045E8,
--section-start=.new.rodata=0x10045F8,--section-start=.new.eh_frame_hdr=0x1004604,
--section-start=.new.eh_frame=0x1004638,--section-start=.new.ctors=0x1204E28,
--section-start=.new.dtors=0x1204E38,--section-start=.new.jcr=0x1204E48,
--section-start=.new.dynamic=0x1204E50,--section-start=.new.got=0x1204FE0,
--section-start=.new.got.plt=0x1204FE8,--section-start=.new.data=0x1205010,
--section-start=.new.bss=0x1205020,--section-start=.new.comment=0xC04000
Run Code Online (Sandbox Code Playgroud)

(请注意,我.new使用objcopy --prefix-sections=.new example-embedobj了部分名称作为前缀,以避免部分名称冲突.)

然后我写了一些代码来生成一个新的可执行文件(借用了一些代码objcopySecurity Warrior预订).新的可执行文件应该具有:

  • 所有部分example-target和所有部分example-embed
  • 符号表,包含来自的example-target所有符号和所有符号example-embed

我写的代码是:

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <bfd.h>
#include <libiberty.h>

struct COPYSECTION_DATA {
    bfd *      obfd;
    asymbol ** syms;
    int        symsize;
    int        symcount;
};

void copy_section(bfd * ibfd, asection * section, PTR data)
{
    struct COPYSECTION_DATA * csd  = data;
    bfd *             obfd = csd->obfd;
    asection *        s;
    long              size, count, sz_reloc;

    if((bfd_get_section_flags(ibfd, section) & SEC_GROUP) != 0) {
        return;
    }

    /* get output section from input section struct */
    s        = section->output_section;
    /* get sizes for copy */
    size     = bfd_get_section_size(section);
    sz_reloc = bfd_get_reloc_upper_bound(ibfd, section);

    if(!sz_reloc) {
        /* no relocations */
        bfd_set_reloc(obfd, s, NULL, 0);
    } else if(sz_reloc > 0) {
        arelent ** buf;

        /* build relocations */
        buf   = xmalloc(sz_reloc);
        count = bfd_canonicalize_reloc(ibfd, section, buf, csd->syms);
        /* set relocations for the output section */
        bfd_set_reloc(obfd, s, count ? buf : NULL, count);
        free(buf);
    }

    /* get input section contents, set output section contents */
    if(section->flags & SEC_HAS_CONTENTS) {
        bfd_byte * memhunk = NULL;
        bfd_get_full_section_contents(ibfd, section, &memhunk);
        bfd_set_section_contents(obfd, s, memhunk, 0, size);
        free(memhunk);
    }
}

void define_section(bfd * ibfd, asection * section, PTR data)
{
    bfd *      obfd = data;
    asection * s    = bfd_make_section_anyway_with_flags(obfd,
            section->name, bfd_get_section_flags(ibfd, section));
    /* set size to same as ibfd section */
    bfd_set_section_size(obfd, s, bfd_section_size(ibfd, section));

    /* set vma */
    bfd_set_section_vma(obfd, s, bfd_section_vma(ibfd, section));
    /* set load address */
    s->lma = section->lma;
    /* set alignment -- the power 2 will be raised to */
    bfd_set_section_alignment(obfd, s,
            bfd_section_alignment(ibfd, section));
    s->alignment_power = section->alignment_power;
    /* link the output section to the input section */
    section->output_section = s;
    section->output_offset  = 0;

    /* copy merge entity size */
    s->entsize = section->entsize;

    /* copy private BFD data from ibfd section to obfd section */
    bfd_copy_private_section_data(ibfd, section, obfd, s);
}

void merge_symtable(bfd * ibfd, bfd * embedbfd, bfd * obfd,
        struct COPYSECTION_DATA * csd)
{
    /* set obfd */
    csd->obfd     = obfd;

    /* get required size for both symbol tables and allocate memory */
    csd->symsize  = bfd_get_symtab_upper_bound(ibfd) /********+
            bfd_get_symtab_upper_bound(embedbfd) */;
    csd->syms     = xmalloc(csd->symsize);

    csd->symcount =  bfd_canonicalize_symtab (ibfd, csd->syms);
    /******** csd->symcount += bfd_canonicalize_symtab (embedbfd,
            csd->syms + csd->symcount); */

    /* copy merged symbol table to obfd */
    bfd_set_symtab(obfd, csd->syms, csd->symcount);
}

bool merge_object(bfd * ibfd, bfd * embedbfd, bfd * obfd)
{
    struct COPYSECTION_DATA csd = {0};

    if(!ibfd || !embedbfd || !obfd) {
        return FALSE;
    }

    /* set output parameters to ibfd settings */
    bfd_set_format(obfd, bfd_get_format(ibfd));
    bfd_set_arch_mach(obfd, bfd_get_arch(ibfd), bfd_get_mach(ibfd));
    bfd_set_file_flags(obfd, bfd_get_file_flags(ibfd) &
            bfd_applicable_file_flags(obfd));

    /* set the entry point of obfd */
    bfd_set_start_address(obfd, bfd_get_start_address(ibfd));

    /* define sections for output file */
    bfd_map_over_sections(ibfd, define_section, obfd);
    /******** bfd_map_over_sections(embedbfd, define_section, obfd); */

    /* merge private data into obfd */
    bfd_merge_private_bfd_data(ibfd, obfd);
    /******** bfd_merge_private_bfd_data(embedbfd, obfd); */

    merge_symtable(ibfd, embedbfd, obfd, &csd);

    bfd_map_over_sections(ibfd, copy_section, &csd);
    /******** bfd_map_over_sections(embedbfd, copy_section, &csd); */

    free(csd.syms);
    return TRUE;
}

int main(int argc, char **argv)
{
    bfd * ibfd;
    bfd * embedbfd;
    bfd * obfd;

    if(argc != 4) {
        perror("Usage: infile embedfile outfile\n");
        xexit(-1);
    }

    bfd_init();
    ibfd     = bfd_openr(argv[1], NULL);
    embedbfd = bfd_openr(argv[2], NULL);

    if(ibfd == NULL || embedbfd == NULL) {
        perror("asdfasdf");
        xexit(-1);
    }

    if(!bfd_check_format(ibfd, bfd_object) ||
            !bfd_check_format(embedbfd, bfd_object)) {
        perror("File format error");
        xexit(-1);
    }

    obfd = bfd_openw(argv[3], NULL);
    bfd_set_format(obfd, bfd_object);

    if(!(merge_object(ibfd, embedbfd, obfd))) {
        perror("Error merging input/obj");
        xexit(-1);
    }

    bfd_close(ibfd);
    bfd_close(embedbfd);
    bfd_close(obfd);
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

总结一下这段代码的作用,需要2个输入文件(ibfdembedbfd)来生成输出文件(obfd).

  • 副本格式/弓/马赫/文件标志,并从起始地址ibfdobfd
  • 定义from ibfdembedbfdto的部分obfd.这些部分的数量是分开发生的,因为BFD要求在任何开始填充之前创建所有部分.
  • 将两个输入BFD的私有数据合并到输出BFD.由于BFD是许多文件格式之上的通用抽象,因此它不一定能够全面地封装底层文件格式所需的所有内容.
  • 创建一个由符号表组成的组合符号表ibfd,embedbfd并将其设置为符号表obfd.此符号表已保存,以便以后可用于构建重定位信息.
  • 将部分复制ibfdobfd.除了复制部分内容外,此步骤还涉及构建和设置重定位表.

在上面的代码中,一些行被注释掉了/******** */.这些线条涉及合并example-embed.如果它们被注释掉了,那么会发生什么,obfd它只是作为副本构建的ibfd.我测试了这个,它工作正常.但是,一旦我在问题开始发生时将这些线条评论回来.

使用完全合并的未注释版本,它仍然会生成输出文件.可以检查此输出文件,objdump并发现它具有两个输入的所有部分,代码和符号表.然而,objdump抱怨:

BFD: BFD (GNU Binutils for Ubuntu) 2.21.53.20110810 assertion fail ../../bfd/elf.c:1708
BFD: BFD (GNU Binutils for Ubuntu) 2.21.53.20110810 assertion fail ../../bfd/elf.c:1708
Run Code Online (Sandbox Code Playgroud)

在我的系统,1708elf.c是:

BFD_ASSERT (elf_dynsymtab (abfd) == 0);
Run Code Online (Sandbox Code Playgroud)

elf_dynsymtab是一个宏elf-bfd.h:

#define elf_dynsymtab(bfd)  (elf_tdata(bfd) -> dynsymtab_section)
Run Code Online (Sandbox Code Playgroud)

我不熟悉ELF层,但我认为这是读取动态符号表(或者说它不存在)的问题.当时,我试图避免必须直接进入ELF层.有人能够在我的代码或概念上告诉我我做错了什么吗?

如果它有用,我还可以发布链接器命令生成的代码或示例二进制文件的编译版本.


我意识到这是一个非常大的问题,因此,我想对能够帮助我的人给予适当的奖励.如果我能够在某人的帮助下解决这个问题,我很乐意奖励500+奖金.

zvr*_*rba 1

为什么所有这些都要手动进行?鉴于您拥有所有符号信息(如果您想以合理的方式编辑二进制文件,则必须这样做),将可执行文件拆分为单独的目标文件(例如,每个函数一个目标文件)不是更容易吗?编辑,然后重新链接?