Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)
(시리즈 글이 9개 있습니다.)
.NET Framework: 216. 라이선스까지도 뛰어넘는 .NET Profiler
; https://www.sysnet.pe.kr/2/0/1046

.NET Framework: 336. .NET Profiler가 COM 개체일까?
; https://www.sysnet.pe.kr/2/0/1352

.NET Framework: 576. 기본적인 CLR Profiler 소스 코드 설명
; https://www.sysnet.pe.kr/2/0/10950

.NET Framework: 582. CLR Profiler - 별도 정의한 .NET 코드를 호출하도록 IL 코드 변경
; https://www.sysnet.pe.kr/2/0/10959

.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
; https://www.sysnet.pe.kr/2/0/11810

오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
; https://www.sysnet.pe.kr/2/0/12384

.NET Framework: 987. .NET Profiler - FunctionID와 연관된 ClassID를 구할 수 없는 문제
; https://www.sysnet.pe.kr/2/0/12465

.NET Framework: 1041. C# - AssemblyID, ModuleID를 관리 코드에서 구하는 방법
; https://www.sysnet.pe.kr/2/0/12605

닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
; https://www.sysnet.pe.kr/2/0/13576




CLR Profiler - 별도 정의한 .NET 코드를 호출하도록 IL 코드 변경

지난번에 기본적인 CLR Profiler를 소개했고,

기본적인 CLR Profiler 소스 코드 설명
; https://www.sysnet.pe.kr/2/0/10950

그중에서 ModuleLoadFinished 콜백 동작을 테스트해봤었습니다

CLR Profiler로 살펴보는 SharedDomain의 모듈 로드 동작
; https://www.sysnet.pe.kr/2/0/10951

이번엔 ModuleLoadFinished와 함께 JITCompilationStarted를 조합해서 원하는 닷넷 메서드에 대해 우리가 정의한 C# DLL의 메서드를 호출하는 코드를 끼워넣을 것입니다. 이렇게 하려면 다음의 2가지 절차를 따라야 합니다.

  1. ModuleLoadFinished 콜백: JIT 컴파일 단계에서 끼워넣을 외부 코드의 메타데이터 추가
  2. JITCompilationStarted 콜백: 기존 JIT 코드에 외부 DLL에 정의된 메서드 호출

순서에 따라, C# DLL을 다음과 같은 코드로 간단하게 정의해서 GAC에 등록합니다.

using System;
using System.Diagnostics;

[assembly: System.Security.SecurityCritical]
[assembly: System.Security.AllowPartiallyTrustedCallers]

namespace Intercept.Helper
{
    public class ManagedLayer
    {
        [System.Security.SecuritySafeCritical]
        public static void Enter()
        {
            StackFrame sf = new StackFrame(1);
            Console.WriteLine("[Profiler] " + sf.GetMethod().Name + " called");
        }
    }
}

/*
C:\WINDOWS\system32>gacutil /i C:\call_managed_profiler\Intercept.Helper\bin\Debug\Intercept.Helper.dll
Microsoft (R) .NET Global Assembly Cache Utility.  Version 4.0.30319.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Assembly successfully added to the cache
*/

그다음 공개키 토큰 값을 알아내서,

C:\WINDOWS\system32>sn -T C:\call_managed_profiler\Intercept.Helper\bin\Debug\Intercept.Helper.dll

Microsoft (R) .NET Framework Strong Name Utility  Version 4.0.30319.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Public key token is 20a5976064ab527b

이 값을 C++ Profiler 코드에 바이트 배열로 정의해 둡니다.

BYTE g_rgbPublicKeyToken[] = { 0x20, 0xa5, 0x97, 0x60, 0x64, 0xab, 0x52, 0x7b };

이제 다음과 같이 ModuleLoadFinished 콜백에서 우리가 만들어 두었던 C# 라이브러리인 Intercept.Helper.dll에 대한 참조를 추가합니다.

BYTE g_rgbPublicKeyToken[] = { 0x20, 0xa5, 0x97, 0x60, 0x64, 0xab, 0x52, 0x7b };

