Tharaka Wijebandara
Tharaka Wijebandara

Reputation: 8065

List imported DLL of PE file

I tried to list imported DLL of PE file using following code, but it didn't work and windows says that exe has stopped working when I run it. In code, I simply mapped given exe file into memory using CreateFileMapping function and then explorer each section using appropriate structures given in Win32 API. How can I correct it?

#include <stdio.h>
#include <windows.h>

//add Pointer Values
#define MakePtr( cast, ptr, addValue ) (cast)( (unsigned long)(ptr)+(unsigned long)(addValue))


int main(int argc , char ** argv) //main method
{
HANDLE hMapObject, hFile;//File Mapping Object
LPVOID lpBase;//Pointer to the base memory of mapped 

PIMAGE_DOS_HEADER dosHeader;//Pointer to DOS Header
PIMAGE_NT_HEADERS ntHeader;//Pointer to NT Header
PIMAGE_IMPORT_DESCRIPTOR importDesc;//Pointer to import descriptor

hFile = CreateFile(argv[1],GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);//Open the Exe File
if(hFile == INVALID_HANDLE_VALUE){
         printf("\nERROR : Could not open the file specified\n");
}
hMapObject = CreateFileMapping(hFile,NULL,PAGE_READONLY,0,0,NULL);
lpBase = MapViewOfFile(hMapObject,FILE_MAP_READ,0,0,0);//Mapping Given EXE file to Memory

dosHeader = (PIMAGE_DOS_HEADER)lpBase;//Get the DOS Header Base
//verify dos header
if ( dosHeader->e_magic == IMAGE_DOS_SIGNATURE)
{

    ntHeader = MakePtr(PIMAGE_NT_HEADERS, dosHeader, dosHeader->e_lfanew);//Get the NT Header
            //verify NT header
    if (ntHeader->Signature == IMAGE_NT_SIGNATURE ){
        importDesc = MakePtr(PIMAGE_IMPORT_DESCRIPTOR, dosHeader,ntHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);

        while (importDesc->Name)
        {
            printf("%s\n",MakePtr(char*, dosHeader,importDesc->Name));
            importDesc++;               
        }

    }
}

getchar();

}

Upvotes: 0

Views: 2829

Answers (1)

mox
mox

Reputation: 6324

The content of the list you are looking for is contained in a section (like almost everything in a PE image). You must access the section where the directory is pointing to. Take a look at the code of Matt Pietrek (PeDump) to see how it works.

Upvotes: 4

Related Questions