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)
13616정성태5/3/20248612닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
13615정성태5/3/20249515닷넷: 2255. C# 배열을 Numpy ndarray 배열과 상호 변환
13614정성태5/2/20249181닷넷: 2254. C# - COM 인터페이스의 상속 시 중복으로 메서드를 선언
13613정성태5/1/20248906닷넷: 2253. C# - Video Capture 장치(Camera) 열거 및 지원 포맷 조회파일 다운로드1
13612정성태4/30/20249178오류 유형: 902. Visual Studio - error MSB3021: Unable to copy file
13611정성태4/29/20248563닷넷: 2252. C# - GUID 타입 전용의 UnmanagedType.LPStruct - 두 번째 이야기파일 다운로드1
13610정성태4/28/20248945닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/20249163닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/20249498닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/20249495닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/20249362닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/202410701닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/20248400오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/20249663닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/20248941닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/20249052닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/20249662닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/20249512닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/202410727닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/20249105닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20249745닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20249894닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20249760닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20248976닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/202411296C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동 [1]
13591정성태4/2/20249420닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...