Microsoft MVP성태의 닷넷 이야기
디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [링크 복사], [링크+제목 복사]
조회: 4971
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

windbg - Win32 API 호출 시점에 BP 거는 방법

아래의 Q&A를 보면,

MiniDumpWriteDump API로 덤프수집을 했는데요..
; https://www.sysnet.pe.kr/3/0/5811

procdump가 생성한 덤프 파일은 정상적으로 handle 값이 보이는 반면, 단순히 MiniDumpWriteDump를 한 경우에는 그렇지 않다고 합니다. 그런데, 사실 procdump라고 해서 특별히 독자적으로 만든 덤프 코드를 쓰지는 않을 것입니다. 즉, 동일하게 MiniDumpWriteDump API를 사용할 텐데요, 그럼 혹시 procdump가 MiniDumpWriteDump를 특별한 옵션 조합으로 사용하는 것은 아닐까요? ^^

바로 그런 경우, windbg를 이용할 수 있습니다. 단순히 다음의 옵션으로 실행할 수 있는데,

dbg_win32api_1.png

// 실습을 위해 notepad를 실행시켰고 그것의 process id가 37768인 상태.

Executable: c:\temp\procdump
Arguments: -ma 37768
Start directory: c:\temp
Target architecture: Autodetect

위의 옵션으로 "Debug" 버튼을 눌러 시작하면 해당 프로세스가 시작하자마자 BP가 걸리게 됩니다. 그런데, procdump의 경우 해당 프로세스는 32비트 프로세스라서 64비트 프로세스의 덤프를 뜨지 못합니다. 그래서 procdump는 대상 프로세스가 64비트인 경우 내부 리소스에 보관한 procdump64.exe 이미지를 실행 중에 디스크에 쓰고 그것을 자식 프로세스로 실행한 다음 해당 파일을 지우는 것으로 마무리합니다.

따라서, 우리가 원하는 MiniDumpWriteDump Win32 API는 현재의 32비트 procdump.exe에서 호출하지 않고 자식 프로세스의 procdump64.exe에서 호출될 것이므로 위와 같은 설정으로 실행하게 되면 BP가 잡히질 않습니다.

그래서 제 경우에는, procdump를 windbg 내에서 어느 정도 실행하다 procdump64.exe를 디스크에 쓰는 시점에 그 파일을 별도로 procdump64_2.exe로 복사해 두었습니다. 그런 다음, 다시 windbg 시작을 다음의 옵션으로 바꾸고,

Executable: c:\temp\procdump64_2
Arguments: -ma 37768
Start directory: c:\temp
Target architecture: Autodetect

디버그 세션을 진행했습니다. 문서에 보면,

MiniDumpWriteDump function (minidumpapiset.h)
; https://learn.microsoft.com/en-us/windows/win32/api/minidumpapiset/nf-minidumpapiset-minidumpwritedump

MiniDumpWriteDump API는 dbghelp.dll 또는 dbgcore.dll에 구현됐다고 하는데요, Windows 11의 경우에는 dbgcore.dll에 있으므로 다음과 같이 DLL 로딩 시 BP가 걸리는 명령어를 수행합니다.

sxe ld:Dbgcore.dll

// 운영체제에 따라 
// sxe ld:Dbghelp.dll

그다음 'g' 키를 눌러 dbgcore.dll 로딩 시점에 멈췄으면 이제 MiniDumpWriteDump API에 bp가 걸리도록 명령어를 수행합니다.

bp Dbgcore!MiniDumpWriteDump

다시 'g' 키를 눌러 실행하면 다음과 같이 bp가 걸리는 것을 확인할 수 있습니다.

dbg_win32api_2.png

MiniDumpWriteDump의 4번째 인자에 들어가는 값이 MINIDUMP_TYPE이니까, 위의 화면에서 r9 레지스터의 값이 0x0000000000469927 == 4,626,727이므로,

0100 0110 1001 1001 0010 0111

