I am trying to get the contents of the .text section of a file (notepad.exe) using the following code:
#define SECHDROFFSET(a) ((LPVOID) ( (LPBYTE) a + \ ((PIMAGE_DOS_HEADER)a)->e_lfanew + \ sizeof(IMAGE_NT_HEADERS))) PIMAGE_DOS_HEADER pDosH; PIMAGE_NT_HEADERS pNtH; PIMAGE_SECTION_HEADER pSecH; HANDLE hFile; DWORD dwFileSize, dwSectionSize, dwStubSize, dwVSize, dwOldProt, dwSpot, dwGap, bytes; LPBYTE FileBuffer, SectionBuffer; CHAR FileName[MAX_PATH]; printf("Input file path: "); scanf("%s", &FileName); // open it and get the size hFile = CreateFileA(FileName, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); dwFileSize = GetFileSize(hFile, 0); // load it into memory FileBuffer = (LPBYTE) malloc(dwFileSize); ReadFile(hFile, FileBuffer, dwFileSize, &bytes, 0); pDosH = (PIMAGE_DOS_HEADER) FileBuffer; // basic checks if(pDosH->e_magic != IMAGE_DOS_SIGNATURE) return -1; pNtH = (PIMAGE_NT_HEADERS) (FileBuffer + pDosH->e_lfanew); if(pNtH->Signature != IMAGE_NT_SIGNATURE) return -2; pSecH = (PIMAGE_SECTION_HEADER) SECHDROFFSET(FileBuffer); while(memcmp(pSecH->Name, ".text", 5)) pSecH++; The problem is that the section names are not valid; when debugging I never see a string of type .<section_name> to take the value of pSecH->Name. They are always unprintable characters.
Am I reading from the correct offset?
SECHDROFFSET()is not a standard macro; I just Googled for it and the implementations I saw will often produce the wrong offset for the section table. Don't useSECHDROFFSET()since its formula is incorrect.IMAGE_FIRST_SECTION(), whose formula is correct.