1

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?

5
  • 1
    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 use SECHDROFFSET() since its formula is incorrect. Mar 5 '16 at 20:20
  • @Jason Geffner I've added the macro. How can I jump over the DOS header?
    – Sebi
    Mar 5 '16 at 20:27
  • 1
    If you want to use a macro to find the section table, use IMAGE_FIRST_SECTION(), whose formula is correct. Mar 5 '16 at 20:33
  • Thanks. I got it working by using pSecH = IMAGE_FIRST_SECTION(pNtH);
    – Sebi
    Mar 5 '16 at 22:42
  • 1
    Glad it's working! I'll add that as an answer below now. Mar 6 '16 at 1:14
6

As per the comments above, the SECHDROFFSET() macro formula is not reliable. You should instead use the macro IMAGE_FIRST_SECTION().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.