HRESULT CBasicClrProfiler::ModuleLoadFinished(ModuleID moduleId, HRESULT hrStatus)
{
    IMetaDataAssemblyEmit *pAssemblyEmit = nullptr;
    
    do
    {
        hr = m_pICorProfilerInfo2->GetModuleMetaData(moduleId, ofWrite, IID_IMetaDataAssemblyEmit, (LPUNKNOWN *)&pAssemblyEmit);
        if (hr != S_OK)
        {
            break;
        }

        WCHAR wszLocale[] = { L"neutral" };

        ASSEMBLYMETADATA assemblyMetaData;
        ZeroMemory(&assemblyMetaData, sizeof(assemblyMetaData));
        assemblyMetaData.usMajorVersion = 1;
        assemblyMetaData.usMinorVersion = 0;
        assemblyMetaData.usBuildNumber = 0;
        assemblyMetaData.usRevisionNumber = 0;
        assemblyMetaData.szLocale = wszLocale;
        assemblyMetaData.cbLocale = _countof(wszLocale);

        mdAssemblyRef assemblyRef = NULL;
        hr = pAssemblyEmit->DefineAssemblyRef(
            (void *)g_rgbPublicKeyToken, sizeof(g_rgbPublicKeyToken),
            L"Intercept.Helper", &assemblyMetaData, NULL, NULL, 0, &assemblyRef);
        if (hr != S_OK)
        {
            break;
        }

    } while (false);

    if (pAssemblyEmit != nullptr)
    {
        pAssemblyEmit->Release();
    }
}

그런데, DLL 참조만 추가해서는 안됩니다. 해당 DLL에 정의된 ManagedLayer 타입을 사용할 것이기 때문에 그에 대한 참조를 추가해줘야 합니다.

HRESULT CBasicClrProfiler::ModuleLoadFinished(ModuleID moduleId, HRESULT hrStatus)
{
    IMetaDataAssemblyEmit *pAssemblyEmit = nullptr;
    IMetaDataEmit *pEmit = nullptr;

    do
    {
        // ...[생략]...

        hr = m_pICorProfilerInfo2->GetModuleMetaData(moduleId, ofWrite, IID_IMetaDataEmit, (LPUNKNOWN *)&pEmit);
        if (hr != S_OK)
        {
            break;
        }

        // ...[생략]...

        mdTypeRef typeRef = mdTokenNil;
        hr = pEmit->DefineTypeRefByName(assemblyRef, L"Intercept.Helper.ManagedLayer", &typeRef);
        if (hr != S_OK)
        {
            break;
        }

    } while (false);

    if (pAssemblyEmit != nullptr)
    {
        pAssemblyEmit->Release();
    }

    if (pAssemblyEmit != nullptr)
    {
        pAssemblyEmit->Release();
    }
}

그래도 한 가지 남았군요. ^^ ManagedLayer 타입의 Enter 메서드를 호출할 것이므로 이에 대한 참조도 추가해야 합니다.

HRESULT CBasicClrProfiler::ModuleLoadFinished(ModuleID moduleId, HRESULT hrStatus)
{
    IMetaDataAssemblyEmit *pAssemblyEmit = nullptr;
    IMetaDataEmit *pEmit = nullptr;

    do
    {
        // ...[생략]...

        COR_SIGNATURE sigFunctionProbe[] = {
            IMAGE_CEE_CS_CALLCONV_DEFAULT,      // default calling convention
            0x0,                                // number of arguments == 0
            ELEMENT_TYPE_VOID,                  // return type == void
        };

        mdToken mdEnterProbeRef;
        hr = pEmit->DefineMemberRef(typeRef, L"Enter",
            sigFunctionProbe, sizeof(sigFunctionProbe), &mdEnterProbeRef);
        if (hr != S_OK)
        {
            break;
        }

    } while (false);

    // ...[생략]...
}

이것으로 참조 작업은 모두 끝났는데, 아직 여분의 작업이 2가지 남았습니다. 먼저, 위의 작업의 마지막 결과물인 mdEnterProbeRef 값을 JITCompilationStarted 단계에서 쓸 수 있도록 보관해 놓는 작업입니다. 사실 JITCompilationStarted 단계에서도 참조된 값을 구할 수는 있지만 그 작업으로 인한 코드가 번거롭기 때문에 미리 값을 보존해 두는 것이 더 좋은 선택입니다. 따라서, 다음과 같은 부가적인 코드가 필요합니다.

