Microsoft MVP성태의 닷넷 이야기
.NET Framework: 476. Visual Studio에서 Mono용 Profiler 개발 [링크 복사], [링크+제목 복사],
조회: 21779
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 4개 있습니다.)

Visual Studio에서 Mono용 Profiler 개발

Microsoft .NET용 프로파일러는 문서화가 잘 되어 있는 반면, Mono용은 쉽게 찾을 수 없어서 정리를 해봤습니다. (미리 말해두자면, Microsoft .NET용 프로파일러 제작 방법과는 많이 다릅니다.)

우선, Mono 소스 코드를 먼저 다운로드 받아서 빌드해야 합니다. 이에 대해서는 저번 글에 썼으니 참고해서 빌드해 둡니다.

Visual Studio 2013에서 Mono 컴파일하는 방법
; https://www.sysnet.pe.kr/2/0/1796

그다음, 프로파일러용 Win32 DLL Visual C++ 프로젝트를 만들고, 프로젝트 속성에서 헤더 및 라이브러리 폴더를 지정해야 하는데요. 각각 다음과 같은 경로로 포함하면 됩니다. (컴파일된 모노가 E:\mono 폴더라고 가정)

===== Include 추가 경로 =====
e:\mono\mono\metadata
e:\mono\mono\eglib\src

===== Library 추가 경로 =====
e:\mono\msvc\Win32\lib

(사실, 모노를 빌드하는 이유는 단 하나입니다. lib 폴더의 eglib.lib 파일을 쉽게 얻기 위해 빌드한 것입니다.)

소스 코드는 이렇게 시작할 수 있습니다.

// ================================ PerfProfiler.h

#ifdef PERFPROFILER_EXPORTS
#define PERFPROFILER_API __declspec(dllexport)
#else
#define PERFPROFILER_API __declspec(dllimport)
#endif

extern "C"
{
    PERFPROFILER_API void mono_profiler_startup(const char *args);
};

// ================================ PerfProfiler.cpp

#include "stdafx.h"
#include <mono/metadata/profiler.h> 
#include <mono/metadata/debug-helpers.h>

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <eglib\src\glib.h>

#pragma comment(lib, "eglib.lib")

#include "PerfProfiler.h"

PERFPROFILER_API void mono_profiler_startup(const char *args)
{
} 

mono_profiler_startup 함수에서 해야 할 대표적인 작업은 2가지입니다.

  1. 프로파일링 시, 콜백 함수에 전달될 임의의 문맥 정보 생성
  2. Mono 측에 어떤 범주의 프로파일링을 원하는지를 알린다.

1단계 먼저 살펴보면, 문맥 정보는 포인터를 통해 콜백 함수에 전달되므로 원하는 구조체를 정의해서 포인터로 넘겨주면 됩니다. 관례인지는 모르겠지만 그 구조체의 이름을 _MonoProfiler, MonoProfiler로 따르는 것 같습니다. 따라서, 저도 다음과 같이 정의해 봤습니다.

struct _MonoProfiler
{
    size_t _jitCount = 0;
};

typedef _MonoProfiler MonoProfiler;

이 구조체를 동적 할당한 후 mono_profiler_install 메서드에 넘겨주면 이후의 CALLBACK 함수에서 이 포인터를 넘겨줍니다. 물론, 관심있는 callback 함수의 등록 및 이벤트 등록도 함께 해주는 것은 그나마 Microsoft .NET Profiler 만드는 요령과 닮았습니다.

static HMODULE hMonoModule = nullptr;

typedef void(*mono_profiler_installFunc) (MonoProfiler *prof, MonoProfileFunc shutdown_callback);
typedef void(*mono_profiler_install_jit_compileFunc) (MonoProfileMethodFunc enterCallback, MonoProfileMethodResult leaveCallback);
typedef void(*mono_profiler_set_eventsFunc) (MonoProfileFlags events);

static mono_profiler_installFunc g_mono_profiler_install;
static mono_profiler_install_jit_compileFunc g_mono_profiler_install_jit_compile;
static mono_profiler_set_eventsFunc g_mono_profiler_set_events;

void mono_profiler_shutdown_callback(MonoProfiler *prof)
{
}

void mono_profiler_jit_compile_enter(MonoProfiler *prof, MonoMethod *method)
{
}

void mono_profiler_jit_compile_leave(MonoProfiler *prof, MonoMethod *method, int result)
{
}

