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)
13398정성태8/3/20234157스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
13397정성태7/23/20233659닷넷: 2134. C# - 문자열 연결 시 string.Create를 이용한 GC 할당 최소화
13396정성태7/22/20233348스크립트: 54. 파이썬 pystack 소개 - 메모리 덤프로부터 콜 스택 열거
13395정성태7/20/20233311개발 환경 구성: 685. 로컬에서 개발 중인 ASP.NET Core/5+ 웹 사이트에 대해 localhost 이외의 호스트 이름으로 접근하는 방법
13394정성태7/16/20233259오류 유형: 873. Oracle.ManagedDataAccess.Client - 쿼리 수행 시 System.InvalidOperationException
13393정성태7/16/20233424닷넷: 2133. C# - Oracle 데이터베이스의 Sleep 쿼리 실행하는 방법
13392정성태7/16/20233299오류 유형: 872. Oracle - ORA-01031: insufficient privileges
13391정성태7/14/20233370닷넷: 2132. C# - sealed 클래스의 메서드를 callback 호출했을 때 인라인 처리가 될까요?
13390정성태7/12/20233341스크립트: 53. 파이썬 - localhost 호출 시의 hang 현상
13389정성태7/5/20233324개발 환경 구성: 684. IIS Express로 호스팅하는 웹을 WSL 환경에서 접근하는 방법
13388정성태7/3/20233517오류 유형: 871. 윈도우 탐색기에서 열리지 않는 zip 파일 - The Compressed (zipped) Folder '[...].zip' is invalid. [1]파일 다운로드1
13387정성태6/28/20233536오류 유형: 870. _mysql - Commands out of sync; you can't run this command now
13386정성태6/27/20233605Linux: 61. docker - 원격 제어를 위한 TCP 바인딩 추가
13385정성태6/27/20233826Linux: 60. Linux - 외부에서의 접속을 허용하기 위한 TCP 포트 여는 방법
13384정성태6/26/20233569.NET Framework: 2131. C# - Source Generator로 해결하는 enum 박싱 문제파일 다운로드1
13383정성태6/26/20233315개발 환경 구성: 683. GPU 런타임을 사용하는 Colab 노트북 설정
13382정성태6/25/20233358.NET Framework: 2130. C# - Win32 API를 이용한 윈도우 계정 정보 (예: 마지막 로그온 시간)파일 다운로드1
13381정성태6/25/20233746오류 유형: 869. Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
13380정성태6/24/20233196스크립트: 52. 파이썬 3.x에서의 동적 함수 추가
13379정성태6/23/20233210스크립트: 51. 파이썬 2.x에서의 동적 함수 추가
13378정성태6/22/20233098오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20236901오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
13376정성태6/21/20233286.NET Framework: 2129. C# - Polly를 이용한 클라이언트 측의 요청 재시도파일 다운로드1
13375정성태6/20/20232986스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233111오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234400오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...