LLDB mainline
windows/Host.cpp
Go to the documentation of this file.
1//===-- source/Host/windows/Host.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
12#include <cstdio>
13
15#include "lldb/Host/Host.h"
16#include "lldb/Host/HostInfo.h"
20#include "lldb/Utility/Log.h"
22#include "lldb/Utility/Status.h"
25
26#include "llvm/ADT/StringRef.h"
27#include "llvm/Support/ConvertUTF.h"
28
29// Windows includes
30#include <tlhelp32.h>
31
32using namespace lldb;
33using namespace lldb_private;
34
35using llvm::sys::windows::UTF8ToUTF16;
36
37static bool GetTripleForProcess(const FileSpec &executable,
38 llvm::Triple &triple) {
39 // Open the PE File as a binary file, and parse just enough information to
40 // determine the machine type.
41 auto imageBinaryP = FileSystem::Instance().Open(
42 executable, File::eOpenOptionReadOnly, lldb::eFilePermissionsUserRead);
43 if (!imageBinaryP)
44 return llvm::errorToBool(imageBinaryP.takeError());
45 File &imageBinary = *imageBinaryP.get();
46 imageBinary.SeekFromStart(0x3c);
47 int32_t peOffset = 0;
48 uint32_t peHead = 0;
49 uint16_t machineType = 0;
50 size_t readSize = sizeof(peOffset);
51 imageBinary.Read(&peOffset, readSize);
52 imageBinary.SeekFromStart(peOffset);
53 imageBinary.Read(&peHead, readSize);
54 if (peHead != 0x00004550) // "PE\0\0", little-endian
55 return false; // Status: Can't find PE header
56 readSize = 2;
57 imageBinary.Read(&machineType, readSize);
58 triple.setVendor(llvm::Triple::PC);
59 triple.setOS(llvm::Triple::Win32);
60 triple.setArch(llvm::Triple::UnknownArch);
61 if (machineType == 0x8664)
62 triple.setArch(llvm::Triple::x86_64);
63 else if (machineType == 0x14c)
64 triple.setArch(llvm::Triple::x86);
65 else if (machineType == 0x1c4)
66 triple.setArch(llvm::Triple::arm);
67 else if (machineType == 0xaa64)
68 triple.setArch(llvm::Triple::aarch64);
69
70 return true;
71}
72
73static bool GetExecutableForProcess(const AutoHandle &handle,
74 std::string &path) {
75 // Get the process image path. MAX_PATH isn't long enough, paths can
76 // actually be up to 32KB.
77 std::vector<wchar_t> buffer(PATH_MAX);
78 DWORD dwSize = buffer.size();
79 if (!::QueryFullProcessImageNameW(handle.get(), 0, &buffer[0], &dwSize))
80 return false;
81 if (!llvm::convertWideToUTF8(buffer.data(), path))
82 return false;
83 // A process launched through an extended-length path has the "\\?\" prefix.
84 path = StripExtendedLengthPrefix(path);
85 return true;
86}
87
88static void GetProcessExecutableAndTriple(const AutoHandle &handle,
89 ProcessInstanceInfo &process) {
90 // We may not have permissions to read the path from the process. So start
91 // off by setting the executable file to whatever Toolhelp32 gives us, and
92 // then try to enhance this with more detailed information, but fail
93 // gracefully.
94 std::string executable;
95 llvm::Triple triple;
96 triple.setVendor(llvm::Triple::PC);
97 triple.setOS(llvm::Triple::Win32);
98 triple.setArch(llvm::Triple::UnknownArch);
99 if (GetExecutableForProcess(handle, executable)) {
100 FileSpec executableFile(executable.c_str());
101 process.SetExecutableFile(executableFile, true);
102 GetTripleForProcess(executableFile, triple);
103 }
104 process.SetArchitecture(ArchSpec(triple));
105
106 // TODO(zturner): Add the ability to get the process user name.
107}
108
111}
112
113void Host::Kill(lldb::pid_t pid, int signo) {
114 AutoHandle handle(::OpenProcess(PROCESS_TERMINATE, FALSE, pid), nullptr);
115 if (handle.IsValid())
116 ::TerminateProcess(handle.get(), 1);
117}
118
119const char *Host::GetSignalAsCString(int signo) { return nullptr; }
120
121FileSpec Host::GetModuleFileSpecForHostAddress(const void *host_addr) {
122 FileSpec module_filespec;
123
124 HMODULE hmodule = nullptr;
125 if (!::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
126 (LPCTSTR)host_addr, &hmodule))
127 return module_filespec;
128
129 std::vector<wchar_t> buffer(PATH_MAX);
130 DWORD chars_copied = 0;
131 do {
132 chars_copied = ::GetModuleFileNameW(hmodule, &buffer[0], buffer.size());
133 if (chars_copied == buffer.size() &&
134 ::GetLastError() == ERROR_INSUFFICIENT_BUFFER)
135 buffer.resize(buffer.size() * 2);
136 } while (chars_copied >= buffer.size());
137 std::string path;
138 if (!llvm::convertWideToUTF8(buffer.data(), path))
139 return module_filespec;
140 module_filespec.SetFile(path, FileSpec::Style::native);
141 return module_filespec;
142}
143
144// CreateToolhelp32Snapshot walks a process list that other processes are
145// concurrently modifying, and fails with ERROR_BAD_LENGTH when it loses that
146// race. The documented remedy is to retry.
148 constexpr int max_attempts = 10;
149 for (int attempt = 0; attempt < max_attempts; ++attempt) {
150 HANDLE snapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
151 if (snapshot != INVALID_HANDLE_VALUE ||
152 ::GetLastError() != ERROR_BAD_LENGTH)
153 return snapshot;
154 }
155 return INVALID_HANDLE_VALUE;
156}
157
158uint32_t Host::FindProcessesImpl(const ProcessInstanceInfoMatch &match_info,
159 ProcessInstanceInfoList &process_infos) {
160 process_infos.clear();
161
162 AutoHandle snapshot(CreateProcessSnapshot());
163 if (!snapshot.IsValid())
164 return 0;
165
166 PROCESSENTRY32W pe = {};
167 pe.dwSize = sizeof(PROCESSENTRY32W);
168 if (Process32FirstW(snapshot.get(), &pe)) {
169 do {
170 AutoHandle handle(::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE,
171 pe.th32ProcessID),
172 nullptr);
173
174 ProcessInstanceInfo process;
175 std::string exeFile;
176 llvm::convertWideToUTF8(pe.szExeFile, exeFile);
177 process.SetExecutableFile(FileSpec(exeFile), true);
178 process.SetProcessID(pe.th32ProcessID);
179 process.SetParentProcessID(pe.th32ParentProcessID);
180 GetProcessExecutableAndTriple(handle, process);
181
182 if (match_info.MatchAllProcesses() || match_info.Matches(process))
183 process_infos.push_back(process);
184 } while (Process32NextW(snapshot.get(), &pe));
185 }
186 return process_infos.size();
187}
188
190 process_info.Clear();
191
192 AutoHandle handle(
193 ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid),
194 nullptr);
195 if (!handle.IsValid())
196 return false;
197
198 process_info.SetProcessID(pid);
199 GetProcessExecutableAndTriple(handle, process_info);
200
201 AutoHandle snapshot(CreateProcessSnapshot());
202 if (!snapshot.IsValid())
203 return false;
204
205 PROCESSENTRY32W pe;
206 pe.dwSize = sizeof(PROCESSENTRY32W);
207 if (!Process32FirstW(snapshot.get(), &pe))
208 return false;
209
210 do {
211 if (pe.th32ProcessID == pid) {
212 process_info.SetParentProcessID(pe.th32ParentProcessID);
213 return true;
214 }
215 } while (Process32NextW(snapshot.get(), &pe));
216
217 return false;
218}
219
220llvm::Expected<HostThread> Host::StartMonitoringChildProcess(
221 const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid) {
222 return HostThread();
223}
224
226 const Timeout<std::micro> &timeout) {
228 if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) {
229 FileSpec expand_tool_spec = HostInfo::GetSupportExeDir();
230 if (!expand_tool_spec) {
232 "could not find support executable directory for "
233 "the lldb-argdumper tool");
234 return error;
235 }
236 expand_tool_spec.AppendPathComponent("lldb-argdumper.exe");
237 if (!FileSystem::Instance().Exists(expand_tool_spec)) {
238 error = Status::FromErrorString("could not find the lldb-argdumper tool");
239 return error;
240 }
241
242 std::string quoted_cmd_string;
243 launch_info.GetArguments().GetQuotedCommandString(quoted_cmd_string);
244 std::replace(quoted_cmd_string.begin(), quoted_cmd_string.end(), '\\', '/');
245 StreamString expand_command;
246
247 expand_command.Printf("\"%s\" %s", expand_tool_spec.GetPath().c_str(),
248 quoted_cmd_string.c_str());
249
250 int status;
251 std::string output;
252 std::string command = expand_command.GetString().str();
253 Status e =
254 RunShellCommand(command.c_str(), launch_info.GetWorkingDirectory(),
255 &status, nullptr, &output, nullptr, timeout);
256
257 if (e.Fail())
258 return e;
259
260 if (status != 0) {
262 "lldb-argdumper exited with error %d", status);
263 return error;
264 }
265
266 auto data_sp = StructuredData::ParseJSON(output);
267 if (!data_sp) {
268 error = Status::FromErrorString("invalid JSON");
269 return error;
270 }
271
272 auto dict_sp = data_sp->GetAsDictionary();
273 if (!dict_sp) {
274 error = Status::FromErrorString("invalid JSON");
275 return error;
276 }
277
278 auto args_sp = dict_sp->GetObjectForDotSeparatedPath("arguments");
279 if (!args_sp) {
280 error = Status::FromErrorString("invalid JSON");
281 return error;
282 }
283
284 auto args_array_sp = args_sp->GetAsArray();
285 if (!args_array_sp) {
286 error = Status::FromErrorString("invalid JSON");
287 return error;
288 }
289
290 launch_info.GetArguments().Clear();
291
292 for (size_t i = 0; i < args_array_sp->GetSize(); i++) {
293 auto item_sp = args_array_sp->GetItemAtIndex(i);
294 if (!item_sp)
295 continue;
296 auto str_sp = item_sp->GetAsString();
297 if (!str_sp)
298 continue;
299
300 launch_info.GetArguments().AppendArgument(str_sp->GetValue());
301 }
302 }
303
304 return error;
305}
306
308 Environment env;
309 // The environment block on Windows is a contiguous buffer of null-terminated
310 // strings, where the end of the environment block is indicated by two
311 // consecutive NULLs.
312 LPWCH environment_block = ::GetEnvironmentStringsW();
313 while (*environment_block != L'\0') {
314 std::string current_var;
315 auto current_var_size = wcslen(environment_block) + 1;
316 if (!llvm::convertWideToUTF8(environment_block, current_var)) {
317 environment_block += current_var_size;
318 continue;
319 }
320 if (current_var[0] != '=')
321 env.insert(current_var);
322
323 environment_block += current_var_size;
324 }
325 return env;
326}
327
328void Host::SystemLog(Severity severity, llvm::StringRef message) {
329 if (message.empty())
330 return;
331
332 std::string log_msg;
333 llvm::raw_string_ostream stream(log_msg);
334
335 switch (severity) {
337 stream << "[Warning] ";
338 break;
340 stream << "[Error] ";
341 break;
343 stream << "[Info] ";
344 break;
345 }
346
347 stream << message;
348 stream.flush();
349
350 OutputDebugStringA(log_msg.c_str());
351}
static llvm::raw_ostream & error(Stream &strm)
void * HANDLE
An architecture specification class.
Definition ArchSpec.h:32
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition Args.cpp:332
bool GetQuotedCommandString(std::string &command) const
Definition Args.cpp:232
void Clear()
Clear the arguments.
Definition Args.cpp:388
std::pair< iterator, bool > insert(llvm::StringRef KeyEqValue)
Definition Environment.h:72
A file utility class.
Definition FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
void AppendPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:454
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
int Open(const char *path, int flags, int mode=0600)
Wraps open in a platform-independent way.
static FileSystem & Instance()
An abstract base class for files.
Definition FileBase.h:34
Status Read(void *buf, size_t &num_bytes) override
Read bytes from a file from the current file position into buf.
Definition File.cpp:99
virtual off_t SeekFromStart(off_t offset, Status *error_ptr=nullptr)
Seek to an offset relative to the beginning of the file.
Definition File.cpp:123
bool Test(ValueType bit) const
Test a single flag bit.
Definition Flags.h:96
static void SystemLog(lldb::Severity severity, llvm::StringRef message)
Emit the given message to the operating system log.
static lldb::thread_t GetCurrentThread()
Get the thread token (the one returned by ThreadCreate when the thread was created) for the calling t...
static Status ShellExpandArguments(ProcessLaunchInfo &launch_info, const Timeout< std::micro > &timeout)
Perform expansion of the command-line for this launch info This can potentially involve wildcard expa...
Definition aix/Host.cpp:216
static Environment GetEnvironment()
static Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, std::string *error_output, const Timeout< std::micro > &timeout, bool run_in_shell=true)
Run a shell command.
static uint32_t FindProcessesImpl(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &proc_infos)
Definition aix/Host.cpp:169
static bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info)
Definition aix/Host.cpp:211
static FileSpec GetModuleFileSpecForHostAddress(const void *host_addr)
Given an address in the current process (the process that is running the LLDB code),...
std::function< void(lldb::pid_t pid, int signal, int status)> MonitorChildProcessCallback
Definition Host.h:88
static llvm::Expected< HostThread > StartMonitoringChildProcess(const MonitorChildProcessCallback &callback, lldb::pid_t pid)
Start monitoring a child process.
static void Kill(lldb::pid_t pid, int signo)
static const char * GetSignalAsCString(int signo)
void SetExecutableFile(const FileSpec &exe_file, bool add_exe_file_as_first_arg)
void SetArchitecture(const ArchSpec &arch)
Definition ProcessInfo.h:64
void SetProcessID(lldb::pid_t pid)
Definition ProcessInfo.h:68
bool Matches(const ProcessInstanceInfo &proc_info) const
void SetParentProcessID(lldb::pid_t pid)
const FileSpec & GetWorkingDirectory() const
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
llvm::StringRef GetString() const
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
static ObjectSP ParseJSON(llvm::StringRef json_text)
A class that represents a running process on the host machine.
std::string StripExtendedLengthPrefix(llvm::StringRef path)
Convert an extended-length path to a regular DOS path: "\\?\C:\a" becomes "C:\a" and "\\?...
Definition PathUtils.h:21
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
Definition Host.h:32
Severity
Used for expressing severity in logs and diagnostics.
pthread_t thread_t
Definition lldb-types.h:58
uint64_t pid_t
Definition lldb-types.h:84
static void GetProcessExecutableAndTriple(const AutoHandle &handle, ProcessInstanceInfo &process)
static bool GetTripleForProcess(const FileSpec &executable, llvm::Triple &triple)
static HANDLE CreateProcessSnapshot()
static bool GetExecutableForProcess(const AutoHandle &handle, std::string &path)
#define PATH_MAX