Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

ProcDump - C/C++ 예외 코드 필터를 지정한 덤프 생성

간단하게 crash 덤프를 유발하도록 코드를 만들어 볼까요?

#include <Windows.h>
#include <iostream>

char *CallRecursive(int start, int diff)
{
    printf(".");
    char* pBytes = (char*)alloca(4); // 이 코드가 없으면 재귀 호출의 최적화로 인해 
                                     // Release 모드에서 stack overflow가 발생하지 않습니다.

    CallRecursive(start, start + diff);

    return pBytes;
}

int main()
{
    DWORD pid = ::GetCurrentProcessId();
    std::cout << pid << ", Press any key to crash...\n";
    auto ch = std::getchar();

    if (ch == 'q')
    {
        std::cout << "Exiting gracefully...\n";
        return 0;
    }

    if (ch == 'z')
    {
        std::cout << "divide by zero...\n";
        int n = 5;
        n /= 0;
        return 0;
    }

    std::cout << "stack-overflow...\n";
    CallRecursive(0, 1);
    return 1;
}

보는 바와 같이 'z' + ENTER 키를 입력하면 Divide By Zero 예외가 발생하고, 그냥 ENTER 키를 입력하면 Stack Overflow 예외가 발생합니다.

그리고 위의 상황에서 ProcDump로 덤프를 생성하면 이런 식의 출력을 볼 수 있습니다.

// 'z' + ENTER: Divide By Zero

c:\temp> procdump -ma -e 1 ConsoleApplication1.exe
...[생략]...
Press Ctrl-C to end monitoring without terminating the process.

[13:43:18] Exception: C0000094.INT_DIVIDE_BY_ZERO
[13:43:18] Unhandled: C0000094.INT_DIVIDE_BY_ZERO
[13:43:18] Dump 1 initiated: c:\temp\ConsoleApplication1.exe_134318.dmp
[13:43:18] Dump 1 writing: Estimated dump file size is 13 MB.
[13:43:18] Dump 1 complete: 13 MB written in 0.1 seconds
[13:43:18] Dump count reached.

// ENTER: Stack Overflow

c:\temp> procdump -ma -e 1 ConsoleApplication1.exe
...[생략]...
Press Ctrl-C to end monitoring without terminating the process.

[13:44:06] Exception: C00000FD.STACK_OVERFLOW
[13:44:06] Dump 1 initiated: c:\temp\ConsoleApplication1.exe_134406.dmp
[13:44:06] Dump 1 writing: Estimated dump file size is 14 MB.
[13:44:06] Dump 1 complete: 14 MB written in 0.1 seconds
[13:44:06] Dump count reached.

그렇다면, 만약 stack overflow로 인해 프로세스가 비정상 종료된 경우에만 덤프를 남기고 싶다면 어떻게 해야 할까요? 이를 위해 "-f" 옵션이 제공되긴 하는데요,

procdump -ma -e 1 -f C00000FD ConsoleApplication1.exe

// 또는 process id == 6400이라고 가정할 때
procdump -ma -e 1 -f C00000FD 6400

여기서 한 가지 유의할 점이 있다면, EXE 파일이 debug 모드로 빌드된 경우라면 저 필터 옵션(-f)이 동작하지 않는다는 것입니다. 즉, Release 모드로 빌드한 경우에만 -f 옵션이 적용된다는 점! (이게 의도한 동작인지, 또는 버그인지는 모르겠습니다.)




참고로, 저런 식으로 옵션을 지정하는 것은 다소 빈번하게 예외가 발생했을 상황일 것입니다. 그에 반해 간혹 발생하는 경우라면 (RDP로 접속해 세션을 열어두거나 하는 것이 부담스러울 수 있는데) 이럴 때는 그냥 아예 덤프 절차에 ProcDump가 관여하도록 설정하는 것이 좋습니다.

// 관리자 권한으로 실행
// 
// 윈도우 시스템이 비정상 종료해 덤프를 남겨야겠다고 판단하면,
// procdump를 이용해 c:\temp 디렉터리에 덤프 파일 생성

C:\temp> procdump -ma -i c:\temp

ProcDump v11.0 - Sysinternals process dump utility
Copyright (C) 2009-2022 Mark Russinovich and Andrew Richards
Sysinternals - www.sysinternals.com

Set to:
  HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug
    (REG_SZ) Auto     = 1
    (REG_SZ) Debugger = "d:\tools\Sysinternals\procdump.exe" -accepteula -ma -j "c:\temp" %ld %ld %p

Set to:
  HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug
    (REG_SZ) Auto     = 1
    (REG_SZ) Debugger = "d:\tools\Sysinternals\procdump.exe" -accepteula -ma -j "c:\temp" %ld %ld %p

ProcDump is now set as the Just-in-time (AeDebug) debugger.

C:\temp> 