// BasicClrProfiler.h 
#pragma once
#include "resource.h"       // main symbols

#include "SampleProfiler_i.h"

#include "ICorProfilerCallback3Impl.h"

struct ModuleInfo
{
    mdToken m_mdEnterProbeRef;
};

// ..[생략]...

class ATL_NO_VTABLE CBasicClrProfiler :
    // ..[생략]...
    public ICorProfilerCallback3Impl<CBasicClrProfiler>
{
public:
    CBasicClrProfiler()
    {
    }

DECLARE_REGISTRY_RESOURCEID(IDR_BASICCLRPROFILER)

BEGIN_COM_MAP(CBasicClrProfiler)
    COM_INTERFACE_ENTRY(IBasicClrProfiler)
    COM_INTERFACE_ENTRY(IDispatch)
    COM_INTERFACE_ENTRY(ICorProfilerCallback)
    COM_INTERFACE_ENTRY(ICorProfilerCallback2)
    COM_INTERFACE_ENTRY(ICorProfilerCallback3)
END_COM_MAP()

// ..[생략]...

    IDToInfoMap<ModuleID, ModuleInfo> m_moduleIDToInfoMap; // 구체적인 코드는 첨부파일 참조
};

OBJECT_ENTRY_AUTO(__uuidof(BasicClrProfiler), CBasicClrProfiler)

// BasicClrProfiler.cpp

HRESULT CBasicClrProfiler::ModuleLoadFinished(ModuleID moduleId, HRESULT hrStatus)
{
    ModuleInfo moduleInfo = { 0 };
    // ...[생략]...

    do
    {
        // ...[생략]...

        mdToken mdEnterProbeRef;
        hr = pEmit->DefineMemberRef(typeRef, L"Enter",
            sigFunctionProbe, sizeof(sigFunctionProbe), &mdEnterProbeRef);
        if (hr != S_OK)
        {
            break;
        }

        moduleInfo.m_mdEnterProbeRef = mdEnterProbeRef;

    } while (false);

    // ...[생략]...

    m_moduleIDToInfoMap.Update(moduleId, moduleInfo);
}

물론, Module이 Unload되었을 때 보관해 두었던 값을 제거해 주는 것도 잊으면 안되겠지요.

HRESULT CBasicClrProfiler::ModuleUnloadStarted(ModuleID moduleId)
{
    m_moduleIDToInfoMap.EraseIfExists(moduleId);
    return S_OK;
}

두 번째로 필요한 작업은 꼭 필요한 제약으로 인한 것인데, 바로 mscorlib.dll로 인한 ModuleLoadFinished가 발생했을 때는 우리가 만든 코드를 참조 추가해서는 안된다는 점입니다. 왜냐하면 Intercept.Helper.dll은 mscorlib.dll을 참조하고 있는데, mscorlib.dll에 다시 Intercept.Helper.dll을 참조하면 순환 참조가 되기 때문입니다. 실제로 마이크로소프트 측은 mscorlib.dll에 참조를 걸지 말라고 주의를 주고 있습니다. 따라서 다음과 같이 mscorlib.dll을 구분하는 코드를 넣어야 합니다.

BOOL CBasicClrProfiler::ContainsAtEnd(LPCWSTR wszContainer, LPCWSTR wszProspectiveEnding)
{
    size_t cchContainer = wcslen(wszContainer);
    size_t cchEnding = wcslen(wszProspectiveEnding);

    if (cchContainer < cchEnding)
        return FALSE;

    if (cchEnding == 0)
        return FALSE;

    if (_wcsicmp(wszProspectiveEnding, &(wszContainer[cchContainer - cchEnding])) != 0)
    {
        return FALSE;
    }

    return TRUE;
}

