Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I'm manually adding a section to a PE using CFF Explorer.

Here's the PE (after inserting the section):
http://content.screencast.com/users/DELLX/folders/Snagit/media/daedd962-f2e7-4c71-88af-40ffc2a56ccd/09.08.2013-20.36.10.png[^]

Now I'm using this code:
C++
PBYTE base = (PBYTE)GetModuleHandle(0);
PIMAGE_DOS_HEADER __IDH = (PIMAGE_DOS_HEADER)base ;
PIMAGE_NT_HEADERS __NTHEADER ;
__NTHEADER = PIMAGE_NT_HEADERS( (DWORD)__IDH +__IDH->e_lfanew);
PIMAGE_SECTION_HEADER __SECTIONHEAD = NULL;
for(int i =0;i<__NTHEADER->FileHeader.NumberOfSections;i++)
{
    __SECTIONHEAD = (PIMAGE_SECTION_HEADER)((DWORD)base+__IDH->e_lfanew+248+(i*40));
    puts((const char*)__SECTIONHEAD->Name);
    if(!strcmp((const char*)__SECTIONHEAD->Name,".cdata"))
    {
        char* PtrToData = (char*)((DWORD)__NTHEADER->OptionalHeader.ImageBase + __SECTIONHEAD->VirtualAddress);
        printf("address of cdata=0x%x",PtrToData);
    }
 }


It all works well and good, but the pointer calculated to the address of the start of ".cdata" (PtrToData) section does not actually lead me to where that section is in memory. It's just a bunch of random junk.

Does anyone see the problem? Or am I missing something more fundamental about how sections are loaded in memory?

Thank you very much for any help you can give
Posted

1 solution

I don't follow your code completely but it looks like you are incorrectly doing pointer arithmetic. The short answer is that you need to do some casting to calculate offsets in bytes.

Consider the code:

C++
char* ch = new char[20];
char* pch = ch + 1;
int* in = new int[20];
int* pin = in + 1;

Note that pch points 1 byte past 'ch', but (surprise!) pin points 4 bytes (sizeof(int)) past 'in'. When you add an integer to a pointer of type 'x', the result is the pointer plus the integer times sizeof(x). It is not pointer plus integer.

You probably want to cast the pointers in your code to be 1 byte fields (ie. char* or equivalent)...
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 9-Sep-13 1:25am    
Nice catch even if this is not the only problem, 5ed.
—SA
H.Brydon 9-Sep-13 1:45am    
Thank you Sergey. Agreed, I think that there are probably other issues to address, too.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900