Microsoft MVP성태의 닷넷 이야기
.NET Framework: 186. windbg로 확인하는 .NET CLR LCG 메서드(DynamicMethod) [링크 복사], [링크+제목 복사],
조회: 19293
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
windbg로 확인하는 .NET CLR LCG 메서드(DynamicMethod)

지난번 글에 이어서.

windbg로 확인하는 .NET CLR 메서드
; https://www.sysnet.pe.kr/2/0/940

그럼, 동적으로 생성되는 Dynamic 메서드는 어떻게 확인이 될까요?

예제 코드 먼저 만들어야겠지요. (아래의 실습은 .NET 3.5 x64 환경에서 행해졌습니다.)

static void Main(string[] args)
{
    DynamicMethod dynamicMethod = CreateTestMethod(typeof(Program), "Test");
            
    dynamicMethod.Invoke(null, null);
    Console.ReadLine();
}
        
private static DynamicMethod CreateTestMethod(Type type, string name)
{
    DynamicMethod dynamicMethod =
    new DynamicMethod(
        name, MethodAttributes.Static | MethodAttributes.Public,
        CallingConventions.Standard, typeof(void), Type.EmptyTypes, type, false );

    ILGenerator gen = dynamicMethod.GetILGenerator();
    gen.EmitWriteLine(type.Name + "." + name);
    gen.Emit(OpCodes.Ret);

    dynamicMethod.CreateDelegate(typeof(Action));
    return dynamicMethod;
}

windbg로 연결해 보면, 일단 어려운 것이 기존 MethodDesc 테이블에는 이 항목이 추가되지 않는다는 점입니다. 사실 동적으로 생성된 "Test" 메서드를 찾아갈 방법도 없기 때문에 아래와 같이 "Main" 메서드를 기준으로 MethodDesc 테이블을 확인할 수밖에 없습니다.

.loadby sos mscorwks

0:003> !name2ee ConsoleApplication1.exe!ConsoleApplication1.Program.Main
Module: 000007ff000333d0 (ConsoleApplication1.exe)
Token: 0x0000000006000001
MethodDesc: 000007ff00033988
Name: ConsoleApplication1.Program.Main(System.String[])
JITTED Code Address: 000007ff00180120

0:003> !dumpmd 000007ff00033988
Method Name: ConsoleApplication1.Program.Main(System.String[])
Class: 000007ff00172218
MethodTable: 000007ff000339c0
mdToken: 06000001
Module: 000007ff000333d0
IsJitted: yes
CodeAddr: 000007ff00180120

0:003> !dumpmt -md 000007ff000339c0
EEClass: 000007ff00172218
Module: 000007ff000333d0
Name: ConsoleApplication1.Program
mdToken: 02000002  (D:\...[경로생략]...\ConsoleApplication1.exe)
BaseSize: 0x18
ComponentSize: 0x0
Number of IFaces in IFaceMap: 0
Slots in VTable: 8
--------------------------------------
MethodDesc Table
           Entry       MethodDesc      JIT Name
000007fef0a4abe0 000007fef07ce828   PreJIT System.Object.ToString()
000007fef0a52560 000007fef07ce830   PreJIT System.Object.Equals(System.Object)
000007fef0a4bc70 000007fef07ce870   PreJIT System.Object.GetHashCode()
000007fef0afe5f0 000007fef07ce8a0   PreJIT System.Object.Finalize()
000007ff0003c038 000007ff000339b8     NONE ConsoleApplication1.Program..ctor()
000007ff00180120 000007ff00033988      JIT ConsoleApplication1.Program.Main(System.String[])
000007ff001801e0 000007ff00033998      JIT ConsoleApplication1.Program.CreateTestMethod(System.Type, System.String)
000007ff001804a0 000007ff000339a8      JIT ConsoleApplication1.Program.ShowMethodDesc(System.Reflection.Emit.DynamicMethod)

보시는 것처럼 Program 타입에는 LCG 메서드가 없습니다. 아쉽지만, DynamicMethod를 찾을 수 있는 명확한 방법이 없습니다. 그나마 찾을 수 있었던 방법이 있는데,

Executing dynamic IL with DynamicMethod
; http://www.josebonnin.com/post/2008/08/23/Executing-dynamic-IL-with-DynamicMethod.aspx

위의 방법을 이번 예제에 적용해 보면 다음과 같이 찾아들어갈 수 있습니다.

0:003> !DumpHeap -stat 
total 6210 objects
Statistics:
              MT    Count    TotalSize Class Name
