C语言实现读取elf文件某section
生活随笔
收集整理的這篇文章主要介紹了
C语言实现读取elf文件某section
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
C語言實現(xiàn)讀取elf文件某section
這方面資料很少,所有結(jié)合相關(guān)信息寫出代碼
代碼
#include <stdio.h> #include <memory.h> #include <stddef.h> #include <stdlib.h> #include <memory.h> #include <string.h> #include <elf.h>int main(int argc, char* argv[]) {// 參數(shù)錯誤if (argc < 2){printf("invalid arguments\n");exit(0);}// 打開文件FILE *fp;fp = fopen(argv[1], "r");if (NULL == fp){printf("fail to open the file");exit(0);}// 解析headElf64_Ehdr elf_head;int shnum, a;// 讀取 head 到elf_heada = fread(&elf_head, sizeof(Elf64_Ehdr), 1, fp); //fread參數(shù)1:讀取內(nèi)容存儲地址,參數(shù)2:讀取內(nèi)容大小,參數(shù)3:讀取次數(shù),參數(shù)4:文件讀取引擎if (0 == a){printf("fail to read head\n");exit(0);}// 判斷elf文件類型if (elf_head.e_ident[0] != 0x7F ||elf_head.e_ident[1] != 'E' ||elf_head.e_ident[2] != 'L' ||elf_head.e_ident[3] != 'F'){printf("Not a ELF file\n");exit(0);}// 解析section 分配內(nèi)存 section * 數(shù)量Elf64_Shdr *shdr = (Elf64_Shdr*)malloc(sizeof(Elf64_Shdr) * elf_head.e_shnum);if (NULL == shdr){printf("shdr malloc failed\n");exit(0);}// 設(shè)置fp偏移量 offset,e_shoff含義a = fseek(fp, elf_head.e_shoff, SEEK_SET); //fseek調(diào)整指針的位置,采用參考位置+偏移量if (0 != a){printf("\nfaile to fseek\n");exit(0);}// 讀取section 到 shdr, 大小為shdr * 數(shù)量a = fread(shdr, sizeof(Elf64_Shdr) * elf_head.e_shnum, 1, fp);if (0 == a){printf("\nfail to read section\n");exit(0);}// 重置指針位置到文件流開頭rewind(fp);// 將fp指針移到 字符串表偏移位置處fseek(fp, shdr[elf_head.e_shstrndx].sh_offset, SEEK_SET);// 第e_shstrndx項是字符串表 定義 字節(jié) 長度 char類型 數(shù)組char shstrtab[shdr[elf_head.e_shstrndx].sh_size];char *temp = shstrtab;// 讀取內(nèi)容a = fread(shstrtab, shdr[elf_head.e_shstrndx].sh_size, 1, fp);if (0 == a){printf("\nfaile to read\n");}// 遍歷for (int i = 0; i < elf_head.e_shnum; i++){temp = shstrtab;temp = temp + shdr[i].sh_name;if (strcmp(temp, ".dynsym") != 0) continue;//該section名稱printf("節(jié)的名稱: %s\n", temp);printf("節(jié)首的偏移: %x\n", shdr[i].sh_offset);printf("節(jié)的大小: %x\n", shdr[i].sh_size);uint8_t *sign_data=(uint8_t*)malloc(sizeof(uint8_t)*shdr[i].sh_size);// 依據(jù)此段在文件中的偏移讀取出fseek(fp, shdr[i].sh_offset, SEEK_SET);fread(sign_data, sizeof(uint8_t)*shdr[i].sh_size, 1, fp);// 顯示讀取的內(nèi)容uint8_t *p = sign_data;int j = 0;for (j=0; j<shdr[i].sh_size; j++){printf("%x", *p);p++;}}return 0; }linux中演示
查看hello文件中section
readelf --wide --header hello讀取section中".dynsym"信息
讀取hello.c生成的hello文件
//hello.c #include<stdio.h> int main(){printf("hello"); } gcc hello.c -o hello讀取hello中section的 “ .dynsym”
gcc read_section.c -o read_section ./read_section hello總結(jié)
以上是生活随笔為你收集整理的C语言实现读取elf文件某section的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux:I/O多路转接之select
- 下一篇: Linux: 系统配置 crond 和