Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 3개 있습니다.)
.NET Framework: 181. AssemblyVersion, AssemblyFileVersion, AssemblyInformationalVersion
; https://www.sysnet.pe.kr/2/0/897

닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법
; https://www.sysnet.pe.kr/2/0/13651

닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법
; https://www.sysnet.pe.kr/2/0/13652




C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법

지난 글에서,

C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법
; https://www.sysnet.pe.kr/2/0/13651

DLL에 Win32 Resource로 저장된 AssemblyFileVersion을 구했는데요, 그렇다면 대상 환경이 Linux인 경우에는 어떻게 해야 할까요? 당연히 MetadataLoadContext 패키지를 이용한 Reflection 방법을 쓰면 가능하겠지만, 직접 Win32 API를 DllImport로 호출하는 방법은 사용할 수 없습니다. 왜냐하면 리눅스에는 ^^; Win32 DLL이 없기 때문입니다.

비록 Win32 API는 사용할 수 없지만, 그래도 다행인 점은 해당 파일이 CLI 스펙에서 명시하고 있듯이,

ECMA-335, Common Language Infrastructure (CLI), 6th edition, June 2012
; https://ecma-international.org/publications-and-standards/standards/ecma-335/

// II.25 File format extensios to PE

The file format for CLI components is a strict extension of the current Portable Executable (PE) File
Format.

PE 포맷을 따른다는 점입니다. 그렇기 때문에 C# 컴파일러는 AssemblyFileVersionAttribute 특성에 지정한 버전 정보를 (윈도우 운영체제가 아님에도) DLL 파일 생성 시 PE 포맷의 리소스 영역에 (윈도우와 동일하게) 저장합니다.




간단하게 확인해 볼까요? ^^ 이를 위해 Console 프로젝트를 하나 만들어 리눅스용으로 빌드한 다음,

dotnet publish -c Release -r linux-x64 --self-contained true

생성된 \Release\net8.0\linux-x64\publish 디렉터리의 ./ConsoleApp1 실행 파일의 포맷을 보면,

$ file ConsoleApp1
ConsoleApp1: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=b048c77e08dcc335070a0c135f9603cae12a7cba, stripped

ELF 포맷으로 나오는데요, 실행 파일이 이렇게 나오는 것은 어쩔 수 없습니다. 하지만, DLL이라면 예상한 대로 PE 포맷이어서,

$ file ConsoleApp1.dll
ConsoleApp1.dll: PE32+ executable (console) x86-64 Mono/.Net assembly, for MS Windows

결국, Linux에서도 DLL 파일을 로드해 PE 포맷에 맞게 접근하면 파일 정보를 구할 수 있습니다.

자, 그럼 C#을 이용해 저 Win32 리소스를 순수하게 파일 포맷을 접근하는 과정으로 구현하면 될 텐데요, 다행히 ^^ PE 포맷을 해석해 주는 nuget 패키지가 있으니,

Install-Package Workshell.PE
Install-Package Workshell.PE.Resources

// 그러고 보니, 예전에도 한 번 소개한 적이 있군요. ^^

다음과 같이 간단하게 작성할 수 있습니다.

using Workshell.PE.Resources;
using Workshell.PE;
using Workshell.PE.Resources.Version;
using System.Reflection;

[assembly: AssemblyFileVersion("5.0.0.1")]

namespace ConsoleApp3;

internal class Program
{
    static void Main(string[] args)
    {
        VersionResource.Register();

        {
            string dllPath = typeof(Program).Assembly.Location;
            Version version = GetFileVersion(dllPath);

            Console.WriteLine($"File Version: {version}"); // 출력 결과 "File Version: 5.0.0.1"
        }
    }

    static Version _emptyVersion = new Version();

    private static Version GetFileVersion(string dllPath)
    {
        PortableExecutableImage pe = PortableExecutableImage.FromFile(dllPath);
        ResourceCollection resources = ResourceCollection.Get(pe);

        foreach (ResourceType resource in resources)
        {
            if (resource.Id == ResourceType.Version)
            {
                VersionResource? res = resource[0] as VersionResource;

                if (res != null)
                {
                    VersionInfo versionInfo = res.GetInfo(res.Languages.FirstOrDefault());
                    return versionInfo.Fixed.FileVersion;
                }
            }
        }

        return _emptyVersion;
    }
}

