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)
13507정성태1/2/20242787닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232357닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232904닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232480닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232349Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232445닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232261개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232327디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233011닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232429오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232413Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232379Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232524Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232616닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232304개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232240Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232362개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232146개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232078오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232394개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232209개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232093오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232169개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232309닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232893닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232279개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...