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

비밀번호

댓글 작성자
 




... 46  47  48  [49]  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12424정성태11/24/202010375VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202011265.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/20209074.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/20208824.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/20208012오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/20209288VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202011317오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/20208730오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/202010001오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202010119.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202011173VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202010840.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202013077.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202010118오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/20209973디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202011342.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202022950도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202011675.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202013231.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202010630.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202011188.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202011214.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202011818.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202010763VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/20207700오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202011453.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
... 46  47  48  [49]  50  51  52  53  54  55  56  57  58  59  60  ...