(2024-07-17 업데이트) 패치된 4.0.0.147 버전이 올라왔습니다. 참고로, 현재(2024-06-21) 시점의 3.0.0.130 Workshell.PE 패키지는 버그가 있어서,

Bug in parsing VS_VERSION_INFO #9
; https://github.com/Workshell/pe/issues/9

경우에 따라 Win32 Resource 구조를 분석 시 오류가 발생합니다. 조만간 nuget에 패치 버전이 올라오겠지만, 그때까지는 "https://github.com/Workshell/pe/tree/feature/issue-9" 브랜치를 직접 빌드해서 사용해야 합니다.




그러니까, 위의 소스코드에서 다룬 2진 파일 포맷은 과거 Win32 C/C++ 프로젝트 시절에 우리가 흔히 봐왔던 rc 파일의 VS_VERSION_INFO를 빌드했을 때 생성되는 리소스 영역입니다.

VS_VERSION_INFO VERSIONINFO
 FILEVERSION 1,0,0,1
 PRODUCTVERSION 1,0,0,1
 FILEFLAGSMASK 0x3fL
 FILEFLAGS 0x0L
 FILEOS 0x40004L
 FILETYPE 0x1L
 FILESUBTYPE 0x0L
BEGIN

    BLOCK "VarFileInfo"
    BEGIN
        VALUE "Translation", 0x412, 1200
    END

    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "041204b0"
        BEGIN
            VALUE "CompanyName", "TODO: <Company name>"
            VALUE "FileDescription", "TODO: <File description>"
            VALUE "FileVersion", "1.0.0.1"
            VALUE "InternalName", "ConsoleA.exe"
            VALUE "LegalCopyright", "Copyright (C) 2024"
            VALUE "OriginalFilename", "ConsoleA.exe"
            VALUE "ProductName", "TODO: <Product name>"
            VALUE "ProductVersion", "1.0.0.1"
        END
    END
END

검색해 보니, Win32 Resource File Format에 대한 좋은 문서가 나오는데요,

Win32 Resource (RES) File Format / RESFMT.TXT
; https://bytepointer.com/resources/win32_res_format.htm
; https://web.archive.org/web/20240229115941/http://bytepointer.com/resources/win32_res_format.htm

저 중에서 "4.12 Version Resourses"의 내용이 바로 오늘의 주제와 관련이 있습니다. 문서에 나온 VS_VERSION_INFO를 보면,

VS_VERSION_INFO { 
    WORD wLength;             /* Length of the version resource */ 
    WORD wValueLength;        /* Length of the value field for this block */ 
    WORD wType;               /* type of information:  1==string, 0==binary */ 
    WCHAR szKey[];            /* Unicode string KEY field */ 
    [WORD Padding1;]          /* possible word of padding */ 
    VS_FIXEDFILEINFO Value;   /* Fixed File Info Structure */ 
    BYTE Children[];      /* position of VarFileInfo or StringFileInfo data */ 
}; 

주요 구조체라고는 VS_FIXEDFILEINFO와 "Children[]"으로 오게 되는 StringFileInfo, VarFileInfo가 전부입니다.

StringFileInfo는 다시 내부에 StringTable이 들어가고, StringTable은 결국 String 포맷의 배열을 가지게 됩니다. (2024-06-24 업데이트: 좀 더 완전한 유형의 포맷을 "C# - Win32 Resource 포맷 해석" 글에 실었습니다.)

StringFileInfo { 
    WCHAR       szKey[];      /* Unicode "StringFileInfo" */ 
    [WORD        padding;]    /* possible padding */ 
    StringTable Children[]; 
}; 
 
StringTable { 
    WCHAR      szKey[];   /* Unicode string denoting the language - 8 bytes */ 
    String Children[];    /* array of children String structures */ 
} 
 
