성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - NonGC(FOH) 영역에 .NET 개체를 생성</h1> <p> 지난 글에서,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# - Native 메모리에 .NET 개체를 생성 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/13537'>https://www.sysnet.pe.kr/2/0/13537</a> </pre> <br /> .NET 개체를 임의로 네이티브 메모리에 생성하는 방법을 알아봤는데요, 재미있는 건 마이크로소프트도 이미 저 방식을 CLR 내부에서 사용하고 있었다는 점입니다. 그런 의미에서 FOH를 다시 한번 읽어보시면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > .NET 8 - NonGC Heap / FOH (Frozen Object Heap) ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/13536'>https://www.sysnet.pe.kr/2/0/13536</a> </pre> <br /> 이번엔 새롭게 해석이 될 것입니다. 그리고 저 2개의 글을 이해하셨다면, 이제 아래의 글이 더욱 재미있을 것입니다. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Exploring .NET frozen segments ; <a target='tab' href='https://minidump.net/exploring-frozen-segments/'>https://minidump.net/exploring-frozen-segments/</a> </pre> <br /> 현재 FOH는 마이크로소프트 내부에서만 사용하고 있을 텐데, 위의 글에서는 숨겨져 있는 메서드를 사용해 우리도 FOH를 등록/해제할 수 있는 방법을 소개하고 있습니다.<br /> <br /> 핵심은 공개되지 않은 메서드 2개인데요, 따라서 현재는 Reflection으로 이렇게 감싸야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System.Reflection; namespace ConsoleApp1; internal class GCExtension { internal static IntPtr RegisterFrozenSegment(IntPtr sectionAddress, nint sectionSize) { return (IntPtr)typeof(GC).GetMethod("<span style='color: blue; font-weight: bold'>_RegisterFrozenSegment</span>", BindingFlags.NonPublic | BindingFlags.Static)! .Invoke(null, [sectionAddress, sectionSize])!; } internal static void UnregisterFrozenSegment(IntPtr segment) { typeof(GC).GetMethod("<span style='color: blue; font-weight: bold'>_UnregisterFrozenSegment</span>", BindingFlags.NonPublic | BindingFlags.Static)! .Invoke(null, [segment]); } } </pre> <br /> 그럼 ^^ 위의 메서드를 이용해서 지난 글에서처럼 닷넷 개체를 FOH에 등록해 볼까요? 이번엔 MyObject 사용자 개체 대신 문자열을 생성해 볼 텐데요, 코드는 다음과 같이 정리할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // <a target='tab' href='https://minidump.net/exploring-frozen-segments/'>https://minidump.net/exploring-frozen-segments/</a> public class StringExtension { public static int GetAllocatedStringSize(ReadOnlySpan<char> data) { int headerSize = IntPtr.Size + IntPtr.Size + sizeof(int); // object header + method-table ptr + len(string) return headerSize + ((data.Length + 1) * sizeof(char)); } public static unsafe string AllocateString(void* address, ReadOnlySpan<char> data) { var ptr = (byte*)address; // Write the header *(nint*)ptr = 0; ptr += sizeof(nint); // Retrieve the method-table pointer var mt = typeof(string).TypeHandle.Value; // Write it *(nint*)ptr = mt; ptr += sizeof(nint); *(int*)ptr = data.Length; ptr += sizeof(int); var destination = new Span<char>(ptr, data.Length + 1); data.CopyTo(destination); destination[^1] = '\0'; var strRef = (nint)address + sizeof(nint); return Unsafe.As<nint, string>(ref strRef); } } </pre> <br /> 이를 이용해 네이티브 메모리를 할당한 후 문자열 복사를 다음과 같이 할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > string text = new string('c', short.MaxValue * 2); int objectSize = StringExtension.GetAllocatedStringSize(text); /* NativeMemory.AlignedAlloc The current design of CoreCLR's FrozenObjectHeapManager has certain design limitations such as: * Large objects are not supported. * Objects requiring unusual data alignment are not supported. */ var allocated = <a target='tab' href='https://www.sysnet.pe.kr/2/0/13477#aligned_alloc'>NativeMemory.AlignedAlloc</a>((nuint)objectSize, (nuint)IntPtr.Size); NativeMemory.Clear(allocated, (nuint)objectSize); // textOnNative == 네이티브 메모리에 보관한 문자열 개체 string textOnNative = StringExtension.AllocateString(allocated, text); </pre> <br /> 마지막으로, 저렇게 구성한 네이티브 메모리를 FOH에 등록만 해주면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > <span style='color: blue; font-weight: bold'>var segment = GCExtension.RegisterFrozenSegment((IntPtr)allocated, objectSize);</span> fixed (char* ptr = textOnNative) { Console.WriteLine($"address of text: {(nint)ptr:x}"); } Console.WriteLine($"address of AlignedAlloc: {(nint)allocated:x}"); Console.WriteLine($"address of FOH: {segment:x}"); Console.WriteLine("Press any key to exit..."); Console.ReadLine(); <span style='color: blue; font-weight: bold'>GCExtension.UnregisterFrozenSegment(segment);</span> </pre> <br /> 실행 시 중간에 넣어둔 출력 결과가 이렇게 나오고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > address of text: 1e48045f18c address of AlignedAlloc: <span style='color: blue; font-weight: bold'>1e48045f178</span> address of FOH: <span style='color: blue; font-weight: bold'>1e4e3b2d9d0</span> </pre> <br /> 이와 함께 Console.ReadLine으로 걸렸을 때 windbg로 연결하면 이런 결과가 나옵니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 0:014> <span style='color: blue; font-weight: bold'>!eeheap</span> ...[생략]... ======================================== Number of GC Heaps: 1 ---------------------------------------- Small object heap <span style='color: blue; font-weight: bold'>segment</span> <span style='color: blue; font-weight: bold'>begin</span> allocated committed allocated size committed size generation 0: 0224f990f320 01e4e8400028 01e4e841f0e0 01e4e8421000 0x1f0b8 (127160) 0x21000 (135168) generation 1: 0224f990f270 01e4e8000028 01e4e8000028 01e4e8001000 0x1000 (4096) generation 2: 0224f990f1c0 01e4e7c00028 01e4e7c00028 01e4e7c01000 0x1000 (4096) Frozen object heap segment begin allocated committed allocated size committed size 01e4e3aa7620 01e480000008 01e480003d30 01e480010000 0x3d28 (15656) 0x10000 (65536) <span style='color: blue; font-weight: bold'>01e4e3b2d9d0</span> <span style='color: blue; font-weight: bold'>01e48045f180</span> 01e48047f18a 01e48047f18a 0x2000a (131082) 0x20012 (131090) Large object heap segment begin allocated committed allocated size committed size 0224f990f3d0 01e4e8800028 01e4e8820060 01e4e8821000 0x20038 (131128) 0x21000 (135168) Pinned object heap segment begin allocated committed allocated size committed size 0224f990ec40 01e4e5c00028 01e4e5c07ff0 01e4e5c11000 0x7fc8 (32712) 0x11000 (69632) ------------------------------ GC Allocated Heap Size: Size: 0x6adea (437738) bytes. GC Committed Heap Size: Size: 0x85012 (544786) bytes. Total bytes consumed by CLR: 0x39c012 (3784722) </pre> <br /> 우리가 출력한 "address of FOH"의 값이 segment 칼럼 값에 해당하고, "address of AlignedAlloc"에 +8을 한 값이 "begin" 칼럼으로 사용되고 있습니다. 그러니까, Object Header를 넘어서 Method Table을 가리키는 첫 번째 개체의 위치를 "begin"으로 나타내고 있는 것입니다.<br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=2137&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> <br /> <hr style='width: 50%' /><br /> <br /> FOH의 특성상 불멸 객체만 담아둔다고 했는데요, 따라서 관리 개체의 메모리 구조만 맞춰서 저렇게 만들어 두면 GC의 영향도 받지 않으니 속도 향상에 나름 기여할 수 있습니다. 게다가 이를 기반으로 FOH 영역임을 런타임에서 인식할 수 있다면 RyuJit의 입장에서도 그 영역에 담긴 개체들은 불멸할 것임을 보증 받을 수 있으므로 코드 생성에 유리했을 것으로 추측이 됩니다.<br /> <br /> 그런데, 그런 의도와는 다르게 _RegisterFrozenSegment와 함께 _UnregisterFrozenSegment까지 만들어 두었다는 것이 재미있습니다. 물론 Unregister를 해도 영향은 없을 것입니다. 중요한 것은 네이티브 메모리를 해제만 하지 않으면 되기 때문인데, 어쨌든 닷넷 런타임 측에서도 아마 프로세스 종료 시점에나 Unregister/Free를 같이 하는 식이지 않을까 싶습니다.<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
2049
(왼쪽의 숫자를 입력해야 합니다.)