000007fef0bde5d0        1           24 System.IO.TextReader+NullTextReader
000007fef0bde0a0        1           24 System.Collections.Generic.GenericEqualityComparer`1[[System.String, mscorlib]]
...[생략]...
000007fef0b98520        1          104 System.Threading.Thread
000007fef0bb3588        1          112 System.Reflection.Emit.DynamicMethod
...[생략]...
000007fef0b9fac0       62       126024 System.Byte[]
000007fef0b85870     1361       149296 System.Object[]
000007fef0b97a80      903       154344 System.String
Total 6210 objects

// 위의 출력결과가 너무 많기 때문에,
// 다음과 같이 필터링하는 방법이 제공됩니다.

0:003> .shell -ci "!dumpheap -stat" findstr DynamicMethod
000007fef0bb38d8        1           56 System.Reflection.Emit.DynamicMethod+RTDynamicMethod
000007fef0bb3588        1          112 System.Reflection.Emit.DynamicMethod
.shell: Process exited


0:003> !DumpHeap -mt 000007fef0bb3588 
         Address               MT     Size
00000000027c63f0 000007fef0bb3588      112     
... [프로그램에서 생성한 DynamicMethod 목록이 여기에 출력됨]...
total 1 objects
Statistics:
              MT    Count    TotalSize Class Name
000007fef0bb3588        1          112 System.Reflection.Emit.DynamicMethod
Total 1 objects

0:003> !DumpIL 00000000027c63f0
This is dynamic IL. Exception info is not reported at this time.
If a token is unresolved, run "!do <addr>" on the addr given
in parenthesis. You can also look at the token table yourself, by
running "!DumpArray 00000000027c99a0".

IL_0000: ldstr 70000002 "Program.Test"
IL_0005: call 6000003 System.Console.WriteLine(System.String)
IL_000a: ret 

그런데, 현실 세계의 프로그램에서 저렇게 간단하게 하나만 정의하는 프로젝트가 몇 개나 되겠습니까? "!DumpHeap -mt ..."로 출력된 Address 값들을 일일이 하나씩 DumpIL로 출력해 봐야만 알 수 있다는 것이니,,, 아쉬운 데로 이번에는 여기까지!




LCG 메서드가 MethodDesc 테이블에 등록되어 있지 않다고 해서 MethodDesc 자료구조가 없다는 것은 아닙니다. 위에서 알아본 것처럼 DynamicMethod 타입의 힙에 제공이 되고 있으며, 이 값은 Reflection을 이용해서 알아보는 것이 가능합니다.

static void ShowMethodDesc(DynamicMethod dynamicMethod)
{
    // RuntimeMethodHandle methodHandle = dynamicMethod.MethodHandle; // 예외 발생

    FieldInfo fieldInfo = typeof(DynamicMethod).GetField("m_method", BindingFlags.NonPublic | BindingFlags.Instance);
    RuntimeMethodHandle methodHandle = ((RuntimeMethodHandle)fieldInfo.GetValue(dynamicMethod));

    Console.WriteLine("[" + dynamicMethod.Name + "]");
    Console.WriteLine("MethodHandle == 0x" + methodHandle.Value.ToString("x"));

    IntPtr pAddress = methodHandle.GetFunctionPointer();
    Console.WriteLine("Stub or Jitted Address == 0x" + pAddress.ToString("x"));
    Console.WriteLine();
}

여기서도 아쉬운 점이 있는데요. DynamicMethod의 경우에는 일반 메서드에서처럼 MethodHandle 값을 직접 구하려고 시도하면 예외가 발생합니다. 대신 내부의 private에 저장된 m_method 필드를 액세스해서 그 값을 구해오는 방식을 사용해야 합니다.

일단, MethodHandle 값을 얻어오면 나머지는 이전 글에서 했던 것과 동일하게 JIT 컴파일 이전/이후에 대해서 GetFunctionPointer의 값이 달라지는 것을 확인할 수 있습니다. 게다가 methodHandle.Value 값으로 windbg에서 "!dumpmd [methodHandle.Value로 얻은 값]" 명령어를 내리게 되면 동일하게 다음과 같은 식으로 출력이 됩니다.

0:003> !dumpmd 0x7ff00054bf0
Method Name: DynamicClass.Test()
Class: 000007ff00054ad8
MethodTable: 000007ff00054b80
mdToken: 06000000
Module: 000007ff000533d0
IsJitted: yes
CodeAddr: 000007ff001e0130  // 이 값이 methodHandle.GetFunctionPointer();

0:003> !dumpmt -md 000007ff00054b80
EEClass: 000007ff00054ad8
Module: 000007ff000533d0
Name: 
mdToken: 02000000  (D:\...[경로 생략]...\ConsoleApplication1.exe)
BaseSize: 0x10
ComponentSize: 0x0
Number of IFaces in IFaceMap: 0
Slots in VTable: 0
--------------------------------------
MethodDesc Table
           Entry       MethodDesc      JIT Name   // 보는 것처럼, MethodDesc 테이블은 비어 있음

계속 아쉬운 이야기만 하게 되는데요. ^^;

.NET 4.0에서는 m_method마저 없어져버려서 다른 방법을 찾아야만 했습니다. .NET Reflector로 보면, 다행히 "internal RuntimeMethodHandle GetMethodDescriptor()" 메서드가 제공되어 다음과 같이 구하는 것이 가능했습니다.

RuntimeMethodHandle methodHandle;

if (Environment.Version.Major == 4)
{
    MethodInfo getMethodDescriptorInfo = typeof(DynamicMethod).GetMethod("GetMethodDescriptor", 
            BindingFlags.NonPublic | BindingFlags.Instance);
    methodHandle = (RuntimeMethodHandle)getMethodDescriptorInfo.Invoke(dynamicMethod, null);
}

끝!
[연관 글]






[최초 등록일: ]
[최종 수정일: 6/23/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2011-06-23 10시06분
Saving Dynamic Assembly in .NET 4.0 using Windbg
; http://naveensrinivasan.com/2010/12/23/saving-dynamic-assembly-in-net-4-0-using-windbg/

참고로, 이제는 PSSCOR4가 나왔기 때문에 .NET 4.0 응용 프로그램에 대해서 !dumpdynamicassembly 명령어를 사용할 수 있게 되었습니다. ^^
정성태

1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13439정성태11/10/20233100닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232669닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232852닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20233106닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20233003닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232781스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232470스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232551오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232932스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232764닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233052닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233153닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233340닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233490스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233256닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233233스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233391닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233477닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235796스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233286스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233999닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233527닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233299오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233802닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233580디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233776닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...