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)
13430정성태10/30/20232666닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232940닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233011닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233198닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233359스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233169닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233147스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233284닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233334닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235497스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233163스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233854닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233406닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233206오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233699닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233470디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233667닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236945닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233445Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20234963닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233819닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233800Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233556닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233520VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20233967닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233477오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...