How can I get the symbol name in struct “Elf64_Rela”

北城以北 提交于 2019-12-13 12:34:11

问题


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <errno.h>
#include <fcntl.h>
#include <elf.h>


Elf64_Rela *retab;
Elf64_Rela *retab_end;
Elf64_Ehdr *ehdr;
Elf64_Shdr *shdr;
char *strtab;

void elf_open(char *filename)
{

    int fd = open(filename, O_RDONLY);
    struct stat sbuf;
    fstat(fd, &sbuf);
    void *maddr = mmap(NULL, sbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
    close(fd);


    ehdr = maddr;
    shdr = (Elf64_Shdr *)(maddr + ehdr->e_shoff);
    for (int i = 0; i < ehdr->e_shnum; i++) 
    {
        if (shdr[i].sh_type == SHT_RELA) 
        {   
            retab = (Elf64_Rela *)(maddr + shdr[i].sh_offset);
            retab_end = (Elf64_Rela *)((char *)retab + shdr[i].sh_size);
            strtab = (char *)(maddr + shdr[shdr[i].sh_link].sh_offset);
            break;
        }
    }
}

int main()
{
    elf_open("lib1.so");
    Elf64_Rela *p = retab;

    while(p<retab_end)  
    {
        printf("%x %d\n",p->r_offset,p->r_info);

        p++;
    }
}

This is my code to get .rela.dyn section . But I don't know hot to get the symbol's name. I know that Elf64_Rela structure doesn't have a name field. In the 'SYMTAB' section, I can get the symbol name using &strtab[p->st_name]. How can I do?

typedef struct {
    Elf64_Addr r_offset;
    Elf64_Xword r_info;
    Elf64_Sxword r_addend;
} Elf64_Rela;

回答1:


Not all relocations refer to symbols, so you need to check ELF64_R_TYPE (p->r_info) first. The set of relocations which have symbols are architecture-specific.

For those relocations which have symbols, ELF64_R_SYM (p->r_info) should be the index of the associated symbol in the .dynsym section.



来源:https://stackoverflow.com/questions/45319775/how-can-i-get-the-symbol-name-in-struct-elf64-rela

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!