Microsoft MVP성태의 닷넷 이야기
닷넷: 2331. C# - 실행 시에 메서드 가로채기 (.NET 9) [링크 복사], [링크+제목 복사],
조회: 1642
글쓴 사람
정성태 (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 9)

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

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

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

언급했듯이 기존 소스 코드로는 .NET 9 환경에서 가로채기가 안 됩니다. 일단, 어떻게 되는지 현상만을 먼저 살펴볼까요? ^^

using System.Diagnostics;
using System.Reflection;

internal class Program
{
    static void Main(string[] args)
    {
        {
            MethodInfo? instanceMethod = typeof(MyClass).GetMethod("MyMethod");
            MethodInfo? newInstanceMethod = typeof(Program).GetMethod("MyMethod");

            ReplaceMethod.Replace(instanceMethod, newInstanceMethod);
        }

        MyClass cl = new MyClass();
        cl.MyMethod();
    }

    public void MyMethod()
    {
        Console.WriteLine("Program.MyMethod");
    }
}

public class MyClass
{
    public void MyMethod()
    {
        Console.WriteLine("MyClass.MyMethod");
    }
}

위의 코드를 실행하면, (메서드 가로채기가 안 된) 이런 출력을 얻게 되는데요,

MyClass.MyMethod

심지어, 메서드 호출을 미뤄 JIT 컴파일을 하지 않은 상태로 바꾸게 되면,

static void Main(string[] args)
{
    // ...[생략]....
    ReplaceMethod.Replace(instanceMethod, newInstanceMethod);

    CallMethod(); // Main 메서드 호출 시에 MethodDesc를 이용한 JIT 컴파일이 발생하지 않도록 별도의 메서드로 분리
}

private static void CallMethod()
{
    MyClass cl = new MyClass();
    cl.MyMethod();
}

이제는 실행 시점에 예외가 발생하고,

Fatal error. Internal CLR error. (0x80131506)
   at Program.Main(System.String[])

Visual Studio로 디버깅하면 아예 CallMethod의 내부로 진입조차 하지 못하고 이런 예외가 발생하는 것을 확인할 수 있습니다.

System.ExecutionEngineException
  HResult=0x80131506
  Message=Exception of type 'System.ExecutionEngineException' was thrown.

뭔가 많이 바뀌었다는 것이겠죠? ^^;




뭐가 어떻게 변했는지 한번 볼까요? ^^ 이를 위해 다음과 같은 예제를 만들고,

internal class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(IntPtr.Size);
        {
            var mi = typeof(MyClass).GetMethod("MyMethod");
            ReplaceMethod.PrintMethodDescInfo(mi); // MethodDesc 포인터가 가리키는 내용을 총 24바이트 출력
        }
        Console.WriteLine();

        Console.ReadLine(); // WinDbg 연결을 위한 대기

        MyClass cl = new MyClass();
        cl.MyMethod();
    }
}

public class  MyClass
{
    public void MyMethod()
    {
        Console.WriteLine("MyClass.MyMethod");
    }
}

실행하면 이런 출력을 볼 수 있습니다.

MethodDesc: 0x7ffa99896338
        7033004 280005 7ffa99896e90 7ffa99882250
        FuncPtr: 0x7ffa99882250

.NET 8과는 달리 3번째 QWORD 위치에 GetFunctionPointer()가 반환하는 그 주솟값(7ffa99882250)이 들어가 있습니다. 한 가지 더 재미있는 건, 두 번째 QWORD가 가리키는 내용에도,

0:007> dq 00007ffa`99896e90 L2
00007ffa`aa5eb448  00000000`00000000 00007ffa`99882250

마찬가지로 GetFunctionPointer()의 주솟값을 담고 있습니다. 그렇다면 둘 다 바꿔줘야 하는 걸까요? 까짓 거 어려운 일도 아닌데 금방 해보면 될 일입니다. ^^




그 결과, MethodDesc의 3번째 QWORD 값만 바꿔주면 정상적으로 가로채기가 됐습니다. 따라서 다음과 같은 정도만 기존의 Replace 메서드에 추가하면 되고,

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 NET9_0_OR_GREATER
    {
        ulong* ptr = (ulong*)oldMethodPos;
        ptr += 1; // move to 3rd QWORD of MethodDesc
        oldMethodPos = new IntPtr(ptr);
    }
#endif

    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();
    }
}

테스트는 .NET 8에서와 동일하게 다음과 같이 할 수 있습니다.

using System.Diagnostics;
using System.Reflection;

