如何通过nasm将源代码嵌入elf头文件中?错误:执行格式错误

问题描述 投票:1回答:1

根据本教程:http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html,我可以将这段代码嵌入elf头文件结构中。在之前的一步(我的代码和elf标头分开)(也在本教程中)的情况下,它可以工作。但是之后,就没有了。

有名称来源:

BITS 32
    org 0x08048000
ehdr:
    db 0x7F, "ELF"
    db 1,1,1,0 ;e_indent = magic numbers, 32objects, 2compl, arch
    ;times 8 db 0 ; to the end of e_indent buffer (e_indent[16])
    ;PROGRAM EMBEDDED IN ELF HEADER
_start:
    mov bl, 42
    xor eax, eax
    inc eax
    int 0x80
    dw 2; e_type (2 == executable type)
    dw 3; e_machine (3 == intel_80386)
    dd 1; e_version (1 == current_version)
    dd _start; e_entry
    dd phdr - $$; e_phoff (size between this struct and struct phdr)
    dd 0; e_shoff -----> why is offset 0? == org ?
    dd 0; e_flags (should some processor specific flags, do not know value 0)
    dw ehdr_size; e_ehsize
    dw phdr_size; e_phentsize
    dw 1; e_phnum (real number of program headers, do not know what it means)
    dw 0; e_shentsize (because e_shoff == 0)
    dw 0; e_shnum
    dw 0; e_shstrndx

ehdr_size equ $ - ehdr

phdr:
    dd 1; p_type (1 == loadable program segment)
    dd 0; p_offset (segment file offset, but why 0, beginning?)
    dd $$; p_vaddr (segment virtual address, $$ == org)
    dd $$; p_paddr (segment physical address, $$ == org)
    dd file_size; p_filesz (segment size in file)
    dd file_size; p_memsz (segment size in memory)
    dd 5; p_flags (((1<<0) | (1<<2))) == segment is readable and executable)
    dd 0x1000; p_align (segment alignment - 4096 page alignment)

phdr_size equ $ - phdr
file_size equ $ - $$

[查看elf.h文件中该结构的成员的含义后,只有我的评论。

编译为:

nasm -fbin -o a.out a.s
chmod +x a.out
./a.out
bash: ./a.out: cannot execute binary file: Exec format error

正如我之前所说,它是分开的,但是可以工作。在“合并”之后,它将停止工作。一些想法为什么?

x86 nasm binaryfiles elf
1个回答
1
投票

您没有嵌入源代码(ASCII文本),而是试图将机器代码指令嵌入到ELF标头中。

您汇编为83字节,但本文的版本为84字节。与文章的版本相比,您似乎更改了一些内容,将其破坏。比较二进制文件或源代码,找出导致ELF标头无效的破坏原因。

 (after assembling both your source and the working source from the article)
$ file tiny-84
tiny-84: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, no section header
$ file tiny-bad
tiny-bad: ELF 32-bit LSB *unknown arch 0x100* (SYSV)
$ cmp tiny-84 tiny-bad
tiny-84 tiny-bad differ: byte 9, line 1

结果是区别在ehdr的第二条数据线上:

both versions        db      0x7F, "ELF"                     ;   e_ident
-theirs              db      1, 1, 1, 0, 0
+yours               db      1, 1, 1, 0    ;e_indent = magic numbers, 32objects, 2compl, arch

(已调整差异格式的手以使其对齐)

因此,您遗漏了一个字节,将所有后续字节相对于ELF标头中的预期位置未对齐。显然,这会破坏它,但是幸运的是,有一个很好的二进制比较示例,很容易找到问题。

© www.soinside.com 2019 - 2024. All rights reserved.