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)
12399정성태11/5/202011453.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/20209984오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202010159.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/20208449VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/20209794오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/20208186오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208686오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012795.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202011037디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010775.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202010228오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202011016.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202011261Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20209075오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202010295오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202011180.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208895오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010566VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207972오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202010986.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/202010396.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름파일 다운로드1
12377정성태10/15/202011691디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/20208406오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/20209791Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(¥)' 기호로 나오는 경우 [1]
12374정성태10/14/202014416.NET Framework: 953. C# 9.0 - (6) 함수 포인터(Function pointers) [1]파일 다운로드2
12373정성태10/14/20209694.NET Framework: 952. OpCodes.Box와 관련해 IL 형식으로 직접 코딩 시 유의할 점
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...