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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...
NoWriterDateCnt.TitleFile(s)
13237정성태1/30/202314269.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/202313036개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/202312502개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/202314903개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/202316120오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/202312022스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/202311236오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/202312005개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/202313871.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/202314417.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/202313322개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/202312294.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/202311620개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/202312122Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/202312061오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/202311897개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/202312103Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/202311730오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/202311380Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/202311249VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/202311971디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/202311891디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/202314909Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/202313775.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/202312159오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/202313542기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...