Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 6개 있습니다.)
개발 환경 구성: 300. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법
; https://www.sysnet.pe.kr/2/0/11052

.NET Framework: 828. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/11884

개발 환경 구성: 466. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 세 번째 이야기
; https://www.sysnet.pe.kr/2/0/12118

.NET Framework: 878. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 네 번째 이야기(IL 코드로 직접 구현)
; https://www.sysnet.pe.kr/2/0/12120

.NET Framework: 880. C# - PE 파일로부터 IMAGE_COR20_HEADER 및 VTableFixups 테이블 분석
; https://www.sysnet.pe.kr/2/0/12126

.NET Framework: 881. C# DLL에서 제공하는 Win32 export 함수의 내부 동작 방식(VT Fix up Table)
; https://www.sysnet.pe.kr/2/0/12127




C# - PE 파일로부터 IMAGE_COR20_HEADER 및 VTableFixups 테이블 분석

예전에 만들어 놓은,

C# - 로딩된 Native DLL의 export 함수 목록 출력
; https://www.sysnet.pe.kr/2/0/12093

PEImage 라이브러리에 .NET 모듈인 경우 담고 있는 IMAGE_COR20_HEADER에 대해 분석을 확장해 보겠습니다. 지난 글에서 CLRRuntimeHeader를 구했으니 그로부터 IMAGE_COR20_HEADER를,

[StructLayout(LayoutKind.Sequential)]
public struct IMAGE_COR20_HEADER
{
    public uint cb;
    public ushort MajorRuntimeVersion;
    public ushort MinorRuntimeVersion;     // Symbol table and startup information     
    public IMAGE_DATA_DIRECTORY MetaData;
    public uint Flags;
    public uint EntryPointToken;     // Binding information  
    public IMAGE_DATA_DIRECTORY Resources;
    public IMAGE_DATA_DIRECTORY StrongNameSignature;     // Regular fixup and binding information     
    public IMAGE_DATA_DIRECTORY CodeManagerTable;
    public IMAGE_DATA_DIRECTORY VTableFixups;
    public IMAGE_DATA_DIRECTORY ExportAddressTableJumps;
    public IMAGE_DATA_DIRECTORY ManagedNativeHeader;

    public int RuntimeVersion
    {
        get { return this.MajorRuntimeVersion << 16 | this.MinorRuntimeVersion; }
    }
}

구하는 메서드를 다음과 같이 PEImage 타입에 추가할 수 있습니다.

public IMAGE_COR20_HEADER GetClrDirectoryHeader()
{
    if (CLRRuntimeHeaderDirectory.VirtualAddress == 0)
    {
        return default;
    }

    return Read<IMAGE_COR20_HEADER>(CLRRuntimeHeaderDirectory.VirtualAddress);
}

위의 코드를 적용해 Nuget에 올렸으니 다음과 같은 정도로 사용하면 됩니다.

// Install-Package WindowsPE -Version 1.1.4

PEImage img = PEImage.FromLoadedModule("ClassLibrary1.dll");
IMAGE_COR20_HEADER corHeader = img.GetClrDirectoryHeader();
Console.WriteLine($"RuntimeVersion: {corHeader.RuntimeVersion:x}");




기왕 해보는 김에 지난 글에 썼던,

C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 네 번째 이야기(IL 코드로 직접 구현)
; https://www.sysnet.pe.kr/2/0/12120

내용 중에 "VT Fix up Table"을,

