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

비밀번호

댓글 작성자
 




... 91  92  93  [94]  95  96  97  98  99  100  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11584정성태7/5/201818305Math: 35. GeoGebra 기하 (12) - 삼각형의 내심과 내접하는 원파일 다운로드1
11583정성태7/5/201818151.NET Framework: 785. public으로 노출되지 않은 다른 어셈블리의 delegate 인스턴스를 Reflection으로 생성하는 방법파일 다운로드1
11582정성태7/5/201824728.NET Framework: 784. C# - 제네릭 인자를 가진 타입을 생성하는 방법 [1]파일 다운로드1
11581정성태7/4/201821426Math: 34. GeoGebra 기하 (11) - 3대 작도 불능 문제의 하나인 임의 각의 3등분파일 다운로드1
11580정성태7/4/201818258Math: 33. GeoGebra 기하 (10) - 직각의 3등분파일 다운로드1
11579정성태7/4/201817290Math: 32. GeoGebra 기하 (9) - 임의의 선분을 한 변으로 갖는 정삼각형파일 다운로드1
11578정성태7/3/201817435Math: 31. GeoGebra 기하 (8) - 호(Arc)의 이등분파일 다운로드1
11577정성태7/3/201817400Math: 30. GeoGebra 기하 (7) - 각의 이등분파일 다운로드1
11576정성태7/3/201819594Math: 29. GeoGebra 기하 (6) - 대수의 4칙 연산파일 다운로드1
11575정성태7/2/201820017Math: 28. GeoGebra 기하 (5) - 선분을 n 등분하는 방법파일 다운로드1
11574정성태7/2/201818542Math: 27. GeoGebra 기하 (4) - 선분을 n 배 늘이는 방법파일 다운로드1
11573정성태7/2/201817879Math: 26. GeoGebra 기하 (3) - 평행선
11572정성태7/1/201817176.NET Framework: 783. C# 컴파일러가 허용하지 않는 (유효한) 코드를 컴파일해 테스트하는 방법
11571정성태7/1/201818650.NET Framework: 782. C# - JIRA에 등록된 Project의 Version 항목 추가하는 방법파일 다운로드1
11570정성태7/1/201818853Math: 25. GeoGebra 기하 (2) - 임의의 선분과 특정 점을 지나는 수직선파일 다운로드1
11569정성태7/1/201818060Math: 24. GeoGebra 기하 (1) - 수직 이등분선파일 다운로드1
11568정성태7/1/201830265Math: 23. GeoGebra 기하 - 컴퍼스와 자를 이용한 작도 프로그램 [1]
11567정성태6/28/201819580.NET Framework: 781. C# - OpenCvSharp 사용 시 포인터를 이용한 속도 향상파일 다운로드1
11566정성태6/28/201825242.NET Framework: 780. C# - JIRA REST API 사용 정리 (1) Basic 인증 [4]파일 다운로드1
11565정성태6/28/201822097.NET Framework: 779. C# 7.3에서 enum을 boxing 없이 int로 변환하기 - 세 번째 이야기파일 다운로드1
11564정성태6/27/201820584.NET Framework: 778. (Unity가 사용하는) 모노 런타임의 __makeref 오류
11563정성태6/27/201819400개발 환경 구성: 386. .NET Framework Native compiler 프리뷰 버전 사용법 [2]
11562정성태6/26/201818839개발 환경 구성: 385. 레지스트리에 등록된 원격지 스크립트 COM 객체 실행 방법
11561정성태6/26/201830143.NET Framework: 777. UI 요소의 접근은 반드시 그 UI를 만든 스레드에서! [8]파일 다운로드1
11560정성태6/25/201821467.NET Framework: 776. C# 7.3 - 초기화 식에서 변수 사용 가능(expression variables in initializers)파일 다운로드1
11559정성태6/25/201828644개발 환경 구성: 384. 영문 설정의 Windows 10 명령행 창(cmd.exe)의 한글 지원 [6]
... 91  92  93  [94]  95  96  97  98  99  100  101  102  103  104  105  ...