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)
12369정성태10/12/202013507Windows: 176. Raymond Chen이 한글날에 밝히는 윈도우의 한글 자모 분리 현상 [3]
12368정성태10/12/20209534오류 유형: 668. VSIX 확장 빌드 - The "GetDeploymentPathFromVsixManifest" task failed unexpectedly.
12367정성태10/12/202022240오류 유형: 667. Ubuntu - Temporary failure resolving 'kr.archive.ubuntu.com' [2]
12366정성태10/12/202011321.NET Framework: 950. C# 9.0 - (4) 원시 크기 정수(Native ints) [1]파일 다운로드1
12365정성태10/12/202010307.NET Framework: 949. C# 9.0 - (3) 람다 메서드의 매개 변수 무시(Lambda discard parameters)파일 다운로드1
12364정성태10/11/202011521.NET Framework: 948. C# 9.0 - (2) localsinit 플래그 내보내기 무시(Suppress emitting localsinit flag)파일 다운로드1
12363정성태10/11/202012400.NET Framework: 947. C# 9.0 - (1) 대상으로 형식화된 new 식(Target-typed new expressions) [2]파일 다운로드1
12362정성태10/11/20209173VS.NET IDE: 151. Visual Studio 2019에 .NET 5 rc/preview 적용하는 방법
12361정성태10/11/202010774.NET Framework: 946. C# 9.0을 위한 개발 환경 구성
12360정성태10/8/20208032오류 유형: 666. The type or namespace name '...' does not exist in the namespace 'Microsoft.VisualStudio.TestTools' (are you missing an assembly reference?)
12359정성태10/7/20209547오류 유형: 665. Windows - 재부팅 후 iSCSI 연결이 끊기는 문제
12358정성태10/7/20209524오류 유형: 664. Web Deploy 설치 시 "A newer version of Microsoft Web Deploy 3.6 was found on this machine." 오류 [3]
12357정성태10/7/20207642오류 유형: 663. 이벤트 로그 - The storage optimizer couldn't complete retrim on New Volume
12356정성태10/7/202022247오류 유형: 662. ASP.NET Core와 500.19, 500.21 오류 (0x8007000d)
12355정성태10/3/20207704오류 유형: 661. Hyper-V Linux VM의 Internal 유형의 가상 Switch에 대한 IP 연결이 되지 않는 경우
12354정성태10/2/202020499오류 유형: 660. Web Deploy (msdeploy.axd) 실행 시 오류 기록 [1]
12353정성태10/2/202010327개발 환경 구성: 518. 비주얼 스튜디오에서 IIS 웹 서버로 "Web Deploy"를 이용해 배포하는 방법
12352정성태10/2/202010844개발 환경 구성: 517. Hyper-V Internal 네트워크에 NAT을 이용한 인터넷 연결 제공
12351정성태10/2/202010336오류 유형: 659. Nox 실행이 안 되는 경우 - Unable to bind to the underlying transport for ...
12350정성태9/25/202013823Windows: 175. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 [2]파일 다운로드1
12349정성태9/25/20208826Linux: 32. Ubuntu 20.04 - docker를 위한 tcp 바인딩 추가
12348정성태9/25/20209548오류 유형: 658. 리눅스 docker - Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
12347정성태9/25/202023634Windows: 174. WSL 2의 네트워크 통신 방법 [4]
12346정성태9/25/20208784오류 유형: 657. IIS - http://localhost 방문 시 Service Unavailable 503 오류 발생
12345정성태9/25/20208499오류 유형: 656. iisreset 실행 시 "Restart attempt failed." 오류가 발생하지만 웹 서비스는 정상적인 경우파일 다운로드1
12344정성태9/25/20209662Windows: 173. 서비스 관리자에 "IIS Admin Service"가 등록되어 있지 않다면?
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...