我手工制作的ELF文件'mov eax,1''ret'出现了分段错误的错误

时间:2016-09-18 01:38:15

标签: linux assembly elf

我受到link的启发。我想逐步实现一个C编译器。这是我在C中实现主函数的第一步。 这是我的代码。我使用函数'elf_write'手工编写elf文件,但是当我运行生成的ELF文件时,出现了分段错误的错误(我的计算机的Linux版本是Ubuntu 12.04.5 LTS( GUN / Linux 3.2.0-80-generic x86_64)):

    void elf_write(FILE *elf)
    {
        unsigned char code[] = {
            //0x55,//push ebp
            0xb8,0x01,0x00,0x00,0x00,//mov eax,1
            //0x89,0xe5,//mov ebp,esp
            //0x5d,//pop ebp
            0xc3//ret
        };

        uint64_t entry = 0x400000;
        Elf64_Ehdr ehdr = {
            .e_ident = {
                ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3,
                ELFCLASS64,
                ELFDATA2LSB,
                EV_CURRENT,
                ELFOSABI_SYSV,
            },
            .e_type = ET_EXEC,
            .e_machine = EM_X86_64,
            .e_version = EV_CURRENT,
            .e_entry = entry + sizeof(Elf64_Ehdr) + sizeof(Elf64_Phdr),
            .e_phoff = sizeof(Elf64_Ehdr),
            .e_ehsize = sizeof(Elf64_Ehdr),
            .e_phentsize = sizeof(Elf64_Phdr),
            .e_phnum = 1
        };
        Elf64_Phdr phdr_text = {
            .p_type = PT_LOAD,
            //.p_offset = sizeof(Elf64_Ehdr) + 2*sizeof(Elf64_Phdr),
            .p_flags = PF_X | PF_R,
            .p_vaddr = entry,
            .p_filesz = sizeof(code),
            .p_memsz = sizeof(code),
            .p_align = 0x200000
        };
        fwrite(&ehdr, sizeof(ehdr), 1, elf);
        fwrite(&phdr_text, sizeof(phdr_text), 1, elf);
        fwrite(code, sizeof(code), 1, elf);
    }

当我将代码更改为此代码时,它完美执行并在终端中打印“ABCDE”。

    unsigned char code[] = {
        0xb8,0x01,0x00,0x00,0x00,//mov rax,1
        0xba,0x06,0x00,0x00,0x00,//mov rdx,12
        0xbe,0x9a,0x00,0x40,0x00,//mov rsi,0x4000b0
        0xbf,0x01,0x00,0x00,0x00,//mov rdi ,1
        0x0f,0x05,               //syscall
        0xb8,0x3c,0x00,0x00,0x00,//mov rax,60
        0xbf,0x00,0x00,0x00,0x00,//mov rdi ,0
        0x0f,0x05,               //syscall
        0x41,0x42,0x43,0x44,0x45,0x0A//ABCDE
    };

0 个答案:

没有答案