typedef enum _MINIDUMP_TYPE {
    MiniDumpNormal                         = 0x00000000,
    MiniDumpWithDataSegs                   = 0x00000001,
    MiniDumpWithFullMemory                 = 0x00000002,
    MiniDumpWithHandleData                 = 0x00000004,
    MiniDumpFilterMemory                   = 0x00000008,

    MiniDumpScanMemory                     = 0x00000010,
    MiniDumpWithUnloadedModules            = 0x00000020,
    MiniDumpWithIndirectlyReferencedMemory = 0x00000040,
    MiniDumpFilterModulePaths              = 0x00000080,

    MiniDumpWithProcessThreadData          = 0x00000100,
    MiniDumpWithPrivateReadWriteMemory     = 0x00000200,
    MiniDumpWithoutOptionalData            = 0x00000400,
    MiniDumpWithFullMemoryInfo             = 0x00000800,

    MiniDumpWithThreadInfo                 = 0x00001000,
    MiniDumpWithCodeSegs                   = 0x00002000,
    MiniDumpWithoutAuxiliaryState          = 0x00004000,
    MiniDumpWithFullAuxiliaryState         = 0x00008000,

    MiniDumpWithPrivateWriteCopyMemory     = 0x00010000,
    MiniDumpIgnoreInaccessibleMemory       = 0x00020000,
    MiniDumpWithTokenInformation           = 0x00040000,
    MiniDumpWithModuleHeaders              = 0x00080000,

    MiniDumpFilterTriage                   = 0x00100000,
    MiniDumpWithAvxXStateContext           = 0x00200000,
    MiniDumpWithIptTrace                   = 0x00400000,
    MiniDumpScanInaccessiblePartialPages   = 0x00800000,

    MiniDumpFilterWriteCombinedMemory      = 0x01000000,
    MiniDumpValidTypeFlags                 = 0x01ffffff,
} MINIDUMP_TYPE;

대략 값의 조합이 이렇게 나옵니다.

MiniDumpWithDataSegs
MiniDumpWithFullMemory
MiniDumpWithHandleData

MiniDumpWithUnloadedModules

MiniDumpWithProcessThreadData
MiniDumpWithFullMemoryInfo

MiniDumpWithThreadInfo
MiniDumpWithFullAuxiliaryState

MiniDumpIgnoreInaccessibleMemory
MiniDumpWithTokenInformation

MiniDumpWithIptTrace

실제로 procdump를 이용한 덤프 상태와,

0:000> .dumpdebug
----- User Mini Dump Analysis

MINIDUMP_HEADER:
Version         A793 (A05D)
NumberOfStreams 19
Flags           661826
                0002 MiniDumpWithFullMemory
                0004 MiniDumpWithHandleData
                0020 MiniDumpWithUnloadedModules
                0800 MiniDumpWithFullMemoryInfo
                1000 MiniDumpWithThreadInfo
                20000 MiniDumpIgnoreInaccessibleMemory
                40000 MiniDumpWithTokenInformation
                200000 MiniDumpWithAvxXStateContext
                400000 MiniDumpWithIptTrace
...[생략]...

위에서 알아낸 방법으로 조합한 MiniDumpWriteDump의 덤프 상태가,

0:000> .dumpdebug
----- User Mini Dump Analysis

MINIDUMP_HEADER:
Version         A793 (A05D)
NumberOfStreams 18
Flags           661826
                0002 MiniDumpWithFullMemory
                0004 MiniDumpWithHandleData
                0020 MiniDumpWithUnloadedModules
                0800 MiniDumpWithFullMemoryInfo
                1000 MiniDumpWithThreadInfo
                20000 MiniDumpIgnoreInaccessibleMemory
                40000 MiniDumpWithTokenInformation
                200000 MiniDumpWithAvxXStateContext
                400000 MiniDumpWithIptTrace
...[생략]...

거의 비슷합니다. 단지, NumberOfStreams만 procdump가 하나 더 많은데요, 그래서인지 덤프 파일 크기도 procdump 쪽이 아주 약간 더 크게 나옵니다.

