I’m trying to read the contents of an ELF file into memory using C. I can currently read a file with 1 program header fine but am having an issue with more than this.
/* 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);
The issue I think I’m having is with the
fseek(fp, elfhead.phdrpos, SEEK_SET);
As I am just seeking to the start of the 1st program header each time. How do I change this so each time I’m seeking to the start of the first header, then the second header etc..
Thanks
Your code is pretty bad 🙁
You do the following:
In other words, you allocate N times, fread N times, disassemble N times the same first phdr, free N times.
What you want instead: