Microsoft MVP성태의 닷넷 이야기
.NET Framework: 186. windbg로 확인하는 .NET CLR LCG 메서드(DynamicMethod) [링크 복사], [링크+제목 복사],
조회: 19285
글쓴 사람
정성태 (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)
13514정성태1/5/20242296개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242222닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242172개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242194닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242120닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242168오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242215오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242861닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232449닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232977닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232567닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232433Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232545닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232320개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232409디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233095닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232492오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232478Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232412Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232579Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232700닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232375개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232267Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232399개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232175개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232109오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...