I am trying to parse a .elf file to read it and edit it a bit using open() and mmap(). However, my code is not working as expected.
I tried to narrow it down as much as possible while debugging to the point that I am just printing the file content. The problem that I found so far is the file content are not as expected at all when I compare it to an obj dump objdump -s my_file.elf
Here is my code
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
typedef struct iFi {
unsigned char *pB; // memory mapped file
int handle_File;
unsigned long fSize; // file size
struct stat sts; /* File status */
char szFN[1024]; // file name
} XFILE;
int main (int argc, char **argv) {
if(argc != 2)
return 1;
XFILE *pF;
memset (&pF, 0, sizeof (pF));
memset (&pF->pB, 0, sizeof (pF->pB));
memset (&pF->szFN, 0, sizeof (pF->szFN));
strcpy (pF->szFN, argv[1]);
mode_t perms = S_IRUSR | S_IWUSR;
pF->handle_File = open("../hello.elf", O_RDWR, perms);
if (pF->handle_File < 0) {
perror("open");
return (1);
}
int n = stat (pF->szFN, &pF->sts);
if (n != 0) return(1000); // failed
pF->fSize = pF->sts.st_size;
//pF->hFmap = CreateFileMapping (pF->hFile, NULL, PAGE_READWRITE /*PAGE_WRITECOPY*/, 0, 0, NULL);
pF->pB = static_cast<unsigned char*>(mmap(NULL, pF->fSize, PROT_READ | PROT_WRITE, MAP_SHARED, pF->handle_File, 0));
if (pF->pB == NULL) return 1000; // can't map view of file
printf("Contents of file = 0x%xn", *pF->pB);
return 0;
}