Microsoft MVP성태의 닷넷 이야기
.NET Framework: 484. Mono Profiler에서 IL 코드 변경이 가능할까? [링크 복사], [링크+제목 복사],
조회: 20646
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

Mono Profiler에서 IL 코드 변경이 가능할까?

닷넷의 경우, Profiler에서 IL 코드를 변경하고 싶다면 ICorProfilerCallback::JITCompilationStarted 콜백 메서드 단계에서 ICorProfilerInfo::SetILFunctionBody 메서드를 이용하면 됩니다. 즉, 새로운 IL 코드로 덮어 쓰는 것이 가능한 것입니다.

그런데, 자유도 면에서 더 높을 것 같았던 Mono의 경우 Profiler에서 IL 코드를 쓸 수 있는 방법이 없습니다. (공식적인 IL 코드 변경 방법이 제공되고 있지 않습니다.)

지난번 코드에서도 소개했지만,

Visual Studio에서 Mono용 Profiler 개발
; https://www.sysnet.pe.kr/2/0/1805

닷넷의 JITCompilationStarted 콜백에 해당하는 이벤트를 Mono의 경우 mono_profiler_install_jit_compile 함수를 이용해 JIT 컴파일 이전/이후의 시점에 콜백을 받을 수 있습니다. 관련해서 Mono 코드는 다음과 같습니다.

// .\mono\mono\mini\mini.c(4932):    

MonoCompile*
mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts)
{
    // ... [생략] ...
    if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
        mono_profiler_method_jit (method);
    // ... [생략] ...
}

static gpointer
mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt, MonoException **jit_ex)
{
    // ... [생략] ...
        mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
    // ... [생략] ...
}

그래서 우리가 제공한 callback이 불려지는데요.

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

전달받은 method 인자로부터 IL 코드를 담은 바이트 배열까지는 구할 수 있습니다.

MonoMethodHeader *methodHeader = mono_method_get_header (method); 

guint32 code_size = 0;
guint32 maxStack = 0;
const guchar* orgCodes = mono_method_header_get_code(methodHeader, &code_size, &maxStack);

하지만 딱 거기까지입니다. ^^; 공식적으로, Mono는 mono_method_header_set_code와 같은 함수를 제공하지 않기 때문입니다.
혹시 반환받은 orgCodes 포인터에 값을 쓰면 되지 않을까요?

*((guchar *)orgCodes) = CEE_RET;

윈도우 환경의 Mono에서는 이런 경우 다음과 같은 예외가 발생합니다.

First-chance exception at 0x67A7E4E6 (mono-profiler-perf.dll) in mono.exe: 0xC0000005: Access violation writing location 0x032F2A92.
Unhandled exception at 0x67A7E4E6 (mono-profiler-perf.dll) in mono.exe: 0xC0000005: Access violation writing location 0x032F2A92.

이것은 DEP(Data Execution Prevention) 때문인데, orgCodes가 가리키는 포인터 주소가 .NET Assembly 파일의 IL 코드가 있는 데이터 영역이었던 것입니다. (검색해 보면, Ubuntu의 경우에도 기본적으로 DEP가 켜져 있기 때문에 리눅스에서도 동일하게 AV 오류가 발생할 것입니다.)

검색해도, Mono.Cecil을 이용해 DLL 파일을 로드해서 IL 코드를 바꾼 다음 그것을 반영한 DLL 파일로 쓰는 것만 있을 뿐 런타임(Run-time)에 IL 코드를 재작성(Rewrite)하는 것은 없습니다.




일단, 공식적인 방법은 없고 이제... 아쉽지만 ^^; 비공식적인 방법을 찾아야 합니다. 여기서 문제는 DEP 제약이기 때문에 윈도우의 경우 Write 권한을 주어 이 문제를 우회할 수 있습니다.

MEMORY_BASIC_INFORMATION mbi;
memset(&mbi, 0, sizeof(mbi));
VirtualQuery(orgCodes, &mbi, sizeof(mbi)); // mbi.Protect == PAGE_READONLY == 0x02

DWORD dwAttr = PAGE_WRITECOPY;
DWORD oldProtect = 0;
        
BOOL result = VirtualProtect((LPVOID)orgCodes, code_size, dwAttr, &oldProtect);
if (result == TRUE)
{
    *((guchar *)orgCodes) = CEE_RET;
}

당연하겠지만, 이 방법의 문제점은 기존 메서드의 크기를 넘어서는 IL 코드 재작성을 할 수 없다는 점입니다. 이것 이상의 것을 바란다면, Mono 런타임을 컴파일해서 사용자 환경에 배포하는 수밖에 달리 도리가 없어 보입니다.




