检查打开的文件是不是ELF格式的文件,如果是就输出节头字符串表的地址,并依次输出各节的名称,字符串

来源:互联网 发布:布丁软件官网 编辑:程序博客网 时间:2024/05/20 13:17
#include "elf.h"
#include <stdio.h>
int main(int argc, char  *argv[])
{
    FILE  *fp;
    int i = 0;
    int fd = 0;
    Elf64_Ehdr  ehdr;
    
    if ((fp=fopen(argv[1],"r"))==NULL)
    {
        perror("open");
        return -1;    
    }
    else
    {
        printf("%s\n",argv[1] );
        fd=fread(&ehdr,1,sizeof(Elf64_Ehdr),fp);
        if (fd==sizeof(Elf64_Ehdr))
        {
                     if (ehdr.e_ident[EI_MAG0] != ELFMAG0 ||
               ehdr.e_ident[EI_MAG1] != ELFMAG1 ||
                        ehdr.e_ident[EI_MAG2] != ELFMAG2 ||
                  ehdr.e_ident[EI_MAG3] != ELFMAG3) {
            perror("the file is not a valid ELF file");
            return -1;
        }
        else{
        printf("section header table中表项的数目%ld\n",(long int)ehdr.e_shnum);//节表头数量
    
        }
        
        Elf64_Shdr shdr[ehdr.e_shnum];
        fseek(fp,ehdr.e_shoff,0);
        for(i=0;i<ehdr.e_shnum;i++)
        {
            fread(&shdr[i],ehdr.e_shentsize,1,fp);
        }
        printf("节头字符串表的地址:\n");
        
        fseek(fp,ehdr.e_shoff,0);
        fread(shdr,sizeof(Elf64_Shdr),ehdr.e_shnum,fp);//指向节头表
        
        long shstraddr = shdr[ehdr.e_shstrndx].sh_offset;
        printf("%p\n",shdr[ehdr.e_shstrndx].sh_offset);//节头字符串表的地址

        
        fseek(fp,shstraddr,0);
        char buf[1024] = {0};
        fread(buf,1,sizeof(buf),fp);//指向节头字符串表
        
        printf("各节名称字符串:\n");
        for(i=0;i<ehdr.e_shnum;i++)
                printf("%s\n",&buf[shdr[i].sh_name]);
        }
        fclose(fp);

               
    }
        return 0;

}
0 0
原创粉丝点击