12#include "llvm/Support/Windows/WindowsSupport.h"
14#include "llvm/ADT/SmallVector.h"
15#include "llvm/Support/ConvertUTF.h"
16#include "llvm/Support/FileSystem.h"
17#include "llvm/Support/Path.h"
22#if defined(LLDB_PYTHON_DLL_RELATIVE_PATH) || \
23 defined(LLDB_PYTHON_RUNTIME_LIBRARY_FILENAME)
24static std::string GetModulePath(HMODULE module) {
25 std::vector<WCHAR> buffer(MAX_PATH);
26 while (buffer.size() <= PATHCCH_MAX_CCH) {
27 DWORD len = GetModuleFileNameW(module, buffer.data(), buffer.size());
30 if (len < buffer.size()) {
31 std::string buffer_utf8;
32 if (convertWideToUTF8(std::wstring(buffer.data(), len), buffer_utf8))
36 if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER)
37 buffer.resize(buffer.size() * 2);
43#ifdef LLDB_PYTHON_DLL_RELATIVE_PATH
45static std::string GetPathToExecutable() {
return GetModulePath(NULL); }
47bool AddPythonDLLToSearchPath() {
48 std::string path_str = GetPathToExecutable();
52 SmallVector<char, MAX_PATH> path(path_str.begin(), path_str.end());
53 sys::path::remove_filename(path);
54 sys::path::append(path, LLDB_PYTHON_DLL_RELATIVE_PATH);
55 sys::fs::make_absolute(path);
57 SmallVector<wchar_t, 1> path_wide;
58 if (sys::windows::widenPath(path.data(), path_wide))
61 if (sys::fs::exists(path))
62 return SetDllDirectoryW(path_wide.data());
67#ifdef LLDB_PYTHON_RUNTIME_LIBRARY_FILENAME
68std::optional<std::string> GetPythonDLLPath() {
70#define WIDEN(x) WIDEN2(x)
71 HMODULE h = LoadLibraryW(WIDEN(LLDB_PYTHON_RUNTIME_LIBRARY_FILENAME));
75 std::string path = GetModulePath(h);
85#ifdef LLDB_PYTHON_RUNTIME_LIBRARY_FILENAME
86 if (std::optional<std::string> python_path = GetPythonDLLPath())
88#ifdef LLDB_PYTHON_DLL_RELATIVE_PATH
89 if (AddPythonDLLToSearchPath()) {
90 if (std::optional<std::string> python_path = GetPythonDLLPath())
94 return createStringError(
95 inconvertibleErrorCode(),
96 "unable to find '" LLDB_PYTHON_RUNTIME_LIBRARY_FILENAME
"'");
97#elif defined(LLDB_PYTHON_DLL_RELATIVE_PATH)
98 if (!AddPythonDLLToSearchPath())
99 return createStringError(inconvertibleErrorCode(),
100 "unable to find the Python runtime library");
llvm::Expected< std::string > SetupPythonRuntimeLibrary()
Attempts to setup the DLL search path for the Python runtime library.