prodcump: 327 MB (343,619,184 bytes)
MiniDumpWriteDump: 327 MB (343,619,082 bytes)

그래도 아마... 저렇게 맞춘 정도라면 handle 명령어가 제대로 먹히지 않을까 싶군요. ^^




참고로, 위의 내용 중 적절한 시점에 procdump64.exe를 구할 수 있다고 했는데요, 이것 역시 위의 방법대로 동일하게 적용할 수 있습니다. 즉, 하위 프로세스를 생성할 것이므로 CreateProcess에 BP를 걸면 되는데요,

CreateProcessA function (processthreadsapi.h)
; https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa

문서에도 나오듯이 해당 API의 구현 모듈이 kernel32.dll이므로 다음과 같이 DLL 로딩에 BP가 걸리도록 하고,

0:000> sxe ld:kernel32.dll

0:000> g
ModLoad: 00000000`77250000 00000000`7725a000   C:\WINDOWS\System32\wow64cpu.dll
ModLoad: 00000000`75b70000 00000000`75c60000   C:\WINDOWS\SysWOW64\KERNEL32.DLL
ntdll!NtMapViewOfSection+0x14:
00007ffa`f300f304 c3              ret

BP가 걸렸으면 CreateProcess에 bp 설정을 하면 되지만,

0:000> bp KERNEL32!CreateProcessW
Couldn't resolve error at 'KERNEL32!CreateProcessW'

없다고 나옵니다. kernel32.dll의 export 함수를 조사해 보면 CreateProcessWStub을 찾을 수 있는데요, 다시 그걸로 bp 설정을 하고 그 위치에 bp가 걸릴 때까지 실행을 (두 번 정도) 'g' 키로 하면,

0:000> bp KERNEL32!CreateProcessWStub

0:000> g
ModLoad: 00000000`74f80000 00000000`751eb000   C:\WINDOWS\SysWOW64\KERNELBASE.dll
...[생략]...
ModLoad: 00000000`765f0000 00000000`7673d000   C:\WINDOWS\SysWOW64\ole32.dll
ModLoad: 00000000`692e0000 00000000`69306000   d:\tools\sysinternals\pdh.dll
ModLoad: 00000000`751f0000 00000000`7528c000   C:\WINDOWS\SysWOW64\OLEAUT32.dll
(acc0.5928): WOW64 breakpoint - code 4000001f (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
ntdll32!LdrpDoDebuggerBreak+0x2b:
77317847 cc              int     3

0:000:x86> g
SetContext failed, 0x80004005
ModLoad: 75640000 75666000   C:\WINDOWS\SysWOW64\IMM32.DLL
ModLoad: 00000000`555e0000 00000000`557a7000   C:\Program Files (x86)\Windows Kits\10\Debuggers\x86\dbghelp.dll
ModLoad: 00000000`69200000 00000000`69229000   C:\WINDOWS\SysWOW64\dbgcore.DLL
Breakpoint 0 hit
KERNEL32!CreateProcessWStub:
75b8d930 8bff            mov     edi,edi

그 순간, procdump.exe가 있던 디렉터리를 보면 procdump64.exe 파일이 있는 것을 볼 수 있습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/5/2023]

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

비밀번호

댓글 작성자
 



2023-06-01 10시06분
Hacking with Windbg - Part 1 (Notepad)
; https://www.codeproject.com/Articles/1276860/Hacking-with-Windbg-Part-1-Notepad

-------------------------------

Windows debugger trick: Breaking when a specific debugger message is printed
; https://devblogs.microsoft.com/oldnewthing/20240403-00/?p=109607

sxe out:str
ex) sxe out:*assertion failure*
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13608정성태4/26/2024220닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024216닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024239닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024519닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024585오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024785닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024849닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024887닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024908닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024878닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024912닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024894닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241077닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241060닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241075닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241088닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241226C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241201닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241081Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241158닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241273닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241358오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241532Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241313Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241273개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...