["Figure 18-3. Indirect referencing of v-table entries from the EAT" - 출처: https://books.google.co.kr/books?id=Xv_0AwAAQBAJ&pg=P9A353]

il_export_1.png

읽는 코드를 작성해 보겠습니다. 이미 설명한 데로 "VT Fix up Table"은 ".vtfixup"을 정의할 때마다 생성됩니다. 그리고 해당 테이블은 다음과 같은 구조로 정의되어 있어,

[Flags]
public enum CorVtableDefines : ushort
{
    // V-table constants
    COR_VTABLE_32BIT = 0x01,          // V-table slots are 32-bits in size.
    COR_VTABLE_64BIT = 0x02,          // V-table slots are 64-bits in size.
    COR_VTABLE_FROM_UNMANAGED = 0x04,          // If set, transition from unmanaged.
    COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN = 0x08,  // If set, transition from unmanaged with keeping the current appdomain.
    COR_VTABLE_CALL_MOST_DERIVED = 0x10,          // Call most derived method described by
}

// https://github.com/shuffle2/IDA-ClrNative/blob/master/ClrNativeLoader.py
[StructLayout(LayoutKind.Sequential)]
public struct VTableFixups
{
    public uint rva;
    public ushort Count;
    public CorVtableDefines Type;

    public bool Is64bit
    {
        get
        {
            return (Type & CorVtableDefines.COR_VTABLE_64BIT) == CorVtableDefines.COR_VTABLE_64BIT;
        }
    }

    public int GetItemSize()
    {
        return (Is64bit == true) ? sizeof(long) : sizeof(int);
    }

    public override string ToString()
    {
        return $"RVA: 0x{rva:x}, # of entries: {Count}, Type: 0x{Type:x}";
    }
}

배열로 읽어낼 수 있습니다.

// PEImage img = ...;
VTableFixups [] vtfs = img.Reads<VTableFixups>(corHeader.VTableFixups.VirtualAddress, corHeader.VTableFixups.Size);

foreach (var vtf in vtfs)
{
    Console.WriteLine(vtf + ", " + vtf.Type.ToString());
}

만약 DLL에서 export한 형식이 1개의 Table에 3개의 export 항목을 갖는 경우라면,

.vtfixup [3] int64 fromunmanaged at VT_01
.data VT_01 = int64(0)[3]

출력 결과는 다음과 같이 나옵니다.

RVA: 0x4000, # of entries: 3, Type: 0x0006, COR_VTABLE_64BIT, COR_VTABLE_FROM_UNMANAGED

반면, 3개의 Table에 각각 1개씩의 export 항목을 갖도록 정의한 경우라면,

.vtfixup [1] int32 fromunmanaged at VT_01
.data VT_01 = int32(0)

.vtfixup [1] int32 fromunmanaged at VT_02
.data VT_02 = int32(0)

.vtfixup [1] int32 fromunmanaged at VT_03
.data VT_03 = int32(0)

다음과 같은 출력 결과를 얻게 됩니다.

RVA: 0x4000, # of entries: 1, Type: 0x0006, COR_VTABLE_64BIT, COR_VTABLE_FROM_UNMANAGED
RVA: 0x4008, # of entries: 1, Type: 0x0006, COR_VTABLE_64BIT, COR_VTABLE_FROM_UNMANAGED
RVA: 0x4010, # of entries: 1, Type: 0x0006, COR_VTABLE_64BIT, COR_VTABLE_FROM_UNMANAGED

해당 VTableFixups 테이블의 RVA 값은 "Figure 18-3. Indirect referencing of v-table entries from the EAT" 그림에서 "VT Fix up Table"의 항목이 가리키고 있는 "V-Table"의 위치입니다. "V-Table"에 담긴 export 항목의 크기는 VTableFixups.Type 값이 COR_VTABLE_32BIT인 경우 4바이트, COR_VTABLE_64BIT인 경우 8바이트입니다.

따라서, "V-Table" 값도 다음과 같은 형식으로 읽어낼 수 있습니다.

foreach (var vtf in vtfs)
{
    Console.WriteLine(vtf + ", " + vtf.Type.ToString());

    for (int i = 0; i < vtf.Count; i ++)
    {
        int itemSize = vtf.GetItemSize(); // 4 == COR_VTABLE_32BIT, 8 == COR_VTABLE_64BIT
        uint itemPos = (uint)(vtf.rva + (i * itemSize));

        long vtableItem = (itemSize == 8) ? img.Read<long>(itemPos) : img.Read<int>(itemPos);
        Console.WriteLine($"\tVTable[{i}] {vtableItem:x}");
    }
}

역시 .vtfixup을 정의한 수에 따라 각각 다음과 같은 출력을 얻을 수 있습니다.

/*
.vtfixup [3] int64 fromunmanaged at VT_01
.data VT_01 = int64(0)[3]
*/

RVA: 0x4000, # of entries: 3, Type: 0x0006, COR_VTABLE_64BIT, COR_VTABLE_FROM_UNMANAGED
        VTable[0] 6000001
        VTable[1] 6000002
        VTable[2] 6000003

/*
.vtfixup [1] int32 fromunmanaged at VT_01
.data VT_01 = int32(0)

.vtfixup [1] int32 fromunmanaged at VT_02
.data VT_02 = int32(0)

.vtfixup [1] int32 fromunmanaged at VT_03
.data VT_03 = int32(0)
*/

RVA: 0x4000, # of entries: 1, Type: 0x0006, COR_VTABLE_64BIT, COR_VTABLE_FROM_UNMANAGED
        VTable[0] 6000001
RVA: 0x4008, # of entries: 1, Type: 0x0006, COR_VTABLE_64BIT, COR_VTABLE_FROM_UNMANAGED
        VTable[0] 6000002
RVA: 0x4010, # of entries: 1, Type: 0x0006, COR_VTABLE_64BIT, COR_VTABLE_FROM_UNMANAGED
        VTable[0] 6000003

출력된 결과를 보면 "V-Table"이 DLL 파일에서 담고 있는 값은 export시킨 .NET 메서드의 methodDef 토큰 값이기 때문에 4바이트만 유효합니다. 단지, 나중에 해당 DLL이 메모리에 로드될 때 생성되는 "Marshaling Thunks" 코드의 메모리 주소를 담는 것으로 바뀌기 때문에 플랫폼에 따라 4/8바이트 값을 갖게 되는 것입니다.

또한, 컴파일 시 고정되는 VTableFixups 테이블이 ".text" 섹션에 위치하는 것과는 달리 런타임 시에 "Marshaling Thunks" 값으로 바뀌어야 하는 V-Table은 ".sdata" 섹션의 위치하게 됩니다.

(첨부 파일은 이 글에서 실습한 예제 코드를 포함합니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/25/2020]

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)
13679정성태7/16/20247564Linux: 76. Linux - C++ (getaddrinfo 등을 담고 있는) libnss 정적 링크
13678정성태7/15/20248186VS.NET IDE: 191. Visual Studio 2022 - .NET 5 프로젝트를 Docker Support로 실행했을 때 오류
13677정성태7/15/20248587오류 유형: 916. MSBuild - CheckEolTargetFramework (warning NETSDK1138)
13676정성태7/14/20248319Linux: 75. gdb에서 glibc의 함수에 Breakpoint 걸기
13675정성태7/13/202410675C/C++: 166. C/C++ - DLL에서 template 함수를 export하는 방법 [1]파일 다운로드1
13674정성태7/13/20249226오류 유형: 915. Unhandled Exception: Microsoft.Diagnostics.NETCore.Client.ServerNotAvailableException: Unable to connect to Process
13673정성태7/11/20249938닷넷: 2275. C# 13 - (1) 신규 이스케이프 시퀀스 '\e'파일 다운로드1
13672정성태7/10/20247960닷넷: 2274. IIS - (프로세스 종료 없는) AppDomain Recycle
13671정성태7/10/20248284오류 유형: 914. Package ca-certificates is not installed.
13669정성태7/9/20248339오류 유형: 913. C# - AOT StaticExecutable 정적 링킹 시 빌드 오류
13668정성태7/8/20248643개발 환경 구성: 716. Hyper-V - Ubuntu 22.04 Generation 2 유형의 VM 설치
13667정성태7/7/20247226닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20249121Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20249421Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20248542닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20248332닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20248223Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20249029오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20248949개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20249682개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20248774닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20249509Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20249063닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20248748오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20248912닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/202410415닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...