Microsoft MVP성태의 닷넷 이야기
.NET Framework: 476. Visual Studio에서 Mono용 Profiler 개발 [링크 복사], [링크+제목 복사]
조회: 15527
글쓴 사람
정성태 (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)
13280정성태3/9/20234605개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/20234125오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
13278정성태3/8/20234156개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원 [1]
13277정성태3/6/20234812개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/20234476.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/20234792.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/20234356.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/20234086.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
13272정성태2/27/20234357오류 유형: 850. SSMS - mdf 파일을 Attach 시킬 때 Operating system error 5: "5(Access is denied.)" 에러
13271정성태2/25/20234274오류 유형: 849. Sql Server Configuration Manager가 시작 메뉴에 없는 경우
13270정성태2/24/20233872.NET Framework: 2098. dotnet build에 /p 옵션을 적용 시 유의점
13269정성태2/23/20234436스크립트: 46. 파이썬 - uvicorn의 콘솔 출력을 UDP로 전송
13268정성태2/22/20234988개발 환경 구성: 667. WSL 2 내부에서 열고 있는 UDP 서버를 호스트 측에서 접속하는 방법
13267정성태2/21/20234898.NET Framework: 2097. C# - 비동기 소켓 사용 시 메모리 해제가 finalizer 단계에서 발생하는 사례파일 다운로드1
13266정성태2/20/20234506오류 유형: 848. .NET Core/5+ - Process terminated. Couldn't find a valid ICU package installed on the system
13265정성태2/18/20234432.NET Framework: 2096. .NET Core/5+ - PublishSingleFile 유형에 대한 runtimeconfig.json 설정
13264정성태2/17/20235932스크립트: 45. 파이썬 - uvicorn 사용자 정의 Logger 작성
13263정성태2/16/20234087개발 환경 구성: 666. 최신 버전의 ilasm.exe/ildasm.exe 사용하는 방법
13262정성태2/15/20235157디버깅 기술: 191. dnSpy를 이용한 (소스 코드가 없는) 닷넷 응용 프로그램 디버깅 방법 [1]
13261정성태2/15/20234422Windows: 224. Visual Studio - 영문 폰트가 Fullwidth Latin Character로 바뀌는 문제
13260정성태2/14/20234229오류 유형: 847. ilasm.exe 컴파일 오류 - error : syntax error at token '-' in ... -inf
13259정성태2/14/20234377.NET Framework: 2095. C# - .NET5부터 도입된 CollectionsMarshal
13258정성태2/13/20234265오류 유형: 846. .NET Framework 4.8 Developer Pack 설치 실패 - 0x81f40001
13257정성태2/13/20234353.NET Framework: 2094. C# - Job에 Process 포함하는 방법 [1]파일 다운로드1
13256정성태2/10/20235187개발 환경 구성: 665. WSL 2의 네트워크 통신 방법 - 두 번째 이야기
13255정성태2/10/20234516오류 유형: 845. gihub - windows2022 이미지에서 .NET Framework 4.5.2 미만의 프로젝트에 대한 빌드 오류
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...