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)
13532정성태1/17/20242188닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242233닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242188닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242048닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242160Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242105오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242202닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242156오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242214오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242026오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242187닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242253닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20241985오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242078닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242349닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242196스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242300닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242579닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242253개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242162닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242126개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242145닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242081닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242104오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242110오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242787닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...