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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  114  115  116  [117]  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11000정성태7/16/201620555오류 유형: 342. Microsoft Visual Studio 2010 Tools for Office Runtime (x86 and x64) 설치 시 오류
10999정성태7/16/201622021오류 유형: 341. .NET Framework 4.5.2가 설치 안 되는 경우
10998정성태7/16/201621842.NET Framework: 598. C# - Excel 시트에 윈도우 폼 기능을 추가하는 방법 [1]파일 다운로드1
10997정성태7/16/201621188오류 유형: 340. HTTP Error 500.23 - Internal Server Error파일 다운로드1
10996정성태7/14/201626755Windows: 118. 유선 접속 상태에서 재부팅하면 무선 연결이 자동 연결 안되는 문제 [4]파일 다운로드1
10995정성태6/27/201620926VS.NET IDE: 109. Visual Studio 유료 버전 사용자의 주기적인 온라인 인증을 없애는 방법
10994정성태6/23/201620331개발 환경 구성: 285. 알고스팟(https://algospot.com)을 위한 Visual C++ 답안 작성 요령파일 다운로드1
10993정성태6/23/201621122.NET Framework: 597. 닷넷 메타데이터에 struct/class(값/참조 형식)의 구분이 있을까요?
10992정성태6/13/201618280오류 유형: 339. vbs 스크립트 실행 시 항상 실행 여부를 묻는 질문 창이 뜬다면?
10991정성태6/13/201622555오류 유형: 338. octave-gui 실행 시 "octave-gui.exe has stopped working" 오류
10990정성태6/13/201624113오류 유형: 337. missing type specifier - [type] assumed. Note: C++ does not support default-[type]
10989정성태6/7/201620589.NET Framework: 596. C# - WCF wsDualHttpBinding의 ClientBaseAddress 속성 - 두 번째 이야기
10988정성태6/3/201621550기타: 57. Outlook blocked access to the following potentially unsafe attachments
10987정성태6/2/201622600.NET Framework: 595. XLL 파일에 포함된 .NET 어셈블리를 추출하는 방법
10986정성태6/1/201623046.NET Framework: 594. C# - WCF wsDualHttpBinding의 ClientBaseAddress 속성
10985정성태6/1/201621596오류 유형: 336. An error occurred while ejecting 'DVD RW drive ...'
10984정성태5/31/201627290.NET Framework: 593. C# - wsDualHttpBinding WCF 예제 프로그램파일 다운로드1
10983정성태5/30/201621449VC++: 97. C++ 템플릿 remove_pointer, enable_if, is_pointer 사용 예제파일 다운로드1
10982정성태5/26/201619765오류 유형: 335. SQL Server Management Studio - The database ... is not accessible.
10981정성태5/24/201624781.NET Framework: 592. C# - Lights Out 퍼즐 풀기 [2]파일 다운로드1
10980정성태5/24/201622028VS.NET IDE: 108. Visual Studio 2013/2015를 위한 "Macros for Visual Studio"
10979정성태5/23/201625268.NET Framework: 591. C# - 조합(Combination) 예제 코드 - 두 번째 이야기파일 다운로드1
10978정성태5/23/201623910.NET Framework: 590. C# - 모든 경우의 수를 조합하는 코드 (2)파일 다운로드1
10977정성태5/23/201628377.NET Framework: 589. C# - 모든 경우의 수를 조합하는 코드 (1)파일 다운로드1
10976정성태5/20/201622802Math: 18. C# - 오일러 공식을 이용한 복소수 값의 라디안 회전파일 다운로드1
10975정성태5/20/201623216Math: 17. C# - 복소수 타입의 승수를 지원하는 Power 메서드파일 다운로드1
... 106  107  108  109  110  111  112  113  114  115  116  [117]  118  119  120  ...