PERFPROFILER_API void mono_profiler_startup(const char *args)
{
    MonoProfiler *prof = g_new0(MonoProfiler, 1);

    (void) args; 

    hMonoModule = LoadLibrary(L"libmonosgen-2.0.dll");
    // 또는
    // hMonoModule = LoadLibrary(L"mono.dll");

    if (hMonoModule == nullptr)
    {
        return;
    }
    else
    {
        g_mono_profiler_install = (mono_profiler_installFunc)GetProcAddress(hMonoModule, "mono_profiler_install");
        g_mono_profiler_install_jit_compile = (mono_profiler_install_jit_compileFunc)GetProcAddress(hMonoModule, "mono_profiler_install_jit_compile");
        g_mono_profiler_set_events = (mono_profiler_set_eventsFunc)GetProcAddress(hMonoModule, "mono_profiler_set_events");

        g_mono_profiler_install(prof, mono_profiler_shutdown_callback);
        g_mono_profiler_install_jit_compile(mono_profiler_jit_compile_enter, mono_profiler_jit_compile_leave);
        g_mono_profiler_set_events(MONO_PROFILE_JIT_COMPILATION);
    }
} 

위의 소스 코드를 찬찬히 뜯어 보겠습니다. ^^ 우선, g_new0과 같은 다소 생소한 동적 할당 함수를 사용하고 있는데요. 알고 보니 이것은 Glib라는 별도의 라이브러리였습니다. (eglib.lib가 필요한 이유입니다.)

Glib 라이브러리
; http://edgar.tistory.com/25

Mono에서 크로스 플랫폼을 위해 광범위하게 이 라이브러리를 사용하고 있으므로 우리가 만드는 프로파일러도 기왕이면 이것을 따르는 것이 좋을 듯 합니다.

그다음 LoadLibrary를 통해 libmonosgen-2.0.dll을 로드하는 작업입니다. 모노 3.2.3 미만의 버전에서는 "mono.dll"을 로드해야 하고, 그 이후부터는 GC 구현체에 따라 "Boehm", "SGen" 유형으로 나뉘므로 각각 libmonoboehm-2.0.dll, libmonosgen-2.0.dll을 상황에 따라 선택해야 합니다.

그런데, 딱히 이걸 Profiler 입장에서 선택할 수 있는 기준이 없습니다. 따라서, LoadLibary보다는 이미 메모리에 올라와 있는 Mono 런타임 모듈을 구하기 위해 GetModuleHandle API를 사용하는 것이 (제가 생각하기에는) 더 나은 방법입니다.

hMonoModule = GetModuleHandle(L"libmonosgen-2.0.dll");
if (hMonoModule == nullptr)
{
    hMonoModule = GetModuleHandle(L"libmonoboehm-2.0.dll");
}

if (hMonoModule == nullptr)
{
    hMonoModule = GetModuleHandle(L"mono.dll");
}

이후 mono_profiler_install API를 동적 로드해서 모노 측에 관심있는 프로파일링 동작을 등록하면 됩니다. 위의 예제에서는 JIT 컴파일 전/후에 모노로 하여금 콜백 함수를 부르도록 등록하고 있습니다.




이렇게 만들고 빌드하면 DLL 파일이 생성되겠지요? 저는 프로젝트를 PerfProfiler.vcxproj로 만들었기 때문에 출력 DLL의 이름은 PerfProfiler.dll로 됩니다. 문제는, Mono는 profiler를 위해 특별한 명명 규칙이 있기 때문에 이를 따라야 합니다. 기본적으로 "mono-profiler-"라는 prefix를 가지고 있기 때문에 제가 만든 DLL도 그것에 맞게 "mono-profiler-perf.dll"로 출력되도록 이름을 바꿨습니다.

바뀐 이름으로 프로파일링을 적용할 때는 접두사를 뺀 부분의 문자열만 전달해야 합니다. 예를 들어, 제가 만든 DLL의 이름이 "mono-profiler-perf.dll"이므로 mono에서 다음과 같은 옵션으로 실행해야 합니다.

mono --profile=perf.dll [대상EXE파일]

