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

비밀번호

댓글 작성자
 




... 31  32  [33]  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
13112정성태7/30/202217586.NET Framework: 2037. C# 11 - 목록 패턴(List patterns) [1]파일 다운로드1
13111정성태7/29/202216995.NET Framework: 2036. C# 11 - IntPtr/UIntPtr과 nint/nuint의 통합파일 다운로드1
13110정성태7/27/202216765.NET Framework: 2035. C# 11 - 새로운 연산자 ">>>" (Unsigned Right Shift)파일 다운로드1
13109정성태7/27/202218280VS.NET IDE: 177. 비주얼 스튜디오 2022를 이용한 (소스 코드가 없는) 닷넷 모듈 디버깅 - "외부 원본(External Sources)" [1]
13108정성태7/26/202215685Linux: 53. container에 실행 중인 Golang 프로세스를 디버깅하는 방법 [1]
13107정성태7/25/202214506Linux: 52. Debian/Ubuntu 계열의 docker container에서 자주 설치하게 되는 명령어
13106정성태7/24/202214089오류 유형: 819. 닷넷 6 프로젝트의 "Conditional compilation symbols" 기본값 오류
13105정성태7/23/202216493.NET Framework: 2034. .NET Core/5+ 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 - 두 번째 이야기 [1]
13104정성태7/23/202220205Linux: 51. WSL - init에서 systemd로 전환하는 방법
13103정성태7/22/202215554오류 유형: 818. WSL - systemd-genie와 관련한 2가지(systemd-remount-fs.service, multipathd.socket) 에러
13102정성태7/19/202215439.NET Framework: 2033. .NET Core/5+에서는 구할 수 없는 HttpRuntime.AppDomainAppId
13101정성태7/15/202228566도서: 시작하세요! C# 10 프로그래밍
13100정성태7/15/202217225.NET Framework: 2032. C# 11 - shift 연산자 재정의에 대한 제약 완화 (Relaxing Shift Operator)
13099정성태7/14/202216737.NET Framework: 2031. C# 11 - 사용자 정의 checked 연산자파일 다운로드1
13098정성태7/13/202214357개발 환경 구성: 647. Azure - scale-out 상태의 App Service에서 특정 인스턴스에 요청을 보내는 방법 [1]
13097정성태7/12/202213405오류 유형: 817. Golang - binary.Read: invalid type int32
13096정성태7/8/202217082.NET Framework: 2030. C# 11 - UTF-8 문자열 리터럴
13095정성태7/7/202214516Windows: 208. AD 도메인에 참여하지 않은 컴퓨터에서 Kerberos 인증을 사용하는 방법
13094정성태7/6/202214177오류 유형: 816. Golang - "short write" 오류 원인
13093정성태7/5/202214950.NET Framework: 2029. C# - HttpWebRequest로 localhost 접속 시 2초 이상 지연
13092정성태7/3/202216559.NET Framework: 2028. C# - HttpWebRequest의 POST 동작 방식파일 다운로드1
13091정성태7/3/202215156.NET Framework: 2027. C# - IPv4, IPv6를 모두 지원하는 서버 소켓 생성 방법
13090정성태6/29/202214337오류 유형: 815. PyPI에 업로드한 패키지가 반영이 안 되는 경우
13089정성태6/28/202215020개발 환경 구성: 646. HOSTS 파일 변경 시 Edge 브라우저에 반영하는 방법
13088정성태6/27/202213442개발 환경 구성: 645. "Developer Command Prompt for VS 2022" 명령행 환경의 폰트를 바꾸는 방법
13087정성태6/23/202217442스크립트: 41. 파이썬 - FastAPI / uvicorn 호스팅 환경에서 asyncio 사용하는 방법 [1]
... 31  32  [33]  34  35  36  37  38  39  40  41  42  43  44  45  ...