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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  56  57  [58]  59  60  ...
NoWriterDateCnt.TitleFile(s)
12180정성태3/10/20208617오류 유형: 600. "Docker Desktop for Windows" - EXPOSE 포트가 LISTENING 되지 않는 문제
12179정성태3/10/202020046개발 환경 구성: 481. docker - PostgreSQL 컨테이너 실행
12178정성태3/10/202011549개발 환경 구성: 480. Linux 운영체제의 docker를 위한 tcp 바인딩 추가 [1]
12177정성태3/9/202011153개발 환경 구성: 479. docker - MySQL 컨테이너 실행
12176정성태3/9/202010572개발 환경 구성: 478. 파일의 (sha256 등의) 해시 값(checksum) 확인하는 방법
12175정성태3/8/202010690개발 환경 구성: 477. "Docker Desktop for Windows"의 "Linux Container" 모드를 위한 tcp 바인딩 추가
12174정성태3/7/202010222개발 환경 구성: 476. DockerDesktopVM의 파일 시스템 접근 [3]
12173정성태3/7/202011202개발 환경 구성: 475. docker - SQL Server 2019 컨테이너 실행 [1]
12172정성태3/7/202016113개발 환경 구성: 474. docker - container에서 root 권한 명령어 실행(sudo)
12171정성태3/6/202011073VS.NET IDE: 143. Visual Studio - ASP.NET Core Web Application의 "Enable Docker Support" 옵션으로 달라지는 점 [1]
12170정성태3/6/20209701오류 유형: 599. "Docker Desktop is switching..." 메시지와 DockerDesktopVM CPU 소비 현상
12169정성태3/5/202011710개발 환경 구성: 473. Windows nanoserver에 대한 docker pull의 태그 사용 [1]
12168정성태3/5/202012397개발 환경 구성: 472. 윈도우 환경에서의 dockerd.exe("Docker Engine" 서비스)가 Linux의 것과 다른 점
12167정성태3/5/202011654개발 환경 구성: 471. C# - 닷넷 응용 프로그램에서 DB2 Express-C 데이터베이스 사용 (3) - ibmcom/db2express-c 컨테이너 사용
12166정성태3/4/202011286개발 환경 구성: 470. Windows Server 컨테이너 - DockerMsftProvider 모듈을 이용한 docker 설치
12165정성태3/2/202010947.NET Framework: 900. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 네 번째 이야기(Monitor.Enter 후킹)파일 다운로드1
12164정성태2/29/202011779오류 유형: 598. Surface Pro 6 - Windows Hello Face Software Device가 인식이 안 되는 문제
12163정성태2/27/202010241.NET Framework: 899. 익명 함수를 가리키는 delegate 필드에 대한 직렬화 문제
12162정성태2/26/202013048디버깅 기술: 166. C#에서 만든 COM 객체를 C/C++로 P/Invoke Interop 시 메모리 누수(Memory Leak) 발생 [6]파일 다운로드2
12161정성태2/26/20209678오류 유형: 597. manifest - The value "x64" of attribute "processorArchitecture" in element "assemblyIdentity" is invalid.
12160정성태2/26/202010359개발 환경 구성: 469. Reg-free COM 개체 사용을 위한 manifest 파일 생성 도구 - COMRegFreeManifest
12159정성태2/26/20208539오류 유형: 596. Visual Studio - The project needs to include ATL support
12158정성태2/25/202010347디버깅 기술: 165. C# - Marshal.GetIUnknownForObject/GetIDispatchForObject 사용 시 메모리 누수(Memory Leak) 발생파일 다운로드1
12157정성태2/25/202010260디버깅 기술: 164. C# - Marshal.GetNativeVariantForObject 사용 시 메모리 누수(Memory Leak) 발생 및 해결 방법파일 다운로드1
12156정성태2/25/20209603오류 유형: 595. LINK : warning LNK4098: defaultlib 'nafxcw.lib' conflicts with use of other libs; use /NODEFAULTLIB:library
12155정성태2/25/20208886오류 유형: 594. Warning NU1701 - This package may not be fully compatible with your project
... 46  47  48  49  50  51  52  53  54  55  56  57  [58]  59  60  ...