I compiled the following four lines of code into a file called foo.exe, hoping that the value of the global variable 'i' (i.e, 9) would go into the data section of foo.exe
int i = 9;
int main()
{
}
Then I used the following code to find out if it really was in the .data section of foo.exe, but didn't find anything.. Can someone please explain me what went wrong..??
#include<iostream>
#include<Windows.h>
#include<stdio.h>
#include<WinNT.h>
int main()
{
HANDLE hFile;
HANDLE hFileMapping;
LPVOID lpFileBase;
PIMAGE_DOS_HEADER dosHeader;
hFile = CreateFile(TEXT("foo.exe"), GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if ( hFile == INVALID_HANDLE_VALUE )
{
printf("Couldn't open file with CreateFile()\n");
return 0;
}
hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
if ( hFileMapping == 0 )
{
CloseHandle(hFile);
printf("Couldn't open file mapping with CreateFileMapping()\n");
return 0;
}
lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
if ( lpFileBase == 0 )
{
CloseHandle(hFileMapping);
CloseHandle(hFile);
printf("Couldn't map view of file with MapViewOfFile()\n");
return 0;
}
PIMAGE_DOS_HEADER pimdh;
pimdh = (PIMAGE_DOS_HEADER)lpFileBase;
PIMAGE_NT_HEADERS pimnth;
pimnth = (PIMAGE_NT_HEADERS)((char *)lpFileBase + pimdh->e_lfanew);
PIMAGE_SECTION_HEADER pimsh;
pimsh = (PIMAGE_SECTION_HEADER)(pimnth + 1);
PIMAGE_IMPORT_DESCRIPTOR pimid;
long delta;
for(int i = 0; i<pimnth->FileHeader.NumberOfSections;i++)
{
if(!strcmp((char *)pimsh->Name,".data"))
{
DWORD base = (DWORD)lpFileBase;
for(DWORD start = pimsh ->PointerToRawData; start <= (pimsh->PointerToRawData + pimsh->SizeOfRawData); start++)
{
if(*((int *)(start + base)) == 9)
{
printf("found");
break;
}
}
}
pimsh++;
}
}
The compiler (linker) did not put your variable in the image file because the variable is not even used in the code!