String { 
    WCHAR   szKey[];          /* arbitrary Unicode encoded KEY string */ 
                         /* note that there is a list of pre-defined keys */ 
    [WORD   padding;]         /* possible padding */ 
    WCHAR Value[];            /* Unicode-encoded value for KEY */ 
} String; 

마지막으로 VarFileInfo도 Var 배열의 묶음 형태입니다.

VarFileInfo { 
    WCHAR szKey[];            /* Unicode "VarFileInfo" */ 
    [WORD padding;];          /* possible padding */ 
    Var        Children[];    /* children array */ 
}; 
 
Var { 
    WCHAR szKey[];       /* Unicode "Translation" (or other user key) */ 
    [WORD padding;]      /* possible padding */ 
    WORD  Value[];       /* one or more values, normally language id's */ 
}; 

약간의 가변 배열과 2바이트 WORD Padding 정도만 주의하면 어렵지 않게 분석할 수 있을 것입니다. 일례로 C/C++로 저 구조체를 직접 접근하는 소스코드를 아래의 글에서 찾을 수 있습니다.

C library to read EXE version from Linux?
; https://stackoverflow.com/questions/12396665/c-library-to-read-exe-version-from-linux

위의 글에 있는 소스코드를 그대로 베껴 (약간 수정해) 동작하는 버전으로 만들면 다음과 같이 정리가 됩니다. (첨부 파일로도 포함시켜 두었습니다.)

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>

typedef uint32_t DWORD;
typedef uint16_t WORD;
typedef uint8_t BYTE;

#define READ_BYTE(p) (((unsigned char*)(p))[0])
#define READ_WORD(p) ((((unsigned char*)(p))[0]) | ((((unsigned char*)(p))[1]) << 8))
#define READ_DWORD(p) ((((unsigned char*)(p))[0]) | ((((unsigned char*)(p))[1]) << 8) | \
    ((((unsigned char*)(p))[2]) << 16) | ((((unsigned char*)(p))[3]) << 24))

#define PAD(x) (((x) + 3) & 0xFFFFFFFC)

const char* FindVersion(const char* buf);
int PrintVersion(const char* version, int offs);

int main(int argc, char** argv)
{
    if (argc < 2)
    {
        char fileNameBuffer[256] = { 0 };
        _splitpath_s(argv[0], nullptr, 0, nullptr, 0, fileNameBuffer, 256, nullptr, 0);
        printf("Usage: %s <file>\n", fileNameBuffer);
        return 1;
    }

    struct stat st;
    if (stat(argv[1], &st) < 0)
    {
        perror(argv[1]);
        return 1;
    }

    char* buf = (char *)malloc(st.st_size);

    FILE* f = fopen(argv[1], "r");
    if (!f)
    {
        perror(argv[1]);
        return 2;
    }

    fread(buf, 1, st.st_size, f);
    fclose(f);

    const char* version = FindVersion(buf);
    if (!version)
        printf("No version\n");
    else
        PrintVersion(version, 0);
    return 0;
}

int PrintVersion(const char* version, int offs)
{
    offs = PAD(offs);

    WORD len = READ_WORD(version + offs);
    offs += 2;
    WORD valLen = READ_WORD(version + offs);
    offs += 2;
    WORD type = READ_WORD(version + offs);
    offs += 2;

    char info[200];
    int i;
    for (i = 0; i < 200; ++i)
    {
        WORD c = READ_WORD(version + offs);
        offs += 2;

        info[i] = c;
        if (!c)
            break;
    }

    offs = PAD(offs);

    if (type != 0) //TEXT
    {
        char value[200];
        for (i = 0; i < valLen; ++i)
        {
            WORD c = READ_WORD(version + offs);
            offs += 2;
            value[i] = c;
        }
        value[i] = 0;
        printf("info <%s>: <%s>\n", info, value);
    }
    else
    {
        if (strcmp(info, "VS_VERSION_INFO") == 0)
        {
            //fixed is a VS_FIXEDFILEINFO
            const char* fixed = version + offs;
            WORD fileA = READ_WORD(fixed + 10);
            WORD fileB = READ_WORD(fixed + 8);
            WORD fileC = READ_WORD(fixed + 14);
            WORD fileD = READ_WORD(fixed + 12);
            WORD prodA = READ_WORD(fixed + 18);
            WORD prodB = READ_WORD(fixed + 16);
            WORD prodC = READ_WORD(fixed + 22);
            WORD prodD = READ_WORD(fixed + 20);
            printf("\tFile: %d.%d.%d.%d\n", fileA, fileB, fileC, fileD);
            printf("\tProd: %d.%d.%d.%d\n", prodA, prodB, prodC, prodD);
        }
        offs += valLen;
    }

    while (offs < len)
        offs = PrintVersion(version, offs);

    return PAD(offs);
}

