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)
13370정성태6/14/20233288개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233085개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233222개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233321오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233111.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232884오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233665.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233233스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233153.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233611오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233022오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233343오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233635.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233457.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233752DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233664.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20233941.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233546.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234055VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233318오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233643.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233566.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20233924.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233771오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235026.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236306.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...