Created
August 8, 2018 17:58
-
-
Save allenh1/38441719a2397b2be6176fa406e38d26 to your computer and use it in GitHub Desktop.
An example of how to create a Mini Dump on Windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <functional> | |
| #include <iostream> | |
| #include <windows.h> | |
| #include <dbghelp.h> | |
| template<typename Callback> | |
| struct ScopeExit | |
| { | |
| explicit ScopeExit(Callback p_func) | |
| : m_func(p_func) {} | |
| ~ScopeExit() { m_func(); } | |
| private: | |
| Callback m_func; | |
| }; | |
| template<typename Callback> | |
| ScopeExit<Callback> make_scope_exit(Callback p_func) | |
| { | |
| return ScopeExit<Callback>(p_func); | |
| } | |
| inline auto load_write_minidump(HMODULE & lib) | |
| { | |
| /* TODO(hallen): gross */ | |
| auto cast_version = reinterpret_cast<BOOL (*)(HANDLE, DWORD, HANDLE, MINIDUMP_TYPE, PMINIDUMP_EXCEPTION_INFORMATION, PMINIDUMP_USER_STREAM_INFORMATION, PMINIDUMP_CALLBACK_INFORMATION)>(::GetProcAddress(lib, "MiniDumpWriteDump")); | |
| return std::function<BOOL(HANDLE, DWORD, HANDLE, MINIDUMP_TYPE, PMINIDUMP_EXCEPTION_INFORMATION, PMINIDUMP_USER_STREAM_INFORMATION, PMINIDUMP_CALLBACK_INFORMATION)>(cast_version); | |
| } | |
| bool create_mini_dump(const LPCSTR & file_name) { | |
| HMODULE dbghelp_module = ::LoadLibrary(TEXT("dbghelp.dll")); | |
| HANDLE hFile = | |
| ::CreateFile(file_name, GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); | |
| auto at_exit = make_scope_exit( | |
| [hFile, dbghelp_module]() { | |
| ::CloseHandle(hFile); | |
| ::FreeLibrary(dbghelp_module); | |
| }); | |
| auto minidump_writer = load_write_minidump(dbghelp_module); | |
| if (nullptr == hFile || INVALID_HANDLE_VALUE == hFile) { | |
| std::cerr << "Failed to create MiniDump file!" << std::endl; | |
| return false; | |
| } | |
| // initialize the minidump | |
| MINIDUMP_TYPE type = MiniDumpNormal; | |
| BOOL ret = minidump_writer(::GetCurrentProcess(), ::GetCurrentProcessId(), hFile, type, nullptr, 0, 0); | |
| return ret; | |
| } | |
| int main(int argc, char ** argv) | |
| { | |
| static_cast<void>(argc); | |
| static_cast<void>(argv); | |
| try { | |
| throw std::invalid_argument("OH NO"); | |
| } catch (std::invalid_argument & e) { | |
| std::cerr << "caught exception '" << e.what() << "'" << std::endl; | |
| create_mini_dump("OH_NO.dmp"); | |
| return 1; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment