【问题标题】:Get elf sections offsets获取精灵部分偏移量
【发布时间】:2013-03-12 03:01:00
【问题描述】:

我正在尝试获取 elf 文件的每个部分的偏移量和数据。 我已经有了这段代码的部分名称:

#include <elf.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

int filesize(int fd)
{
  return (lseek(fd, 0, SEEK_END));
}

void    print_section(Elf64_Shdr *shdr, char *strTab, int shNum)
{
  int   i;

  for(i = 0; i < shNum; i++)
     printf("%02d: %s\n", i, &strTab[shdr[i].sh_name]);
}

int main(int ac, char **av)
{
  void  *data;
  Elf64_Ehdr    *elf;
  Elf64_Shdr    *shdr;
  int       fd;
  char      *strtab;

  fd = open(av[1], O_RDONLY);
  data = mmap(NULL, filesize(fd), PROT_READ, MAP_SHARED, fd, 0);
  elf = (Elf64_Ehdr *) data;
  shdr = (Elf64_Shdr *) (data + elf->e_shoff);
  strtab = (char *)(data + shdr[elf->e_shstrndx].sh_offset);
  print_section(shdr, strtab, elf->e_shnum);
  close(fd);
  return 0;
}

但我找不到获取每个部分的数据或其起始偏移量的方法。 感谢您的帮助

【问题讨论】:

    标签: c unix elf


    【解决方案1】:

    我认为你可以使用sh_offsetshdr[i].sh_size

    void    print_section(Elf64_Shdr *shdr, char *strTab, int shNum, uint8_t *data)
    {
      int   i;  
    
      for(i = 0; i < shNum; i++) {
        size_t k;
         printf("%02d: %s Offset %lx\n", i, &strTab[shdr[i].sh_name], 
            shdr[i].sh_offset);
         for (k = shdr[i].sh_offset; k < shdr[i].sh_offset + shdr[i].sh_size; k++) {
           printf("%x", data[k]);
         }   
         printf("\n");
         for (k = shdr[i].sh_offset; k < shdr[i].sh_offset + shdr[i].sh_size; k++) {
           printf("%c", data[k]);
         }   
         printf("\n");
      }
    }
    

    然后这样称呼它:

    print_section(shdr, strtab, elf->e_shnum, (uint8_t*)data);
    

    获取虚拟地址(偏移量)的一种方式:

    Elf64_Phdr *ph = (Elf64_Phdr *) ((uint8_t *) data + elf->e_phoff);
    printf("Virtual address offset: %lx\n", ph->p_vaddr - elf->e_phoff);
    

    【讨论】:

    • 谢谢,它有效!但只是另一个问题。当我在我的程序上使用 objdump -s 时,我得到一个起始地址: 400200。但是在我的中我只有 200,我应该从结构中添加什么来获得 400200?这些偏移量之间有什么区别?谢谢
    • 0x400000 是 x86_64 平台上的默认值,见这里:stackoverflow.com/questions/14314021/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多