Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

windbg/Visual Studio - 값이 변경된 경우를 위한 정지점(BP) 설정(Data Breakpoint)

예전에 설명한,

windbg - CoTaskMemFree/FreeCoTaskMem에서 발생한 덤프 분석 사례 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/12062

덤프에서와 같은 상황이 발생한다면, 이것을 도대체 어떻게 해결할 수 있을까요? 사실 정적인 snapshot 형식의 덤프 파일을 통해서는 Heap 메모리를 깬 원인을 찾기가 쉽지 않습니다.

대신, 라이브 디버깅 상황이라면 windbg의 경우 "ba" 명령어로 해결할 수 있습니다.

windbg ba (Break on Access)
; https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/ba--break-on-access-

예를 들어, 지난 글에 다룬 예제 코드를 다음과 같이 변형해,

using System;

class Program
{
    static unsafe void Main(string[] args)
    {
        int[] test = new int[1];
        test[0] = 0xff;

        Console.WriteLine("int [] ================== ");
        fixed (int* p1 = &test[0])
        {
            Console.WriteLine("OBJECT Header(SyncBlock Index): " + (*(p1 - 3)).ToString("x"));
            Console.WriteLine("MethodTable Address: " + (*(p1 - 2)).ToString("x"));

            int* ptrMT = p1 - 2;
            Console.WriteLine(new IntPtr(ptrMT).ToInt64().ToString("x"));

            Console.ReadLine();

            *(p1 - 2) = 0; // GC의 MethodTable 주소 정보를 제거

            Console.WriteLine("배열 요소 크기: " + (*(p1 - 1)).ToString("x"));
            Console.WriteLine("0번째 배열 값: " + (*(p1 - 0)).ToString("x"));
        }

        GC.Collect(); // 여기서 비정상 종료

        Console.WriteLine("GCed!"); // 이 코드는 절대 수행되지 않음
    }
}

/* Console.ReadLine까지의 출력 결과

int [] ==================
OBJECT Header(SyncBlock Index): 7fff
MethodTable Address: 1
29fc0682f90
*/

Console.ReadLine이 수행된 시점에 windbg를 이용해 attach를 한 후 다음과 같이 "ba" 명령어로 걸어두면,

0:006> ba w4 29fc0682f90

// 29fc0682f90 주소에서 시작하는 4바이트 범위의 값이 변경(write)되었을 때 BreakPoint 동작

"*(p1 - 2) = 0;" 코드가 수행되는 시점에 windbg는 실행을 중지하게 됩니다.

0:006> g
Breakpoint 0 hit
00007fff`867b0ab0 48b9983668d09f020000 mov rcx,29FD0683698h

당연히 이 상황에서 callstack을 확인하면 문제의 그 코드 위치를 정확하게 확인할 수 있습니다.

0:000> .loadby sos clr

0:000> !clrstack
OS Thread Id: 0xe0c (0)
        Child SP               IP Call Site
000000c9cc0fecc0 00007fff867b0ab0 Program.Main(System.String[]) [c:\temp\ConsoleApp1\Program.cs @ 23]
000000c9cc0fefa8 00007fffe5cf6cb3 [GCFrame: 000000c9cc0fefa8] 

좀 더 근본적인 상황 파악을 원한다면 RIP(위의 경우 00007fff`867b0ab0) 값을 통해 코드를 덤프하고,

