Microsoft MVP성태의 닷넷 이야기
닷넷: 2330. C# - 실행 시에 메서드 가로채기 (.NET 5 ~ .NET 8) [링크 복사], [링크+제목 복사],
조회: 873
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

(시리즈 글이 3개 있습니다.)
닷넷: 2329. C# - 실행 시에 메서드 가로채기 (.NET Framework 4.8)
; https://www.sysnet.pe.kr/2/0/13909

닷넷: 2330. C# - 실행 시에 메서드 가로채기 (.NET 5 ~ .NET 8)
; https://www.sysnet.pe.kr/2/0/13912

닷넷: 2331. C# - 실행 시에 메서드 가로채기 (.NET 9)
; https://www.sysnet.pe.kr/2/0/13915




C# - 실행 시에 메서드 가로채기 (.NET 5 ~ .NET 8)

(이번 글의 코드는 .NET 5, 6, 7, 8에서만 테스트되었습니다.)




지난 글에서 .NET Framework 환경에 대해 글을 썼는데요,

C# - 실행 시에 메서드 가로채기 (.NET Framework 4.8)
; https://www.sysnet.pe.kr/2/0/13909

이번에는 (테스트하기 귀찮으므로 .NET Core 1.x ~ 3.x는 제외하고) .NET 8로 한정해서 설명해 보겠습니다. (미리 언급하자면, .NET 9에서는 이 코드가 동작하지 않습니다.)

일단, 시작으로 지난 글의 소스 코드를 그대로 .NET 8 프로젝트로 가져와 실행해 보면 가로채기가 전혀 안 되는 것을 볼 수 있습니다. .NET Framework의 경우에는 메서드 호출을 "call [...]"로 JIT 컴파일 전/후 모두 간접 주소를 이용했는데요, .NET Core의 경우에는 "call ..." 또는 "jmp ..."로 offset 형식의 호출로 변경되면서 방식이 달라졌기 때문입니다. 게다가, MethodDesc에 보관했던 Jitted Address 값을 매번 사용하는 방식이 아닌, 최초 한 번만 그 값을 가져다가 재사용하므로 이후 호출에서는 MethodDesc로부터 구하지 않습니다. 이로 인해 가로채기가 되려면 반드시 "JIT 컴파일 전"에 이뤄져야 합니다.

따라서, 지난 글의 소스 코드에서 oldMethod 인자의 PrepareMethod 호출을 제거하고,

using System;
using System.Reflection;
using System.Runtime.CompilerServices;

public class ReplaceMethod
{
    public unsafe static void Replace(MethodBase oldMethod, MethodInfo newMethod)
    {
        // RuntimeHelpers.PrepareMethod(oldMethod.MethodHandle); // 사실 이 코드는 .NET Framework에서도 필요 없는 작업이었습니다.
        RuntimeHelpers.PrepareMethod(newMethod.MethodHandle);

        IntPtr oldMethodPos = IntPtr.Zero;

        if (oldMethod.IsConstructor && oldMethod.GetParameters().Length == 0)
        {
            oldMethodPos = FromMethodTable(oldMethod);
        }
        else
        {
            oldMethodPos = FromMethodDesc(oldMethod);
        }

        if (oldMethodPos == IntPtr.Zero)
        {
            throw new InvalidOperationException("Failed to get method position.");
        }

        IntPtr newFuncAddr = newMethod.MethodHandle.GetFunctionPointer();
        
        if (IntPtr.Size == 8)
        {
            ulong* ptr = (ulong*)oldMethodPos;
            *ptr = (ulong)newFuncAddr.ToInt64();
        }
        else
        {
            uint* ptr = (uint*)oldMethodPos;
            *ptr = (uint)newFuncAddr.ToInt32();
        }
    }

    // ...[생략]...
}

해당 메서드를 사용하기 전에 가로채기를 완료하면 됩니다.

// 가로채기를 먼저 한 다음,
{
    MethodInfo instanceMethod = typeof(TestClass).GetMethod("TestMethod");
    MethodInfo newInstanceMethod = typeof(Program).GetMethod("MyMethod");
    ReplaceMethod.Replace(instanceMethod, newInstanceMethod);
}

{
    MethodBase ctorMethod = typeof(TestClass).GetConstructor(new Type[] { });
    MethodInfo newCtorMethod = typeof(Program).GetMethod("MyCtor");
    ReplaceMethod.Replace(ctorMethod, newCtorMethod);
}