저렇게 (-i 옵션으로) 설치했을 때의 단점이라면 -f 필터 옵션을 지정할 수 없다는 건데요, 사실 뭐... 비정상 종료하는 마당에 필터링이 필요할까 싶지만!

그리고 원하는 덤프가 나왔다면 다시 원래대로 돌려놓는 것도 잊지 말아야겠고.

// 관리자 권한으로 실행

C:\temp> prodcump -u




위의 예제(ConsoleApplication1.exe)를 Release 모드로 빌드 후 PDB 파일 없이 WinDbg에서 덤프 파일을 열어 "!analyze -v" 명령을 실행하면 대충 다음과 같은 분석 결과가 나옵니다.

0:000> !analyze -v
...[생략]...

FILE_IN_CAB:  ConsoleApplication1.exe_143922.dmp

COMMENT:  
*** procdump  -ma -e 1 -f C00000FD ConsoleApplication1.exe
*** First chance exception: C00000FD.STACK_OVERFLOW

NTGLOBALFLAG:  0

APPLICATION_VERIFIER_FLAGS:  0

CONTEXT:  (.ecxr)
rax=000000aaf3c04070 rbx=000000aaf3c04060 rcx=000000000000005c
rdx=000000aaf3c04070 rsi=000000000000005c rdi=0000000000000000
rip=00007fff91d74563 rsp=000000aaf3c03fc0 rbp=000000000000005c
 r8=0000000000000001  r9=000000aaf3c04060 r10=000000aaf3c04070
r11=00007fff9219f9a0 r12=0000000000000001 r13=0000000000000000
r14=000000aaf3c054f0 r15=0000000000000001
iopl=0         nv up ei pl zr na po nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010246
KERNELBASE!WriteFile+0x53:
00007fff`91d74563 48897c2438      mov     qword ptr [rsp+38h],rdi ss:000000aa`f3c03ff8=0000000000000000
Resetting default scope

EXCEPTION_RECORD:  (.exr -1)
ExceptionAddress: 00007fff91d74563 (KERNELBASE!WriteFile+0x0000000000000053)
   ExceptionCode: c00000fd (Stack overflow)
  ExceptionFlags: 00000000
NumberParameters: 2
   Parameter[0]: 0000000000000001
   Parameter[1]: 000000aaf3c03ff8

PROCESS_NAME:  ConsoleApplication1.exe

RECURRING_STACK: From frames 0x1 to 0x9

ERROR_CODE: (NTSTATUS) 0xc00000fd - A new guard page for the stack cannot be created.

EXCEPTION_CODE_STR:  c00000fd

EXCEPTION_PARAMETER1:  0000000000000001

EXCEPTION_PARAMETER2:  000000aaf3c03ff8

STACK_TEXT:  
000000aa`f3c03fc0 00007fff`920a3ec7     : 00000251`00a38211 00000251`00a38211 00000000`00000001 000000aa`f3c04060 : KERNELBASE!WriteFile+0x53
000000aa`f3c04030 00007fff`920a5b84     : 000000aa`f3c05b20 00000000`00000000 000000aa`f3c05500 00000000`00000001 : ucrtbase!write_text_ansi_nolock+0xb7
000000aa`f3c054a0 00007fff`920a59f4     : 000000aa`f3c05b20 00000000`ffffffff 00000000`00000009 00000000`00000001 : ucrtbase!_write_nolock+0x12c
000000aa`f3c05520 00007fff`920b6eba     : 000000aa`00000001 00000251`00a38210 00007fff`9219e4f8 00007fff`9219e4f8 : ucrtbase!_write_internal+0x9c
000000aa`f3c05580 00007fff`920a307d     : 00000000`00000001 000000aa`f3c056b0 000000aa`f3c05b01 000000aa`f3c05b01 : ucrtbase!_acrt_stdio_flush_nolock+0x52
000000aa`f3c055b0 00007fff`920a2f3b     : 00000000`00000000 000000aa`f3c05af0 000000aa`f3c05bc8 000000aa`f3c05ae0 : ucrtbase!<lambda_303760bc4008a2b3ec4768a30b06a80c>::operator()+0x11d
000000aa`f3c05a80 00007fff`920a2eeb     : 00007fff`9219e4f8 00000000`00000000 000000aa`f3c05b30 000000aa`f3c05ae0 : ucrtbase!__crt_seh_guarded_call<int>::operator()<<lambda_d854c62834386a3b23916ad6dae2782d>,<lambda_303760bc4008a2b3ec4768a30b06a80c> &,<lambda_4780a7ea4f8cbd2590aec34bd14e2bbf> >+0x2b
000000aa`f3c05ab0 00007ff6`3827105d     : 00000000`00000024 00007ff6`382732c0 000000aa`f3c05bc8 00007fff`9219e4f8 : ucrtbase!__stdio_common_vfprintf+0x8b
000000aa`f3c05b70 00007ff6`3827109f     : 00007ff6`382732c0 00000000`00000001 00000000`00000000 00007fff`9219f9a0 : ConsoleApplication1+0x105d
000000aa`f3c05bc0 00007ff6`382710b6     : 000000aa`f3c05c20 00000000`00000001 00007ff6`382732c0 00000000`00000001 : ConsoleApplication1+0x109f
000000aa`f3c05c00 00007ff6`382710b6     : 000000aa`f3c05c70 00000000`00000001 00007ff6`382732c0 00000000`00000001 : ConsoleApplication1+0x10b6
000000aa`f3c05c50 00007ff6`382710b6     : 000000aa`f3c05cc0 00000000`00000001 00007ff6`382732c0 00000000`00000001 : ConsoleApplication1+0x10b6
...[생략]...
000000aa`f3c07230 00007ff6`382710b6     : 000000aa`f3c072a0 00000000`00000001 00007ff6`382732c0 00000000`00000001 : ConsoleApplication1+0x10b6
000000aa`f3c07280 00007ff6`382710b6     : 000000aa`f3c072f0 00000000`00000001 00007ff6`382732c0 00000000`00000001 : ConsoleApplication1+0x10b6
000000aa`f3c072d0 00007ff6`382710b6     : 000000aa`f3c07340 00000000`00000001 00007ff6`382732c0 00000000`00000001 : ConsoleApplication1+0x10b6

