Microsoft MVP성태의 닷넷 이야기
.NET Framework: 476. Visual Studio에서 Mono용 Profiler 개발 [링크 복사], [링크+제목 복사],
조회: 15604
글쓴 사람
정성태 (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]

... 31  32  33  34  35  36  [37]  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12715정성태7/17/20219503오류 유형: 736. Windows - MySQL zip 파일 버전의 "mysqld --skip-grant-tables" 실행 시 비정상 종료 [1]
12714정성태7/16/20218291오류 유형: 735. VCRUNTIME140.dll, MSVCP140.dll, VCRUNTIME140.dll, VCRUNTIME140_1.dll이 없어 exe 실행이 안 되는 경우
12713정성태7/16/20218800.NET Framework: 1077. C# - 동기 방식이면서 비동기 규약을 따르게 만드는 Task.FromResult파일 다운로드1
12712정성태7/15/20218236개발 환경 구성: 579. Azure - 리눅스 호스팅의 Site Extension 제작 방법
12711정성태7/15/20218611개발 환경 구성: 578. Azure - Java Web App Service를 위한 Site Extension 제작 방법
12710정성태7/15/202110397개발 환경 구성: 577. MQTT - emqx.io 서비스 소개
12709정성태7/14/20216986Linux: 42. 실행 중인 docker 컨테이너에 대한 구동 시점의 docker run 명령어를 확인하는 방법
12708정성태7/14/202110399Linux: 41. 리눅스 환경에서 디스크 용량 부족 시 원인 분석 방법
12707정성태7/14/202177672오류 유형: 734. MySQL - Authentication method 'caching_sha2_password' not supported by any of the available plugins.
12706정성태7/14/20218826.NET Framework: 1076. C# - AsyncLocal 기능을 CallContext만으로 구현하는 방법 [2]파일 다운로드1
12705정성태7/13/20219004VS.NET IDE: 168. x64 DLL 프로젝트의 컨트롤이 Visual Studio의 Designer에서 보이지 않는 문제 - 두 번째 이야기
12704정성태7/12/20218145개발 환경 구성: 576. Azure VM의 서비스를 Azure Web App Service에서만 접근하도록 NSG 설정을 제한하는 방법
12703정성태7/11/202113811개발 환경 구성: 575. Azure VM에 (ICMP) ping을 허용하는 방법
12702정성태7/11/20218922오류 유형: 733. TaskScheduler에 등록된 wacs.exe의 Let's Encrypt 인증서 업데이트 문제
12701정성태7/9/20218593.NET Framework: 1075. C# - ThreadPool의 스레드는 반환 시 ThreadStatic과 AsyncLocal 값이 초기화 될까요?파일 다운로드1
12700정성태7/8/20218970.NET Framework: 1074. RuntimeType의 메모리 누수? [1]
12699정성태7/8/20217768VS.NET IDE: 167. Visual Studio 디버깅 중 GC Heap 상태를 보여주는 "Show Diagnostic Tools" 메뉴 사용법
12698정성태7/7/202111738오류 유형: 732. Windows 11 업데이트 시 3% 또는 0%에서 다운로드가 멈춘 경우
12697정성태7/7/20217585개발 환경 구성: 574. Windows 11 (Insider Preview) 설치하는 방법
12696정성태7/6/20218195VC++: 146. 운영체제의 스레드 문맥 교환(Context Switch)을 유사하게 구현하는 방법파일 다운로드2
12695정성태7/3/20218226VC++: 145. C 언어의 setjmp/longjmp 기능을 Thread Context를 이용해 유사하게 구현하는 방법파일 다운로드1
12694정성태7/2/202110224Java: 24. Azure - Spring Boot 앱을 Java SE(Embedded Web Server)로 호스팅 시 로그 파일 남기는 방법 [1]
12693정성태6/30/20217967오류 유형: 731. Azure Web App Site Extension - Failed to install web app extension [...]. {1}
12692정성태6/30/20217888디버깅 기술: 180. Azure - Web App의 비정상 종료 시 남겨지는 로그 확인
12691정성태6/30/20218677개발 환경 구성: 573. 테스트 용도이지만 테스트에 적합하지 않은 Azure D1 공유(shared) 요금제
12690정성태6/28/20219499Java: 23. Azure - 자바(Java)로 만드는 Web App Service - Tomcat 호스팅
... 31  32  33  34  35  36  [37]  38  39  40  41  42  43  44  45  ...