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)
13785정성태10/23/202459C/C++: 182. 윈도우가 운영하는 2개의 Code Page파일 다운로드1
13784정성태10/23/202461Linux: 95. eBPF - kprobe를 이용한 트레이스
13783정성태10/23/202462Linux: 94. eBPF - vmlinux.h 헤더 포함하는 방법 (bpf2go에서 사용)
13782정성태10/23/202493Linux: 93. Ubuntu 22.04 - 커널 이미지로부터 커널 함수 역어셈블
13781정성태10/22/2024236오류 유형: 930. WSL + eBPF: modprobe: FATAL: Module kheaders not found in directory
13780정성태10/22/2024186Linux: 92. WSL 2 - 커널 이미지로부터 커널 함수 역어셈블
13779정성태10/22/202491개발 환경 구성: 729. WSL 2 - Mariner VM 커널 이미지 업데이트 방법
13778정성태10/21/2024202C/C++: 181. C/C++ - 소스코드 파일의 인코딩, 바이너리 모듈 상태의 인코딩
13777정성태10/20/2024249Windows: 265. Win32 API의 W(유니코드) 버전은 UCS-2일까요? UTF-16 인코딩일까요?
13776정성태10/19/2024613C/C++: 180. C++ - 고수준 FILE I/O 함수에서의 Unicode stream 모드(_O_WTEXT, _O_U16TEXT, _O_U8TEXT)파일 다운로드1
13775정성태10/19/2024639개발 환경 구성: 728. 윈도우 환경의 개발자를 위한 UTF-8 환경 설정
13774정성태10/18/2024616Linux: 91. Container 환경에서 출력하는 eBPF bpf_get_current_pid_tgid의 pid가 존재하지 않는 이유
13773정성태10/18/2024561Linux: 90. pid 네임스페이스 구성으로 본 WSL 2 + docker-desktop
13772정성태10/17/2024640Linux: 89. pid 네임스페이스 구성으로 본 WSL 2 배포본의 계층 관계
13771정성태10/17/2024833Linux: 88. WSL 2 리눅스 배포본 내에서의 pid 네임스페이스 구성
13770정성태10/17/2024593Linux: 87. ps + grep 조합에서 grep 명령어를 사용한 프로세스를 출력에서 제거하는 방법
13769정성태10/15/2024608Linux: 86. Golang + bpf2go를 사용한 eBPF 기본 예제파일 다운로드1
13768정성태10/15/2024621C/C++: 179. C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드파일 다운로드2
13767정성태10/14/2024706오류 유형: 929. bpftrace 수행 시 "ERROR: Could not resolve symbol: /proc/self/exe:BEGIN_trigger"
13766정성태10/14/2024756C/C++: 178. C++ - 파일에 대한 Text 모드의 "translated" 동작파일 다운로드1
13765정성태10/12/2024765오류 유형: 928. go build 시 "package maps is not in GOROOT" 오류
13764정성태10/11/2024717Linux: 85. Ubuntu - 원하는 golang 버전 설치
13763정성태10/11/2024770Linux: 84. WSL / Ubuntu 20.04 - bpftool 설치
13762정성태10/11/2024803Linux: 83. WSL / Ubuntu 22.04 - bpftool 설치
13761정성태10/11/2024737오류 유형: 927. WSL / Ubuntu - /usr/include/linux/types.h:5:10: fatal error: 'asm/types.h' file not found
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...