在C中读取elf文件的正确方法

时间:2016-03-27 11:03:14

标签: c linux elf

我正在尝试遵循本指南:http://wiki.osdev.org/ELF_Tutorial来处理elf files

然而,函数bool elf_check_fil指出,给定文件不是正确的精灵(尽管readelf显示它是)

代码:

bool elf_check_file(Elf32_Ehdr *hdr) {
    if(!hdr) return false;
    if(hdr->e_ident[EI_MAG0] != ELFMAG0) {
        ERROR("ELF Header EI_MAG0 incorrect.\n");
        return false;
    }
    if(hdr->e_ident[EI_MAG1] != ELFMAG1) {
        ERROR("ELF Header EI_MAG1 incorrect.\n");
        return false;
    }
    if(hdr->e_ident[EI_MAG2] != ELFMAG2) {
        ERROR("ELF Header EI_MAG2 incorrect.\n");
        return false;
    }
    if(hdr->e_ident[EI_MAG3] != ELFMAG3) {
        ERROR("ELF Header EI_MAG3 incorrect.\n");
        return false;
    }
    return true;
}

加载文件:

FILE* elf = fopen(argv[1], "r");
Elf32_Ehdr *hdr = (Elf32_Ehdr *) elf;
elf_check_file(hdr);

使用gdb我检查了hdr->e_ident[EI_MAG0] ... hdr->e_ident[EI_MAG3]实际上不包含正确的幻数。为什么呢?

1 个答案:

答案 0 :(得分:1)

如多条评论所述,您未正确使用elf_check_file

正确的方式应该是这样的:

FILE *fp = fopen(argv[1], "rb");
if (fp == NULL) {
  fprintf(stderr, "Unable to open '%s': %s\n", argv[1], strerror(errno));
  return;
}

Elf32_Ehdr ehdr;
if (fread(&ehdr, sizeof(ehdr), 1, fp) != 1) {
  fprintf(stderr, "fread: %s\n", strerror(errno));
  fclose(fp);
  return;
}

if (!elf_check_file(&ehdr)) {
  fprintf(stderr, "'%s' is not an ELF file\n", argv[1]);
  fclose(fp);
  return;
}
/* Parse the rest of the ELF file here. */

/* Don't forget to close the file. */
fclose(fp);
return;
相关问题