// 메서드를 사용
TestClass testClass = new TestClass();
testClass.TestMethod();}

만약, 저 순서를 바꾸면 가로채기가 안 됩니다.




하지만, 저렇게 했는데도 여전히 "매개변수 없는 생성자"의 호출이 가로채기가 안 되는 것을 볼 수 있습니다. 재미있게도, .NET 5 ~ 8의 경우 (.NET Framework과는 달리) "매개변수 없는 생성자"도 MethodDesc의 구조체에 함수 포인터를 보관하는 방식으로 사용하기 때문입니다.

따라서, 그 부분의 소스 코드도 다음과 같이 변경해 주면 됩니다.

public unsafe static void Replace(MethodBase oldMethod, MethodInfo newMethod)
{
    RuntimeHelpers.PrepareMethod(newMethod.MethodHandle);

    IntPtr oldMethodPos = IntPtr.Zero;

#if !NET5_0_OR_GREATER
    if (oldMethod.IsConstructor && oldMethod.GetParameters().Length == 0)
    {
        oldMethodPos = FromMethodTable(oldMethod);
    }
    else
#endif
    {
        oldMethodPos = FromMethodDesc(oldMethod);
    }

    if (oldMethodPos == IntPtr.Zero)
    {
        throw new InvalidOperationException("Failed to get method position.");
    }

    IntPtr newFuncAddr = newMethod.MethodHandle.GetFunctionPointer();
        
    if (IntPtr.Size == 8)
    {
        ulong* ptr = (ulong*)oldMethodPos;
        *ptr = (ulong)newFuncAddr.ToInt64();
    }
    else
    {
        uint* ptr = (uint*)oldMethodPos;
        *ptr = (uint)newFuncAddr.ToInt32();
    }
}

이제 다시 (x86/x64 상관없이) 실행해 보면,

using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;

internal class Program
{
    static void Main(string[] args)
    {
        // 아래의 코드를 주석 해제하면, 가로채기가 안 됩니다.
        //{
        //    TestClass testClass = new TestClass();
        //    testClass.TestMethod();
        //}

        {
            MethodInfo? instanceMethod = typeof(TestClass).GetMethod("TestMethod");
            MethodInfo? newInstanceMethod = typeof(Program).GetMethod("MyMethod");

            ReplaceMethod.Replace(instanceMethod, newInstanceMethod);
        }

        {
            MethodBase? ctorMethod = typeof(TestClass).GetConstructor(new Type[] { });
            MethodInfo? newCtorMethod = typeof(Program).GetMethod("MyCtor");

            ReplaceMethod.Replace(ctorMethod, newCtorMethod);
        }

        {
            TestClass testClass = new TestClass();
            testClass.TestMethod();
        }
    }

    public void MyMethod()
    {
        Console.WriteLine("MyMethod called! (replaced)");
    }

    public void MyCtor()
    {
        Console.WriteLine("MyCtor called! (replaced)");
    }
}

public class TestClass
{
    string _name = "TestClass";

    public TestClass()
    {
        Console.WriteLine("TestClass constructor");
    }

