0

我正在尝试使用 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);

因为我每次都在寻找第一个程序头的开始。如何更改此设置,以便每次我寻找第一个标题的开头,然后是第二个标题等。

谢谢

4

1 回答 1

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)
于 2013-01-18T05:10:22.567 回答