실패는 했지만, 혹시나 싶어 시도했던 다른 방법을 소개해 보겠습니다. (왜냐하면, 여러분은 이런 시도를 하느라 시간낭비하지 마시라고! ^^)

문제를 우회하기 위해, mono_method_header_get_code의 내부 코드를 봤습니다.

// .\mono\mono\metadata\metadata.c(3652):

const unsigned char*
mono_method_header_get_code (MonoMethodHeader *header, guint32* code_size, guint32* max_stack)
{
    if (code_size)
        *code_size = header->code_size;
    if (max_stack)
        *max_stack = header->max_stack;
    return header->code;
}

그렇습니다. mono_method_header_get_code는 단순히 MonoMethodHeader의 code_size, max_stack, code 멤버를 반환할 뿐입니다. 그런데 이것 자체가 제약입니다. Mono는 Profiler 작성자가 내부 구조체에 의존하지 않도록 MonoMethodHeader와 같은 타입을 (공식적으로) 공개하지 않는 입장입니다. 따라서 이런 내부 구조체를 안전하게 접근하려면 Mono가 공표하는 public-api를 이용하는 수밖에는 없는데, 다시 이야기가 돌아서 Mono는 mono_method_header_set_code와 같은 API를 제공하지 않기 때문에 어쩔 수 없이 MonoMethodHeader의 내부 구조를 접근해야 합니다.

// .\mono\mono\metadata\metadata.h(322)
typedef struct _MonoMethodHeader MonoMethodHeader;

// .\mono\mono\metadata\metadata-internals.h(483)
struct _MonoMethodHeader {
    const unsigned char  *code;
#ifdef MONO_SMALL_CONFIG
    guint16      code_size;
#else
    guint32      code_size;
#endif
    guint16      max_stack   : 15;
    unsigned int is_transient: 1; /* mono_metadata_free_mh () will actually free this header */
    unsigned int num_clauses : 15;
    /* if num_locals != 0, then the following apply: */
    unsigned int init_locals : 1;
    guint16      num_locals;
    MonoExceptionClause *clauses;
    MonoType    *locals [MONO_ZERO_LEN_ARRAY];
};

모든 멤버를 접근하는 것은 위험도를 높이기 때문에 다음과 같이 일부분만 자신의 코드에 복사해 쓸 수 있습니다.

struct _MonoMethodHeader 
{
    guchar* code;
    guint32 code_size;
};

그래서, code 포인터에 새롭게 메모리를 할당해 우리가 원하는 코드를 제약없이 심을 수 있겠다 싶었습니다.

_MonoMethodHeader *pHeader = (_MonoMethodHeader *)methodHeader;

pHeader->code = (guchar *)g_malloc(1);
*(pHeader->code) = CEE_RET;
pHeader->code_size = 1;

하지만, 이렇게 바꿔도 소용없었습니다. 왜냐하면 Mono가 mono_method_get_header API로 반환했던 MonoMethodHeader 포인터는 임시 목적의 저장소일 뿐 이후에 이 데이터를 바탕으로 컴파일을 진행하는 것이 아니기 때문입니다. 실제로 위와 같이 변경한 후 다시 mono_method_get_header API를 호출하면 원본 코드 데이터를 반환하는 것을 볼 수 있습니다. ^^;

_MonoMethodHeader *pHeader = (_MonoMethodHeader *)methodHeader;

pHeader->code = (guchar *)g_malloc(1);
*(pHeader->code) = CEE_RET;
pHeader->code_size = 1;

// 다시 MonoMethodHeader를 구하면
guint32 code_size = 0;
guint32 maxStack = 0;
methodHeader = mono_method_get_header(method);
const guchar* orgCodes = mono_method_header_get_code(methodHeader, &code_size, &maxStack);

// orgCodes 포인터의 내용은 우리가 변경했던 코드가 아님!




혹시, "IL-Rewriting in Mono"와 관련해서 시도해 볼만한 아이디어가 있다면 덧글 부탁드립니다. ^^




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/27/2021]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13667정성태7/7/20246621닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20247700Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20247878Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20247472닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20247490닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20247413Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20247520오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20247858개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20248235개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20247911닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20248074Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20247846닷넷: 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/20247937닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/20249245닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20248487닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20248410개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20247957오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20248278오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20249343개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20247758오류 유형: 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/20248868닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
13643정성태6/12/20248306오류 유형: 907. MySqlConnector 사용 시 System.IO.FileLoadException 오류
13642정성태6/11/20248198스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
13641정성태6/11/20248673Linux: 71. Ubuntu 20.04를 22.04로 업데이트
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...