Last active
December 24, 2022 09:01
-
-
Save izfsk-ium/8ba2f579897bcf5e806712206a585633 to your computer and use it in GitHub Desktop.
读取 ELF 文件的段表字符串表
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <elf.h> | |
#include <string.h> | |
#include <stdlib.h> | |
int main(int argc, char **argv) | |
{ | |
FILE *fp = fopen("test", "rb"); | |
if (fp == NULL) | |
{ | |
perror("Error:"); | |
exit(1); | |
} | |
Elf64_Shdr *str_section_table = (Elf64_Shdr *)malloc(sizeof(Elf64_Shdr)); | |
// ELF Header | |
Elf64_Ehdr *header = (Elf64_Ehdr *)malloc(sizeof(Elf64_Ehdr)); | |
// Read ELF header | |
fread(header, sizeof(Elf64_Ehdr), 1, fp); | |
// Print ELF Magic to verify | |
printf("ELF Header:"); | |
for (int i = 0; i < EI_NIDENT; i++) | |
{ | |
unsigned char byte = header->e_ident[i]; | |
printf("%c", byte == '\0' ? '.' : byte); | |
} | |
printf("\n"); | |
// Get section header table | |
printf("Section Table starts at : %d(%x)\n", header->e_shoff, header->e_shoff); | |
// Get section number | |
printf("There are %d sections.\n", header->e_shnum); | |
// get and print each section info. | |
fseek(fp, header->e_shoff, 0); | |
Elf64_Shdr *section = (Elf64_Shdr *)malloc(sizeof(Elf64_Shdr)); | |
for (int i = 0; i < header->e_shnum; i++) | |
{ | |
memset(section, '\0', sizeof(Elf64_Shdr)); | |
fread(section, header->e_shentsize, 1, fp); | |
printf("Section [%d] : starts at %d(%x) size %d.\n", | |
i, section->sh_offset, | |
section->sh_offset, | |
section->sh_size); | |
if (i == header->e_shstrndx) | |
{ | |
printf("This section No.%d is .shstrtab!\n", i); | |
// Now copy .shstrtab | |
memset(str_section_table, '\0', sizeof(Elf64_Shdr)); | |
memcpy(str_section_table, section, sizeof(Elf64_Shdr)); | |
} | |
} | |
free(section); | |
// Now process string section table | |
printf(".shstrtab starts at %d(%x), size %d.\n ", | |
str_section_table->sh_offset, | |
str_section_table->sh_offset, | |
str_section_table->sh_size); | |
// read this section | |
unsigned char *shstrtab_buff = (unsigned char *)malloc(str_section_table->sh_size); | |
fseek(fp, str_section_table->sh_offset, 0); | |
fread(shstrtab_buff, str_section_table->sh_size, 1, fp); | |
printf("Table content:\n"); | |
for (int i = 0; i != str_section_table->sh_size; i++) | |
{ | |
unsigned char byte = shstrtab_buff[i]; | |
printf("%c", byte == '\0' | |
? '\n' | |
: byte); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment