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

비밀번호

댓글 작성자
 




... [91]  92  93  94  95  96  97  98  99  100  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11368정성태11/25/201720370.NET Framework: 699. UDP 브로드캐스트 주소 255.255.255.255와 192.168.0.255의 차이점과 이를 고려한 C# UDP 서버/클라이언트 예제 [2]파일 다운로드1
11367정성태11/25/201720500개발 환경 구성: 337. 윈도우 운영체제의 route 명령어 사용법
11366정성태11/25/201712304오류 유형: 430. 이벤트 로그 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
11365정성태11/25/201714581오류 유형: 429. 이벤트 로그 - User Policy could not be updated successfully
11364정성태11/24/201715697사물인터넷: 11. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표) [2]
11363정성태11/23/201715395사물인터넷: 10. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
11362정성태11/22/201713059오류 유형: 428. 윈도우 업데이트 KB4048953 - 0x800705b4 [2]
11361정성태11/22/201715618오류 유형: 427. 이벤트 로그 - Filter Manager failed to attach to volume '\Device\HarddiskVolume??' 0xC03A001C
11360정성태11/22/201715406오류 유형: 426. 이벤트 로그 - The kernel power manager has initiated a shutdown transition.
11359정성태11/16/201714766오류 유형: 425. 윈도우 10 Version 1709 (OS Build 16299.64) 업그레이드 시 발생한 문제 2가지
11358정성태11/15/201719049사물인터넷: 9. Visual Studio 2017에서 Raspberry Pi C++ 응용 프로그램 제작 [1]
11357정성태11/15/201719854개발 환경 구성: 336. 윈도우 10 Bash 쉘에서 C++ 컴파일하는 방법
11356정성태11/15/201721214사물인터넷: 8. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 [4]
11355정성태11/15/201717708사물인터넷: 7. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 [2]파일 다운로드2
11354정성태11/14/201720988사물인터넷: 6. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드로 쓰는 방법 [8]
11353정성태11/14/201718747사물인터넷: 5. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 이더넷 카드로 쓰는 방법 [1]
11352정성태11/14/201714365사물인터넷: 4. Samba를 이용해 윈도우와 Raspberry Pi간의 파일 교환 [1]
11351정성태11/7/201717366.NET Framework: 698. C# 컴파일러 대신 직접 구현하는 비동기(async/await) 코드 [6]파일 다운로드1
11350정성태11/1/201713659디버깅 기술: 108. windbg 분석 사례 - Redis 서버로의 호출을 기다리면서 hang 현상 발생
11349정성태10/31/201713546디버깅 기술: 107. windbg - x64 SOS 확장의 !clrstack 명령어가 출력하는 Child SP 값의 의미 [1]파일 다운로드1
11348정성태10/31/201710952디버깅 기술: 106. windbg - x64 역어셈블 코드에서 닷넷 메서드 호출의 인자를 확인하는 방법
11347정성태10/28/201714460오류 유형: 424. Visual Studio - "클래스 다이어그램 보기" 시 "작업을 완료할 수 없습니다. 해당 인터페이스를 지원하지 않습니다." 오류 발생
11346정성태10/25/201710798오류 유형: 423. Windows Server 2003 - The client-side extension could not remove user policy settings for 'Default Domain Policy {...}' (0x8007000d)
11338정성태10/25/201710879.NET Framework: 697. windbg - SOS DumpMT의 "BaseSize", "ComponentSize" 값에 대한 의미파일 다운로드1
11337정성태10/24/201711863.NET Framework: 696. windbg - SOS DumpClass/DumpMT의 "Vtable Slots", "Total Method Slots", "Slots in VTable" 값에 대한 의미파일 다운로드1
11336정성태10/20/201712312.NET Framework: 695. windbg - .NET string의 x86/x64 메모리 할당 구조
... [91]  92  93  94  95  96  97  98  99  100  101  102  103  104  105  ...