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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  [51]  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12363정성태10/11/202012702.NET Framework: 947. C# 9.0 - (1) 대상으로 형식화된 new 식(Target-typed new expressions) [2]파일 다운로드1
12362정성태10/11/20209516VS.NET IDE: 151. Visual Studio 2019에 .NET 5 rc/preview 적용하는 방법
12361정성태10/11/202011118.NET Framework: 946. C# 9.0을 위한 개발 환경 구성
12360정성태10/8/20208339오류 유형: 666. The type or namespace name '...' does not exist in the namespace 'Microsoft.VisualStudio.TestTools' (are you missing an assembly reference?)
12359정성태10/7/20209848오류 유형: 665. Windows - 재부팅 후 iSCSI 연결이 끊기는 문제
12358정성태10/7/20209890오류 유형: 664. Web Deploy 설치 시 "A newer version of Microsoft Web Deploy 3.6 was found on this machine." 오류 [3]
12357정성태10/7/20207950오류 유형: 663. 이벤트 로그 - The storage optimizer couldn't complete retrim on New Volume
12356정성태10/7/202022884오류 유형: 662. ASP.NET Core와 500.19, 500.21 오류 (0x8007000d)
12355정성태10/3/20208046오류 유형: 661. Hyper-V Linux VM의 Internal 유형의 가상 Switch에 대한 IP 연결이 되지 않는 경우
12354정성태10/2/202020968오류 유형: 660. Web Deploy (msdeploy.axd) 실행 시 오류 기록 [1]
12353정성태10/2/202010759개발 환경 구성: 518. 비주얼 스튜디오에서 IIS 웹 서버로 "Web Deploy"를 이용해 배포하는 방법
12352정성태10/2/202011234개발 환경 구성: 517. Hyper-V Internal 네트워크에 NAT을 이용한 인터넷 연결 제공
12351정성태10/2/202010785오류 유형: 659. Nox 실행이 안 되는 경우 - Unable to bind to the underlying transport for ...
12350정성태9/25/202014269Windows: 175. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 [2]파일 다운로드1
12349정성태9/25/20209157Linux: 32. Ubuntu 20.04 - docker를 위한 tcp 바인딩 추가
12348정성태9/25/20209891오류 유형: 658. 리눅스 docker - Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
12347정성태9/25/202024050Windows: 174. WSL 2의 네트워크 통신 방법 [4]
12346정성태9/25/20209146오류 유형: 657. IIS - http://localhost 방문 시 Service Unavailable 503 오류 발생
12345정성태9/25/20208835오류 유형: 656. iisreset 실행 시 "Restart attempt failed." 오류가 발생하지만 웹 서비스는 정상적인 경우파일 다운로드1
12344정성태9/25/202010002Windows: 173. 서비스 관리자에 "IIS Admin Service"가 등록되어 있지 않다면?
12343정성태9/24/202019666.NET Framework: 945. C# - 닷넷 응용 프로그램에서 메모리 누수가 발생할 수 있는 패턴 [5]
12342정성태9/24/202010927디버깅 기술: 171. windbg - 인스턴스가 살아 있어 메모리 누수가 발생하고 있는지 확인하는 방법
12341정성태9/23/202010021.NET Framework: 944. C# - 인스턴스가 살아 있어 메모리 누수가 발생하고 있는지 확인하는 방법파일 다운로드1
12340정성태9/23/20209764.NET Framework: 943. WPF - WindowsFormsHost를 담은 윈도우 생성 시 메모리 누수
12339정성태9/21/20209774오류 유형: 655. 코어 모드의 윈도우는 GUI 모드의 윈도우로 교체가 안 됩니다.
12338정성태9/21/20209315오류 유형: 654. 우분투 설치 시 "CHS: Error 2001 reading sector ..." 오류 발생
... 46  47  48  49  50  [51]  52  53  54  55  56  57  58  59  60  ...