internal class Program
{
    static void Main(string[] args)
    {
        // MyClass cl = new MyClass(); // 이 코드를 주석 해제하면 가로채기가 안 됨
        // cl.MyMethod();

        {
            var instanceMethod = typeof(MyClass).GetConstructor(new Type[] { });
            var newInstanceMethod = typeof(Program).GetMethod("MyCtor");

            ReplaceMethod.Replace(instanceMethod, newInstanceMethod);
        }

        {
            var instanceMethod = typeof(MyClass).GetMethod("MyMethod");
            var newInstanceMethod = typeof(Program).GetMethod("MyMethod");

            ReplaceMethod.Replace(instanceMethod, newInstanceMethod);
        }

        MyClass cl2 = new MyClass();
        cl2.MyMethod();
    }

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

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

public class MyClass
{
    public MyClass()
    {
        Console.WriteLine("MyClass ctor");
    }

    public void MyMethod()
    {
        Console.WriteLine("MyClass.MyMethod");
    }
}

/* 실행 결과:
MyCtor called! (replaced)
Program.MyMethod (replaced)
*/

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




지금까지 .NET 4.8부터 시작해 .NET 5 ~ 8, 그리고 .NET 9까지 메서드 가로채기 방법을 살펴봤는데요, 이 정도면 눈치채셨겠지만 이런 식의 가로채기 기법은 언제든 변할 수 있으므로 현업에서 안정적으로 사용하기에는 무리가 있습니다. 따라서, 그냥 이해 정도의 차원에서만 알아두시길 권장합니다. ^^




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







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

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)
13718정성태8/27/20247401오류 유형: 921. Visual C++ - error C1083: Cannot open include file: 'float.h': No such file or directory [2]
13717정성태8/26/20247007VS.NET IDE: 192. Visual Studio 2022 - Windows XP / 2003용 C/C++ 프로젝트 빌드
13716정성태8/21/20246741C/C++: 167. Visual C++ - 윈도우 환경에서 _execv 동작 [1]
13715정성태8/19/20247335Linux: 78. 리눅스 C/C++ - 특정 버전의 glibc 빌드 (docker-glibc-builder)
13714정성태8/19/20246720닷넷: 2295. C# 12 - 기본 생성자(Primary constructors) (책 오타 수정) [3]
13713정성태8/16/20247430개발 환경 구성: 721. WSL 2에서의 Hyper-V Socket 연동
13712정성태8/14/20247199개발 환경 구성: 720. Synology NAS - docker 원격 제어를 위한 TCP 바인딩 추가
13711정성태8/13/20248047Linux: 77. C# / Linux - zombie process (defunct process) [1]파일 다운로드1
13710정성태8/8/20247963닷넷: 2294. C# 13 - (6) iterator 또는 비동기 메서드에서 ref와 unsafe 사용을 부분적으로 허용파일 다운로드1
13709정성태8/7/20247734닷넷: 2293. C# - safe/unsafe 문맥에 대한 C# 13의 (하위 호환을 깨는) 변화파일 다운로드1
13708정성태8/7/20247522개발 환경 구성: 719. ffmpeg / YoutubeExplode - mp4 동영상 파일로부터 Audio 파일 추출
13707정성태8/6/20247753닷넷: 2292. C# - 자식 프로세스의 출력이 4,096보다 많은 경우 Process.WaitForExit 호출 시 hang 현상파일 다운로드1
13706정성태8/5/20247867개발 환경 구성: 718. Hyper-V - 리눅스 VM에 새로운 디스크 추가
13705정성태8/4/20248138닷넷: 2291. C# 13 - (5) params 인자 타입으로 컬렉션 허용 [2]파일 다운로드1
13704정성태8/2/20248095닷넷: 2290. C# - 간이 dotnet-dump 프로그램 만들기파일 다운로드1
13703정성태8/1/20247422닷넷: 2289. "dotnet-dump ps" 명령어가 닷넷 프로세스를 찾는 방법
13702정성태7/31/20247819닷넷: 2288. Collection 식을 지원하는 사용자 정의 타입을 CollectionBuilder 특성으로 성능 보완파일 다운로드1
13701정성태7/30/20248089닷넷: 2287. C# 13 - (4) Indexer를 이용한 개체 초기화 구문에서 System.Index 연산자 허용파일 다운로드1
13700정성태7/29/20247685디버깅 기술: 200. DLL Export/Import의 Hint 의미
13699정성태7/27/20248222닷넷: 2286. C# 13 - (3) Monitor를 대체할 Lock 타입파일 다운로드1
13698정성태7/27/20248178닷넷: 2285. C# - async 메서드에서의 System.Threading.Lock 잠금 처리파일 다운로드1
13697정성태7/26/20247903닷넷: 2284. C# - async 메서드에서의 lock/Monitor.Enter/Exit 잠금 처리파일 다운로드1
13696정성태7/26/20247439오류 유형: 920. dotnet publish - error NETSDK1047: Assets file '...\obj\project.assets.json' doesn't have a target for '...'
13695정성태7/25/20247420닷넷: 2283. C# - Lock / Wait 상태에서도 STA COM 메서드 호출 처리파일 다운로드1
13694정성태7/25/20247886닷넷: 2282. C# - ASP.NET Core Web App의 Request 용량 상한값 (Kestrel, IIS)
13693정성태7/24/20247218개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법파일 다운로드1
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...