ELF文件中的多个程序标题

时间:2013-01-17 17:20:42

标签: c io elf fread disassembly

我正在尝试使用C将ELF文件的内容读入内存。我当前可以读取1个程序标题的文件,但是我遇到的问题不止于此。

/* Find and read program headers */
  ELFPROGHDR *prgHdr;

  fseek(fp, elfhead.phdrpos, SEEK_SET);
  prgHdr = (ELFPROGHDR*)malloc(sizeof(ELFPROGHDR)*elfhead.phdrcnt);
  if(!prgHdr)
    {
      fprintf(fp, "Out of Memory\n");
      fclose(fp);
      return 3;
      }

  fread(prgHdr, 1, sizeof(ELFPROGHDR)*elfhead.phdrcnt, fp);
  printf("Segment-Offset: %x\n", prgHdr->offset);
  printf("File-size: %d\n", prgHdr->filesize);
  printf("Align: %d\n", prgHdr->align);

/* allocate memory and read in ARM instructions */

  for(i = 0; i < elfhead.phdrcnt; i++)
    {
      armInstructions = (unsigned int *)malloc(prgHdr->filesize + 3 & ~3);
      if(armInstructions == NULL)
    {
      fclose(fp);
      free(prgHdr);
      fprintf(stderr, "Out of Memory\n");
      return 3;
    }
      fseek(fp, prgHdr->offset, SEEK_SET);
      fread(armInstructions, 1, prgHdr->filesize, fp);

/* Disassemble */
      printf("\nInstructions\n\n");

      Disassemble(armInstructions, (prgHdr->filesize + 3 & ~3) /4, prgHdr->virtaddr);
      printf("\n"); 
      free(armInstructions);
    }
  free(prgHdr);

我认为我遇到的问题是

fseek(fp, elfhead.phdrpos, SEEK_SET);

因为我每次只是寻求第一个节目标题的开头。我如何改变这一点,所以每次我寻求第一个标题的开头,然后是第二个标题等。

由于

1 个答案:

答案 0 :(得分:0)

你的代码非常糟糕: - (

您执行以下操作:

for i in phdrcnt
  fseek(phdrpos);
  prgHdr[i] = malloc space for *all* phdrs
  fread() *all* phdrs into the allocated space
  use first phdr to disassemble
  free allocated space

换句话说,你分配N次,fread N次,反汇编N次相同的第一个phdr,免费N次。

你想要的是什么:

fseek(phdrpos)
prgHdr = malloc space for all phdrs
fread all phdrs into space allocated
for i in phdrcnt
  disassemble(pgrHdr[i])
free(pgrHdr)