Microsoft MVP성태의 닷넷 이야기
.NET Framework: 476. Visual Studio에서 Mono용 Profiler 개발 [링크 복사], [링크+제목 복사]
조회: 15462
글쓴 사람
정성태 (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)
13601정성태4/19/2024196닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024276닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024298닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024333닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024394닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024773닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024895닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241016닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241050닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241207C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241168닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241073Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241143닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241197닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241156오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241297Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241096Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241048개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241158Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241420Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241587개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241137닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241494오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241629닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241875닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...