성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 그냥 RSS Reader 기능과 약간의 UI 편의성 때문에 사용...
[이종효] 오래된 소프트웨어는 보안 위협이 되기도 합니다. 혹시 어떤 기능...
[정성태] @Keystroke IEEE의 문서를 소개해 주시다니... +_...
[손민수 (Keystroke)] 괜히 듀얼채널 구성할 때 한번에 같은 제품 사라고 하는 것이 아...
[정성태] 전각(Full-width)/반각(Half-width) 기능을 토...
[정성태] Vector에 대한 내용은 없습니다. Vector가 닷넷 BCL...
[orion] 글 읽고 찾아보니 디자인 타임에는 InitializeCompon...
[orion] 연휴 전에 재현 프로젝트 올리자 생각해 놓고 여의치 않아서 못 ...
[정성태] 아래의 글에 정리했으니 참고하세요. C# - Typed D...
[정성태] 간단한 재현 프로젝트라도 있을까요? 저런 식으로 설명만 해...
글쓰기
제목
이름
암호
전자우편
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# - VMMap처럼 스택 메모리의 reserve/guard/commit 상태 출력</h1> <p> 아래는 <a target='tab' href='https://learn.microsoft.com/en-us/sysinternals/downloads/vmmap'>VMMap 도구</a>로 .NET 7 콘솔 프로그램의 Main 메서드를 수행한 스레드 스택에 대한 가상 메모리 상태를 보여줍니다.<br /> <br /> <img onclick='toggle_img(this)' class='imgView' alt='thread_vmm_1.png' src='/SysWebRes/bbs/thread_vmm_1.png' /><br /> <br /> 혹시, 저 상황을 우리도 구할 수 있을까요? ^^<br /> <br /> 이를 위해 우선 구해야 할 값이 (위의 화면에서는 0xB133A00000에 해당하는) 스택의 가상 메모리 시작 주소를 알아내야 합니다. 비록 정확한 시작 주소를 알 수는 없지만, 우리는 스택 주소 범위 내의 주솟값을 ESP/RSP 레지스터를 통해 구할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 닷넷에서 ESP/RSP 레지스터 값을 구하는 방법 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/13172'>https://www.sysnet.pe.kr/2/0/13172</a> </pre> <br /> 하지만, 저렇게 복잡하게 구하지 않아도 (unsafe 예약어를 적용한) 메서드에 포함된 로컬 변수의 값을 이용하는 것으로도 스택 주소 범위 내의 주솟값을 구하는 것이 가능합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > static <span style='color: blue; font-weight: bold'>unsafe</span> void Main(string[] args) { int dummy = 0; nuint localVarAdderss = new nuint(<span style='color: blue; font-weight: bold'>&dummy</span>); Console.WriteLine($"dummy address: 0x{localVarAdderss:x16}"); } </pre> <br /> 일단 저렇게 스택 범위 내의 주솟값을 구하면, 이를 바탕으로 <a target='tab' href='https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualquery'>VirtualQuery Win32 API</a>를 활용해 가상 메모리 할당의 시작 주솟값을 구할 수 있습니다.<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.Runtime.InteropServices; internal class Program { [DllImport("kernel32.dll", SetLastError = true)] public static extern int VirtualQuery(UIntPtr lpAddress, ref MEMORY_BASIC_INFORMATION lpBuffer, int dwLength); static unsafe void Main(string[] args) { <span style='color: blue; font-weight: bold'>nuint stackBase = GetThreadStackBasse(); Console.WriteLine($"Stack base: 0x{stackBase:X16}");</span> // 출력 값: Stack base: 0x00000081E3830000 } private unsafe static nuint GetThreadStackBasse() { MEMORY_BASIC_INFORMATION mbi = new MEMORY_BASIC_INFORMATION(); nuint stackPtr = new nuint((void*)(&mbi)); int result = VirtualQuery(stackPtr, ref mbi, Marshal.SizeOf(mbi)); if (result != 0) { <span style='color: blue; font-weight: bold'>return mbi.AllocationBase;</span> } return 0; } } [StructLayout(LayoutKind.Sequential)] public struct MEMORY_BASIC_INFORMATION { public UIntPtr BaseAddress; public UIntPtr AllocationBase; public uint AllocationProtect; public IntPtr RegionSize; public uint State; public uint Protect; public uint Type; } </pre> <br /> VirtualQuery가 반환하는 MEMORY_BASIC_INFORMATION 구조체의 AllocationBase가 VMMap에서 보여주는 스택의 시작 주소와 일치합니다.<br /> <a name='thread_size'></a> <br /> 자, 이렇게 해서 시작 주소를 알았는데요, 이제 스레드 스택의 크기를 알아내야 합니다. <a target='tab' href='https://www.sysnet.pe.kr/2/0/13173#pe_stack_reserve'>기본 스레드 크기</a>는 <a target='tab' href='https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32'>PE 헤더의 SizeOfStackReserve</a>로부터 구할 수 있는데, 사용자가 생성한 스레드의 경우에는 그 값을 바꾸는 것이 가능하기 때문에 단순히 SizeOfStackReserve 값을 활용하기에는 범용성이 떨어집니다.<br /> <br /> <a name='GetCurrentThreadStackLimits'></a> 다행히 Windows 8/2012부터는,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > GetCurrentThreadStackLimits function (processthreadsapi.h) ; <a target='tab' href='https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentthreadstacklimits'>https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentthreadstacklimits</a> </pre> <br /> 위의 API를 활용해 다음과 같이 구하는 것이 가능합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [DllImport("kernel32.dll")] static extern void GetCurrentThreadStackLimits(out ulong LowLimit, out ulong HightLimit); static unsafe void Main(string[] args) { <span style='color: blue; font-weight: bold'>GetCurrentThreadStackLimits(out ulong stackLowLimit, out ulong stackHightLimit);</span> Console.WriteLine($"0x{stackLowLimit:X16} ~ 0x{stackHightLimit:X16}"); } /* 출력 결과 0x0000003DD5600000 ~ 0x0000003DD5780000 */ </pre> <br /> 게다가 스택의 시작 주소도 함께 구해주기 때문에 이전에 만들어 둔 GetThreadStackBasse 메서드를 사용할 필요도 없습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 자, 이렇게 해서 스택의 시작과 끝을 구했으니 이제 그 사이의 메모리 Page 들이 어떤 속성으로 할당된 것인지 이전에 사용했던 VirtualQuery를 이용해 다음과 같이 구할 수 있습니다.<br /> <br /> <pre style='height: 400px; margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > GetCurrentThreadStackLimits(out ulong stackLowLimit, out ulong stackHightLimit); <span style='color: blue; font-weight: bold'>for (ulong page = stackLowLimit; page < stackHightLimit;)</span> { MEMORY_BASIC_INFORMATION mbi = new MEMORY_BASIC_INFORMATION(); int result = <span style='color: blue; font-weight: bold'>VirtualQuery((nuint)page, ref mbi, Marshal.SizeOf(mbi));</span> if (result != 0) { WritePageInfo((nuint)page, mbi); } <span style='color: blue; font-weight: bold'>page += (nuint)mbi.RegionSize;</span> } private static void WritePageInfo(nuint page, MEMORY_BASIC_INFORMATION mbi) { string text = $"BaseAddress: 0x{mbi.BaseAddress:X16}, Size: {mbi.RegionSize / 1024} KB, {GetPageState(mbi.State)} {GetPageAccess(mbi.Protect)}"; Console.WriteLine($"{text}"); } private static string GetPageAccess(uint state) { StringBuilder sb = new StringBuilder(); if ((state & 0x10) == 0x10) { sb.Append("PAGE_EXECUTE, "); } if ((state & 0x01) == 0x01) { sb.Append("PAGE_NOACCESS, "); } if ((state & 0x04) == 0x04) { sb.Append("PAGE_READWRITE, "); } if ((state & 0x100) == 0x100) { sb.Append("PAGE_GUARD"); } return sb.ToString(); } private static string GetPageState(uint state) { StringBuilder sb = new StringBuilder(); if ((state & 0x1000) == 0x1000) { sb.Append("MEM_COMMIT, "); } if ((state & 0x10000) == 0x10000) { sb.Append("MEM_FREE, "); } if ((state & 0x2000) == 0x2000) { sb.Append("MEM_RESERVE, "); } return sb.ToString(); } </pre> <br /> 이제 출력 결과를 VMMap과 비교하면,<br /> <br /> <img onclick='toggle_img(this)' class='imgView' alt='thread_vmm_2.png' src='/SysWebRes/bbs/thread_vmm_2.png' /><br /> <br /> 값이 정확히 일치합니다.<br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1986&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1739
(왼쪽의 숫자를 입력해야 합니다.)