Microsoft MVP성태의 닷넷 이야기
.NET Framework: 476. Visual Studio에서 Mono용 Profiler 개발 [링크 복사], [링크+제목 복사],
조회: 21777
글쓴 사람
정성태 (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)
13743정성태9/26/20246416닷넷: 2298. C# - Console 프로젝트에서의 await 대상으로 Main 스레드 활용하는 방법 [1]
13742정성태9/26/20246705닷넷: 2297. C# - ssh-keygen으로 생성한 ecdsa 유형의 Public Key 파일 해석 [1]파일 다운로드1
13741정성태9/25/20245884디버깅 기술: 202. windbg - ASP.NET MVC Web Application (.NET Framework) 응용 프로그램의 덤프 분석 시 요령
13740정성태9/24/20245752기타: 86. RSA 공개키 등의 modulus 값에 0x00 선행 바이트가 있는 이유(ASN.1 인코딩)
13739정성태9/24/20245907닷넷: 2297. C# - ssh-keygen으로 생성한 Public Key 파일 해석과 fingerprint 값(md5, sha256) 생성 [1]파일 다운로드1
13738정성태9/22/20245623C/C++: 174. C/C++ - 윈도우 운영체제에서의 file descriptor, FILE*파일 다운로드1
13737정성태9/21/20245979개발 환경 구성: 727. Visual C++ - 리눅스 프로젝트를 위한 빌드 서버의 msbuild 구성
13736정성태9/20/20245978오류 유형: 923. Visual Studio Code - Could not establish connection to "...": Port forwarding is disabled.
13735정성태9/20/20246064개발 환경 구성: 726. ARM 플랫폼용 Visual C++ 리눅스 프로젝트 빌드
13734정성태9/19/20245759개발 환경 구성: 725. ssh를 이용한 원격 docker 서비스 사용
13733정성태9/19/20246102VS.NET IDE: 194. Visual Studio - Cross Platform / "Authentication Type: Private Key"로 접속하는 방법
13732정성태9/17/20246139개발 환경 구성: 724. ARM + docker 환경에서 .NET 8 설치
13731정성태9/15/20246728개발 환경 구성: 723. C# / Visual C++ - Control Flow Guard (CFG) 활성화 [1]파일 다운로드2
13730정성태9/10/20246377오류 유형: 922. docker - RULE_APPEND failed (No such file or directory): rule in chain DOCKER
13729정성태9/9/20247124C/C++: 173. Windows / C++ - AllocConsole로 할당한 콘솔과 CRT 함수 연동 [1]파일 다운로드1
13728정성태9/7/20246942C/C++: 172. Windows - C 런타임에서 STARTUPINFO의 cbReserved2, lpReserved2 멤버를 사용하는 이유파일 다운로드1
13727정성태9/6/20247482개발 환경 구성: 722. ARM 플랫폼 빌드를 위한 미니 PC(?) - Khadas VIM4 [1]
13726정성태9/5/20247389C/C++: 171. C/C++ - 윈도우 운영체제에서의 file descriptor와 HANDLE파일 다운로드1
13725정성태9/4/20246152디버깅 기술: 201. WinDbg - sos threads 명령어 실행 시 "Failed to request ThreadStore"
13724정성태9/3/20248008닷넷: 2296. Win32/C# - 자식 프로세스로 HANDLE 상속파일 다운로드1
13723정성태9/2/20248267C/C++: 170. Windows - STARTUPINFO의 cbReserved2, lpReserved2 멤버 사용자 정의파일 다운로드2
13722정성태9/2/20246004C/C++: 169. C/C++ - CRT(C Runtime) 함수에 의존성이 없는 프로젝트 생성
13721정성태8/30/20246033C/C++: 168. Visual C++ CRT(C Runtime DLL: msvcr...dll)에 대한 의존성 제거 - 두 번째 이야기
13720정성태8/29/20246199VS.NET IDE: 193. C# - Visual Studio의 자식 프로세스 디버깅
13719정성태8/28/20246343Linux: 79. C++ - pthread_mutexattr_destroy가 없다면 메모리 누수가 발생할까요?
13718정성태8/27/20247429오류 유형: 921. Visual C++ - error C1083: Cannot open include file: 'float.h': No such file or directory [2]
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...