    public TestClass(string name)
    {
        Console.WriteLine("TestClass constructor2");
        _name = name;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    public void TestMethod()
    {
        Console.WriteLine("Instance TestMethod");
    }

    public static void TestMethod2()
    {
        Console.WriteLine("Static TestMethod2");
    }
}

화면에는, 정상적으로 가로채기가 된 결과가 나옵니다.

MyCtor called! (replaced)
MyMethod called! (replaced)

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




만약, 한 번이라도 실행된 적이 있는 메서드에 대해 가로채기를 하고 싶다면 2가지 정도의 방법을 고려할 수 있습니다.

첫 번째로, 호출이 되는 "jmp ..." 명령어의 주소를 읽어 가로챌 대상 메서드의 주소로 offset 값을 계산하여 덮어쓰는 방법입니다. 물론, (원하는) 모든 호출 측 코드를 가로채야 하는 한다면 이는 매우 귀찮은 방법입니다.

두 번째로, "jmp ..." 대상 위치가 되는 Jitted Address의 초입 부분을 trampoline 기법으로 덮어쓰는 방법입니다. (이 과정에서 SharpDisasm을 쓰면 편리합니다.)

방법이야 그렇지만, 2가지 모두 이번 글의 방식에 비해서는 매우 귀찮은 작업임에는 틀림없습니다.




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







[최초 등록일: ]
[최종 수정일: 4/9/2025]

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

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  38  39  40  41  42  43  44  [45]  ...
NoWriterDateCnt.TitleFile(s)
12810정성태8/27/202115443.NET Framework: 1107. .NET Core/5+에서 동적 컴파일한 C# 코드를 (Breakpoint도 활용하며) 디버깅하는 방법 - #line 지시자파일 다운로드1
12809정성태8/26/202115425.NET Framework: 1106. .NET Core/5+에서 C# 코드를 동적으로 컴파일/사용하는 방법 [1]파일 다운로드1
12808정성태8/25/202117037오류 유형: 758. go: ...: missing go.sum entry; to add it: go mod download ...
12807정성태8/25/202117824.NET Framework: 1105. C# 10 - (9) 비동기 메서드가 사용할 AsyncMethodBuilder 선택 가능파일 다운로드1
12806정성태8/24/202114379개발 환경 구성: 601. PyCharm - 다중 프로세스 디버깅 방법
12805정성태8/24/202116086.NET Framework: 1104. C# 10 - (8) 분해 구문에서 기존 변수의 재사용 가능파일 다운로드1
12804정성태8/24/202116261.NET Framework: 1103. C# 10 - (7) Source Generator V2 APIs
12803정성태8/23/202116753개발 환경 구성: 600. pip cache 디렉터리 옮기는 방법
12802정성태8/23/202117183.NET Framework: 1102. .NET Conf Mini 21.08 - WinUI 3 따라해 보기 [1]
12801정성태8/23/202116761.NET Framework: 1101. C# 10 - (6) record class 타입의 ToString 메서드를 sealed 처리 허용파일 다운로드1
12800정성태8/22/202117143개발 환경 구성: 599. PyCharm - (반대로) 원격 프로세스가 PyCharm에 디버그 연결하는 방법
12799정성태8/22/202117413.NET Framework: 1100. C# 10 - (5) 속성 패턴의 개선파일 다운로드1
12798정성태8/21/202118776개발 환경 구성: 598. PyCharm - 원격 프로세스를 디버그하는 방법
12797정성태8/21/202116135Windows: 197. TCP의 MSS(Maximum Segment Size) 크기는 고정된 것일까요?
12796정성태8/21/202117137.NET Framework: 1099. C# 10 - (4) 상수 문자열에 포맷 식 사용 가능파일 다운로드1
12795정성태8/20/202117454.NET Framework: 1098. .NET 6에 포함된 신규 BCL API - 스레드 관련
12794정성태8/20/202116849스크립트: 23. 파이썬 - WSGI를 만족하는 최소한의 구현 코드 및 PyCharm에서의 디버깅 방법 [1]
12793정성태8/20/202117638.NET Framework: 1097. C# 10 - (3) 개선된 변수 초기화 판정파일 다운로드1
12792정성태8/19/202118713.NET Framework: 1096. C# 10 - (2) 전역 네임스페이스 선언파일 다운로드1
12791정성태8/19/202115568.NET Framework: 1095. C# COM 개체를 C++에서 사용하는 예제 [3]파일 다운로드1
12790정성태8/18/202119489.NET Framework: 1094. C# 10 - (1) 구조체를 생성하는 record struct파일 다운로드1
12789정성태8/18/202118166개발 환경 구성: 597. PyCharm - 윈도우 환경에서 WSL을 이용해 파이썬 앱 개발/디버깅하는 방법
12788정성태8/17/202115693.NET Framework: 1093. C# - 인터페이스의 메서드가 다형성을 제공할까요? (virtual일까요?)파일 다운로드1
12787정성태8/17/202116082.NET Framework: 1092. (책 내용 수정) "4.5.1.4 인터페이스"의 "인터페이스와 다형성"
12786정성태8/16/202118012.NET Framework: 1091. C# - Python range 함수 구현 (2) INumber<T>를 이용한 개선 [1]파일 다운로드1
12785정성태8/16/202116479.NET Framework: 1090. .NET 6 Preview 7에 추가된 숫자 형식에 대한 제네릭 연산 지원 [1]파일 다운로드1
... 31  32  33  34  35  36  37  38  39  40  41  42  43  44  [45]  ...