How to determine a windows executables DLL dependencies programmatically?

后端 未结 6 2126
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 05:08

How to determine what DLL\'s a binary depends on using programmatic methods?

To be clear, I am not trying to determine the DLL dependencies of the running exec, bu

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 06:05

    76 lines to do that based on pedump code (don't forget to add Imagehlp.lib as dependancy):

    #include 
    #include "windows.h" //DONT REMOVE IT
    #include "ImageHlp.h"
    #include "stdafx.h"
    
    template  PIMAGE_SECTION_HEADER GetEnclosingSectionHeader(DWORD rva, T* pNTHeader) // 'T' == PIMAGE_NT_HEADERS 
    {
        PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(pNTHeader);
        unsigned i;
    
        for ( i=0; i < pNTHeader->FileHeader.NumberOfSections; i++, section++ )
        {
            // This 3 line idiocy is because Watcom's linker actually sets the
            // Misc.VirtualSize field to 0.  (!!! - Retards....!!!)
            DWORD size = section->Misc.VirtualSize;
            if ( 0 == size )
                size = section->SizeOfRawData;
    
            // Is the RVA within this section?
            if ( (rva >= section->VirtualAddress) && 
                 (rva < (section->VirtualAddress + size)))
                return section;
        }
    
        return 0;
    }
    
    template  LPVOID GetPtrFromRVA( DWORD rva, T* pNTHeader, PBYTE imageBase ) // 'T' = PIMAGE_NT_HEADERS 
    {
        PIMAGE_SECTION_HEADER pSectionHdr;
        INT delta;
    
        pSectionHdr = GetEnclosingSectionHeader( rva, pNTHeader );
        if ( !pSectionHdr )
            return 0;
    
        delta = (INT)(pSectionHdr->VirtualAddress-pSectionHdr->PointerToRawData);
        return (PVOID) ( imageBase + rva - delta );
    }
    
    
    void DumpDllFromPath(wchar_t* path) {
        char name[300];
        wcstombs(name,path,300);
    
        PLOADED_IMAGE image=ImageLoad(name,0);
    
        if (image->FileHeader->OptionalHeader.NumberOfRvaAndSizes>=2) {
            PIMAGE_IMPORT_DESCRIPTOR importDesc=
                (PIMAGE_IMPORT_DESCRIPTOR)GetPtrFromRVA(
                    image->FileHeader->OptionalHeader.DataDirectory[1].VirtualAddress,
                    image->FileHeader,image->MappedAddress);
            while ( 1 )
            {
                // See if we've reached an empty IMAGE_IMPORT_DESCRIPTOR
                if ( (importDesc->TimeDateStamp==0 ) && (importDesc->Name==0) )
                    break;
    
                printf("  %s\n", GetPtrFromRVA(importDesc->Name,
                                               image->FileHeader,
                                               image->MappedAddress) );
                importDesc++;
            }
        }
        ImageUnload(image);
    
    }
    
    //Pass exe or dll as argument 
    int _tmain(int argc, _TCHAR* argv[])
    {
        DumpDllFromPath(argv[1]);
    
        return 0;
    }
    

提交回复
热议问题