problem while reading inport table
Code:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include<winnt.h>
#define BUF_SIZE 256
TCHAR szName[]=TEXT("process.c");
TCHAR szMsg[]=TEXT("Message from first process");
LPCTSTR MapFileRead(LPCTSTR szFileName, size_t * lpcbSize)
{
PCHAR pThunk;
PCHAR pHintName;
DWORD dwAPIaddress;
PCHAR pDllName;
PCHAR pAPIName;
HANDLE hFile, hMapping;
DWORD dwFileSize;
LPTSTR lpView;
MEMORY_BASIC_INFORMATION mbi;
HANDLE hMapFile;
LPCTSTR pBuf;
PIMAGE_NT_HEADERS pimage_nt_headers;
*lpcbSize = 0;
hFile = CreateFile(szFileName, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// hFile=OpenProcess(PROCESS_ALL_ACCESS,0,szFileName);
//printf("%d",GetLastError());
if (INVALID_HANDLE_VALUE == hFile)
{
return NULL;
}
dwFileSize = GetFileSize(hFile, NULL);
printf("%d",GetLastError());
if (INVALID_FILE_SIZE == dwFileSize)
{
CloseHandle(hFile);
return NULL;
}
hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
if (NULL == hMapping)
{
CloseHandle(hFile);
return NULL;
}
lpView = (LPTSTR)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
//printf("%d",lpView);
PIMAGE_DOS_HEADER pimage_dos_header = PIMAGE_DOS_HEADER(lpView);
printf("%d...",pimage_dos_header->e_lfanew+lpView);
pimage_nt_headers = (PIMAGE_NT_HEADERS)
(lpView + pimage_dos_header->e_lfanew);
DWORD it_voffset = pimage_nt_headers->OptionalHeader.
DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
PIMAGE_IMPORT_DESCRIPTOR pimage_import_descriptor= (PIMAGE_IMPORT_DESCRIPTOR)
(lpView+it_voffset);
printf("%d",pimage_import_descriptor->Name);
while(pimage_import_descriptor->Name!=0)
{
pThunk= lpView+pimage_import_descriptor->FirstThunk;
pHintName= lpView;
if(pimage_import_descriptor->OriginalFirstThunk!=0)
{
pHintName+= pimage_import_descriptor->OriginalFirstThunk;
}
else
{
pHintName+= pimage_import_descriptor->FirstThunk;
}
pDllName= lpView + pimage_import_descriptor->Name;
printf(" DLL Name: %s ", pDllName );
}
CloseHandle(hMapping);
CloseHandle(hFile);
if (NULL != lpView)
{
if (VirtualQuery(lpView, &mbi, sizeof(mbi)) >= sizeof(mbi))
{
*lpcbSize = min(dwFileSize, mbi.RegionSize);
}
else
{
*lpcbSize = dwFileSize;
}
}
return lpView;
}
/*
* Close a file mapping view.
*/
BOOL MapFileClose(LPCVOID lpView)
{
return UnmapViewOfFile(lpView);
}
int main(void)
{
size_t cbSize, i;
const char * file_view;
file_view = (const char *) MapFileRead(TEXT("C:\\WINNT\\system32\\calc.exe"), &cbSize);
return 0;
}
In this program i am trying to read the import table of an executable .
In order to write this code i have taken help from google.
when i run this code .. i am getting the error "MEMORY COULD NOT BE READ"
the point where i am getting this error is highlighted with red color
can someone help me........