如何打印整个 ELF 文件头及其所有信息?

问题描述

我必须打印 ELF 文件头。它包含的所有数据,就像运行 readelf -h hello.bin 一样。该程序是用 C 语言编写的。这就是我迄今为止所拥有的:

  typedef struct elf64_hdr {
  unsigned char e_ident[EI_NIDENT]; /* ELF "magic number" */
  Elf64_Half e_type;
  Elf64_Half e_machine;
  Elf64_Word e_version;
  Elf64_Addr e_entry;       /* Entry point virtual address */
  Elf64_Off e_phoff;        /* Program header table file offset */
  Elf64_Off e_shoff;        /* Section header table file offset */
  Elf64_Word e_flags;
  Elf64_Half e_ehsize;
  Elf64_Half e_phentsize;
  Elf64_Half e_phnum;
  Elf64_Half e_shentsize;
  Elf64_Half e_shnum;
  Elf64_Half e_shstrndx;
} Elf64_Ehdr;

typedef struct elf64_shdr {
  Elf64_Word sh_name;       /* Section name,index in string tbl */
  Elf64_Word sh_type;       /* Type of section */
  Elf64_Xword sh_flags;     /* Miscellaneous section attributes */
  Elf64_Addr sh_addr;       /* Section virtual addr at execution */
  Elf64_Off sh_offset;      /* Section file offset */
  Elf64_Xword sh_size;      /* Size of section in bytes */
  Elf64_Word sh_link;       /* Index of another section */
  Elf64_Word sh_info;       /* Additional section information */
  Elf64_Xword sh_addralign; /* Section alignment */
  Elf64_Xword sh_entsize;   /* Entry size if section holds table */
} Elf64_Shdr;

这些是结构。 下面是 main 中声明的变量:

  FILE* ElfFile = NULL;
  char* SectNames = NULL;
  Elf64_Ehdr elfHdr;
  Elf64_Shdr sectHdr;
  uint32_t idx;

这是打印代码的相关部分,需要您的帮助:

// read ELF header,first thing in the file
  fread(&elfHdr,1,sizeof(Elf64_Ehdr),ElfFile); 
  SectNames = malloc(sectHdr.sh_size); //variable for section names (like "Magic","Data" etc.)
  fseek(ElfFile,sectHdr.sh_offset,SEEK_SET); //going to the offset of the section
  fread(SectNames,sectHdr.sh_size,ElfFile); //reading the size of section
  for(int i=0; i<sectHdr.sh_size; i++)
  {
    char *name1 = "";
    fseek(ElfFile,elfHdr.e_shoff + i*sizeof(sectHdr),SEEK_SET);
    fread(&sectHdr,sizeof(sectHdr),ElfFile);
    name1 = SectNames + sectHdr.sh_name;
    printf("%s \n",name1);
  }

代码编译但不打印任何内容。我希望打印“Magic”、“Data”、“Class”等字符串......

解决方法

您不能使用 + 运算符在 C 中添加字符串。

这一行:

char *name1 = "";

表示 name1 指向一个空的常量字符串。
它不会为某些可以添加字符串的字符串对象分配内存。

所以这段代码:

name1 = SectNames + sectHdr.sh_name;

只需在 name1 中放入一个垃圾值(某个数字),这将导致未定义的行为(您的程序可能会崩溃、不打印任何内容或打印随机字符)。

要打印部分名称,您需要这样的代码:

printf("Section name: %u\n",sectHdr.sh_name);

这会将 sectHdr.sh_name 中的值格式化为文本并将其输出到屏幕上。

您将不得不对所有其他字段做类似的事情,一一,但您必须注意字段类型并使用正确的格式说明符。

%u 表示“无符号整数”,它是 Elf64_Word 所拥有的最接近 printf 的东西。
仔细检查其他类型和suitable specifiers