xref: /llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/WindowsMiniDump.cpp (revision 32abe5d49b758edef0f0c19090361a6fe85c4092)
1 //===-- WindowsMiniDump.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 // This function is separated out from ObjectFilePECOFF.cpp to name avoid name
10 // collisions with WinAPI preprocessor macros.
11 
12 #include "WindowsMiniDump.h"
13 #include "lldb/Utility/FileSpec.h"
14 #include "llvm/Support/ConvertUTF.h"
15 
16 #ifdef _WIN32
17 #include "lldb/Host/windows/windows.h"
18 #include <dbghelp.h>
19 #endif
20 
21 namespace lldb_private {
22 
23 bool SaveMiniDump(const lldb::ProcessSP &process_sp,
24                   SaveCoreOptions &core_options, lldb_private::Status &error) {
25   if (!process_sp)
26     return false;
27 #ifdef _WIN32
28   std::optional<FileSpec> outfileSpec = core_options.GetOutputFile();
29   const auto &outfile = outfileSpec.value();
30   HANDLE process_handle = ::OpenProcess(
31       PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_sp->GetID());
32   const std::string file_name = outfile.GetPath();
33   std::wstring wide_name;
34   wide_name.resize(file_name.size() + 1);
35   char *result_ptr = reinterpret_cast<char *>(&wide_name[0]);
36   const llvm::UTF8 *error_ptr = nullptr;
37   if (!llvm::ConvertUTF8toWide(sizeof(wchar_t), file_name, result_ptr,
38                                error_ptr)) {
39     error = Status::FromErrorString("cannot convert file name");
40     return false;
41   }
42   HANDLE file_handle =
43       ::CreateFileW(wide_name.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL,
44                     CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
45   const auto result =
46       ::MiniDumpWriteDump(process_handle, process_sp->GetID(), file_handle,
47                           MiniDumpWithFullMemoryInfo, NULL, NULL, NULL);
48   ::CloseHandle(file_handle);
49   ::CloseHandle(process_handle);
50   if (!result) {
51     error = Status(::GetLastError(), lldb::eErrorTypeWin32);
52     return false;
53   }
54   return true;
55 #endif
56   return false;
57 }
58 
59 } // namesapce lldb_private
60