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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...
NoWriterDateCnt.TitleFile(s)
11810정성태2/11/201911349.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201912822.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201913928디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
11807정성태1/29/201912248Windows: 156. 가상 디스크의 용량을 복구 파티션으로 인해 늘리지 못하는 경우 [4]
11806정성태1/29/201911969디버깅 기술: 122. windbg - 덤프 파일로부터 PID와 환경 변수 등의 정보를 구하는 방법
11805정성태1/28/201913855.NET Framework: 806. C# - int []와 object []의 차이로 이해하는 제네릭의 필요성 [4]파일 다운로드1
11804정성태1/24/201911869Windows: 155. diskpart - remove letter 이후 재부팅 시 다시 드라이브 문자가 할당되는 경우
11803정성태1/10/201911370디버깅 기술: 121. windbg - 닷넷 Finalizer 스레드가 멈춰있는 현상
11802정성태1/7/201912764.NET Framework: 805. 두 개의 윈도우를 각각 실행하는 방법(Windows Forms, WPF)파일 다운로드1
11801정성태1/1/201913738개발 환경 구성: 427. Netsh의 네트워크 모니터링 기능 [3]
11800정성태12/28/201813044오류 유형: 509. WCF 호출 오류 메시지 - System.ServiceModel.CommunicationException: Internal Server Error
11799정성태12/19/201813829.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법 [3]파일 다운로드1
11798정성태12/19/201813034개발 환경 구성: 426. vcpkg - "Building vcpkg.exe failed. Please ensure you have installed Visual Studio with the Desktop C++ workload and the Windows SDK for Desktop C++"
11797정성태12/19/201810407개발 환경 구성: 425. vcpkg - CMake Error: Problem with archive_write_header(): Can't create '' 빌드 오류
11796정성태12/19/201810097개발 환경 구성: 424. vcpkg - "File does not have expected hash" 오류를 무시하는 방법
11795정성태12/19/201812443Windows: 154. PowerShell - Zone 별로 DNS 레코드 유형 정보 조회 [1]
11794정성태12/16/20189922오류 유형: 508. Get-AzureWebsite : Request to a downlevel service failed.
11793정성태12/16/201811513개발 환경 구성: 423. NuGet 패키지 제작 - Native와 Managed DLL을 분리하는 방법 [1]
11792정성태12/11/201812297Graphics: 34. .NET으로 구현하는 OpenGL (11) - Per-Pixel Lighting파일 다운로드1
11791정성태12/11/201812270VS.NET IDE: 130. C/C++ 프로젝트의 시작 프로그램으로 .NET Core EXE를 지정하는 경우 닷넷 디버깅이 안 되는 문제 [1]
11790정성태12/11/201810623오류 유형: 507. Could not save daemon configuration to C:\ProgramData\Docker\config\daemon.json: Access to the path 'C:\ProgramData\Docker\config' is denied.
11789정성태12/10/201820487Windows: 153. C# - USB 장치의 연결 및 해제 알림을 위한 WM_DEVICECHANGE 메시지 처리 [2]파일 다운로드2
11788정성태12/4/201810465오류 유형: 506. SqlClient - Value was either too large or too small for an Int32.Couldn't store <2151292191> in ... Column
11787정성태11/29/201814426Graphics: 33. .NET으로 구현하는 OpenGL (9), (10) - OBJ File Format, Loading 3D Models파일 다운로드1
11786정성태11/29/201811118오류 유형: 505. OpenGL.NET 예제 실행 시 "Managed Debugging Assistant 'CallbackOnCollectedDelegate'" 예외 발생
11785정성태11/21/201813511디버깅 기술: 120. windbg 분석 사례 - ODP.NET 사용 시 Finalizer에서 System.AccessViolationException 예외 발생으로 인한 비정상 종료
... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...