방법을 알았으니, 실제 테스트를 위해 모노 런타임을 준비해야 하는데요. 아쉽게도 "Visual Studio 2013에서 Mono 컴파일하는 방법" 글에서 빌드한 것은 단지 프로파일러를 컴파일하기 위해 Import Library가 필요해서 한 것일 뿐, 이때 빌드된 mono.exe는 써 먹을 수 없습니다. 왜냐하면 그걸 사용하려면 클래스 라이브러리(mscorlib.dll)까지 모두 빌드해야 하는데, 이 과정이 좀 복잡합니다.

이 때문에 제 경우에 모노 런타임을 다운로드 받았는데요. (version 3.2.3)

Mono for Windows is available as a Windows Installer file
; http://www.mono-project.com/download/#download-win

따라서, 다음과 같이 옵션을 주고 실행을 하면 됩니다.

E:\mono\mre\bin>mono --profile=perf.dll TestConsole.exe
Hello World!

자... 여기까지 실습했으면, 이제 Visual Studio의 "F5 디버깅"이 되도록 구성할 수 있습니다. Visual C++의 속성창에서 "Debugging" 범주의 값을 다음과 같이 맞춰 주고,

Command: E:\mono\mre\bin\mono.exe
Command Arguments: --profile=perf.dll "E:\mono\mre\bin\TestConsole.exe"
Working Directory: E:\mono\mre\bin

"General"의 "Output Directory" 값을 "E:\mono\mre\bin"로 해줘서 빌드된 DLL이 해당 폴더에 생성되도록 해주면, 이제부터 "F5"를 눌러 실행할 때마다 다음과 같이 BreakPoint를 사용할 수 있는 디버그 모드로 진입하게 됩니다.

mono_profiler_1.png

오~~~~ 멋지군요. ^^

(첨부한 파일은 이 글의 프로파일러 예제 코드를 포함합니다.)




(여기부터는 시행 착오를 겪은 것입니다.)

잘못 빌드한 경우 다음과 같은 오류가 발생할 수 있습니다.

E:\mono\mre\bin>mono --profile=perf.dll TestConsole.exe
The 'perf.dll' profiler wasn't found in the main executable nor could it be loaded from 'mono-profiler-perf.dll'.
Hello World!

제가 겪은 바로는 mono-2.0.dll과 같은 특정 DLL에 의존해서 빌드하면 안 됩니다.




Unity3d 제품에 포함된 모노 런타임에서도 잘 실행이 됩니다. 단지, Unity3d의 경우 이전 버전의 모노를 사용하기 때문에 프로파일러 내부에서 로드하게 되는 런타임 DLL은 mono.dll입니다.

E:\Program Files (x86)\Unity\Editor\Data\Mono\bin>mono --profile=perf.dll TestConsole.exe
Hello World!




리눅스 환경을 지원하겠다면 철저하게 초기부터 cross-platform을 염두에 두어야 합니다. 가령 GetModuleHandle부터 Win32 API이기 때문에 사용이 불가능하다는 점!




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/10/2021]

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

비밀번호

댓글 작성자
 



2014-11-06 02시49분
[spowner] 도대체 뭘 하시기에 이런 노력을 하고 계시는지.. 어쨌든 대단합니다. 많은 배움 얻고 갑니다
[guest]
2014-11-06 11시51분
아니... 그냥 집에서 심심해서 해보는 정도입니다. 이런 거 말고, 완전한 유형의 프로젝트를 만들어 진행해야 할텐데... 늘 생각만 하다가 시간만 보내고 있습니다. ^^;
정성태
2014-11-11 12시48분
[Lyn] 이런걸 심심해서 해보시다뇨 ㅠ.ㅠ
[guest]

1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13667정성태7/7/20246608닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20247686Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20247864Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20247470닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20247478닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20247398Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20247504오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20247844개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20248221개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20247911닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20248069Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20247843닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20247787오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20247926닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/20249245닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20248472닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20248397개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20247948오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20248266오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20249326개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20247745오류 유형: 908. Process Explorer - "Error configuring dump resources: The system cannot find the file specified."
13645정성태6/13/20248197개발 환경 구성: 711. Visual Studio로 개발 시 기본 등록하는 dev tag 이미지로 Docker Desktop k8s에서 실행하는 방법
13644정성태6/12/20248855닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
13643정성태6/12/20248303오류 유형: 907. MySqlConnector 사용 시 System.IO.FileLoadException 오류
13642정성태6/11/20248196스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
13641정성태6/11/20248659Linux: 71. Ubuntu 20.04를 22.04로 업데이트
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...