Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요?

지난 글에 설명한 Unsafe.AsPointer가,

C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/13017

과연 해당 메모리를 pinning 시킬까요? 사실 저도 지난 글을 쓸 때 그 점을 염두에 두지 않았습니다. (좋은 질문을 해주셔서 이렇게 보완하는 글을 쓰게 되었습니다. ^^)

일단, 얼핏 보고... 판단할 수는 있습니다. fixed의 경우 block이 정해져 있기 때문에 pinning 시킨 메모리의 유효 범위가 결정됩니다. 하지만, Unsafe.AsPointer의 경우에는 해당 포인터가 pinning 되었다면 언제 pinning을 해제해야 할지에 대한 표시가 없습니다. 그런 의미에서, 아마도 Unsafe.AsPointer는 pinning 시키지 않았을 거라고 짐작할 수 있습니다.

간단한 예제를 통해 눈으로도 확인할 수 있습니다.

using System.Runtime.CompilerServices;

class Program
{
    public int value = 27;

    static unsafe void Main(string[] args)
    {
        AllocGarbage();

        Program pg = new Program();
        Program pg2 = new Program();

        WriteAddress("Unsafe.AsPointer", pg);
        WriteAddress("fixed", pg2);

        void* ptr2 = Unsafe.AsPointer(ref pg.value);
        fixed (void* ptr = &pg2.value)
        {
            GC.Collect();
            GC.Collect();
        }

        Console.WriteLine("... gced ...");

        WriteAddress("Unsafe.AsPointer", pg);
        WriteAddress("fixed", pg2);
    }

    private static unsafe void WriteAddress(string title, Program pg)
    {
        void* ptr = Unsafe.AsPointer(ref pg.value);
        IntPtr p = new IntPtr(ptr);

        Console.Write($"{title} ");
        Console.WriteLine(p.ToString("x"));
    }

    private static void AllocGarbage()
    {
        for (int i = 0; i < 10000; i++)
        {
            int[] values = new int[1024];
        }
    }
}

위와 같이 GC가 되었을 경우 메모리가 이동하도록 코드를 구성한 다음, Unsafe.AsPointer의 대상이었던 pg 인스턴스와, fixed의 대상이었던 pg2 인스턴스의 메모리 포인터를 비교해 보면 됩니다.

실행해 보면, 대충 이런 출력 결과를 얻을 수 있습니다.

Unsafe.AsPointer: 2a0a4da7098
fixed: 2a0a4da70b0
... gced ...
Unsafe.AsPointer: 2a0a4da45e8
fixed: 2a0a4da70b0

보시면, Unsafe.AsPointer로 처리한 pg 인스턴스는 이동이 되어 메모리 위치가 바뀐 반면, fixed의 경우에는 바뀌지 않았습니다.




그런데, 갑자기 궁금해졌습니다. pinning 여부가 도대체 어떻게 결정되는 걸까요?

우선, Unsafe.AsPointer의 소스 코드는 이렇습니다.

Unsafe.il
; https://github.com/DotNetCross/Memory.Unsafe/blob/master/src/DotNetCross.Memory.Unsafe/Unsafe.il

.method public hidebysig static void* AsPointer<T>(!!T& 'value') cil managed aggressiveinlining
{
    .custom instance void System.Runtime.Versioning.NonVersionableAttribute::.ctor() = ( 01 00 00 00 )
    .maxstack 1
    ldarg.0
    conv.u
    ret
} // end of method Unsafe::AsPointer

여기서 재미있는 건, 사실 fixed의 IL 코드도 저것과 완전히 동일하다는 점입니다. 가령 다음과 같이 코딩을 한 후,

class Program
{
    public int value = 27;

    static unsafe void Main(string[] args)
    {
        Program pg = new Program();

        fixed (void* ptr = &pg.value)
        {
        }
    }
}

IL 코드로 보면,

.maxstack 1
.entrypoint
.locals init (
    [0] class Program pg,
    [1] void* ptr,
    [2] int32& pinned
)

/* 0x000002A0 00           */ IL_0000: nop  // Fills space if opcodes are patched. No meaningful operation is performed although a processing cycle can be consumed.
/* 0x000002A1 7306000006   */ IL_0001: newobj    instance void Program::.ctor() // Creates a new object or a new instance of a value type, pushing an object reference (type O) onto the evaluation stack.
/* 0x000002A6 0A           */ IL_0006: stloc.0  // Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 0.
/* 0x000002A7 06           */ IL_0007: ldloc.0  // Loads the local variable at index 0 onto the evaluation stack.
/* 0x000002A8 7C03000004   */ IL_0008: ldflda    int32 Program::'value' // Finds the address of a field in the object whose reference is currently on the evaluation stack.
/* 0x000002AD 0C           */ IL_000D: stloc.2  // Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 2.

/* 0x000002AE 08           */ IL_000E: ldloc.2  // Loads the local variable at index 2 onto the evaluation stack.
/* 0x000002AF E0           */ IL_000F: conv.u   // Converts the value on top of the evaluation stack to unsigned native int, and extends it to native int.
/* 0x000002B0 0B           */ IL_0010: stloc.1  // Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 1.

