1 | //===-- ProcessGDBRemote.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 | #include "lldb/Host/Config.h" |
10 | |
11 | #include <cerrno> |
12 | #include <cstdlib> |
13 | #if LLDB_ENABLE_POSIX |
14 | #include <netinet/in.h> |
15 | #include <sys/mman.h> |
16 | #include <sys/socket.h> |
17 | #include <unistd.h> |
18 | #endif |
19 | #include <sys/stat.h> |
20 | #if defined(__APPLE__) |
21 | #include <sys/sysctl.h> |
22 | #endif |
23 | #include <ctime> |
24 | #include <sys/types.h> |
25 | |
26 | #include "lldb/Breakpoint/Watchpoint.h" |
27 | #include "lldb/Breakpoint/WatchpointAlgorithms.h" |
28 | #include "lldb/Breakpoint/WatchpointResource.h" |
29 | #include "lldb/Core/Debugger.h" |
30 | #include "lldb/Core/Module.h" |
31 | #include "lldb/Core/ModuleSpec.h" |
32 | #include "lldb/Core/PluginManager.h" |
33 | #include "lldb/Core/Value.h" |
34 | #include "lldb/DataFormatters/FormatManager.h" |
35 | #include "lldb/Host/ConnectionFileDescriptor.h" |
36 | #include "lldb/Host/FileSystem.h" |
37 | #include "lldb/Host/HostThread.h" |
38 | #include "lldb/Host/PosixApi.h" |
39 | #include "lldb/Host/PseudoTerminal.h" |
40 | #include "lldb/Host/StreamFile.h" |
41 | #include "lldb/Host/ThreadLauncher.h" |
42 | #include "lldb/Host/XML.h" |
43 | #include "lldb/Interpreter/CommandInterpreter.h" |
44 | #include "lldb/Interpreter/CommandObject.h" |
45 | #include "lldb/Interpreter/CommandObjectMultiword.h" |
46 | #include "lldb/Interpreter/CommandReturnObject.h" |
47 | #include "lldb/Interpreter/OptionArgParser.h" |
48 | #include "lldb/Interpreter/OptionGroupBoolean.h" |
49 | #include "lldb/Interpreter/OptionGroupUInt64.h" |
50 | #include "lldb/Interpreter/OptionValueProperties.h" |
51 | #include "lldb/Interpreter/Options.h" |
52 | #include "lldb/Interpreter/Property.h" |
53 | #include "lldb/Symbol/ObjectFile.h" |
54 | #include "lldb/Target/ABI.h" |
55 | #include "lldb/Target/DynamicLoader.h" |
56 | #include "lldb/Target/MemoryRegionInfo.h" |
57 | #include "lldb/Target/RegisterFlags.h" |
58 | #include "lldb/Target/SystemRuntime.h" |
59 | #include "lldb/Target/Target.h" |
60 | #include "lldb/Target/TargetList.h" |
61 | #include "lldb/Target/ThreadPlanCallFunction.h" |
62 | #include "lldb/Utility/Args.h" |
63 | #include "lldb/Utility/FileSpec.h" |
64 | #include "lldb/Utility/LLDBLog.h" |
65 | #include "lldb/Utility/State.h" |
66 | #include "lldb/Utility/StreamString.h" |
67 | #include "lldb/Utility/Timer.h" |
68 | #include <algorithm> |
69 | #include <csignal> |
70 | #include <map> |
71 | #include <memory> |
72 | #include <mutex> |
73 | #include <optional> |
74 | #include <sstream> |
75 | #include <thread> |
76 | |
77 | #include "GDBRemoteRegisterContext.h" |
78 | #include "GDBRemoteRegisterFallback.h" |
79 | #include "Plugins/Process/Utility/GDBRemoteSignals.h" |
80 | #include "Plugins/Process/Utility/InferiorCallPOSIX.h" |
81 | #include "Plugins/Process/Utility/StopInfoMachException.h" |
82 | #include "ProcessGDBRemote.h" |
83 | #include "ProcessGDBRemoteLog.h" |
84 | #include "ThreadGDBRemote.h" |
85 | #include "lldb/Host/Host.h" |
86 | #include "lldb/Utility/StringExtractorGDBRemote.h" |
87 | |
88 | #include "llvm/ADT/ScopeExit.h" |
89 | #include "llvm/ADT/StringMap.h" |
90 | #include "llvm/ADT/StringSwitch.h" |
91 | #include "llvm/Support/FormatAdapters.h" |
92 | #include "llvm/Support/Threading.h" |
93 | #include "llvm/Support/raw_ostream.h" |
94 | |
95 | #define DEBUGSERVER_BASENAME "debugserver" |
96 | using namespace lldb; |
97 | using namespace lldb_private; |
98 | using namespace lldb_private::process_gdb_remote; |
99 | |
100 | LLDB_PLUGIN_DEFINE(ProcessGDBRemote) |
101 | |
102 | namespace lldb { |
103 | // Provide a function that can easily dump the packet history if we know a |
104 | // ProcessGDBRemote * value (which we can get from logs or from debugging). We |
105 | // need the function in the lldb namespace so it makes it into the final |
106 | // executable since the LLDB shared library only exports stuff in the lldb |
107 | // namespace. This allows you to attach with a debugger and call this function |
108 | // and get the packet history dumped to a file. |
109 | void DumpProcessGDBRemotePacketHistory(void *p, const char *path) { |
110 | auto file = FileSystem::Instance().Open( |
111 | file_spec: FileSpec(path), options: File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate); |
112 | if (!file) { |
113 | llvm::consumeError(Err: file.takeError()); |
114 | return; |
115 | } |
116 | StreamFile stream(std::move(file.get())); |
117 | ((Process *)p)->DumpPluginHistory(s&: stream); |
118 | } |
119 | } // namespace lldb |
120 | |
121 | namespace { |
122 | |
123 | #define LLDB_PROPERTIES_processgdbremote |
124 | #include "ProcessGDBRemoteProperties.inc" |
125 | |
126 | enum { |
127 | #define LLDB_PROPERTIES_processgdbremote |
128 | #include "ProcessGDBRemotePropertiesEnum.inc" |
129 | }; |
130 | |
131 | class PluginProperties : public Properties { |
132 | public: |
133 | static llvm::StringRef GetSettingName() { |
134 | return ProcessGDBRemote::GetPluginNameStatic(); |
135 | } |
136 | |
137 | PluginProperties() : Properties() { |
138 | m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); |
139 | m_collection_sp->Initialize(g_processgdbremote_properties); |
140 | } |
141 | |
142 | ~PluginProperties() override = default; |
143 | |
144 | uint64_t GetPacketTimeout() { |
145 | const uint32_t idx = ePropertyPacketTimeout; |
146 | return GetPropertyAtIndexAs<uint64_t>( |
147 | idx, g_processgdbremote_properties[idx].default_uint_value); |
148 | } |
149 | |
150 | bool SetPacketTimeout(uint64_t timeout) { |
151 | const uint32_t idx = ePropertyPacketTimeout; |
152 | return SetPropertyAtIndex(idx, timeout); |
153 | } |
154 | |
155 | FileSpec GetTargetDefinitionFile() const { |
156 | const uint32_t idx = ePropertyTargetDefinitionFile; |
157 | return GetPropertyAtIndexAs<FileSpec>(idx, {}); |
158 | } |
159 | |
160 | bool GetUseSVR4() const { |
161 | const uint32_t idx = ePropertyUseSVR4; |
162 | return GetPropertyAtIndexAs<bool>( |
163 | idx, g_processgdbremote_properties[idx].default_uint_value != 0); |
164 | } |
165 | |
166 | bool GetUseGPacketForReading() const { |
167 | const uint32_t idx = ePropertyUseGPacketForReading; |
168 | return GetPropertyAtIndexAs<bool>(idx, true); |
169 | } |
170 | }; |
171 | |
172 | std::chrono::seconds ResumeTimeout() { return std::chrono::seconds(5); } |
173 | |
174 | } // namespace |
175 | |
176 | static PluginProperties &GetGlobalPluginProperties() { |
177 | static PluginProperties g_settings; |
178 | return g_settings; |
179 | } |
180 | |
181 | // TODO Randomly assigning a port is unsafe. We should get an unused |
182 | // ephemeral port from the kernel and make sure we reserve it before passing it |
183 | // to debugserver. |
184 | |
185 | #if defined(__APPLE__) |
186 | #define LOW_PORT (IPPORT_RESERVED) |
187 | #define HIGH_PORT (IPPORT_HIFIRSTAUTO) |
188 | #else |
189 | #define LOW_PORT (1024u) |
190 | #define HIGH_PORT (49151u) |
191 | #endif |
192 | |
193 | llvm::StringRef ProcessGDBRemote::GetPluginDescriptionStatic() { |
194 | return "GDB Remote protocol based debugging plug-in."; |
195 | } |
196 | |
197 | void ProcessGDBRemote::Terminate() { |
198 | PluginManager::UnregisterPlugin(create_callback: ProcessGDBRemote::CreateInstance); |
199 | } |
200 | |
201 | lldb::ProcessSP ProcessGDBRemote::CreateInstance( |
202 | lldb::TargetSP target_sp, ListenerSP listener_sp, |
203 | const FileSpec *crash_file_path, bool can_connect) { |
204 | lldb::ProcessSP process_sp; |
205 | if (crash_file_path == nullptr) |
206 | process_sp = std::shared_ptr<ProcessGDBRemote>( |
207 | new ProcessGDBRemote(target_sp, listener_sp)); |
208 | return process_sp; |
209 | } |
210 | |
211 | void ProcessGDBRemote::DumpPluginHistory(Stream &s) { |
212 | GDBRemoteCommunicationClient &gdb_comm(GetGDBRemote()); |
213 | gdb_comm.DumpHistory(strm&: s); |
214 | } |
215 | |
216 | std::chrono::seconds ProcessGDBRemote::GetPacketTimeout() { |
217 | return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout()); |
218 | } |
219 | |
220 | ArchSpec ProcessGDBRemote::GetSystemArchitecture() { |
221 | return m_gdb_comm.GetHostArchitecture(); |
222 | } |
223 | |
224 | bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp, |
225 | bool plugin_specified_by_name) { |
226 | if (plugin_specified_by_name) |
227 | return true; |
228 | |
229 | // For now we are just making sure the file exists for a given module |
230 | Module *exe_module = target_sp->GetExecutableModulePointer(); |
231 | if (exe_module) { |
232 | ObjectFile *exe_objfile = exe_module->GetObjectFile(); |
233 | // We can't debug core files... |
234 | switch (exe_objfile->GetType()) { |
235 | case ObjectFile::eTypeInvalid: |
236 | case ObjectFile::eTypeCoreFile: |
237 | case ObjectFile::eTypeDebugInfo: |
238 | case ObjectFile::eTypeObjectFile: |
239 | case ObjectFile::eTypeSharedLibrary: |
240 | case ObjectFile::eTypeStubLibrary: |
241 | case ObjectFile::eTypeJIT: |
242 | return false; |
243 | case ObjectFile::eTypeExecutable: |
244 | case ObjectFile::eTypeDynamicLinker: |
245 | case ObjectFile::eTypeUnknown: |
246 | break; |
247 | } |
248 | return FileSystem::Instance().Exists(file_spec: exe_module->GetFileSpec()); |
249 | } |
250 | // However, if there is no executable module, we return true since we might |
251 | // be preparing to attach. |
252 | return true; |
253 | } |
254 | |
255 | // ProcessGDBRemote constructor |
256 | ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp, |
257 | ListenerSP listener_sp) |
258 | : Process(target_sp, listener_sp), |
259 | m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_register_info_sp(nullptr), |
260 | m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"), |
261 | m_async_listener_sp( |
262 | Listener::MakeListener(name: "lldb.process.gdb-remote.async-listener")), |
263 | m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(), |
264 | m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(), |
265 | m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(), |
266 | m_max_memory_size(0), m_remote_stub_max_memory_size(0), |
267 | m_addr_to_mmap_size(), m_thread_create_bp_sp(), |
268 | m_waiting_for_attach(false), m_command_sp(), m_breakpoint_pc_offset(0), |
269 | m_initial_tid(LLDB_INVALID_THREAD_ID), m_allow_flash_writes(false), |
270 | m_erased_flash_ranges(), m_vfork_in_progress_count(0) { |
271 | m_async_broadcaster.SetEventName(event_mask: eBroadcastBitAsyncThreadShouldExit, |
272 | name: "async thread should exit"); |
273 | m_async_broadcaster.SetEventName(event_mask: eBroadcastBitAsyncContinue, |
274 | name: "async thread continue"); |
275 | m_async_broadcaster.SetEventName(event_mask: eBroadcastBitAsyncThreadDidExit, |
276 | name: "async thread did exit"); |
277 | |
278 | Log *log = GetLog(mask: GDBRLog::Async); |
279 | |
280 | const uint32_t async_event_mask = |
281 | eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit; |
282 | |
283 | if (m_async_listener_sp->StartListeningForEvents( |
284 | broadcaster: &m_async_broadcaster, event_mask: async_event_mask) != async_event_mask) { |
285 | LLDB_LOGF(log, |
286 | "ProcessGDBRemote::%s failed to listen for " |
287 | "m_async_broadcaster events", |
288 | __FUNCTION__); |
289 | } |
290 | |
291 | const uint64_t timeout_seconds = |
292 | GetGlobalPluginProperties().GetPacketTimeout(); |
293 | if (timeout_seconds > 0) |
294 | m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds)); |
295 | |
296 | m_use_g_packet_for_reading = |
297 | GetGlobalPluginProperties().GetUseGPacketForReading(); |
298 | } |
299 | |
300 | // Destructor |
301 | ProcessGDBRemote::~ProcessGDBRemote() { |
302 | // m_mach_process.UnregisterNotificationCallbacks (this); |
303 | Clear(); |
304 | // We need to call finalize on the process before destroying ourselves to |
305 | // make sure all of the broadcaster cleanup goes as planned. If we destruct |
306 | // this class, then Process::~Process() might have problems trying to fully |
307 | // destroy the broadcaster. |
308 | Finalize(destructing: true /* destructing */); |
309 | |
310 | // The general Finalize is going to try to destroy the process and that |
311 | // SHOULD shut down the async thread. However, if we don't kill it it will |
312 | // get stranded and its connection will go away so when it wakes up it will |
313 | // crash. So kill it for sure here. |
314 | StopAsyncThread(); |
315 | KillDebugserverProcess(); |
316 | } |
317 | |
318 | bool ProcessGDBRemote::ParsePythonTargetDefinition( |
319 | const FileSpec &target_definition_fspec) { |
320 | ScriptInterpreter *interpreter = |
321 | GetTarget().GetDebugger().GetScriptInterpreter(); |
322 | Status error; |
323 | StructuredData::ObjectSP module_object_sp( |
324 | interpreter->LoadPluginModule(file_spec: target_definition_fspec, error)); |
325 | if (module_object_sp) { |
326 | StructuredData::DictionarySP target_definition_sp( |
327 | interpreter->GetDynamicSettings(plugin_module_sp: module_object_sp, target: &GetTarget(), |
328 | setting_name: "gdb-server-target-definition", error)); |
329 | |
330 | if (target_definition_sp) { |
331 | StructuredData::ObjectSP target_object( |
332 | target_definition_sp->GetValueForKey(key: "host-info")); |
333 | if (target_object) { |
334 | if (auto host_info_dict = target_object->GetAsDictionary()) { |
335 | StructuredData::ObjectSP triple_value = |
336 | host_info_dict->GetValueForKey(key: "triple"); |
337 | if (auto triple_string_value = triple_value->GetAsString()) { |
338 | std::string triple_string = |
339 | std::string(triple_string_value->GetValue()); |
340 | ArchSpec host_arch(triple_string.c_str()); |
341 | if (!host_arch.IsCompatibleMatch(rhs: GetTarget().GetArchitecture())) { |
342 | GetTarget().SetArchitecture(arch_spec: host_arch); |
343 | } |
344 | } |
345 | } |
346 | } |
347 | m_breakpoint_pc_offset = 0; |
348 | StructuredData::ObjectSP breakpoint_pc_offset_value = |
349 | target_definition_sp->GetValueForKey(key: "breakpoint-pc-offset"); |
350 | if (breakpoint_pc_offset_value) { |
351 | if (auto breakpoint_pc_int_value = |
352 | breakpoint_pc_offset_value->GetAsSignedInteger()) |
353 | m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue(); |
354 | } |
355 | |
356 | if (m_register_info_sp->SetRegisterInfo( |
357 | dict: *target_definition_sp, arch: GetTarget().GetArchitecture()) > 0) { |
358 | return true; |
359 | } |
360 | } |
361 | } |
362 | return false; |
363 | } |
364 | |
365 | static size_t SplitCommaSeparatedRegisterNumberString( |
366 | const llvm::StringRef &comma_separated_register_numbers, |
367 | std::vector<uint32_t> ®nums, int base) { |
368 | regnums.clear(); |
369 | for (llvm::StringRef x : llvm::split(Str: comma_separated_register_numbers, Separator: ',')) { |
370 | uint32_t reg; |
371 | if (llvm::to_integer(S: x, Num&: reg, Base: base)) |
372 | regnums.push_back(x: reg); |
373 | } |
374 | return regnums.size(); |
375 | } |
376 | |
377 | void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) { |
378 | if (!force && m_register_info_sp) |
379 | return; |
380 | |
381 | m_register_info_sp = std::make_shared<GDBRemoteDynamicRegisterInfo>(); |
382 | |
383 | // Check if qHostInfo specified a specific packet timeout for this |
384 | // connection. If so then lets update our setting so the user knows what the |
385 | // timeout is and can see it. |
386 | const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout(); |
387 | if (host_packet_timeout > std::chrono::seconds(0)) { |
388 | GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout.count()); |
389 | } |
390 | |
391 | // Register info search order: |
392 | // 1 - Use the target definition python file if one is specified. |
393 | // 2 - If the target definition doesn't have any of the info from the |
394 | // target.xml (registers) then proceed to read the target.xml. |
395 | // 3 - Fall back on the qRegisterInfo packets. |
396 | // 4 - Use hardcoded defaults if available. |
397 | |
398 | FileSpec target_definition_fspec = |
399 | GetGlobalPluginProperties().GetTargetDefinitionFile(); |
400 | if (!FileSystem::Instance().Exists(file_spec: target_definition_fspec)) { |
401 | // If the filename doesn't exist, it may be a ~ not having been expanded - |
402 | // try to resolve it. |
403 | FileSystem::Instance().Resolve(file_spec&: target_definition_fspec); |
404 | } |
405 | if (target_definition_fspec) { |
406 | // See if we can get register definitions from a python file |
407 | if (ParsePythonTargetDefinition(target_definition_fspec)) |
408 | return; |
409 | |
410 | Debugger::ReportError(message: "target description file "+ |
411 | target_definition_fspec.GetPath() + |
412 | " failed to parse", |
413 | debugger_id: GetTarget().GetDebugger().GetID()); |
414 | } |
415 | |
416 | const ArchSpec &target_arch = GetTarget().GetArchitecture(); |
417 | const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture(); |
418 | const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture(); |
419 | |
420 | // Use the process' architecture instead of the host arch, if available |
421 | ArchSpec arch_to_use; |
422 | if (remote_process_arch.IsValid()) |
423 | arch_to_use = remote_process_arch; |
424 | else |
425 | arch_to_use = remote_host_arch; |
426 | |
427 | if (!arch_to_use.IsValid()) |
428 | arch_to_use = target_arch; |
429 | |
430 | if (GetGDBServerRegisterInfo(arch&: arch_to_use)) |
431 | return; |
432 | |
433 | char packet[128]; |
434 | std::vector<DynamicRegisterInfo::Register> registers; |
435 | uint32_t reg_num = 0; |
436 | for (StringExtractorGDBRemote::ResponseType response_type = |
437 | StringExtractorGDBRemote::eResponse; |
438 | response_type == StringExtractorGDBRemote::eResponse; ++reg_num) { |
439 | const int packet_len = |
440 | ::snprintf(s: packet, maxlen: sizeof(packet), format: "qRegisterInfo%x", reg_num); |
441 | assert(packet_len < (int)sizeof(packet)); |
442 | UNUSED_IF_ASSERT_DISABLED(packet_len); |
443 | StringExtractorGDBRemote response; |
444 | if (m_gdb_comm.SendPacketAndWaitForResponse(payload: packet, response) == |
445 | GDBRemoteCommunication::PacketResult::Success) { |
446 | response_type = response.GetResponseType(); |
447 | if (response_type == StringExtractorGDBRemote::eResponse) { |
448 | llvm::StringRef name; |
449 | llvm::StringRef value; |
450 | DynamicRegisterInfo::Register reg_info; |
451 | |
452 | while (response.GetNameColonValue(name, value)) { |
453 | if (name == "name") { |
454 | reg_info.name.SetString(value); |
455 | } else if (name == "alt-name") { |
456 | reg_info.alt_name.SetString(value); |
457 | } else if (name == "bitsize") { |
458 | if (!value.getAsInteger(Radix: 0, Result&: reg_info.byte_size)) |
459 | reg_info.byte_size /= CHAR_BIT; |
460 | } else if (name == "offset") { |
461 | value.getAsInteger(Radix: 0, Result&: reg_info.byte_offset); |
462 | } else if (name == "encoding") { |
463 | const Encoding encoding = Args::StringToEncoding(s: value); |
464 | if (encoding != eEncodingInvalid) |
465 | reg_info.encoding = encoding; |
466 | } else if (name == "format") { |
467 | if (!OptionArgParser::ToFormat(s: value.str().c_str(), format&: reg_info.format, byte_size_ptr: nullptr) |
468 | .Success()) |
469 | reg_info.format = |
470 | llvm::StringSwitch<Format>(value) |
471 | .Case(S: "binary", Value: eFormatBinary) |
472 | .Case(S: "decimal", Value: eFormatDecimal) |
473 | .Case(S: "hex", Value: eFormatHex) |
474 | .Case(S: "float", Value: eFormatFloat) |
475 | .Case(S: "vector-sint8", Value: eFormatVectorOfSInt8) |
476 | .Case(S: "vector-uint8", Value: eFormatVectorOfUInt8) |
477 | .Case(S: "vector-sint16", Value: eFormatVectorOfSInt16) |
478 | .Case(S: "vector-uint16", Value: eFormatVectorOfUInt16) |
479 | .Case(S: "vector-sint32", Value: eFormatVectorOfSInt32) |
480 | .Case(S: "vector-uint32", Value: eFormatVectorOfUInt32) |
481 | .Case(S: "vector-float32", Value: eFormatVectorOfFloat32) |
482 | .Case(S: "vector-uint64", Value: eFormatVectorOfUInt64) |
483 | .Case(S: "vector-uint128", Value: eFormatVectorOfUInt128) |
484 | .Default(Value: eFormatInvalid); |
485 | } else if (name == "set") { |
486 | reg_info.set_name.SetString(value); |
487 | } else if (name == "gcc"|| name == "ehframe") { |
488 | value.getAsInteger(Radix: 0, Result&: reg_info.regnum_ehframe); |
489 | } else if (name == "dwarf") { |
490 | value.getAsInteger(Radix: 0, Result&: reg_info.regnum_dwarf); |
491 | } else if (name == "generic") { |
492 | reg_info.regnum_generic = Args::StringToGenericRegister(s: value); |
493 | } else if (name == "container-regs") { |
494 | SplitCommaSeparatedRegisterNumberString(comma_separated_register_numbers: value, regnums&: reg_info.value_regs, base: 16); |
495 | } else if (name == "invalidate-regs") { |
496 | SplitCommaSeparatedRegisterNumberString(comma_separated_register_numbers: value, regnums&: reg_info.invalidate_regs, base: 16); |
497 | } |
498 | } |
499 | |
500 | assert(reg_info.byte_size != 0); |
501 | registers.push_back(x: reg_info); |
502 | } else { |
503 | break; // ensure exit before reg_num is incremented |
504 | } |
505 | } else { |
506 | break; |
507 | } |
508 | } |
509 | |
510 | if (registers.empty()) |
511 | registers = GetFallbackRegisters(arch_to_use); |
512 | |
513 | AddRemoteRegisters(registers, arch_to_use); |
514 | } |
515 | |
516 | Status ProcessGDBRemote::DoWillLaunch(lldb_private::Module *module) { |
517 | return WillLaunchOrAttach(); |
518 | } |
519 | |
520 | Status ProcessGDBRemote::DoWillAttachToProcessWithID(lldb::pid_t pid) { |
521 | return WillLaunchOrAttach(); |
522 | } |
523 | |
524 | Status ProcessGDBRemote::DoWillAttachToProcessWithName(const char *process_name, |
525 | bool wait_for_launch) { |
526 | return WillLaunchOrAttach(); |
527 | } |
528 | |
529 | Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) { |
530 | Log *log = GetLog(mask: GDBRLog::Process); |
531 | |
532 | Status error(WillLaunchOrAttach()); |
533 | if (error.Fail()) |
534 | return error; |
535 | |
536 | error = ConnectToDebugserver(host_port: remote_url); |
537 | if (error.Fail()) |
538 | return error; |
539 | |
540 | StartAsyncThread(); |
541 | |
542 | lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); |
543 | if (pid == LLDB_INVALID_PROCESS_ID) { |
544 | // We don't have a valid process ID, so note that we are connected and |
545 | // could now request to launch or attach, or get remote process listings... |
546 | SetPrivateState(eStateConnected); |
547 | } else { |
548 | // We have a valid process |
549 | SetID(pid); |
550 | GetThreadList(); |
551 | StringExtractorGDBRemote response; |
552 | if (m_gdb_comm.GetStopReply(response)) { |
553 | SetLastStopPacket(response); |
554 | |
555 | Target &target = GetTarget(); |
556 | if (!target.GetArchitecture().IsValid()) { |
557 | if (m_gdb_comm.GetProcessArchitecture().IsValid()) { |
558 | target.SetArchitecture(arch_spec: m_gdb_comm.GetProcessArchitecture()); |
559 | } else { |
560 | if (m_gdb_comm.GetHostArchitecture().IsValid()) { |
561 | target.SetArchitecture(arch_spec: m_gdb_comm.GetHostArchitecture()); |
562 | } |
563 | } |
564 | } |
565 | |
566 | const StateType state = SetThreadStopInfo(response); |
567 | if (state != eStateInvalid) { |
568 | SetPrivateState(state); |
569 | } else |
570 | error = Status::FromErrorStringWithFormat( |
571 | format: "Process %"PRIu64 " was reported after connecting to " |
572 | "'%s', but state was not stopped: %s", |
573 | pid, remote_url.str().c_str(), StateAsCString(state)); |
574 | } else |
575 | error = Status::FromErrorStringWithFormat( |
576 | format: "Process %"PRIu64 " was reported after connecting to '%s', " |
577 | "but no stop reply packet was received", |
578 | pid, remote_url.str().c_str()); |
579 | } |
580 | |
581 | LLDB_LOGF(log, |
582 | "ProcessGDBRemote::%s pid %"PRIu64 |
583 | ": normalizing target architecture initial triple: %s " |
584 | "(GetTarget().GetArchitecture().IsValid() %s, " |
585 | "m_gdb_comm.GetHostArchitecture().IsValid(): %s)", |
586 | __FUNCTION__, GetID(), |
587 | GetTarget().GetArchitecture().GetTriple().getTriple().c_str(), |
588 | GetTarget().GetArchitecture().IsValid() ? "true": "false", |
589 | m_gdb_comm.GetHostArchitecture().IsValid() ? "true": "false"); |
590 | |
591 | if (error.Success() && !GetTarget().GetArchitecture().IsValid() && |
592 | m_gdb_comm.GetHostArchitecture().IsValid()) { |
593 | // Prefer the *process'* architecture over that of the *host*, if |
594 | // available. |
595 | if (m_gdb_comm.GetProcessArchitecture().IsValid()) |
596 | GetTarget().SetArchitecture(arch_spec: m_gdb_comm.GetProcessArchitecture()); |
597 | else |
598 | GetTarget().SetArchitecture(arch_spec: m_gdb_comm.GetHostArchitecture()); |
599 | } |
600 | |
601 | LLDB_LOGF(log, |
602 | "ProcessGDBRemote::%s pid %"PRIu64 |
603 | ": normalized target architecture triple: %s", |
604 | __FUNCTION__, GetID(), |
605 | GetTarget().GetArchitecture().GetTriple().getTriple().c_str()); |
606 | |
607 | return error; |
608 | } |
609 | |
610 | Status ProcessGDBRemote::WillLaunchOrAttach() { |
611 | Status error; |
612 | m_stdio_communication.Clear(); |
613 | return error; |
614 | } |
615 | |
616 | // Process Control |
617 | Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module, |
618 | ProcessLaunchInfo &launch_info) { |
619 | Log *log = GetLog(mask: GDBRLog::Process); |
620 | Status error; |
621 | |
622 | LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__); |
623 | |
624 | uint32_t launch_flags = launch_info.GetFlags().Get(); |
625 | FileSpec stdin_file_spec{}; |
626 | FileSpec stdout_file_spec{}; |
627 | FileSpec stderr_file_spec{}; |
628 | FileSpec working_dir = launch_info.GetWorkingDirectory(); |
629 | |
630 | const FileAction *file_action; |
631 | file_action = launch_info.GetFileActionForFD(STDIN_FILENO); |
632 | if (file_action) { |
633 | if (file_action->GetAction() == FileAction::eFileActionOpen) |
634 | stdin_file_spec = file_action->GetFileSpec(); |
635 | } |
636 | file_action = launch_info.GetFileActionForFD(STDOUT_FILENO); |
637 | if (file_action) { |
638 | if (file_action->GetAction() == FileAction::eFileActionOpen) |
639 | stdout_file_spec = file_action->GetFileSpec(); |
640 | } |
641 | file_action = launch_info.GetFileActionForFD(STDERR_FILENO); |
642 | if (file_action) { |
643 | if (file_action->GetAction() == FileAction::eFileActionOpen) |
644 | stderr_file_spec = file_action->GetFileSpec(); |
645 | } |
646 | |
647 | if (log) { |
648 | if (stdin_file_spec || stdout_file_spec || stderr_file_spec) |
649 | LLDB_LOGF(log, |
650 | "ProcessGDBRemote::%s provided with STDIO paths via " |
651 | "launch_info: stdin=%s, stdout=%s, stderr=%s", |
652 | __FUNCTION__, |
653 | stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>", |
654 | stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>", |
655 | stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"); |
656 | else |
657 | LLDB_LOGF(log, |
658 | "ProcessGDBRemote::%s no STDIO paths given via launch_info", |
659 | __FUNCTION__); |
660 | } |
661 | |
662 | const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0; |
663 | if (stdin_file_spec || disable_stdio) { |
664 | // the inferior will be reading stdin from the specified file or stdio is |
665 | // completely disabled |
666 | m_stdin_forward = false; |
667 | } else { |
668 | m_stdin_forward = true; |
669 | } |
670 | |
671 | // ::LogSetBitMask (GDBR_LOG_DEFAULT); |
672 | // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | |
673 | // LLDB_LOG_OPTION_PREPEND_TIMESTAMP | |
674 | // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD); |
675 | // ::LogSetLogFile ("/dev/stdout"); |
676 | |
677 | error = EstablishConnectionIfNeeded(process_info: launch_info); |
678 | if (error.Success()) { |
679 | PseudoTerminal pty; |
680 | const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0; |
681 | |
682 | PlatformSP platform_sp(GetTarget().GetPlatform()); |
683 | if (disable_stdio) { |
684 | // set to /dev/null unless redirected to a file above |
685 | if (!stdin_file_spec) |
686 | stdin_file_spec.SetFile(path: FileSystem::DEV_NULL, |
687 | style: FileSpec::Style::native); |
688 | if (!stdout_file_spec) |
689 | stdout_file_spec.SetFile(path: FileSystem::DEV_NULL, |
690 | style: FileSpec::Style::native); |
691 | if (!stderr_file_spec) |
692 | stderr_file_spec.SetFile(path: FileSystem::DEV_NULL, |
693 | style: FileSpec::Style::native); |
694 | } else if (platform_sp && platform_sp->IsHost()) { |
695 | // If the debugserver is local and we aren't disabling STDIO, lets use |
696 | // a pseudo terminal to instead of relying on the 'O' packets for stdio |
697 | // since 'O' packets can really slow down debugging if the inferior |
698 | // does a lot of output. |
699 | if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) && |
700 | !errorToBool(Err: pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) { |
701 | FileSpec secondary_name(pty.GetSecondaryName()); |
702 | |
703 | if (!stdin_file_spec) |
704 | stdin_file_spec = secondary_name; |
705 | |
706 | if (!stdout_file_spec) |
707 | stdout_file_spec = secondary_name; |
708 | |
709 | if (!stderr_file_spec) |
710 | stderr_file_spec = secondary_name; |
711 | } |
712 | LLDB_LOGF( |
713 | log, |
714 | "ProcessGDBRemote::%s adjusted STDIO paths for local platform " |
715 | "(IsHost() is true) using secondary: stdin=%s, stdout=%s, " |
716 | "stderr=%s", |
717 | __FUNCTION__, |
718 | stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>", |
719 | stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>", |
720 | stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"); |
721 | } |
722 | |
723 | LLDB_LOGF(log, |
724 | "ProcessGDBRemote::%s final STDIO paths after all " |
725 | "adjustments: stdin=%s, stdout=%s, stderr=%s", |
726 | __FUNCTION__, |
727 | stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>", |
728 | stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>", |
729 | stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"); |
730 | |
731 | if (stdin_file_spec) |
732 | m_gdb_comm.SetSTDIN(stdin_file_spec); |
733 | if (stdout_file_spec) |
734 | m_gdb_comm.SetSTDOUT(stdout_file_spec); |
735 | if (stderr_file_spec) |
736 | m_gdb_comm.SetSTDERR(stderr_file_spec); |
737 | |
738 | m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR); |
739 | m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError); |
740 | |
741 | m_gdb_comm.SendLaunchArchPacket( |
742 | arch: GetTarget().GetArchitecture().GetArchitectureName()); |
743 | |
744 | const char *launch_event_data = launch_info.GetLaunchEventData(); |
745 | if (launch_event_data != nullptr && *launch_event_data != '\0') |
746 | m_gdb_comm.SendLaunchEventDataPacket(data: launch_event_data); |
747 | |
748 | if (working_dir) { |
749 | m_gdb_comm.SetWorkingDir(working_dir); |
750 | } |
751 | |
752 | // Send the environment and the program + arguments after we connect |
753 | m_gdb_comm.SendEnvironment(env: launch_info.GetEnvironment()); |
754 | |
755 | { |
756 | // Scope for the scoped timeout object |
757 | GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm, |
758 | std::chrono::seconds(10)); |
759 | |
760 | // Since we can't send argv0 separate from the executable path, we need to |
761 | // make sure to use the actual executable path found in the launch_info... |
762 | Args args = launch_info.GetArguments(); |
763 | if (FileSpec exe_file = launch_info.GetExecutableFile()) |
764 | args.ReplaceArgumentAtIndex(idx: 0, arg_str: exe_file.GetPath(denormalize: false)); |
765 | if (llvm::Error err = m_gdb_comm.LaunchProcess(args)) { |
766 | error = Status::FromErrorStringWithFormatv( |
767 | format: "Cannot launch '{0}': {1}", args: args.GetArgumentAtIndex(idx: 0), |
768 | args: llvm::fmt_consume(Item: std::move(err))); |
769 | } else { |
770 | SetID(m_gdb_comm.GetCurrentProcessID()); |
771 | } |
772 | } |
773 | |
774 | if (GetID() == LLDB_INVALID_PROCESS_ID) { |
775 | LLDB_LOGF(log, "failed to connect to debugserver: %s", |
776 | error.AsCString()); |
777 | KillDebugserverProcess(); |
778 | return error; |
779 | } |
780 | |
781 | StringExtractorGDBRemote response; |
782 | if (m_gdb_comm.GetStopReply(response)) { |
783 | SetLastStopPacket(response); |
784 | |
785 | const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture(); |
786 | |
787 | if (process_arch.IsValid()) { |
788 | GetTarget().MergeArchitecture(arch_spec: process_arch); |
789 | } else { |
790 | const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture(); |
791 | if (host_arch.IsValid()) |
792 | GetTarget().MergeArchitecture(arch_spec: host_arch); |
793 | } |
794 | |
795 | SetPrivateState(SetThreadStopInfo(response)); |
796 | |
797 | if (!disable_stdio) { |
798 | if (pty.GetPrimaryFileDescriptor() != PseudoTerminal::invalid_fd) |
799 | SetSTDIOFileDescriptor(pty.ReleasePrimaryFileDescriptor()); |
800 | } |
801 | } |
802 | } else { |
803 | LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString()); |
804 | } |
805 | return error; |
806 | } |
807 | |
808 | Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) { |
809 | Status error; |
810 | // Only connect if we have a valid connect URL |
811 | Log *log = GetLog(mask: GDBRLog::Process); |
812 | |
813 | if (!connect_url.empty()) { |
814 | LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, |
815 | connect_url.str().c_str()); |
816 | std::unique_ptr<ConnectionFileDescriptor> conn_up( |
817 | new ConnectionFileDescriptor()); |
818 | if (conn_up) { |
819 | const uint32_t max_retry_count = 50; |
820 | uint32_t retry_count = 0; |
821 | while (!m_gdb_comm.IsConnected()) { |
822 | if (conn_up->Connect(url: connect_url, error_ptr: &error) == eConnectionStatusSuccess) { |
823 | m_gdb_comm.SetConnection(std::move(conn_up)); |
824 | break; |
825 | } |
826 | |
827 | retry_count++; |
828 | |
829 | if (retry_count >= max_retry_count) |
830 | break; |
831 | |
832 | std::this_thread::sleep_for(rtime: std::chrono::milliseconds(100)); |
833 | } |
834 | } |
835 | } |
836 | |
837 | if (!m_gdb_comm.IsConnected()) { |
838 | if (error.Success()) |
839 | error = Status::FromErrorString(str: "not connected to remote gdb server"); |
840 | return error; |
841 | } |
842 | |
843 | // We always seem to be able to open a connection to a local port so we need |
844 | // to make sure we can then send data to it. If we can't then we aren't |
845 | // actually connected to anything, so try and do the handshake with the |
846 | // remote GDB server and make sure that goes alright. |
847 | if (!m_gdb_comm.HandshakeWithServer(error_ptr: &error)) { |
848 | m_gdb_comm.Disconnect(); |
849 | if (error.Success()) |
850 | error = Status::FromErrorString(str: "not connected to remote gdb server"); |
851 | return error; |
852 | } |
853 | |
854 | m_gdb_comm.GetEchoSupported(); |
855 | m_gdb_comm.GetThreadSuffixSupported(); |
856 | m_gdb_comm.GetListThreadsInStopReplySupported(); |
857 | m_gdb_comm.GetHostInfo(); |
858 | m_gdb_comm.GetVContSupported(flavor: 'c'); |
859 | m_gdb_comm.GetVAttachOrWaitSupported(); |
860 | m_gdb_comm.EnableErrorStringInPacket(); |
861 | |
862 | // First dispatch any commands from the platform: |
863 | auto handle_cmds = [&] (const Args &args) -> void { |
864 | for (const Args::ArgEntry &entry : args) { |
865 | StringExtractorGDBRemote response; |
866 | m_gdb_comm.SendPacketAndWaitForResponse( |
867 | payload: entry.c_str(), response); |
868 | } |
869 | }; |
870 | |
871 | PlatformSP platform_sp = GetTarget().GetPlatform(); |
872 | if (platform_sp) { |
873 | handle_cmds(platform_sp->GetExtraStartupCommands()); |
874 | } |
875 | |
876 | // Then dispatch any process commands: |
877 | handle_cmds(GetExtraStartupCommands()); |
878 | |
879 | return error; |
880 | } |
881 | |
882 | void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) { |
883 | Log *log = GetLog(mask: GDBRLog::Process); |
884 | BuildDynamicRegisterInfo(force: false); |
885 | |
886 | // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer |
887 | // qProcessInfo as it will be more specific to our process. |
888 | |
889 | const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture(); |
890 | if (remote_process_arch.IsValid()) { |
891 | process_arch = remote_process_arch; |
892 | LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}", |
893 | process_arch.GetArchitectureName(), |
894 | process_arch.GetTriple().getTriple()); |
895 | } else { |
896 | process_arch = m_gdb_comm.GetHostArchitecture(); |
897 | LLDB_LOG(log, |
898 | "gdb-remote did not have process architecture, using gdb-remote " |
899 | "host architecture {0} {1}", |
900 | process_arch.GetArchitectureName(), |
901 | process_arch.GetTriple().getTriple()); |
902 | } |
903 | |
904 | AddressableBits addressable_bits = m_gdb_comm.GetAddressableBits(); |
905 | SetAddressableBitMasks(addressable_bits); |
906 | |
907 | if (process_arch.IsValid()) { |
908 | const ArchSpec &target_arch = GetTarget().GetArchitecture(); |
909 | if (target_arch.IsValid()) { |
910 | LLDB_LOG(log, "analyzing target arch, currently {0} {1}", |
911 | target_arch.GetArchitectureName(), |
912 | target_arch.GetTriple().getTriple()); |
913 | |
914 | // If the remote host is ARM and we have apple as the vendor, then |
915 | // ARM executables and shared libraries can have mixed ARM |
916 | // architectures. |
917 | // You can have an armv6 executable, and if the host is armv7, then the |
918 | // system will load the best possible architecture for all shared |
919 | // libraries it has, so we really need to take the remote host |
920 | // architecture as our defacto architecture in this case. |
921 | |
922 | if ((process_arch.GetMachine() == llvm::Triple::arm || |
923 | process_arch.GetMachine() == llvm::Triple::thumb) && |
924 | process_arch.GetTriple().getVendor() == llvm::Triple::Apple) { |
925 | GetTarget().SetArchitecture(arch_spec: process_arch); |
926 | LLDB_LOG(log, |
927 | "remote process is ARM/Apple, " |
928 | "setting target arch to {0} {1}", |
929 | process_arch.GetArchitectureName(), |
930 | process_arch.GetTriple().getTriple()); |
931 | } else { |
932 | // Fill in what is missing in the triple |
933 | const llvm::Triple &remote_triple = process_arch.GetTriple(); |
934 | llvm::Triple new_target_triple = target_arch.GetTriple(); |
935 | if (new_target_triple.getVendorName().size() == 0) { |
936 | new_target_triple.setVendor(remote_triple.getVendor()); |
937 | |
938 | if (new_target_triple.getOSName().size() == 0) { |
939 | new_target_triple.setOS(remote_triple.getOS()); |
940 | |
941 | if (new_target_triple.getEnvironmentName().size() == 0) |
942 | new_target_triple.setEnvironment(remote_triple.getEnvironment()); |
943 | } |
944 | |
945 | ArchSpec new_target_arch = target_arch; |
946 | new_target_arch.SetTriple(new_target_triple); |
947 | GetTarget().SetArchitecture(arch_spec: new_target_arch); |
948 | } |
949 | } |
950 | |
951 | LLDB_LOG(log, |
952 | "final target arch after adjustments for remote architecture: " |
953 | "{0} {1}", |
954 | target_arch.GetArchitectureName(), |
955 | target_arch.GetTriple().getTriple()); |
956 | } else { |
957 | // The target doesn't have a valid architecture yet, set it from the |
958 | // architecture we got from the remote GDB server |
959 | GetTarget().SetArchitecture(arch_spec: process_arch); |
960 | } |
961 | } |
962 | |
963 | // Target and Process are reasonably initailized; |
964 | // load any binaries we have metadata for / set load address. |
965 | LoadStubBinaries(); |
966 | MaybeLoadExecutableModule(); |
967 | |
968 | // Find out which StructuredDataPlugins are supported by the debug monitor. |
969 | // These plugins transmit data over async $J packets. |
970 | if (StructuredData::Array *supported_packets = |
971 | m_gdb_comm.GetSupportedStructuredDataPlugins()) |
972 | MapSupportedStructuredDataPlugins(supported_type_names: *supported_packets); |
973 | |
974 | // If connected to LLDB ("native-signals+"), use signal defs for |
975 | // the remote platform. If connected to GDB, just use the standard set. |
976 | if (!m_gdb_comm.UsesNativeSignals()) { |
977 | SetUnixSignals(std::make_shared<GDBRemoteSignals>()); |
978 | } else { |
979 | PlatformSP platform_sp = GetTarget().GetPlatform(); |
980 | if (platform_sp && platform_sp->IsConnected()) |
981 | SetUnixSignals(platform_sp->GetUnixSignals()); |
982 | else |
983 | SetUnixSignals(UnixSignals::Create(arch: GetTarget().GetArchitecture())); |
984 | } |
985 | } |
986 | |
987 | void ProcessGDBRemote::LoadStubBinaries() { |
988 | // The remote stub may know about the "main binary" in |
989 | // the context of a firmware debug session, and can |
990 | // give us a UUID and an address/slide of where the |
991 | // binary is loaded in memory. |
992 | UUID standalone_uuid; |
993 | addr_t standalone_value; |
994 | bool standalone_value_is_offset; |
995 | if (m_gdb_comm.GetProcessStandaloneBinary(uuid&: standalone_uuid, value&: standalone_value, |
996 | value_is_offset&: standalone_value_is_offset)) { |
997 | ModuleSP module_sp; |
998 | |
999 | if (standalone_uuid.IsValid()) { |
1000 | const bool force_symbol_search = true; |
1001 | const bool notify = true; |
1002 | const bool set_address_in_target = true; |
1003 | const bool allow_memory_image_last_resort = false; |
1004 | DynamicLoader::LoadBinaryWithUUIDAndAddress( |
1005 | process: this, name: "", uuid: standalone_uuid, value: standalone_value, |
1006 | value_is_offset: standalone_value_is_offset, force_symbol_search, notify, |
1007 | set_address_in_target, allow_memory_image_last_resort); |
1008 | } |
1009 | } |
1010 | |
1011 | // The remote stub may know about a list of binaries to |
1012 | // force load into the process -- a firmware type situation |
1013 | // where multiple binaries are present in virtual memory, |
1014 | // and we are only given the addresses of the binaries. |
1015 | // Not intended for use with userland debugging, when we use |
1016 | // a DynamicLoader plugin that knows how to find the loaded |
1017 | // binaries, and will track updates as binaries are added. |
1018 | |
1019 | std::vector<addr_t> bin_addrs = m_gdb_comm.GetProcessStandaloneBinaries(); |
1020 | if (bin_addrs.size()) { |
1021 | UUID uuid; |
1022 | const bool value_is_slide = false; |
1023 | for (addr_t addr : bin_addrs) { |
1024 | const bool notify = true; |
1025 | // First see if this is a special platform |
1026 | // binary that may determine the DynamicLoader and |
1027 | // Platform to be used in this Process and Target. |
1028 | if (GetTarget() |
1029 | .GetDebugger() |
1030 | .GetPlatformList() |
1031 | .LoadPlatformBinaryAndSetup(process: this, addr, notify)) |
1032 | continue; |
1033 | |
1034 | const bool force_symbol_search = true; |
1035 | const bool set_address_in_target = true; |
1036 | const bool allow_memory_image_last_resort = false; |
1037 | // Second manually load this binary into the Target. |
1038 | DynamicLoader::LoadBinaryWithUUIDAndAddress( |
1039 | process: this, name: llvm::StringRef(), uuid, value: addr, value_is_offset: value_is_slide, |
1040 | force_symbol_search, notify, set_address_in_target, |
1041 | allow_memory_image_last_resort); |
1042 | } |
1043 | } |
1044 | } |
1045 | |
1046 | void ProcessGDBRemote::MaybeLoadExecutableModule() { |
1047 | ModuleSP module_sp = GetTarget().GetExecutableModule(); |
1048 | if (!module_sp) |
1049 | return; |
1050 | |
1051 | std::optional<QOffsets> offsets = m_gdb_comm.GetQOffsets(); |
1052 | if (!offsets) |
1053 | return; |
1054 | |
1055 | bool is_uniform = |
1056 | size_t(llvm::count(Range&: offsets->offsets, Element: offsets->offsets[0])) == |
1057 | offsets->offsets.size(); |
1058 | if (!is_uniform) |
1059 | return; // TODO: Handle non-uniform responses. |
1060 | |
1061 | bool changed = false; |
1062 | module_sp->SetLoadAddress(target&: GetTarget(), value: offsets->offsets[0], |
1063 | /*value_is_offset=*/true, changed); |
1064 | if (changed) { |
1065 | ModuleList list; |
1066 | list.Append(module_sp); |
1067 | m_process->GetTarget().ModulesDidLoad(module_list&: list); |
1068 | } |
1069 | } |
1070 | |
1071 | void ProcessGDBRemote::DidLaunch() { |
1072 | ArchSpec process_arch; |
1073 | DidLaunchOrAttach(process_arch); |
1074 | } |
1075 | |
1076 | Status ProcessGDBRemote::DoAttachToProcessWithID( |
1077 | lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) { |
1078 | Log *log = GetLog(mask: GDBRLog::Process); |
1079 | Status error; |
1080 | |
1081 | LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__); |
1082 | |
1083 | // Clear out and clean up from any current state |
1084 | Clear(); |
1085 | if (attach_pid != LLDB_INVALID_PROCESS_ID) { |
1086 | error = EstablishConnectionIfNeeded(process_info: attach_info); |
1087 | if (error.Success()) { |
1088 | m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError()); |
1089 | |
1090 | char packet[64]; |
1091 | const int packet_len = |
1092 | ::snprintf(s: packet, maxlen: sizeof(packet), format: "vAttach;%"PRIx64, attach_pid); |
1093 | SetID(attach_pid); |
1094 | auto data_sp = |
1095 | std::make_shared<EventDataBytes>(args: llvm::StringRef(packet, packet_len)); |
1096 | m_async_broadcaster.BroadcastEvent(event_type: eBroadcastBitAsyncContinue, event_data_sp: data_sp); |
1097 | } else |
1098 | SetExitStatus(exit_status: -1, exit_string: error.AsCString()); |
1099 | } |
1100 | |
1101 | return error; |
1102 | } |
1103 | |
1104 | Status ProcessGDBRemote::DoAttachToProcessWithName( |
1105 | const char *process_name, const ProcessAttachInfo &attach_info) { |
1106 | Status error; |
1107 | // Clear out and clean up from any current state |
1108 | Clear(); |
1109 | |
1110 | if (process_name && process_name[0]) { |
1111 | error = EstablishConnectionIfNeeded(process_info: attach_info); |
1112 | if (error.Success()) { |
1113 | StreamString packet; |
1114 | |
1115 | m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError()); |
1116 | |
1117 | if (attach_info.GetWaitForLaunch()) { |
1118 | if (!m_gdb_comm.GetVAttachOrWaitSupported()) { |
1119 | packet.PutCString(cstr: "vAttachWait"); |
1120 | } else { |
1121 | if (attach_info.GetIgnoreExisting()) |
1122 | packet.PutCString(cstr: "vAttachWait"); |
1123 | else |
1124 | packet.PutCString(cstr: "vAttachOrWait"); |
1125 | } |
1126 | } else |
1127 | packet.PutCString(cstr: "vAttachName"); |
1128 | packet.PutChar(ch: ';'); |
1129 | packet.PutBytesAsRawHex8(src: process_name, src_len: strlen(s: process_name), |
1130 | src_byte_order: endian::InlHostByteOrder(), |
1131 | dst_byte_order: endian::InlHostByteOrder()); |
1132 | |
1133 | auto data_sp = std::make_shared<EventDataBytes>(args: packet.GetString()); |
1134 | m_async_broadcaster.BroadcastEvent(event_type: eBroadcastBitAsyncContinue, event_data_sp: data_sp); |
1135 | |
1136 | } else |
1137 | SetExitStatus(exit_status: -1, exit_string: error.AsCString()); |
1138 | } |
1139 | return error; |
1140 | } |
1141 | |
1142 | llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() { |
1143 | return m_gdb_comm.SendTraceSupported(interrupt_timeout: GetInterruptTimeout()); |
1144 | } |
1145 | |
1146 | llvm::Error ProcessGDBRemote::TraceStop(const TraceStopRequest &request) { |
1147 | return m_gdb_comm.SendTraceStop(request, interrupt_timeout: GetInterruptTimeout()); |
1148 | } |
1149 | |
1150 | llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) { |
1151 | return m_gdb_comm.SendTraceStart(request, interrupt_timeout: GetInterruptTimeout()); |
1152 | } |
1153 | |
1154 | llvm::Expected<std::string> |
1155 | ProcessGDBRemote::TraceGetState(llvm::StringRef type) { |
1156 | return m_gdb_comm.SendTraceGetState(type, interrupt_timeout: GetInterruptTimeout()); |
1157 | } |
1158 | |
1159 | llvm::Expected<std::vector<uint8_t>> |
1160 | ProcessGDBRemote::TraceGetBinaryData(const TraceGetBinaryDataRequest &request) { |
1161 | return m_gdb_comm.SendTraceGetBinaryData(request, interrupt_timeout: GetInterruptTimeout()); |
1162 | } |
1163 | |
1164 | void ProcessGDBRemote::DidExit() { |
1165 | // When we exit, disconnect from the GDB server communications |
1166 | m_gdb_comm.Disconnect(); |
1167 | } |
1168 | |
1169 | void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) { |
1170 | // If you can figure out what the architecture is, fill it in here. |
1171 | process_arch.Clear(); |
1172 | DidLaunchOrAttach(process_arch); |
1173 | } |
1174 | |
1175 | Status ProcessGDBRemote::WillResume() { |
1176 | m_continue_c_tids.clear(); |
1177 | m_continue_C_tids.clear(); |
1178 | m_continue_s_tids.clear(); |
1179 | m_continue_S_tids.clear(); |
1180 | m_jstopinfo_sp.reset(); |
1181 | m_jthreadsinfo_sp.reset(); |
1182 | return Status(); |
1183 | } |
1184 | |
1185 | bool ProcessGDBRemote::SupportsReverseDirection() { |
1186 | return m_gdb_comm.GetReverseStepSupported() || |
1187 | m_gdb_comm.GetReverseContinueSupported(); |
1188 | } |
1189 | |
1190 | Status ProcessGDBRemote::DoResume(RunDirection direction) { |
1191 | Status error; |
1192 | Log *log = GetLog(mask: GDBRLog::Process); |
1193 | LLDB_LOGF(log, "ProcessGDBRemote::Resume(%s)", |
1194 | direction == RunDirection::eRunForward ? "": "reverse"); |
1195 | |
1196 | ListenerSP listener_sp( |
1197 | Listener::MakeListener(name: "gdb-remote.resume-packet-sent")); |
1198 | if (listener_sp->StartListeningForEvents( |
1199 | broadcaster: &m_gdb_comm, event_mask: GDBRemoteClientBase::eBroadcastBitRunPacketSent)) { |
1200 | listener_sp->StartListeningForEvents( |
1201 | broadcaster: &m_async_broadcaster, |
1202 | event_mask: ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit); |
1203 | |
1204 | const size_t num_threads = GetThreadList().GetSize(); |
1205 | |
1206 | StreamString continue_packet; |
1207 | bool continue_packet_error = false; |
1208 | // Number of threads continuing with "c", i.e. continuing without a signal |
1209 | // to deliver. |
1210 | const size_t num_continue_c_tids = m_continue_c_tids.size(); |
1211 | // Number of threads continuing with "C", i.e. continuing with a signal to |
1212 | // deliver. |
1213 | const size_t num_continue_C_tids = m_continue_C_tids.size(); |
1214 | // Number of threads continuing with "s", i.e. single-stepping. |
1215 | const size_t num_continue_s_tids = m_continue_s_tids.size(); |
1216 | // Number of threads continuing with "S", i.e. single-stepping with a signal |
1217 | // to deliver. |
1218 | const size_t num_continue_S_tids = m_continue_S_tids.size(); |
1219 | if (direction == RunDirection::eRunForward && |
1220 | m_gdb_comm.HasAnyVContSupport()) { |
1221 | std::string pid_prefix; |
1222 | if (m_gdb_comm.GetMultiprocessSupported()) |
1223 | pid_prefix = llvm::formatv(Fmt: "p{0:x-}.", Vals: GetID()); |
1224 | |
1225 | if (num_continue_c_tids == num_threads || |
1226 | (m_continue_c_tids.empty() && m_continue_C_tids.empty() && |
1227 | m_continue_s_tids.empty() && m_continue_S_tids.empty())) { |
1228 | // All threads are continuing |
1229 | if (m_gdb_comm.GetMultiprocessSupported()) |
1230 | continue_packet.Format(format: "vCont;c:{0}-1", args&: pid_prefix); |
1231 | else |
1232 | continue_packet.PutCString(cstr: "c"); |
1233 | } else { |
1234 | continue_packet.PutCString(cstr: "vCont"); |
1235 | |
1236 | if (!m_continue_c_tids.empty()) { |
1237 | if (m_gdb_comm.GetVContSupported(flavor: 'c')) { |
1238 | for (tid_collection::const_iterator |
1239 | t_pos = m_continue_c_tids.begin(), |
1240 | t_end = m_continue_c_tids.end(); |
1241 | t_pos != t_end; ++t_pos) |
1242 | continue_packet.Format(format: ";c:{0}{1:x-}", args&: pid_prefix, args: *t_pos); |
1243 | } else |
1244 | continue_packet_error = true; |
1245 | } |
1246 | |
1247 | if (!continue_packet_error && !m_continue_C_tids.empty()) { |
1248 | if (m_gdb_comm.GetVContSupported(flavor: 'C')) { |
1249 | for (tid_sig_collection::const_iterator |
1250 | s_pos = m_continue_C_tids.begin(), |
1251 | s_end = m_continue_C_tids.end(); |
1252 | s_pos != s_end; ++s_pos) |
1253 | continue_packet.Format(format: ";C{0:x-2}:{1}{2:x-}", args: s_pos->second, |
1254 | args&: pid_prefix, args: s_pos->first); |
1255 | } else |
1256 | continue_packet_error = true; |
1257 | } |
1258 | |
1259 | if (!continue_packet_error && !m_continue_s_tids.empty()) { |
1260 | if (m_gdb_comm.GetVContSupported(flavor: 's')) { |
1261 | for (tid_collection::const_iterator |
1262 | t_pos = m_continue_s_tids.begin(), |
1263 | t_end = m_continue_s_tids.end(); |
1264 | t_pos != t_end; ++t_pos) |
1265 | continue_packet.Format(format: ";s:{0}{1:x-}", args&: pid_prefix, args: *t_pos); |
1266 | } else |
1267 | continue_packet_error = true; |
1268 | } |
1269 | |
1270 | if (!continue_packet_error && !m_continue_S_tids.empty()) { |
1271 | if (m_gdb_comm.GetVContSupported(flavor: 'S')) { |
1272 | for (tid_sig_collection::const_iterator |
1273 | s_pos = m_continue_S_tids.begin(), |
1274 | s_end = m_continue_S_tids.end(); |
1275 | s_pos != s_end; ++s_pos) |
1276 | continue_packet.Format(format: ";S{0:x-2}:{1}{2:x-}", args: s_pos->second, |
1277 | args&: pid_prefix, args: s_pos->first); |
1278 | } else |
1279 | continue_packet_error = true; |
1280 | } |
1281 | |
1282 | if (continue_packet_error) |
1283 | continue_packet.Clear(); |
1284 | } |
1285 | } else |
1286 | continue_packet_error = true; |
1287 | |
1288 | if (direction == RunDirection::eRunForward && continue_packet_error) { |
1289 | // Either no vCont support, or we tried to use part of the vCont packet |
1290 | // that wasn't supported by the remote GDB server. We need to try and |
1291 | // make a simple packet that can do our continue. |
1292 | if (num_continue_c_tids > 0) { |
1293 | if (num_continue_c_tids == num_threads) { |
1294 | // All threads are resuming... |
1295 | m_gdb_comm.SetCurrentThreadForRun(tid: -1); |
1296 | continue_packet.PutChar(ch: 'c'); |
1297 | continue_packet_error = false; |
1298 | } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 && |
1299 | num_continue_s_tids == 0 && num_continue_S_tids == 0) { |
1300 | // Only one thread is continuing |
1301 | m_gdb_comm.SetCurrentThreadForRun(tid: m_continue_c_tids.front()); |
1302 | continue_packet.PutChar(ch: 'c'); |
1303 | continue_packet_error = false; |
1304 | } |
1305 | } |
1306 | |
1307 | if (continue_packet_error && num_continue_C_tids > 0) { |
1308 | if ((num_continue_C_tids + num_continue_c_tids) == num_threads && |
1309 | num_continue_C_tids > 0 && num_continue_s_tids == 0 && |
1310 | num_continue_S_tids == 0) { |
1311 | const int continue_signo = m_continue_C_tids.front().second; |
1312 | // Only one thread is continuing |
1313 | if (num_continue_C_tids > 1) { |
1314 | // More that one thread with a signal, yet we don't have vCont |
1315 | // support and we are being asked to resume each thread with a |
1316 | // signal, we need to make sure they are all the same signal, or we |
1317 | // can't issue the continue accurately with the current support... |
1318 | if (num_continue_C_tids > 1) { |
1319 | continue_packet_error = false; |
1320 | for (size_t i = 1; i < m_continue_C_tids.size(); ++i) { |
1321 | if (m_continue_C_tids[i].second != continue_signo) |
1322 | continue_packet_error = true; |
1323 | } |
1324 | } |
1325 | if (!continue_packet_error) |
1326 | m_gdb_comm.SetCurrentThreadForRun(tid: -1); |
1327 | } else { |
1328 | // Set the continue thread ID |
1329 | continue_packet_error = false; |
1330 | m_gdb_comm.SetCurrentThreadForRun(tid: m_continue_C_tids.front().first); |
1331 | } |
1332 | if (!continue_packet_error) { |
1333 | // Add threads continuing with the same signo... |
1334 | continue_packet.Printf(format: "C%2.2x", continue_signo); |
1335 | } |
1336 | } |
1337 | } |
1338 | |
1339 | if (continue_packet_error && num_continue_s_tids > 0) { |
1340 | if (num_continue_s_tids == num_threads) { |
1341 | // All threads are resuming... |
1342 | m_gdb_comm.SetCurrentThreadForRun(tid: -1); |
1343 | |
1344 | continue_packet.PutChar(ch: 's'); |
1345 | |
1346 | continue_packet_error = false; |
1347 | } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 && |
1348 | num_continue_s_tids == 1 && num_continue_S_tids == 0) { |
1349 | // Only one thread is stepping |
1350 | m_gdb_comm.SetCurrentThreadForRun(tid: m_continue_s_tids.front()); |
1351 | continue_packet.PutChar(ch: 's'); |
1352 | continue_packet_error = false; |
1353 | } |
1354 | } |
1355 | |
1356 | if (!continue_packet_error && num_continue_S_tids > 0) { |
1357 | if (num_continue_S_tids == num_threads) { |
1358 | const int step_signo = m_continue_S_tids.front().second; |
1359 | // Are all threads trying to step with the same signal? |
1360 | continue_packet_error = false; |
1361 | if (num_continue_S_tids > 1) { |
1362 | for (size_t i = 1; i < num_threads; ++i) { |
1363 | if (m_continue_S_tids[i].second != step_signo) |
1364 | continue_packet_error = true; |
1365 | } |
1366 | } |
1367 | if (!continue_packet_error) { |
1368 | // Add threads stepping with the same signo... |
1369 | m_gdb_comm.SetCurrentThreadForRun(tid: -1); |
1370 | continue_packet.Printf(format: "S%2.2x", step_signo); |
1371 | } |
1372 | } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 && |
1373 | num_continue_s_tids == 0 && num_continue_S_tids == 1) { |
1374 | // Only one thread is stepping with signal |
1375 | m_gdb_comm.SetCurrentThreadForRun(tid: m_continue_S_tids.front().first); |
1376 | continue_packet.Printf(format: "S%2.2x", m_continue_S_tids.front().second); |
1377 | continue_packet_error = false; |
1378 | } |
1379 | } |
1380 | } |
1381 | |
1382 | if (direction == RunDirection::eRunReverse) { |
1383 | if (num_continue_s_tids > 0 || num_continue_S_tids > 0) { |
1384 | if (!m_gdb_comm.GetReverseStepSupported()) { |
1385 | LLDB_LOGF(log, "ProcessGDBRemote::DoResume: target does not " |
1386 | "support reverse-stepping"); |
1387 | return Status::FromErrorString( |
1388 | str: "target does not support reverse-stepping"); |
1389 | } |
1390 | |
1391 | if (num_continue_S_tids > 0) { |
1392 | LLDB_LOGF( |
1393 | log, |
1394 | "ProcessGDBRemote::DoResume: Signals not supported in reverse"); |
1395 | return Status::FromErrorString( |
1396 | str: "can't deliver signals while running in reverse"); |
1397 | } |
1398 | |
1399 | if (num_continue_s_tids > 1) { |
1400 | LLDB_LOGF(log, "ProcessGDBRemote::DoResume: can't step multiple " |
1401 | "threads in reverse"); |
1402 | return Status::FromErrorString( |
1403 | str: "can't step multiple threads while reverse-stepping"); |
1404 | } |
1405 | |
1406 | m_gdb_comm.SetCurrentThreadForRun(tid: m_continue_s_tids.front()); |
1407 | continue_packet.PutCString(cstr: "bs"); |
1408 | } else { |
1409 | if (!m_gdb_comm.GetReverseContinueSupported()) { |
1410 | LLDB_LOGF(log, "ProcessGDBRemote::DoResume: target does not " |
1411 | "support reverse-continue"); |
1412 | return Status::FromErrorString( |
1413 | str: "target does not support reverse execution of processes"); |
1414 | } |
1415 | |
1416 | if (num_continue_C_tids > 0) { |
1417 | LLDB_LOGF( |
1418 | log, |
1419 | "ProcessGDBRemote::DoResume: Signals not supported in reverse"); |
1420 | return Status::FromErrorString( |
1421 | str: "can't deliver signals while running in reverse"); |
1422 | } |
1423 | |
1424 | // All threads continue whether requested or not --- |
1425 | // we can't change how threads ran in the past. |
1426 | continue_packet.PutCString(cstr: "bc"); |
1427 | } |
1428 | |
1429 | continue_packet_error = false; |
1430 | } |
1431 | |
1432 | if (continue_packet_error) { |
1433 | return Status::FromErrorString( |
1434 | str: "can't make continue packet for this resume"); |
1435 | } else { |
1436 | EventSP event_sp; |
1437 | if (!m_async_thread.IsJoinable()) { |
1438 | error = Status::FromErrorString( |
1439 | str: "Trying to resume but the async thread is dead."); |
1440 | LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the " |
1441 | "async thread is dead."); |
1442 | return error; |
1443 | } |
1444 | |
1445 | auto data_sp = |
1446 | std::make_shared<EventDataBytes>(args: continue_packet.GetString()); |
1447 | m_async_broadcaster.BroadcastEvent(event_type: eBroadcastBitAsyncContinue, event_data_sp: data_sp); |
1448 | |
1449 | if (!listener_sp->GetEvent(event_sp, timeout: ResumeTimeout())) { |
1450 | error = Status::FromErrorString(str: "Resume timed out."); |
1451 | LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out."); |
1452 | } else if (event_sp->BroadcasterIs(broadcaster: &m_async_broadcaster)) { |
1453 | error = Status::FromErrorString( |
1454 | str: "Broadcast continue, but the async thread was " |
1455 | "killed before we got an ack back."); |
1456 | LLDB_LOGF(log, |
1457 | "ProcessGDBRemote::DoResume: Broadcast continue, but the " |
1458 | "async thread was killed before we got an ack back."); |
1459 | return error; |
1460 | } |
1461 | } |
1462 | } |
1463 | |
1464 | return error; |
1465 | } |
1466 | |
1467 | void ProcessGDBRemote::ClearThreadIDList() { |
1468 | std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); |
1469 | m_thread_ids.clear(); |
1470 | m_thread_pcs.clear(); |
1471 | } |
1472 | |
1473 | size_t ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue( |
1474 | llvm::StringRef value) { |
1475 | m_thread_ids.clear(); |
1476 | lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); |
1477 | StringExtractorGDBRemote thread_ids{value}; |
1478 | |
1479 | do { |
1480 | auto pid_tid = thread_ids.GetPidTid(default_pid: pid); |
1481 | if (pid_tid && pid_tid->first == pid) { |
1482 | lldb::tid_t tid = pid_tid->second; |
1483 | if (tid != LLDB_INVALID_THREAD_ID && |
1484 | tid != StringExtractorGDBRemote::AllProcesses) |
1485 | m_thread_ids.push_back(x: tid); |
1486 | } |
1487 | } while (thread_ids.GetChar() == ','); |
1488 | |
1489 | return m_thread_ids.size(); |
1490 | } |
1491 | |
1492 | size_t ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue( |
1493 | llvm::StringRef value) { |
1494 | m_thread_pcs.clear(); |
1495 | for (llvm::StringRef x : llvm::split(Str: value, Separator: ',')) { |
1496 | lldb::addr_t pc; |
1497 | if (llvm::to_integer(S: x, Num&: pc, Base: 16)) |
1498 | m_thread_pcs.push_back(x: pc); |
1499 | } |
1500 | return m_thread_pcs.size(); |
1501 | } |
1502 | |
1503 | bool ProcessGDBRemote::UpdateThreadIDList() { |
1504 | std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); |
1505 | |
1506 | if (m_jthreadsinfo_sp) { |
1507 | // If we have the JSON threads info, we can get the thread list from that |
1508 | StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray(); |
1509 | if (thread_infos && thread_infos->GetSize() > 0) { |
1510 | m_thread_ids.clear(); |
1511 | m_thread_pcs.clear(); |
1512 | thread_infos->ForEach(foreach_callback: [this](StructuredData::Object *object) -> bool { |
1513 | StructuredData::Dictionary *thread_dict = object->GetAsDictionary(); |
1514 | if (thread_dict) { |
1515 | // Set the thread stop info from the JSON dictionary |
1516 | SetThreadStopInfo(thread_dict); |
1517 | lldb::tid_t tid = LLDB_INVALID_THREAD_ID; |
1518 | if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(key: "tid", result&: tid)) |
1519 | m_thread_ids.push_back(x: tid); |
1520 | } |
1521 | return true; // Keep iterating through all thread_info objects |
1522 | }); |
1523 | } |
1524 | if (!m_thread_ids.empty()) |
1525 | return true; |
1526 | } else { |
1527 | // See if we can get the thread IDs from the current stop reply packets |
1528 | // that might contain a "threads" key/value pair |
1529 | |
1530 | if (m_last_stop_packet) { |
1531 | // Get the thread stop info |
1532 | StringExtractorGDBRemote &stop_info = *m_last_stop_packet; |
1533 | const std::string &stop_info_str = std::string(stop_info.GetStringRef()); |
1534 | |
1535 | m_thread_pcs.clear(); |
1536 | const size_t thread_pcs_pos = stop_info_str.find(s: ";thread-pcs:"); |
1537 | if (thread_pcs_pos != std::string::npos) { |
1538 | const size_t start = thread_pcs_pos + strlen(s: ";thread-pcs:"); |
1539 | const size_t end = stop_info_str.find(c: ';', pos: start); |
1540 | if (end != std::string::npos) { |
1541 | std::string value = stop_info_str.substr(pos: start, n: end - start); |
1542 | UpdateThreadPCsFromStopReplyThreadsValue(value); |
1543 | } |
1544 | } |
1545 | |
1546 | const size_t threads_pos = stop_info_str.find(s: ";threads:"); |
1547 | if (threads_pos != std::string::npos) { |
1548 | const size_t start = threads_pos + strlen(s: ";threads:"); |
1549 | const size_t end = stop_info_str.find(c: ';', pos: start); |
1550 | if (end != std::string::npos) { |
1551 | std::string value = stop_info_str.substr(pos: start, n: end - start); |
1552 | if (UpdateThreadIDsFromStopReplyThreadsValue(value)) |
1553 | return true; |
1554 | } |
1555 | } |
1556 | } |
1557 | } |
1558 | |
1559 | bool sequence_mutex_unavailable = false; |
1560 | m_gdb_comm.GetCurrentThreadIDs(thread_ids&: m_thread_ids, sequence_mutex_unavailable); |
1561 | if (sequence_mutex_unavailable) { |
1562 | return false; // We just didn't get the list |
1563 | } |
1564 | return true; |
1565 | } |
1566 | |
1567 | bool ProcessGDBRemote::DoUpdateThreadList(ThreadList &old_thread_list, |
1568 | ThreadList &new_thread_list) { |
1569 | // locker will keep a mutex locked until it goes out of scope |
1570 | Log *log = GetLog(mask: GDBRLog::Thread); |
1571 | LLDB_LOGV(log, "pid = {0}", GetID()); |
1572 | |
1573 | size_t num_thread_ids = m_thread_ids.size(); |
1574 | // The "m_thread_ids" thread ID list should always be updated after each stop |
1575 | // reply packet, but in case it isn't, update it here. |
1576 | if (num_thread_ids == 0) { |
1577 | if (!UpdateThreadIDList()) |
1578 | return false; |
1579 | num_thread_ids = m_thread_ids.size(); |
1580 | } |
1581 | |
1582 | ThreadList old_thread_list_copy(old_thread_list); |
1583 | if (num_thread_ids > 0) { |
1584 | for (size_t i = 0; i < num_thread_ids; ++i) { |
1585 | lldb::tid_t tid = m_thread_ids[i]; |
1586 | ThreadSP thread_sp( |
1587 | old_thread_list_copy.RemoveThreadByProtocolID(tid, can_update: false)); |
1588 | if (!thread_sp) { |
1589 | thread_sp = std::make_shared<ThreadGDBRemote>(args&: *this, args&: tid); |
1590 | LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.", |
1591 | thread_sp.get(), thread_sp->GetID()); |
1592 | } else { |
1593 | LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.", |
1594 | thread_sp.get(), thread_sp->GetID()); |
1595 | } |
1596 | |
1597 | SetThreadPc(thread_sp, index: i); |
1598 | new_thread_list.AddThreadSortedByIndexID(thread_sp); |
1599 | } |
1600 | } |
1601 | |
1602 | // Whatever that is left in old_thread_list_copy are not present in |
1603 | // new_thread_list. Remove non-existent threads from internal id table. |
1604 | size_t old_num_thread_ids = old_thread_list_copy.GetSize(can_update: false); |
1605 | for (size_t i = 0; i < old_num_thread_ids; i++) { |
1606 | ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(idx: i, can_update: false)); |
1607 | if (old_thread_sp) { |
1608 | lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID(); |
1609 | m_thread_id_to_index_id_map.erase(x: old_thread_id); |
1610 | } |
1611 | } |
1612 | |
1613 | return true; |
1614 | } |
1615 | |
1616 | void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) { |
1617 | if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() && |
1618 | GetByteOrder() != eByteOrderInvalid) { |
1619 | ThreadGDBRemote *gdb_thread = |
1620 | static_cast<ThreadGDBRemote *>(thread_sp.get()); |
1621 | RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext()); |
1622 | if (reg_ctx_sp) { |
1623 | uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber( |
1624 | kind: eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); |
1625 | if (pc_regnum != LLDB_INVALID_REGNUM) { |
1626 | gdb_thread->PrivateSetRegisterValue(reg: pc_regnum, regval: m_thread_pcs[index]); |
1627 | } |
1628 | } |
1629 | } |
1630 | } |
1631 | |
1632 | bool ProcessGDBRemote::GetThreadStopInfoFromJSON( |
1633 | ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) { |
1634 | // See if we got thread stop infos for all threads via the "jThreadsInfo" |
1635 | // packet |
1636 | if (thread_infos_sp) { |
1637 | StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray(); |
1638 | if (thread_infos) { |
1639 | lldb::tid_t tid; |
1640 | const size_t n = thread_infos->GetSize(); |
1641 | for (size_t i = 0; i < n; ++i) { |
1642 | StructuredData::Dictionary *thread_dict = |
1643 | thread_infos->GetItemAtIndex(idx: i)->GetAsDictionary(); |
1644 | if (thread_dict) { |
1645 | if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>( |
1646 | key: "tid", result&: tid, LLDB_INVALID_THREAD_ID)) { |
1647 | if (tid == thread->GetID()) |
1648 | return (bool)SetThreadStopInfo(thread_dict); |
1649 | } |
1650 | } |
1651 | } |
1652 | } |
1653 | } |
1654 | return false; |
1655 | } |
1656 | |
1657 | bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) { |
1658 | // See if we got thread stop infos for all threads via the "jThreadsInfo" |
1659 | // packet |
1660 | if (GetThreadStopInfoFromJSON(thread, thread_infos_sp: m_jthreadsinfo_sp)) |
1661 | return true; |
1662 | |
1663 | // See if we got thread stop info for any threads valid stop info reasons |
1664 | // threads via the "jstopinfo" packet stop reply packet key/value pair? |
1665 | if (m_jstopinfo_sp) { |
1666 | // If we have "jstopinfo" then we have stop descriptions for all threads |
1667 | // that have stop reasons, and if there is no entry for a thread, then it |
1668 | // has no stop reason. |
1669 | if (!GetThreadStopInfoFromJSON(thread, thread_infos_sp: m_jstopinfo_sp)) |
1670 | thread->SetStopInfo(StopInfoSP()); |
1671 | return true; |
1672 | } |
1673 | |
1674 | // Fall back to using the qThreadStopInfo packet |
1675 | StringExtractorGDBRemote stop_packet; |
1676 | if (GetGDBRemote().GetThreadStopInfo(tid: thread->GetProtocolID(), response&: stop_packet)) |
1677 | return SetThreadStopInfo(stop_packet) == eStateStopped; |
1678 | return false; |
1679 | } |
1680 | |
1681 | void ProcessGDBRemote::ParseExpeditedRegisters( |
1682 | ExpeditedRegisterMap &expedited_register_map, ThreadSP thread_sp) { |
1683 | ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get()); |
1684 | RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext()); |
1685 | |
1686 | for (const auto &pair : expedited_register_map) { |
1687 | StringExtractor reg_value_extractor(pair.second); |
1688 | WritableDataBufferSP buffer_sp( |
1689 | new DataBufferHeap(reg_value_extractor.GetStringRef().size() / 2, 0)); |
1690 | reg_value_extractor.GetHexBytes(dest: buffer_sp->GetData(), fail_fill_value: '\xcc'); |
1691 | uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber( |
1692 | kind: eRegisterKindProcessPlugin, num: pair.first); |
1693 | gdb_thread->PrivateSetRegisterValue(reg: lldb_regnum, data: buffer_sp->GetData()); |
1694 | } |
1695 | } |
1696 | |
1697 | ThreadSP ProcessGDBRemote::SetThreadStopInfo( |
1698 | lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map, |
1699 | uint8_t signo, const std::string &thread_name, const std::string &reason, |
1700 | const std::string &description, uint32_t exc_type, |
1701 | const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr, |
1702 | bool queue_vars_valid, // Set to true if queue_name, queue_kind and |
1703 | // queue_serial are valid |
1704 | LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t, |
1705 | std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) { |
1706 | |
1707 | if (tid == LLDB_INVALID_THREAD_ID) |
1708 | return nullptr; |
1709 | |
1710 | ThreadSP thread_sp; |
1711 | // Scope for "locker" below |
1712 | { |
1713 | // m_thread_list_real does have its own mutex, but we need to hold onto the |
1714 | // mutex between the call to m_thread_list_real.FindThreadByID(...) and the |
1715 | // m_thread_list_real.AddThread(...) so it doesn't change on us |
1716 | std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); |
1717 | thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, can_update: false); |
1718 | |
1719 | if (!thread_sp) { |
1720 | // Create the thread if we need to |
1721 | thread_sp = std::make_shared<ThreadGDBRemote>(args&: *this, args&: tid); |
1722 | m_thread_list_real.AddThread(thread_sp); |
1723 | } |
1724 | } |
1725 | |
1726 | ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get()); |
1727 | RegisterContextSP reg_ctx_sp(gdb_thread->GetRegisterContext()); |
1728 | |
1729 | reg_ctx_sp->InvalidateIfNeeded(force: true); |
1730 | |
1731 | auto iter = llvm::find(Range&: m_thread_ids, Val: tid); |
1732 | if (iter != m_thread_ids.end()) |
1733 | SetThreadPc(thread_sp, index: iter - m_thread_ids.begin()); |
1734 | |
1735 | ParseExpeditedRegisters(expedited_register_map, thread_sp); |
1736 | |
1737 | if (reg_ctx_sp->ReconfigureRegisterInfo()) { |
1738 | // Now we have changed the offsets of all the registers, so the values |
1739 | // will be corrupted. |
1740 | reg_ctx_sp->InvalidateAllRegisters(); |
1741 | // Expedited registers values will never contain registers that would be |
1742 | // resized by a reconfigure. So we are safe to continue using these |
1743 | // values. |
1744 | ParseExpeditedRegisters(expedited_register_map, thread_sp); |
1745 | } |
1746 | |
1747 | thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str()); |
1748 | |
1749 | gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr); |
1750 | // Check if the GDB server was able to provide the queue name, kind and serial |
1751 | // number |
1752 | if (queue_vars_valid) |
1753 | gdb_thread->SetQueueInfo(queue_name: std::move(queue_name), queue_kind, queue_serial, |
1754 | dispatch_queue_t, associated_with_libdispatch_queue: associated_with_dispatch_queue); |
1755 | else |
1756 | gdb_thread->ClearQueueInfo(); |
1757 | |
1758 | gdb_thread->SetAssociatedWithLibdispatchQueue(associated_with_dispatch_queue); |
1759 | |
1760 | if (dispatch_queue_t != LLDB_INVALID_ADDRESS) |
1761 | gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t); |
1762 | |
1763 | // Make sure we update our thread stop reason just once, but don't overwrite |
1764 | // the stop info for threads that haven't moved: |
1765 | StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(calculate: false); |
1766 | if (thread_sp->GetTemporaryResumeState() == eStateSuspended && |
1767 | current_stop_info_sp) { |
1768 | thread_sp->SetStopInfo(current_stop_info_sp); |
1769 | return thread_sp; |
1770 | } |
1771 | |
1772 | if (!thread_sp->StopInfoIsUpToDate()) { |
1773 | thread_sp->SetStopInfo(StopInfoSP()); |
1774 | |
1775 | addr_t pc = thread_sp->GetRegisterContext()->GetPC(); |
1776 | BreakpointSiteSP bp_site_sp = |
1777 | thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(addr: pc); |
1778 | if (bp_site_sp && bp_site_sp->IsEnabled()) |
1779 | thread_sp->SetThreadStoppedAtUnexecutedBP(pc); |
1780 | |
1781 | if (exc_type != 0) { |
1782 | // For thread plan async interrupt, creating stop info on the |
1783 | // original async interrupt request thread instead. If interrupt thread |
1784 | // does not exist anymore we fallback to current signal receiving thread |
1785 | // instead. |
1786 | ThreadSP interrupt_thread; |
1787 | if (m_interrupt_tid != LLDB_INVALID_THREAD_ID) |
1788 | interrupt_thread = HandleThreadAsyncInterrupt(signo, description); |
1789 | if (interrupt_thread) |
1790 | thread_sp = interrupt_thread; |
1791 | else { |
1792 | const size_t exc_data_size = exc_data.size(); |
1793 | thread_sp->SetStopInfo( |
1794 | StopInfoMachException::CreateStopReasonWithMachException( |
1795 | thread&: *thread_sp, exc_type, exc_data_count: exc_data_size, |
1796 | exc_code: exc_data_size >= 1 ? exc_data[0] : 0, |
1797 | exc_sub_code: exc_data_size >= 2 ? exc_data[1] : 0, |
1798 | exc_sub_sub_code: exc_data_size >= 3 ? exc_data[2] : 0)); |
1799 | } |
1800 | } else { |
1801 | bool handled = false; |
1802 | bool did_exec = false; |
1803 | // debugserver can send reason = "none" which is equivalent |
1804 | // to no reason. |
1805 | if (!reason.empty() && reason != "none") { |
1806 | if (reason == "trace") { |
1807 | thread_sp->SetStopInfo(StopInfo::CreateStopReasonToTrace(thread&: *thread_sp)); |
1808 | handled = true; |
1809 | } else if (reason == "breakpoint") { |
1810 | thread_sp->SetThreadHitBreakpointSite(); |
1811 | if (bp_site_sp) { |
1812 | // If the breakpoint is for this thread, then we'll report the hit, |
1813 | // but if it is for another thread, we can just report no reason. |
1814 | // We don't need to worry about stepping over the breakpoint here, |
1815 | // that will be taken care of when the thread resumes and notices |
1816 | // that there's a breakpoint under the pc. |
1817 | handled = true; |
1818 | if (bp_site_sp->ValidForThisThread(thread&: *thread_sp)) { |
1819 | thread_sp->SetStopInfo( |
1820 | StopInfo::CreateStopReasonWithBreakpointSiteID( |
1821 | thread&: *thread_sp, break_id: bp_site_sp->GetID())); |
1822 | } else { |
1823 | StopInfoSP invalid_stop_info_sp; |
1824 | thread_sp->SetStopInfo(invalid_stop_info_sp); |
1825 | } |
1826 | } |
1827 | } else if (reason == "trap") { |
1828 | // Let the trap just use the standard signal stop reason below... |
1829 | } else if (reason == "watchpoint") { |
1830 | // We will have between 1 and 3 fields in the description. |
1831 | // |
1832 | // \a wp_addr which is the original start address that |
1833 | // lldb requested be watched, or an address that the |
1834 | // hardware reported. This address should be within the |
1835 | // range of a currently active watchpoint region - lldb |
1836 | // should be able to find a watchpoint with this address. |
1837 | // |
1838 | // \a wp_index is the hardware watchpoint register number. |
1839 | // |
1840 | // \a wp_hit_addr is the actual address reported by the hardware, |
1841 | // which may be outside the range of a region we are watching. |
1842 | // |
1843 | // On MIPS, we may get a false watchpoint exception where an |
1844 | // access to the same 8 byte granule as a watchpoint will trigger, |
1845 | // even if the access was not within the range of the watched |
1846 | // region. When we get a \a wp_hit_addr outside the range of any |
1847 | // set watchpoint, continue execution without making it visible to |
1848 | // the user. |
1849 | // |
1850 | // On ARM, a related issue where a large access that starts |
1851 | // before the watched region (and extends into the watched |
1852 | // region) may report a hit address before the watched region. |
1853 | // lldb will not find the "nearest" watchpoint to |
1854 | // disable/step/re-enable it, so one of the valid watchpoint |
1855 | // addresses should be provided as \a wp_addr. |
1856 | StringExtractor desc_extractor(description.c_str()); |
1857 | // FIXME NativeThreadLinux::SetStoppedByWatchpoint sends this |
1858 | // up as |
1859 | // <address within wp range> <wp hw index> <actual accessed addr> |
1860 | // but this is not reading the <wp hw index>. Seems like it |
1861 | // wouldn't work on MIPS, where that third field is important. |
1862 | addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS); |
1863 | addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS); |
1864 | watch_id_t watch_id = LLDB_INVALID_WATCH_ID; |
1865 | bool silently_continue = false; |
1866 | WatchpointResourceSP wp_resource_sp; |
1867 | if (wp_hit_addr != LLDB_INVALID_ADDRESS) { |
1868 | wp_resource_sp = |
1869 | m_watchpoint_resource_list.FindByAddress(addr: wp_hit_addr); |
1870 | // On MIPS, \a wp_hit_addr outside the range of a watched |
1871 | // region means we should silently continue, it is a false hit. |
1872 | ArchSpec::Core core = GetTarget().GetArchitecture().GetCore(); |
1873 | if (!wp_resource_sp && core >= ArchSpec::kCore_mips_first && |
1874 | core <= ArchSpec::kCore_mips_last) |
1875 | silently_continue = true; |
1876 | } |
1877 | if (!wp_resource_sp && wp_addr != LLDB_INVALID_ADDRESS) |
1878 | wp_resource_sp = m_watchpoint_resource_list.FindByAddress(addr: wp_addr); |
1879 | if (!wp_resource_sp) { |
1880 | Log *log(GetLog(mask: GDBRLog::Watchpoints)); |
1881 | LLDB_LOGF(log, "failed to find watchpoint"); |
1882 | watch_id = LLDB_INVALID_SITE_ID; |
1883 | } else { |
1884 | // LWP_TODO: This is hardcoding a single Watchpoint in a |
1885 | // Resource, need to add |
1886 | // StopInfo::CreateStopReasonWithWatchpointResource which |
1887 | // represents all watchpoints that were tripped at this stop. |
1888 | watch_id = wp_resource_sp->GetConstituentAtIndex(idx: 0)->GetID(); |
1889 | } |
1890 | thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID( |
1891 | thread&: *thread_sp, watch_id, silently_continue)); |
1892 | handled = true; |
1893 | } else if (reason == "exception") { |
1894 | thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException( |
1895 | thread&: *thread_sp, description: description.c_str())); |
1896 | handled = true; |
1897 | } else if (reason == "history boundary") { |
1898 | thread_sp->SetStopInfo(StopInfo::CreateStopReasonHistoryBoundary( |
1899 | thread&: *thread_sp, description: description.c_str())); |
1900 | handled = true; |
1901 | } else if (reason == "exec") { |
1902 | did_exec = true; |
1903 | thread_sp->SetStopInfo( |
1904 | StopInfo::CreateStopReasonWithExec(thread&: *thread_sp)); |
1905 | handled = true; |
1906 | } else if (reason == "processor trace") { |
1907 | thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace( |
1908 | thread&: *thread_sp, description: description.c_str())); |
1909 | } else if (reason == "fork") { |
1910 | StringExtractor desc_extractor(description.c_str()); |
1911 | lldb::pid_t child_pid = |
1912 | desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID); |
1913 | lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID); |
1914 | thread_sp->SetStopInfo( |
1915 | StopInfo::CreateStopReasonFork(thread&: *thread_sp, child_pid, child_tid)); |
1916 | handled = true; |
1917 | } else if (reason == "vfork") { |
1918 | StringExtractor desc_extractor(description.c_str()); |
1919 | lldb::pid_t child_pid = |
1920 | desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID); |
1921 | lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID); |
1922 | thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork( |
1923 | thread&: *thread_sp, child_pid, child_tid)); |
1924 | handled = true; |
1925 | } else if (reason == "vforkdone") { |
1926 | thread_sp->SetStopInfo( |
1927 | StopInfo::CreateStopReasonVForkDone(thread&: *thread_sp)); |
1928 | handled = true; |
1929 | } |
1930 | } |
1931 | |
1932 | if (!handled && signo && !did_exec) { |
1933 | if (signo == SIGTRAP) { |
1934 | // Currently we are going to assume SIGTRAP means we are either |
1935 | // hitting a breakpoint or hardware single stepping. |
1936 | |
1937 | // We can't disambiguate between stepping-to-a-breakpointsite and |
1938 | // hitting-a-breakpointsite. |
1939 | // |
1940 | // A user can instruction-step, and be stopped at a BreakpointSite. |
1941 | // Or a user can be sitting at a BreakpointSite, |
1942 | // instruction-step which hits the breakpoint and the pc does not |
1943 | // advance. |
1944 | // |
1945 | // In both cases, we're at a BreakpointSite when stopped, and |
1946 | // the resume state was eStateStepping. |
1947 | |
1948 | // Assume if we're at a BreakpointSite, we hit it. |
1949 | handled = true; |
1950 | addr_t pc = |
1951 | thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset; |
1952 | BreakpointSiteSP bp_site_sp = |
1953 | thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress( |
1954 | addr: pc); |
1955 | |
1956 | // We can't know if we hit it or not. So if we are stopped at |
1957 | // a BreakpointSite, assume we hit it, and should step past the |
1958 | // breakpoint when we resume. This is contrary to how we handle |
1959 | // BreakpointSites in any other location, but we can't know for |
1960 | // sure what happened so it's a reasonable default. |
1961 | if (bp_site_sp) { |
1962 | if (bp_site_sp->IsEnabled()) |
1963 | thread_sp->SetThreadHitBreakpointSite(); |
1964 | |
1965 | if (bp_site_sp->ValidForThisThread(thread&: *thread_sp)) { |
1966 | if (m_breakpoint_pc_offset != 0) |
1967 | thread_sp->GetRegisterContext()->SetPC(pc); |
1968 | thread_sp->SetStopInfo( |
1969 | StopInfo::CreateStopReasonWithBreakpointSiteID( |
1970 | thread&: *thread_sp, break_id: bp_site_sp->GetID())); |
1971 | } else { |
1972 | StopInfoSP invalid_stop_info_sp; |
1973 | thread_sp->SetStopInfo(invalid_stop_info_sp); |
1974 | } |
1975 | } else { |
1976 | // If we were stepping then assume the stop was the result of the |
1977 | // trace. If we were not stepping then report the SIGTRAP. |
1978 | if (thread_sp->GetTemporaryResumeState() == eStateStepping) |
1979 | thread_sp->SetStopInfo( |
1980 | StopInfo::CreateStopReasonToTrace(thread&: *thread_sp)); |
1981 | else |
1982 | thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal( |
1983 | thread&: *thread_sp, signo, description: description.c_str())); |
1984 | } |
1985 | } |
1986 | if (!handled) { |
1987 | // For thread plan async interrupt, creating stop info on the |
1988 | // original async interrupt request thread instead. If interrupt |
1989 | // thread does not exist anymore we fallback to current signal |
1990 | // receiving thread instead. |
1991 | ThreadSP interrupt_thread; |
1992 | if (m_interrupt_tid != LLDB_INVALID_THREAD_ID) |
1993 | interrupt_thread = HandleThreadAsyncInterrupt(signo, description); |
1994 | if (interrupt_thread) |
1995 | thread_sp = interrupt_thread; |
1996 | else |
1997 | thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal( |
1998 | thread&: *thread_sp, signo, description: description.c_str())); |
1999 | } |
2000 | } |
2001 | |
2002 | if (!description.empty()) { |
2003 | lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo()); |
2004 | if (stop_info_sp) { |
2005 | const char *stop_info_desc = stop_info_sp->GetDescription(); |
2006 | if (!stop_info_desc || !stop_info_desc[0]) |
2007 | stop_info_sp->SetDescription(description.c_str()); |
2008 | } else { |
2009 | thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException( |
2010 | thread&: *thread_sp, description: description.c_str())); |
2011 | } |
2012 | } |
2013 | } |
2014 | } |
2015 | return thread_sp; |
2016 | } |
2017 | |
2018 | ThreadSP |
2019 | ProcessGDBRemote::HandleThreadAsyncInterrupt(uint8_t signo, |
2020 | const std::string &description) { |
2021 | ThreadSP thread_sp; |
2022 | { |
2023 | std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); |
2024 | thread_sp = m_thread_list_real.FindThreadByProtocolID(tid: m_interrupt_tid, |
2025 | /*can_update=*/false); |
2026 | } |
2027 | if (thread_sp) |
2028 | thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithInterrupt( |
2029 | thread&: *thread_sp, signo, description: description.c_str())); |
2030 | // Clear m_interrupt_tid regardless we can find original interrupt thread or |
2031 | // not. |
2032 | m_interrupt_tid = LLDB_INVALID_THREAD_ID; |
2033 | return thread_sp; |
2034 | } |
2035 | |
2036 | lldb::ThreadSP |
2037 | ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) { |
2038 | static constexpr llvm::StringLiteral g_key_tid("tid"); |
2039 | static constexpr llvm::StringLiteral g_key_name("name"); |
2040 | static constexpr llvm::StringLiteral g_key_reason("reason"); |
2041 | static constexpr llvm::StringLiteral g_key_metype("metype"); |
2042 | static constexpr llvm::StringLiteral g_key_medata("medata"); |
2043 | static constexpr llvm::StringLiteral g_key_qaddr("qaddr"); |
2044 | static constexpr llvm::StringLiteral g_key_dispatch_queue_t( |
2045 | "dispatch_queue_t"); |
2046 | static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue( |
2047 | "associated_with_dispatch_queue"); |
2048 | static constexpr llvm::StringLiteral g_key_queue_name("qname"); |
2049 | static constexpr llvm::StringLiteral g_key_queue_kind("qkind"); |
2050 | static constexpr llvm::StringLiteral g_key_queue_serial_number("qserialnum"); |
2051 | static constexpr llvm::StringLiteral g_key_registers("registers"); |
2052 | static constexpr llvm::StringLiteral g_key_memory("memory"); |
2053 | static constexpr llvm::StringLiteral g_key_description("description"); |
2054 | static constexpr llvm::StringLiteral g_key_signal("signal"); |
2055 | |
2056 | // Stop with signal and thread info |
2057 | lldb::tid_t tid = LLDB_INVALID_THREAD_ID; |
2058 | uint8_t signo = 0; |
2059 | std::string thread_name; |
2060 | std::string reason; |
2061 | std::string description; |
2062 | uint32_t exc_type = 0; |
2063 | std::vector<addr_t> exc_data; |
2064 | addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; |
2065 | ExpeditedRegisterMap expedited_register_map; |
2066 | bool queue_vars_valid = false; |
2067 | addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS; |
2068 | LazyBool associated_with_dispatch_queue = eLazyBoolCalculate; |
2069 | std::string queue_name; |
2070 | QueueKind queue_kind = eQueueKindUnknown; |
2071 | uint64_t queue_serial_number = 0; |
2072 | // Iterate through all of the thread dictionary key/value pairs from the |
2073 | // structured data dictionary |
2074 | |
2075 | // FIXME: we're silently ignoring invalid data here |
2076 | thread_dict->ForEach(callback: [this, &tid, &expedited_register_map, &thread_name, |
2077 | &signo, &reason, &description, &exc_type, &exc_data, |
2078 | &thread_dispatch_qaddr, &queue_vars_valid, |
2079 | &associated_with_dispatch_queue, &dispatch_queue_t, |
2080 | &queue_name, &queue_kind, &queue_serial_number]( |
2081 | llvm::StringRef key, |
2082 | StructuredData::Object *object) -> bool { |
2083 | if (key == g_key_tid) { |
2084 | // thread in big endian hex |
2085 | tid = object->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID); |
2086 | } else if (key == g_key_metype) { |
2087 | // exception type in big endian hex |
2088 | exc_type = object->GetUnsignedIntegerValue(fail_value: 0); |
2089 | } else if (key == g_key_medata) { |
2090 | // exception data in big endian hex |
2091 | StructuredData::Array *array = object->GetAsArray(); |
2092 | if (array) { |
2093 | array->ForEach(foreach_callback: [&exc_data](StructuredData::Object *object) -> bool { |
2094 | exc_data.push_back(x: object->GetUnsignedIntegerValue()); |
2095 | return true; // Keep iterating through all array items |
2096 | }); |
2097 | } |
2098 | } else if (key == g_key_name) { |
2099 | thread_name = std::string(object->GetStringValue()); |
2100 | } else if (key == g_key_qaddr) { |
2101 | thread_dispatch_qaddr = |
2102 | object->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS); |
2103 | } else if (key == g_key_queue_name) { |
2104 | queue_vars_valid = true; |
2105 | queue_name = std::string(object->GetStringValue()); |
2106 | } else if (key == g_key_queue_kind) { |
2107 | std::string queue_kind_str = std::string(object->GetStringValue()); |
2108 | if (queue_kind_str == "serial") { |
2109 | queue_vars_valid = true; |
2110 | queue_kind = eQueueKindSerial; |
2111 | } else if (queue_kind_str == "concurrent") { |
2112 | queue_vars_valid = true; |
2113 | queue_kind = eQueueKindConcurrent; |
2114 | } |
2115 | } else if (key == g_key_queue_serial_number) { |
2116 | queue_serial_number = object->GetUnsignedIntegerValue(fail_value: 0); |
2117 | if (queue_serial_number != 0) |
2118 | queue_vars_valid = true; |
2119 | } else if (key == g_key_dispatch_queue_t) { |
2120 | dispatch_queue_t = object->GetUnsignedIntegerValue(fail_value: 0); |
2121 | if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS) |
2122 | queue_vars_valid = true; |
2123 | } else if (key == g_key_associated_with_dispatch_queue) { |
2124 | queue_vars_valid = true; |
2125 | bool associated = object->GetBooleanValue(); |
2126 | if (associated) |
2127 | associated_with_dispatch_queue = eLazyBoolYes; |
2128 | else |
2129 | associated_with_dispatch_queue = eLazyBoolNo; |
2130 | } else if (key == g_key_reason) { |
2131 | reason = std::string(object->GetStringValue()); |
2132 | } else if (key == g_key_description) { |
2133 | description = std::string(object->GetStringValue()); |
2134 | } else if (key == g_key_registers) { |
2135 | StructuredData::Dictionary *registers_dict = object->GetAsDictionary(); |
2136 | |
2137 | if (registers_dict) { |
2138 | registers_dict->ForEach( |
2139 | callback: [&expedited_register_map](llvm::StringRef key, |
2140 | StructuredData::Object *object) -> bool { |
2141 | uint32_t reg; |
2142 | if (llvm::to_integer(S: key, Num&: reg)) |
2143 | expedited_register_map[reg] = |
2144 | std::string(object->GetStringValue()); |
2145 | return true; // Keep iterating through all array items |
2146 | }); |
2147 | } |
2148 | } else if (key == g_key_memory) { |
2149 | StructuredData::Array *array = object->GetAsArray(); |
2150 | if (array) { |
2151 | array->ForEach(foreach_callback: [this](StructuredData::Object *object) -> bool { |
2152 | StructuredData::Dictionary *mem_cache_dict = |
2153 | object->GetAsDictionary(); |
2154 | if (mem_cache_dict) { |
2155 | lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS; |
2156 | if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>( |
2157 | key: "address", result&: mem_cache_addr)) { |
2158 | if (mem_cache_addr != LLDB_INVALID_ADDRESS) { |
2159 | llvm::StringRef str; |
2160 | if (mem_cache_dict->GetValueForKeyAsString(key: "bytes", result&: str)) { |
2161 | StringExtractor bytes(str); |
2162 | bytes.SetFilePos(0); |
2163 | |
2164 | const size_t byte_size = bytes.GetStringRef().size() / 2; |
2165 | WritableDataBufferSP data_buffer_sp( |
2166 | new DataBufferHeap(byte_size, 0)); |
2167 | const size_t bytes_copied = |
2168 | bytes.GetHexBytes(dest: data_buffer_sp->GetData(), fail_fill_value: 0); |
2169 | if (bytes_copied == byte_size) |
2170 | m_memory_cache.AddL1CacheData(addr: mem_cache_addr, |
2171 | data_buffer_sp); |
2172 | } |
2173 | } |
2174 | } |
2175 | } |
2176 | return true; // Keep iterating through all array items |
2177 | }); |
2178 | } |
2179 | |
2180 | } else if (key == g_key_signal) |
2181 | signo = object->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER); |
2182 | return true; // Keep iterating through all dictionary key/value pairs |
2183 | }); |
2184 | |
2185 | return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name, |
2186 | reason, description, exc_type, exc_data, |
2187 | thread_dispatch_qaddr, queue_vars_valid, |
2188 | associated_with_dispatch_queue, dispatch_queue_t, |
2189 | queue_name, queue_kind, queue_serial: queue_serial_number); |
2190 | } |
2191 | |
2192 | StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) { |
2193 | lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); |
2194 | stop_packet.SetFilePos(0); |
2195 | const char stop_type = stop_packet.GetChar(); |
2196 | switch (stop_type) { |
2197 | case 'T': |
2198 | case 'S': { |
2199 | // This is a bit of a hack, but it is required. If we did exec, we need to |
2200 | // clear our thread lists and also know to rebuild our dynamic register |
2201 | // info before we lookup and threads and populate the expedited register |
2202 | // values so we need to know this right away so we can cleanup and update |
2203 | // our registers. |
2204 | const uint32_t stop_id = GetStopID(); |
2205 | if (stop_id == 0) { |
2206 | // Our first stop, make sure we have a process ID, and also make sure we |
2207 | // know about our registers |
2208 | if (GetID() == LLDB_INVALID_PROCESS_ID && pid != LLDB_INVALID_PROCESS_ID) |
2209 | SetID(pid); |
2210 | BuildDynamicRegisterInfo(force: true); |
2211 | } |
2212 | // Stop with signal and thread info |
2213 | lldb::pid_t stop_pid = LLDB_INVALID_PROCESS_ID; |
2214 | lldb::tid_t tid = LLDB_INVALID_THREAD_ID; |
2215 | const uint8_t signo = stop_packet.GetHexU8(); |
2216 | llvm::StringRef key; |
2217 | llvm::StringRef value; |
2218 | std::string thread_name; |
2219 | std::string reason; |
2220 | std::string description; |
2221 | uint32_t exc_type = 0; |
2222 | std::vector<addr_t> exc_data; |
2223 | addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; |
2224 | bool queue_vars_valid = |
2225 | false; // says if locals below that start with "queue_" are valid |
2226 | addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS; |
2227 | LazyBool associated_with_dispatch_queue = eLazyBoolCalculate; |
2228 | std::string queue_name; |
2229 | QueueKind queue_kind = eQueueKindUnknown; |
2230 | uint64_t queue_serial_number = 0; |
2231 | ExpeditedRegisterMap expedited_register_map; |
2232 | AddressableBits addressable_bits; |
2233 | while (stop_packet.GetNameColonValue(name&: key, value)) { |
2234 | if (key.compare(RHS: "metype") == 0) { |
2235 | // exception type in big endian hex |
2236 | value.getAsInteger(Radix: 16, Result&: exc_type); |
2237 | } else if (key.compare(RHS: "medata") == 0) { |
2238 | // exception data in big endian hex |
2239 | uint64_t x; |
2240 | value.getAsInteger(Radix: 16, Result&: x); |
2241 | exc_data.push_back(x: x); |
2242 | } else if (key.compare(RHS: "thread") == 0) { |
2243 | // thread-id |
2244 | StringExtractorGDBRemote thread_id{value}; |
2245 | auto pid_tid = thread_id.GetPidTid(default_pid: pid); |
2246 | if (pid_tid) { |
2247 | stop_pid = pid_tid->first; |
2248 | tid = pid_tid->second; |
2249 | } else |
2250 | tid = LLDB_INVALID_THREAD_ID; |
2251 | } else if (key.compare(RHS: "threads") == 0) { |
2252 | std::lock_guard<std::recursive_mutex> guard( |
2253 | m_thread_list_real.GetMutex()); |
2254 | UpdateThreadIDsFromStopReplyThreadsValue(value); |
2255 | } else if (key.compare(RHS: "thread-pcs") == 0) { |
2256 | m_thread_pcs.clear(); |
2257 | // A comma separated list of all threads in the current |
2258 | // process that includes the thread for this stop reply packet |
2259 | lldb::addr_t pc; |
2260 | while (!value.empty()) { |
2261 | llvm::StringRef pc_str; |
2262 | std::tie(args&: pc_str, args&: value) = value.split(Separator: ','); |
2263 | if (pc_str.getAsInteger(Radix: 16, Result&: pc)) |
2264 | pc = LLDB_INVALID_ADDRESS; |
2265 | m_thread_pcs.push_back(x: pc); |
2266 | } |
2267 | } else if (key.compare(RHS: "jstopinfo") == 0) { |
2268 | StringExtractor json_extractor(value); |
2269 | std::string json; |
2270 | // Now convert the HEX bytes into a string value |
2271 | json_extractor.GetHexByteString(str&: json); |
2272 | |
2273 | // This JSON contains thread IDs and thread stop info for all threads. |
2274 | // It doesn't contain expedited registers, memory or queue info. |
2275 | m_jstopinfo_sp = StructuredData::ParseJSON(json_text: json); |
2276 | } else if (key.compare(RHS: "hexname") == 0) { |
2277 | StringExtractor name_extractor(value); |
2278 | // Now convert the HEX bytes into a string value |
2279 | name_extractor.GetHexByteString(str&: thread_name); |
2280 | } else if (key.compare(RHS: "name") == 0) { |
2281 | thread_name = std::string(value); |
2282 | } else if (key.compare(RHS: "qaddr") == 0) { |
2283 | value.getAsInteger(Radix: 16, Result&: thread_dispatch_qaddr); |
2284 | } else if (key.compare(RHS: "dispatch_queue_t") == 0) { |
2285 | queue_vars_valid = true; |
2286 | value.getAsInteger(Radix: 16, Result&: dispatch_queue_t); |
2287 | } else if (key.compare(RHS: "qname") == 0) { |
2288 | queue_vars_valid = true; |
2289 | StringExtractor name_extractor(value); |
2290 | // Now convert the HEX bytes into a string value |
2291 | name_extractor.GetHexByteString(str&: queue_name); |
2292 | } else if (key.compare(RHS: "qkind") == 0) { |
2293 | queue_kind = llvm::StringSwitch<QueueKind>(value) |
2294 | .Case(S: "serial", Value: eQueueKindSerial) |
2295 | .Case(S: "concurrent", Value: eQueueKindConcurrent) |
2296 | .Default(Value: eQueueKindUnknown); |
2297 | queue_vars_valid = queue_kind != eQueueKindUnknown; |
2298 | } else if (key.compare(RHS: "qserialnum") == 0) { |
2299 | if (!value.getAsInteger(Radix: 0, Result&: queue_serial_number)) |
2300 | queue_vars_valid = true; |
2301 | } else if (key.compare(RHS: "reason") == 0) { |
2302 | reason = std::string(value); |
2303 | } else if (key.compare(RHS: "description") == 0) { |
2304 | StringExtractor desc_extractor(value); |
2305 | // Now convert the HEX bytes into a string value |
2306 | desc_extractor.GetHexByteString(str&: description); |
2307 | } else if (key.compare(RHS: "memory") == 0) { |
2308 | // Expedited memory. GDB servers can choose to send back expedited |
2309 | // memory that can populate the L1 memory cache in the process so that |
2310 | // things like the frame pointer backchain can be expedited. This will |
2311 | // help stack backtracing be more efficient by not having to send as |
2312 | // many memory read requests down the remote GDB server. |
2313 | |
2314 | // Key/value pair format: memory:<addr>=<bytes>; |
2315 | // <addr> is a number whose base will be interpreted by the prefix: |
2316 | // "0x[0-9a-fA-F]+" for hex |
2317 | // "0[0-7]+" for octal |
2318 | // "[1-9]+" for decimal |
2319 | // <bytes> is native endian ASCII hex bytes just like the register |
2320 | // values |
2321 | llvm::StringRef addr_str, bytes_str; |
2322 | std::tie(args&: addr_str, args&: bytes_str) = value.split(Separator: '='); |
2323 | if (!addr_str.empty() && !bytes_str.empty()) { |
2324 | lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS; |
2325 | if (!addr_str.getAsInteger(Radix: 0, Result&: mem_cache_addr)) { |
2326 | StringExtractor bytes(bytes_str); |
2327 | const size_t byte_size = bytes.GetBytesLeft() / 2; |
2328 | WritableDataBufferSP data_buffer_sp( |
2329 | new DataBufferHeap(byte_size, 0)); |
2330 | const size_t bytes_copied = |
2331 | bytes.GetHexBytes(dest: data_buffer_sp->GetData(), fail_fill_value: 0); |
2332 | if (bytes_copied == byte_size) |
2333 | m_memory_cache.AddL1CacheData(addr: mem_cache_addr, data_buffer_sp); |
2334 | } |
2335 | } |
2336 | } else if (key.compare(RHS: "watch") == 0 || key.compare(RHS: "rwatch") == 0 || |
2337 | key.compare(RHS: "awatch") == 0) { |
2338 | // Support standard GDB remote stop reply packet 'TAAwatch:addr' |
2339 | lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS; |
2340 | value.getAsInteger(Radix: 16, Result&: wp_addr); |
2341 | |
2342 | WatchpointResourceSP wp_resource_sp = |
2343 | m_watchpoint_resource_list.FindByAddress(addr: wp_addr); |
2344 | |
2345 | // Rewrite gdb standard watch/rwatch/awatch to |
2346 | // "reason:watchpoint" + "description:ADDR", |
2347 | // which is parsed in SetThreadStopInfo. |
2348 | reason = "watchpoint"; |
2349 | StreamString ostr; |
2350 | ostr.Printf(format: "%"PRIu64, wp_addr); |
2351 | description = std::string(ostr.GetString()); |
2352 | } else if (key.compare(RHS: "swbreak") == 0 || key.compare(RHS: "hwbreak") == 0) { |
2353 | reason = "breakpoint"; |
2354 | } else if (key.compare(RHS: "replaylog") == 0) { |
2355 | reason = "history boundary"; |
2356 | } else if (key.compare(RHS: "library") == 0) { |
2357 | auto error = LoadModules(); |
2358 | if (error) { |
2359 | Log *log(GetLog(mask: GDBRLog::Process)); |
2360 | LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}"); |
2361 | } |
2362 | } else if (key.compare(RHS: "fork") == 0 || key.compare(RHS: "vfork") == 0) { |
2363 | // fork includes child pid/tid in thread-id format |
2364 | StringExtractorGDBRemote thread_id{value}; |
2365 | auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID); |
2366 | if (!pid_tid) { |
2367 | Log *log(GetLog(mask: GDBRLog::Process)); |
2368 | LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value); |
2369 | pid_tid = {{LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID}}; |
2370 | } |
2371 | |
2372 | reason = key.str(); |
2373 | StreamString ostr; |
2374 | ostr.Printf(format: "%"PRIu64 " %"PRIu64, pid_tid->first, pid_tid->second); |
2375 | description = std::string(ostr.GetString()); |
2376 | } else if (key.compare(RHS: "addressing_bits") == 0) { |
2377 | uint64_t addressing_bits; |
2378 | if (!value.getAsInteger(Radix: 0, Result&: addressing_bits)) { |
2379 | addressable_bits.SetAddressableBits(addressing_bits); |
2380 | } |
2381 | } else if (key.compare(RHS: "low_mem_addressing_bits") == 0) { |
2382 | uint64_t addressing_bits; |
2383 | if (!value.getAsInteger(Radix: 0, Result&: addressing_bits)) { |
2384 | addressable_bits.SetLowmemAddressableBits(addressing_bits); |
2385 | } |
2386 | } else if (key.compare(RHS: "high_mem_addressing_bits") == 0) { |
2387 | uint64_t addressing_bits; |
2388 | if (!value.getAsInteger(Radix: 0, Result&: addressing_bits)) { |
2389 | addressable_bits.SetHighmemAddressableBits(addressing_bits); |
2390 | } |
2391 | } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) { |
2392 | uint32_t reg = UINT32_MAX; |
2393 | if (!key.getAsInteger(Radix: 16, Result&: reg)) |
2394 | expedited_register_map[reg] = std::string(std::move(value)); |
2395 | } |
2396 | // swbreak and hwbreak are also expected keys, but we don't need to |
2397 | // change our behaviour for them because lldb always expects the remote |
2398 | // to adjust the program counter (if relevant, e.g., for x86 targets) |
2399 | } |
2400 | |
2401 | if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) { |
2402 | Log *log = GetLog(mask: GDBRLog::Process); |
2403 | LLDB_LOG(log, |
2404 | "Received stop for incorrect PID = {0} (inferior PID = {1})", |
2405 | stop_pid, pid); |
2406 | return eStateInvalid; |
2407 | } |
2408 | |
2409 | if (tid == LLDB_INVALID_THREAD_ID) { |
2410 | // A thread id may be invalid if the response is old style 'S' packet |
2411 | // which does not provide the |
2412 | // thread information. So update the thread list and choose the first |
2413 | // one. |
2414 | UpdateThreadIDList(); |
2415 | |
2416 | if (!m_thread_ids.empty()) { |
2417 | tid = m_thread_ids.front(); |
2418 | } |
2419 | } |
2420 | |
2421 | SetAddressableBitMasks(addressable_bits); |
2422 | |
2423 | ThreadSP thread_sp = SetThreadStopInfo( |
2424 | tid, expedited_register_map, signo, thread_name, reason, description, |
2425 | exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid, |
2426 | associated_with_dispatch_queue, dispatch_queue_t, queue_name, |
2427 | queue_kind, queue_serial: queue_serial_number); |
2428 | |
2429 | return eStateStopped; |
2430 | } break; |
2431 | |
2432 | case 'W': |
2433 | case 'X': |
2434 | // process exited |
2435 | return eStateExited; |
2436 | |
2437 | default: |
2438 | break; |
2439 | } |
2440 | return eStateInvalid; |
2441 | } |
2442 | |
2443 | void ProcessGDBRemote::RefreshStateAfterStop() { |
2444 | std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex()); |
2445 | |
2446 | m_thread_ids.clear(); |
2447 | m_thread_pcs.clear(); |
2448 | |
2449 | // Set the thread stop info. It might have a "threads" key whose value is a |
2450 | // list of all thread IDs in the current process, so m_thread_ids might get |
2451 | // set. |
2452 | // Check to see if SetThreadStopInfo() filled in m_thread_ids? |
2453 | if (m_thread_ids.empty()) { |
2454 | // No, we need to fetch the thread list manually |
2455 | UpdateThreadIDList(); |
2456 | } |
2457 | |
2458 | // We might set some stop info's so make sure the thread list is up to |
2459 | // date before we do that or we might overwrite what was computed here. |
2460 | UpdateThreadListIfNeeded(); |
2461 | |
2462 | if (m_last_stop_packet) |
2463 | SetThreadStopInfo(*m_last_stop_packet); |
2464 | m_last_stop_packet.reset(); |
2465 | |
2466 | // If we have queried for a default thread id |
2467 | if (m_initial_tid != LLDB_INVALID_THREAD_ID) { |
2468 | m_thread_list.SetSelectedThreadByID(tid: m_initial_tid); |
2469 | m_initial_tid = LLDB_INVALID_THREAD_ID; |
2470 | } |
2471 | |
2472 | // Let all threads recover from stopping and do any clean up based on the |
2473 | // previous thread state (if any). |
2474 | m_thread_list_real.RefreshStateAfterStop(); |
2475 | } |
2476 | |
2477 | Status ProcessGDBRemote::DoHalt(bool &caused_stop) { |
2478 | Status error; |
2479 | |
2480 | if (m_public_state.GetValue() == eStateAttaching) { |
2481 | // We are being asked to halt during an attach. We used to just close our |
2482 | // file handle and debugserver will go away, but with remote proxies, it |
2483 | // is better to send a positive signal, so let's send the interrupt first... |
2484 | caused_stop = m_gdb_comm.Interrupt(interrupt_timeout: GetInterruptTimeout()); |
2485 | m_gdb_comm.Disconnect(); |
2486 | } else |
2487 | caused_stop = m_gdb_comm.Interrupt(interrupt_timeout: GetInterruptTimeout()); |
2488 | return error; |
2489 | } |
2490 | |
2491 | Status ProcessGDBRemote::DoDetach(bool keep_stopped) { |
2492 | Status error; |
2493 | Log *log = GetLog(mask: GDBRLog::Process); |
2494 | LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped); |
2495 | |
2496 | error = m_gdb_comm.Detach(keep_stopped); |
2497 | if (log) { |
2498 | if (error.Success()) |
2499 | log->PutCString( |
2500 | cstr: "ProcessGDBRemote::DoDetach() detach packet sent successfully"); |
2501 | else |
2502 | LLDB_LOGF(log, |
2503 | "ProcessGDBRemote::DoDetach() detach packet send failed: %s", |
2504 | error.AsCString() ? error.AsCString() : "<unknown error>"); |
2505 | } |
2506 | |
2507 | if (!error.Success()) |
2508 | return error; |
2509 | |
2510 | // Sleep for one second to let the process get all detached... |
2511 | StopAsyncThread(); |
2512 | |
2513 | SetPrivateState(eStateDetached); |
2514 | ResumePrivateStateThread(); |
2515 | |
2516 | // KillDebugserverProcess (); |
2517 | return error; |
2518 | } |
2519 | |
2520 | Status ProcessGDBRemote::DoDestroy() { |
2521 | Log *log = GetLog(mask: GDBRLog::Process); |
2522 | LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()"); |
2523 | |
2524 | // Interrupt if our inferior is running... |
2525 | int exit_status = SIGABRT; |
2526 | std::string exit_string; |
2527 | |
2528 | if (m_gdb_comm.IsConnected()) { |
2529 | if (m_public_state.GetValue() != eStateAttaching) { |
2530 | llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(pid: GetID()); |
2531 | |
2532 | if (kill_res) { |
2533 | exit_status = kill_res.get(); |
2534 | #if defined(__APPLE__) |
2535 | // For Native processes on Mac OS X, we launch through the Host |
2536 | // Platform, then hand the process off to debugserver, which becomes |
2537 | // the parent process through "PT_ATTACH". Then when we go to kill |
2538 | // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then |
2539 | // we call waitpid which returns with no error and the correct |
2540 | // status. But amusingly enough that doesn't seem to actually reap |
2541 | // the process, but instead it is left around as a Zombie. Probably |
2542 | // the kernel is in the process of switching ownership back to lldb |
2543 | // which was the original parent, and gets confused in the handoff. |
2544 | // Anyway, so call waitpid here to finally reap it. |
2545 | PlatformSP platform_sp(GetTarget().GetPlatform()); |
2546 | if (platform_sp && platform_sp->IsHost()) { |
2547 | int status; |
2548 | ::pid_t reap_pid; |
2549 | reap_pid = waitpid(GetID(), &status, WNOHANG); |
2550 | LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status); |
2551 | } |
2552 | #endif |
2553 | ClearThreadIDList(); |
2554 | exit_string.assign(s: "killed"); |
2555 | } else { |
2556 | exit_string.assign(str: llvm::toString(E: kill_res.takeError())); |
2557 | } |
2558 | } else { |
2559 | exit_string.assign(s: "killed or interrupted while attaching."); |
2560 | } |
2561 | } else { |
2562 | // If we missed setting the exit status on the way out, do it here. |
2563 | // NB set exit status can be called multiple times, the first one sets the |
2564 | // status. |
2565 | exit_string.assign(s: "destroying when not connected to debugserver"); |
2566 | } |
2567 | |
2568 | SetExitStatus(exit_status, exit_string: exit_string.c_str()); |
2569 | |
2570 | StopAsyncThread(); |
2571 | KillDebugserverProcess(); |
2572 | RemoveNewThreadBreakpoints(); |
2573 | return Status(); |
2574 | } |
2575 | |
2576 | void ProcessGDBRemote::RemoveNewThreadBreakpoints() { |
2577 | if (m_thread_create_bp_sp) { |
2578 | if (TargetSP target_sp = m_target_wp.lock()) |
2579 | target_sp->RemoveBreakpointByID(break_id: m_thread_create_bp_sp->GetID()); |
2580 | m_thread_create_bp_sp.reset(); |
2581 | } |
2582 | } |
2583 | |
2584 | void ProcessGDBRemote::SetLastStopPacket( |
2585 | const StringExtractorGDBRemote &response) { |
2586 | const bool did_exec = |
2587 | response.GetStringRef().find(Str: ";reason:exec;") != std::string::npos; |
2588 | if (did_exec) { |
2589 | Log *log = GetLog(mask: GDBRLog::Process); |
2590 | LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec"); |
2591 | |
2592 | m_thread_list_real.Clear(); |
2593 | m_thread_list.Clear(); |
2594 | BuildDynamicRegisterInfo(force: true); |
2595 | m_gdb_comm.ResetDiscoverableSettings(did_exec); |
2596 | } |
2597 | |
2598 | m_last_stop_packet = response; |
2599 | } |
2600 | |
2601 | void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) { |
2602 | Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(args: signals_sp)); |
2603 | } |
2604 | |
2605 | // Process Queries |
2606 | |
2607 | bool ProcessGDBRemote::IsAlive() { |
2608 | return m_gdb_comm.IsConnected() && Process::IsAlive(); |
2609 | } |
2610 | |
2611 | addr_t ProcessGDBRemote::GetImageInfoAddress() { |
2612 | // request the link map address via the $qShlibInfoAddr packet |
2613 | lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr(); |
2614 | |
2615 | // the loaded module list can also provides a link map address |
2616 | if (addr == LLDB_INVALID_ADDRESS) { |
2617 | llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList(); |
2618 | if (!list) { |
2619 | Log *log = GetLog(mask: GDBRLog::Process); |
2620 | LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}."); |
2621 | } else { |
2622 | addr = list->m_link_map; |
2623 | } |
2624 | } |
2625 | |
2626 | return addr; |
2627 | } |
2628 | |
2629 | void ProcessGDBRemote::WillPublicStop() { |
2630 | // See if the GDB remote client supports the JSON threads info. If so, we |
2631 | // gather stop info for all threads, expedited registers, expedited memory, |
2632 | // runtime queue information (iOS and MacOSX only), and more. Expediting |
2633 | // memory will help stack backtracing be much faster. Expediting registers |
2634 | // will make sure we don't have to read the thread registers for GPRs. |
2635 | m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo(); |
2636 | |
2637 | if (m_jthreadsinfo_sp) { |
2638 | // Now set the stop info for each thread and also expedite any registers |
2639 | // and memory that was in the jThreadsInfo response. |
2640 | StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray(); |
2641 | if (thread_infos) { |
2642 | const size_t n = thread_infos->GetSize(); |
2643 | for (size_t i = 0; i < n; ++i) { |
2644 | StructuredData::Dictionary *thread_dict = |
2645 | thread_infos->GetItemAtIndex(idx: i)->GetAsDictionary(); |
2646 | if (thread_dict) |
2647 | SetThreadStopInfo(thread_dict); |
2648 | } |
2649 | } |
2650 | } |
2651 | } |
2652 | |
2653 | // Process Memory |
2654 | size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size, |
2655 | Status &error) { |
2656 | using xPacketState = GDBRemoteCommunicationClient::xPacketState; |
2657 | |
2658 | GetMaxMemorySize(); |
2659 | xPacketState x_state = m_gdb_comm.GetxPacketState(); |
2660 | |
2661 | // M and m packets take 2 bytes for 1 byte of memory |
2662 | size_t max_memory_size = x_state != xPacketState::Unimplemented |
2663 | ? m_max_memory_size |
2664 | : m_max_memory_size / 2; |
2665 | if (size > max_memory_size) { |
2666 | // Keep memory read sizes down to a sane limit. This function will be |
2667 | // called multiple times in order to complete the task by |
2668 | // lldb_private::Process so it is ok to do this. |
2669 | size = max_memory_size; |
2670 | } |
2671 | |
2672 | char packet[64]; |
2673 | int packet_len; |
2674 | packet_len = ::snprintf(s: packet, maxlen: sizeof(packet), format: "%c%"PRIx64 ",%"PRIx64, |
2675 | x_state != xPacketState::Unimplemented ? 'x' : 'm', |
2676 | (uint64_t)addr, (uint64_t)size); |
2677 | assert(packet_len + 1 < (int)sizeof(packet)); |
2678 | UNUSED_IF_ASSERT_DISABLED(packet_len); |
2679 | StringExtractorGDBRemote response; |
2680 | if (m_gdb_comm.SendPacketAndWaitForResponse(payload: packet, response, |
2681 | interrupt_timeout: GetInterruptTimeout()) == |
2682 | GDBRemoteCommunication::PacketResult::Success) { |
2683 | if (response.IsNormalResponse()) { |
2684 | error.Clear(); |
2685 | if (x_state != xPacketState::Unimplemented) { |
2686 | // The lower level GDBRemoteCommunication packet receive layer has |
2687 | // already de-quoted any 0x7d character escaping that was present in |
2688 | // the packet |
2689 | |
2690 | llvm::StringRef data_received = response.GetStringRef(); |
2691 | if (x_state == xPacketState::Prefixed && |
2692 | !data_received.consume_front(Prefix: "b")) { |
2693 | error = Status::FromErrorStringWithFormatv( |
2694 | format: "unexpected response to GDB server memory read packet '{0}': " |
2695 | "'{1}'", |
2696 | args&: packet, args&: data_received); |
2697 | return 0; |
2698 | } |
2699 | // Don't write past the end of BUF if the remote debug server gave us |
2700 | // too much data for some reason. |
2701 | size_t memcpy_size = std::min(a: size, b: data_received.size()); |
2702 | memcpy(dest: buf, src: data_received.data(), n: memcpy_size); |
2703 | return memcpy_size; |
2704 | } else { |
2705 | return response.GetHexBytes( |
2706 | dest: llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), fail_fill_value: '\xdd'); |
2707 | } |
2708 | } else if (response.IsErrorResponse()) |
2709 | error = Status::FromErrorStringWithFormat( |
2710 | format: "memory read failed for 0x%"PRIx64, addr); |
2711 | else if (response.IsUnsupportedResponse()) |
2712 | error = Status::FromErrorStringWithFormat( |
2713 | format: "GDB server does not support reading memory"); |
2714 | else |
2715 | error = Status::FromErrorStringWithFormat( |
2716 | format: "unexpected response to GDB server memory read packet '%s': '%s'", |
2717 | packet, response.GetStringRef().data()); |
2718 | } else { |
2719 | error = Status::FromErrorStringWithFormat(format: "failed to send packet: '%s'", |
2720 | packet); |
2721 | } |
2722 | return 0; |
2723 | } |
2724 | |
2725 | bool ProcessGDBRemote::SupportsMemoryTagging() { |
2726 | return m_gdb_comm.GetMemoryTaggingSupported(); |
2727 | } |
2728 | |
2729 | llvm::Expected<std::vector<uint8_t>> |
2730 | ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr, size_t len, |
2731 | int32_t type) { |
2732 | // By this point ReadMemoryTags has validated that tagging is enabled |
2733 | // for this target/process/address. |
2734 | DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type); |
2735 | if (!buffer_sp) { |
2736 | return llvm::createStringError(EC: llvm::inconvertibleErrorCode(), |
2737 | S: "Error reading memory tags from remote"); |
2738 | } |
2739 | |
2740 | // Return the raw tag data |
2741 | llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData(); |
2742 | std::vector<uint8_t> got; |
2743 | got.reserve(n: tag_data.size()); |
2744 | std::copy(first: tag_data.begin(), last: tag_data.end(), result: std::back_inserter(x&: got)); |
2745 | return got; |
2746 | } |
2747 | |
2748 | Status ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr, size_t len, |
2749 | int32_t type, |
2750 | const std::vector<uint8_t> &tags) { |
2751 | // By now WriteMemoryTags should have validated that tagging is enabled |
2752 | // for this target/process. |
2753 | return m_gdb_comm.WriteMemoryTags(addr, len, type, tags); |
2754 | } |
2755 | |
2756 | Status ProcessGDBRemote::WriteObjectFile( |
2757 | std::vector<ObjectFile::LoadableData> entries) { |
2758 | Status error; |
2759 | // Sort the entries by address because some writes, like those to flash |
2760 | // memory, must happen in order of increasing address. |
2761 | llvm::stable_sort(Range&: entries, C: [](const ObjectFile::LoadableData a, |
2762 | const ObjectFile::LoadableData b) { |
2763 | return a.Dest < b.Dest; |
2764 | }); |
2765 | m_allow_flash_writes = true; |
2766 | error = Process::WriteObjectFile(entries); |
2767 | if (error.Success()) |
2768 | error = FlashDone(); |
2769 | else |
2770 | // Even though some of the writing failed, try to send a flash done if some |
2771 | // of the writing succeeded so the flash state is reset to normal, but |
2772 | // don't stomp on the error status that was set in the write failure since |
2773 | // that's the one we want to report back. |
2774 | FlashDone(); |
2775 | m_allow_flash_writes = false; |
2776 | return error; |
2777 | } |
2778 | |
2779 | bool ProcessGDBRemote::HasErased(FlashRange range) { |
2780 | auto size = m_erased_flash_ranges.GetSize(); |
2781 | for (size_t i = 0; i < size; ++i) |
2782 | if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range)) |
2783 | return true; |
2784 | return false; |
2785 | } |
2786 | |
2787 | Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) { |
2788 | Status status; |
2789 | |
2790 | MemoryRegionInfo region; |
2791 | status = GetMemoryRegionInfo(load_addr: addr, range_info&: region); |
2792 | if (!status.Success()) |
2793 | return status; |
2794 | |
2795 | // The gdb spec doesn't say if erasures are allowed across multiple regions, |
2796 | // but we'll disallow it to be safe and to keep the logic simple by worring |
2797 | // about only one region's block size. DoMemoryWrite is this function's |
2798 | // primary user, and it can easily keep writes within a single memory region |
2799 | if (addr + size > region.GetRange().GetRangeEnd()) { |
2800 | status = |
2801 | Status::FromErrorString(str: "Unable to erase flash in multiple regions"); |
2802 | return status; |
2803 | } |
2804 | |
2805 | uint64_t blocksize = region.GetBlocksize(); |
2806 | if (blocksize == 0) { |
2807 | status = |
2808 | Status::FromErrorString(str: "Unable to erase flash because blocksize is 0"); |
2809 | return status; |
2810 | } |
2811 | |
2812 | // Erasures can only be done on block boundary adresses, so round down addr |
2813 | // and round up size |
2814 | lldb::addr_t block_start_addr = addr - (addr % blocksize); |
2815 | size += (addr - block_start_addr); |
2816 | if ((size % blocksize) != 0) |
2817 | size += (blocksize - size % blocksize); |
2818 | |
2819 | FlashRange range(block_start_addr, size); |
2820 | |
2821 | if (HasErased(range)) |
2822 | return status; |
2823 | |
2824 | // We haven't erased the entire range, but we may have erased part of it. |
2825 | // (e.g., block A is already erased and range starts in A and ends in B). So, |
2826 | // adjust range if necessary to exclude already erased blocks. |
2827 | if (!m_erased_flash_ranges.IsEmpty()) { |
2828 | // Assuming that writes and erasures are done in increasing addr order, |
2829 | // because that is a requirement of the vFlashWrite command. Therefore, we |
2830 | // only need to look at the last range in the list for overlap. |
2831 | const auto &last_range = *m_erased_flash_ranges.Back(); |
2832 | if (range.GetRangeBase() < last_range.GetRangeEnd()) { |
2833 | auto overlap = last_range.GetRangeEnd() - range.GetRangeBase(); |
2834 | // overlap will be less than range.GetByteSize() or else HasErased() |
2835 | // would have been true |
2836 | range.SetByteSize(range.GetByteSize() - overlap); |
2837 | range.SetRangeBase(range.GetRangeBase() + overlap); |
2838 | } |
2839 | } |
2840 | |
2841 | StreamString packet; |
2842 | packet.Printf(format: "vFlashErase:%"PRIx64 ",%"PRIx64, range.GetRangeBase(), |
2843 | (uint64_t)range.GetByteSize()); |
2844 | |
2845 | StringExtractorGDBRemote response; |
2846 | if (m_gdb_comm.SendPacketAndWaitForResponse(payload: packet.GetString(), response, |
2847 | interrupt_timeout: GetInterruptTimeout()) == |
2848 | GDBRemoteCommunication::PacketResult::Success) { |
2849 | if (response.IsOKResponse()) { |
2850 | m_erased_flash_ranges.Insert(entry: range, combine: true); |
2851 | } else { |
2852 | if (response.IsErrorResponse()) |
2853 | status = Status::FromErrorStringWithFormat( |
2854 | format: "flash erase failed for 0x%"PRIx64, addr); |
2855 | else if (response.IsUnsupportedResponse()) |
2856 | status = Status::FromErrorStringWithFormat( |
2857 | format: "GDB server does not support flashing"); |
2858 | else |
2859 | status = Status::FromErrorStringWithFormat( |
2860 | format: "unexpected response to GDB server flash erase packet '%s': '%s'", |
2861 | packet.GetData(), response.GetStringRef().data()); |
2862 | } |
2863 | } else { |
2864 | status = Status::FromErrorStringWithFormat(format: "failed to send packet: '%s'", |
2865 | packet.GetData()); |
2866 | } |
2867 | return status; |
2868 | } |
2869 | |
2870 | Status ProcessGDBRemote::FlashDone() { |
2871 | Status status; |
2872 | // If we haven't erased any blocks, then we must not have written anything |
2873 | // either, so there is no need to actually send a vFlashDone command |
2874 | if (m_erased_flash_ranges.IsEmpty()) |
2875 | return status; |
2876 | StringExtractorGDBRemote response; |
2877 | if (m_gdb_comm.SendPacketAndWaitForResponse(payload: "vFlashDone", response, |
2878 | interrupt_timeout: GetInterruptTimeout()) == |
2879 | GDBRemoteCommunication::PacketResult::Success) { |
2880 | if (response.IsOKResponse()) { |
2881 | m_erased_flash_ranges.Clear(); |
2882 | } else { |
2883 | if (response.IsErrorResponse()) |
2884 | status = Status::FromErrorStringWithFormat(format: "flash done failed"); |
2885 | else if (response.IsUnsupportedResponse()) |
2886 | status = Status::FromErrorStringWithFormat( |
2887 | format: "GDB server does not support flashing"); |
2888 | else |
2889 | status = Status::FromErrorStringWithFormat( |
2890 | format: "unexpected response to GDB server flash done packet: '%s'", |
2891 | response.GetStringRef().data()); |
2892 | } |
2893 | } else { |
2894 | status = |
2895 | Status::FromErrorStringWithFormat(format: "failed to send flash done packet"); |
2896 | } |
2897 | return status; |
2898 | } |
2899 | |
2900 | size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf, |
2901 | size_t size, Status &error) { |
2902 | GetMaxMemorySize(); |
2903 | // M and m packets take 2 bytes for 1 byte of memory |
2904 | size_t max_memory_size = m_max_memory_size / 2; |
2905 | if (size > max_memory_size) { |
2906 | // Keep memory read sizes down to a sane limit. This function will be |
2907 | // called multiple times in order to complete the task by |
2908 | // lldb_private::Process so it is ok to do this. |
2909 | size = max_memory_size; |
2910 | } |
2911 | |
2912 | StreamGDBRemote packet; |
2913 | |
2914 | MemoryRegionInfo region; |
2915 | Status region_status = GetMemoryRegionInfo(load_addr: addr, range_info&: region); |
2916 | |
2917 | bool is_flash = |
2918 | region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes; |
2919 | |
2920 | if (is_flash) { |
2921 | if (!m_allow_flash_writes) { |
2922 | error = Status::FromErrorString(str: "Writing to flash memory is not allowed"); |
2923 | return 0; |
2924 | } |
2925 | // Keep the write within a flash memory region |
2926 | if (addr + size > region.GetRange().GetRangeEnd()) |
2927 | size = region.GetRange().GetRangeEnd() - addr; |
2928 | // Flash memory must be erased before it can be written |
2929 | error = FlashErase(addr, size); |
2930 | if (!error.Success()) |
2931 | return 0; |
2932 | packet.Printf(format: "vFlashWrite:%"PRIx64 ":", addr); |
2933 | packet.PutEscapedBytes(s: buf, src_len: size); |
2934 | } else { |
2935 | packet.Printf(format: "M%"PRIx64 ",%"PRIx64 ":", addr, (uint64_t)size); |
2936 | packet.PutBytesAsRawHex8(src: buf, src_len: size, src_byte_order: endian::InlHostByteOrder(), |
2937 | dst_byte_order: endian::InlHostByteOrder()); |
2938 | } |
2939 | StringExtractorGDBRemote response; |
2940 | if (m_gdb_comm.SendPacketAndWaitForResponse(payload: packet.GetString(), response, |
2941 | interrupt_timeout: GetInterruptTimeout()) == |
2942 | GDBRemoteCommunication::PacketResult::Success) { |
2943 | if (response.IsOKResponse()) { |
2944 | error.Clear(); |
2945 | return size; |
2946 | } else if (response.IsErrorResponse()) |
2947 | error = Status::FromErrorStringWithFormat( |
2948 | format: "memory write failed for 0x%"PRIx64, addr); |
2949 | else if (response.IsUnsupportedResponse()) |
2950 | error = Status::FromErrorStringWithFormat( |
2951 | format: "GDB server does not support writing memory"); |
2952 | else |
2953 | error = Status::FromErrorStringWithFormat( |
2954 | format: "unexpected response to GDB server memory write packet '%s': '%s'", |
2955 | packet.GetData(), response.GetStringRef().data()); |
2956 | } else { |
2957 | error = Status::FromErrorStringWithFormat(format: "failed to send packet: '%s'", |
2958 | packet.GetData()); |
2959 | } |
2960 | return 0; |
2961 | } |
2962 | |
2963 | lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size, |
2964 | uint32_t permissions, |
2965 | Status &error) { |
2966 | Log *log = GetLog(mask: LLDBLog::Process | LLDBLog::Expressions); |
2967 | addr_t allocated_addr = LLDB_INVALID_ADDRESS; |
2968 | |
2969 | if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) { |
2970 | allocated_addr = m_gdb_comm.AllocateMemory(size, permissions); |
2971 | if (allocated_addr != LLDB_INVALID_ADDRESS || |
2972 | m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes) |
2973 | return allocated_addr; |
2974 | } |
2975 | |
2976 | if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) { |
2977 | // Call mmap() to create memory in the inferior.. |
2978 | unsigned prot = 0; |
2979 | if (permissions & lldb::ePermissionsReadable) |
2980 | prot |= eMmapProtRead; |
2981 | if (permissions & lldb::ePermissionsWritable) |
2982 | prot |= eMmapProtWrite; |
2983 | if (permissions & lldb::ePermissionsExecutable) |
2984 | prot |= eMmapProtExec; |
2985 | |
2986 | if (InferiorCallMmap(proc: this, allocated_addr, addr: 0, length: size, prot, |
2987 | flags: eMmapFlagsAnon | eMmapFlagsPrivate, fd: -1, offset: 0)) |
2988 | m_addr_to_mmap_size[allocated_addr] = size; |
2989 | else { |
2990 | allocated_addr = LLDB_INVALID_ADDRESS; |
2991 | LLDB_LOGF(log, |
2992 | "ProcessGDBRemote::%s no direct stub support for memory " |
2993 | "allocation, and InferiorCallMmap also failed - is stub " |
2994 | "missing register context save/restore capability?", |
2995 | __FUNCTION__); |
2996 | } |
2997 | } |
2998 | |
2999 | if (allocated_addr == LLDB_INVALID_ADDRESS) |
3000 | error = Status::FromErrorStringWithFormat( |
3001 | format: "unable to allocate %"PRIu64 " bytes of memory with permissions %s", |
3002 | (uint64_t)size, GetPermissionsAsCString(permissions)); |
3003 | else |
3004 | error.Clear(); |
3005 | return allocated_addr; |
3006 | } |
3007 | |
3008 | Status ProcessGDBRemote::DoGetMemoryRegionInfo(addr_t load_addr, |
3009 | MemoryRegionInfo ®ion_info) { |
3010 | |
3011 | Status error(m_gdb_comm.GetMemoryRegionInfo(addr: load_addr, range_info&: region_info)); |
3012 | return error; |
3013 | } |
3014 | |
3015 | std::optional<uint32_t> ProcessGDBRemote::GetWatchpointSlotCount() { |
3016 | return m_gdb_comm.GetWatchpointSlotCount(); |
3017 | } |
3018 | |
3019 | std::optional<bool> ProcessGDBRemote::DoGetWatchpointReportedAfter() { |
3020 | return m_gdb_comm.GetWatchpointReportedAfter(); |
3021 | } |
3022 | |
3023 | Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) { |
3024 | Status error; |
3025 | LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); |
3026 | |
3027 | switch (supported) { |
3028 | case eLazyBoolCalculate: |
3029 | // We should never be deallocating memory without allocating memory first |
3030 | // so we should never get eLazyBoolCalculate |
3031 | error = Status::FromErrorString( |
3032 | str: "tried to deallocate memory without ever allocating memory"); |
3033 | break; |
3034 | |
3035 | case eLazyBoolYes: |
3036 | if (!m_gdb_comm.DeallocateMemory(addr)) |
3037 | error = Status::FromErrorStringWithFormat( |
3038 | format: "unable to deallocate memory at 0x%"PRIx64, addr); |
3039 | break; |
3040 | |
3041 | case eLazyBoolNo: |
3042 | // Call munmap() to deallocate memory in the inferior.. |
3043 | { |
3044 | MMapMap::iterator pos = m_addr_to_mmap_size.find(x: addr); |
3045 | if (pos != m_addr_to_mmap_size.end() && |
3046 | InferiorCallMunmap(proc: this, addr, length: pos->second)) |
3047 | m_addr_to_mmap_size.erase(position: pos); |
3048 | else |
3049 | error = Status::FromErrorStringWithFormat( |
3050 | format: "unable to deallocate memory at 0x%"PRIx64, addr); |
3051 | } |
3052 | break; |
3053 | } |
3054 | |
3055 | return error; |
3056 | } |
3057 | |
3058 | // Process STDIO |
3059 | size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len, |
3060 | Status &error) { |
3061 | if (m_stdio_communication.IsConnected()) { |
3062 | ConnectionStatus status; |
3063 | m_stdio_communication.WriteAll(src, src_len, status, error_ptr: nullptr); |
3064 | } else if (m_stdin_forward) { |
3065 | m_gdb_comm.SendStdinNotification(data: src, data_len: src_len); |
3066 | } |
3067 | return 0; |
3068 | } |
3069 | |
3070 | Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) { |
3071 | Status error; |
3072 | assert(bp_site != nullptr); |
3073 | |
3074 | // Get logging info |
3075 | Log *log = GetLog(mask: GDBRLog::Breakpoints); |
3076 | user_id_t site_id = bp_site->GetID(); |
3077 | |
3078 | // Get the breakpoint address |
3079 | const addr_t addr = bp_site->GetLoadAddress(); |
3080 | |
3081 | // Log that a breakpoint was requested |
3082 | LLDB_LOGF(log, |
3083 | "ProcessGDBRemote::EnableBreakpointSite (size_id = %"PRIu64 |
3084 | ") address = 0x%"PRIx64, |
3085 | site_id, (uint64_t)addr); |
3086 | |
3087 | // Breakpoint already exists and is enabled |
3088 | if (bp_site->IsEnabled()) { |
3089 | LLDB_LOGF(log, |
3090 | "ProcessGDBRemote::EnableBreakpointSite (size_id = %"PRIu64 |
3091 | ") address = 0x%"PRIx64 " -- SUCCESS (already enabled)", |
3092 | site_id, (uint64_t)addr); |
3093 | return error; |
3094 | } |
3095 | |
3096 | // Get the software breakpoint trap opcode size |
3097 | const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); |
3098 | |
3099 | // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this |
3100 | // breakpoint type is supported by the remote stub. These are set to true by |
3101 | // default, and later set to false only after we receive an unimplemented |
3102 | // response when sending a breakpoint packet. This means initially that |
3103 | // unless we were specifically instructed to use a hardware breakpoint, LLDB |
3104 | // will attempt to set a software breakpoint. HardwareRequired() also queries |
3105 | // a boolean variable which indicates if the user specifically asked for |
3106 | // hardware breakpoints. If true then we will skip over software |
3107 | // breakpoints. |
3108 | if (m_gdb_comm.SupportsGDBStoppointPacket(type: eBreakpointSoftware) && |
3109 | (!bp_site->HardwareRequired())) { |
3110 | // Try to send off a software breakpoint packet ($Z0) |
3111 | uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( |
3112 | type: eBreakpointSoftware, insert: true, addr, length: bp_op_size, interrupt_timeout: GetInterruptTimeout()); |
3113 | if (error_no == 0) { |
3114 | // The breakpoint was placed successfully |
3115 | bp_site->SetEnabled(true); |
3116 | bp_site->SetType(BreakpointSite::eExternal); |
3117 | return error; |
3118 | } |
3119 | |
3120 | // SendGDBStoppointTypePacket() will return an error if it was unable to |
3121 | // set this breakpoint. We need to differentiate between a error specific |
3122 | // to placing this breakpoint or if we have learned that this breakpoint |
3123 | // type is unsupported. To do this, we must test the support boolean for |
3124 | // this breakpoint type to see if it now indicates that this breakpoint |
3125 | // type is unsupported. If they are still supported then we should return |
3126 | // with the error code. If they are now unsupported, then we would like to |
3127 | // fall through and try another form of breakpoint. |
3128 | if (m_gdb_comm.SupportsGDBStoppointPacket(type: eBreakpointSoftware)) { |
3129 | if (error_no != UINT8_MAX) |
3130 | error = Status::FromErrorStringWithFormat( |
3131 | format: "error: %d sending the breakpoint request", error_no); |
3132 | else |
3133 | error = Status::FromErrorString(str: "error sending the breakpoint request"); |
3134 | return error; |
3135 | } |
3136 | |
3137 | // We reach here when software breakpoints have been found to be |
3138 | // unsupported. For future calls to set a breakpoint, we will not attempt |
3139 | // to set a breakpoint with a type that is known not to be supported. |
3140 | LLDB_LOGF(log, "Software breakpoints are unsupported"); |
3141 | |
3142 | // So we will fall through and try a hardware breakpoint |
3143 | } |
3144 | |
3145 | // The process of setting a hardware breakpoint is much the same as above. |
3146 | // We check the supported boolean for this breakpoint type, and if it is |
3147 | // thought to be supported then we will try to set this breakpoint with a |
3148 | // hardware breakpoint. |
3149 | if (m_gdb_comm.SupportsGDBStoppointPacket(type: eBreakpointHardware)) { |
3150 | // Try to send off a hardware breakpoint packet ($Z1) |
3151 | uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( |
3152 | type: eBreakpointHardware, insert: true, addr, length: bp_op_size, interrupt_timeout: GetInterruptTimeout()); |
3153 | if (error_no == 0) { |
3154 | // The breakpoint was placed successfully |
3155 | bp_site->SetEnabled(true); |
3156 | bp_site->SetType(BreakpointSite::eHardware); |
3157 | return error; |
3158 | } |
3159 | |
3160 | // Check if the error was something other then an unsupported breakpoint |
3161 | // type |
3162 | if (m_gdb_comm.SupportsGDBStoppointPacket(type: eBreakpointHardware)) { |
3163 | // Unable to set this hardware breakpoint |
3164 | if (error_no != UINT8_MAX) |
3165 | error = Status::FromErrorStringWithFormat( |
3166 | format: "error: %d sending the hardware breakpoint request " |
3167 | "(hardware breakpoint resources might be exhausted or unavailable)", |
3168 | error_no); |
3169 | else |
3170 | error = Status::FromErrorString( |
3171 | str: "error sending the hardware breakpoint request " |
3172 | "(hardware breakpoint resources " |
3173 | "might be exhausted or unavailable)"); |
3174 | return error; |
3175 | } |
3176 | |
3177 | // We will reach here when the stub gives an unsupported response to a |
3178 | // hardware breakpoint |
3179 | LLDB_LOGF(log, "Hardware breakpoints are unsupported"); |
3180 | |
3181 | // Finally we will falling through to a #trap style breakpoint |
3182 | } |
3183 | |
3184 | // Don't fall through when hardware breakpoints were specifically requested |
3185 | if (bp_site->HardwareRequired()) { |
3186 | error = Status::FromErrorString(str: "hardware breakpoints are not supported"); |
3187 | return error; |
3188 | } |
3189 | |
3190 | // As a last resort we want to place a manual breakpoint. An instruction is |
3191 | // placed into the process memory using memory write packets. |
3192 | return EnableSoftwareBreakpoint(bp_site); |
3193 | } |
3194 | |
3195 | Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) { |
3196 | Status error; |
3197 | assert(bp_site != nullptr); |
3198 | addr_t addr = bp_site->GetLoadAddress(); |
3199 | user_id_t site_id = bp_site->GetID(); |
3200 | Log *log = GetLog(mask: GDBRLog::Breakpoints); |
3201 | LLDB_LOGF(log, |
3202 | "ProcessGDBRemote::DisableBreakpointSite (site_id = %"PRIu64 |
3203 | ") addr = 0x%8.8"PRIx64, |
3204 | site_id, (uint64_t)addr); |
3205 | |
3206 | if (bp_site->IsEnabled()) { |
3207 | const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); |
3208 | |
3209 | BreakpointSite::Type bp_type = bp_site->GetType(); |
3210 | switch (bp_type) { |
3211 | case BreakpointSite::eSoftware: |
3212 | error = DisableSoftwareBreakpoint(bp_site); |
3213 | break; |
3214 | |
3215 | case BreakpointSite::eHardware: |
3216 | if (m_gdb_comm.SendGDBStoppointTypePacket(type: eBreakpointHardware, insert: false, |
3217 | addr, length: bp_op_size, |
3218 | interrupt_timeout: GetInterruptTimeout())) |
3219 | error = Status::FromErrorString(str: "unknown error"); |
3220 | break; |
3221 | |
3222 | case BreakpointSite::eExternal: { |
3223 | if (m_gdb_comm.SendGDBStoppointTypePacket(type: eBreakpointSoftware, insert: false, |
3224 | addr, length: bp_op_size, |
3225 | interrupt_timeout: GetInterruptTimeout())) |
3226 | error = Status::FromErrorString(str: "unknown error"); |
3227 | } break; |
3228 | } |
3229 | if (error.Success()) |
3230 | bp_site->SetEnabled(false); |
3231 | } else { |
3232 | LLDB_LOGF(log, |
3233 | "ProcessGDBRemote::DisableBreakpointSite (site_id = %"PRIu64 |
3234 | ") addr = 0x%8.8"PRIx64 " -- SUCCESS (already disabled)", |
3235 | site_id, (uint64_t)addr); |
3236 | return error; |
3237 | } |
3238 | |
3239 | if (error.Success()) |
3240 | error = Status::FromErrorString(str: "unknown error"); |
3241 | return error; |
3242 | } |
3243 | |
3244 | // Pre-requisite: wp != NULL. |
3245 | static GDBStoppointType |
3246 | GetGDBStoppointType(const WatchpointResourceSP &wp_res_sp) { |
3247 | assert(wp_res_sp); |
3248 | bool read = wp_res_sp->WatchpointResourceRead(); |
3249 | bool write = wp_res_sp->WatchpointResourceWrite(); |
3250 | |
3251 | assert((read || write) && |
3252 | "WatchpointResource type is neither read nor write"); |
3253 | if (read && write) |
3254 | return eWatchpointReadWrite; |
3255 | else if (read) |
3256 | return eWatchpointRead; |
3257 | else |
3258 | return eWatchpointWrite; |
3259 | } |
3260 | |
3261 | Status ProcessGDBRemote::EnableWatchpoint(WatchpointSP wp_sp, bool notify) { |
3262 | Status error; |
3263 | if (!wp_sp) { |
3264 | error = Status::FromErrorString(str: "No watchpoint specified"); |
3265 | return error; |
3266 | } |
3267 | user_id_t watchID = wp_sp->GetID(); |
3268 | addr_t addr = wp_sp->GetLoadAddress(); |
3269 | Log *log(GetLog(mask: GDBRLog::Watchpoints)); |
3270 | LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %"PRIu64 ")", |
3271 | watchID); |
3272 | if (wp_sp->IsEnabled()) { |
3273 | LLDB_LOGF(log, |
3274 | "ProcessGDBRemote::EnableWatchpoint(watchID = %"PRIu64 |
3275 | ") addr = 0x%8.8"PRIx64 ": watchpoint already enabled.", |
3276 | watchID, (uint64_t)addr); |
3277 | return error; |
3278 | } |
3279 | |
3280 | bool read = wp_sp->WatchpointRead(); |
3281 | bool write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify(); |
3282 | size_t size = wp_sp->GetByteSize(); |
3283 | |
3284 | ArchSpec target_arch = GetTarget().GetArchitecture(); |
3285 | WatchpointHardwareFeature supported_features = |
3286 | m_gdb_comm.GetSupportedWatchpointTypes(); |
3287 | |
3288 | std::vector<WatchpointResourceSP> resources = |
3289 | WatchpointAlgorithms::AtomizeWatchpointRequest( |
3290 | addr, size, read, write, supported_features, arch&: target_arch); |
3291 | |
3292 | // LWP_TODO: Now that we know the WP Resources needed to implement this |
3293 | // Watchpoint, we need to look at currently allocated Resources in the |
3294 | // Process and if they match, or are within the same memory granule, or |
3295 | // overlapping memory ranges, then we need to combine them. e.g. one |
3296 | // Watchpoint watching 1 byte at 0x1002 and a second watchpoint watching 1 |
3297 | // byte at 0x1003, they must use the same hardware watchpoint register |
3298 | // (Resource) to watch them. |
3299 | |
3300 | // This may mean that an existing resource changes its type (read to |
3301 | // read+write) or address range it is watching, in which case the old |
3302 | // watchpoint needs to be disabled and the new Resource addr/size/type |
3303 | // watchpoint enabled. |
3304 | |
3305 | // If we modify a shared Resource to accomodate this newly added Watchpoint, |
3306 | // and we are unable to set all of the Resources for it in the inferior, we |
3307 | // will return an error for this Watchpoint and the shared Resource should |
3308 | // be restored. e.g. this Watchpoint requires three Resources, one which |
3309 | // is shared with another Watchpoint. We extend the shared Resouce to |
3310 | // handle both Watchpoints and we try to set two new ones. But if we don't |
3311 | // have sufficient watchpoint register for all 3, we need to show an error |
3312 | // for creating this Watchpoint and we should reset the shared Resource to |
3313 | // its original configuration because it is no longer shared. |
3314 | |
3315 | bool set_all_resources = true; |
3316 | std::vector<WatchpointResourceSP> succesfully_set_resources; |
3317 | for (const auto &wp_res_sp : resources) { |
3318 | addr_t addr = wp_res_sp->GetLoadAddress(); |
3319 | size_t size = wp_res_sp->GetByteSize(); |
3320 | GDBStoppointType type = GetGDBStoppointType(wp_res_sp); |
3321 | if (!m_gdb_comm.SupportsGDBStoppointPacket(type) || |
3322 | m_gdb_comm.SendGDBStoppointTypePacket(type, insert: true, addr, length: size, |
3323 | interrupt_timeout: GetInterruptTimeout())) { |
3324 | set_all_resources = false; |
3325 | break; |
3326 | } else { |
3327 | succesfully_set_resources.push_back(x: wp_res_sp); |
3328 | } |
3329 | } |
3330 | if (set_all_resources) { |
3331 | wp_sp->SetEnabled(enabled: true, notify); |
3332 | for (const auto &wp_res_sp : resources) { |
3333 | // LWP_TODO: If we expanded/reused an existing Resource, |
3334 | // it's already in the WatchpointResourceList. |
3335 | wp_res_sp->AddConstituent(constituent: wp_sp); |
3336 | m_watchpoint_resource_list.Add(site_sp: wp_res_sp); |
3337 | } |
3338 | return error; |
3339 | } else { |
3340 | // We failed to allocate one of the resources. Unset all |
3341 | // of the new resources we did successfully set in the |
3342 | // process. |
3343 | for (const auto &wp_res_sp : succesfully_set_resources) { |
3344 | addr_t addr = wp_res_sp->GetLoadAddress(); |
3345 | size_t size = wp_res_sp->GetByteSize(); |
3346 | GDBStoppointType type = GetGDBStoppointType(wp_res_sp); |
3347 | m_gdb_comm.SendGDBStoppointTypePacket(type, insert: false, addr, length: size, |
3348 | interrupt_timeout: GetInterruptTimeout()); |
3349 | } |
3350 | error = Status::FromErrorString( |
3351 | str: "Setting one of the watchpoint resources failed"); |
3352 | } |
3353 | return error; |
3354 | } |
3355 | |
3356 | Status ProcessGDBRemote::DisableWatchpoint(WatchpointSP wp_sp, bool notify) { |
3357 | Status error; |
3358 | if (!wp_sp) { |
3359 | error = Status::FromErrorString(str: "Watchpoint argument was NULL."); |
3360 | return error; |
3361 | } |
3362 | |
3363 | user_id_t watchID = wp_sp->GetID(); |
3364 | |
3365 | Log *log(GetLog(mask: GDBRLog::Watchpoints)); |
3366 | |
3367 | addr_t addr = wp_sp->GetLoadAddress(); |
3368 | |
3369 | LLDB_LOGF(log, |
3370 | "ProcessGDBRemote::DisableWatchpoint (watchID = %"PRIu64 |
3371 | ") addr = 0x%8.8"PRIx64, |
3372 | watchID, (uint64_t)addr); |
3373 | |
3374 | if (!wp_sp->IsEnabled()) { |
3375 | LLDB_LOGF(log, |
3376 | "ProcessGDBRemote::DisableWatchpoint (watchID = %"PRIu64 |
3377 | ") addr = 0x%8.8"PRIx64 " -- SUCCESS (already disabled)", |
3378 | watchID, (uint64_t)addr); |
3379 | // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling |
3380 | // attempt might come from the user-supplied actions, we'll route it in |
3381 | // order for the watchpoint object to intelligently process this action. |
3382 | wp_sp->SetEnabled(enabled: false, notify); |
3383 | return error; |
3384 | } |
3385 | |
3386 | if (wp_sp->IsHardware()) { |
3387 | bool disabled_all = true; |
3388 | |
3389 | std::vector<WatchpointResourceSP> unused_resources; |
3390 | for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) { |
3391 | if (wp_res_sp->ConstituentsContains(wp_sp)) { |
3392 | GDBStoppointType type = GetGDBStoppointType(wp_res_sp); |
3393 | addr_t addr = wp_res_sp->GetLoadAddress(); |
3394 | size_t size = wp_res_sp->GetByteSize(); |
3395 | if (m_gdb_comm.SendGDBStoppointTypePacket(type, insert: false, addr, length: size, |
3396 | interrupt_timeout: GetInterruptTimeout())) { |
3397 | disabled_all = false; |
3398 | } else { |
3399 | wp_res_sp->RemoveConstituent(constituent&: wp_sp); |
3400 | if (wp_res_sp->GetNumberOfConstituents() == 0) |
3401 | unused_resources.push_back(x: wp_res_sp); |
3402 | } |
3403 | } |
3404 | } |
3405 | for (auto &wp_res_sp : unused_resources) |
3406 | m_watchpoint_resource_list.Remove(site_id: wp_res_sp->GetID()); |
3407 | |
3408 | wp_sp->SetEnabled(enabled: false, notify); |
3409 | if (!disabled_all) |
3410 | error = Status::FromErrorString( |
3411 | str: "Failure disabling one of the watchpoint locations"); |
3412 | } |
3413 | return error; |
3414 | } |
3415 | |
3416 | void ProcessGDBRemote::Clear() { |
3417 | m_thread_list_real.Clear(); |
3418 | m_thread_list.Clear(); |
3419 | } |
3420 | |
3421 | Status ProcessGDBRemote::DoSignal(int signo) { |
3422 | Status error; |
3423 | Log *log = GetLog(mask: GDBRLog::Process); |
3424 | LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo); |
3425 | |
3426 | if (!m_gdb_comm.SendAsyncSignal(signo, interrupt_timeout: GetInterruptTimeout())) |
3427 | error = |
3428 | Status::FromErrorStringWithFormat(format: "failed to send signal %i", signo); |
3429 | return error; |
3430 | } |
3431 | |
3432 | Status |
3433 | ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) { |
3434 | // Make sure we aren't already connected? |
3435 | if (m_gdb_comm.IsConnected()) |
3436 | return Status(); |
3437 | |
3438 | PlatformSP platform_sp(GetTarget().GetPlatform()); |
3439 | if (platform_sp && !platform_sp->IsHost()) |
3440 | return Status::FromErrorString(str: "Lost debug server connection"); |
3441 | |
3442 | auto error = LaunchAndConnectToDebugserver(process_info); |
3443 | if (error.Fail()) { |
3444 | const char *error_string = error.AsCString(); |
3445 | if (error_string == nullptr) |
3446 | error_string = "unable to launch "DEBUGSERVER_BASENAME; |
3447 | } |
3448 | return error; |
3449 | } |
3450 | #if !defined(_WIN32) |
3451 | #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1 |
3452 | #endif |
3453 | |
3454 | #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION |
3455 | static bool SetCloexecFlag(int fd) { |
3456 | #if defined(FD_CLOEXEC) |
3457 | int flags = ::fcntl(fd: fd, F_GETFD); |
3458 | if (flags == -1) |
3459 | return false; |
3460 | return (::fcntl(fd: fd, F_SETFD, flags | FD_CLOEXEC) == 0); |
3461 | #else |
3462 | return false; |
3463 | #endif |
3464 | } |
3465 | #endif |
3466 | |
3467 | Status ProcessGDBRemote::LaunchAndConnectToDebugserver( |
3468 | const ProcessInfo &process_info) { |
3469 | using namespace std::placeholders; // For _1, _2, etc. |
3470 | |
3471 | Status error; |
3472 | if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) { |
3473 | // If we locate debugserver, keep that located version around |
3474 | static FileSpec g_debugserver_file_spec; |
3475 | |
3476 | ProcessLaunchInfo debugserver_launch_info; |
3477 | // Make debugserver run in its own session so signals generated by special |
3478 | // terminal key sequences (^C) don't affect debugserver. |
3479 | debugserver_launch_info.SetLaunchInSeparateProcessGroup(true); |
3480 | |
3481 | const std::weak_ptr<ProcessGDBRemote> this_wp = |
3482 | std::static_pointer_cast<ProcessGDBRemote>(r: shared_from_this()); |
3483 | debugserver_launch_info.SetMonitorProcessCallback( |
3484 | std::bind(f&: MonitorDebugserverProcess, args: this_wp, args: _1, args: _2, args: _3)); |
3485 | debugserver_launch_info.SetUserID(process_info.GetUserID()); |
3486 | |
3487 | #if defined(__APPLE__) |
3488 | // On macOS 11, we need to support x86_64 applications translated to |
3489 | // arm64. We check whether a binary is translated and spawn the correct |
3490 | // debugserver accordingly. |
3491 | int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, |
3492 | static_cast<int>(process_info.GetProcessID()) }; |
3493 | struct kinfo_proc processInfo; |
3494 | size_t bufsize = sizeof(processInfo); |
3495 | if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo, |
3496 | &bufsize, NULL, 0) == 0 && bufsize > 0) { |
3497 | if (processInfo.kp_proc.p_flag & P_TRANSLATED) { |
3498 | FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver"); |
3499 | debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false); |
3500 | } |
3501 | } |
3502 | #endif |
3503 | |
3504 | shared_fd_t communication_fd = SharedSocket::kInvalidFD; |
3505 | #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION |
3506 | // Use a socketpair on non-Windows systems for security and performance |
3507 | // reasons. |
3508 | int sockets[2]; /* the pair of socket descriptors */ |
3509 | if (socketpair(AF_UNIX, SOCK_STREAM, protocol: 0, fds: sockets) == -1) { |
3510 | error = Status::FromErrno(); |
3511 | return error; |
3512 | } |
3513 | |
3514 | int our_socket = sockets[0]; |
3515 | int gdb_socket = sockets[1]; |
3516 | auto cleanup_our = llvm::make_scope_exit(F: [&]() { close(fd: our_socket); }); |
3517 | auto cleanup_gdb = llvm::make_scope_exit(F: [&]() { close(fd: gdb_socket); }); |
3518 | |
3519 | // Don't let any child processes inherit our communication socket |
3520 | SetCloexecFlag(our_socket); |
3521 | communication_fd = gdb_socket; |
3522 | #endif |
3523 | |
3524 | error = m_gdb_comm.StartDebugserverProcess( |
3525 | url: nullptr, platform: GetTarget().GetPlatform().get(), launch_info&: debugserver_launch_info, |
3526 | port: nullptr, inferior_args: nullptr, pass_comm_fd: communication_fd); |
3527 | |
3528 | if (error.Success()) |
3529 | m_debugserver_pid = debugserver_launch_info.GetProcessID(); |
3530 | else |
3531 | m_debugserver_pid = LLDB_INVALID_PROCESS_ID; |
3532 | |
3533 | if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { |
3534 | #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION |
3535 | // Our process spawned correctly, we can now set our connection to use |
3536 | // our end of the socket pair |
3537 | cleanup_our.release(); |
3538 | m_gdb_comm.SetConnection( |
3539 | std::make_unique<ConnectionFileDescriptor>(args&: our_socket, args: true)); |
3540 | #endif |
3541 | StartAsyncThread(); |
3542 | } |
3543 | |
3544 | if (error.Fail()) { |
3545 | Log *log = GetLog(mask: GDBRLog::Process); |
3546 | |
3547 | LLDB_LOGF(log, "failed to start debugserver process: %s", |
3548 | error.AsCString()); |
3549 | return error; |
3550 | } |
3551 | |
3552 | if (m_gdb_comm.IsConnected()) { |
3553 | // Finish the connection process by doing the handshake without |
3554 | // connecting (send NULL URL) |
3555 | error = ConnectToDebugserver(connect_url: ""); |
3556 | } else { |
3557 | error = Status::FromErrorString(str: "connection failed"); |
3558 | } |
3559 | } |
3560 | return error; |
3561 | } |
3562 | |
3563 | void ProcessGDBRemote::MonitorDebugserverProcess( |
3564 | std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid, |
3565 | int signo, // Zero for no signal |
3566 | int exit_status // Exit value of process if signal is zero |
3567 | ) { |
3568 | // "debugserver_pid" argument passed in is the process ID for debugserver |
3569 | // that we are tracking... |
3570 | Log *log = GetLog(mask: GDBRLog::Process); |
3571 | |
3572 | LLDB_LOGF(log, |
3573 | "ProcessGDBRemote::%s(process_wp, pid=%"PRIu64 |
3574 | ", signo=%i (0x%x), exit_status=%i)", |
3575 | __FUNCTION__, debugserver_pid, signo, signo, exit_status); |
3576 | |
3577 | std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock(); |
3578 | LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__, |
3579 | static_cast<void *>(process_sp.get())); |
3580 | if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid) |
3581 | return; |
3582 | |
3583 | // Sleep for a half a second to make sure our inferior process has time to |
3584 | // set its exit status before we set it incorrectly when both the debugserver |
3585 | // and the inferior process shut down. |
3586 | std::this_thread::sleep_for(rtime: std::chrono::milliseconds(500)); |
3587 | |
3588 | // If our process hasn't yet exited, debugserver might have died. If the |
3589 | // process did exit, then we are reaping it. |
3590 | const StateType state = process_sp->GetState(); |
3591 | |
3592 | if (state != eStateInvalid && state != eStateUnloaded && |
3593 | state != eStateExited && state != eStateDetached) { |
3594 | StreamString stream; |
3595 | if (signo == 0) |
3596 | stream.Format(DEBUGSERVER_BASENAME " died with an exit status of {0:x8}", |
3597 | args&: exit_status); |
3598 | else { |
3599 | llvm::StringRef signal_name = |
3600 | process_sp->GetUnixSignals()->GetSignalAsStringRef(signo); |
3601 | const char *format_str = DEBUGSERVER_BASENAME " died with signal {0}"; |
3602 | if (!signal_name.empty()) |
3603 | stream.Format(format: format_str, args&: signal_name); |
3604 | else |
3605 | stream.Format(format: format_str, args&: signo); |
3606 | } |
3607 | process_sp->SetExitStatus(exit_status: -1, exit_string: stream.GetString()); |
3608 | } |
3609 | // Debugserver has exited we need to let our ProcessGDBRemote know that it no |
3610 | // longer has a debugserver instance |
3611 | process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; |
3612 | } |
3613 | |
3614 | void ProcessGDBRemote::KillDebugserverProcess() { |
3615 | m_gdb_comm.Disconnect(); |
3616 | if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { |
3617 | Host::Kill(pid: m_debugserver_pid, SIGINT); |
3618 | m_debugserver_pid = LLDB_INVALID_PROCESS_ID; |
3619 | } |
3620 | } |
3621 | |
3622 | void ProcessGDBRemote::Initialize() { |
3623 | static llvm::once_flag g_once_flag; |
3624 | |
3625 | llvm::call_once(flag&: g_once_flag, F: []() { |
3626 | PluginManager::RegisterPlugin(name: GetPluginNameStatic(), |
3627 | description: GetPluginDescriptionStatic(), create_callback: CreateInstance, |
3628 | debugger_init_callback: DebuggerInitialize); |
3629 | }); |
3630 | } |
3631 | |
3632 | void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) { |
3633 | if (!PluginManager::GetSettingForProcessPlugin( |
3634 | debugger, setting_name: PluginProperties::GetSettingName())) { |
3635 | const bool is_global_setting = true; |
3636 | PluginManager::CreateSettingForProcessPlugin( |
3637 | debugger, properties_sp: GetGlobalPluginProperties().GetValueProperties(), |
3638 | description: "Properties for the gdb-remote process plug-in.", is_global_property: is_global_setting); |
3639 | } |
3640 | } |
3641 | |
3642 | bool ProcessGDBRemote::StartAsyncThread() { |
3643 | Log *log = GetLog(mask: GDBRLog::Process); |
3644 | |
3645 | LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); |
3646 | |
3647 | std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); |
3648 | if (!m_async_thread.IsJoinable()) { |
3649 | // Create a thread that watches our internal state and controls which |
3650 | // events make it to clients (into the DCProcess event queue). |
3651 | |
3652 | llvm::Expected<HostThread> async_thread = |
3653 | ThreadLauncher::LaunchThread(name: "<lldb.process.gdb-remote.async>", thread_function: [this] { |
3654 | return ProcessGDBRemote::AsyncThread(); |
3655 | }); |
3656 | if (!async_thread) { |
3657 | LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(), |
3658 | "failed to launch host thread: {0}"); |
3659 | return false; |
3660 | } |
3661 | m_async_thread = *async_thread; |
3662 | } else |
3663 | LLDB_LOGF(log, |
3664 | "ProcessGDBRemote::%s () - Called when Async thread was " |
3665 | "already running.", |
3666 | __FUNCTION__); |
3667 | |
3668 | return m_async_thread.IsJoinable(); |
3669 | } |
3670 | |
3671 | void ProcessGDBRemote::StopAsyncThread() { |
3672 | Log *log = GetLog(mask: GDBRLog::Process); |
3673 | |
3674 | LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); |
3675 | |
3676 | std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex); |
3677 | if (m_async_thread.IsJoinable()) { |
3678 | m_async_broadcaster.BroadcastEvent(event_type: eBroadcastBitAsyncThreadShouldExit); |
3679 | |
3680 | // This will shut down the async thread. |
3681 | m_gdb_comm.Disconnect(); // Disconnect from the debug server. |
3682 | |
3683 | // Stop the stdio thread |
3684 | m_async_thread.Join(result: nullptr); |
3685 | m_async_thread.Reset(); |
3686 | } else |
3687 | LLDB_LOGF( |
3688 | log, |
3689 | "ProcessGDBRemote::%s () - Called when Async thread was not running.", |
3690 | __FUNCTION__); |
3691 | } |
3692 | |
3693 | thread_result_t ProcessGDBRemote::AsyncThread() { |
3694 | Log *log = GetLog(mask: GDBRLog::Process); |
3695 | LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %"PRIu64 ") thread starting...", |
3696 | __FUNCTION__, GetID()); |
3697 | |
3698 | EventSP event_sp; |
3699 | |
3700 | // We need to ignore any packets that come in after we have |
3701 | // have decided the process has exited. There are some |
3702 | // situations, for instance when we try to interrupt a running |
3703 | // process and the interrupt fails, where another packet might |
3704 | // get delivered after we've decided to give up on the process. |
3705 | // But once we've decided we are done with the process we will |
3706 | // not be in a state to do anything useful with new packets. |
3707 | // So it is safer to simply ignore any remaining packets by |
3708 | // explicitly checking for eStateExited before reentering the |
3709 | // fetch loop. |
3710 | |
3711 | bool done = false; |
3712 | while (!done && GetPrivateState() != eStateExited) { |
3713 | LLDB_LOGF(log, |
3714 | "ProcessGDBRemote::%s(pid = %"PRIu64 |
3715 | ") listener.WaitForEvent (NULL, event_sp)...", |
3716 | __FUNCTION__, GetID()); |
3717 | |
3718 | if (m_async_listener_sp->GetEvent(event_sp, timeout: std::nullopt)) { |
3719 | const uint32_t event_type = event_sp->GetType(); |
3720 | if (event_sp->BroadcasterIs(broadcaster: &m_async_broadcaster)) { |
3721 | LLDB_LOGF(log, |
3722 | "ProcessGDBRemote::%s(pid = %"PRIu64 |
3723 | ") Got an event of type: %d...", |
3724 | __FUNCTION__, GetID(), event_type); |
3725 | |
3726 | switch (event_type) { |
3727 | case eBroadcastBitAsyncContinue: { |
3728 | const EventDataBytes *continue_packet = |
3729 | EventDataBytes::GetEventDataFromEvent(event_ptr: event_sp.get()); |
3730 | |
3731 | if (continue_packet) { |
3732 | const char *continue_cstr = |
3733 | (const char *)continue_packet->GetBytes(); |
3734 | const size_t continue_cstr_len = continue_packet->GetByteSize(); |
3735 | LLDB_LOGF(log, |
3736 | "ProcessGDBRemote::%s(pid = %"PRIu64 |
3737 | ") got eBroadcastBitAsyncContinue: %s", |
3738 | __FUNCTION__, GetID(), continue_cstr); |
3739 | |
3740 | if (::strstr(haystack: continue_cstr, needle: "vAttach") == nullptr) |
3741 | SetPrivateState(eStateRunning); |
3742 | StringExtractorGDBRemote response; |
3743 | |
3744 | StateType stop_state = |
3745 | GetGDBRemote().SendContinuePacketAndWaitForResponse( |
3746 | delegate&: *this, signals: *GetUnixSignals(), |
3747 | payload: llvm::StringRef(continue_cstr, continue_cstr_len), |
3748 | interrupt_timeout: GetInterruptTimeout(), response); |
3749 | |
3750 | // We need to immediately clear the thread ID list so we are sure |
3751 | // to get a valid list of threads. The thread ID list might be |
3752 | // contained within the "response", or the stop reply packet that |
3753 | // caused the stop. So clear it now before we give the stop reply |
3754 | // packet to the process using the |
3755 | // SetLastStopPacket()... |
3756 | ClearThreadIDList(); |
3757 | |
3758 | switch (stop_state) { |
3759 | case eStateStopped: |
3760 | case eStateCrashed: |
3761 | case eStateSuspended: |
3762 | SetLastStopPacket(response); |
3763 | SetPrivateState(stop_state); |
3764 | break; |
3765 | |
3766 | case eStateExited: { |
3767 | SetLastStopPacket(response); |
3768 | ClearThreadIDList(); |
3769 | response.SetFilePos(1); |
3770 | |
3771 | int exit_status = response.GetHexU8(); |
3772 | std::string desc_string; |
3773 | if (response.GetBytesLeft() > 0 && response.GetChar(fail_value: '-') == ';') { |
3774 | llvm::StringRef desc_str; |
3775 | llvm::StringRef desc_token; |
3776 | while (response.GetNameColonValue(name&: desc_token, value&: desc_str)) { |
3777 | if (desc_token != "description") |
3778 | continue; |
3779 | StringExtractor extractor(desc_str); |
3780 | extractor.GetHexByteString(str&: desc_string); |
3781 | } |
3782 | } |
3783 | SetExitStatus(exit_status, exit_string: desc_string.c_str()); |
3784 | done = true; |
3785 | break; |
3786 | } |
3787 | case eStateInvalid: { |
3788 | // Check to see if we were trying to attach and if we got back |
3789 | // the "E87" error code from debugserver -- this indicates that |
3790 | // the process is not debuggable. Return a slightly more |
3791 | // helpful error message about why the attach failed. |
3792 | if (::strstr(haystack: continue_cstr, needle: "vAttach") != nullptr && |
3793 | response.GetError() == 0x87) { |
3794 | SetExitStatus(exit_status: -1, exit_string: "cannot attach to process due to " |
3795 | "System Integrity Protection"); |
3796 | } else if (::strstr(haystack: continue_cstr, needle: "vAttach") != nullptr && |
3797 | response.GetStatus().Fail()) { |
3798 | SetExitStatus(exit_status: -1, exit_string: response.GetStatus().AsCString()); |
3799 | } else { |
3800 | SetExitStatus(exit_status: -1, exit_string: "lost connection"); |
3801 | } |
3802 | done = true; |
3803 | break; |
3804 | } |
3805 | |
3806 | default: |
3807 | SetPrivateState(stop_state); |
3808 | break; |
3809 | } // switch(stop_state) |
3810 | } // if (continue_packet) |
3811 | } // case eBroadcastBitAsyncContinue |
3812 | break; |
3813 | |
3814 | case eBroadcastBitAsyncThreadShouldExit: |
3815 | LLDB_LOGF(log, |
3816 | "ProcessGDBRemote::%s(pid = %"PRIu64 |
3817 | ") got eBroadcastBitAsyncThreadShouldExit...", |
3818 | __FUNCTION__, GetID()); |
3819 | done = true; |
3820 | break; |
3821 | |
3822 | default: |
3823 | LLDB_LOGF(log, |
3824 | "ProcessGDBRemote::%s(pid = %"PRIu64 |
3825 | ") got unknown event 0x%8.8x", |
3826 | __FUNCTION__, GetID(), event_type); |
3827 | done = true; |
3828 | break; |
3829 | } |
3830 | } |
3831 | } else { |
3832 | LLDB_LOGF(log, |
3833 | "ProcessGDBRemote::%s(pid = %"PRIu64 |
3834 | ") listener.WaitForEvent (NULL, event_sp) => false", |
3835 | __FUNCTION__, GetID()); |
3836 | done = true; |
3837 | } |
3838 | } |
3839 | |
3840 | LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %"PRIu64 ") thread exiting...", |
3841 | __FUNCTION__, GetID()); |
3842 | |
3843 | return {}; |
3844 | } |
3845 | |
3846 | // uint32_t |
3847 | // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList |
3848 | // &matches, std::vector<lldb::pid_t> &pids) |
3849 | //{ |
3850 | // // If we are planning to launch the debugserver remotely, then we need to |
3851 | // fire up a debugserver |
3852 | // // process and ask it for the list of processes. But if we are local, we |
3853 | // can let the Host do it. |
3854 | // if (m_local_debugserver) |
3855 | // { |
3856 | // return Host::ListProcessesMatchingName (name, matches, pids); |
3857 | // } |
3858 | // else |
3859 | // { |
3860 | // // FIXME: Implement talking to the remote debugserver. |
3861 | // return 0; |
3862 | // } |
3863 | // |
3864 | //} |
3865 | // |
3866 | bool ProcessGDBRemote::NewThreadNotifyBreakpointHit( |
3867 | void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, |
3868 | lldb::user_id_t break_loc_id) { |
3869 | // I don't think I have to do anything here, just make sure I notice the new |
3870 | // thread when it starts to |
3871 | // run so I can stop it if that's what I want to do. |
3872 | Log *log = GetLog(mask: LLDBLog::Step); |
3873 | LLDB_LOGF(log, "Hit New Thread Notification breakpoint."); |
3874 | return false; |
3875 | } |
3876 | |
3877 | Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() { |
3878 | Log *log = GetLog(mask: GDBRLog::Process); |
3879 | LLDB_LOG(log, "Check if need to update ignored signals"); |
3880 | |
3881 | // QPassSignals package is not supported by the server, there is no way we |
3882 | // can ignore any signals on server side. |
3883 | if (!m_gdb_comm.GetQPassSignalsSupported()) |
3884 | return Status(); |
3885 | |
3886 | // No signals, nothing to send. |
3887 | if (m_unix_signals_sp == nullptr) |
3888 | return Status(); |
3889 | |
3890 | // Signals' version hasn't changed, no need to send anything. |
3891 | uint64_t new_signals_version = m_unix_signals_sp->GetVersion(); |
3892 | if (new_signals_version == m_last_signals_version) { |
3893 | LLDB_LOG(log, "Signals' version hasn't changed. version={0}", |
3894 | m_last_signals_version); |
3895 | return Status(); |
3896 | } |
3897 | |
3898 | auto signals_to_ignore = |
3899 | m_unix_signals_sp->GetFilteredSignals(should_suppress: false, should_stop: false, should_notify: false); |
3900 | Status error = m_gdb_comm.SendSignalsToIgnore(signals: signals_to_ignore); |
3901 | |
3902 | LLDB_LOG(log, |
3903 | "Signals' version changed. old version={0}, new version={1}, " |
3904 | "signals ignored={2}, update result={3}", |
3905 | m_last_signals_version, new_signals_version, |
3906 | signals_to_ignore.size(), error); |
3907 | |
3908 | if (error.Success()) |
3909 | m_last_signals_version = new_signals_version; |
3910 | |
3911 | return error; |
3912 | } |
3913 | |
3914 | bool ProcessGDBRemote::StartNoticingNewThreads() { |
3915 | Log *log = GetLog(mask: LLDBLog::Step); |
3916 | if (m_thread_create_bp_sp) { |
3917 | if (log && log->GetVerbose()) |
3918 | LLDB_LOGF(log, "Enabled noticing new thread breakpoint."); |
3919 | m_thread_create_bp_sp->SetEnabled(true); |
3920 | } else { |
3921 | PlatformSP platform_sp(GetTarget().GetPlatform()); |
3922 | if (platform_sp) { |
3923 | m_thread_create_bp_sp = |
3924 | platform_sp->SetThreadCreationBreakpoint(GetTarget()); |
3925 | if (m_thread_create_bp_sp) { |
3926 | if (log && log->GetVerbose()) |
3927 | LLDB_LOGF( |
3928 | log, "Successfully created new thread notification breakpoint %i", |
3929 | m_thread_create_bp_sp->GetID()); |
3930 | m_thread_create_bp_sp->SetCallback( |
3931 | callback: ProcessGDBRemote::NewThreadNotifyBreakpointHit, baton: this, is_synchronous: true); |
3932 | } else { |
3933 | LLDB_LOGF(log, "Failed to create new thread notification breakpoint."); |
3934 | } |
3935 | } |
3936 | } |
3937 | return m_thread_create_bp_sp.get() != nullptr; |
3938 | } |
3939 | |
3940 | bool ProcessGDBRemote::StopNoticingNewThreads() { |
3941 | Log *log = GetLog(mask: LLDBLog::Step); |
3942 | if (log && log->GetVerbose()) |
3943 | LLDB_LOGF(log, "Disabling new thread notification breakpoint."); |
3944 | |
3945 | if (m_thread_create_bp_sp) |
3946 | m_thread_create_bp_sp->SetEnabled(false); |
3947 | |
3948 | return true; |
3949 | } |
3950 | |
3951 | DynamicLoader *ProcessGDBRemote::GetDynamicLoader() { |
3952 | if (m_dyld_up.get() == nullptr) |
3953 | m_dyld_up.reset(p: DynamicLoader::FindPlugin(process: this, plugin_name: "")); |
3954 | return m_dyld_up.get(); |
3955 | } |
3956 | |
3957 | Status ProcessGDBRemote::SendEventData(const char *data) { |
3958 | int return_value; |
3959 | bool was_supported; |
3960 | |
3961 | Status error; |
3962 | |
3963 | return_value = m_gdb_comm.SendLaunchEventDataPacket(data, was_supported: &was_supported); |
3964 | if (return_value != 0) { |
3965 | if (!was_supported) |
3966 | error = Status::FromErrorString( |
3967 | str: "Sending events is not supported for this process."); |
3968 | else |
3969 | error = Status::FromErrorStringWithFormat(format: "Error sending event data: %d.", |
3970 | return_value); |
3971 | } |
3972 | return error; |
3973 | } |
3974 | |
3975 | DataExtractor ProcessGDBRemote::GetAuxvData() { |
3976 | DataBufferSP buf; |
3977 | if (m_gdb_comm.GetQXferAuxvReadSupported()) { |
3978 | llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature(object: "auxv", annex: ""); |
3979 | if (response) |
3980 | buf = std::make_shared<DataBufferHeap>(args: response->c_str(), |
3981 | args: response->length()); |
3982 | else |
3983 | LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}"); |
3984 | } |
3985 | return DataExtractor(buf, GetByteOrder(), GetAddressByteSize()); |
3986 | } |
3987 | |
3988 | StructuredData::ObjectSP |
3989 | ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) { |
3990 | StructuredData::ObjectSP object_sp; |
3991 | |
3992 | if (m_gdb_comm.GetThreadExtendedInfoSupported()) { |
3993 | StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); |
3994 | SystemRuntime *runtime = GetSystemRuntime(); |
3995 | if (runtime) { |
3996 | runtime->AddThreadExtendedInfoPacketHints(dict: args_dict); |
3997 | } |
3998 | args_dict->GetAsDictionary()->AddIntegerItem(key: "thread", value: tid); |
3999 | |
4000 | StreamString packet; |
4001 | packet << "jThreadExtendedInfo:"; |
4002 | args_dict->Dump(s&: packet, pretty_print: false); |
4003 | |
4004 | // FIXME the final character of a JSON dictionary, '}', is the escape |
4005 | // character in gdb-remote binary mode. lldb currently doesn't escape |
4006 | // these characters in its packet output -- so we add the quoted version of |
4007 | // the } character here manually in case we talk to a debugserver which un- |
4008 | // escapes the characters at packet read time. |
4009 | packet << (char)(0x7d ^ 0x20); |
4010 | |
4011 | StringExtractorGDBRemote response; |
4012 | response.SetResponseValidatorToJSON(); |
4013 | if (m_gdb_comm.SendPacketAndWaitForResponse(payload: packet.GetString(), response) == |
4014 | GDBRemoteCommunication::PacketResult::Success) { |
4015 | StringExtractorGDBRemote::ResponseType response_type = |
4016 | response.GetResponseType(); |
4017 | if (response_type == StringExtractorGDBRemote::eResponse) { |
4018 | if (!response.Empty()) { |
4019 | object_sp = StructuredData::ParseJSON(json_text: response.GetStringRef()); |
4020 | } |
4021 | } |
4022 | } |
4023 | } |
4024 | return object_sp; |
4025 | } |
4026 | |
4027 | StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( |
4028 | lldb::addr_t image_list_address, lldb::addr_t image_count) { |
4029 | |
4030 | StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); |
4031 | args_dict->GetAsDictionary()->AddIntegerItem(key: "image_list_address", |
4032 | value: image_list_address); |
4033 | args_dict->GetAsDictionary()->AddIntegerItem(key: "image_count", value: image_count); |
4034 | |
4035 | return GetLoadedDynamicLibrariesInfos_sender(args: args_dict); |
4036 | } |
4037 | |
4038 | StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() { |
4039 | StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); |
4040 | |
4041 | args_dict->GetAsDictionary()->AddBooleanItem(key: "fetch_all_solibs", value: true); |
4042 | |
4043 | return GetLoadedDynamicLibrariesInfos_sender(args: args_dict); |
4044 | } |
4045 | |
4046 | StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( |
4047 | const std::vector<lldb::addr_t> &load_addresses) { |
4048 | StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); |
4049 | StructuredData::ArraySP addresses(new StructuredData::Array); |
4050 | |
4051 | for (auto addr : load_addresses) |
4052 | addresses->AddIntegerItem(value: addr); |
4053 | |
4054 | args_dict->GetAsDictionary()->AddItem(key: "solib_addresses", value_sp: addresses); |
4055 | |
4056 | return GetLoadedDynamicLibrariesInfos_sender(args: args_dict); |
4057 | } |
4058 | |
4059 | StructuredData::ObjectSP |
4060 | ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender( |
4061 | StructuredData::ObjectSP args_dict) { |
4062 | StructuredData::ObjectSP object_sp; |
4063 | |
4064 | if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) { |
4065 | // Scope for the scoped timeout object |
4066 | GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm, |
4067 | std::chrono::seconds(10)); |
4068 | |
4069 | StreamString packet; |
4070 | packet << "jGetLoadedDynamicLibrariesInfos:"; |
4071 | args_dict->Dump(s&: packet, pretty_print: false); |
4072 | |
4073 | // FIXME the final character of a JSON dictionary, '}', is the escape |
4074 | // character in gdb-remote binary mode. lldb currently doesn't escape |
4075 | // these characters in its packet output -- so we add the quoted version of |
4076 | // the } character here manually in case we talk to a debugserver which un- |
4077 | // escapes the characters at packet read time. |
4078 | packet << (char)(0x7d ^ 0x20); |
4079 | |
4080 | StringExtractorGDBRemote response; |
4081 | response.SetResponseValidatorToJSON(); |
4082 | if (m_gdb_comm.SendPacketAndWaitForResponse(payload: packet.GetString(), response) == |
4083 | GDBRemoteCommunication::PacketResult::Success) { |
4084 | StringExtractorGDBRemote::ResponseType response_type = |
4085 | response.GetResponseType(); |
4086 | if (response_type == StringExtractorGDBRemote::eResponse) { |
4087 | if (!response.Empty()) { |
4088 | object_sp = StructuredData::ParseJSON(json_text: response.GetStringRef()); |
4089 | } |
4090 | } |
4091 | } |
4092 | } |
4093 | return object_sp; |
4094 | } |
4095 | |
4096 | StructuredData::ObjectSP ProcessGDBRemote::GetDynamicLoaderProcessState() { |
4097 | StructuredData::ObjectSP object_sp; |
4098 | StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); |
4099 | |
4100 | if (m_gdb_comm.GetDynamicLoaderProcessStateSupported()) { |
4101 | StringExtractorGDBRemote response; |
4102 | response.SetResponseValidatorToJSON(); |
4103 | if (m_gdb_comm.SendPacketAndWaitForResponse(payload: "jGetDyldProcessState", |
4104 | response) == |
4105 | GDBRemoteCommunication::PacketResult::Success) { |
4106 | StringExtractorGDBRemote::ResponseType response_type = |
4107 | response.GetResponseType(); |
4108 | if (response_type == StringExtractorGDBRemote::eResponse) { |
4109 | if (!response.Empty()) { |
4110 | object_sp = StructuredData::ParseJSON(json_text: response.GetStringRef()); |
4111 | } |
4112 | } |
4113 | } |
4114 | } |
4115 | return object_sp; |
4116 | } |
4117 | |
4118 | StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() { |
4119 | StructuredData::ObjectSP object_sp; |
4120 | StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); |
4121 | |
4122 | if (m_gdb_comm.GetSharedCacheInfoSupported()) { |
4123 | StreamString packet; |
4124 | packet << "jGetSharedCacheInfo:"; |
4125 | args_dict->Dump(s&: packet, pretty_print: false); |
4126 | |
4127 | // FIXME the final character of a JSON dictionary, '}', is the escape |
4128 | // character in gdb-remote binary mode. lldb currently doesn't escape |
4129 | // these characters in its packet output -- so we add the quoted version of |
4130 | // the } character here manually in case we talk to a debugserver which un- |
4131 | // escapes the characters at packet read time. |
4132 | packet << (char)(0x7d ^ 0x20); |
4133 | |
4134 | StringExtractorGDBRemote response; |
4135 | response.SetResponseValidatorToJSON(); |
4136 | if (m_gdb_comm.SendPacketAndWaitForResponse(payload: packet.GetString(), response) == |
4137 | GDBRemoteCommunication::PacketResult::Success) { |
4138 | StringExtractorGDBRemote::ResponseType response_type = |
4139 | response.GetResponseType(); |
4140 | if (response_type == StringExtractorGDBRemote::eResponse) { |
4141 | if (!response.Empty()) { |
4142 | object_sp = StructuredData::ParseJSON(json_text: response.GetStringRef()); |
4143 | } |
4144 | } |
4145 | } |
4146 | } |
4147 | return object_sp; |
4148 | } |
4149 | |
4150 | Status ProcessGDBRemote::ConfigureStructuredData( |
4151 | llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) { |
4152 | return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp); |
4153 | } |
4154 | |
4155 | // Establish the largest memory read/write payloads we should use. If the |
4156 | // remote stub has a max packet size, stay under that size. |
4157 | // |
4158 | // If the remote stub's max packet size is crazy large, use a reasonable |
4159 | // largeish default. |
4160 | // |
4161 | // If the remote stub doesn't advertise a max packet size, use a conservative |
4162 | // default. |
4163 | |
4164 | void ProcessGDBRemote::GetMaxMemorySize() { |
4165 | const uint64_t reasonable_largeish_default = 128 * 1024; |
4166 | const uint64_t conservative_default = 512; |
4167 | |
4168 | if (m_max_memory_size == 0) { |
4169 | uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize(); |
4170 | if (stub_max_size != UINT64_MAX && stub_max_size != 0) { |
4171 | // Save the stub's claimed maximum packet size |
4172 | m_remote_stub_max_memory_size = stub_max_size; |
4173 | |
4174 | // Even if the stub says it can support ginormous packets, don't exceed |
4175 | // our reasonable largeish default packet size. |
4176 | if (stub_max_size > reasonable_largeish_default) { |
4177 | stub_max_size = reasonable_largeish_default; |
4178 | } |
4179 | |
4180 | // Memory packet have other overheads too like Maddr,size:#NN Instead of |
4181 | // calculating the bytes taken by size and addr every time, we take a |
4182 | // maximum guess here. |
4183 | if (stub_max_size > 70) |
4184 | stub_max_size -= 32 + 32 + 6; |
4185 | else { |
4186 | // In unlikely scenario that max packet size is less then 70, we will |
4187 | // hope that data being written is small enough to fit. |
4188 | Log *log(GetLog(mask: GDBRLog::Comm | GDBRLog::Memory)); |
4189 | if (log) |
4190 | log->Warning(fmt: "Packet size is too small. " |
4191 | "LLDB may face problems while writing memory"); |
4192 | } |
4193 | |
4194 | m_max_memory_size = stub_max_size; |
4195 | } else { |
4196 | m_max_memory_size = conservative_default; |
4197 | } |
4198 | } |
4199 | } |
4200 | |
4201 | void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize( |
4202 | uint64_t user_specified_max) { |
4203 | if (user_specified_max != 0) { |
4204 | GetMaxMemorySize(); |
4205 | |
4206 | if (m_remote_stub_max_memory_size != 0) { |
4207 | if (m_remote_stub_max_memory_size < user_specified_max) { |
4208 | m_max_memory_size = m_remote_stub_max_memory_size; // user specified a |
4209 | // packet size too |
4210 | // big, go as big |
4211 | // as the remote stub says we can go. |
4212 | } else { |
4213 | m_max_memory_size = user_specified_max; // user's packet size is good |
4214 | } |
4215 | } else { |
4216 | m_max_memory_size = |
4217 | user_specified_max; // user's packet size is probably fine |
4218 | } |
4219 | } |
4220 | } |
4221 | |
4222 | bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec, |
4223 | const ArchSpec &arch, |
4224 | ModuleSpec &module_spec) { |
4225 | Log *log = GetLog(mask: LLDBLog::Platform); |
4226 | |
4227 | const ModuleCacheKey key(module_file_spec.GetPath(), |
4228 | arch.GetTriple().getTriple()); |
4229 | auto cached = m_cached_module_specs.find(Val: key); |
4230 | if (cached != m_cached_module_specs.end()) { |
4231 | module_spec = cached->second; |
4232 | return bool(module_spec); |
4233 | } |
4234 | |
4235 | if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch_spec: arch, module_spec)) { |
4236 | LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s", |
4237 | __FUNCTION__, module_file_spec.GetPath().c_str(), |
4238 | arch.GetTriple().getTriple().c_str()); |
4239 | return false; |
4240 | } |
4241 | |
4242 | if (log) { |
4243 | StreamString stream; |
4244 | module_spec.Dump(strm&: stream); |
4245 | LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s", |
4246 | __FUNCTION__, module_file_spec.GetPath().c_str(), |
4247 | arch.GetTriple().getTriple().c_str(), stream.GetData()); |
4248 | } |
4249 | |
4250 | m_cached_module_specs[key] = module_spec; |
4251 | return true; |
4252 | } |
4253 | |
4254 | void ProcessGDBRemote::PrefetchModuleSpecs( |
4255 | llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) { |
4256 | auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple); |
4257 | if (module_specs) { |
4258 | for (const FileSpec &spec : module_file_specs) |
4259 | m_cached_module_specs[ModuleCacheKey(spec.GetPath(), |
4260 | triple.getTriple())] = ModuleSpec(); |
4261 | for (const ModuleSpec &spec : *module_specs) |
4262 | m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(), |
4263 | triple.getTriple())] = spec; |
4264 | } |
4265 | } |
4266 | |
4267 | llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() { |
4268 | return m_gdb_comm.GetOSVersion(); |
4269 | } |
4270 | |
4271 | llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() { |
4272 | return m_gdb_comm.GetMacCatalystVersion(); |
4273 | } |
4274 | |
4275 | namespace { |
4276 | |
4277 | typedef std::vector<std::string> stringVec; |
4278 | |
4279 | typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec; |
4280 | struct RegisterSetInfo { |
4281 | ConstString name; |
4282 | }; |
4283 | |
4284 | typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap; |
4285 | |
4286 | struct GdbServerTargetInfo { |
4287 | std::string arch; |
4288 | std::string osabi; |
4289 | stringVec includes; |
4290 | RegisterSetMap reg_set_map; |
4291 | }; |
4292 | |
4293 | static FieldEnum::Enumerators ParseEnumEvalues(const XMLNode &enum_node) { |
4294 | Log *log(GetLog(mask: GDBRLog::Process)); |
4295 | // We will use the last instance of each value. Also we preserve the order |
4296 | // of declaration in the XML, as it may not be numerical. |
4297 | // For example, hardware may intially release with two states that softwware |
4298 | // can read from a register field: |
4299 | // 0 = startup, 1 = running |
4300 | // If in a future hardware release, the designers added a pre-startup state: |
4301 | // 0 = startup, 1 = running, 2 = pre-startup |
4302 | // Now it makes more sense to list them in this logical order as opposed to |
4303 | // numerical order: |
4304 | // 2 = pre-startup, 1 = startup, 0 = startup |
4305 | // This only matters for "register info" but let's trust what the server |
4306 | // chose regardless. |
4307 | std::map<uint64_t, FieldEnum::Enumerator> enumerators; |
4308 | |
4309 | enum_node.ForEachChildElementWithName( |
4310 | name: "evalue", callback: [&enumerators, &log](const XMLNode &enumerator_node) { |
4311 | std::optional<llvm::StringRef> name; |
4312 | std::optional<uint64_t> value; |
4313 | |
4314 | enumerator_node.ForEachAttribute( |
4315 | callback: [&name, &value, &log](const llvm::StringRef &attr_name, |
4316 | const llvm::StringRef &attr_value) { |
4317 | if (attr_name == "name") { |
4318 | if (attr_value.size()) |
4319 | name = attr_value; |
4320 | else |
4321 | LLDB_LOG(log, "ProcessGDBRemote::ParseEnumEvalues " |
4322 | "Ignoring empty name in evalue"); |
4323 | } else if (attr_name == "value") { |
4324 | uint64_t parsed_value = 0; |
4325 | if (llvm::to_integer(S: attr_value, Num&: parsed_value)) |
4326 | value = parsed_value; |
4327 | else |
4328 | LLDB_LOG(log, |
4329 | "ProcessGDBRemote::ParseEnumEvalues " |
4330 | "Invalid value \"{0}\" in " |
4331 | "evalue", |
4332 | attr_value.data()); |
4333 | } else |
4334 | LLDB_LOG(log, |
4335 | "ProcessGDBRemote::ParseEnumEvalues Ignoring " |
4336 | "unknown attribute " |
4337 | "\"{0}\" in evalue", |
4338 | attr_name.data()); |
4339 | |
4340 | // Keep walking attributes. |
4341 | return true; |
4342 | }); |
4343 | |
4344 | if (value && name) |
4345 | enumerators.insert_or_assign( |
4346 | k: *value, obj: FieldEnum::Enumerator(*value, name->str())); |
4347 | |
4348 | // Find all evalue elements. |
4349 | return true; |
4350 | }); |
4351 | |
4352 | FieldEnum::Enumerators final_enumerators; |
4353 | for (auto [_, enumerator] : enumerators) |
4354 | final_enumerators.push_back(x: enumerator); |
4355 | |
4356 | return final_enumerators; |
4357 | } |
4358 | |
4359 | static void |
4360 | ParseEnums(XMLNode feature_node, |
4361 | llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) { |
4362 | Log *log(GetLog(mask: GDBRLog::Process)); |
4363 | |
4364 | // The top level element is "<enum...". |
4365 | feature_node.ForEachChildElementWithName( |
4366 | name: "enum", callback: [log, ®isters_enum_types](const XMLNode &enum_node) { |
4367 | std::string id; |
4368 | |
4369 | enum_node.ForEachAttribute(callback: [&id](const llvm::StringRef &attr_name, |
4370 | const llvm::StringRef &attr_value) { |
4371 | if (attr_name == "id") |
4372 | id = attr_value; |
4373 | |
4374 | // There is also a "size" attribute that is supposed to be the size in |
4375 | // bytes of the register this applies to. However: |
4376 | // * LLDB doesn't need this information. |
4377 | // * It is difficult to verify because you have to wait until the |
4378 | // enum is applied to a field. |
4379 | // |
4380 | // So we will emit this attribute in XML for GDB's sake, but will not |
4381 | // bother ingesting it. |
4382 | |
4383 | // Walk all attributes. |
4384 | return true; |
4385 | }); |
4386 | |
4387 | if (!id.empty()) { |
4388 | FieldEnum::Enumerators enumerators = ParseEnumEvalues(enum_node); |
4389 | if (!enumerators.empty()) { |
4390 | LLDB_LOG(log, |
4391 | "ProcessGDBRemote::ParseEnums Found enum type \"{0}\"", |
4392 | id); |
4393 | registers_enum_types.insert_or_assign( |
4394 | Key: id, Val: std::make_unique<FieldEnum>(args&: id, args&: enumerators)); |
4395 | } |
4396 | } |
4397 | |
4398 | // Find all <enum> elements. |
4399 | return true; |
4400 | }); |
4401 | } |
4402 | |
4403 | static std::vector<RegisterFlags::Field> ParseFlagsFields( |
4404 | XMLNode flags_node, unsigned size, |
4405 | const llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) { |
4406 | Log *log(GetLog(mask: GDBRLog::Process)); |
4407 | const unsigned max_start_bit = size * 8 - 1; |
4408 | |
4409 | // Process the fields of this set of flags. |
4410 | std::vector<RegisterFlags::Field> fields; |
4411 | flags_node.ForEachChildElementWithName(name: "field", callback: [&fields, max_start_bit, &log, |
4412 | ®isters_enum_types]( |
4413 | const XMLNode |
4414 | &field_node) { |
4415 | std::optional<llvm::StringRef> name; |
4416 | std::optional<unsigned> start; |
4417 | std::optional<unsigned> end; |
4418 | std::optional<llvm::StringRef> type; |
4419 | |
4420 | field_node.ForEachAttribute(callback: [&name, &start, &end, &type, max_start_bit, |
4421 | &log](const llvm::StringRef &attr_name, |
4422 | const llvm::StringRef &attr_value) { |
4423 | // Note that XML in general requires that each of these attributes only |
4424 | // appears once, so we don't have to handle that here. |
4425 | if (attr_name == "name") { |
4426 | LLDB_LOG( |
4427 | log, |
4428 | "ProcessGDBRemote::ParseFlagsFields Found field node name \"{0}\"", |
4429 | attr_value.data()); |
4430 | name = attr_value; |
4431 | } else if (attr_name == "start") { |
4432 | unsigned parsed_start = 0; |
4433 | if (llvm::to_integer(S: attr_value, Num&: parsed_start)) { |
4434 | if (parsed_start > max_start_bit) { |
4435 | LLDB_LOG(log, |
4436 | "ProcessGDBRemote::ParseFlagsFields Invalid start {0} in " |
4437 | "field node, " |
4438 | "cannot be > {1}", |
4439 | parsed_start, max_start_bit); |
4440 | } else |
4441 | start = parsed_start; |
4442 | } else { |
4443 | LLDB_LOG( |
4444 | log, |
4445 | "ProcessGDBRemote::ParseFlagsFields Invalid start \"{0}\" in " |
4446 | "field node", |
4447 | attr_value.data()); |
4448 | } |
4449 | } else if (attr_name == "end") { |
4450 | unsigned parsed_end = 0; |
4451 | if (llvm::to_integer(S: attr_value, Num&: parsed_end)) |
4452 | if (parsed_end > max_start_bit) { |
4453 | LLDB_LOG(log, |
4454 | "ProcessGDBRemote::ParseFlagsFields Invalid end {0} in " |
4455 | "field node, " |
4456 | "cannot be > {1}", |
4457 | parsed_end, max_start_bit); |
4458 | } else |
4459 | end = parsed_end; |
4460 | else { |
4461 | LLDB_LOG(log, |
4462 | "ProcessGDBRemote::ParseFlagsFields Invalid end \"{0}\" in " |
4463 | "field node", |
4464 | attr_value.data()); |
4465 | } |
4466 | } else if (attr_name == "type") { |
4467 | type = attr_value; |
4468 | } else { |
4469 | LLDB_LOG( |
4470 | log, |
4471 | "ProcessGDBRemote::ParseFlagsFields Ignoring unknown attribute " |
4472 | "\"{0}\" in field node", |
4473 | attr_name.data()); |
4474 | } |
4475 | |
4476 | return true; // Walk all attributes of the field. |
4477 | }); |
4478 | |
4479 | if (name && start && end) { |
4480 | if (*start > *end) |
4481 | LLDB_LOG( |
4482 | log, |
4483 | "ProcessGDBRemote::ParseFlagsFields Start {0} > end {1} in field " |
4484 | "\"{2}\", ignoring", |
4485 | *start, *end, name->data()); |
4486 | else { |
4487 | if (RegisterFlags::Field::GetSizeInBits(start: *start, end: *end) > 64) |
4488 | LLDB_LOG(log, |
4489 | "ProcessGDBRemote::ParseFlagsFields Ignoring field \"{2}\" " |
4490 | "that has " |
4491 | "size > 64 bits, this is not supported", |
4492 | name->data()); |
4493 | else { |
4494 | // A field's type may be set to the name of an enum type. |
4495 | const FieldEnum *enum_type = nullptr; |
4496 | if (type && !type->empty()) { |
4497 | auto found = registers_enum_types.find(Key: *type); |
4498 | if (found != registers_enum_types.end()) { |
4499 | enum_type = found->second.get(); |
4500 | |
4501 | // No enumerator can exceed the range of the field itself. |
4502 | uint64_t max_value = |
4503 | RegisterFlags::Field::GetMaxValue(start: *start, end: *end); |
4504 | for (const auto &enumerator : enum_type->GetEnumerators()) { |
4505 | if (enumerator.m_value > max_value) { |
4506 | enum_type = nullptr; |
4507 | LLDB_LOG( |
4508 | log, |
4509 | "ProcessGDBRemote::ParseFlagsFields In enum \"{0}\" " |
4510 | "evalue \"{1}\" with value {2} exceeds the maximum value " |
4511 | "of field \"{3}\" ({4}), ignoring enum", |
4512 | type->data(), enumerator.m_name, enumerator.m_value, |
4513 | name->data(), max_value); |
4514 | break; |
4515 | } |
4516 | } |
4517 | } else { |
4518 | LLDB_LOG(log, |
4519 | "ProcessGDBRemote::ParseFlagsFields Could not find type " |
4520 | "\"{0}\" " |
4521 | "for field \"{1}\", ignoring", |
4522 | type->data(), name->data()); |
4523 | } |
4524 | } |
4525 | |
4526 | fields.push_back( |
4527 | x: RegisterFlags::Field(name->str(), *start, *end, enum_type)); |
4528 | } |
4529 | } |
4530 | } |
4531 | |
4532 | return true; // Iterate all "field" nodes. |
4533 | }); |
4534 | return fields; |
4535 | } |
4536 | |
4537 | void ParseFlags( |
4538 | XMLNode feature_node, |
4539 | llvm::StringMap<std::unique_ptr<RegisterFlags>> ®isters_flags_types, |
4540 | const llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) { |
4541 | Log *log(GetLog(mask: GDBRLog::Process)); |
4542 | |
4543 | feature_node.ForEachChildElementWithName( |
4544 | name: "flags", |
4545 | callback: [&log, ®isters_flags_types, |
4546 | ®isters_enum_types](const XMLNode &flags_node) -> bool { |
4547 | LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"", |
4548 | flags_node.GetAttributeValue("id").c_str()); |
4549 | |
4550 | std::optional<llvm::StringRef> id; |
4551 | std::optional<unsigned> size; |
4552 | flags_node.ForEachAttribute( |
4553 | callback: [&id, &size, &log](const llvm::StringRef &name, |
4554 | const llvm::StringRef &value) { |
4555 | if (name == "id") { |
4556 | id = value; |
4557 | } else if (name == "size") { |
4558 | unsigned parsed_size = 0; |
4559 | if (llvm::to_integer(S: value, Num&: parsed_size)) |
4560 | size = parsed_size; |
4561 | else { |
4562 | LLDB_LOG(log, |
4563 | "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" " |
4564 | "in flags node", |
4565 | value.data()); |
4566 | } |
4567 | } else { |
4568 | LLDB_LOG(log, |
4569 | "ProcessGDBRemote::ParseFlags Ignoring unknown " |
4570 | "attribute \"{0}\" in flags node", |
4571 | name.data()); |
4572 | } |
4573 | return true; // Walk all attributes. |
4574 | }); |
4575 | |
4576 | if (id && size) { |
4577 | // Process the fields of this set of flags. |
4578 | std::vector<RegisterFlags::Field> fields = |
4579 | ParseFlagsFields(flags_node, size: *size, registers_enum_types); |
4580 | if (fields.size()) { |
4581 | // Sort so that the fields with the MSBs are first. |
4582 | std::sort(first: fields.rbegin(), last: fields.rend()); |
4583 | std::vector<RegisterFlags::Field>::const_iterator overlap = |
4584 | std::adjacent_find(first: fields.begin(), last: fields.end(), |
4585 | binary_pred: [](const RegisterFlags::Field &lhs, |
4586 | const RegisterFlags::Field &rhs) { |
4587 | return lhs.Overlaps(other: rhs); |
4588 | }); |
4589 | |
4590 | // If no fields overlap, use them. |
4591 | if (overlap == fields.end()) { |
4592 | if (registers_flags_types.contains(Key: *id)) { |
4593 | // In theory you could define some flag set, use it with a |
4594 | // register then redefine it. We do not know if anyone does |
4595 | // that, or what they would expect to happen in that case. |
4596 | // |
4597 | // LLDB chooses to take the first definition and ignore the rest |
4598 | // as waiting until everything has been processed is more |
4599 | // expensive and difficult. This means that pointers to flag |
4600 | // sets in the register info remain valid if later the flag set |
4601 | // is redefined. If we allowed redefinitions, LLDB would crash |
4602 | // when you tried to print a register that used the original |
4603 | // definition. |
4604 | LLDB_LOG( |
4605 | log, |
4606 | "ProcessGDBRemote::ParseFlags Definition of flags " |
4607 | "\"{0}\" shadows " |
4608 | "previous definition, using original definition instead.", |
4609 | id->data()); |
4610 | } else { |
4611 | registers_flags_types.insert_or_assign( |
4612 | Key: *id, Val: std::make_unique<RegisterFlags>(args: id->str(), args&: *size, |
4613 | args: std::move(fields))); |
4614 | } |
4615 | } else { |
4616 | // If any fields overlap, ignore the whole set of flags. |
4617 | std::vector<RegisterFlags::Field>::const_iterator next = |
4618 | std::next(x: overlap); |
4619 | LLDB_LOG( |
4620 | log, |
4621 | "ProcessGDBRemote::ParseFlags Ignoring flags because fields " |
4622 | "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) " |
4623 | "overlap.", |
4624 | overlap->GetName().c_str(), overlap->GetStart(), |
4625 | overlap->GetEnd(), next->GetName().c_str(), next->GetStart(), |
4626 | next->GetEnd()); |
4627 | } |
4628 | } else { |
4629 | LLDB_LOG( |
4630 | log, |
4631 | "ProcessGDBRemote::ParseFlags Ignoring definition of flags " |
4632 | "\"{0}\" because it contains no fields.", |
4633 | id->data()); |
4634 | } |
4635 | } |
4636 | |
4637 | return true; // Keep iterating through all "flags" elements. |
4638 | }); |
4639 | } |
4640 | |
4641 | bool ParseRegisters( |
4642 | XMLNode feature_node, GdbServerTargetInfo &target_info, |
4643 | std::vector<DynamicRegisterInfo::Register> ®isters, |
4644 | llvm::StringMap<std::unique_ptr<RegisterFlags>> ®isters_flags_types, |
4645 | llvm::StringMap<std::unique_ptr<FieldEnum>> ®isters_enum_types) { |
4646 | if (!feature_node) |
4647 | return false; |
4648 | |
4649 | Log *log(GetLog(mask: GDBRLog::Process)); |
4650 | |
4651 | // Enums first because they are referenced by fields in the flags. |
4652 | ParseEnums(feature_node, registers_enum_types); |
4653 | for (const auto &enum_type : registers_enum_types) |
4654 | enum_type.second->DumpToLog(log); |
4655 | |
4656 | ParseFlags(feature_node, registers_flags_types, registers_enum_types); |
4657 | for (const auto &flags : registers_flags_types) |
4658 | flags.second->DumpToLog(log); |
4659 | |
4660 | feature_node.ForEachChildElementWithName( |
4661 | name: "reg", |
4662 | callback: [&target_info, ®isters, ®isters_flags_types, |
4663 | log](const XMLNode ®_node) -> bool { |
4664 | std::string gdb_group; |
4665 | std::string gdb_type; |
4666 | DynamicRegisterInfo::Register reg_info; |
4667 | bool encoding_set = false; |
4668 | bool format_set = false; |
4669 | |
4670 | // FIXME: we're silently ignoring invalid data here |
4671 | reg_node.ForEachAttribute(callback: [&target_info, &gdb_group, &gdb_type, |
4672 | &encoding_set, &format_set, ®_info, |
4673 | log](const llvm::StringRef &name, |
4674 | const llvm::StringRef &value) -> bool { |
4675 | if (name == "name") { |
4676 | reg_info.name.SetString(value); |
4677 | } else if (name == "bitsize") { |
4678 | if (llvm::to_integer(S: value, Num&: reg_info.byte_size)) |
4679 | reg_info.byte_size = |
4680 | llvm::divideCeil(Numerator: reg_info.byte_size, CHAR_BIT); |
4681 | } else if (name == "type") { |
4682 | gdb_type = value.str(); |
4683 | } else if (name == "group") { |
4684 | gdb_group = value.str(); |
4685 | } else if (name == "regnum") { |
4686 | llvm::to_integer(S: value, Num&: reg_info.regnum_remote); |
4687 | } else if (name == "offset") { |
4688 | llvm::to_integer(S: value, Num&: reg_info.byte_offset); |
4689 | } else if (name == "altname") { |
4690 | reg_info.alt_name.SetString(value); |
4691 | } else if (name == "encoding") { |
4692 | encoding_set = true; |
4693 | reg_info.encoding = Args::StringToEncoding(s: value, fail_value: eEncodingUint); |
4694 | } else if (name == "format") { |
4695 | format_set = true; |
4696 | if (!OptionArgParser::ToFormat(s: value.data(), format&: reg_info.format, |
4697 | byte_size_ptr: nullptr) |
4698 | .Success()) |
4699 | reg_info.format = |
4700 | llvm::StringSwitch<lldb::Format>(value) |
4701 | .Case(S: "vector-sint8", Value: eFormatVectorOfSInt8) |
4702 | .Case(S: "vector-uint8", Value: eFormatVectorOfUInt8) |
4703 | .Case(S: "vector-sint16", Value: eFormatVectorOfSInt16) |
4704 | .Case(S: "vector-uint16", Value: eFormatVectorOfUInt16) |
4705 | .Case(S: "vector-sint32", Value: eFormatVectorOfSInt32) |
4706 | .Case(S: "vector-uint32", Value: eFormatVectorOfUInt32) |
4707 | .Case(S: "vector-float32", Value: eFormatVectorOfFloat32) |
4708 | .Case(S: "vector-uint64", Value: eFormatVectorOfUInt64) |
4709 | .Case(S: "vector-uint128", Value: eFormatVectorOfUInt128) |
4710 | .Default(Value: eFormatInvalid); |
4711 | } else if (name == "group_id") { |
4712 | uint32_t set_id = UINT32_MAX; |
4713 | llvm::to_integer(S: value, Num&: set_id); |
4714 | RegisterSetMap::const_iterator pos = |
4715 | target_info.reg_set_map.find(x: set_id); |
4716 | if (pos != target_info.reg_set_map.end()) |
4717 | reg_info.set_name = pos->second.name; |
4718 | } else if (name == "gcc_regnum"|| name == "ehframe_regnum") { |
4719 | llvm::to_integer(S: value, Num&: reg_info.regnum_ehframe); |
4720 | } else if (name == "dwarf_regnum") { |
4721 | llvm::to_integer(S: value, Num&: reg_info.regnum_dwarf); |
4722 | } else if (name == "generic") { |
4723 | reg_info.regnum_generic = Args::StringToGenericRegister(s: value); |
4724 | } else if (name == "value_regnums") { |
4725 | SplitCommaSeparatedRegisterNumberString(comma_separated_register_numbers: value, regnums&: reg_info.value_regs, |
4726 | base: 0); |
4727 | } else if (name == "invalidate_regnums") { |
4728 | SplitCommaSeparatedRegisterNumberString( |
4729 | comma_separated_register_numbers: value, regnums&: reg_info.invalidate_regs, base: 0); |
4730 | } else { |
4731 | LLDB_LOGF(log, |
4732 | "ProcessGDBRemote::ParseRegisters unhandled reg " |
4733 | "attribute %s = %s", |
4734 | name.data(), value.data()); |
4735 | } |
4736 | return true; // Keep iterating through all attributes |
4737 | }); |
4738 | |
4739 | if (!gdb_type.empty()) { |
4740 | // gdb_type could reference some flags type defined in XML. |
4741 | llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it = |
4742 | registers_flags_types.find(Key: gdb_type); |
4743 | if (it != registers_flags_types.end()) { |
4744 | auto flags_type = it->second.get(); |
4745 | if (reg_info.byte_size == flags_type->GetSize()) |
4746 | reg_info.flags_type = flags_type; |
4747 | else |
4748 | LLDB_LOGF(log, |
4749 | "ProcessGDBRemote::ParseRegisters Size of register " |
4750 | "flags %s (%d bytes) for " |
4751 | "register %s does not match the register size (%d " |
4752 | "bytes). Ignoring this set of flags.", |
4753 | flags_type->GetID().c_str(), flags_type->GetSize(), |
4754 | reg_info.name.AsCString(), reg_info.byte_size); |
4755 | } |
4756 | |
4757 | // There's a slim chance that the gdb_type name is both a flags type |
4758 | // and a simple type. Just in case, look for that too (setting both |
4759 | // does no harm). |
4760 | if (!gdb_type.empty() && !(encoding_set || format_set)) { |
4761 | if (llvm::StringRef(gdb_type).starts_with(Prefix: "int")) { |
4762 | reg_info.format = eFormatHex; |
4763 | reg_info.encoding = eEncodingUint; |
4764 | } else if (gdb_type == "data_ptr"|| gdb_type == "code_ptr") { |
4765 | reg_info.format = eFormatAddressInfo; |
4766 | reg_info.encoding = eEncodingUint; |
4767 | } else if (gdb_type == "float") { |
4768 | reg_info.format = eFormatFloat; |
4769 | reg_info.encoding = eEncodingIEEE754; |
4770 | } else if (gdb_type == "aarch64v"|| |
4771 | llvm::StringRef(gdb_type).starts_with(Prefix: "vec") || |
4772 | gdb_type == "i387_ext"|| gdb_type == "uint128"|| |
4773 | reg_info.byte_size > 16) { |
4774 | // lldb doesn't handle 128-bit uints correctly (for ymm*h), so |
4775 | // treat them as vector (similarly to xmm/ymm). |
4776 | // We can fall back to handling anything else <= 128 bit as an |
4777 | // unsigned integer, more than that, call it a vector of bytes. |
4778 | // This can happen if we don't recognise the type for AArc64 SVE |
4779 | // registers. |
4780 | reg_info.format = eFormatVectorOfUInt8; |
4781 | reg_info.encoding = eEncodingVector; |
4782 | } else { |
4783 | LLDB_LOGF( |
4784 | log, |
4785 | "ProcessGDBRemote::ParseRegisters Could not determine lldb" |
4786 | "format and encoding for gdb type %s", |
4787 | gdb_type.c_str()); |
4788 | } |
4789 | } |
4790 | } |
4791 | |
4792 | // Only update the register set name if we didn't get a "reg_set" |
4793 | // attribute. "set_name" will be empty if we didn't have a "reg_set" |
4794 | // attribute. |
4795 | if (!reg_info.set_name) { |
4796 | if (!gdb_group.empty()) { |
4797 | reg_info.set_name.SetCString(gdb_group.c_str()); |
4798 | } else { |
4799 | // If no register group name provided anywhere, |
4800 | // we'll create a 'general' register set |
4801 | reg_info.set_name.SetCString("general"); |
4802 | } |
4803 | } |
4804 | |
4805 | if (reg_info.byte_size == 0) { |
4806 | LLDB_LOGF(log, |
4807 | "ProcessGDBRemote::%s Skipping zero bitsize register %s", |
4808 | __FUNCTION__, reg_info.name.AsCString()); |
4809 | } else |
4810 | registers.push_back(x: reg_info); |
4811 | |
4812 | return true; // Keep iterating through all "reg" elements |
4813 | }); |
4814 | return true; |
4815 | } |
4816 | |
4817 | } // namespace |
4818 | |
4819 | // This method fetches a register description feature xml file from |
4820 | // the remote stub and adds registers/register groupsets/architecture |
4821 | // information to the current process. It will call itself recursively |
4822 | // for nested register definition files. It returns true if it was able |
4823 | // to fetch and parse an xml file. |
4824 | bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess( |
4825 | ArchSpec &arch_to_use, std::string xml_filename, |
4826 | std::vector<DynamicRegisterInfo::Register> ®isters) { |
4827 | // request the target xml file |
4828 | llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature(object: "features", annex: xml_filename); |
4829 | if (errorToBool(Err: raw.takeError())) |
4830 | return false; |
4831 | |
4832 | XMLDocument xml_document; |
4833 | |
4834 | if (xml_document.ParseMemory(xml: raw->c_str(), xml_length: raw->size(), |
4835 | url: xml_filename.c_str())) { |
4836 | GdbServerTargetInfo target_info; |
4837 | std::vector<XMLNode> feature_nodes; |
4838 | |
4839 | // The top level feature XML file will start with a <target> tag. |
4840 | XMLNode target_node = xml_document.GetRootElement(required_name: "target"); |
4841 | if (target_node) { |
4842 | target_node.ForEachChildElement(callback: [&target_info, &feature_nodes]( |
4843 | const XMLNode &node) -> bool { |
4844 | llvm::StringRef name = node.GetName(); |
4845 | if (name == "architecture") { |
4846 | node.GetElementText(text&: target_info.arch); |
4847 | } else if (name == "osabi") { |
4848 | node.GetElementText(text&: target_info.osabi); |
4849 | } else if (name == "xi:include"|| name == "include") { |
4850 | std::string href = node.GetAttributeValue(name: "href"); |
4851 | if (!href.empty()) |
4852 | target_info.includes.push_back(x: href); |
4853 | } else if (name == "feature") { |
4854 | feature_nodes.push_back(x: node); |
4855 | } else if (name == "groups") { |
4856 | node.ForEachChildElementWithName( |
4857 | name: "group", callback: [&target_info](const XMLNode &node) -> bool { |
4858 | uint32_t set_id = UINT32_MAX; |
4859 | RegisterSetInfo set_info; |
4860 | |
4861 | node.ForEachAttribute( |
4862 | callback: [&set_id, &set_info](const llvm::StringRef &name, |
4863 | const llvm::StringRef &value) -> bool { |
4864 | // FIXME: we're silently ignoring invalid data here |
4865 | if (name == "id") |
4866 | llvm::to_integer(S: value, Num&: set_id); |
4867 | if (name == "name") |
4868 | set_info.name = ConstString(value); |
4869 | return true; // Keep iterating through all attributes |
4870 | }); |
4871 | |
4872 | if (set_id != UINT32_MAX) |
4873 | target_info.reg_set_map[set_id] = set_info; |
4874 | return true; // Keep iterating through all "group" elements |
4875 | }); |
4876 | } |
4877 | return true; // Keep iterating through all children of the target_node |
4878 | }); |
4879 | } else { |
4880 | // In an included XML feature file, we're already "inside" the <target> |
4881 | // tag of the initial XML file; this included file will likely only have |
4882 | // a <feature> tag. Need to check for any more included files in this |
4883 | // <feature> element. |
4884 | XMLNode feature_node = xml_document.GetRootElement(required_name: "feature"); |
4885 | if (feature_node) { |
4886 | feature_nodes.push_back(x: feature_node); |
4887 | feature_node.ForEachChildElement(callback: [&target_info]( |
4888 | const XMLNode &node) -> bool { |
4889 | llvm::StringRef name = node.GetName(); |
4890 | if (name == "xi:include"|| name == "include") { |
4891 | std::string href = node.GetAttributeValue(name: "href"); |
4892 | if (!href.empty()) |
4893 | target_info.includes.push_back(x: href); |
4894 | } |
4895 | return true; |
4896 | }); |
4897 | } |
4898 | } |
4899 | |
4900 | // gdbserver does not implement the LLDB packets used to determine host |
4901 | // or process architecture. If that is the case, attempt to use |
4902 | // the <architecture/> field from target.xml, e.g.: |
4903 | // |
4904 | // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi) |
4905 | // <architecture>arm</architecture> (seen from Segger JLink on unspecified |
4906 | // arm board) |
4907 | if (!arch_to_use.IsValid() && !target_info.arch.empty()) { |
4908 | // We don't have any information about vendor or OS. |
4909 | arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch) |
4910 | .Case(S: "i386:x86-64", Value: "x86_64") |
4911 | .Case(S: "riscv:rv64", Value: "riscv64") |
4912 | .Case(S: "riscv:rv32", Value: "riscv32") |
4913 | .Default(Value: target_info.arch) + |
4914 | "--"); |
4915 | |
4916 | if (arch_to_use.IsValid()) |
4917 | GetTarget().MergeArchitecture(arch_spec: arch_to_use); |
4918 | } |
4919 | |
4920 | if (arch_to_use.IsValid()) { |
4921 | for (auto &feature_node : feature_nodes) { |
4922 | ParseRegisters(feature_node, target_info, registers, |
4923 | registers_flags_types&: m_registers_flags_types, registers_enum_types&: m_registers_enum_types); |
4924 | } |
4925 | |
4926 | for (const auto &include : target_info.includes) { |
4927 | GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, xml_filename: include, |
4928 | registers); |
4929 | } |
4930 | } |
4931 | } else { |
4932 | return false; |
4933 | } |
4934 | return true; |
4935 | } |
4936 | |
4937 | void ProcessGDBRemote::AddRemoteRegisters( |
4938 | std::vector<DynamicRegisterInfo::Register> ®isters, |
4939 | const ArchSpec &arch_to_use) { |
4940 | std::map<uint32_t, uint32_t> remote_to_local_map; |
4941 | uint32_t remote_regnum = 0; |
4942 | for (auto it : llvm::enumerate(First&: registers)) { |
4943 | DynamicRegisterInfo::Register &remote_reg_info = it.value(); |
4944 | |
4945 | // Assign successive remote regnums if missing. |
4946 | if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM) |
4947 | remote_reg_info.regnum_remote = remote_regnum; |
4948 | |
4949 | // Create a mapping from remote to local regnos. |
4950 | remote_to_local_map[remote_reg_info.regnum_remote] = it.index(); |
4951 | |
4952 | remote_regnum = remote_reg_info.regnum_remote + 1; |
4953 | } |
4954 | |
4955 | for (DynamicRegisterInfo::Register &remote_reg_info : registers) { |
4956 | auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) { |
4957 | auto lldb_regit = remote_to_local_map.find(x: process_regnum); |
4958 | return lldb_regit != remote_to_local_map.end() ? lldb_regit->second |
4959 | : LLDB_INVALID_REGNUM; |
4960 | }; |
4961 | |
4962 | llvm::transform(Range&: remote_reg_info.value_regs, |
4963 | d_first: remote_reg_info.value_regs.begin(), F: proc_to_lldb); |
4964 | llvm::transform(Range&: remote_reg_info.invalidate_regs, |
4965 | d_first: remote_reg_info.invalidate_regs.begin(), F: proc_to_lldb); |
4966 | } |
4967 | |
4968 | // Don't use Process::GetABI, this code gets called from DidAttach, and |
4969 | // in that context we haven't set the Target's architecture yet, so the |
4970 | // ABI is also potentially incorrect. |
4971 | if (ABISP abi_sp = ABI::FindPlugin(process_sp: shared_from_this(), arch: arch_to_use)) |
4972 | abi_sp->AugmentRegisterInfo(regs&: registers); |
4973 | |
4974 | m_register_info_sp->SetRegisterInfo(regs: std::move(registers), arch: arch_to_use); |
4975 | } |
4976 | |
4977 | // query the target of gdb-remote for extended target information returns |
4978 | // true on success (got register definitions), false on failure (did not). |
4979 | bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) { |
4980 | // Make sure LLDB has an XML parser it can use first |
4981 | if (!XMLDocument::XMLEnabled()) |
4982 | return false; |
4983 | |
4984 | // check that we have extended feature read support |
4985 | if (!m_gdb_comm.GetQXferFeaturesReadSupported()) |
4986 | return false; |
4987 | |
4988 | // These hold register type information for the whole of target.xml. |
4989 | // target.xml may include further documents that |
4990 | // GetGDBServerRegisterInfoXMLAndProcess will recurse to fetch and process. |
4991 | // That's why we clear the cache here, and not in |
4992 | // GetGDBServerRegisterInfoXMLAndProcess. To prevent it being cleared on every |
4993 | // include read. |
4994 | m_registers_flags_types.clear(); |
4995 | m_registers_enum_types.clear(); |
4996 | std::vector<DynamicRegisterInfo::Register> registers; |
4997 | if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, xml_filename: "target.xml", |
4998 | registers) && |
4999 | // Target XML is not required to include register information. |
5000 | !registers.empty()) |
5001 | AddRemoteRegisters(registers, arch_to_use); |
5002 | |
5003 | return m_register_info_sp->GetNumRegisters() > 0; |
5004 | } |
5005 | |
5006 | llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() { |
5007 | // Make sure LLDB has an XML parser it can use first |
5008 | if (!XMLDocument::XMLEnabled()) |
5009 | return llvm::createStringError(EC: llvm::inconvertibleErrorCode(), |
5010 | S: "XML parsing not available"); |
5011 | |
5012 | Log *log = GetLog(mask: LLDBLog::Process); |
5013 | LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__); |
5014 | |
5015 | LoadedModuleInfoList list; |
5016 | GDBRemoteCommunicationClient &comm = m_gdb_comm; |
5017 | bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4(); |
5018 | |
5019 | // check that we have extended feature read support |
5020 | if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) { |
5021 | // request the loaded library list |
5022 | llvm::Expected<std::string> raw = comm.ReadExtFeature(object: "libraries-svr4", annex: ""); |
5023 | if (!raw) |
5024 | return raw.takeError(); |
5025 | |
5026 | // parse the xml file in memory |
5027 | LLDB_LOGF(log, "parsing: %s", raw->c_str()); |
5028 | XMLDocument doc; |
5029 | |
5030 | if (!doc.ParseMemory(xml: raw->c_str(), xml_length: raw->size(), url: "noname.xml")) |
5031 | return llvm::createStringError(EC: llvm::inconvertibleErrorCode(), |
5032 | S: "Error reading noname.xml"); |
5033 | |
5034 | XMLNode root_element = doc.GetRootElement(required_name: "library-list-svr4"); |
5035 | if (!root_element) |
5036 | return llvm::createStringError( |
5037 | EC: llvm::inconvertibleErrorCode(), |
5038 | S: "Error finding library-list-svr4 xml element"); |
5039 | |
5040 | // main link map structure |
5041 | std::string main_lm = root_element.GetAttributeValue(name: "main-lm"); |
5042 | // FIXME: we're silently ignoring invalid data here |
5043 | if (!main_lm.empty()) |
5044 | llvm::to_integer(S: main_lm, Num&: list.m_link_map); |
5045 | |
5046 | root_element.ForEachChildElementWithName( |
5047 | name: "library", callback: [log, &list](const XMLNode &library) -> bool { |
5048 | LoadedModuleInfoList::LoadedModuleInfo module; |
5049 | |
5050 | // FIXME: we're silently ignoring invalid data here |
5051 | library.ForEachAttribute( |
5052 | callback: [&module](const llvm::StringRef &name, |
5053 | const llvm::StringRef &value) -> bool { |
5054 | uint64_t uint_value = LLDB_INVALID_ADDRESS; |
5055 | if (name == "name") |
5056 | module.set_name(value.str()); |
5057 | else if (name == "lm") { |
5058 | // the address of the link_map struct. |
5059 | llvm::to_integer(S: value, Num&: uint_value); |
5060 | module.set_link_map(uint_value); |
5061 | } else if (name == "l_addr") { |
5062 | // the displacement as read from the field 'l_addr' of the |
5063 | // link_map struct. |
5064 | llvm::to_integer(S: value, Num&: uint_value); |
5065 | module.set_base(uint_value); |
5066 | // base address is always a displacement, not an absolute |
5067 | // value. |
5068 | module.set_base_is_offset(true); |
5069 | } else if (name == "l_ld") { |
5070 | // the memory address of the libraries PT_DYNAMIC section. |
5071 | llvm::to_integer(S: value, Num&: uint_value); |
5072 | module.set_dynamic(uint_value); |
5073 | } |
5074 | |
5075 | return true; // Keep iterating over all properties of "library" |
5076 | }); |
5077 | |
5078 | if (log) { |
5079 | std::string name; |
5080 | lldb::addr_t lm = 0, base = 0, ld = 0; |
5081 | bool base_is_offset; |
5082 | |
5083 | module.get_name(out&: name); |
5084 | module.get_link_map(out&: lm); |
5085 | module.get_base(out&: base); |
5086 | module.get_base_is_offset(out&: base_is_offset); |
5087 | module.get_dynamic(out&: ld); |
5088 | |
5089 | LLDB_LOGF(log, |
5090 | "found (link_map:0x%08"PRIx64 ", base:0x%08"PRIx64 |
5091 | "[%s], ld:0x%08"PRIx64 ", name:'%s')", |
5092 | lm, base, (base_is_offset ? "offset": "absolute"), ld, |
5093 | name.c_str()); |
5094 | } |
5095 | |
5096 | list.add(mod: module); |
5097 | return true; // Keep iterating over all "library" elements in the root |
5098 | // node |
5099 | }); |
5100 | |
5101 | if (log) |
5102 | LLDB_LOGF(log, "found %"PRId32 " modules in total", |
5103 | (int)list.m_list.size()); |
5104 | return list; |
5105 | } else if (comm.GetQXferLibrariesReadSupported()) { |
5106 | // request the loaded library list |
5107 | llvm::Expected<std::string> raw = comm.ReadExtFeature(object: "libraries", annex: ""); |
5108 | |
5109 | if (!raw) |
5110 | return raw.takeError(); |
5111 | |
5112 | LLDB_LOGF(log, "parsing: %s", raw->c_str()); |
5113 | XMLDocument doc; |
5114 | |
5115 | if (!doc.ParseMemory(xml: raw->c_str(), xml_length: raw->size(), url: "noname.xml")) |
5116 | return llvm::createStringError(EC: llvm::inconvertibleErrorCode(), |
5117 | S: "Error reading noname.xml"); |
5118 | |
5119 | XMLNode root_element = doc.GetRootElement(required_name: "library-list"); |
5120 | if (!root_element) |
5121 | return llvm::createStringError(EC: llvm::inconvertibleErrorCode(), |
5122 | S: "Error finding library-list xml element"); |
5123 | |
5124 | // FIXME: we're silently ignoring invalid data here |
5125 | root_element.ForEachChildElementWithName( |
5126 | name: "library", callback: [log, &list](const XMLNode &library) -> bool { |
5127 | LoadedModuleInfoList::LoadedModuleInfo module; |
5128 | |
5129 | std::string name = library.GetAttributeValue(name: "name"); |
5130 | module.set_name(name); |
5131 | |
5132 | // The base address of a given library will be the address of its |
5133 | // first section. Most remotes send only one section for Windows |
5134 | // targets for example. |
5135 | const XMLNode §ion = |
5136 | library.FindFirstChildElementWithName(name: "section"); |
5137 | std::string address = section.GetAttributeValue(name: "address"); |
5138 | uint64_t address_value = LLDB_INVALID_ADDRESS; |
5139 | llvm::to_integer(S: address, Num&: address_value); |
5140 | module.set_base(address_value); |
5141 | // These addresses are absolute values. |
5142 | module.set_base_is_offset(false); |
5143 | |
5144 | if (log) { |
5145 | std::string name; |
5146 | lldb::addr_t base = 0; |
5147 | bool base_is_offset; |
5148 | module.get_name(out&: name); |
5149 | module.get_base(out&: base); |
5150 | module.get_base_is_offset(out&: base_is_offset); |
5151 | |
5152 | LLDB_LOGF(log, "found (base:0x%08"PRIx64 "[%s], name:'%s')", base, |
5153 | (base_is_offset ? "offset": "absolute"), name.c_str()); |
5154 | } |
5155 | |
5156 | list.add(mod: module); |
5157 | return true; // Keep iterating over all "library" elements in the root |
5158 | // node |
5159 | }); |
5160 | |
5161 | if (log) |
5162 | LLDB_LOGF(log, "found %"PRId32 " modules in total", |
5163 | (int)list.m_list.size()); |
5164 | return list; |
5165 | } else { |
5166 | return llvm::createStringError(EC: llvm::inconvertibleErrorCode(), |
5167 | S: "Remote libraries not supported"); |
5168 | } |
5169 | } |
5170 | |
5171 | lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file, |
5172 | lldb::addr_t link_map, |
5173 | lldb::addr_t base_addr, |
5174 | bool value_is_offset) { |
5175 | DynamicLoader *loader = GetDynamicLoader(); |
5176 | if (!loader) |
5177 | return nullptr; |
5178 | |
5179 | return loader->LoadModuleAtAddress(file, link_map_addr: link_map, base_addr, |
5180 | base_addr_is_offset: value_is_offset); |
5181 | } |
5182 | |
5183 | llvm::Error ProcessGDBRemote::LoadModules() { |
5184 | using lldb_private::process_gdb_remote::ProcessGDBRemote; |
5185 | |
5186 | // request a list of loaded libraries from GDBServer |
5187 | llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList(); |
5188 | if (!module_list) |
5189 | return module_list.takeError(); |
5190 | |
5191 | // get a list of all the modules |
5192 | ModuleList new_modules; |
5193 | |
5194 | for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) { |
5195 | std::string mod_name; |
5196 | lldb::addr_t mod_base; |
5197 | lldb::addr_t link_map; |
5198 | bool mod_base_is_offset; |
5199 | |
5200 | bool valid = true; |
5201 | valid &= modInfo.get_name(out&: mod_name); |
5202 | valid &= modInfo.get_base(out&: mod_base); |
5203 | valid &= modInfo.get_base_is_offset(out&: mod_base_is_offset); |
5204 | if (!valid) |
5205 | continue; |
5206 | |
5207 | if (!modInfo.get_link_map(out&: link_map)) |
5208 | link_map = LLDB_INVALID_ADDRESS; |
5209 | |
5210 | FileSpec file(mod_name); |
5211 | FileSystem::Instance().Resolve(file_spec&: file); |
5212 | lldb::ModuleSP module_sp = |
5213 | LoadModuleAtAddress(file, link_map, base_addr: mod_base, value_is_offset: mod_base_is_offset); |
5214 | |
5215 | if (module_sp.get()) |
5216 | new_modules.Append(module_sp); |
5217 | } |
5218 | |
5219 | if (new_modules.GetSize() > 0) { |
5220 | ModuleList removed_modules; |
5221 | Target &target = GetTarget(); |
5222 | ModuleList &loaded_modules = m_process->GetTarget().GetImages(); |
5223 | |
5224 | for (size_t i = 0; i < loaded_modules.GetSize(); ++i) { |
5225 | const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(idx: i); |
5226 | |
5227 | bool found = false; |
5228 | for (size_t j = 0; j < new_modules.GetSize(); ++j) { |
5229 | if (new_modules.GetModuleAtIndex(idx: j).get() == loaded_module.get()) |
5230 | found = true; |
5231 | } |
5232 | |
5233 | // The main executable will never be included in libraries-svr4, don't |
5234 | // remove it |
5235 | if (!found && |
5236 | loaded_module.get() != target.GetExecutableModulePointer()) { |
5237 | removed_modules.Append(module_sp: loaded_module); |
5238 | } |
5239 | } |
5240 | |
5241 | loaded_modules.Remove(module_list&: removed_modules); |
5242 | m_process->GetTarget().ModulesDidUnload(module_list&: removed_modules, delete_locations: false); |
5243 | |
5244 | new_modules.ForEach(callback: [&target](const lldb::ModuleSP module_sp) -> bool { |
5245 | lldb_private::ObjectFile *obj = module_sp->GetObjectFile(); |
5246 | if (!obj) |
5247 | return true; |
5248 | |
5249 | if (obj->GetType() != ObjectFile::Type::eTypeExecutable) |
5250 | return true; |
5251 | |
5252 | lldb::ModuleSP module_copy_sp = module_sp; |
5253 | target.SetExecutableModule(module_sp&: module_copy_sp, load_dependent_files: eLoadDependentsNo); |
5254 | return false; |
5255 | }); |
5256 | |
5257 | loaded_modules.AppendIfNeeded(module_list: new_modules); |
5258 | m_process->GetTarget().ModulesDidLoad(module_list&: new_modules); |
5259 | } |
5260 | |
5261 | return llvm::ErrorSuccess(); |
5262 | } |
5263 | |
5264 | Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file, |
5265 | bool &is_loaded, |
5266 | lldb::addr_t &load_addr) { |
5267 | is_loaded = false; |
5268 | load_addr = LLDB_INVALID_ADDRESS; |
5269 | |
5270 | std::string file_path = file.GetPath(denormalize: false); |
5271 | if (file_path.empty()) |
5272 | return Status::FromErrorString(str: "Empty file name specified"); |
5273 | |
5274 | StreamString packet; |
5275 | packet.PutCString(cstr: "qFileLoadAddress:"); |
5276 | packet.PutStringAsRawHex8(s: file_path); |
5277 | |
5278 | StringExtractorGDBRemote response; |
5279 | if (m_gdb_comm.SendPacketAndWaitForResponse(payload: packet.GetString(), response) != |
5280 | GDBRemoteCommunication::PacketResult::Success) |
5281 | return Status::FromErrorString(str: "Sending qFileLoadAddress packet failed"); |
5282 | |
5283 | if (response.IsErrorResponse()) { |
5284 | if (response.GetError() == 1) { |
5285 | // The file is not loaded into the inferior |
5286 | is_loaded = false; |
5287 | load_addr = LLDB_INVALID_ADDRESS; |
5288 | return Status(); |
5289 | } |
5290 | |
5291 | return Status::FromErrorString( |
5292 | str: "Fetching file load address from remote server returned an error"); |
5293 | } |
5294 | |
5295 | if (response.IsNormalResponse()) { |
5296 | is_loaded = true; |
5297 | load_addr = response.GetHexMaxU64(little_endian: false, LLDB_INVALID_ADDRESS); |
5298 | return Status(); |
5299 | } |
5300 | |
5301 | return Status::FromErrorString( |
5302 | str: "Unknown error happened during sending the load address packet"); |
5303 | } |
5304 | |
5305 | void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) { |
5306 | // We must call the lldb_private::Process::ModulesDidLoad () first before we |
5307 | // do anything |
5308 | Process::ModulesDidLoad(module_list); |
5309 | |
5310 | // After loading shared libraries, we can ask our remote GDB server if it |
5311 | // needs any symbols. |
5312 | m_gdb_comm.ServeSymbolLookups(process: this); |
5313 | } |
5314 | |
5315 | void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) { |
5316 | AppendSTDOUT(s: out.data(), len: out.size()); |
5317 | } |
5318 | |
5319 | static const char *end_delimiter = "--end--;"; |
5320 | static const int end_delimiter_len = 8; |
5321 | |
5322 | void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) { |
5323 | std::string input = data.str(); // '1' to move beyond 'A' |
5324 | if (m_partial_profile_data.length() > 0) { |
5325 | m_partial_profile_data.append(str: input); |
5326 | input = m_partial_profile_data; |
5327 | m_partial_profile_data.clear(); |
5328 | } |
5329 | |
5330 | size_t found, pos = 0, len = input.length(); |
5331 | while ((found = input.find(s: end_delimiter, pos: pos)) != std::string::npos) { |
5332 | StringExtractorGDBRemote profileDataExtractor( |
5333 | input.substr(pos: pos, n: found).c_str()); |
5334 | std::string profile_data = |
5335 | HarmonizeThreadIdsForProfileData(inputStringExtractor&: profileDataExtractor); |
5336 | BroadcastAsyncProfileData(one_profile_data: profile_data); |
5337 | |
5338 | pos = found + end_delimiter_len; |
5339 | } |
5340 | |
5341 | if (pos < len) { |
5342 | // Last incomplete chunk. |
5343 | m_partial_profile_data = input.substr(pos: pos); |
5344 | } |
5345 | } |
5346 | |
5347 | std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData( |
5348 | StringExtractorGDBRemote &profileDataExtractor) { |
5349 | std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map; |
5350 | std::string output; |
5351 | llvm::raw_string_ostream output_stream(output); |
5352 | llvm::StringRef name, value; |
5353 | |
5354 | // Going to assuming thread_used_usec comes first, else bail out. |
5355 | while (profileDataExtractor.GetNameColonValue(name, value)) { |
5356 | if (name.compare(RHS: "thread_used_id") == 0) { |
5357 | StringExtractor threadIDHexExtractor(value); |
5358 | uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(little_endian: false, fail_value: 0); |
5359 | |
5360 | bool has_used_usec = false; |
5361 | uint32_t curr_used_usec = 0; |
5362 | llvm::StringRef usec_name, usec_value; |
5363 | uint32_t input_file_pos = profileDataExtractor.GetFilePos(); |
5364 | if (profileDataExtractor.GetNameColonValue(name&: usec_name, value&: usec_value)) { |
5365 | if (usec_name == "thread_used_usec") { |
5366 | has_used_usec = true; |
5367 | usec_value.getAsInteger(Radix: 0, Result&: curr_used_usec); |
5368 | } else { |
5369 | // We didn't find what we want, it is probably an older version. Bail |
5370 | // out. |
5371 | profileDataExtractor.SetFilePos(input_file_pos); |
5372 | } |
5373 | } |
5374 | |
5375 | if (has_used_usec) { |
5376 | uint32_t prev_used_usec = 0; |
5377 | std::map<uint64_t, uint32_t>::iterator iterator = |
5378 | m_thread_id_to_used_usec_map.find(x: thread_id); |
5379 | if (iterator != m_thread_id_to_used_usec_map.end()) |
5380 | prev_used_usec = iterator->second; |
5381 | |
5382 | uint32_t real_used_usec = curr_used_usec - prev_used_usec; |
5383 | // A good first time record is one that runs for at least 0.25 sec |
5384 | bool good_first_time = |
5385 | (prev_used_usec == 0) && (real_used_usec > 250000); |
5386 | bool good_subsequent_time = |
5387 | (prev_used_usec > 0) && |
5388 | ((real_used_usec > 0) || (HasAssignedIndexIDToThread(sb_thread_id: thread_id))); |
5389 | |
5390 | if (good_first_time || good_subsequent_time) { |
5391 | // We try to avoid doing too many index id reservation, resulting in |
5392 | // fast increase of index ids. |
5393 | |
5394 | output_stream << name << ":"; |
5395 | int32_t index_id = AssignIndexIDToThread(thread_id); |
5396 | output_stream << index_id << ";"; |
5397 | |
5398 | output_stream << usec_name << ":"<< usec_value << ";"; |
5399 | } else { |
5400 | // Skip past 'thread_used_name'. |
5401 | llvm::StringRef local_name, local_value; |
5402 | profileDataExtractor.GetNameColonValue(name&: local_name, value&: local_value); |
5403 | } |
5404 | |
5405 | // Store current time as previous time so that they can be compared |
5406 | // later. |
5407 | new_thread_id_to_used_usec_map[thread_id] = curr_used_usec; |
5408 | } else { |
5409 | // Bail out and use old string. |
5410 | output_stream << name << ":"<< value << ";"; |
5411 | } |
5412 | } else { |
5413 | output_stream << name << ":"<< value << ";"; |
5414 | } |
5415 | } |
5416 | output_stream << end_delimiter; |
5417 | m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map; |
5418 | |
5419 | return output; |
5420 | } |
5421 | |
5422 | void ProcessGDBRemote::HandleStopReply() { |
5423 | if (GetStopID() != 0) |
5424 | return; |
5425 | |
5426 | if (GetID() == LLDB_INVALID_PROCESS_ID) { |
5427 | lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); |
5428 | if (pid != LLDB_INVALID_PROCESS_ID) |
5429 | SetID(pid); |
5430 | } |
5431 | BuildDynamicRegisterInfo(force: true); |
5432 | } |
5433 | |
5434 | llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) { |
5435 | if (!m_gdb_comm.GetSaveCoreSupported()) |
5436 | return false; |
5437 | |
5438 | StreamString packet; |
5439 | packet.PutCString(cstr: "qSaveCore;path-hint:"); |
5440 | packet.PutStringAsRawHex8(s: outfile); |
5441 | |
5442 | StringExtractorGDBRemote response; |
5443 | if (m_gdb_comm.SendPacketAndWaitForResponse(payload: packet.GetString(), response) == |
5444 | GDBRemoteCommunication::PacketResult::Success) { |
5445 | // TODO: grab error message from the packet? StringExtractor seems to |
5446 | // be missing a method for that |
5447 | if (response.IsErrorResponse()) |
5448 | return llvm::createStringError( |
5449 | EC: llvm::inconvertibleErrorCode(), |
5450 | S: llvm::formatv(Fmt: "qSaveCore returned an error")); |
5451 | |
5452 | std::string path; |
5453 | |
5454 | // process the response |
5455 | for (auto x : llvm::split(Str: response.GetStringRef(), Separator: ';')) { |
5456 | if (x.consume_front(Prefix: "core-path:")) |
5457 | StringExtractor(x).GetHexByteString(str&: path); |
5458 | } |
5459 | |
5460 | // verify that we've gotten what we need |
5461 | if (path.empty()) |
5462 | return llvm::createStringError(EC: llvm::inconvertibleErrorCode(), |
5463 | S: "qSaveCore returned no core path"); |
5464 | |
5465 | // now transfer the core file |
5466 | FileSpec remote_core{llvm::StringRef(path)}; |
5467 | Platform &platform = *GetTarget().GetPlatform(); |
5468 | Status error = platform.GetFile(source: remote_core, destination: FileSpec(outfile)); |
5469 | |
5470 | if (platform.IsRemote()) { |
5471 | // NB: we unlink the file on error too |
5472 | platform.Unlink(file_spec: remote_core); |
5473 | if (error.Fail()) |
5474 | return error.ToError(); |
5475 | } |
5476 | |
5477 | return true; |
5478 | } |
5479 | |
5480 | return llvm::createStringError(EC: llvm::inconvertibleErrorCode(), |
5481 | S: "Unable to send qSaveCore"); |
5482 | } |
5483 | |
5484 | static const char *const s_async_json_packet_prefix = "JSON-async:"; |
5485 | |
5486 | static StructuredData::ObjectSP |
5487 | ParseStructuredDataPacket(llvm::StringRef packet) { |
5488 | Log *log = GetLog(mask: GDBRLog::Process); |
5489 | |
5490 | if (!packet.consume_front(Prefix: s_async_json_packet_prefix)) { |
5491 | if (log) { |
5492 | LLDB_LOGF( |
5493 | log, |
5494 | "GDBRemoteCommunicationClientBase::%s() received $J packet " |
5495 | "but was not a StructuredData packet: packet starts with " |
5496 | "%s", |
5497 | __FUNCTION__, |
5498 | packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str()); |
5499 | } |
5500 | return StructuredData::ObjectSP(); |
5501 | } |
5502 | |
5503 | // This is an asynchronous JSON packet, destined for a StructuredDataPlugin. |
5504 | StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(json_text: packet); |
5505 | if (log) { |
5506 | if (json_sp) { |
5507 | StreamString json_str; |
5508 | json_sp->Dump(s&: json_str, pretty_print: true); |
5509 | json_str.Flush(); |
5510 | LLDB_LOGF(log, |
5511 | "ProcessGDBRemote::%s() " |
5512 | "received Async StructuredData packet: %s", |
5513 | __FUNCTION__, json_str.GetData()); |
5514 | } else { |
5515 | LLDB_LOGF(log, |
5516 | "ProcessGDBRemote::%s" |
5517 | "() received StructuredData packet:" |
5518 | " parse failure", |
5519 | __FUNCTION__); |
5520 | } |
5521 | } |
5522 | return json_sp; |
5523 | } |
5524 | |
5525 | void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) { |
5526 | auto structured_data_sp = ParseStructuredDataPacket(packet: data); |
5527 | if (structured_data_sp) |
5528 | RouteAsyncStructuredData(object_sp: structured_data_sp); |
5529 | } |
5530 | |
5531 | class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed { |
5532 | public: |
5533 | CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) |
5534 | : CommandObjectParsed(interpreter, "process plugin packet speed-test", |
5535 | "Tests packet speeds of various sizes to determine " |
5536 | "the performance characteristics of the GDB remote " |
5537 | "connection. ", |
5538 | nullptr), |
5539 | m_option_group(), |
5540 | m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, |
5541 | "The number of packets to send of each varying size " |
5542 | "(default is 1000).", |
5543 | 1000), |
5544 | m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, |
5545 | "The maximum number of bytes to send in a packet. Sizes " |
5546 | "increase in powers of 2 while the size is less than or " |
5547 | "equal to this option value. (default 1024).", |
5548 | 1024), |
5549 | m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, |
5550 | "The maximum number of bytes to receive in a packet. Sizes " |
5551 | "increase in powers of 2 while the size is less than or " |
5552 | "equal to this option value. (default 1024).", |
5553 | 1024), |
5554 | m_json(LLDB_OPT_SET_1, false, "json", 'j', |
5555 | "Print the output as JSON data for easy parsing.", false, true) { |
5556 | m_option_group.Append(group: &m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); |
5557 | m_option_group.Append(group: &m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); |
5558 | m_option_group.Append(group: &m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); |
5559 | m_option_group.Append(group: &m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); |
5560 | m_option_group.Finalize(); |
5561 | } |
5562 | |
5563 | ~CommandObjectProcessGDBRemoteSpeedTest() override = default; |
5564 | |
5565 | Options *GetOptions() override { return &m_option_group; } |
5566 | |
5567 | void DoExecute(Args &command, CommandReturnObject &result) override { |
5568 | const size_t argc = command.GetArgumentCount(); |
5569 | if (argc == 0) { |
5570 | ProcessGDBRemote *process = |
5571 | (ProcessGDBRemote *)m_interpreter.GetExecutionContext() |
5572 | .GetProcessPtr(); |
5573 | if (process) { |
5574 | StreamSP output_stream_sp = result.GetImmediateOutputStream(); |
5575 | if (!output_stream_sp) |
5576 | output_stream_sp = m_interpreter.GetDebugger().GetAsyncOutputStream(); |
5577 | result.SetImmediateOutputStream(output_stream_sp); |
5578 | |
5579 | const uint32_t num_packets = |
5580 | (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue(); |
5581 | const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue(); |
5582 | const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue(); |
5583 | const bool json = m_json.GetOptionValue().GetCurrentValue(); |
5584 | const uint64_t k_recv_amount = |
5585 | 4 * 1024 * 1024; // Receive amount in bytes |
5586 | process->GetGDBRemote().TestPacketSpeed( |
5587 | num_packets, max_send, max_recv, recv_amount: k_recv_amount, json, |
5588 | strm&: output_stream_sp ? *output_stream_sp : result.GetOutputStream()); |
5589 | result.SetStatus(eReturnStatusSuccessFinishResult); |
5590 | return; |
5591 | } |
5592 | } else { |
5593 | result.AppendErrorWithFormat(format: "'%s' takes no arguments", |
5594 | m_cmd_name.c_str()); |
5595 | } |
5596 | result.SetStatus(eReturnStatusFailed); |
5597 | } |
5598 | |
5599 | protected: |
5600 | OptionGroupOptions m_option_group; |
5601 | OptionGroupUInt64 m_num_packets; |
5602 | OptionGroupUInt64 m_max_send; |
5603 | OptionGroupUInt64 m_max_recv; |
5604 | OptionGroupBoolean m_json; |
5605 | }; |
5606 | |
5607 | class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed { |
5608 | private: |
5609 | public: |
5610 | CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) |
5611 | : CommandObjectParsed(interpreter, "process plugin packet history", |
5612 | "Dumps the packet history buffer. ", nullptr) {} |
5613 | |
5614 | ~CommandObjectProcessGDBRemotePacketHistory() override = default; |
5615 | |
5616 | void DoExecute(Args &command, CommandReturnObject &result) override { |
5617 | ProcessGDBRemote *process = |
5618 | (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); |
5619 | if (process) { |
5620 | process->DumpPluginHistory(s&: result.GetOutputStream()); |
5621 | result.SetStatus(eReturnStatusSuccessFinishResult); |
5622 | return; |
5623 | } |
5624 | result.SetStatus(eReturnStatusFailed); |
5625 | } |
5626 | }; |
5627 | |
5628 | class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed { |
5629 | private: |
5630 | public: |
5631 | CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) |
5632 | : CommandObjectParsed( |
5633 | interpreter, "process plugin packet xfer-size", |
5634 | "Maximum size that lldb will try to read/write one one chunk.", |
5635 | nullptr) { |
5636 | AddSimpleArgumentList(arg_type: eArgTypeUnsignedInteger); |
5637 | } |
5638 | |
5639 | ~CommandObjectProcessGDBRemotePacketXferSize() override = default; |
5640 | |
5641 | void DoExecute(Args &command, CommandReturnObject &result) override { |
5642 | const size_t argc = command.GetArgumentCount(); |
5643 | if (argc == 0) { |
5644 | result.AppendErrorWithFormat(format: "'%s' takes an argument to specify the max " |
5645 | "amount to be transferred when " |
5646 | "reading/writing", |
5647 | m_cmd_name.c_str()); |
5648 | return; |
5649 | } |
5650 | |
5651 | ProcessGDBRemote *process = |
5652 | (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); |
5653 | if (process) { |
5654 | const char *packet_size = command.GetArgumentAtIndex(idx: 0); |
5655 | errno = 0; |
5656 | uint64_t user_specified_max = strtoul(nptr: packet_size, endptr: nullptr, base: 10); |
5657 | if (errno == 0 && user_specified_max != 0) { |
5658 | process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max); |
5659 | result.SetStatus(eReturnStatusSuccessFinishResult); |
5660 | return; |
5661 | } |
5662 | } |
5663 | result.SetStatus(eReturnStatusFailed); |
5664 | } |
5665 | }; |
5666 | |
5667 | class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed { |
5668 | private: |
5669 | public: |
5670 | CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) |
5671 | : CommandObjectParsed(interpreter, "process plugin packet send", |
5672 | "Send a custom packet through the GDB remote " |
5673 | "protocol and print the answer. " |
5674 | "The packet header and footer will automatically " |
5675 | "be added to the packet prior to sending and " |
5676 | "stripped from the result.", |
5677 | nullptr) { |
5678 | AddSimpleArgumentList(arg_type: eArgTypeNone, repetition_type: eArgRepeatStar); |
5679 | } |
5680 | |
5681 | ~CommandObjectProcessGDBRemotePacketSend() override = default; |
5682 | |
5683 | void DoExecute(Args &command, CommandReturnObject &result) override { |
5684 | const size_t argc = command.GetArgumentCount(); |
5685 | if (argc == 0) { |
5686 | result.AppendErrorWithFormat( |
5687 | format: "'%s' takes a one or more packet content arguments", |
5688 | m_cmd_name.c_str()); |
5689 | return; |
5690 | } |
5691 | |
5692 | ProcessGDBRemote *process = |
5693 | (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); |
5694 | if (process) { |
5695 | for (size_t i = 0; i < argc; ++i) { |
5696 | const char *packet_cstr = command.GetArgumentAtIndex(idx: 0); |
5697 | StringExtractorGDBRemote response; |
5698 | process->GetGDBRemote().SendPacketAndWaitForResponse( |
5699 | payload: packet_cstr, response, interrupt_timeout: process->GetInterruptTimeout()); |
5700 | result.SetStatus(eReturnStatusSuccessFinishResult); |
5701 | Stream &output_strm = result.GetOutputStream(); |
5702 | output_strm.Printf(format: " packet: %s\n", packet_cstr); |
5703 | std::string response_str = std::string(response.GetStringRef()); |
5704 | |
5705 | if (strstr(haystack: packet_cstr, needle: "qGetProfileData") != nullptr) { |
5706 | response_str = process->HarmonizeThreadIdsForProfileData(profileDataExtractor&: response); |
5707 | } |
5708 | |
5709 | if (response_str.empty()) |
5710 | output_strm.PutCString(cstr: "response: \nerror: UNIMPLEMENTED\n"); |
5711 | else |
5712 | output_strm.Printf(format: "response: %s\n", response.GetStringRef().data()); |
5713 | } |
5714 | } |
5715 | } |
5716 | }; |
5717 | |
5718 | class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw { |
5719 | private: |
5720 | public: |
5721 | CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) |
5722 | : CommandObjectRaw(interpreter, "process plugin packet monitor", |
5723 | "Send a qRcmd packet through the GDB remote protocol " |
5724 | "and print the response." |
5725 | "The argument passed to this command will be hex " |
5726 | "encoded into a valid 'qRcmd' packet, sent and the " |
5727 | "response will be printed.") {} |
5728 | |
5729 | ~CommandObjectProcessGDBRemotePacketMonitor() override = default; |
5730 | |
5731 | void DoExecute(llvm::StringRef command, |
5732 | CommandReturnObject &result) override { |
5733 | if (command.empty()) { |
5734 | result.AppendErrorWithFormat(format: "'%s' takes a command string argument", |
5735 | m_cmd_name.c_str()); |
5736 | return; |
5737 | } |
5738 | |
5739 | ProcessGDBRemote *process = |
5740 | (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); |
5741 | if (process) { |
5742 | StreamString packet; |
5743 | packet.PutCString(cstr: "qRcmd,"); |
5744 | packet.PutBytesAsRawHex8(src: command.data(), src_len: command.size()); |
5745 | |
5746 | StringExtractorGDBRemote response; |
5747 | Stream &output_strm = result.GetOutputStream(); |
5748 | process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport( |
5749 | payload: packet.GetString(), response, interrupt_timeout: process->GetInterruptTimeout(), |
5750 | output_callback: [&output_strm](llvm::StringRef output) { output_strm << output; }); |
5751 | result.SetStatus(eReturnStatusSuccessFinishResult); |
5752 | output_strm.Printf(format: " packet: %s\n", packet.GetData()); |
5753 | const std::string &response_str = std::string(response.GetStringRef()); |
5754 | |
5755 | if (response_str.empty()) |
5756 | output_strm.PutCString(cstr: "response: \nerror: UNIMPLEMENTED\n"); |
5757 | else |
5758 | output_strm.Printf(format: "response: %s\n", response.GetStringRef().data()); |
5759 | } |
5760 | } |
5761 | }; |
5762 | |
5763 | class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword { |
5764 | private: |
5765 | public: |
5766 | CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) |
5767 | : CommandObjectMultiword(interpreter, "process plugin packet", |
5768 | "Commands that deal with GDB remote packets.", |
5769 | nullptr) { |
5770 | LoadSubCommand( |
5771 | cmd_name: "history", |
5772 | command_obj: CommandObjectSP( |
5773 | new CommandObjectProcessGDBRemotePacketHistory(interpreter))); |
5774 | LoadSubCommand( |
5775 | cmd_name: "send", command_obj: CommandObjectSP( |
5776 | new CommandObjectProcessGDBRemotePacketSend(interpreter))); |
5777 | LoadSubCommand( |
5778 | cmd_name: "monitor", |
5779 | command_obj: CommandObjectSP( |
5780 | new CommandObjectProcessGDBRemotePacketMonitor(interpreter))); |
5781 | LoadSubCommand( |
5782 | cmd_name: "xfer-size", |
5783 | command_obj: CommandObjectSP( |
5784 | new CommandObjectProcessGDBRemotePacketXferSize(interpreter))); |
5785 | LoadSubCommand(cmd_name: "speed-test", |
5786 | command_obj: CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest( |
5787 | interpreter))); |
5788 | } |
5789 | |
5790 | ~CommandObjectProcessGDBRemotePacket() override = default; |
5791 | }; |
5792 | |
5793 | class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword { |
5794 | public: |
5795 | CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter) |
5796 | : CommandObjectMultiword( |
5797 | interpreter, "process plugin", |
5798 | "Commands for operating on a ProcessGDBRemote process.", |
5799 | "process plugin <subcommand> [<subcommand-options>]") { |
5800 | LoadSubCommand( |
5801 | cmd_name: "packet", |
5802 | command_obj: CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter))); |
5803 | } |
5804 | |
5805 | ~CommandObjectMultiwordProcessGDBRemote() override = default; |
5806 | }; |
5807 | |
5808 | CommandObject *ProcessGDBRemote::GetPluginCommandObject() { |
5809 | if (!m_command_sp) |
5810 | m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>( |
5811 | args&: GetTarget().GetDebugger().GetCommandInterpreter()); |
5812 | return m_command_sp.get(); |
5813 | } |
5814 | |
5815 | void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable) { |
5816 | GetBreakpointSiteList().ForEach(callback: [this, enable](BreakpointSite *bp_site) { |
5817 | if (bp_site->IsEnabled() && |
5818 | (bp_site->GetType() == BreakpointSite::eSoftware || |
5819 | bp_site->GetType() == BreakpointSite::eExternal)) { |
5820 | m_gdb_comm.SendGDBStoppointTypePacket( |
5821 | type: eBreakpointSoftware, insert: enable, addr: bp_site->GetLoadAddress(), |
5822 | length: GetSoftwareBreakpointTrapOpcode(bp_site), interrupt_timeout: GetInterruptTimeout()); |
5823 | } |
5824 | }); |
5825 | } |
5826 | |
5827 | void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable) { |
5828 | if (m_gdb_comm.SupportsGDBStoppointPacket(type: eBreakpointHardware)) { |
5829 | GetBreakpointSiteList().ForEach(callback: [this, enable](BreakpointSite *bp_site) { |
5830 | if (bp_site->IsEnabled() && |
5831 | bp_site->GetType() == BreakpointSite::eHardware) { |
5832 | m_gdb_comm.SendGDBStoppointTypePacket( |
5833 | type: eBreakpointHardware, insert: enable, addr: bp_site->GetLoadAddress(), |
5834 | length: GetSoftwareBreakpointTrapOpcode(bp_site), interrupt_timeout: GetInterruptTimeout()); |
5835 | } |
5836 | }); |
5837 | } |
5838 | |
5839 | for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) { |
5840 | addr_t addr = wp_res_sp->GetLoadAddress(); |
5841 | size_t size = wp_res_sp->GetByteSize(); |
5842 | GDBStoppointType type = GetGDBStoppointType(wp_res_sp); |
5843 | m_gdb_comm.SendGDBStoppointTypePacket(type, insert: enable, addr, length: size, |
5844 | interrupt_timeout: GetInterruptTimeout()); |
5845 | } |
5846 | } |
5847 | |
5848 | void ProcessGDBRemote::DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) { |
5849 | Log *log = GetLog(mask: GDBRLog::Process); |
5850 | |
5851 | lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID(); |
5852 | // Any valid TID will suffice, thread-relevant actions will set a proper TID |
5853 | // anyway. |
5854 | lldb::tid_t parent_tid = m_thread_ids.front(); |
5855 | |
5856 | lldb::pid_t follow_pid, detach_pid; |
5857 | lldb::tid_t follow_tid, detach_tid; |
5858 | |
5859 | switch (GetFollowForkMode()) { |
5860 | case eFollowParent: |
5861 | follow_pid = parent_pid; |
5862 | follow_tid = parent_tid; |
5863 | detach_pid = child_pid; |
5864 | detach_tid = child_tid; |
5865 | break; |
5866 | case eFollowChild: |
5867 | follow_pid = child_pid; |
5868 | follow_tid = child_tid; |
5869 | detach_pid = parent_pid; |
5870 | detach_tid = parent_tid; |
5871 | break; |
5872 | } |
5873 | |
5874 | // Switch to the process that is going to be detached. |
5875 | if (!m_gdb_comm.SetCurrentThread(tid: detach_tid, pid: detach_pid)) { |
5876 | LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid"); |
5877 | return; |
5878 | } |
5879 | |
5880 | // Disable all software breakpoints in the forked process. |
5881 | if (m_gdb_comm.SupportsGDBStoppointPacket(type: eBreakpointSoftware)) |
5882 | DidForkSwitchSoftwareBreakpoints(enable: false); |
5883 | |
5884 | // Remove hardware breakpoints / watchpoints from parent process if we're |
5885 | // following child. |
5886 | if (GetFollowForkMode() == eFollowChild) |
5887 | DidForkSwitchHardwareTraps(enable: false); |
5888 | |
5889 | // Switch to the process that is going to be followed |
5890 | if (!m_gdb_comm.SetCurrentThread(tid: follow_tid, pid: follow_pid) || |
5891 | !m_gdb_comm.SetCurrentThreadForRun(tid: follow_tid, pid: follow_pid)) { |
5892 | LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid"); |
5893 | return; |
5894 | } |
5895 | |
5896 | LLDB_LOG(log, "Detaching process {0}", detach_pid); |
5897 | Status error = m_gdb_comm.Detach(keep_stopped: false, pid: detach_pid); |
5898 | if (error.Fail()) { |
5899 | LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}", |
5900 | error.AsCString() ? error.AsCString() : "<unknown error>"); |
5901 | return; |
5902 | } |
5903 | |
5904 | // Hardware breakpoints/watchpoints are not inherited implicitly, |
5905 | // so we need to readd them if we're following child. |
5906 | if (GetFollowForkMode() == eFollowChild) { |
5907 | DidForkSwitchHardwareTraps(enable: true); |
5908 | // Update our PID |
5909 | SetID(child_pid); |
5910 | } |
5911 | } |
5912 | |
5913 | void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) { |
5914 | Log *log = GetLog(mask: GDBRLog::Process); |
5915 | |
5916 | LLDB_LOG( |
5917 | log, |
5918 | "ProcessGDBRemote::DidFork() called for child_pid: {0}, child_tid {1}", |
5919 | child_pid, child_tid); |
5920 | ++m_vfork_in_progress_count; |
5921 | |
5922 | // Disable all software breakpoints for the duration of vfork. |
5923 | if (m_gdb_comm.SupportsGDBStoppointPacket(type: eBreakpointSoftware)) |
5924 | DidForkSwitchSoftwareBreakpoints(enable: false); |
5925 | |
5926 | lldb::pid_t detach_pid; |
5927 | lldb::tid_t detach_tid; |
5928 | |
5929 | switch (GetFollowForkMode()) { |
5930 | case eFollowParent: |
5931 | detach_pid = child_pid; |
5932 | detach_tid = child_tid; |
5933 | break; |
5934 | case eFollowChild: |
5935 | detach_pid = m_gdb_comm.GetCurrentProcessID(); |
5936 | // Any valid TID will suffice, thread-relevant actions will set a proper TID |
5937 | // anyway. |
5938 | detach_tid = m_thread_ids.front(); |
5939 | |
5940 | // Switch to the parent process before detaching it. |
5941 | if (!m_gdb_comm.SetCurrentThread(tid: detach_tid, pid: detach_pid)) { |
5942 | LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid"); |
5943 | return; |
5944 | } |
5945 | |
5946 | // Remove hardware breakpoints / watchpoints from the parent process. |
5947 | DidForkSwitchHardwareTraps(enable: false); |
5948 | |
5949 | // Switch to the child process. |
5950 | if (!m_gdb_comm.SetCurrentThread(tid: child_tid, pid: child_pid) || |
5951 | !m_gdb_comm.SetCurrentThreadForRun(tid: child_tid, pid: child_pid)) { |
5952 | LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid"); |
5953 | return; |
5954 | } |
5955 | break; |
5956 | } |
5957 | |
5958 | LLDB_LOG(log, "Detaching process {0}", detach_pid); |
5959 | Status error = m_gdb_comm.Detach(keep_stopped: false, pid: detach_pid); |
5960 | if (error.Fail()) { |
5961 | LLDB_LOG(log, |
5962 | "ProcessGDBRemote::DidFork() detach packet send failed: {0}", |
5963 | error.AsCString() ? error.AsCString() : "<unknown error>"); |
5964 | return; |
5965 | } |
5966 | |
5967 | if (GetFollowForkMode() == eFollowChild) { |
5968 | // Update our PID |
5969 | SetID(child_pid); |
5970 | } |
5971 | } |
5972 | |
5973 | void ProcessGDBRemote::DidVForkDone() { |
5974 | assert(m_vfork_in_progress_count > 0); |
5975 | --m_vfork_in_progress_count; |
5976 | |
5977 | // Reenable all software breakpoints that were enabled before vfork. |
5978 | if (m_gdb_comm.SupportsGDBStoppointPacket(type: eBreakpointSoftware)) |
5979 | DidForkSwitchSoftwareBreakpoints(enable: true); |
5980 | } |
5981 | |
5982 | void ProcessGDBRemote::DidExec() { |
5983 | // If we are following children, vfork is finished by exec (rather than |
5984 | // vforkdone that is submitted for parent). |
5985 | if (GetFollowForkMode() == eFollowChild) { |
5986 | if (m_vfork_in_progress_count > 0) |
5987 | --m_vfork_in_progress_count; |
5988 | } |
5989 | Process::DidExec(); |
5990 | } |
5991 |
Definitions
- DumpProcessGDBRemotePacketHistory
- PluginProperties
- GetSettingName
- PluginProperties
- ~PluginProperties
- GetPacketTimeout
- SetPacketTimeout
- GetTargetDefinitionFile
- GetUseSVR4
- GetUseGPacketForReading
- ResumeTimeout
- GetGlobalPluginProperties
- GetPluginDescriptionStatic
- Terminate
- CreateInstance
- DumpPluginHistory
- GetPacketTimeout
- GetSystemArchitecture
- CanDebug
- ProcessGDBRemote
- ~ProcessGDBRemote
- ParsePythonTargetDefinition
- SplitCommaSeparatedRegisterNumberString
- BuildDynamicRegisterInfo
- DoWillLaunch
- DoWillAttachToProcessWithID
- DoWillAttachToProcessWithName
- DoConnectRemote
- WillLaunchOrAttach
- DoLaunch
- ConnectToDebugserver
- DidLaunchOrAttach
- LoadStubBinaries
- MaybeLoadExecutableModule
- DidLaunch
- DoAttachToProcessWithID
- DoAttachToProcessWithName
- TraceSupported
- TraceStop
- TraceStart
- TraceGetState
- TraceGetBinaryData
- DidExit
- DidAttach
- WillResume
- SupportsReverseDirection
- DoResume
- ClearThreadIDList
- UpdateThreadIDsFromStopReplyThreadsValue
- UpdateThreadPCsFromStopReplyThreadsValue
- UpdateThreadIDList
- DoUpdateThreadList
- SetThreadPc
- GetThreadStopInfoFromJSON
- CalculateThreadStopInfo
- ParseExpeditedRegisters
- SetThreadStopInfo
- HandleThreadAsyncInterrupt
- SetThreadStopInfo
- SetThreadStopInfo
- RefreshStateAfterStop
- DoHalt
- DoDetach
- DoDestroy
- RemoveNewThreadBreakpoints
- SetLastStopPacket
- SetUnixSignals
- IsAlive
- GetImageInfoAddress
- WillPublicStop
- DoReadMemory
- SupportsMemoryTagging
- DoReadMemoryTags
- DoWriteMemoryTags
- WriteObjectFile
- HasErased
- FlashErase
- FlashDone
- DoWriteMemory
- DoAllocateMemory
- DoGetMemoryRegionInfo
- GetWatchpointSlotCount
- DoGetWatchpointReportedAfter
- DoDeallocateMemory
- PutSTDIN
- EnableBreakpointSite
- DisableBreakpointSite
- GetGDBStoppointType
- EnableWatchpoint
- DisableWatchpoint
- Clear
- DoSignal
- EstablishConnectionIfNeeded
- SetCloexecFlag
- LaunchAndConnectToDebugserver
- MonitorDebugserverProcess
- KillDebugserverProcess
- Initialize
- DebuggerInitialize
- StartAsyncThread
- StopAsyncThread
- AsyncThread
- NewThreadNotifyBreakpointHit
- UpdateAutomaticSignalFiltering
- StartNoticingNewThreads
- StopNoticingNewThreads
- GetDynamicLoader
- SendEventData
- GetAuxvData
- GetExtendedInfoForThread
- GetLoadedDynamicLibrariesInfos
- GetLoadedDynamicLibrariesInfos
- GetLoadedDynamicLibrariesInfos
- GetLoadedDynamicLibrariesInfos_sender
- GetDynamicLoaderProcessState
- GetSharedCacheInfo
- ConfigureStructuredData
- GetMaxMemorySize
- SetUserSpecifiedMaxMemoryTransferSize
- GetModuleSpec
- PrefetchModuleSpecs
- GetHostOSVersion
- GetHostMacCatalystVersion
- RegisterSetInfo
- GdbServerTargetInfo
- ParseEnumEvalues
- ParseEnums
- ParseFlagsFields
- ParseFlags
- ParseRegisters
- GetGDBServerRegisterInfoXMLAndProcess
- AddRemoteRegisters
- GetGDBServerRegisterInfo
- GetLoadedModuleList
- LoadModuleAtAddress
- LoadModules
- GetFileLoadAddress
- ModulesDidLoad
- HandleAsyncStdout
- end_delimiter
- end_delimiter_len
- HandleAsyncMisc
- HarmonizeThreadIdsForProfileData
- HandleStopReply
- SaveCore
- s_async_json_packet_prefix
- ParseStructuredDataPacket
- HandleAsyncStructuredDataPacket
- CommandObjectProcessGDBRemoteSpeedTest
- CommandObjectProcessGDBRemoteSpeedTest
- ~CommandObjectProcessGDBRemoteSpeedTest
- GetOptions
- DoExecute
- CommandObjectProcessGDBRemotePacketHistory
- CommandObjectProcessGDBRemotePacketHistory
- ~CommandObjectProcessGDBRemotePacketHistory
- DoExecute
- CommandObjectProcessGDBRemotePacketXferSize
- CommandObjectProcessGDBRemotePacketXferSize
- ~CommandObjectProcessGDBRemotePacketXferSize
- DoExecute
- CommandObjectProcessGDBRemotePacketSend
- CommandObjectProcessGDBRemotePacketSend
- ~CommandObjectProcessGDBRemotePacketSend
- DoExecute
- CommandObjectProcessGDBRemotePacketMonitor
- CommandObjectProcessGDBRemotePacketMonitor
- ~CommandObjectProcessGDBRemotePacketMonitor
- DoExecute
- CommandObjectProcessGDBRemotePacket
- CommandObjectProcessGDBRemotePacket
- ~CommandObjectProcessGDBRemotePacket
- CommandObjectMultiwordProcessGDBRemote
- CommandObjectMultiwordProcessGDBRemote
- ~CommandObjectMultiwordProcessGDBRemote
- GetPluginCommandObject
- DidForkSwitchSoftwareBreakpoints
- DidForkSwitchHardwareTraps
- DidFork
- DidVFork
- DidVForkDone
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more