0:000> !u 00007fff`867b0ab0
Normal JIT generated code
Program.Main(System.String[])
Begin 00007fff867b0890, size 306

c:\temp\ConsoleApp1\Program.cs @ 6:
00007fff`867b0890 55              push    rbp
00007fff`867b0891 57              push    rdi
00007fff`867b0892 56              push    rsi
00007fff`867b0893 4881ece0000000  sub     rsp,0E0h
00007fff`867b089a 488dac24f0000000 lea     rbp,[rsp+0F0h]
00007fff`867b08a2 488bf1          mov     rsi,rcx
00007fff`867b08a5 488dbd30ffffff  lea     rdi,[rbp-0D0h]
00007fff`867b08ac b930000000      mov     ecx,30h
00007fff`867b08b1 33c0            xor     eax,eax
00007fff`867b08b3 f3ab            rep stos dword ptr [rdi]
00007fff`867b08b5 488bce          mov     rcx,rsi
00007fff`867b08b8 48894d10        mov     qword ptr [rbp+10h],rcx
00007fff`867b08bc 833d053defff00  cmp     dword ptr [00007fff`866a45c8],0
00007fff`867b08c3 7405            je      00007fff`867b08ca
00007fff`867b08c5 e84606a55f      call    clr!JIT_DbgIsJustMyCode (00007fff`e6200f10)
00007fff`867b08ca 90              nop

...[생략]...

c:\temp\ConsoleApp1\Program.cs @ 21:
00007fff`867b0a91 488b4de8        mov     rcx,qword ptr [rbp-18h]
00007fff`867b0a95 ba02000000      mov     edx,2
00007fff`867b0a9a 4863d2          movsxd  rdx,edx
00007fff`867b0a9d b804000000      mov     eax,4
00007fff`867b0aa2 4863c0          movsxd  rax,eax
00007fff`867b0aa5 480fafd0        imul    rdx,rax
00007fff`867b0aa9 482bca          sub     rcx,rdx
00007fff`867b0aac 33d2            xor     edx,edx
00007fff`867b0aae 8911            mov     dword ptr [rcx],edx

c:\temp\ConsoleApp1\Program.cs @ 23:
>>> 00007fff`867b0ab0 48b9983668d09f020000 mov rcx,29FD0683698h
00007fff`867b0aba 488b09          mov     rcx,qword ptr [rcx]
...[생략]...

c:\temp\ConsoleApp1\Program.cs @ 30:
00007fff`867b0b8d 90              nop
00007fff`867b0b8e 488d65f0        lea     rsp,[rbp-10h]
00007fff`867b0b92 5e              pop     rsi
00007fff`867b0b93 5f              pop     rdi
00007fff`867b0b94 5d              pop     rbp
00007fff`867b0b95 c3              ret

rip의 값이 현재 문제가 발생한 코드를 기준으로 다음번 수행할 명령어를 가리키므로 위의 경우 실제 문제는 "00007fff`867b0aae" 주소의 코드이며,

00007fff`867b0aae 8911            mov     dword ptr [rcx],edx

당연히 rcx 레지스터에는 29fc0682f90 값이, edx 레지스터에는 0이 들어 있는 것으로 원인을 정확하게 짚어낼 수 있습니다.




참고로, Visual Studio에서는 "ba"에 해당하는 기능을 "Data Breakpoint"라는 이름으로 제공하는데,

data_bp_ba_1.png

"Native" 환경, 즉 C/C++ 프로그램에 대해 Visual Studio 2017부터 기능을 구현했으며,

Data Breakpoints ? Visual Studio 2017 15.8 Update
; https://devblogs.microsoft.com/cppblog/data-breakpoints-15-8-update/

Visual Studio 2019부터는 (.NET Core 3.0 이상이라는 제약이 있지만) .NET 환경까지 제공 범위를 확대했습니다.

Break When Value Changes: Data Breakpoints for .NET Core in Visual Studio 2019
; https://devblogs.microsoft.com/visualstudio/break-when-value-changes-data-breakpoints-for-net-core-in-visual-studio-2019/

Use breakpoints in the Visual Studio debugger
- Set data breakpoints (.NET Core 3.0 or higher)
; https://learn.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2019#BKMK_set_a_data_breakpoint_managed

(혹시나 싶어 .NET 응용 프로그램에 대해 "Mixed mode"로 디버깅을 시작했지만 "Data Breakpoint" 메뉴는 활성화되지 않습니다.)




참고로, lldb의 경우 watchpoint라는 이름으로 동등한 기능이 제공됩니다.

watchpoint - lldb
; https://libsora.so/posts/buffer-overflow-broken-dtor-debugging-post-mortem/




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 3/9/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...
NoWriterDateCnt.TitleFile(s)
13304정성태3/31/20234387VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20233729Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234358Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234452Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20234096Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20233870Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20233826Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234486Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20233825Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20234113Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234282.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234345오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234461Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20234831.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234326.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233514Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233627Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20233790Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234234Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20233822Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20234045Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233583오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20233914Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20233840Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/20234591개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/20234117오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...