生成尽可能小的ELF文件的代码有什么问题?它运行,但产生一个segfault,因为这是程序启动-我似乎不能调试它。
程序代码应该执行与exit syscall等效的操作,这是我从this excellent blog post中抄来的
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <elf.h>
const char* programCode =
"\xb8\x01\x00\x00\x00" // mov eax, 0x1
"\xbb\x2a\x00\x00\x00" // mov ebx, 0x2a
"\xcd\x80"; // int 0x80
int main() {
// ELF header
Elf64_Ehdr elfHeader = {
.e_ident = {
ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3,
ELFCLASS64, ELFDATA2LSB, EV_CURRENT,
ELFOSABI_NONE, 0, 0, 0, 0, 0, 0, 0
},
.e_type = ET_EXEC,
.e_machine = EM_X86_64,
.e_version = EV_CURRENT,
.e_entry = 0x401000,
.e_phoff = sizeof(Elf64_Ehdr),
.e_shoff = 0,
.e_flags = 0,
.e_ehsize = sizeof(Elf64_Ehdr),
.e_phentsize = sizeof(Elf64_Phdr),
.e_phnum = 1,
.e_shentsize = 0,
.e_shnum = 0,
.e_shstrndx = 0
};
// Program header
Elf64_Phdr programHeader = {
.p_type = PT_LOAD,
.p_flags = PF_R | PF_X,
.p_offset = sizeof(Elf64_Ehdr) + sizeof(Elf64_Phdr),
.p_vaddr = 0x401000,
.p_paddr = 0,
.p_filesz = sizeof(programCode),
.p_memsz = sizeof(programCode),
.p_align = 0x1000
};
// Create and write the ELF file
int fd = open("minimal.elf", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR);
if (fd == -1) {
perror("open");
return 1;
}
ssize_t written = write(fd, &elfHeader, sizeof(Elf64_Ehdr));
if (written == -1) {
perror("write");
close(fd);
return 1;
}
written = write(fd, &programHeader, sizeof(Elf64_Phdr));
if (written == -1) {
perror("write");
close(fd);
return 1;
}
written = write(fd, programCode, sizeof(programCode));
if (written == -1) {
perror("write");
close(fd);
return 1;
}
close(fd);
return 0;
}
1条答案
按热度按时间mccptt671#
下面是工作C代码:
我已经在上面评论了它,以帮助解释我是如何得到我的理由的。您也可以在my repository中找到代码