Windows C++ 애플리케이션의 크래시 분석을 위한 덤프 파일 생성 기법

Windows 환경에서 C++ 애플리케이션을 개발할 때 예외 추적 및 크래시 분석은 매우 중요한 요소입니다. C++은 Java나 C#과 달리 런타임에 스택 트레이스 정보를 직접 추출하는 내장 메커니즘이 부족합니다. 따라서 예외가 발생하거나 오류가 반환될 때 호출 스택 정보를 자동으로 기록하기 어렵습니다. 이러한 한계를 극복하고 정확한 버그 분석을 수행하기 위해서는 전역 예외를捕获(캡처)하여 메모리 상태를 덤프(Dump) 파일로 저장하는 기능이 필수적입니다.

핵심 메커니즘

1. 전역 예외 핸들러 등록

예측하지 못한 크래시를 잡기 위해서는 Win32 API인 SetUnhandledExceptionFilter를 사용하여 전역 예외 필터를 등록해야 합니다. 이 콜백 함수는 처리되지 않은 예외가 발생할 때 시스템에 의해 호출됩니다.

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

// 전역 예외 처리 콜백 함수
LONG WINAPI GlobalExceptionCallback(LPEXCEPTION_POINTERS exceptionInfo) {
    std::cout << "Unhandled exception caught. Generating dump..." << std::endl;
    return EXCEPTION_EXECUTE_HANDLER;
}

int main() {
    // 전역 예외 필터 등록
    SetUnhandledExceptionFilter(GlobalExceptionCallback);
    
    // 애플리케이션 로직 실행
    return 0;
}

2. 미니덤프 파일 작성

실제 덤프 파일을 생성하기 위해서는 DbgHelp.h에 정의된 MiniDumpWriteDump 함수를 사용합니다. 이 함수는 EXCEPTION_POINTERS 구조체를 필요로 하며, 이는 전역 예외 콜백의 인자로 전달받거나 인위적으로 예외를 발생시켜 획득할 수 있습니다.

#include <Windows.h>
#include <DbgHelp.h>
#include <string>

#pragma comment(lib, "Dbghelp.lib")

void CaptureMemoryState(const std::string& filePath) {
    __try {
        // 인위적으로 예외를 발생시켜 현재 스레드의 컨텍스트 획득
        RaiseException(0xE0000002, 0, 0, NULL);
    } 
    __except (WriteMinidumpToFile(GetExceptionInformation(), filePath)) {
        // 예외가 처리되었으므로 프로그램은 종료되지 않고 계속 실행됨
    }
}

유틸리티 클래스 구현

위의 핵심 로직을 재사용 가능하고 유지보수가 용이하도록 클래스로 캡슐화합니다. 디렉토리 자동 생성, 오래된 덤프 파일 정리, 그리고 임의 시점의 스냅샷 기능을 포함하도록 설계를 변경했습니다.

CrashDumpManager.h

#pragma once
#include <string>

namespace SystemDiagnostics {
    class CrashDumpManager {
    public:
        // 크래시 발생 시 덤프 생성 기능 활성화/비활성화
        static void EnableCrashDump(bool isEnabled);
        
        // 덤프 파일이 저장될 디렉토리 경로 설정
        static void ConfigureDumpDirectory(const std::string& dirPath);
        
        // 보관할 최대 덤프 파일 개수 설정 (초과 시 오래된 파일 자동 삭제)
        static void SetMaxDumpLimit(int limit);
        
        // 현재 시점의 메모리 스냅샷 수동 캡처
        static void CaptureMemorySnapshot(const std::string& filePath);
    };
}

CrashDumpManager.cpp

#include "CrashDumpManager.h"
#include <Windows.h>
#include <DbgHelp.h>
#include <ShlObj.h>
#include <ctime>
#include <vector>
#include <algorithm>
#include <iostream>

#pragma comment(lib, "Dbghelp.lib")
#pragma comment(lib, "Shell32.lib")

namespace SystemDiagnostics {
    static std::string dumpDirPath_ = ".\\";
    static int maxDumpFiles_ = 100;

    // 디렉토리 존재 여부 확인 및 생성
    static bool EnsureDirectoryExists(const std::string& path) {
        DWORD attrib = GetFileAttributesA(path.c_str());
        if (attrib == INVALID_FILE_ATTRIBUTES) {
            return SHCreateDirectoryExA(NULL, path.c_str(), NULL) == ERROR_SUCCESS;
        }
        return (attrib & FILE_ATTRIBUTE_DIRECTORY) != 0;
    }

    // 오래된 덤프 파일 정리
    static void CleanupOldDumps(const std::string& dir, int maxFiles) {
        std::string searchPath = dir + "\\*.dmp";
        WIN32_FIND_DATAA findData;
        HANDLE hFind = FindFirstFileA(searchPath.c_str(), &findData);
        if (hFind == INVALID_HANDLE_VALUE) return;

        std::vector<std::string> dumpFiles;
        do {
            dumpFiles.push_back(dir + "\\" + findData.cFileName);
        } while (FindNextFileA(hFind, &findData));
        FindClose(hFind);

        if (static_cast<int>(dumpFiles.size()) <= maxFiles) return;

        // 파일명(타임스탬프) 기준 정렬
        std::sort(dumpFiles.begin(), dumpFiles.end());
        
        size_t filesToDelete = dumpFiles.size() - maxFiles;
        for (size_t i = 0; i < filesToDelete; ++i) {
            DeleteFileA(dumpFiles[i].c_str());
        }
    }

