Microsoft MVP성태의 닷넷 이야기
.NET Framework: 484. Mono Profiler에서 IL 코드 변경이 가능할까? [링크 복사], [링크+제목 복사],
조회: 20759
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 76  77  78  79  [80]  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11936정성태6/10/201918378Math: 58. C# - 최소 자승법의 1차, 2차 수렴 그래프 변화 확인 [2]파일 다운로드1
11935정성태6/9/201919943.NET Framework: 843. C# - PLplot 출력을 파일이 아닌 Window 화면으로 변경
11934정성태6/7/201921284VC++: 133. typedef struct와 타입 전방 선언으로 인한 C2371 오류파일 다운로드1
11933정성태6/7/201919611VC++: 132. enum 정의를 C++11의 enum class로 바꿀 때 유의할 사항파일 다운로드1
11932정성태6/7/201918789오류 유형: 544. C++ - fatal error C1017: invalid integer constant expression파일 다운로드1
11931정성태6/6/201919306개발 환경 구성: 441. C# - CairoSharp/GtkSharp 사용을 위한 프로젝트 구성 방법
11930정성태6/5/201919840.NET Framework: 842. .NET Reflection을 대체할 System.Reflection.Metadata 소개 [1]
11929정성태6/5/201919404.NET Framework: 841. Windows Forms/C# - 클립보드에 RTF 텍스트를 복사 및 확인하는 방법 [1]
11928정성태6/5/201918172오류 유형: 543. PowerShell 확장 설치 시 "Catalog file '[...].cat' is not found in the contents of the module" 오류 발생
11927정성태6/5/201919407스크립트: 15. PowerShell ISE의 스크립트를 복사 후 PPT/Word에 붙여 넣으면 한글이 깨지는 문제 [1]
11926정성태6/4/201919936오류 유형: 542. Visual Studio - pointer to incomplete class type is not allowed
11925정성태6/4/201919782VC++: 131. Visual C++ - uuid 확장 속성과 __uuidof 확장 연산자파일 다운로드1
11924정성태5/30/201921420Math: 57. C# - 해석학적 방법을 이용한 최소 자승법 [1]파일 다운로드1
11923정성태5/30/201921047Math: 56. C# - 그래프 그리기로 알아보는 경사 하강법의 최소/최댓값 구하기파일 다운로드1
11922정성태5/29/201918538.NET Framework: 840. ML.NET 데이터 정규화파일 다운로드1
11921정성태5/28/201924397Math: 55. C# - 다항식을 위한 최소 자승법(Least Squares Method)파일 다운로드1
11920정성태5/28/201916053.NET Framework: 839. C# - PLplot 색상 제어
11919정성태5/27/201920312Math: 54. C# - 최소 자승법의 1차 함수에 대한 매개변수를 단순 for 문으로 구하는 방법 [1]파일 다운로드1
11918정성태5/25/201921151Math: 53. C# - 행렬식을 이용한 최소 자승법(LSM: Least Square Method)파일 다운로드1
11917정성태5/24/201922136Math: 52. MathNet을 이용한 간단한 통계 정보 처리 - 분산/표준편차파일 다운로드1
11916정성태5/24/201919952Math: 51. MathNET + OxyPlot을 이용한 간단한 통계 정보 처리 - Histogram파일 다운로드1
11915정성태5/24/201923067Linux: 11. 리눅스의 환경 변수 관련 함수 정리 - putenv, setenv, unsetenv
11914정성태5/24/201922058Linux: 10. 윈도우의 GetTickCount와 리눅스의 clock_gettime파일 다운로드1
11913정성태5/23/201918764.NET Framework: 838. C# - 숫자형 타입의 bit(2진) 문자열, 16진수 문자열 구하는 방법파일 다운로드1
11912정성태5/23/201918726VS.NET IDE: 137. Visual Studio 2019 버전 16.1부터 리눅스 C/C++ 프로젝트에 추가된 WSL 지원
11911정성태5/23/201917494VS.NET IDE: 136. Visual Studio 2019 - 리눅스 C/C++ 프로젝트에 인텔리센스가 동작하지 않는 경우
... 76  77  78  79  [80]  81  82  83  84  85  86  87  88  89  90  ...