const char* FindVersion(const char* buf)
{
    //buf is a IMAGE_DOS_HEADER
    if (READ_WORD(buf) != 0x5A4D) //MZ signature
        return nullptr;

    //pe is a IMAGE_NT_HEADERS32
    int offset = READ_DWORD(buf + 0x3C);
    const char* pe = buf + READ_DWORD(buf + 0x3C) - 1;
    if (READ_WORD(pe) != 0x4550) //PE signature
        return nullptr;

    //coff is a IMAGE_FILE_HEADER
    const char* coff = pe + 4;

    WORD numSections = READ_WORD(coff + 2);
    WORD optHeaderSize = READ_WORD(coff + 16);
    if (numSections == 0 || optHeaderSize == 0)
        return nullptr;

    //optHeader is a IMAGE_OPTIONAL_HEADER32
    const char* optHeader = coff + 20;
    WORD magic = READ_WORD(optHeader);
    if (magic != 0x10b && magic != 0x20b)
        return nullptr;

    //dataDir is an array of IMAGE_DATA_DIRECTORY
    const char* dataDir = optHeader + (magic == 0x10b ? 96 : 112);
    DWORD vaRes = READ_DWORD(dataDir + 8 * 2);

    //secTable is an array of IMAGE_SECTION_HEADER
    const char* secTable = optHeader + optHeaderSize;

    int i;
    for (i = 0; i < numSections; ++i)
    {
        //sec is a IMAGE_SECTION_HEADER*
        const char* sec = secTable + 40 * i;
        char secName[9];
        memcpy(secName, sec, 8);
        secName[8] = 0;

        if (strcmp(secName, ".rsrc") != 0)
            continue;

        DWORD vaSec = READ_DWORD(sec + 12);
        const char* raw = buf + READ_DWORD(sec + 20);

        const char* resSec = raw + (vaRes - vaSec);

        WORD numNamed = READ_WORD(resSec + 12);
        WORD numId = READ_WORD(resSec + 14);

        int j;
        for (j = 0; j < numNamed + numId; ++j)
        {
            //resSec is a IMAGE_RESOURCE_DIRECTORY followed by an array
           // of IMAGE_RESOURCE_DIRECTORY_ENTRY
            const char* res = resSec + 16 + 8 * j;
            DWORD name = READ_DWORD(res);
            if (name != 16) //RT_VERSION
                continue;

            DWORD offs = READ_DWORD(res + 4);
            if ((offs & 0x80000000) == 0) //is a dir resource?
                return NULL;
            //verDir is another IMAGE_RESOURCE_DIRECTORY and 
            // IMAGE_RESOURCE_DIRECTORY_ENTRY array
            const char* verDir = resSec + (offs & 0x7FFFFFFF);

            numNamed = READ_WORD(verDir + 12);
            numId = READ_WORD(verDir + 14);
            if (numNamed == 0 && numId == 0)
                return NULL;
            res = verDir + 16;
            offs = READ_DWORD(res + 4);
            if ((offs & 0x80000000) == 0) //is a dir resource?
                return NULL;

            //and yet another IMAGE_RESOURCE_DIRECTORY, etc.
            verDir = resSec + (offs & 0x7FFFFFFF);
            numNamed = READ_WORD(verDir + 12);
            numId = READ_WORD(verDir + 14);
            if (numNamed == 0 && numId == 0)
                return NULL;
            res = verDir + 16;
            offs = READ_DWORD(res + 4);
            if ((offs & 0x80000000) != 0) //is a dir resource?
                return NULL;
            verDir = resSec + offs;

            DWORD verVa = READ_DWORD(verDir);

            const char* verPtr = raw + (verVa - vaSec);
            return verPtr;
        }

        return nullptr;
    }

    return nullptr;

}