    // 실제 미니덤프 기록
    static int WriteMinidumpToFile(EXCEPTION_POINTERS* exceptionPtrs, const std::string& path) {
        HANDLE hFile = CreateFileA(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        if (hFile != INVALID_HANDLE_VALUE) {
            MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
            dumpInfo.ThreadId = GetCurrentThreadId();
            dumpInfo.ExceptionPointers = exceptionPtrs;
            dumpInfo.ClientPointers = TRUE;

            MiniDumpWriteDump(
                GetCurrentProcess(),
                GetCurrentProcessId(),
                hFile,
                MiniDumpNormal,
                &dumpInfo,
                NULL,
                NULL
            );
            CloseHandle(hFile);
        }
        return EXCEPTION_EXECUTE_HANDLER;
    }

    // 전역 예외 콜백
    static LONG WINAPI GlobalExceptionCallback(LPEXCEPTION_POINTERS exceptionInfo) {
        if (!EnsureDirectoryExists(dumpDirPath_)) {
            return EXCEPTION_EXECUTE_HANDLER;
        }

        CleanupOldDumps(dumpDirPath_, maxDumpFiles_);

        time_t now = time(NULL);
        struct tm timeInfo;
        localtime_s(&timeInfo, &now);

        char fileName[MAX_PATH];
        sprintf_s(fileName, "%s\\crash_%04d%02d%02d_%02d%02d%02d.dmp", 
            dumpDirPath_.c_str(), 
            timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday,
            timeInfo.tm_hour, timeInfo.tm_min, timeInfo.tm_sec);

        return WriteMinidumpToFile(exceptionInfo, fileName);
    }

    void CrashDumpManager::EnableCrashDump(bool isEnabled) {
        SetUnhandledExceptionFilter(isEnabled ? GlobalExceptionCallback : NULL);
    }

    void CrashDumpManager::ConfigureDumpDirectory(const std::string& dirPath) {
        dumpDirPath_ = dirPath;
        if (dumpDirPath_.empty()) {
            dumpDirPath_ = ".\\";
        } else if (dumpDirPath_.back() != '\\') {
            dumpDirPath_.push_back('\\');
        }
    }

    void CrashDumpManager::SetMaxDumpLimit(int limit) {
        maxDumpFiles_ = (limit > 0) ? limit : 100;
    }

    void CrashDumpManager::CaptureMemorySnapshot(const std::string& filePath) {
        __try {
            RaiseException(0xE0000002, 0, 0, NULL);
        } 
        __except (WriteMinidumpToFile(GetExceptionInformation(), filePath)) {
            // 스냅샷 캡처 후 정상 흐름으로 복귀
        }
    }
}

활용 예제

1. 크래시 발생 시 자동 덤프 생성

애플리케이션 초기화 단계에서 전역 예외 핸들러를 등록해 두면, 처리되지 않은 예외(예: 0으로 나누기, 널 포인터 접근 등)가 발생할 때 자동으로 덤프 파일이 생성됩니다.

#include "CrashDumpManager.h"
#include <iostream>

int main() {
    // 크래시 덤프 기능 활성화
    SystemDiagnostics::CrashDumpManager::EnableCrashDump(true);
    
    // 저장 경로 및 최대 보관 개수 설정
    SystemDiagnostics::CrashDumpManager::ConfigureDumpDirectory("C:\\AppLogs\\Dumps");
    SystemDiagnostics::CrashDumpManager::SetMaxDumpLimit(20);

    std::cout << "Application started. Triggering crash..." << std::endl;

    // 고의적인 크래시 유발 (Access Violation)
    int* nullPtr = nullptr;
    *nullPtr = 42; 

    return 0;
}

위 코드가 실행되면 지정된 디렉토리에 .dmp 파일이 생성됩니다. Visual Studio에서 해당 덤프 파일을 열고 디버깅을 시작하면, 크래시가 발생한 정확한 코드 라인과 호출 스택을 확인할 수 있습니다. (단, 빌드 시 생성된 PDB 파일과 소스 코드가 덤프 파일과 정확히 일치해야 합니다.)

2. 임의 시점의 메모리 스냅샷 추출

프로그램이 크래시하지 않더라도, 특정 로직의 상태를 분석하기 위해 CaptureMemorySnapshot 메서드를 호출하여 현재 메모리 상태를 저장할 수 있습니다. 이 과정은 내부적으로 예외를 발생시키고 즉시 처리하므로 애플리케이션의 정상적인 실행 흐름을 중단시키지 않습니다.

#include "CrashDumpManager.h"
#include <iostream>
#include <vector>

void ProcessHeavyData() {
    std::vector<int> data(1000000, 42);
    
    // 복잡한 로직 수행 중 메모리 상태 스냅샷 저장
    SystemDiagnostics::CrashDumpManager::CaptureMemorySnapshot("C:\\AppLogs\\Dumps\\snapshot_mid_process.dmp");
    
    // 후속 작업 계속 진행
    std::cout << "Data processing completed." << std::endl;
}

int main() {
    ProcessHeavyData();
    return 0;
}

태그: C++ Windows Minidump ExceptionHandling DbgHelp

10월 23일 04:38에 게시됨