Microsoft MVP성태의 닷넷 이야기
.NET Framework: 186. windbg로 확인하는 .NET CLR LCG 메서드(DynamicMethod) [링크 복사], [링크+제목 복사],
조회: 19292
글쓴 사람
정성태 (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)
13490정성태12/19/20232402개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232178개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232115오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232417개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232233개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232124오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232202개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232341닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20233028닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232322개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232719개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232377개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232634닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232322닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232419닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232235개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232513닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232251C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232363Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232688닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232457닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232354닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232457오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232622닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232362개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232496닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...