Host.cpp
9.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//===-- source/Host/windows/Host.cpp --------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Host/windows/AutoHandle.h"
#include "lldb/Host/windows/windows.h"
#include <stdio.h>
#include "lldb/Host/FileSystem.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/ProcessLaunchInfo.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/ProcessInfo.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/StructuredData.h"
#include "llvm/Support/ConvertUTF.h"
// Windows includes
#include <tlhelp32.h>
using namespace lldb;
using namespace lldb_private;
namespace {
bool GetTripleForProcess(const FileSpec &executable, llvm::Triple &triple) {
// Open the PE File as a binary file, and parse just enough information to
// determine the machine type.
auto imageBinaryP = FileSystem::Instance().Open(
executable, File::eOpenOptionRead, lldb::eFilePermissionsUserRead);
if (!imageBinaryP)
return llvm::errorToBool(imageBinaryP.takeError());
File &imageBinary = *imageBinaryP.get();
imageBinary.SeekFromStart(0x3c);
int32_t peOffset = 0;
uint32_t peHead = 0;
uint16_t machineType = 0;
size_t readSize = sizeof(peOffset);
imageBinary.Read(&peOffset, readSize);
imageBinary.SeekFromStart(peOffset);
imageBinary.Read(&peHead, readSize);
if (peHead != 0x00004550) // "PE\0\0", little-endian
return false; // Status: Can't find PE header
readSize = 2;
imageBinary.Read(&machineType, readSize);
triple.setVendor(llvm::Triple::PC);
triple.setOS(llvm::Triple::Win32);
triple.setArch(llvm::Triple::UnknownArch);
if (machineType == 0x8664)
triple.setArch(llvm::Triple::x86_64);
else if (machineType == 0x14c)
triple.setArch(llvm::Triple::x86);
else if (machineType == 0x1c4)
triple.setArch(llvm::Triple::arm);
else if (machineType == 0xaa64)
triple.setArch(llvm::Triple::aarch64);
return true;
}
bool GetExecutableForProcess(const AutoHandle &handle, std::string &path) {
// Get the process image path. MAX_PATH isn't long enough, paths can
// actually be up to 32KB.
std::vector<wchar_t> buffer(PATH_MAX);
DWORD dwSize = buffer.size();
if (!::QueryFullProcessImageNameW(handle.get(), 0, &buffer[0], &dwSize))
return false;
return llvm::convertWideToUTF8(buffer.data(), path);
}
void GetProcessExecutableAndTriple(const AutoHandle &handle,
ProcessInstanceInfo &process) {
// We may not have permissions to read the path from the process. So start
// off by setting the executable file to whatever Toolhelp32 gives us, and
// then try to enhance this with more detailed information, but fail
// gracefully.
std::string executable;
llvm::Triple triple;
triple.setVendor(llvm::Triple::PC);
triple.setOS(llvm::Triple::Win32);
triple.setArch(llvm::Triple::UnknownArch);
if (GetExecutableForProcess(handle, executable)) {
FileSpec executableFile(executable.c_str());
process.SetExecutableFile(executableFile, true);
GetTripleForProcess(executableFile, triple);
}
process.SetArchitecture(ArchSpec(triple));
// TODO(zturner): Add the ability to get the process user name.
}
}
lldb::thread_t Host::GetCurrentThread() {
return lldb::thread_t(::GetCurrentThread());
}
void Host::Kill(lldb::pid_t pid, int signo) {
TerminateProcess((HANDLE)pid, 1);
}
const char *Host::GetSignalAsCString(int signo) { return NULL; }
FileSpec Host::GetModuleFileSpecForHostAddress(const void *host_addr) {
FileSpec module_filespec;
HMODULE hmodule = NULL;
if (!::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCTSTR)host_addr, &hmodule))
return module_filespec;
std::vector<wchar_t> buffer(PATH_MAX);
DWORD chars_copied = 0;
do {
chars_copied = ::GetModuleFileNameW(hmodule, &buffer[0], buffer.size());
if (chars_copied == buffer.size() &&
::GetLastError() == ERROR_INSUFFICIENT_BUFFER)
buffer.resize(buffer.size() * 2);
} while (chars_copied >= buffer.size());
std::string path;
if (!llvm::convertWideToUTF8(buffer.data(), path))
return module_filespec;
module_filespec.SetFile(path, FileSpec::Style::native);
return module_filespec;
}
uint32_t Host::FindProcessesImpl(const ProcessInstanceInfoMatch &match_info,
ProcessInstanceInfoList &process_infos) {
process_infos.clear();
AutoHandle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
if (!snapshot.IsValid())
return 0;
PROCESSENTRY32W pe = {};
pe.dwSize = sizeof(PROCESSENTRY32W);
if (Process32FirstW(snapshot.get(), &pe)) {
do {
AutoHandle handle(::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE,
pe.th32ProcessID),
nullptr);
ProcessInstanceInfo process;
std::string exeFile;
llvm::convertWideToUTF8(pe.szExeFile, exeFile);
process.SetExecutableFile(FileSpec(exeFile), true);
process.SetProcessID(pe.th32ProcessID);
process.SetParentProcessID(pe.th32ParentProcessID);
GetProcessExecutableAndTriple(handle, process);
if (match_info.MatchAllProcesses() || match_info.Matches(process))
process_infos.push_back(process);
} while (Process32NextW(snapshot.get(), &pe));
}
return process_infos.size();
}
bool Host::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) {
process_info.Clear();
AutoHandle handle(
::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid),
nullptr);
if (!handle.IsValid())
return false;
process_info.SetProcessID(pid);
GetProcessExecutableAndTriple(handle, process_info);
// Need to read the PEB to get parent process and command line arguments.
AutoHandle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
if (!snapshot.IsValid())
return false;
PROCESSENTRY32W pe;
pe.dwSize = sizeof(PROCESSENTRY32W);
if (Process32FirstW(snapshot.get(), &pe)) {
do {
if (pe.th32ProcessID == pid) {
process_info.SetParentProcessID(pe.th32ParentProcessID);
return true;
}
} while (Process32NextW(snapshot.get(), &pe));
}
return false;
}
llvm::Expected<HostThread> Host::StartMonitoringChildProcess(
const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid,
bool monitor_signals) {
return HostThread();
}
Status Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) {
Status error;
if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) {
FileSpec expand_tool_spec = HostInfo::GetSupportExeDir();
if (!expand_tool_spec) {
error.SetErrorString("could not find support executable directory for "
"the lldb-argdumper tool");
return error;
}
expand_tool_spec.AppendPathComponent("lldb-argdumper.exe");
if (!FileSystem::Instance().Exists(expand_tool_spec)) {
error.SetErrorString("could not find the lldb-argdumper tool");
return error;
}
std::string quoted_cmd_string;
launch_info.GetArguments().GetQuotedCommandString(quoted_cmd_string);
std::replace(quoted_cmd_string.begin(), quoted_cmd_string.end(), '\\', '/');
StreamString expand_command;
expand_command.Printf("\"%s\" %s", expand_tool_spec.GetPath().c_str(),
quoted_cmd_string.c_str());
int status;
std::string output;
std::string command = expand_command.GetString().str();
Status e =
RunShellCommand(command.c_str(), launch_info.GetWorkingDirectory(),
&status, nullptr, &output, std::chrono::seconds(10));
if (e.Fail())
return e;
if (status != 0) {
error.SetErrorStringWithFormat("lldb-argdumper exited with error %d",
status);
return error;
}
auto data_sp = StructuredData::ParseJSON(output);
if (!data_sp) {
error.SetErrorString("invalid JSON");
return error;
}
auto dict_sp = data_sp->GetAsDictionary();
if (!data_sp) {
error.SetErrorString("invalid JSON");
return error;
}
auto args_sp = dict_sp->GetObjectForDotSeparatedPath("arguments");
if (!args_sp) {
error.SetErrorString("invalid JSON");
return error;
}
auto args_array_sp = args_sp->GetAsArray();
if (!args_array_sp) {
error.SetErrorString("invalid JSON");
return error;
}
launch_info.GetArguments().Clear();
for (size_t i = 0; i < args_array_sp->GetSize(); i++) {
auto item_sp = args_array_sp->GetItemAtIndex(i);
if (!item_sp)
continue;
auto str_sp = item_sp->GetAsString();
if (!str_sp)
continue;
launch_info.GetArguments().AppendArgument(str_sp->GetValue());
}
}
return error;
}
Environment Host::GetEnvironment() {
Environment env;
// The environment block on Windows is a contiguous buffer of NULL terminated
// strings, where the end of the environment block is indicated by two
// consecutive NULLs.
LPWCH environment_block = ::GetEnvironmentStringsW();
while (*environment_block != L'\0') {
std::string current_var;
auto current_var_size = wcslen(environment_block) + 1;
if (!llvm::convertWideToUTF8(environment_block, current_var)) {
environment_block += current_var_size;
continue;
}
if (current_var[0] != '=')
env.insert(current_var);
environment_block += current_var_size;
}
return env;
}