Search code examples
dllexecutablefile-extensionportable-executable

How to tell if a file is an EXE or a DLL?


If you've gotten the file extensions messed up, how can you tell an executable apart from a DLL?

They both seem to have entry points and everything...


Solution

  • Look at this article for a good explanation of a portable executable on windows.

    And then look at the section about the PE header. Also the code there-in shows in C the way to open and examine a PE file using Win32. This information you are looking for is stored in the IMAGE_FILE_HEADER. Specifically in the Characteristics field which would include the flag IMAGE_FILE_DLL 0x2000 if it is a dll.

    That should give you enough information to create a small utility that makes the determination of a bunch of files if that is what you are looking for.

    The most relevant bits of code for reference purposes, copied from the article above and edited to remove extraneous detail/error handling.

    void DumpFile(LPWSTR filename)
    {
        HANDLE hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
    
        HANDLE hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    
        LPVOID lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);    
    
        PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)lpFileBase;
    
        PIMAGE_NT_HEADERS pNTHeader = (PIMAGE_NT_HEADERS)((DWORD)pDosHeader + (DWORD)pDosHeader->e_lfanew);
    
        if ((pNTHeader->FileHeader.Characteristics & IMAGE_FILE_DLL))
             printf("dll"); 
        if ((pNTHeader->FileHeader.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE))
             printf("exe"); 
        else 
             printf("????");
    
        UnmapViewOfFile(lpFileBase);
        CloseHandle(hFileMapping);
        CloseHandle(hFile);
    }