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)
12458정성태12/16/20209460오류 유형: 694. C# - Task.Start 메서드 호출 시 "System.InvalidOperationException: 'Start may not be called on a task that has completed.'" 예외 발생 [1]
12457정성태12/15/20209017Windows: 185. C# - Windows 10/2019부터 추가된 SIO_TCP_INFO파일 다운로드1
12456정성태12/15/20209292VS.NET IDE: 156. Visual Studio - "Migrate packages.config to PackageReference"
12455정성태12/15/20208802오류 유형: 693. DLL 로딩 시 0x800704ec - This Program is Blocked by Group Policy
12454정성태12/15/20209398Windows: 184. Windows - AppLocker의 "DLL Rules"를 이용해 임의 경로에 설치한 DLL의 로딩을 막는 방법 [1]
12453정성태12/14/202010355.NET Framework: 984. C# - bool / BOOL / VARIANT_BOOL에 대한 Interop [1]파일 다운로드1
12452정성태12/14/202010583Windows: 183. 설정은 가능하지만 구할 수는 없는 TcpTimedWaitDelay 값
12451정성태12/14/20209732Windows: 182. WMI Namespace를 열거하고, 그 안에 정의된 클래스를 열거하는 방법 [5]
12450정성태12/13/202010464.NET Framework: 983. C# - TIME_WAIT과 ephemeral port 재사용파일 다운로드1
12449정성태12/11/202010828.NET Framework: 982. C# - HttpClient에서의 ephemeral port 재사용 [2]파일 다운로드1
12448정성태12/11/202012478.NET Framework: 981. C# - HttpWebRequest, WebClient와 ephemeral port 재사용파일 다운로드1
12447정성태12/10/202010621.NET Framework: 980. C# - CopyFileEx API 사용 예제 코드파일 다운로드1
12446정성태12/10/202011280.NET Framework: 979. C# - CoCreateInstanceEx 사용 예제 코드파일 다운로드1
12445정성태12/8/20208648오류 유형: 692. C# Marshal.PtrToStructure - The structure must not be a value class.파일 다운로드1
12444정성태12/8/20209481.NET Framework: 978. C# - GUID 타입 전용의 UnmanagedType.LPStruct [1]파일 다운로드1
12443정성태12/8/20209374.NET Framework: 977. C# PInvoke - C++의 매개변수에 대한 마샬링을 tlbexp.exe를 이용해 확인하는 방법
12442정성태12/4/20208167오류 유형: 691. Visual Studio - Build Events에 robocopy를 사용할때 "Invalid Parameter #1" 오류가 발행하는 경우
12441정성태12/4/20207846오류 유형: 690. robocopy - ERROR : No Destination Directory Specified.
12440정성태12/4/20208898오류 유형: 689. SignTool Error: Invalid option: /as
12439정성태12/4/202010163디버깅 기술: 176. windbg - 특정 Win32 API에서 BP가 안 걸리는 경우 (2) [1]
12438정성태12/2/202010102오류 유형: 688. .Visual C++ - Error C2011 'sockaddr': 'struct' type redefinition
12437정성태12/1/20209759VS.NET IDE: 155. pfx의 암호 키 파일을 Visual Studio 없이 등록하는 방법
12436정성태12/1/202010055오류 유형: 687. .NET Core 2.2 빌드 - error MSB4018: The "RazorTagHelper" task failed unexpectedly.
12435정성태12/1/202015526Windows: 181. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (4) - ReuseUnicastPort를 이용한 포트 고갈 문제 해결 [1]파일 다운로드1
12434정성태11/30/202010846Windows: 180. C# - dynamicport 값의 범위를 알아내는 방법
12433정성태11/29/20209901Windows: 179. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (3) - SO_PORT_SCALABILITY파일 다운로드1
... 46  [47]  48  49  50  51  52  53  54  55  56  57  58  59  60  ...