HRESULT CBasicClrProfiler::ModuleLoadFinished(ModuleID moduleId, HRESULT hrStatus)
{
    ULONG cchModule = _MAX_PATH;
    ULONG rCchModule = 0;
    AssemblyID assemblyId = 0;
    LPCBYTE pModuleBaseLoadAddress;
    wchar_t szModule[_MAX_PATH];

    HRESULT hr = m_pICorProfilerInfo2->GetModuleInfo(moduleId,
        &pModuleBaseLoadAddress, cchModule, &rCchModule, szModule, &assemblyId);
    if (hr != S_OK)
    {
        return S_OK;
    }

    if (ContainsAtEnd(szModule, L"mscorlib.dll")
        || ContainsAtEnd(szModule, L"intercept.helper.dll"))
    {
        return S_OK;
    }

    IMetaDataAssemblyEmit *pAssemblyEmit = nullptr;
    IMetaDataEmit *pEmit = nullptr;

    do
    {
        // ...[생략]...
    } while (false);

    // ...[생략]...
}




여기까지 했으면 이제 나머지 작업은 여러분들이 원하는 대상 메서드가 JIT 컴파일될 때 Intercept.Helper.ManagedLayer.Enter 메서드를 호출하도록 IL 코드를 변경하는 것입니다. 아쉽게도, 이 작업은 굉장히 복잡하기 때문에 제가 일일이 설명드릴 수 없습니다. 마이크로소프트 역시 이를 잘 알고 있어서, 다음과 같이 코드를 공개해 놓고 있는데 이를 참조하면 그래도 상당히 쉽게 만들 수 있습니다. ^^

New sample code for rewriting IL: ILRewrite Profiler
; http://i1.blogs.msdn.com/b/davbr/archive/2012/11/19/new-sample-code-for-rewriting-il-ilrewrite-profiler.aspx

Welcome to the CLR Profiler CodePlex site
; https://github.com/MicrosoftArchive/clrprofiler

이렇게 공개된 코드를 사용하면 다음과 같이 간단하게 JITCompilationStarted 코드를 완성할 수 있습니다.

HRESULT CBasicClrProfiler::Initialize(IUnknown * pICorProfilerInfoUnk)
{
    if (pICorProfilerInfoUnk == NULL)
    {
        return S_OK;
    }

    m_pICorProfilerInfo2 = pICorProfilerInfoUnk;

    DWORD dwEventMask = COR_PRF_MONITOR_MODULE_LOADS | COR_PRF_MONITOR_JIT_COMPILATION | COR_PRF_DISABLE_INLINING;
    m_pICorProfilerInfo2->SetEventMask(dwEventMask);

    return S_OK;}
}

HRESULT CBasicClrProfiler::JITCompilationStarted(FunctionID functionId, BOOL fIsSafeToBlock)
{
    mdToken methodToken = 0;
    ModuleID moduleId = 0;
    ClassID classId;

    HRESULT hr = m_pICorProfilerInfo2->GetFunctionInfo(functionId, &classId, &moduleId, &methodToken);
    if (hr != S_OK || methodToken == 0)
    {
        return S_OK;
    }

    ModuleInfo moduleInfo;
    
    if (m_moduleIDToInfoMap.LookupIfExists(moduleId, &moduleInfo) == FALSE)
    {
        return S_OK;
    }

    if (IsNilToken(moduleInfo.m_mdEnterProbeRef) == TRUE)
    {
        return S_OK;
    }

    RewriteIL(m_pICorProfilerInfo2, moduleId, methodToken, moduleInfo.m_mdEnterProbeRef);

    return S_OK;
}

여기까지 만들고 다음의 예제 코드에 대해 프로파일링을 시작하면,

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MyMethod();
            Console.WriteLine("TEST");
            Console.ReadLine();
        }

        static void MyMethod()
        {
        }
    }
}

출력 결과는 다음과 같습니다.

[Profiler] Main called
[Profiler] MyMethod called
TEST

"[Profiler]...called" 문자열은 ManagedLayer.Enter 메서드로 구현했던 바로 그 출력 내용이 호출된 것입니다.




이 정도면, 대충 IL 코드를 변경하는 프로파일러가 돌아가는 구조가 눈에 보이실 것입니다.

(첨부한 파일은 이 글의 예제 코드와 마이크로소프트의 ILRewrite Profiler 예제의 압축 파일(ILRewrite10Source.zip)을 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/15/2024]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13356정성태5/15/20233889DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233826.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234077.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233695.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234202VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233475오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233776.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233682.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234074.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233899오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235276.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236483.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234354디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234268.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234000닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234074오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234736닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234255닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234762Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234569.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234669.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234301Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233746Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233845Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233850오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233493Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...