문서에 나온 Resource 데이터 포맷이 이렇게 정리가 되는데,

4. Resource Data Format
    4.1 Version Resources
    4.2 Icon Resources 
    4.3 Menu Resources 
    4.4 Dialog Box Resources 
    4.5 Cursor Resources 
    4.6 Bitmap Resources 
    4.7 Font and Font Directory Resources 
    4.8 String Table Resources 
    4.9 Accelerator Table Resources 
    4.10 User Defined Resources and RCDATA 
    4.11 Name Table and Error Table Resources 
    4.12 Version Resourses
    4.13 Messagetable Resources 

오늘 다룬 내용을 시작으로 인연이 있을 때마다 하나씩 다루는 ^^ 글을 써보면 재미있을 듯합니다. 안 그래도 위의 목차 중 "4.4 Dialog Box Resources"는 oldnewthing의 블로그에 정리된 글을 번역하면서 소개한 적이 있었습니다. ^^

Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
; https://www.sysnet.pe.kr/2/0/13286

Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법
; https://www.sysnet.pe.kr/2/0/13287




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/17/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13870정성태1/18/2025531개발 환경 구성: 741. WinDbg - 네트워크 커널 디버깅이 가능한 NIC 카드 지원 확대
13869정성태1/18/2025516개발 환경 구성: 740. WinDbg - _NT_SYMBOL_PATH 환경 변수에 설정한 경로로 심벌 파일을 다운로드하지 않는 경우
13868정성태1/17/2025481Windows: 277. Hyper-V - Windows 11 VM의 Enhanced Session 모드로 로그인을 할 수 없는 문제
13867정성태1/17/2025524오류 유형: 943. Hyper-V에 Windows 11 설치 시 "This PC doesn't currently meet Windows 11 system requirements" 오류
13866정성태1/16/2025673개발 환경 구성: 739. Windows 10부터 바뀐 device driver 서명 방법
13865정성태1/15/2025844오류 유형: 942. C# - .NET Framework 4.5.2 이하의 버전에서 HttpWebRequest로 https 호출 시 "System.Net.WebException" 예외 발생
13864정성태1/15/2025905Linux: 114. eBPF를 위해 필요한 SELinux 보안 정책
13863정성태1/14/2025971Linux: 113. Linux - 프로세스를 위한 전용 SELinux 보안 문맥 지정
13862정성태1/13/2025895Linux: 112. Linux - 데몬을 위한 SELinux 보안 정책 설정
13861정성태1/11/2025946Windows: 276. 명령행에서 원격 서비스를 동기/비동기로 시작/중지
13860정성태1/10/2025951디버깅 기술: 216. WinDbg - 2가지 유형의 식 평가 방법(MASM, C++)
13859정성태1/9/2025946디버깅 기술: 215. Windbg - syscall 이후 실행되는 KiSystemCall64 함수 및 SSDT 디버깅
13858정성태1/8/20251030개발 환경 구성: 738. PowerShell - 원격 호출 시 "powershell.exe"가 아닌 "pwsh.exe" 환경으로 명령어를 실행하는 방법
13857정성태1/7/20251007C/C++: 187. Golang - 콘솔 응용 프로그램을 Linux 데몬 서비스를 지원하도록 변경파일 다운로드1
13856정성태1/6/20251001디버깅 기술: 214. Windbg - syscall 단계까지의 Win32 API 호출 (예: Sleep)
13855정성태12/28/20241506오류 유형: 941. Golang - os.StartProcess() 사용 시 오류 정리
13854정성태12/27/20241468C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20241753디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/20241672디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20241560디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/20241628오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/20242010디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20242315디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20242221오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
13846정성태12/17/20242255디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...