Microsoft MVP성태의 닷넷 이야기
.NET Framework: 186. windbg로 확인하는 .NET CLR LCG 메서드(DynamicMethod) [링크 복사], [링크+제목 복사]
조회: 19234
글쓴 사람
정성태 (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)
13602정성태4/20/2024219닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024252닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024298닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024413닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024425닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024489닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024837닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024974닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241030닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241051닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241209C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241169닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241073Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241143닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241197닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241157오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241304Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241096Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241050개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241158Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241421Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241589개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241138닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241494오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241631닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...