...[생략]...

만약 Visual Studio를 선호한다면 위의 덤프를 열게 되었을 때 다음과 같이 CallStack 창이 보일 텐데요,

procdump_native_app_crash_1.png

해당 프레임이 재귀 호출로 인해 제법 깊게 쌓여 있는 것을 확인할 수 있습니다. 검색해 보면 이 값을 조절할 수 있다고 하는데요,

Adjusting StackFrames in Visual Studio
; https://www.poppastring.com/blog/adjusting-stackframes-in-visual-studio

따라서 VSDebugEng_Impl_Engine.pkgdef 파일을 열어,

%VSINSTALLDIR%\Common7\IDE\CommonExtensions\Platform\Debugger\VSDebugEng_Impl_Engine.pkgdef

"C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\CommonExtensions\Platform\Debugger\VSDebugEng_Impl_Engine.pkgdef"

MaxFrames 속성을 찾아 적당한 정도의 16진수 값(기본값: 00001388, 즉 5,000개의 프레임)을 지정하면 됩니다.

...[생략]...

[$RootKey$\Debugger]
"DefaultEvaluationTimeout"=dword:00002710
"MaxFrames"=dword:0000000f

...[생략]...

설정/저장 후, 새로운 비주얼 스튜디오를 띄웠다고 해서 저 변경이 반영되지는 않고 (저 문서에 나온 대로) "devenv /setup" 명령을 한 번 실행해 줘야 합니다. 그래서 위와 같이 0x0f (16)으로 설정한 경우라면 이제 call stack 창에 다음과 같은 출력이 보일 것입니다.

procdump_native_app_crash_2.png




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







[최초 등록일: ]
[최종 수정일: 7/3/2025]

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

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  84  85  [86]  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11824정성태2/25/201920668오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201921755오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201921070오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201921905오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201925012오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201924292Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201921952VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201918122오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201922021Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201920141오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201918498오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201919529.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201916866오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201922985오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201919759.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201922671.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201924205디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
11807정성태1/29/201921994Windows: 156. 가상 디스크의 용량을 복구 파티션으로 인해 늘리지 못하는 경우 [4]
11806정성태1/29/201920825디버깅 기술: 122. windbg - 덤프 파일로부터 PID와 환경 변수 등의 정보를 구하는 방법
11805정성태1/28/201923798.NET Framework: 806. C# - int []와 object []의 차이로 이해하는 제네릭의 필요성 [4]파일 다운로드1
11804정성태1/24/201921336Windows: 155. diskpart - remove letter 이후 재부팅 시 다시 드라이브 문자가 할당되는 경우
11803정성태1/10/201920239디버깅 기술: 121. windbg - 닷넷 Finalizer 스레드가 멈춰있는 현상
11802정성태1/7/201921845.NET Framework: 805. 두 개의 윈도우를 각각 실행하는 방법(Windows Forms, WPF)파일 다운로드1
11801정성태1/1/201922835개발 환경 구성: 427. Netsh의 네트워크 모니터링 기능 [3]
11800정성태12/28/201822245오류 유형: 509. WCF 호출 오류 메시지 - System.ServiceModel.CommunicationException: Internal Server Error
11799정성태12/19/201824471.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법 [3]파일 다운로드1
... 76  77  78  79  80  81  82  83  84  85  [86]  87  88  89  90  ...