/* 0x000002B1 00           */ IL_0011: nop  // Fills space if opcodes are patched. No meaningful operation is performed although a processing cycle can be consumed.
/* 0x000002B2 00           */ IL_0012: nop  // Fills space if opcodes are patched. No meaningful operation is performed although a processing cycle can be consumed.
/* 0x000002B3 16           */ IL_0013: ldc.i4.0 // Pushes the integer value of 0 onto the evaluation stack as an int32.
/* 0x000002B4 E0           */ IL_0014: conv.u   // Converts the value on top of the evaluation stack to unsigned native int, and extends it to native int.
/* 0x000002B5 0C           */ IL_0015: stloc.2  // Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 2.
/* 0x000002B6 2A           */ IL_0016: ret  // Returns from the current method, pushing a return value (if present) from the callee's evaluation stack onto the caller's evaluation stack.

단순히, conv.u 연산을 해 void* 변수에 넣는 것이 전부입니다. 그런데, 어떻게 저것이 fixed 블록에 의해 pinning 되는 걸까요? 그 이유는, 로컬 변수 중 pinned 특성이 지정된 특별한 변수 때문입니다.

.locals init (
    [0] class Program pg,
    [1] void* ptr,
    [2] int32& pinned
)

IL 코드를 보면, pg2 인스턴스를 저 pinned 특성이 적용된 [2]번 로컬 변수에 저장하는 코드가 나옵니다.

/* 0x000002A8 7C03000004   */ IL_0008: ldflda    int32 Program::'value' // Finds the address of a field in the object whose reference is currently on the evaluation stack.
/* 0x000002AD 0C           */ IL_000D: stloc.2  // Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 2.

그런 다음, fixed 블록이 끝나는 지점에 단순히 [2]번 로컬 변수에 null을 대입해 pg2 인스턴스에 대한 참조를 해제합니다.

/* 0x000002B3 16           */ IL_0013: ldc.i4.0 // Pushes the integer value of 0 onto the evaluation stack as an int32.
/* 0x000002B4 E0           */ IL_0014: conv.u   // Converts the value on top of the evaluation stack to unsigned native int, and extends it to native int.
/* 0x000002B5 0C           */ IL_0015: stloc.2  // Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 2.

예상할 수 있듯이, Unsafe.AsPointer를 사용한 경우에는 void* 변수는 있지만, pinned 특성이 적용된 변수는 없습니다.




정리해 보면, Unsafe.AsPointer는 스택에 위치한 로컬 변수에 대해서만 안전한 포인터 위치를 반환합니다. 반면, 힙에 위치한 인스턴스의 경우, 즉 위의 예제에서처럼 pg.value를 Unsafe.AsPointer에 전달하는 것은 이후 사용을 조심해야 합니다. 왜냐하면, Unsafe.AsPointer를 호출한 시점의 pg.value가 위치한 주소를 반환은 하겠지만, 이후 그 포인터를 사용하는 사이 GC가 발생한다면 해당 참조 인스턴스는 메모리가 이동할 수 있기 때문입니다. 따라서, 힙에 할당된 인스턴스에 Unsafe.AsPointer를 사용하고 싶다면, 단순히 디버깅이나 간단한 테스트 용도의 목적 정도로만 한정해야 합니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/1/2022]

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

비밀번호

댓글 작성자
 



2022-03-30 03시41분
[guest] 고정이 안되는걸 알고 질문드린건데 무슨차이로 인해 고정이 되고 안되는건지가 궁금했었거든요 오늘도 한수 배워갑니다 ^^
[guest]
2022-03-30 03시48분
[guest] 저런 매커니즘이라면 void DoSomething(Action<Intptr>) 형식의 Dynamicmethod를 빌드하여 사용하면 .net framework (7.0) 에서도 안정적인 pinning이 가능할듯하네요.
[guest]
2022-03-30 04시06분
[guest] void DoSomething<T>(T source, Action<Intptr> action) 이런식으로 DynamicMethod를 짜면 될것 같습니다. 개인적으로 ref 필드를 ref 없이 바꿀순 없을까? 라고 고민해본게 lambda 안에서 ref 로 넘겨야할때였는데요 이 방법으로 가능할지 내일 테스트 해봐야겠네요.
[guest]
2022-03-30 10시59분
@손님 테스트 결과가 기대되는군요. ^^ 개인적으로는, "저런 메커니즘"과 void DoSomething(Action<Intptr>) 형식의 DynamicMethod 간에 어떤 점으로 인해 pinning이 가능하다고 생각하는지 상상은 안 가지만...
정성태
2022-03-30 06시24분
[guest] 테스트 결과는 성공적이네요. 글을 올릴데가 없어서 질문 답변 게시판에 간단하게 인증샷 첨부했습니다.

https://www.sysnet.pe.kr/3/0/5635
[guest]

1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...
NoWriterDateCnt.TitleFile(s)
13249정성태2/7/20234949오류 유형: 842. 리눅스 - You must wait longer to change your password
13248정성태2/7/20234052오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/20234966VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/20234096개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20234643.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20234003VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20234862디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234307디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20233831디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20233988디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233632디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20235649.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235337.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20234975개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234526개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235565개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20236914오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234718스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233624오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234035개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20234985.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235121.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20234833개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234518.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20233759개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234119Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...