Bug Summary

File:tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
Warning:line 3288, column 7
Value stored to 'error_string' is never read

Annotated Source Code

1//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Host/Config.h"
11
12// C Includes
13#include <errno(*__errno_location ()).h>
14#include <stdlib.h>
15#ifndef LLDB_DISABLE_POSIX
16#include <netinet/in.h>
17#include <sys/mman.h> // for mmap
18#include <sys/socket.h>
19#include <unistd.h>
20#endif
21#include <sys/stat.h>
22#include <sys/types.h>
23#include <time.h>
24
25// C++ Includes
26#include <algorithm>
27#include <map>
28#include <mutex>
29#include <sstream>
30
31#include "lldb/Breakpoint/Watchpoint.h"
32#include "lldb/Core/ArchSpec.h"
33#include "lldb/Core/Debugger.h"
34#include "lldb/Core/Module.h"
35#include "lldb/Core/ModuleSpec.h"
36#include "lldb/Core/PluginManager.h"
37#include "lldb/Core/State.h"
38#include "lldb/Core/StreamFile.h"
39#include "lldb/Core/Value.h"
40#include "lldb/DataFormatters/FormatManager.h"
41#include "lldb/Host/ConnectionFileDescriptor.h"
42#include "lldb/Host/FileSystem.h"
43#include "lldb/Host/HostThread.h"
44#include "lldb/Host/PosixApi.h"
45#include "lldb/Host/PseudoTerminal.h"
46#include "lldb/Host/StringConvert.h"
47#include "lldb/Host/Symbols.h"
48#include "lldb/Host/ThreadLauncher.h"
49#include "lldb/Host/XML.h"
50#include "lldb/Interpreter/Args.h"
51#include "lldb/Interpreter/CommandInterpreter.h"
52#include "lldb/Interpreter/CommandObject.h"
53#include "lldb/Interpreter/CommandObjectMultiword.h"
54#include "lldb/Interpreter/CommandReturnObject.h"
55#include "lldb/Interpreter/OptionGroupBoolean.h"
56#include "lldb/Interpreter/OptionGroupUInt64.h"
57#include "lldb/Interpreter/OptionValueProperties.h"
58#include "lldb/Interpreter/Options.h"
59#include "lldb/Interpreter/Property.h"
60#include "lldb/Symbol/ObjectFile.h"
61#include "lldb/Target/ABI.h"
62#include "lldb/Target/DynamicLoader.h"
63#include "lldb/Target/SystemRuntime.h"
64#include "lldb/Target/Target.h"
65#include "lldb/Target/TargetList.h"
66#include "lldb/Target/ThreadPlanCallFunction.h"
67#include "lldb/Utility/CleanUp.h"
68#include "lldb/Utility/FileSpec.h"
69#include "lldb/Utility/StreamString.h"
70#include "lldb/Utility/Timer.h"
71
72// Project includes
73#include "GDBRemoteRegisterContext.h"
74#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
75#include "Plugins/Process/Utility/GDBRemoteSignals.h"
76#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
77#include "Plugins/Process/Utility/StopInfoMachException.h"
78#include "ProcessGDBRemote.h"
79#include "ProcessGDBRemoteLog.h"
80#include "ThreadGDBRemote.h"
81#include "Utility/StringExtractorGDBRemote.h"
82#include "lldb/Host/Host.h"
83
84#include "llvm/ADT/StringSwitch.h"
85#include "llvm/Support/Threading.h"
86#include "llvm/Support/raw_ostream.h"
87
88#define DEBUGSERVER_BASENAME"debugserver" "debugserver"
89using namespace lldb;
90using namespace lldb_private;
91using namespace lldb_private::process_gdb_remote;
92
93namespace lldb {
94// Provide a function that can easily dump the packet history if we know a
95// ProcessGDBRemote * value (which we can get from logs or from debugging).
96// We need the function in the lldb namespace so it makes it into the final
97// executable since the LLDB shared library only exports stuff in the lldb
98// namespace. This allows you to attach with a debugger and call this
99// function and get the packet history dumped to a file.
100void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
101 StreamFile strm;
102 Status error(strm.GetFile().Open(path, File::eOpenOptionWrite |
103 File::eOpenOptionCanCreate));
104 if (error.Success())
105 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(strm);
106}
107}
108
109namespace {
110
111static PropertyDefinition g_properties[] = {
112 {"packet-timeout", OptionValue::eTypeUInt64, true, 1, NULL__null, NULL__null,
113 "Specify the default packet timeout in seconds."},
114 {"target-definition-file", OptionValue::eTypeFileSpec, true, 0, NULL__null, NULL__null,
115 "The file that provides the description for remote target registers."},
116 {NULL__null, OptionValue::eTypeInvalid, false, 0, NULL__null, NULL__null, NULL__null}};
117
118enum { ePropertyPacketTimeout, ePropertyTargetDefinitionFile };
119
120class PluginProperties : public Properties {
121public:
122 static ConstString GetSettingName() {
123 return ProcessGDBRemote::GetPluginNameStatic();
124 }
125
126 PluginProperties() : Properties() {
127 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
128 m_collection_sp->Initialize(g_properties);
129 }
130
131 virtual ~PluginProperties() {}
132
133 uint64_t GetPacketTimeout() {
134 const uint32_t idx = ePropertyPacketTimeout;
135 return m_collection_sp->GetPropertyAtIndexAsUInt64(
136 NULL__null, idx, g_properties[idx].default_uint_value);
137 }
138
139 bool SetPacketTimeout(uint64_t timeout) {
140 const uint32_t idx = ePropertyPacketTimeout;
141 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL__null, idx, timeout);
142 }
143
144 FileSpec GetTargetDefinitionFile() const {
145 const uint32_t idx = ePropertyTargetDefinitionFile;
146 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL__null, idx);
147 }
148};
149
150typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
151
152static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
153 static ProcessKDPPropertiesSP g_settings_sp;
154 if (!g_settings_sp)
155 g_settings_sp.reset(new PluginProperties());
156 return g_settings_sp;
157}
158
159} // anonymous namespace end
160
161// TODO Randomly assigning a port is unsafe. We should get an unused
162// ephemeral port from the kernel and make sure we reserve it before passing
163// it to debugserver.
164
165#if defined(__APPLE__)
166#define LOW_PORT(1024u) (IPPORT_RESERVED)
167#define HIGH_PORT(49151u) (IPPORT_HIFIRSTAUTO)
168#else
169#define LOW_PORT(1024u) (1024u)
170#define HIGH_PORT(49151u) (49151u)
171#endif
172
173#if defined(__APPLE__) && \
174 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
175static bool rand_initialized = false;
176
177static inline uint16_t get_random_port() {
178 if (!rand_initialized) {
179 time_t seed = time(NULL__null);
180
181 rand_initialized = true;
182 srand(seed);
183 }
184 return (rand() % (HIGH_PORT(49151u) - LOW_PORT(1024u))) + LOW_PORT(1024u);
185}
186#endif
187
188ConstString ProcessGDBRemote::GetPluginNameStatic() {
189 static ConstString g_name("gdb-remote");
190 return g_name;
191}
192
193const char *ProcessGDBRemote::GetPluginDescriptionStatic() {
194 return "GDB Remote protocol based debugging plug-in.";
195}
196
197void ProcessGDBRemote::Terminate() {
198 PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
199}
200
201lldb::ProcessSP
202ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
203 ListenerSP listener_sp,
204 const FileSpec *crash_file_path) {
205 lldb::ProcessSP process_sp;
206 if (crash_file_path == NULL__null)
207 process_sp.reset(new ProcessGDBRemote(target_sp, listener_sp));
208 return process_sp;
209}
210
211bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
212 bool plugin_specified_by_name) {
213 if (plugin_specified_by_name)
214 return true;
215
216 // For now we are just making sure the file exists for a given module
217 Module *exe_module = target_sp->GetExecutableModulePointer();
218 if (exe_module) {
219 ObjectFile *exe_objfile = exe_module->GetObjectFile();
220 // We can't debug core files...
221 switch (exe_objfile->GetType()) {
222 case ObjectFile::eTypeInvalid:
223 case ObjectFile::eTypeCoreFile:
224 case ObjectFile::eTypeDebugInfo:
225 case ObjectFile::eTypeObjectFile:
226 case ObjectFile::eTypeSharedLibrary:
227 case ObjectFile::eTypeStubLibrary:
228 case ObjectFile::eTypeJIT:
229 return false;
230 case ObjectFile::eTypeExecutable:
231 case ObjectFile::eTypeDynamicLinker:
232 case ObjectFile::eTypeUnknown:
233 break;
234 }
235 return exe_module->GetFileSpec().Exists();
236 }
237 // However, if there is no executable module, we return true since we might be
238 // preparing to attach.
239 return true;
240}
241
242//----------------------------------------------------------------------
243// ProcessGDBRemote constructor
244//----------------------------------------------------------------------
245ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
246 ListenerSP listener_sp)
247 : Process(target_sp, listener_sp), m_flags(0), m_gdb_comm(),
248 m_debugserver_pid(LLDB_INVALID_PROCESS_ID0), m_last_stop_packet_mutex(),
249 m_register_info(),
250 m_async_broadcaster(NULL__null, "lldb.process.gdb-remote.async-broadcaster"),
251 m_async_listener_sp(
252 Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
253 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
254 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
255 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
256 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
257 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
258 m_waiting_for_attach(false), m_destroy_tried_resuming(false),
259 m_command_sp(), m_breakpoint_pc_offset(0),
260 m_initial_tid(LLDB_INVALID_THREAD_ID0) {
261 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
262 "async thread should exit");
263 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
264 "async thread continue");
265 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
266 "async thread did exit");
267
268 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC(1u << 11)));
269
270 const uint32_t async_event_mask =
271 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
272
273 if (m_async_listener_sp->StartListeningForEvents(
274 &m_async_broadcaster, async_event_mask) != async_event_mask) {
275 if (log)
276 log->Printf("ProcessGDBRemote::%s failed to listen for "
277 "m_async_broadcaster events",
278 __FUNCTION__);
279 }
280
281 const uint32_t gdb_event_mask =
282 Communication::eBroadcastBitReadThreadDidExit |
283 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
284 if (m_async_listener_sp->StartListeningForEvents(
285 &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
286 if (log)
287 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm 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
297//----------------------------------------------------------------------
298// Destructor
299//----------------------------------------------------------------------
300ProcessGDBRemote::~ProcessGDBRemote() {
301 // m_mach_process.UnregisterNotificationCallbacks (this);
302 Clear();
303 // We need to call finalize on the process before destroying ourselves
304 // to make sure all of the broadcaster cleanup goes as planned. If we
305 // destruct this class, then Process::~Process() might have problems
306 // trying to fully destroy the broadcaster.
307 Finalize();
308
309 // The general Finalize is going to try to destroy the process and that SHOULD
310 // shut down the async thread. However, if we don't kill it it will get
311 // stranded and
312 // its connection will go away so when it wakes up it will crash. So kill it
313 // for sure here.
314 StopAsyncThread();
315 KillDebugserverProcess();
316}
317
318//----------------------------------------------------------------------
319// PluginInterface
320//----------------------------------------------------------------------
321ConstString ProcessGDBRemote::GetPluginName() { return GetPluginNameStatic(); }
322
323uint32_t ProcessGDBRemote::GetPluginVersion() { return 1; }
324
325bool ProcessGDBRemote::ParsePythonTargetDefinition(
326 const FileSpec &target_definition_fspec) {
327 ScriptInterpreter *interpreter =
328 GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
329 Status error;
330 StructuredData::ObjectSP module_object_sp(
331 interpreter->LoadPluginModule(target_definition_fspec, error));
332 if (module_object_sp) {
333 StructuredData::DictionarySP target_definition_sp(
334 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
335 "gdb-server-target-definition", error));
336
337 if (target_definition_sp) {
338 StructuredData::ObjectSP target_object(
339 target_definition_sp->GetValueForKey("host-info"));
340 if (target_object) {
341 if (auto host_info_dict = target_object->GetAsDictionary()) {
342 StructuredData::ObjectSP triple_value =
343 host_info_dict->GetValueForKey("triple");
344 if (auto triple_string_value = triple_value->GetAsString()) {
345 std::string triple_string = triple_string_value->GetValue();
346 ArchSpec host_arch(triple_string.c_str());
347 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
348 GetTarget().SetArchitecture(host_arch);
349 }
350 }
351 }
352 }
353 m_breakpoint_pc_offset = 0;
354 StructuredData::ObjectSP breakpoint_pc_offset_value =
355 target_definition_sp->GetValueForKey("breakpoint-pc-offset");
356 if (breakpoint_pc_offset_value) {
357 if (auto breakpoint_pc_int_value =
358 breakpoint_pc_offset_value->GetAsInteger())
359 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
360 }
361
362 if (m_register_info.SetRegisterInfo(*target_definition_sp,
363 GetTarget().GetArchitecture()) > 0) {
364 return true;
365 }
366 }
367 }
368 return false;
369}
370
371// If the remote stub didn't give us eh_frame or DWARF register numbers for a
372// register,
373// see if the ABI can provide them.
374// DWARF and eh_frame register numbers are defined as a part of the ABI.
375static void AugmentRegisterInfoViaABI(RegisterInfo &reg_info,
376 ConstString reg_name, ABISP abi_sp) {
377 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM(4294967295U) ||
378 reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM(4294967295U)) {
379 if (abi_sp) {
380 RegisterInfo abi_reg_info;
381 if (abi_sp->GetRegisterInfoByName(reg_name, abi_reg_info)) {
382 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM(4294967295U) &&
383 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM(4294967295U)) {
384 reg_info.kinds[eRegisterKindEHFrame] =
385 abi_reg_info.kinds[eRegisterKindEHFrame];
386 }
387 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM(4294967295U) &&
388 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM(4294967295U)) {
389 reg_info.kinds[eRegisterKindDWARF] =
390 abi_reg_info.kinds[eRegisterKindDWARF];
391 }
392 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM(4294967295U) &&
393 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM(4294967295U)) {
394 reg_info.kinds[eRegisterKindGeneric] =
395 abi_reg_info.kinds[eRegisterKindGeneric];
396 }
397 }
398 }
399 }
400}
401
402static size_t SplitCommaSeparatedRegisterNumberString(
403 const llvm::StringRef &comma_separated_regiter_numbers,
404 std::vector<uint32_t> &regnums, int base) {
405 regnums.clear();
406 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
407 value_pair.second = comma_separated_regiter_numbers;
408 do {
409 value_pair = value_pair.second.split(',');
410 if (!value_pair.first.empty()) {
411 uint32_t reg = StringConvert::ToUInt32(value_pair.first.str().c_str(),
412 LLDB_INVALID_REGNUM(4294967295U), base);
413 if (reg != LLDB_INVALID_REGNUM(4294967295U))
414 regnums.push_back(reg);
415 }
416 } while (!value_pair.second.empty());
417 return regnums.size();
418}
419
420void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
421 if (!force && m_register_info.GetNumRegisters() > 0)
422 return;
423
424 m_register_info.Clear();
425
426 // Check if qHostInfo specified a specific packet timeout for this connection.
427 // If so then lets update our setting so the user knows what the timeout is
428 // and can see it.
429 const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
430 if (host_packet_timeout > std::chrono::seconds(0)) {
431 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout.count());
432 }
433
434 // Register info search order:
435 // 1 - Use the target definition python file if one is specified.
436 // 2 - If the target definition doesn't have any of the info from the
437 // target.xml (registers) then proceed to read the target.xml.
438 // 3 - Fall back on the qRegisterInfo packets.
439
440 FileSpec target_definition_fspec =
441 GetGlobalPluginProperties()->GetTargetDefinitionFile();
442 if (!target_definition_fspec.Exists()) {
443 // If the filename doesn't exist, it may be a ~ not having been expanded -
444 // try to resolve it.
445 target_definition_fspec.ResolvePath();
446 }
447 if (target_definition_fspec) {
448 // See if we can get register definitions from a python file
449 if (ParsePythonTargetDefinition(target_definition_fspec)) {
450 return;
451 } else {
452 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
453 stream_sp->Printf("ERROR: target description file %s failed to parse.\n",
454 target_definition_fspec.GetPath().c_str());
455 }
456 }
457
458 const ArchSpec &target_arch = GetTarget().GetArchitecture();
459 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
460 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
461
462 // Use the process' architecture instead of the host arch, if available
463 ArchSpec arch_to_use;
464 if (remote_process_arch.IsValid())
465 arch_to_use = remote_process_arch;
466 else
467 arch_to_use = remote_host_arch;
468
469 if (!arch_to_use.IsValid())
470 arch_to_use = target_arch;
471
472 if (GetGDBServerRegisterInfo(arch_to_use))
473 return;
474
475 char packet[128];
476 uint32_t reg_offset = 0;
477 uint32_t reg_num = 0;
478 for (StringExtractorGDBRemote::ResponseType response_type =
479 StringExtractorGDBRemote::eResponse;
480 response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
481 const int packet_len =
482 ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
483 assert(packet_len < (int)sizeof(packet))((packet_len < (int)sizeof(packet)) ? static_cast<void>
(0) : __assert_fail ("packet_len < (int)sizeof(packet)", "/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 483, __PRETTY_FUNCTION__))
;
484 UNUSED_IF_ASSERT_DISABLED(packet_len)((void)(packet_len));
485 StringExtractorGDBRemote response;
486 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, false) ==
487 GDBRemoteCommunication::PacketResult::Success) {
488 response_type = response.GetResponseType();
489 if (response_type == StringExtractorGDBRemote::eResponse) {
490 llvm::StringRef name;
491 llvm::StringRef value;
492 ConstString reg_name;
493 ConstString alt_name;
494 ConstString set_name;
495 std::vector<uint32_t> value_regs;
496 std::vector<uint32_t> invalidate_regs;
497 std::vector<uint8_t> dwarf_opcode_bytes;
498 RegisterInfo reg_info = {
499 NULL__null, // Name
500 NULL__null, // Alt name
501 0, // byte size
502 reg_offset, // offset
503 eEncodingUint, // encoding
504 eFormatHex, // format
505 {
506 LLDB_INVALID_REGNUM(4294967295U), // eh_frame reg num
507 LLDB_INVALID_REGNUM(4294967295U), // DWARF reg num
508 LLDB_INVALID_REGNUM(4294967295U), // generic reg num
509 reg_num, // process plugin reg num
510 reg_num // native register number
511 },
512 NULL__null,
513 NULL__null,
514 NULL__null, // Dwarf expression opcode bytes pointer
515 0 // Dwarf expression opcode bytes length
516 };
517
518 while (response.GetNameColonValue(name, value)) {
519 if (name.equals("name")) {
520 reg_name.SetString(value);
521 } else if (name.equals("alt-name")) {
522 alt_name.SetString(value);
523 } else if (name.equals("bitsize")) {
524 value.getAsInteger(0, reg_info.byte_size);
525 reg_info.byte_size /= CHAR_BIT8;
526 } else if (name.equals("offset")) {
527 if (value.getAsInteger(0, reg_offset))
528 reg_offset = UINT32_MAX(4294967295U);
529 } else if (name.equals("encoding")) {
530 const Encoding encoding = Args::StringToEncoding(value);
531 if (encoding != eEncodingInvalid)
532 reg_info.encoding = encoding;
533 } else if (name.equals("format")) {
534 Format format = eFormatInvalid;
535 if (Args::StringToFormat(value.str().c_str(), format, NULL__null)
536 .Success())
537 reg_info.format = format;
538 else {
539 reg_info.format =
540 llvm::StringSwitch<Format>(value)
541 .Case("binary", eFormatBinary)
542 .Case("decimal", eFormatDecimal)
543 .Case("hex", eFormatHex)
544 .Case("float", eFormatFloat)
545 .Case("vector-sint8", eFormatVectorOfSInt8)
546 .Case("vector-uint8", eFormatVectorOfUInt8)
547 .Case("vector-sint16", eFormatVectorOfSInt16)
548 .Case("vector-uint16", eFormatVectorOfUInt16)
549 .Case("vector-sint32", eFormatVectorOfSInt32)
550 .Case("vector-uint32", eFormatVectorOfUInt32)
551 .Case("vector-float32", eFormatVectorOfFloat32)
552 .Case("vector-uint64", eFormatVectorOfUInt64)
553 .Case("vector-uint128", eFormatVectorOfUInt128)
554 .Default(eFormatInvalid);
555 }
556 } else if (name.equals("set")) {
557 set_name.SetString(value);
558 } else if (name.equals("gcc") || name.equals("ehframe")) {
559 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindEHFrame]))
560 reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM(4294967295U);
561 } else if (name.equals("dwarf")) {
562 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindDWARF]))
563 reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM(4294967295U);
564 } else if (name.equals("generic")) {
565 reg_info.kinds[eRegisterKindGeneric] =
566 Args::StringToGenericRegister(value);
567 } else if (name.equals("container-regs")) {
568 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
569 } else if (name.equals("invalidate-regs")) {
570 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
571 } else if (name.equals("dynamic_size_dwarf_expr_bytes")) {
572 size_t dwarf_opcode_len = value.size() / 2;
573 assert(dwarf_opcode_len > 0)((dwarf_opcode_len > 0) ? static_cast<void> (0) : __assert_fail
("dwarf_opcode_len > 0", "/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 573, __PRETTY_FUNCTION__))
;
574
575 dwarf_opcode_bytes.resize(dwarf_opcode_len);
576 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
577
578 StringExtractor opcode_extractor(value);
579 uint32_t ret_val =
580 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
581 assert(dwarf_opcode_len == ret_val)((dwarf_opcode_len == ret_val) ? static_cast<void> (0) :
__assert_fail ("dwarf_opcode_len == ret_val", "/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 581, __PRETTY_FUNCTION__))
;
582 UNUSED_IF_ASSERT_DISABLED(ret_val)((void)(ret_val));
583 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
584 }
585 }
586
587 reg_info.byte_offset = reg_offset;
588 assert(reg_info.byte_size != 0)((reg_info.byte_size != 0) ? static_cast<void> (0) : __assert_fail
("reg_info.byte_size != 0", "/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 588, __PRETTY_FUNCTION__))
;
589 reg_offset += reg_info.byte_size;
590 if (!value_regs.empty()) {
591 value_regs.push_back(LLDB_INVALID_REGNUM(4294967295U));
592 reg_info.value_regs = value_regs.data();
593 }
594 if (!invalidate_regs.empty()) {
595 invalidate_regs.push_back(LLDB_INVALID_REGNUM(4294967295U));
596 reg_info.invalidate_regs = invalidate_regs.data();
597 }
598
599 // We have to make a temporary ABI here, and not use the GetABI because
600 // this code
601 // gets called in DidAttach, when the target architecture (and
602 // consequently the ABI we'll get from
603 // the process) may be wrong.
604 ABISP abi_to_use = ABI::FindPlugin(shared_from_this(), arch_to_use);
605
606 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_to_use);
607
608 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
609 } else {
610 break; // ensure exit before reg_num is incremented
611 }
612 } else {
613 break;
614 }
615 }
616
617 if (m_register_info.GetNumRegisters() > 0) {
618 m_register_info.Finalize(GetTarget().GetArchitecture());
619 return;
620 }
621
622 // We didn't get anything if the accumulated reg_num is zero. See if we are
623 // debugging ARM and fill with a hard coded register set until we can get an
624 // updated debugserver down on the devices.
625 // On the other hand, if the accumulated reg_num is positive, see if we can
626 // add composite registers to the existing primordial ones.
627 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
628
629 if (!target_arch.IsValid()) {
630 if (arch_to_use.IsValid() &&
631 (arch_to_use.GetMachine() == llvm::Triple::arm ||
632 arch_to_use.GetMachine() == llvm::Triple::thumb) &&
633 arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple)
634 m_register_info.HardcodeARMRegisters(from_scratch);
635 } else if (target_arch.GetMachine() == llvm::Triple::arm ||
636 target_arch.GetMachine() == llvm::Triple::thumb) {
637 m_register_info.HardcodeARMRegisters(from_scratch);
638 }
639
640 // At this point, we can finalize our register info.
641 m_register_info.Finalize(GetTarget().GetArchitecture());
642}
643
644Status ProcessGDBRemote::WillLaunch(Module *module) {
645 return WillLaunchOrAttach();
646}
647
648Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) {
649 return WillLaunchOrAttach();
650}
651
652Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name,
653 bool wait_for_launch) {
654 return WillLaunchOrAttach();
655}
656
657Status ProcessGDBRemote::DoConnectRemote(Stream *strm,
658 llvm::StringRef remote_url) {
659 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
660 Status error(WillLaunchOrAttach());
661
662 if (error.Fail())
663 return error;
664
665 error = ConnectToDebugserver(remote_url);
666
667 if (error.Fail())
668 return error;
669 StartAsyncThread();
670
671 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
672 if (pid == LLDB_INVALID_PROCESS_ID0) {
673 // We don't have a valid process ID, so note that we are connected
674 // and could now request to launch or attach, or get remote process
675 // listings...
676 SetPrivateState(eStateConnected);
677 } else {
678 // We have a valid process
679 SetID(pid);
680 GetThreadList();
681 StringExtractorGDBRemote response;
682 if (m_gdb_comm.GetStopReply(response)) {
683 SetLastStopPacket(response);
684
685 // '?' Packets must be handled differently in non-stop mode
686 if (GetTarget().GetNonStopModeEnabled())
687 HandleStopReplySequence();
688
689 Target &target = GetTarget();
690 if (!target.GetArchitecture().IsValid()) {
691 if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
692 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
693 } else {
694 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
695 }
696 }
697
698 const StateType state = SetThreadStopInfo(response);
699 if (state != eStateInvalid) {
700 SetPrivateState(state);
701 } else
702 error.SetErrorStringWithFormat(
703 "Process %" PRIu64"l" "u" " was reported after connecting to "
704 "'%s', but state was not stopped: %s",
705 pid, remote_url.str().c_str(), StateAsCString(state));
706 } else
707 error.SetErrorStringWithFormat("Process %" PRIu64"l" "u"
708 " was reported after connecting to '%s', "
709 "but no stop reply packet was received",
710 pid, remote_url.str().c_str());
711 }
712
713 if (log)
714 log->Printf("ProcessGDBRemote::%s pid %" PRIu64"l" "u"
715 ": normalizing target architecture initial triple: %s "
716 "(GetTarget().GetArchitecture().IsValid() %s, "
717 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
718 __FUNCTION__, GetID(),
719 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
720 GetTarget().GetArchitecture().IsValid() ? "true" : "false",
721 m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
722
723 if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
724 m_gdb_comm.GetHostArchitecture().IsValid()) {
725 // Prefer the *process'* architecture over that of the *host*, if available.
726 if (m_gdb_comm.GetProcessArchitecture().IsValid())
727 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
728 else
729 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
730 }
731
732 if (log)
733 log->Printf("ProcessGDBRemote::%s pid %" PRIu64"l" "u"
734 ": normalized target architecture triple: %s",
735 __FUNCTION__, GetID(),
736 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
737
738 if (error.Success()) {
739 PlatformSP platform_sp = GetTarget().GetPlatform();
740 if (platform_sp && platform_sp->IsConnected())
741 SetUnixSignals(platform_sp->GetUnixSignals());
742 else
743 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
744 }
745
746 return error;
747}
748
749Status ProcessGDBRemote::WillLaunchOrAttach() {
750 Status error;
751 m_stdio_communication.Clear();
752 return error;
753}
754
755//----------------------------------------------------------------------
756// Process Control
757//----------------------------------------------------------------------
758Status ProcessGDBRemote::DoLaunch(Module *exe_module,
759 ProcessLaunchInfo &launch_info) {
760 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
761 Status error;
762
763 if (log)
764 log->Printf("ProcessGDBRemote::%s() entered", __FUNCTION__);
765
766 uint32_t launch_flags = launch_info.GetFlags().Get();
767 FileSpec stdin_file_spec{};
768 FileSpec stdout_file_spec{};
769 FileSpec stderr_file_spec{};
770 FileSpec working_dir = launch_info.GetWorkingDirectory();
771
772 const FileAction *file_action;
773 file_action = launch_info.GetFileActionForFD(STDIN_FILENO0);
774 if (file_action) {
775 if (file_action->GetAction() == FileAction::eFileActionOpen)
776 stdin_file_spec = file_action->GetFileSpec();
777 }
778 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO1);
779 if (file_action) {
780 if (file_action->GetAction() == FileAction::eFileActionOpen)
781 stdout_file_spec = file_action->GetFileSpec();
782 }
783 file_action = launch_info.GetFileActionForFD(STDERR_FILENO2);
784 if (file_action) {
785 if (file_action->GetAction() == FileAction::eFileActionOpen)
786 stderr_file_spec = file_action->GetFileSpec();
787 }
788
789 if (log) {
790 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
791 log->Printf("ProcessGDBRemote::%s provided with STDIO paths via "
792 "launch_info: stdin=%s, stdout=%s, stderr=%s",
793 __FUNCTION__,
794 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
795 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
796 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
797 else
798 log->Printf("ProcessGDBRemote::%s no STDIO paths given via launch_info",
799 __FUNCTION__);
800 }
801
802 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
803 if (stdin_file_spec || disable_stdio) {
804 // the inferior will be reading stdin from the specified file
805 // or stdio is completely disabled
806 m_stdin_forward = false;
807 } else {
808 m_stdin_forward = true;
809 }
810
811 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
812 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
813 // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
814 // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
815 // ::LogSetLogFile ("/dev/stdout");
816
817 ObjectFile *object_file = exe_module->GetObjectFile();
818 if (object_file) {
819 error = EstablishConnectionIfNeeded(launch_info);
820 if (error.Success()) {
821 lldb_utility::PseudoTerminal pty;
822 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
823
824 PlatformSP platform_sp(GetTarget().GetPlatform());
825 if (disable_stdio) {
826 // set to /dev/null unless redirected to a file above
827 if (!stdin_file_spec)
828 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false);
829 if (!stdout_file_spec)
830 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false);
831 if (!stderr_file_spec)
832 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false);
833 } else if (platform_sp && platform_sp->IsHost()) {
834 // If the debugserver is local and we aren't disabling STDIO, lets use
835 // a pseudo terminal to instead of relying on the 'O' packets for stdio
836 // since 'O' packets can really slow down debugging if the inferior
837 // does a lot of output.
838 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
839 pty.OpenFirstAvailableMaster(O_RDWR02 | O_NOCTTY0400, NULL__null, 0)) {
840 FileSpec slave_name{pty.GetSlaveName(NULL__null, 0), false};
841
842 if (!stdin_file_spec)
843 stdin_file_spec = slave_name;
844
845 if (!stdout_file_spec)
846 stdout_file_spec = slave_name;
847
848 if (!stderr_file_spec)
849 stderr_file_spec = slave_name;
850 }
851 if (log)
852 log->Printf(
853 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
854 "(IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
855 __FUNCTION__,
856 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
857 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
858 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
859 }
860
861 if (log)
862 log->Printf("ProcessGDBRemote::%s final STDIO paths after all "
863 "adjustments: stdin=%s, stdout=%s, stderr=%s",
864 __FUNCTION__,
865 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
866 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
867 stderr_file_spec ? stderr_file_spec.GetCString()
868 : "<null>");
869
870 if (stdin_file_spec)
871 m_gdb_comm.SetSTDIN(stdin_file_spec);
872 if (stdout_file_spec)
873 m_gdb_comm.SetSTDOUT(stdout_file_spec);
874 if (stderr_file_spec)
875 m_gdb_comm.SetSTDERR(stderr_file_spec);
876
877 m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
878 m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
879
880 m_gdb_comm.SendLaunchArchPacket(
881 GetTarget().GetArchitecture().GetArchitectureName());
882
883 const char *launch_event_data = launch_info.GetLaunchEventData();
884 if (launch_event_data != NULL__null && *launch_event_data != '\0')
885 m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
886
887 if (working_dir) {
888 m_gdb_comm.SetWorkingDir(working_dir);
889 }
890
891 // Send the environment and the program + arguments after we connect
892 const Args &environment = launch_info.GetEnvironmentEntries();
893 if (environment.GetArgumentCount()) {
894 size_t num_environment_entries = environment.GetArgumentCount();
895 for (size_t i = 0; i < num_environment_entries; ++i) {
896 const char *env_entry = environment.GetArgumentAtIndex(i);
897 if (env_entry == NULL__null ||
898 m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
899 break;
900 }
901 }
902
903 {
904 // Scope for the scoped timeout object
905 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
906 std::chrono::seconds(10));
907
908 int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
909 if (arg_packet_err == 0) {
910 std::string error_str;
911 if (m_gdb_comm.GetLaunchSuccess(error_str)) {
912 SetID(m_gdb_comm.GetCurrentProcessID());
913 } else {
914 error.SetErrorString(error_str.c_str());
915 }
916 } else {
917 error.SetErrorStringWithFormat("'A' packet returned an error: %i",
918 arg_packet_err);
919 }
920 }
921
922 if (GetID() == LLDB_INVALID_PROCESS_ID0) {
923 if (log)
924 log->Printf("failed to connect to debugserver: %s",
925 error.AsCString());
926 KillDebugserverProcess();
927 return error;
928 }
929
930 StringExtractorGDBRemote response;
931 if (m_gdb_comm.GetStopReply(response)) {
932 SetLastStopPacket(response);
933 // '?' Packets must be handled differently in non-stop mode
934 if (GetTarget().GetNonStopModeEnabled())
935 HandleStopReplySequence();
936
937 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
938
939 if (process_arch.IsValid()) {
940 GetTarget().MergeArchitecture(process_arch);
941 } else {
942 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
943 if (host_arch.IsValid())
944 GetTarget().MergeArchitecture(host_arch);
945 }
946
947 SetPrivateState(SetThreadStopInfo(response));
948
949 if (!disable_stdio) {
950 if (pty.GetMasterFileDescriptor() !=
951 lldb_utility::PseudoTerminal::invalid_fd)
952 SetSTDIOFileDescriptor(pty.ReleaseMasterFileDescriptor());
953 }
954 }
955 } else {
956 if (log)
957 log->Printf("failed to connect to debugserver: %s", error.AsCString());
958 }
959 } else {
960 // Set our user ID to an invalid process ID.
961 SetID(LLDB_INVALID_PROCESS_ID0);
962 error.SetErrorStringWithFormat(
963 "failed to get object file from '%s' for arch %s",
964 exe_module->GetFileSpec().GetFilename().AsCString(),
965 exe_module->GetArchitecture().GetArchitectureName());
966 }
967 return error;
968}
969
970Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
971 Status error;
972 // Only connect if we have a valid connect URL
973 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
974
975 if (!connect_url.empty()) {
976 if (log)
977 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
978 connect_url.str().c_str());
979 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
980 new ConnectionFileDescriptor());
981 if (conn_ap.get()) {
982 const uint32_t max_retry_count = 50;
983 uint32_t retry_count = 0;
984 while (!m_gdb_comm.IsConnected()) {
985 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess) {
986 m_gdb_comm.SetConnection(conn_ap.release());
987 break;
988 } else if (error.WasInterrupted()) {
989 // If we were interrupted, don't keep retrying.
990 break;
991 }
992
993 retry_count++;
994
995 if (retry_count >= max_retry_count)
996 break;
997
998 usleep(100000);
999 }
1000 }
1001 }
1002
1003 if (!m_gdb_comm.IsConnected()) {
1004 if (error.Success())
1005 error.SetErrorString("not connected to remote gdb server");
1006 return error;
1007 }
1008
1009 // Start the communications read thread so all incoming data can be
1010 // parsed into packets and queued as they arrive.
1011 if (GetTarget().GetNonStopModeEnabled())
1012 m_gdb_comm.StartReadThread();
1013
1014 // We always seem to be able to open a connection to a local port
1015 // so we need to make sure we can then send data to it. If we can't
1016 // then we aren't actually connected to anything, so try and do the
1017 // handshake with the remote GDB server and make sure that goes
1018 // alright.
1019 if (!m_gdb_comm.HandshakeWithServer(&error)) {
1020 m_gdb_comm.Disconnect();
1021 if (error.Success())
1022 error.SetErrorString("not connected to remote gdb server");
1023 return error;
1024 }
1025
1026 // Send $QNonStop:1 packet on startup if required
1027 if (GetTarget().GetNonStopModeEnabled())
1028 GetTarget().SetNonStopModeEnabled(m_gdb_comm.SetNonStopMode(true));
1029
1030 m_gdb_comm.GetEchoSupported();
1031 m_gdb_comm.GetThreadSuffixSupported();
1032 m_gdb_comm.GetListThreadsInStopReplySupported();
1033 m_gdb_comm.GetHostInfo();
1034 m_gdb_comm.GetVContSupported('c');
1035 m_gdb_comm.GetVAttachOrWaitSupported();
1036 m_gdb_comm.EnableErrorStringInPacket();
1037
1038 // Ask the remote server for the default thread id
1039 if (GetTarget().GetNonStopModeEnabled())
1040 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1041
1042 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1043 for (size_t idx = 0; idx < num_cmds; idx++) {
1044 StringExtractorGDBRemote response;
1045 m_gdb_comm.SendPacketAndWaitForResponse(
1046 GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1047 }
1048 return error;
1049}
1050
1051void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
1052 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
1053 if (log)
1054 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1055 if (GetID() != LLDB_INVALID_PROCESS_ID0) {
1056 BuildDynamicRegisterInfo(false);
1057
1058 // See if the GDB server supports the qHostInfo information
1059
1060 // See if the GDB server supports the qProcessInfo packet, if so
1061 // prefer that over the Host information as it will be more specific
1062 // to our process.
1063
1064 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1065 if (remote_process_arch.IsValid()) {
1066 process_arch = remote_process_arch;
1067 if (log)
1068 log->Printf("ProcessGDBRemote::%s gdb-remote had process architecture, "
1069 "using %s %s",
1070 __FUNCTION__, process_arch.GetArchitectureName()
1071 ? process_arch.GetArchitectureName()
1072 : "<null>",
1073 process_arch.GetTriple().getTriple().c_str()
1074 ? process_arch.GetTriple().getTriple().c_str()
1075 : "<null>");
1076 } else {
1077 process_arch = m_gdb_comm.GetHostArchitecture();
1078 if (log)
1079 log->Printf("ProcessGDBRemote::%s gdb-remote did not have process "
1080 "architecture, using gdb-remote host architecture %s %s",
1081 __FUNCTION__, process_arch.GetArchitectureName()
1082 ? process_arch.GetArchitectureName()
1083 : "<null>",
1084 process_arch.GetTriple().getTriple().c_str()
1085 ? process_arch.GetTriple().getTriple().c_str()
1086 : "<null>");
1087 }
1088
1089 if (process_arch.IsValid()) {
1090 const ArchSpec &target_arch = GetTarget().GetArchitecture();
1091 if (target_arch.IsValid()) {
1092 if (log)
1093 log->Printf(
1094 "ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1095 __FUNCTION__, target_arch.GetArchitectureName()
1096 ? target_arch.GetArchitectureName()
1097 : "<null>",
1098 target_arch.GetTriple().getTriple().c_str()
1099 ? target_arch.GetTriple().getTriple().c_str()
1100 : "<null>");
1101
1102 // If the remote host is ARM and we have apple as the vendor, then
1103 // ARM executables and shared libraries can have mixed ARM
1104 // architectures.
1105 // You can have an armv6 executable, and if the host is armv7, then the
1106 // system will load the best possible architecture for all shared
1107 // libraries
1108 // it has, so we really need to take the remote host architecture as our
1109 // defacto architecture in this case.
1110
1111 if ((process_arch.GetMachine() == llvm::Triple::arm ||
1112 process_arch.GetMachine() == llvm::Triple::thumb) &&
1113 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
1114 GetTarget().SetArchitecture(process_arch);
1115 if (log)
1116 log->Printf("ProcessGDBRemote::%s remote process is ARM/Apple, "
1117 "setting target arch to %s %s",
1118 __FUNCTION__, process_arch.GetArchitectureName()
1119 ? process_arch.GetArchitectureName()
1120 : "<null>",
1121 process_arch.GetTriple().getTriple().c_str()
1122 ? process_arch.GetTriple().getTriple().c_str()
1123 : "<null>");
1124 } else {
1125 // Fill in what is missing in the triple
1126 const llvm::Triple &remote_triple = process_arch.GetTriple();
1127 llvm::Triple new_target_triple = target_arch.GetTriple();
1128 if (new_target_triple.getVendorName().size() == 0) {
1129 new_target_triple.setVendor(remote_triple.getVendor());
1130
1131 if (new_target_triple.getOSName().size() == 0) {
1132 new_target_triple.setOS(remote_triple.getOS());
1133
1134 if (new_target_triple.getEnvironmentName().size() == 0)
1135 new_target_triple.setEnvironment(
1136 remote_triple.getEnvironment());
1137 }
1138
1139 ArchSpec new_target_arch = target_arch;
1140 new_target_arch.SetTriple(new_target_triple);
1141 GetTarget().SetArchitecture(new_target_arch);
1142 }
1143 }
1144
1145 if (log)
1146 log->Printf("ProcessGDBRemote::%s final target arch after "
1147 "adjustments for remote architecture: %s %s",
1148 __FUNCTION__, target_arch.GetArchitectureName()
1149 ? target_arch.GetArchitectureName()
1150 : "<null>",
1151 target_arch.GetTriple().getTriple().c_str()
1152 ? target_arch.GetTriple().getTriple().c_str()
1153 : "<null>");
1154 } else {
1155 // The target doesn't have a valid architecture yet, set it from
1156 // the architecture we got from the remote GDB server
1157 GetTarget().SetArchitecture(process_arch);
1158 }
1159 }
1160
1161 // Find out which StructuredDataPlugins are supported by the
1162 // debug monitor. These plugins transmit data over async $J packets.
1163 auto supported_packets_array =
1164 m_gdb_comm.GetSupportedStructuredDataPlugins();
1165 if (supported_packets_array)
1166 MapSupportedStructuredDataPlugins(*supported_packets_array);
1167 }
1168}
1169
1170void ProcessGDBRemote::DidLaunch() {
1171 ArchSpec process_arch;
1172 DidLaunchOrAttach(process_arch);
1173}
1174
1175Status ProcessGDBRemote::DoAttachToProcessWithID(
1176 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1177 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
1178 Status error;
1179
1180 if (log)
1181 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1182
1183 // Clear out and clean up from any current state
1184 Clear();
1185 if (attach_pid != LLDB_INVALID_PROCESS_ID0) {
1186 error = EstablishConnectionIfNeeded(attach_info);
1187 if (error.Success()) {
1188 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1189
1190 char packet[64];
1191 const int packet_len =
1192 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64"l" "x", attach_pid);
1193 SetID(attach_pid);
1194 m_async_broadcaster.BroadcastEvent(
1195 eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1196 } else
1197 SetExitStatus(-1, error.AsCString());
1198 }
1199
1200 return error;
1201}
1202
1203Status ProcessGDBRemote::DoAttachToProcessWithName(
1204 const char *process_name, const ProcessAttachInfo &attach_info) {
1205 Status error;
1206 // Clear out and clean up from any current state
1207 Clear();
1208
1209 if (process_name && process_name[0]) {
1210 error = EstablishConnectionIfNeeded(attach_info);
1211 if (error.Success()) {
1212 StreamString packet;
1213
1214 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1215
1216 if (attach_info.GetWaitForLaunch()) {
1217 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1218 packet.PutCString("vAttachWait");
1219 } else {
1220 if (attach_info.GetIgnoreExisting())
1221 packet.PutCString("vAttachWait");
1222 else
1223 packet.PutCString("vAttachOrWait");
1224 }
1225 } else
1226 packet.PutCString("vAttachName");
1227 packet.PutChar(';');
1228 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1229 endian::InlHostByteOrder(),
1230 endian::InlHostByteOrder());
1231
1232 m_async_broadcaster.BroadcastEvent(
1233 eBroadcastBitAsyncContinue,
1234 new EventDataBytes(packet.GetString().data(), packet.GetSize()));
1235
1236 } else
1237 SetExitStatus(-1, error.AsCString());
1238 }
1239 return error;
1240}
1241
1242lldb::user_id_t ProcessGDBRemote::StartTrace(const TraceOptions &options,
1243 Status &error) {
1244 return m_gdb_comm.SendStartTracePacket(options, error);
1245}
1246
1247Status ProcessGDBRemote::StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
1248 return m_gdb_comm.SendStopTracePacket(uid, thread_id);
1249}
1250
1251Status ProcessGDBRemote::GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
1252 llvm::MutableArrayRef<uint8_t> &buffer,
1253 size_t offset) {
1254 return m_gdb_comm.SendGetDataPacket(uid, thread_id, buffer, offset);
1255}
1256
1257Status ProcessGDBRemote::GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
1258 llvm::MutableArrayRef<uint8_t> &buffer,
1259 size_t offset) {
1260 return m_gdb_comm.SendGetMetaDataPacket(uid, thread_id, buffer, offset);
1261}
1262
1263Status ProcessGDBRemote::GetTraceConfig(lldb::user_id_t uid,
1264 TraceOptions &options) {
1265 return m_gdb_comm.SendGetTraceConfigPacket(uid, options);
1266}
1267
1268void ProcessGDBRemote::DidExit() {
1269 // When we exit, disconnect from the GDB server communications
1270 m_gdb_comm.Disconnect();
1271}
1272
1273void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1274 // If you can figure out what the architecture is, fill it in here.
1275 process_arch.Clear();
1276 DidLaunchOrAttach(process_arch);
1277}
1278
1279Status ProcessGDBRemote::WillResume() {
1280 m_continue_c_tids.clear();
1281 m_continue_C_tids.clear();
1282 m_continue_s_tids.clear();
1283 m_continue_S_tids.clear();
1284 m_jstopinfo_sp.reset();
1285 m_jthreadsinfo_sp.reset();
1286 return Status();
1287}
1288
1289Status ProcessGDBRemote::DoResume() {
1290 Status error;
1291 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
1292 if (log)
1293 log->Printf("ProcessGDBRemote::Resume()");
1294
1295 ListenerSP listener_sp(
1296 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1297 if (listener_sp->StartListeningForEvents(
1298 &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
1299 listener_sp->StartListeningForEvents(
1300 &m_async_broadcaster,
1301 ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1302
1303 const size_t num_threads = GetThreadList().GetSize();
1304
1305 StreamString continue_packet;
1306 bool continue_packet_error = false;
1307 if (m_gdb_comm.HasAnyVContSupport()) {
1308 if (!GetTarget().GetNonStopModeEnabled() &&
1309 (m_continue_c_tids.size() == num_threads ||
1310 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1311 m_continue_s_tids.empty() && m_continue_S_tids.empty()))) {
1312 // All threads are continuing, just send a "c" packet
1313 continue_packet.PutCString("c");
1314 } else {
1315 continue_packet.PutCString("vCont");
1316
1317 if (!m_continue_c_tids.empty()) {
1318 if (m_gdb_comm.GetVContSupported('c')) {
1319 for (tid_collection::const_iterator
1320 t_pos = m_continue_c_tids.begin(),
1321 t_end = m_continue_c_tids.end();
1322 t_pos != t_end; ++t_pos)
1323 continue_packet.Printf(";c:%4.4" PRIx64"l" "x", *t_pos);
1324 } else
1325 continue_packet_error = true;
1326 }
1327
1328 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1329 if (m_gdb_comm.GetVContSupported('C')) {
1330 for (tid_sig_collection::const_iterator
1331 s_pos = m_continue_C_tids.begin(),
1332 s_end = m_continue_C_tids.end();
1333 s_pos != s_end; ++s_pos)
1334 continue_packet.Printf(";C%2.2x:%4.4" PRIx64"l" "x", s_pos->second,
1335 s_pos->first);
1336 } else
1337 continue_packet_error = true;
1338 }
1339
1340 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1341 if (m_gdb_comm.GetVContSupported('s')) {
1342 for (tid_collection::const_iterator
1343 t_pos = m_continue_s_tids.begin(),
1344 t_end = m_continue_s_tids.end();
1345 t_pos != t_end; ++t_pos)
1346 continue_packet.Printf(";s:%4.4" PRIx64"l" "x", *t_pos);
1347 } else
1348 continue_packet_error = true;
1349 }
1350
1351 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1352 if (m_gdb_comm.GetVContSupported('S')) {
1353 for (tid_sig_collection::const_iterator
1354 s_pos = m_continue_S_tids.begin(),
1355 s_end = m_continue_S_tids.end();
1356 s_pos != s_end; ++s_pos)
1357 continue_packet.Printf(";S%2.2x:%4.4" PRIx64"l" "x", s_pos->second,
1358 s_pos->first);
1359 } else
1360 continue_packet_error = true;
1361 }
1362
1363 if (continue_packet_error)
1364 continue_packet.Clear();
1365 }
1366 } else
1367 continue_packet_error = true;
1368
1369 if (continue_packet_error) {
1370 // Either no vCont support, or we tried to use part of the vCont
1371 // packet that wasn't supported by the remote GDB server.
1372 // We need to try and make a simple packet that can do our continue
1373 const size_t num_continue_c_tids = m_continue_c_tids.size();
1374 const size_t num_continue_C_tids = m_continue_C_tids.size();
1375 const size_t num_continue_s_tids = m_continue_s_tids.size();
1376 const size_t num_continue_S_tids = m_continue_S_tids.size();
1377 if (num_continue_c_tids > 0) {
1378 if (num_continue_c_tids == num_threads) {
1379 // All threads are resuming...
1380 m_gdb_comm.SetCurrentThreadForRun(-1);
1381 continue_packet.PutChar('c');
1382 continue_packet_error = false;
1383 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1384 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1385 // Only one thread is continuing
1386 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1387 continue_packet.PutChar('c');
1388 continue_packet_error = false;
1389 }
1390 }
1391
1392 if (continue_packet_error && num_continue_C_tids > 0) {
1393 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1394 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1395 num_continue_S_tids == 0) {
1396 const int continue_signo = m_continue_C_tids.front().second;
1397 // Only one thread is continuing
1398 if (num_continue_C_tids > 1) {
1399 // More that one thread with a signal, yet we don't have
1400 // vCont support and we are being asked to resume each
1401 // thread with a signal, we need to make sure they are
1402 // all the same signal, or we can't issue the continue
1403 // accurately with the current support...
1404 if (num_continue_C_tids > 1) {
1405 continue_packet_error = false;
1406 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1407 if (m_continue_C_tids[i].second != continue_signo)
1408 continue_packet_error = true;
1409 }
1410 }
1411 if (!continue_packet_error)
1412 m_gdb_comm.SetCurrentThreadForRun(-1);
1413 } else {
1414 // Set the continue thread ID
1415 continue_packet_error = false;
1416 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1417 }
1418 if (!continue_packet_error) {
1419 // Add threads continuing with the same signo...
1420 continue_packet.Printf("C%2.2x", continue_signo);
1421 }
1422 }
1423 }
1424
1425 if (continue_packet_error && num_continue_s_tids > 0) {
1426 if (num_continue_s_tids == num_threads) {
1427 // All threads are resuming...
1428 m_gdb_comm.SetCurrentThreadForRun(-1);
1429
1430 // If in Non-Stop-Mode use vCont when stepping
1431 if (GetTarget().GetNonStopModeEnabled()) {
1432 if (m_gdb_comm.GetVContSupported('s'))
1433 continue_packet.PutCString("vCont;s");
1434 else
1435 continue_packet.PutChar('s');
1436 } else
1437 continue_packet.PutChar('s');
1438
1439 continue_packet_error = false;
1440 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1441 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1442 // Only one thread is stepping
1443 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1444 continue_packet.PutChar('s');
1445 continue_packet_error = false;
1446 }
1447 }
1448
1449 if (!continue_packet_error && num_continue_S_tids > 0) {
1450 if (num_continue_S_tids == num_threads) {
1451 const int step_signo = m_continue_S_tids.front().second;
1452 // Are all threads trying to step with the same signal?
1453 continue_packet_error = false;
1454 if (num_continue_S_tids > 1) {
1455 for (size_t i = 1; i < num_threads; ++i) {
1456 if (m_continue_S_tids[i].second != step_signo)
1457 continue_packet_error = true;
1458 }
1459 }
1460 if (!continue_packet_error) {
1461 // Add threads stepping with the same signo...
1462 m_gdb_comm.SetCurrentThreadForRun(-1);
1463 continue_packet.Printf("S%2.2x", step_signo);
1464 }
1465 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1466 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1467 // Only one thread is stepping with signal
1468 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1469 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1470 continue_packet_error = false;
1471 }
1472 }
1473 }
1474
1475 if (continue_packet_error) {
1476 error.SetErrorString("can't make continue packet for this resume");
1477 } else {
1478 EventSP event_sp;
1479 if (!m_async_thread.IsJoinable()) {
1480 error.SetErrorString("Trying to resume but the async thread is dead.");
1481 if (log)
1482 log->Printf("ProcessGDBRemote::DoResume: Trying to resume but the "
1483 "async thread is dead.");
1484 return error;
1485 }
1486
1487 m_async_broadcaster.BroadcastEvent(
1488 eBroadcastBitAsyncContinue,
1489 new EventDataBytes(continue_packet.GetString().data(),
1490 continue_packet.GetSize()));
1491
1492 if (listener_sp->GetEvent(event_sp, std::chrono::seconds(5)) == false) {
1493 error.SetErrorString("Resume timed out.");
1494 if (log)
1495 log->Printf("ProcessGDBRemote::DoResume: Resume timed out.");
1496 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1497 error.SetErrorString("Broadcast continue, but the async thread was "
1498 "killed before we got an ack back.");
1499 if (log)
1500 log->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the "
1501 "async thread was killed before we got an ack back.");
1502 return error;
1503 }
1504 }
1505 }
1506
1507 return error;
1508}
1509
1510void ProcessGDBRemote::HandleStopReplySequence() {
1511 while (true) {
1512 // Send vStopped
1513 StringExtractorGDBRemote response;
1514 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1515
1516 // OK represents end of signal list
1517 if (response.IsOKResponse())
1518 break;
1519
1520 // If not OK or a normal packet we have a problem
1521 if (!response.IsNormalResponse())
1522 break;
1523
1524 SetLastStopPacket(response);
1525 }
1526}
1527
1528void ProcessGDBRemote::ClearThreadIDList() {
1529 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1530 m_thread_ids.clear();
1531 m_thread_pcs.clear();
1532}
1533
1534size_t
1535ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) {
1536 m_thread_ids.clear();
1537 m_thread_pcs.clear();
1538 size_t comma_pos;
1539 lldb::tid_t tid;
1540 while ((comma_pos = value.find(',')) != std::string::npos) {
1541 value[comma_pos] = '\0';
1542 // thread in big endian hex
1543 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID0, 16);
1544 if (tid != LLDB_INVALID_THREAD_ID0)
1545 m_thread_ids.push_back(tid);
1546 value.erase(0, comma_pos + 1);
1547 }
1548 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID0, 16);
1549 if (tid != LLDB_INVALID_THREAD_ID0)
1550 m_thread_ids.push_back(tid);
1551 return m_thread_ids.size();
1552}
1553
1554size_t
1555ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) {
1556 m_thread_pcs.clear();
1557 size_t comma_pos;
1558 lldb::addr_t pc;
1559 while ((comma_pos = value.find(',')) != std::string::npos) {
1560 value[comma_pos] = '\0';
1561 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS(18446744073709551615UL), 16);
1562 if (pc != LLDB_INVALID_ADDRESS(18446744073709551615UL))
1563 m_thread_pcs.push_back(pc);
1564 value.erase(0, comma_pos + 1);
1565 }
1566 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS(18446744073709551615UL), 16);
1567 if (pc != LLDB_INVALID_THREAD_ID0)
1568 m_thread_pcs.push_back(pc);
1569 return m_thread_pcs.size();
1570}
1571
1572bool ProcessGDBRemote::UpdateThreadIDList() {
1573 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1574
1575 if (m_jthreadsinfo_sp) {
1576 // If we have the JSON threads info, we can get the thread list from that
1577 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1578 if (thread_infos && thread_infos->GetSize() > 0) {
1579 m_thread_ids.clear();
1580 m_thread_pcs.clear();
1581 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1582 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1583 if (thread_dict) {
1584 // Set the thread stop info from the JSON dictionary
1585 SetThreadStopInfo(thread_dict);
1586 lldb::tid_t tid = LLDB_INVALID_THREAD_ID0;
1587 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1588 m_thread_ids.push_back(tid);
1589 }
1590 return true; // Keep iterating through all thread_info objects
1591 });
1592 }
1593 if (!m_thread_ids.empty())
1594 return true;
1595 } else {
1596 // See if we can get the thread IDs from the current stop reply packets
1597 // that might contain a "threads" key/value pair
1598
1599 // Lock the thread stack while we access it
1600 // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1601 std::unique_lock<std::recursive_mutex> stop_stack_lock(
1602 m_last_stop_packet_mutex, std::defer_lock);
1603 if (stop_stack_lock.try_lock()) {
1604 // Get the number of stop packets on the stack
1605 int nItems = m_stop_packet_stack.size();
1606 // Iterate over them
1607 for (int i = 0; i < nItems; i++) {
1608 // Get the thread stop info
1609 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1610 const std::string &stop_info_str = stop_info.GetStringRef();
1611
1612 m_thread_pcs.clear();
1613 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1614 if (thread_pcs_pos != std::string::npos) {
1615 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1616 const size_t end = stop_info_str.find(';', start);
1617 if (end != std::string::npos) {
1618 std::string value = stop_info_str.substr(start, end - start);
1619 UpdateThreadPCsFromStopReplyThreadsValue(value);
1620 }
1621 }
1622
1623 const size_t threads_pos = stop_info_str.find(";threads:");
1624 if (threads_pos != std::string::npos) {
1625 const size_t start = threads_pos + strlen(";threads:");
1626 const size_t end = stop_info_str.find(';', start);
1627 if (end != std::string::npos) {
1628 std::string value = stop_info_str.substr(start, end - start);
1629 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1630 return true;
1631 }
1632 }
1633 }
1634 }
1635 }
1636
1637 bool sequence_mutex_unavailable = false;
1638 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1639 if (sequence_mutex_unavailable) {
1640 return false; // We just didn't get the list
1641 }
1642 return true;
1643}
1644
1645bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list,
1646 ThreadList &new_thread_list) {
1647 // locker will keep a mutex locked until it goes out of scope
1648 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD(1u << 2)));
1649 LLDB_LOGV(log, "pid = {0}", GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "pid = {0}", GetID()); } while (0)
;
1650
1651 size_t num_thread_ids = m_thread_ids.size();
1652 // The "m_thread_ids" thread ID list should always be updated after each stop
1653 // reply packet, but in case it isn't, update it here.
1654 if (num_thread_ids == 0) {
1655 if (!UpdateThreadIDList())
1656 return false;
1657 num_thread_ids = m_thread_ids.size();
1658 }
1659
1660 ThreadList old_thread_list_copy(old_thread_list);
1661 if (num_thread_ids > 0) {
1662 for (size_t i = 0; i < num_thread_ids; ++i) {
1663 tid_t tid = m_thread_ids[i];
1664 ThreadSP thread_sp(
1665 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1666 if (!thread_sp) {
1667 thread_sp.reset(new ThreadGDBRemote(*this, tid));
1668 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "Making new thread: {0} for thread ID: {1:x}."
, thread_sp.get(), thread_sp->GetID()); } while (0)
1669 thread_sp.get(), thread_sp->GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "Making new thread: {0} for thread ID: {1:x}."
, thread_sp.get(), thread_sp->GetID()); } while (0)
;
1670 } else {
1671 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "Found old thread: {0} for thread ID: {1:x}."
, thread_sp.get(), thread_sp->GetID()); } while (0)
1672 thread_sp.get(), thread_sp->GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "Found old thread: {0} for thread ID: {1:x}."
, thread_sp.get(), thread_sp->GetID()); } while (0)
;
1673 }
1674
1675 SetThreadPc(thread_sp, i);
1676 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1677 }
1678 }
1679
1680 // Whatever that is left in old_thread_list_copy are not
1681 // present in new_thread_list. Remove non-existent threads from internal id
1682 // table.
1683 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1684 for (size_t i = 0; i < old_num_thread_ids; i++) {
1685 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1686 if (old_thread_sp) {
1687 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1688 m_thread_id_to_index_id_map.erase(old_thread_id);
1689 }
1690 }
1691
1692 return true;
1693}
1694
1695void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1696 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1697 GetByteOrder() != eByteOrderInvalid) {
1698 ThreadGDBRemote *gdb_thread =
1699 static_cast<ThreadGDBRemote *>(thread_sp.get());
1700 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1701 if (reg_ctx_sp) {
1702 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1703 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC0);
1704 if (pc_regnum != LLDB_INVALID_REGNUM(4294967295U)) {
1705 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1706 }
1707 }
1708 }
1709}
1710
1711bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1712 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1713 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1714 // packet
1715 if (thread_infos_sp) {
1716 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1717 if (thread_infos) {
1718 lldb::tid_t tid;
1719 const size_t n = thread_infos->GetSize();
1720 for (size_t i = 0; i < n; ++i) {
1721 StructuredData::Dictionary *thread_dict =
1722 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1723 if (thread_dict) {
1724 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1725 "tid", tid, LLDB_INVALID_THREAD_ID0)) {
1726 if (tid == thread->GetID())
1727 return (bool)SetThreadStopInfo(thread_dict);
1728 }
1729 }
1730 }
1731 }
1732 }
1733 return false;
1734}
1735
1736bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1737 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1738 // packet
1739 if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1740 return true;
1741
1742 // See if we got thread stop info for any threads valid stop info reasons
1743 // threads
1744 // via the "jstopinfo" packet stop reply packet key/value pair?
1745 if (m_jstopinfo_sp) {
1746 // If we have "jstopinfo" then we have stop descriptions for all threads
1747 // that have stop reasons, and if there is no entry for a thread, then
1748 // it has no stop reason.
1749 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1750 if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1751 thread->SetStopInfo(StopInfoSP());
1752 }
1753 return true;
1754 }
1755
1756 // Fall back to using the qThreadStopInfo packet
1757 StringExtractorGDBRemote stop_packet;
1758 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1759 return SetThreadStopInfo(stop_packet) == eStateStopped;
1760 return false;
1761}
1762
1763ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1764 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1765 uint8_t signo, const std::string &thread_name, const std::string &reason,
1766 const std::string &description, uint32_t exc_type,
1767 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1768 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1769 // queue_serial are valid
1770 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1771 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1772 ThreadSP thread_sp;
1773 if (tid != LLDB_INVALID_THREAD_ID0) {
1774 // Scope for "locker" below
1775 {
1776 // m_thread_list_real does have its own mutex, but we need to
1777 // hold onto the mutex between the call to
1778 // m_thread_list_real.FindThreadByID(...)
1779 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1780 std::lock_guard<std::recursive_mutex> guard(
1781 m_thread_list_real.GetMutex());
1782 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1783
1784 if (!thread_sp) {
1785 // Create the thread if we need to
1786 thread_sp.reset(new ThreadGDBRemote(*this, tid));
1787 m_thread_list_real.AddThread(thread_sp);
1788 }
1789 }
1790
1791 if (thread_sp) {
1792 ThreadGDBRemote *gdb_thread =
1793 static_cast<ThreadGDBRemote *>(thread_sp.get());
1794 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1795
1796 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1797 if (iter != m_thread_ids.end()) {
1798 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1799 }
1800
1801 for (const auto &pair : expedited_register_map) {
1802 StringExtractor reg_value_extractor;
1803 reg_value_extractor.GetStringRef() = pair.second;
1804 DataBufferSP buffer_sp(new DataBufferHeap(
1805 reg_value_extractor.GetStringRef().size() / 2, 0));
1806 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1807 gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
1808 }
1809
1810 thread_sp->SetName(thread_name.empty() ? NULL__null : thread_name.c_str());
1811
1812 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1813 // Check if the GDB server was able to provide the queue name, kind and
1814 // serial number
1815 if (queue_vars_valid)
1816 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1817 queue_serial, dispatch_queue_t,
1818 associated_with_dispatch_queue);
1819 else
1820 gdb_thread->ClearQueueInfo();
1821
1822 gdb_thread->SetAssociatedWithLibdispatchQueue(
1823 associated_with_dispatch_queue);
1824
1825 if (dispatch_queue_t != LLDB_INVALID_ADDRESS(18446744073709551615UL))
1826 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1827
1828 // Make sure we update our thread stop reason just once
1829 if (!thread_sp->StopInfoIsUpToDate()) {
1830 thread_sp->SetStopInfo(StopInfoSP());
1831 // If there's a memory thread backed by this thread, we need to use it
1832 // to calcualte StopInfo.
1833 ThreadSP memory_thread_sp =
1834 m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
1835 if (memory_thread_sp)
1836 thread_sp = memory_thread_sp;
1837
1838 if (exc_type != 0) {
1839 const size_t exc_data_size = exc_data.size();
1840
1841 thread_sp->SetStopInfo(
1842 StopInfoMachException::CreateStopReasonWithMachException(
1843 *thread_sp, exc_type, exc_data_size,
1844 exc_data_size >= 1 ? exc_data[0] : 0,
1845 exc_data_size >= 2 ? exc_data[1] : 0,
1846 exc_data_size >= 3 ? exc_data[2] : 0));
1847 } else {
1848 bool handled = false;
1849 bool did_exec = false;
1850 if (!reason.empty()) {
1851 if (reason.compare("trace") == 0) {
1852 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1853 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1854 ->GetBreakpointSiteList()
1855 .FindByAddress(pc);
1856
1857 // If the current pc is a breakpoint site then the StopInfo should
1858 // be set to Breakpoint
1859 // Otherwise, it will be set to Trace.
1860 if (bp_site_sp &&
1861 bp_site_sp->ValidForThisThread(thread_sp.get())) {
1862 thread_sp->SetStopInfo(
1863 StopInfo::CreateStopReasonWithBreakpointSiteID(
1864 *thread_sp, bp_site_sp->GetID()));
1865 } else
1866 thread_sp->SetStopInfo(
1867 StopInfo::CreateStopReasonToTrace(*thread_sp));
1868 handled = true;
1869 } else if (reason.compare("breakpoint") == 0) {
1870 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1871 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1872 ->GetBreakpointSiteList()
1873 .FindByAddress(pc);
1874 if (bp_site_sp) {
1875 // If the breakpoint is for this thread, then we'll report the
1876 // hit, but if it is for another thread,
1877 // we can just report no reason. We don't need to worry about
1878 // stepping over the breakpoint here, that
1879 // will be taken care of when the thread resumes and notices
1880 // that there's a breakpoint under the pc.
1881 handled = true;
1882 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1883 thread_sp->SetStopInfo(
1884 StopInfo::CreateStopReasonWithBreakpointSiteID(
1885 *thread_sp, bp_site_sp->GetID()));
1886 } else {
1887 StopInfoSP invalid_stop_info_sp;
1888 thread_sp->SetStopInfo(invalid_stop_info_sp);
1889 }
1890 }
1891 } else if (reason.compare("trap") == 0) {
1892 // Let the trap just use the standard signal stop reason below...
1893 } else if (reason.compare("watchpoint") == 0) {
1894 StringExtractor desc_extractor(description.c_str());
1895 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS(18446744073709551615UL));
1896 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32(4294967295U));
1897 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS(18446744073709551615UL));
1898 watch_id_t watch_id = LLDB_INVALID_WATCH_ID0;
1899 if (wp_addr != LLDB_INVALID_ADDRESS(18446744073709551615UL)) {
1900 WatchpointSP wp_sp;
1901 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1902 if ((core >= ArchSpec::kCore_mips_first &&
1903 core <= ArchSpec::kCore_mips_last) ||
1904 (core >= ArchSpec::eCore_arm_generic &&
1905 core <= ArchSpec::eCore_arm_aarch64))
1906 wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1907 wp_hit_addr);
1908 if (!wp_sp)
1909 wp_sp =
1910 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1911 if (wp_sp) {
1912 wp_sp->SetHardwareIndex(wp_index);
1913 watch_id = wp_sp->GetID();
1914 }
1915 }
1916 if (watch_id == LLDB_INVALID_WATCH_ID0) {
1917 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
1918 GDBR_LOG_WATCHPOINTS(1u << 8)));
1919 if (log)
1920 log->Printf("failed to find watchpoint");
1921 }
1922 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1923 *thread_sp, watch_id, wp_hit_addr));
1924 handled = true;
1925 } else if (reason.compare("exception") == 0) {
1926 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1927 *thread_sp, description.c_str()));
1928 handled = true;
1929 } else if (reason.compare("exec") == 0) {
1930 did_exec = true;
1931 thread_sp->SetStopInfo(
1932 StopInfo::CreateStopReasonWithExec(*thread_sp));
1933 handled = true;
1934 }
1935 } else if (!signo) {
1936 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1937 lldb::BreakpointSiteSP bp_site_sp =
1938 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1939 pc);
1940
1941 // If the current pc is a breakpoint site then the StopInfo should
1942 // be set to Breakpoint
1943 // even though the remote stub did not set it as such. This can
1944 // happen when
1945 // the thread is involuntarily interrupted (e.g. due to stops on
1946 // other
1947 // threads) just as it is about to execute the breakpoint
1948 // instruction.
1949 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
1950 thread_sp->SetStopInfo(
1951 StopInfo::CreateStopReasonWithBreakpointSiteID(
1952 *thread_sp, bp_site_sp->GetID()));
1953 handled = true;
1954 }
1955 }
1956
1957 if (!handled && signo && did_exec == false) {
1958 if (signo == SIGTRAP5) {
1959 // Currently we are going to assume SIGTRAP means we are either
1960 // hitting a breakpoint or hardware single stepping.
1961 handled = true;
1962 addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1963 m_breakpoint_pc_offset;
1964 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1965 ->GetBreakpointSiteList()
1966 .FindByAddress(pc);
1967
1968 if (bp_site_sp) {
1969 // If the breakpoint is for this thread, then we'll report the
1970 // hit, but if it is for another thread,
1971 // we can just report no reason. We don't need to worry about
1972 // stepping over the breakpoint here, that
1973 // will be taken care of when the thread resumes and notices
1974 // that there's a breakpoint under the pc.
1975 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1976 if (m_breakpoint_pc_offset != 0)
1977 thread_sp->GetRegisterContext()->SetPC(pc);
1978 thread_sp->SetStopInfo(
1979 StopInfo::CreateStopReasonWithBreakpointSiteID(
1980 *thread_sp, bp_site_sp->GetID()));
1981 } else {
1982 StopInfoSP invalid_stop_info_sp;
1983 thread_sp->SetStopInfo(invalid_stop_info_sp);
1984 }
1985 } else {
1986 // If we were stepping then assume the stop was the result of
1987 // the trace. If we were
1988 // not stepping then report the SIGTRAP.
1989 // FIXME: We are still missing the case where we single step
1990 // over a trap instruction.
1991 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1992 thread_sp->SetStopInfo(
1993 StopInfo::CreateStopReasonToTrace(*thread_sp));
1994 else
1995 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1996 *thread_sp, signo, description.c_str()));
1997 }
1998 }
1999 if (!handled)
2000 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2001 *thread_sp, signo, description.c_str()));
2002 }
2003
2004 if (!description.empty()) {
2005 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
2006 if (stop_info_sp) {
2007 const char *stop_info_desc = stop_info_sp->GetDescription();
2008 if (!stop_info_desc || !stop_info_desc[0])
2009 stop_info_sp->SetDescription(description.c_str());
2010 } else {
2011 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2012 *thread_sp, description.c_str()));
2013 }
2014 }
2015 }
2016 }
2017 }
2018 }
2019 return thread_sp;
2020}
2021
2022lldb::ThreadSP
2023ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
2024 static ConstString g_key_tid("tid");
2025 static ConstString g_key_name("name");
2026 static ConstString g_key_reason("reason");
2027 static ConstString g_key_metype("metype");
2028 static ConstString g_key_medata("medata");
2029 static ConstString g_key_qaddr("qaddr");
2030 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2031 static ConstString g_key_associated_with_dispatch_queue(
2032 "associated_with_dispatch_queue");
2033 static ConstString g_key_queue_name("qname");
2034 static ConstString g_key_queue_kind("qkind");
2035 static ConstString g_key_queue_serial_number("qserialnum");
2036 static ConstString g_key_registers("registers");
2037 static ConstString g_key_memory("memory");
2038 static ConstString g_key_address("address");
2039 static ConstString g_key_bytes("bytes");
2040 static ConstString g_key_description("description");
2041 static ConstString g_key_signal("signal");
2042
2043 // Stop with signal and thread info
2044 lldb::tid_t tid = LLDB_INVALID_THREAD_ID0;
2045 uint8_t signo = 0;
2046 std::string value;
2047 std::string thread_name;
2048 std::string reason;
2049 std::string description;
2050 uint32_t exc_type = 0;
2051 std::vector<addr_t> exc_data;
2052 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2053 ExpeditedRegisterMap expedited_register_map;
2054 bool queue_vars_valid = false;
2055 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2056 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2057 std::string queue_name;
2058 QueueKind queue_kind = eQueueKindUnknown;
2059 uint64_t queue_serial_number = 0;
2060 // Iterate through all of the thread dictionary key/value pairs from the
2061 // structured data dictionary
2062
2063 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2064 &signo, &reason, &description, &exc_type, &exc_data,
2065 &thread_dispatch_qaddr, &queue_vars_valid,
2066 &associated_with_dispatch_queue, &dispatch_queue_t,
2067 &queue_name, &queue_kind, &queue_serial_number](
2068 ConstString key,
2069 StructuredData::Object *object) -> bool {
2070 if (key == g_key_tid) {
2071 // thread in big endian hex
2072 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID0);
2073 } else if (key == g_key_metype) {
2074 // exception type in big endian hex
2075 exc_type = object->GetIntegerValue(0);
2076 } else if (key == g_key_medata) {
2077 // exception data in big endian hex
2078 StructuredData::Array *array = object->GetAsArray();
2079 if (array) {
2080 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2081 exc_data.push_back(object->GetIntegerValue());
2082 return true; // Keep iterating through all array items
2083 });
2084 }
2085 } else if (key == g_key_name) {
2086 thread_name = object->GetStringValue();
2087 } else if (key == g_key_qaddr) {
2088 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS(18446744073709551615UL));
2089 } else if (key == g_key_queue_name) {
2090 queue_vars_valid = true;
2091 queue_name = object->GetStringValue();
2092 } else if (key == g_key_queue_kind) {
2093 std::string queue_kind_str = object->GetStringValue();
2094 if (queue_kind_str == "serial") {
2095 queue_vars_valid = true;
2096 queue_kind = eQueueKindSerial;
2097 } else if (queue_kind_str == "concurrent") {
2098 queue_vars_valid = true;
2099 queue_kind = eQueueKindConcurrent;
2100 }
2101 } else if (key == g_key_queue_serial_number) {
2102 queue_serial_number = object->GetIntegerValue(0);
2103 if (queue_serial_number != 0)
2104 queue_vars_valid = true;
2105 } else if (key == g_key_dispatch_queue_t) {
2106 dispatch_queue_t = object->GetIntegerValue(0);
2107 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS(18446744073709551615UL))
2108 queue_vars_valid = true;
2109 } else if (key == g_key_associated_with_dispatch_queue) {
2110 queue_vars_valid = true;
2111 bool associated = object->GetBooleanValue();
2112 if (associated)
2113 associated_with_dispatch_queue = eLazyBoolYes;
2114 else
2115 associated_with_dispatch_queue = eLazyBoolNo;
2116 } else if (key == g_key_reason) {
2117 reason = object->GetStringValue();
2118 } else if (key == g_key_description) {
2119 description = object->GetStringValue();
2120 } else if (key == g_key_registers) {
2121 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2122
2123 if (registers_dict) {
2124 registers_dict->ForEach(
2125 [&expedited_register_map](ConstString key,
2126 StructuredData::Object *object) -> bool {
2127 const uint32_t reg =
2128 StringConvert::ToUInt32(key.GetCString(), UINT32_MAX(4294967295U), 10);
2129 if (reg != UINT32_MAX(4294967295U))
2130 expedited_register_map[reg] = object->GetStringValue();
2131 return true; // Keep iterating through all array items
2132 });
2133 }
2134 } else if (key == g_key_memory) {
2135 StructuredData::Array *array = object->GetAsArray();
2136 if (array) {
2137 array->ForEach([this](StructuredData::Object *object) -> bool {
2138 StructuredData::Dictionary *mem_cache_dict =
2139 object->GetAsDictionary();
2140 if (mem_cache_dict) {
2141 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2142 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2143 "address", mem_cache_addr)) {
2144 if (mem_cache_addr != LLDB_INVALID_ADDRESS(18446744073709551615UL)) {
2145 llvm::StringRef str;
2146 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2147 StringExtractor bytes(str);
2148 bytes.SetFilePos(0);
2149
2150 const size_t byte_size = bytes.GetStringRef().size() / 2;
2151 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2152 const size_t bytes_copied =
2153 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2154 if (bytes_copied == byte_size)
2155 m_memory_cache.AddL1CacheData(mem_cache_addr,
2156 data_buffer_sp);
2157 }
2158 }
2159 }
2160 }
2161 return true; // Keep iterating through all array items
2162 });
2163 }
2164
2165 } else if (key == g_key_signal)
2166 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER(2147483647));
2167 return true; // Keep iterating through all dictionary key/value pairs
2168 });
2169
2170 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2171 reason, description, exc_type, exc_data,
2172 thread_dispatch_qaddr, queue_vars_valid,
2173 associated_with_dispatch_queue, dispatch_queue_t,
2174 queue_name, queue_kind, queue_serial_number);
2175}
2176
2177StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2178 stop_packet.SetFilePos(0);
2179 const char stop_type = stop_packet.GetChar();
2180 switch (stop_type) {
2181 case 'T':
2182 case 'S': {
2183 // This is a bit of a hack, but is is required. If we did exec, we
2184 // need to clear our thread lists and also know to rebuild our dynamic
2185 // register info before we lookup and threads and populate the expedited
2186 // register values so we need to know this right away so we can cleanup
2187 // and update our registers.
2188 const uint32_t stop_id = GetStopID();
2189 if (stop_id == 0) {
2190 // Our first stop, make sure we have a process ID, and also make
2191 // sure we know about our registers
2192 if (GetID() == LLDB_INVALID_PROCESS_ID0) {
2193 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2194 if (pid != LLDB_INVALID_PROCESS_ID0)
2195 SetID(pid);
2196 }
2197 BuildDynamicRegisterInfo(true);
2198 }
2199 // Stop with signal and thread info
2200 lldb::tid_t tid = LLDB_INVALID_THREAD_ID0;
2201 const uint8_t signo = stop_packet.GetHexU8();
2202 llvm::StringRef key;
2203 llvm::StringRef value;
2204 std::string thread_name;
2205 std::string reason;
2206 std::string description;
2207 uint32_t exc_type = 0;
2208 std::vector<addr_t> exc_data;
2209 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2210 bool queue_vars_valid =
2211 false; // says if locals below that start with "queue_" are valid
2212 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2213 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2214 std::string queue_name;
2215 QueueKind queue_kind = eQueueKindUnknown;
2216 uint64_t queue_serial_number = 0;
2217 ExpeditedRegisterMap expedited_register_map;
2218 while (stop_packet.GetNameColonValue(key, value)) {
2219 if (key.compare("metype") == 0) {
2220 // exception type in big endian hex
2221 value.getAsInteger(16, exc_type);
2222 } else if (key.compare("medata") == 0) {
2223 // exception data in big endian hex
2224 uint64_t x;
2225 value.getAsInteger(16, x);
2226 exc_data.push_back(x);
2227 } else if (key.compare("thread") == 0) {
2228 // thread in big endian hex
2229 if (value.getAsInteger(16, tid))
2230 tid = LLDB_INVALID_THREAD_ID0;
2231 } else if (key.compare("threads") == 0) {
2232 std::lock_guard<std::recursive_mutex> guard(
2233 m_thread_list_real.GetMutex());
2234
2235 m_thread_ids.clear();
2236 // A comma separated list of all threads in the current
2237 // process that includes the thread for this stop reply
2238 // packet
2239 lldb::tid_t tid;
2240 while (!value.empty()) {
2241 llvm::StringRef tid_str;
2242 std::tie(tid_str, value) = value.split(',');
2243 if (tid_str.getAsInteger(16, tid))
2244 tid = LLDB_INVALID_THREAD_ID0;
2245 m_thread_ids.push_back(tid);
2246 }
2247 } else if (key.compare("thread-pcs") == 0) {
2248 m_thread_pcs.clear();
2249 // A comma separated list of all threads in the current
2250 // process that includes the thread for this stop reply
2251 // packet
2252 lldb::addr_t pc;
2253 while (!value.empty()) {
2254 llvm::StringRef pc_str;
2255 std::tie(pc_str, value) = value.split(',');
2256 if (pc_str.getAsInteger(16, pc))
2257 pc = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2258 m_thread_pcs.push_back(pc);
2259 }
2260 } else if (key.compare("jstopinfo") == 0) {
2261 StringExtractor json_extractor(value);
2262 std::string json;
2263 // Now convert the HEX bytes into a string value
2264 json_extractor.GetHexByteString(json);
2265
2266 // This JSON contains thread IDs and thread stop info for all threads.
2267 // It doesn't contain expedited registers, memory or queue info.
2268 m_jstopinfo_sp = StructuredData::ParseJSON(json);
2269 } else if (key.compare("hexname") == 0) {
2270 StringExtractor name_extractor(value);
2271 std::string name;
2272 // Now convert the HEX bytes into a string value
2273 name_extractor.GetHexByteString(thread_name);
2274 } else if (key.compare("name") == 0) {
2275 thread_name = value;
2276 } else if (key.compare("qaddr") == 0) {
2277 value.getAsInteger(16, thread_dispatch_qaddr);
2278 } else if (key.compare("dispatch_queue_t") == 0) {
2279 queue_vars_valid = true;
2280 value.getAsInteger(16, dispatch_queue_t);
2281 } else if (key.compare("qname") == 0) {
2282 queue_vars_valid = true;
2283 StringExtractor name_extractor(value);
2284 // Now convert the HEX bytes into a string value
2285 name_extractor.GetHexByteString(queue_name);
2286 } else if (key.compare("qkind") == 0) {
2287 queue_kind = llvm::StringSwitch<QueueKind>(value)
2288 .Case("serial", eQueueKindSerial)
2289 .Case("concurrent", eQueueKindConcurrent)
2290 .Default(eQueueKindUnknown);
2291 queue_vars_valid = queue_kind != eQueueKindUnknown;
2292 } else if (key.compare("qserialnum") == 0) {
2293 if (!value.getAsInteger(0, queue_serial_number))
2294 queue_vars_valid = true;
2295 } else if (key.compare("reason") == 0) {
2296 reason = value;
2297 } else if (key.compare("description") == 0) {
2298 StringExtractor desc_extractor(value);
2299 // Now convert the HEX bytes into a string value
2300 desc_extractor.GetHexByteString(description);
2301 } else if (key.compare("memory") == 0) {
2302 // Expedited memory. GDB servers can choose to send back expedited
2303 // memory
2304 // that can populate the L1 memory cache in the process so that things
2305 // like
2306 // the frame pointer backchain can be expedited. This will help stack
2307 // backtracing be more efficient by not having to send as many memory
2308 // read
2309 // requests down the remote GDB server.
2310
2311 // Key/value pair format: memory:<addr>=<bytes>;
2312 // <addr> is a number whose base will be interpreted by the prefix:
2313 // "0x[0-9a-fA-F]+" for hex
2314 // "0[0-7]+" for octal
2315 // "[1-9]+" for decimal
2316 // <bytes> is native endian ASCII hex bytes just like the register
2317 // values
2318 llvm::StringRef addr_str, bytes_str;
2319 std::tie(addr_str, bytes_str) = value.split('=');
2320 if (!addr_str.empty() && !bytes_str.empty()) {
2321 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2322 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2323 StringExtractor bytes(bytes_str);
2324 const size_t byte_size = bytes.GetBytesLeft() / 2;
2325 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2326 const size_t bytes_copied =
2327 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2328 if (bytes_copied == byte_size)
2329 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2330 }
2331 }
2332 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2333 key.compare("awatch") == 0) {
2334 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2335 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2336 value.getAsInteger(16, wp_addr);
2337
2338 WatchpointSP wp_sp =
2339 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2340 uint32_t wp_index = LLDB_INVALID_INDEX32(4294967295U);
2341
2342 if (wp_sp)
2343 wp_index = wp_sp->GetHardwareIndex();
2344
2345 reason = "watchpoint";
2346 StreamString ostr;
2347 ostr.Printf("%" PRIu64"l" "u" " %" PRIu32"u", wp_addr, wp_index);
2348 description = ostr.GetString();
2349 } else if (key.compare("library") == 0) {
2350 LoadModules();
2351 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2352 uint32_t reg = UINT32_MAX(4294967295U);
2353 if (!key.getAsInteger(16, reg))
2354 expedited_register_map[reg] = std::move(value);
2355 }
2356 }
2357
2358 if (tid == LLDB_INVALID_THREAD_ID0) {
2359 // A thread id may be invalid if the response is old style 'S' packet
2360 // which does not provide the
2361 // thread information. So update the thread list and choose the first one.
2362 UpdateThreadIDList();
2363
2364 if (!m_thread_ids.empty()) {
2365 tid = m_thread_ids.front();
2366 }
2367 }
2368
2369 ThreadSP thread_sp = SetThreadStopInfo(
2370 tid, expedited_register_map, signo, thread_name, reason, description,
2371 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2372 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2373 queue_kind, queue_serial_number);
2374
2375 return eStateStopped;
2376 } break;
2377
2378 case 'W':
2379 case 'X':
2380 // process exited
2381 return eStateExited;
2382
2383 default:
2384 break;
2385 }
2386 return eStateInvalid;
2387}
2388
2389void ProcessGDBRemote::RefreshStateAfterStop() {
2390 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2391
2392 m_thread_ids.clear();
2393 m_thread_pcs.clear();
2394 // Set the thread stop info. It might have a "threads" key whose value is
2395 // a list of all thread IDs in the current process, so m_thread_ids might
2396 // get set.
2397
2398 // Scope for the lock
2399 {
2400 // Lock the thread stack while we access it
2401 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2402 // Get the number of stop packets on the stack
2403 int nItems = m_stop_packet_stack.size();
2404 // Iterate over them
2405 for (int i = 0; i < nItems; i++) {
2406 // Get the thread stop info
2407 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2408 // Process thread stop info
2409 SetThreadStopInfo(stop_info);
2410 }
2411 // Clear the thread stop stack
2412 m_stop_packet_stack.clear();
2413 }
2414
2415 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2416 if (m_thread_ids.empty()) {
2417 // No, we need to fetch the thread list manually
2418 UpdateThreadIDList();
2419 }
2420
2421 // If we have queried for a default thread id
2422 if (m_initial_tid != LLDB_INVALID_THREAD_ID0) {
2423 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2424 m_initial_tid = LLDB_INVALID_THREAD_ID0;
2425 }
2426
2427 // Let all threads recover from stopping and do any clean up based
2428 // on the previous thread state (if any).
2429 m_thread_list_real.RefreshStateAfterStop();
2430}
2431
2432Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2433 Status error;
2434
2435 if (m_public_state.GetValue() == eStateAttaching) {
2436 // We are being asked to halt during an attach. We need to just close
2437 // our file handle and debugserver will go away, and we can be done...
2438 m_gdb_comm.Disconnect();
2439 } else
2440 caused_stop = m_gdb_comm.Interrupt();
2441 return error;
2442}
2443
2444Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2445 Status error;
2446 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
2447 if (log)
2448 log->Printf("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2449
2450 error = m_gdb_comm.Detach(keep_stopped);
2451 if (log) {
2452 if (error.Success())
2453 log->PutCString(
2454 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2455 else
2456 log->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2457 error.AsCString() ? error.AsCString() : "<unknown error>");
2458 }
2459
2460 if (!error.Success())
2461 return error;
2462
2463 // Sleep for one second to let the process get all detached...
2464 StopAsyncThread();
2465
2466 SetPrivateState(eStateDetached);
2467 ResumePrivateStateThread();
2468
2469 // KillDebugserverProcess ();
2470 return error;
2471}
2472
2473Status ProcessGDBRemote::DoDestroy() {
2474 Status error;
2475 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
2476 if (log)
2477 log->Printf("ProcessGDBRemote::DoDestroy()");
2478
2479 // There is a bug in older iOS debugservers where they don't shut down the
2480 // process
2481 // they are debugging properly. If the process is sitting at a breakpoint or
2482 // an exception,
2483 // this can cause problems with restarting. So we check to see if any of our
2484 // threads are stopped
2485 // at a breakpoint, and if so we remove all the breakpoints, resume the
2486 // process, and THEN
2487 // destroy it again.
2488 //
2489 // Note, we don't have a good way to test the version of debugserver, but I
2490 // happen to know that
2491 // the set of all the iOS debugservers which don't support
2492 // GetThreadSuffixSupported() and that of
2493 // the debugservers with this bug are equal. There really should be a better
2494 // way to test this!
2495 //
2496 // We also use m_destroy_tried_resuming to make sure we only do this once, if
2497 // we resume and then halt and
2498 // get called here to destroy again and we're still at a breakpoint or
2499 // exception, then we should
2500 // just do the straight-forward kill.
2501 //
2502 // And of course, if we weren't able to stop the process by the time we get
2503 // here, it isn't
2504 // necessary (or helpful) to do any of this.
2505
2506 if (!m_gdb_comm.GetThreadSuffixSupported() &&
2507 m_public_state.GetValue() != eStateRunning) {
2508 PlatformSP platform_sp = GetTarget().GetPlatform();
2509
2510 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2511 if (platform_sp && platform_sp->GetName() &&
2512 platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
2513 if (m_destroy_tried_resuming) {
2514 if (log)
2515 log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2516 "destroy once already, not doing it again.");
2517 } else {
2518 // At present, the plans are discarded and the breakpoints disabled
2519 // Process::Destroy,
2520 // but we really need it to happen here and it doesn't matter if we do
2521 // it twice.
2522 m_thread_list.DiscardThreadPlans();
2523 DisableAllBreakpointSites();
2524
2525 bool stop_looks_like_crash = false;
2526 ThreadList &threads = GetThreadList();
2527
2528 {
2529 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2530
2531 size_t num_threads = threads.GetSize();
2532 for (size_t i = 0; i < num_threads; i++) {
2533 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2534 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2535 StopReason reason = eStopReasonInvalid;
2536 if (stop_info_sp)
2537 reason = stop_info_sp->GetStopReason();
2538 if (reason == eStopReasonBreakpoint ||
2539 reason == eStopReasonException) {
2540 if (log)
2541 log->Printf(
2542 "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64"l" "x"
2543 " stopped with reason: %s.",
2544 thread_sp->GetProtocolID(), stop_info_sp->GetDescription());
2545 stop_looks_like_crash = true;
2546 break;
2547 }
2548 }
2549 }
2550
2551 if (stop_looks_like_crash) {
2552 if (log)
2553 log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2554 "breakpoint, continue and then kill.");
2555 m_destroy_tried_resuming = true;
2556
2557 // If we are going to run again before killing, it would be good to
2558 // suspend all the threads
2559 // before resuming so they won't get into more trouble. Sadly, for
2560 // the threads stopped with
2561 // the breakpoint or exception, the exception doesn't get cleared if
2562 // it is suspended, so we do
2563 // have to run the risk of letting those threads proceed a bit.
2564
2565 {
2566 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2567
2568 size_t num_threads = threads.GetSize();
2569 for (size_t i = 0; i < num_threads; i++) {
2570 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2571 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2572 StopReason reason = eStopReasonInvalid;
2573 if (stop_info_sp)
2574 reason = stop_info_sp->GetStopReason();
2575 if (reason != eStopReasonBreakpoint &&
2576 reason != eStopReasonException) {
2577 if (log)
2578 log->Printf("ProcessGDBRemote::DoDestroy() - Suspending "
2579 "thread: 0x%4.4" PRIx64"l" "x" " before running.",
2580 thread_sp->GetProtocolID());
2581 thread_sp->SetResumeState(eStateSuspended);
2582 }
2583 }
2584 }
2585 Resume();
2586 return Destroy(false);
2587 }
2588 }
2589 }
2590 }
2591
2592 // Interrupt if our inferior is running...
2593 int exit_status = SIGABRT6;
2594 std::string exit_string;
2595
2596 if (m_gdb_comm.IsConnected()) {
2597 if (m_public_state.GetValue() != eStateAttaching) {
2598 StringExtractorGDBRemote response;
2599 bool send_async = true;
2600 GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
2601 std::chrono::seconds(3));
2602
2603 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
2604 GDBRemoteCommunication::PacketResult::Success) {
2605 char packet_cmd = response.GetChar(0);
2606
2607 if (packet_cmd == 'W' || packet_cmd == 'X') {
2608#if defined(__APPLE__)
2609 // For Native processes on Mac OS X, we launch through the Host
2610 // Platform, then hand the process off
2611 // to debugserver, which becomes the parent process through
2612 // "PT_ATTACH". Then when we go to kill
2613 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we
2614 // call waitpid which returns
2615 // with no error and the correct status. But amusingly enough that
2616 // doesn't seem to actually reap
2617 // the process, but instead it is left around as a Zombie. Probably
2618 // the kernel is in the process of
2619 // switching ownership back to lldb which was the original parent, and
2620 // gets confused in the handoff.
2621 // Anyway, so call waitpid here to finally reap it.
2622 PlatformSP platform_sp(GetTarget().GetPlatform());
2623 if (platform_sp && platform_sp->IsHost()) {
2624 int status;
2625 ::pid_t reap_pid;
2626 reap_pid = waitpid(GetID(), &status, WNOHANG1);
2627 if (log)
2628 log->Printf("Reaped pid: %d, status: %d.\n", reap_pid, status);
2629 }
2630#endif
2631 SetLastStopPacket(response);
2632 ClearThreadIDList();
2633 exit_status = response.GetHexU8();
2634 } else {
2635 if (log)
2636 log->Printf("ProcessGDBRemote::DoDestroy - got unexpected response "
2637 "to k packet: %s",
2638 response.GetStringRef().c_str());
2639 exit_string.assign("got unexpected response to k packet: ");
2640 exit_string.append(response.GetStringRef());
2641 }
2642 } else {
2643 if (log)
2644 log->Printf("ProcessGDBRemote::DoDestroy - failed to send k packet");
2645 exit_string.assign("failed to send the k packet");
2646 }
2647 } else {
2648 if (log)
2649 log->Printf("ProcessGDBRemote::DoDestroy - killed or interrupted while "
2650 "attaching");
2651 exit_string.assign("killed or interrupted while attaching.");
2652 }
2653 } else {
2654 // If we missed setting the exit status on the way out, do it here.
2655 // NB set exit status can be called multiple times, the first one sets the
2656 // status.
2657 exit_string.assign("destroying when not connected to debugserver");
2658 }
2659
2660 SetExitStatus(exit_status, exit_string.c_str());
2661
2662 StopAsyncThread();
2663 KillDebugserverProcess();
2664 return error;
2665}
2666
2667void ProcessGDBRemote::SetLastStopPacket(
2668 const StringExtractorGDBRemote &response) {
2669 const bool did_exec =
2670 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2671 if (did_exec) {
2672 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
2673 if (log)
2674 log->Printf("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2675
2676 m_thread_list_real.Clear();
2677 m_thread_list.Clear();
2678 BuildDynamicRegisterInfo(true);
2679 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2680 }
2681
2682 // Scope the lock
2683 {
2684 // Lock the thread stack while we access it
2685 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2686
2687 // We are are not using non-stop mode, there can only be one last stop
2688 // reply packet, so clear the list.
2689 if (GetTarget().GetNonStopModeEnabled() == false)
2690 m_stop_packet_stack.clear();
2691
2692 // Add this stop packet to the stop packet stack
2693 // This stack will get popped and examined when we switch to the
2694 // Stopped state
2695 m_stop_packet_stack.push_back(response);
2696 }
2697}
2698
2699void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2700 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2701}
2702
2703//------------------------------------------------------------------
2704// Process Queries
2705//------------------------------------------------------------------
2706
2707bool ProcessGDBRemote::IsAlive() {
2708 return m_gdb_comm.IsConnected() && Process::IsAlive();
2709}
2710
2711addr_t ProcessGDBRemote::GetImageInfoAddress() {
2712 // request the link map address via the $qShlibInfoAddr packet
2713 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2714
2715 // the loaded module list can also provides a link map address
2716 if (addr == LLDB_INVALID_ADDRESS(18446744073709551615UL)) {
2717 LoadedModuleInfoList list;
2718 if (GetLoadedModuleList(list).Success())
2719 addr = list.m_link_map;
2720 }
2721
2722 return addr;
2723}
2724
2725void ProcessGDBRemote::WillPublicStop() {
2726 // See if the GDB remote client supports the JSON threads info.
2727 // If so, we gather stop info for all threads, expedited registers,
2728 // expedited memory, runtime queue information (iOS and MacOSX only),
2729 // and more. Expediting memory will help stack backtracing be much
2730 // faster. Expediting registers will make sure we don't have to read
2731 // the thread registers for GPRs.
2732 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2733
2734 if (m_jthreadsinfo_sp) {
2735 // Now set the stop info for each thread and also expedite any registers
2736 // and memory that was in the jThreadsInfo response.
2737 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2738 if (thread_infos) {
2739 const size_t n = thread_infos->GetSize();
2740 for (size_t i = 0; i < n; ++i) {
2741 StructuredData::Dictionary *thread_dict =
2742 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2743 if (thread_dict)
2744 SetThreadStopInfo(thread_dict);
2745 }
2746 }
2747 }
2748}
2749
2750//------------------------------------------------------------------
2751// Process Memory
2752//------------------------------------------------------------------
2753size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2754 Status &error) {
2755 GetMaxMemorySize();
2756 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2757 // M and m packets take 2 bytes for 1 byte of memory
2758 size_t max_memory_size =
2759 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2760 if (size > max_memory_size) {
2761 // Keep memory read sizes down to a sane limit. This function will be
2762 // called multiple times in order to complete the task by
2763 // lldb_private::Process so it is ok to do this.
2764 size = max_memory_size;
2765 }
2766
2767 char packet[64];
2768 int packet_len;
2769 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64"l" "x" ",%" PRIx64"l" "x",
2770 binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2771 (uint64_t)size);
2772 assert(packet_len + 1 < (int)sizeof(packet))((packet_len + 1 < (int)sizeof(packet)) ? static_cast<void
> (0) : __assert_fail ("packet_len + 1 < (int)sizeof(packet)"
, "/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 2772, __PRETTY_FUNCTION__))
;
2773 UNUSED_IF_ASSERT_DISABLED(packet_len)((void)(packet_len));
2774 StringExtractorGDBRemote response;
2775 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
2776 GDBRemoteCommunication::PacketResult::Success) {
2777 if (response.IsNormalResponse()) {
2778 error.Clear();
2779 if (binary_memory_read) {
2780 // The lower level GDBRemoteCommunication packet receive layer has
2781 // already de-quoted any
2782 // 0x7d character escaping that was present in the packet
2783
2784 size_t data_received_size = response.GetBytesLeft();
2785 if (data_received_size > size) {
2786 // Don't write past the end of BUF if the remote debug server gave us
2787 // too
2788 // much data for some reason.
2789 data_received_size = size;
2790 }
2791 memcpy(buf, response.GetStringRef().data(), data_received_size);
2792 return data_received_size;
2793 } else {
2794 return response.GetHexBytes(
2795 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2796 }
2797 } else if (response.IsErrorResponse())
2798 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64"l" "x", addr);
2799 else if (response.IsUnsupportedResponse())
2800 error.SetErrorStringWithFormat(
2801 "GDB server does not support reading memory");
2802 else
2803 error.SetErrorStringWithFormat(
2804 "unexpected response to GDB server memory read packet '%s': '%s'",
2805 packet, response.GetStringRef().c_str());
2806 } else {
2807 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2808 }
2809 return 0;
2810}
2811
2812size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2813 size_t size, Status &error) {
2814 GetMaxMemorySize();
2815 // M and m packets take 2 bytes for 1 byte of memory
2816 size_t max_memory_size = m_max_memory_size / 2;
2817 if (size > max_memory_size) {
2818 // Keep memory read sizes down to a sane limit. This function will be
2819 // called multiple times in order to complete the task by
2820 // lldb_private::Process so it is ok to do this.
2821 size = max_memory_size;
2822 }
2823
2824 StreamString packet;
2825 packet.Printf("M%" PRIx64"l" "x" ",%" PRIx64"l" "x" ":", addr, (uint64_t)size);
2826 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2827 endian::InlHostByteOrder());
2828 StringExtractorGDBRemote response;
2829 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2830 true) ==
2831 GDBRemoteCommunication::PacketResult::Success) {
2832 if (response.IsOKResponse()) {
2833 error.Clear();
2834 return size;
2835 } else if (response.IsErrorResponse())
2836 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64"l" "x",
2837 addr);
2838 else if (response.IsUnsupportedResponse())
2839 error.SetErrorStringWithFormat(
2840 "GDB server does not support writing memory");
2841 else
2842 error.SetErrorStringWithFormat(
2843 "unexpected response to GDB server memory write packet '%s': '%s'",
2844 packet.GetData(), response.GetStringRef().c_str());
2845 } else {
2846 error.SetErrorStringWithFormat("failed to send packet: '%s'",
2847 packet.GetData());
2848 }
2849 return 0;
2850}
2851
2852lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2853 uint32_t permissions,
2854 Status &error) {
2855 Log *log(
2856 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS(1u << 1) | LIBLLDB_LOG_EXPRESSIONS(1u << 8)));
2857 addr_t allocated_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2858
2859 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2860 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2861 if (allocated_addr != LLDB_INVALID_ADDRESS(18446744073709551615UL) ||
2862 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2863 return allocated_addr;
2864 }
2865
2866 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2867 // Call mmap() to create memory in the inferior..
2868 unsigned prot = 0;
2869 if (permissions & lldb::ePermissionsReadable)
2870 prot |= eMmapProtRead;
2871 if (permissions & lldb::ePermissionsWritable)
2872 prot |= eMmapProtWrite;
2873 if (permissions & lldb::ePermissionsExecutable)
2874 prot |= eMmapProtExec;
2875
2876 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2877 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2878 m_addr_to_mmap_size[allocated_addr] = size;
2879 else {
2880 allocated_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2881 if (log)
2882 log->Printf("ProcessGDBRemote::%s no direct stub support for memory "
2883 "allocation, and InferiorCallMmap also failed - is stub "
2884 "missing register context save/restore capability?",
2885 __FUNCTION__);
2886 }
2887 }
2888
2889 if (allocated_addr == LLDB_INVALID_ADDRESS(18446744073709551615UL))
2890 error.SetErrorStringWithFormat(
2891 "unable to allocate %" PRIu64"l" "u" " bytes of memory with permissions %s",
2892 (uint64_t)size, GetPermissionsAsCString(permissions));
2893 else
2894 error.Clear();
2895 return allocated_addr;
2896}
2897
2898Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
2899 MemoryRegionInfo &region_info) {
2900
2901 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2902 return error;
2903}
2904
2905Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
2906
2907 Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
2908 return error;
2909}
2910
2911Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2912 Status error(m_gdb_comm.GetWatchpointSupportInfo(
2913 num, after, GetTarget().GetArchitecture()));
2914 return error;
2915}
2916
2917Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
2918 Status error;
2919 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2920
2921 switch (supported) {
2922 case eLazyBoolCalculate:
2923 // We should never be deallocating memory without allocating memory
2924 // first so we should never get eLazyBoolCalculate
2925 error.SetErrorString(
2926 "tried to deallocate memory without ever allocating memory");
2927 break;
2928
2929 case eLazyBoolYes:
2930 if (!m_gdb_comm.DeallocateMemory(addr))
2931 error.SetErrorStringWithFormat(
2932 "unable to deallocate memory at 0x%" PRIx64"l" "x", addr);
2933 break;
2934
2935 case eLazyBoolNo:
2936 // Call munmap() to deallocate memory in the inferior..
2937 {
2938 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2939 if (pos != m_addr_to_mmap_size.end() &&
2940 InferiorCallMunmap(this, addr, pos->second))
2941 m_addr_to_mmap_size.erase(pos);
2942 else
2943 error.SetErrorStringWithFormat(
2944 "unable to deallocate memory at 0x%" PRIx64"l" "x", addr);
2945 }
2946 break;
2947 }
2948
2949 return error;
2950}
2951
2952//------------------------------------------------------------------
2953// Process STDIO
2954//------------------------------------------------------------------
2955size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
2956 Status &error) {
2957 if (m_stdio_communication.IsConnected()) {
2958 ConnectionStatus status;
2959 m_stdio_communication.Write(src, src_len, status, NULL__null);
2960 } else if (m_stdin_forward) {
2961 m_gdb_comm.SendStdinNotification(src, src_len);
2962 }
2963 return 0;
2964}
2965
2966Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
2967 Status error;
2968 assert(bp_site != NULL)((bp_site != __null) ? static_cast<void> (0) : __assert_fail
("bp_site != NULL", "/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 2968, __PRETTY_FUNCTION__))
;
2969
2970 // Get logging info
2971 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS(1u << 7)));
2972 user_id_t site_id = bp_site->GetID();
2973
2974 // Get the breakpoint address
2975 const addr_t addr = bp_site->GetLoadAddress();
2976
2977 // Log that a breakpoint was requested
2978 if (log)
2979 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64"l" "u"
2980 ") address = 0x%" PRIx64"l" "x",
2981 site_id, (uint64_t)addr);
2982
2983 // Breakpoint already exists and is enabled
2984 if (bp_site->IsEnabled()) {
2985 if (log)
2986 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64"l" "u"
2987 ") address = 0x%" PRIx64"l" "x" " -- SUCCESS (already enabled)",
2988 site_id, (uint64_t)addr);
2989 return error;
2990 }
2991
2992 // Get the software breakpoint trap opcode size
2993 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2994
2995 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
2996 // breakpoint type
2997 // is supported by the remote stub. These are set to true by default, and
2998 // later set to false
2999 // only after we receive an unimplemented response when sending a breakpoint
3000 // packet. This means
3001 // initially that unless we were specifically instructed to use a hardware
3002 // breakpoint, LLDB will
3003 // attempt to set a software breakpoint. HardwareRequired() also queries a
3004 // boolean variable which
3005 // indicates if the user specifically asked for hardware breakpoints. If true
3006 // then we will
3007 // skip over software breakpoints.
3008 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3009 (!bp_site->HardwareRequired())) {
3010 // Try to send off a software breakpoint packet ($Z0)
3011 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3012 eBreakpointSoftware, true, addr, bp_op_size);
3013 if (error_no == 0) {
3014 // The breakpoint was placed successfully
3015 bp_site->SetEnabled(true);
3016 bp_site->SetType(BreakpointSite::eExternal);
3017 return error;
3018 }
3019
3020 // SendGDBStoppointTypePacket() will return an error if it was unable to set
3021 // this
3022 // breakpoint. We need to differentiate between a error specific to placing
3023 // this breakpoint
3024 // or if we have learned that this breakpoint type is unsupported. To do
3025 // this, we
3026 // must test the support boolean for this breakpoint type to see if it now
3027 // indicates that
3028 // this breakpoint type is unsupported. If they are still supported then we
3029 // should return
3030 // with the error code. If they are now unsupported, then we would like to
3031 // fall through
3032 // and try another form of breakpoint.
3033 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3034 if (error_no != UINT8_MAX(255))
3035 error.SetErrorStringWithFormat(
3036 "error: %d sending the breakpoint request", errno(*__errno_location ()));
3037 else
3038 error.SetErrorString("error sending the breakpoint request");
3039 return error;
3040 }
3041
3042 // We reach here when software breakpoints have been found to be
3043 // unsupported. For future
3044 // calls to set a breakpoint, we will not attempt to set a breakpoint with a
3045 // type that is
3046 // known not to be supported.
3047 if (log)
3048 log->Printf("Software breakpoints are unsupported");
3049
3050 // So we will fall through and try a hardware breakpoint
3051 }
3052
3053 // The process of setting a hardware breakpoint is much the same as above. We
3054 // check the
3055 // supported boolean for this breakpoint type, and if it is thought to be
3056 // supported then we
3057 // will try to set this breakpoint with a hardware breakpoint.
3058 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3059 // Try to send off a hardware breakpoint packet ($Z1)
3060 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3061 eBreakpointHardware, true, addr, bp_op_size);
3062 if (error_no == 0) {
3063 // The breakpoint was placed successfully
3064 bp_site->SetEnabled(true);
3065 bp_site->SetType(BreakpointSite::eHardware);
3066 return error;
3067 }
3068
3069 // Check if the error was something other then an unsupported breakpoint
3070 // type
3071 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3072 // Unable to set this hardware breakpoint
3073 if (error_no != UINT8_MAX(255))
3074 error.SetErrorStringWithFormat(
3075 "error: %d sending the hardware breakpoint request "
3076 "(hardware breakpoint resources might be exhausted or unavailable)",
3077 error_no);
3078 else
3079 error.SetErrorString("error sending the hardware breakpoint request "
3080 "(hardware breakpoint resources "
3081 "might be exhausted or unavailable)");
3082 return error;
3083 }
3084
3085 // We will reach here when the stub gives an unsupported response to a
3086 // hardware breakpoint
3087 if (log)
3088 log->Printf("Hardware breakpoints are unsupported");
3089
3090 // Finally we will falling through to a #trap style breakpoint
3091 }
3092
3093 // Don't fall through when hardware breakpoints were specifically requested
3094 if (bp_site->HardwareRequired()) {
3095 error.SetErrorString("hardware breakpoints are not supported");
3096 return error;
3097 }
3098
3099 // As a last resort we want to place a manual breakpoint. An instruction
3100 // is placed into the process memory using memory write packets.
3101 return EnableSoftwareBreakpoint(bp_site);
3102}
3103
3104Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3105 Status error;
3106 assert(bp_site != NULL)((bp_site != __null) ? static_cast<void> (0) : __assert_fail
("bp_site != NULL", "/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 3106, __PRETTY_FUNCTION__))
;
3107 addr_t addr = bp_site->GetLoadAddress();
3108 user_id_t site_id = bp_site->GetID();
3109 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS(1u << 7)));
3110 if (log)
3111 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64"l" "u"
3112 ") addr = 0x%8.8" PRIx64"l" "x",
3113 site_id, (uint64_t)addr);
3114
3115 if (bp_site->IsEnabled()) {
3116 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3117
3118 BreakpointSite::Type bp_type = bp_site->GetType();
3119 switch (bp_type) {
3120 case BreakpointSite::eSoftware:
3121 error = DisableSoftwareBreakpoint(bp_site);
3122 break;
3123
3124 case BreakpointSite::eHardware:
3125 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3126 addr, bp_op_size))
3127 error.SetErrorToGenericError();
3128 break;
3129
3130 case BreakpointSite::eExternal: {
3131 GDBStoppointType stoppoint_type;
3132 if (bp_site->IsHardware())
3133 stoppoint_type = eBreakpointHardware;
3134 else
3135 stoppoint_type = eBreakpointSoftware;
3136
3137 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr,
3138 bp_op_size))
3139 error.SetErrorToGenericError();
3140 } break;
3141 }
3142 if (error.Success())
3143 bp_site->SetEnabled(false);
3144 } else {
3145 if (log)
3146 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64"l" "u"
3147 ") addr = 0x%8.8" PRIx64"l" "x" " -- SUCCESS (already disabled)",
3148 site_id, (uint64_t)addr);
3149 return error;
3150 }
3151
3152 if (error.Success())
3153 error.SetErrorToGenericError();
3154 return error;
3155}
3156
3157// Pre-requisite: wp != NULL.
3158static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3159 assert(wp)((wp) ? static_cast<void> (0) : __assert_fail ("wp", "/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 3159, __PRETTY_FUNCTION__))
;
3160 bool watch_read = wp->WatchpointRead();
3161 bool watch_write = wp->WatchpointWrite();
3162
3163 // watch_read and watch_write cannot both be false.
3164 assert(watch_read || watch_write)((watch_read || watch_write) ? static_cast<void> (0) : __assert_fail
("watch_read || watch_write", "/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 3164, __PRETTY_FUNCTION__))
;
3165 if (watch_read && watch_write)
3166 return eWatchpointReadWrite;
3167 else if (watch_read)
3168 return eWatchpointRead;
3169 else // Must be watch_write, then.
3170 return eWatchpointWrite;
3171}
3172
3173Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3174 Status error;
3175 if (wp) {
3176 user_id_t watchID = wp->GetID();
3177 addr_t addr = wp->GetLoadAddress();
3178 Log *log(
3179 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS(1u << 8)));
3180 if (log)
3181 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64"l" "u" ")",
3182 watchID);
3183 if (wp->IsEnabled()) {
3184 if (log)
3185 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64"l" "u"
3186 ") addr = 0x%8.8" PRIx64"l" "x" ": watchpoint already enabled.",
3187 watchID, (uint64_t)addr);
3188 return error;
3189 }
3190
3191 GDBStoppointType type = GetGDBStoppointType(wp);
3192 // Pass down an appropriate z/Z packet...
3193 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3194 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3195 wp->GetByteSize()) == 0) {
3196 wp->SetEnabled(true, notify);
3197 return error;
3198 } else
3199 error.SetErrorString("sending gdb watchpoint packet failed");
3200 } else
3201 error.SetErrorString("watchpoints not supported");
3202 } else {
3203 error.SetErrorString("Watchpoint argument was NULL.");
3204 }
3205 if (error.Success())
3206 error.SetErrorToGenericError();
3207 return error;
3208}
3209
3210Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3211 Status error;
3212 if (wp) {
3213 user_id_t watchID = wp->GetID();
3214
3215 Log *log(
3216 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS(1u << 8)));
3217
3218 addr_t addr = wp->GetLoadAddress();
3219
3220 if (log)
3221 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64"l" "u"
3222 ") addr = 0x%8.8" PRIx64"l" "x",
3223 watchID, (uint64_t)addr);
3224
3225 if (!wp->IsEnabled()) {
3226 if (log)
3227 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64"l" "u"
3228 ") addr = 0x%8.8" PRIx64"l" "x" " -- SUCCESS (already disabled)",
3229 watchID, (uint64_t)addr);
3230 // See also 'class WatchpointSentry' within StopInfo.cpp.
3231 // This disabling attempt might come from the user-supplied actions, we'll
3232 // route it in order for
3233 // the watchpoint object to intelligently process this action.
3234 wp->SetEnabled(false, notify);
3235 return error;
3236 }
3237
3238 if (wp->IsHardware()) {
3239 GDBStoppointType type = GetGDBStoppointType(wp);
3240 // Pass down an appropriate z/Z packet...
3241 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3242 wp->GetByteSize()) == 0) {
3243 wp->SetEnabled(false, notify);
3244 return error;
3245 } else
3246 error.SetErrorString("sending gdb watchpoint packet failed");
3247 }
3248 // TODO: clear software watchpoints if we implement them
3249 } else {
3250 error.SetErrorString("Watchpoint argument was NULL.");
3251 }
3252 if (error.Success())
3253 error.SetErrorToGenericError();
3254 return error;
3255}
3256
3257void ProcessGDBRemote::Clear() {
3258 m_flags = 0;
3259 m_thread_list_real.Clear();
3260 m_thread_list.Clear();
3261}
3262
3263Status ProcessGDBRemote::DoSignal(int signo) {
3264 Status error;
3265 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
3266 if (log)
3267 log->Printf("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3268
3269 if (!m_gdb_comm.SendAsyncSignal(signo))
3270 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3271 return error;
3272}
3273
3274Status
3275ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
3276 // Make sure we aren't already connected?
3277 if (m_gdb_comm.IsConnected())
3278 return Status();
3279
3280 PlatformSP platform_sp(GetTarget().GetPlatform());
3281 if (platform_sp && !platform_sp->IsHost())
3282 return Status("Lost debug server connection");
3283
3284 auto error = LaunchAndConnectToDebugserver(process_info);
3285 if (error.Fail()) {
3286 const char *error_string = error.AsCString();
3287 if (error_string == nullptr)
3288 error_string = "unable to launch " DEBUGSERVER_BASENAME"debugserver";
Value stored to 'error_string' is never read
3289 }
3290 return error;
3291}
3292#if !defined(_WIN32)
3293#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION1 1
3294#endif
3295
3296#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION1
3297static bool SetCloexecFlag(int fd) {
3298#if defined(FD_CLOEXEC1)
3299 int flags = ::fcntl(fd, F_GETFD1);
3300 if (flags == -1)
3301 return false;
3302 return (::fcntl(fd, F_SETFD2, flags | FD_CLOEXEC1) == 0);
3303#else
3304 return false;
3305#endif
3306}
3307#endif
3308
3309Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
3310 const ProcessInfo &process_info) {
3311 using namespace std::placeholders; // For _1, _2, etc.
3312
3313 Status error;
3314 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID0) {
3315 // If we locate debugserver, keep that located version around
3316 static FileSpec g_debugserver_file_spec;
3317
3318 ProcessLaunchInfo debugserver_launch_info;
3319 // Make debugserver run in its own session so signals generated by
3320 // special terminal key sequences (^C) don't affect debugserver.
3321 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3322
3323 const std::weak_ptr<ProcessGDBRemote> this_wp =
3324 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3325 debugserver_launch_info.SetMonitorProcessCallback(
3326 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3327 debugserver_launch_info.SetUserID(process_info.GetUserID());
3328
3329 int communication_fd = -1;
3330#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION1
3331 // Auto close the sockets we might open up unless everything goes OK. This
3332 // helps us not leak file descriptors when things go wrong.
3333 lldb_utility::CleanUp<int, int> our_socket(-1, -1, close);
3334 lldb_utility::CleanUp<int, int> gdb_socket(-1, -1, close);
3335
3336 // Use a socketpair on non-Windows systems for security and performance
3337 // reasons.
3338 {
3339 int sockets[2]; /* the pair of socket descriptors */
3340 if (socketpair(AF_UNIX1, SOCK_STREAMSOCK_STREAM, 0, sockets) == -1) {
3341 error.SetErrorToErrno();
3342 return error;
3343 }
3344
3345 our_socket.set(sockets[0]);
3346 gdb_socket.set(sockets[1]);
3347 }
3348
3349 // Don't let any child processes inherit our communication socket
3350 SetCloexecFlag(our_socket.get());
3351 communication_fd = gdb_socket.get();
3352#endif
3353
3354 error = m_gdb_comm.StartDebugserverProcess(
3355 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3356 nullptr, nullptr, communication_fd);
3357
3358 if (error.Success())
3359 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3360 else
3361 m_debugserver_pid = LLDB_INVALID_PROCESS_ID0;
3362
3363 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID0) {
3364#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION1
3365 // Our process spawned correctly, we can now set our connection to use our
3366 // end of the socket pair
3367 m_gdb_comm.SetConnection(
3368 new ConnectionFileDescriptor(our_socket.release(), true));
3369#endif
3370 StartAsyncThread();
3371 }
3372
3373 if (error.Fail()) {
3374 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
3375
3376 if (log)
3377 log->Printf("failed to start debugserver process: %s",
3378 error.AsCString());
3379 return error;
3380 }
3381
3382 if (m_gdb_comm.IsConnected()) {
3383 // Finish the connection process by doing the handshake without connecting
3384 // (send NULL URL)
3385 ConnectToDebugserver("");
3386 } else {
3387 error.SetErrorString("connection failed");
3388 }
3389 }
3390 return error;
3391}
3392
3393bool ProcessGDBRemote::MonitorDebugserverProcess(
3394 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3395 bool exited, // True if the process did exit
3396 int signo, // Zero for no signal
3397 int exit_status // Exit value of process if signal is zero
3398 ) {
3399 // "debugserver_pid" argument passed in is the process ID for
3400 // debugserver that we are tracking...
3401 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
3402 const bool handled = true;
3403
3404 if (log)
3405 log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64"l" "u"
3406 ", signo=%i (0x%x), exit_status=%i)",
3407 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3408
3409 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3410 if (log)
3411 log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3412 static_cast<void *>(process_sp.get()));
3413 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3414 return handled;
3415
3416 // Sleep for a half a second to make sure our inferior process has
3417 // time to set its exit status before we set it incorrectly when
3418 // both the debugserver and the inferior process shut down.
3419 usleep(500000);
3420 // If our process hasn't yet exited, debugserver might have died.
3421 // If the process did exit, then we are reaping it.
3422 const StateType state = process_sp->GetState();
3423
3424 if (state != eStateInvalid && state != eStateUnloaded &&
3425 state != eStateExited && state != eStateDetached) {
3426 char error_str[1024];
3427 if (signo) {
3428 const char *signal_cstr =
3429 process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3430 if (signal_cstr)
3431 ::snprintf(error_str, sizeof(error_str),
3432 DEBUGSERVER_BASENAME"debugserver" " died with signal %s", signal_cstr);
3433 else
3434 ::snprintf(error_str, sizeof(error_str),
3435 DEBUGSERVER_BASENAME"debugserver" " died with signal %i", signo);
3436 } else {
3437 ::snprintf(error_str, sizeof(error_str),
3438 DEBUGSERVER_BASENAME"debugserver" " died with an exit status of 0x%8.8x",
3439 exit_status);
3440 }
3441
3442 process_sp->SetExitStatus(-1, error_str);
3443 }
3444 // Debugserver has exited we need to let our ProcessGDBRemote
3445 // know that it no longer has a debugserver instance
3446 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID0;
3447 return handled;
3448}
3449
3450void ProcessGDBRemote::KillDebugserverProcess() {
3451 m_gdb_comm.Disconnect();
3452 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID0) {
3453 Host::Kill(m_debugserver_pid, SIGINT2);
3454 m_debugserver_pid = LLDB_INVALID_PROCESS_ID0;
3455 }
3456}
3457
3458void ProcessGDBRemote::Initialize() {
3459 static llvm::once_flag g_once_flag;
3460
3461 llvm::call_once(g_once_flag, []() {
3462 PluginManager::RegisterPlugin(GetPluginNameStatic(),
3463 GetPluginDescriptionStatic(), CreateInstance,
3464 DebuggerInitialize);
3465 });
3466}
3467
3468void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3469 if (!PluginManager::GetSettingForProcessPlugin(
3470 debugger, PluginProperties::GetSettingName())) {
3471 const bool is_global_setting = true;
3472 PluginManager::CreateSettingForProcessPlugin(
3473 debugger, GetGlobalPluginProperties()->GetValueProperties(),
3474 ConstString("Properties for the gdb-remote process plug-in."),
3475 is_global_setting);
3476 }
3477}
3478
3479bool ProcessGDBRemote::StartAsyncThread() {
3480 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
3481
3482 if (log)
3483 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3484
3485 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3486 if (!m_async_thread.IsJoinable()) {
3487 // Create a thread that watches our internal state and controls which
3488 // events make it to clients (into the DCProcess event queue).
3489
3490 m_async_thread =
3491 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>",
3492 ProcessGDBRemote::AsyncThread, this, NULL__null);
3493 } else if (log)
3494 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
3495 "already running.",
3496 __FUNCTION__);
3497
3498 return m_async_thread.IsJoinable();
3499}
3500
3501void ProcessGDBRemote::StopAsyncThread() {
3502 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
3503
3504 if (log)
3505 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3506
3507 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3508 if (m_async_thread.IsJoinable()) {
3509 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3510
3511 // This will shut down the async thread.
3512 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3513
3514 // Stop the stdio thread
3515 m_async_thread.Join(nullptr);
3516 m_async_thread.Reset();
3517 } else if (log)
3518 log->Printf(
3519 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3520 __FUNCTION__);
3521}
3522
3523bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3524 // get the packet at a string
3525 const std::string &pkt = packet.GetStringRef();
3526 // skip %stop:
3527 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3528
3529 // pass as a thread stop info packet
3530 SetLastStopPacket(stop_info);
3531
3532 // check for more stop reasons
3533 HandleStopReplySequence();
3534
3535 // if the process is stopped then we need to fake a resume
3536 // so that we can stop properly with the new break. This
3537 // is possible due to SetPrivateState() broadcasting the
3538 // state change as a side effect.
3539 if (GetPrivateState() == lldb::StateType::eStateStopped) {
3540 SetPrivateState(lldb::StateType::eStateRunning);
3541 }
3542
3543 // since we have some stopped packets we can halt the process
3544 SetPrivateState(lldb::StateType::eStateStopped);
3545
3546 return true;
3547}
3548
3549thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3550 ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3551
3552 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
3553 if (log)
3554 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64"l" "u"
3555 ") thread starting...",
3556 __FUNCTION__, arg, process->GetID());
3557
3558 EventSP event_sp;
3559 bool done = false;
3560 while (!done) {
3561 if (log)
3562 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64"l" "u"
3563 ") listener.WaitForEvent (NULL, event_sp)...",
3564 __FUNCTION__, arg, process->GetID());
3565 if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
3566 const uint32_t event_type = event_sp->GetType();
3567 if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
3568 if (log)
3569 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64"l" "u"
3570 ") Got an event of type: %d...",
3571 __FUNCTION__, arg, process->GetID(), event_type);
3572
3573 switch (event_type) {
3574 case eBroadcastBitAsyncContinue: {
3575 const EventDataBytes *continue_packet =
3576 EventDataBytes::GetEventDataFromEvent(event_sp.get());
3577
3578 if (continue_packet) {
3579 const char *continue_cstr =
3580 (const char *)continue_packet->GetBytes();
3581 const size_t continue_cstr_len = continue_packet->GetByteSize();
3582 if (log)
3583 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64"l" "u"
3584 ") got eBroadcastBitAsyncContinue: %s",
3585 __FUNCTION__, arg, process->GetID(), continue_cstr);
3586
3587 if (::strstr(continue_cstr, "vAttach") == NULL__null)
3588 process->SetPrivateState(eStateRunning);
3589 StringExtractorGDBRemote response;
3590
3591 // If in Non-Stop-Mode
3592 if (process->GetTarget().GetNonStopModeEnabled()) {
3593 // send the vCont packet
3594 if (!process->GetGDBRemote().SendvContPacket(
3595 llvm::StringRef(continue_cstr, continue_cstr_len),
3596 response)) {
3597 // Something went wrong
3598 done = true;
3599 break;
3600 }
3601 }
3602 // If in All-Stop-Mode
3603 else {
3604 StateType stop_state =
3605 process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3606 *process, *process->GetUnixSignals(),
3607 llvm::StringRef(continue_cstr, continue_cstr_len),
3608 response);
3609
3610 // We need to immediately clear the thread ID list so we are sure
3611 // to get a valid list of threads.
3612 // The thread ID list might be contained within the "response", or
3613 // the stop reply packet that
3614 // caused the stop. So clear it now before we give the stop reply
3615 // packet to the process
3616 // using the process->SetLastStopPacket()...
3617 process->ClearThreadIDList();
3618
3619 switch (stop_state) {
3620 case eStateStopped:
3621 case eStateCrashed:
3622 case eStateSuspended:
3623 process->SetLastStopPacket(response);
3624 process->SetPrivateState(stop_state);
3625 break;
3626
3627 case eStateExited: {
3628 process->SetLastStopPacket(response);
3629 process->ClearThreadIDList();
3630 response.SetFilePos(1);
3631
3632 int exit_status = response.GetHexU8();
3633 std::string desc_string;
3634 if (response.GetBytesLeft() > 0 &&
3635 response.GetChar('-') == ';') {
3636 llvm::StringRef desc_str;
3637 llvm::StringRef desc_token;
3638 while (response.GetNameColonValue(desc_token, desc_str)) {
3639 if (desc_token != "description")
3640 continue;
3641 StringExtractor extractor(desc_str);
3642 extractor.GetHexByteString(desc_string);
3643 }
3644 }
3645 process->SetExitStatus(exit_status, desc_string.c_str());
3646 done = true;
3647 break;
3648 }
3649 case eStateInvalid: {
3650 // Check to see if we were trying to attach and if we got back
3651 // the "E87" error code from debugserver -- this indicates that
3652 // the process is not debuggable. Return a slightly more
3653 // helpful
3654 // error message about why the attach failed.
3655 if (::strstr(continue_cstr, "vAttach") != NULL__null &&
3656 response.GetError() == 0x87) {
3657 process->SetExitStatus(-1, "cannot attach to process due to "
3658 "System Integrity Protection");
3659 }
3660 // E01 code from vAttach means that the attach failed
3661 if (::strstr(continue_cstr, "vAttach") != NULL__null &&
3662 response.GetError() == 0x1) {
3663 process->SetExitStatus(-1, "unable to attach");
3664 } else {
3665 process->SetExitStatus(-1, "lost connection");
3666 }
3667 break;
3668 }
3669
3670 default:
3671 process->SetPrivateState(stop_state);
3672 break;
3673 } // switch(stop_state)
3674 } // else // if in All-stop-mode
3675 } // if (continue_packet)
3676 } // case eBroadcastBitAysncContinue
3677 break;
3678
3679 case eBroadcastBitAsyncThreadShouldExit:
3680 if (log)
3681 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64"l" "u"
3682 ") got eBroadcastBitAsyncThreadShouldExit...",
3683 __FUNCTION__, arg, process->GetID());
3684 done = true;
3685 break;
3686
3687 default:
3688 if (log)
3689 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64"l" "u"
3690 ") got unknown event 0x%8.8x",
3691 __FUNCTION__, arg, process->GetID(), event_type);
3692 done = true;
3693 break;
3694 }
3695 } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3696 switch (event_type) {
3697 case Communication::eBroadcastBitReadThreadDidExit:
3698 process->SetExitStatus(-1, "lost connection");
3699 done = true;
3700 break;
3701
3702 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3703 lldb_private::Event *event = event_sp.get();
3704 const EventDataBytes *continue_packet =
3705 EventDataBytes::GetEventDataFromEvent(event);
3706 StringExtractorGDBRemote notify(
3707 (const char *)continue_packet->GetBytes());
3708 // Hand this over to the process to handle
3709 process->HandleNotifyPacket(notify);
3710 break;
3711 }
3712
3713 default:
3714 if (log)
3715 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64"l" "u"
3716 ") got unknown event 0x%8.8x",
3717 __FUNCTION__, arg, process->GetID(), event_type);
3718 done = true;
3719 break;
3720 }
3721 }
3722 } else {
3723 if (log)
3724 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64"l" "u"
3725 ") listener.WaitForEvent (NULL, event_sp) => false",
3726 __FUNCTION__, arg, process->GetID());
3727 done = true;
3728 }
3729 }
3730
3731 if (log)
3732 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64"l" "u"
3733 ") thread exiting...",
3734 __FUNCTION__, arg, process->GetID());
3735
3736 return NULL__null;
3737}
3738
3739// uint32_t
3740// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3741// &matches, std::vector<lldb::pid_t> &pids)
3742//{
3743// // If we are planning to launch the debugserver remotely, then we need to
3744// fire up a debugserver
3745// // process and ask it for the list of processes. But if we are local, we
3746// can let the Host do it.
3747// if (m_local_debugserver)
3748// {
3749// return Host::ListProcessesMatchingName (name, matches, pids);
3750// }
3751// else
3752// {
3753// // FIXME: Implement talking to the remote debugserver.
3754// return 0;
3755// }
3756//
3757//}
3758//
3759bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3760 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3761 lldb::user_id_t break_loc_id) {
3762 // I don't think I have to do anything here, just make sure I notice the new
3763 // thread when it starts to
3764 // run so I can stop it if that's what I want to do.
3765 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP(1u << 7)));
3766 if (log)
3767 log->Printf("Hit New Thread Notification breakpoint.");
3768 return false;
3769}
3770
3771Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3772 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
3773 LLDB_LOG(log, "Check if need to update ignored signals")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "Check if need to update ignored signals"); }
while (0)
;
3774
3775 // QPassSignals package is not supported by the server,
3776 // there is no way we can ignore any signals on server side.
3777 if (!m_gdb_comm.GetQPassSignalsSupported())
3778 return Status();
3779
3780 // No signals, nothing to send.
3781 if (m_unix_signals_sp == nullptr)
3782 return Status();
3783
3784 // Signals' version hasn't changed, no need to send anything.
3785 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3786 if (new_signals_version == m_last_signals_version) {
3787 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "Signals' version hasn't changed. version={0}"
, m_last_signals_version); } while (0)
3788 m_last_signals_version)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "Signals' version hasn't changed. version={0}"
, m_last_signals_version); } while (0)
;
3789 return Status();
3790 }
3791
3792 auto signals_to_ignore =
3793 m_unix_signals_sp->GetFilteredSignals(false, false, false);
3794 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3795
3796 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "Signals' version changed. old version={0}, new version={1}, "
"signals ignored={2}, update result={3}", m_last_signals_version
, new_signals_version, signals_to_ignore.size(), error); } while
(0)
3797 "Signals' version changed. old version={0}, new version={1}, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "Signals' version changed. old version={0}, new version={1}, "
"signals ignored={2}, update result={3}", m_last_signals_version
, new_signals_version, signals_to_ignore.size(), error); } while
(0)
3798 "signals ignored={2}, update result={3}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "Signals' version changed. old version={0}, new version={1}, "
"signals ignored={2}, update result={3}", m_last_signals_version
, new_signals_version, signals_to_ignore.size(), error); } while
(0)
3799 m_last_signals_version, new_signals_version,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "Signals' version changed. old version={0}, new version={1}, "
"signals ignored={2}, update result={3}", m_last_signals_version
, new_signals_version, signals_to_ignore.size(), error); } while
(0)
3800 signals_to_ignore.size(), error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __FUNCTION__, "Signals' version changed. old version={0}, new version={1}, "
"signals ignored={2}, update result={3}", m_last_signals_version
, new_signals_version, signals_to_ignore.size(), error); } while
(0)
;
3801
3802 if (error.Success())
3803 m_last_signals_version = new_signals_version;
3804
3805 return error;
3806}
3807
3808bool ProcessGDBRemote::StartNoticingNewThreads() {
3809 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP(1u << 7)));
3810 if (m_thread_create_bp_sp) {
3811 if (log && log->GetVerbose())
3812 log->Printf("Enabled noticing new thread breakpoint.");
3813 m_thread_create_bp_sp->SetEnabled(true);
3814 } else {
3815 PlatformSP platform_sp(GetTarget().GetPlatform());
3816 if (platform_sp) {
3817 m_thread_create_bp_sp =
3818 platform_sp->SetThreadCreationBreakpoint(GetTarget());
3819 if (m_thread_create_bp_sp) {
3820 if (log && log->GetVerbose())
3821 log->Printf(
3822 "Successfully created new thread notification breakpoint %i",
3823 m_thread_create_bp_sp->GetID());
3824 m_thread_create_bp_sp->SetCallback(
3825 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3826 } else {
3827 if (log)
3828 log->Printf("Failed to create new thread notification breakpoint.");
3829 }
3830 }
3831 }
3832 return m_thread_create_bp_sp.get() != NULL__null;
3833}
3834
3835bool ProcessGDBRemote::StopNoticingNewThreads() {
3836 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP(1u << 7)));
3837 if (log && log->GetVerbose())
3838 log->Printf("Disabling new thread notification breakpoint.");
3839
3840 if (m_thread_create_bp_sp)
3841 m_thread_create_bp_sp->SetEnabled(false);
3842
3843 return true;
3844}
3845
3846DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3847 if (m_dyld_ap.get() == NULL__null)
3848 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, NULL__null));
3849 return m_dyld_ap.get();
3850}
3851
3852Status ProcessGDBRemote::SendEventData(const char *data) {
3853 int return_value;
3854 bool was_supported;
3855
3856 Status error;
3857
3858 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3859 if (return_value != 0) {
3860 if (!was_supported)
3861 error.SetErrorString("Sending events is not supported for this process.");
3862 else
3863 error.SetErrorStringWithFormat("Error sending event data: %d.",
3864 return_value);
3865 }
3866 return error;
3867}
3868
3869const DataBufferSP ProcessGDBRemote::GetAuxvData() {
3870 DataBufferSP buf;
3871 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3872 std::string response_string;
3873 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
3874 response_string) ==
3875 GDBRemoteCommunication::PacketResult::Success)
3876 buf.reset(new DataBufferHeap(response_string.c_str(),
3877 response_string.length()));
3878 }
3879 return buf;
3880}
3881
3882StructuredData::ObjectSP
3883ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3884 StructuredData::ObjectSP object_sp;
3885
3886 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3887 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3888 SystemRuntime *runtime = GetSystemRuntime();
3889 if (runtime) {
3890 runtime->AddThreadExtendedInfoPacketHints(args_dict);
3891 }
3892 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3893
3894 StreamString packet;
3895 packet << "jThreadExtendedInfo:";
3896 args_dict->Dump(packet, false);
3897
3898 // FIXME the final character of a JSON dictionary, '}', is the escape
3899 // character in gdb-remote binary mode. lldb currently doesn't escape
3900 // these characters in its packet output -- so we add the quoted version
3901 // of the } character here manually in case we talk to a debugserver which
3902 // un-escapes the characters at packet read time.
3903 packet << (char)(0x7d ^ 0x20);
3904
3905 StringExtractorGDBRemote response;
3906 response.SetResponseValidatorToJSON();
3907 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3908 false) ==
3909 GDBRemoteCommunication::PacketResult::Success) {
3910 StringExtractorGDBRemote::ResponseType response_type =
3911 response.GetResponseType();
3912 if (response_type == StringExtractorGDBRemote::eResponse) {
3913 if (!response.Empty()) {
3914 object_sp = StructuredData::ParseJSON(response.GetStringRef());
3915 }
3916 }
3917 }
3918 }
3919 return object_sp;
3920}
3921
3922StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3923 lldb::addr_t image_list_address, lldb::addr_t image_count) {
3924
3925 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3926 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3927 image_list_address);
3928 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
3929
3930 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3931}
3932
3933StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
3934 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3935
3936 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3937
3938 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3939}
3940
3941StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3942 const std::vector<lldb::addr_t> &load_addresses) {
3943 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3944 StructuredData::ArraySP addresses(new StructuredData::Array);
3945
3946 for (auto addr : load_addresses) {
3947 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
3948 addresses->AddItem(addr_sp);
3949 }
3950
3951 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3952
3953 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3954}
3955
3956StructuredData::ObjectSP
3957ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
3958 StructuredData::ObjectSP args_dict) {
3959 StructuredData::ObjectSP object_sp;
3960
3961 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
3962 // Scope for the scoped timeout object
3963 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
3964 std::chrono::seconds(10));
3965
3966 StreamString packet;
3967 packet << "jGetLoadedDynamicLibrariesInfos:";
3968 args_dict->Dump(packet, false);
3969
3970 // FIXME the final character of a JSON dictionary, '}', is the escape
3971 // character in gdb-remote binary mode. lldb currently doesn't escape
3972 // these characters in its packet output -- so we add the quoted version
3973 // of the } character here manually in case we talk to a debugserver which
3974 // un-escapes the characters at packet read time.
3975 packet << (char)(0x7d ^ 0x20);
3976
3977 StringExtractorGDBRemote response;
3978 response.SetResponseValidatorToJSON();
3979 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3980 false) ==
3981 GDBRemoteCommunication::PacketResult::Success) {
3982 StringExtractorGDBRemote::ResponseType response_type =
3983 response.GetResponseType();
3984 if (response_type == StringExtractorGDBRemote::eResponse) {
3985 if (!response.Empty()) {
3986 object_sp = StructuredData::ParseJSON(response.GetStringRef());
3987 }
3988 }
3989 }
3990 }
3991 return object_sp;
3992}
3993
3994StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
3995 StructuredData::ObjectSP object_sp;
3996 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3997
3998 if (m_gdb_comm.GetSharedCacheInfoSupported()) {
3999 StreamString packet;
4000 packet << "jGetSharedCacheInfo:";
4001 args_dict->Dump(packet, false);
4002
4003 // FIXME the final character of a JSON dictionary, '}', is the escape
4004 // character in gdb-remote binary mode. lldb currently doesn't escape
4005 // these characters in its packet output -- so we add the quoted version
4006 // of the } character here manually in case we talk to a debugserver which
4007 // un-escapes the characters at packet read time.
4008 packet << (char)(0x7d ^ 0x20);
4009
4010 StringExtractorGDBRemote response;
4011 response.SetResponseValidatorToJSON();
4012 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4013 false) ==
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(response.GetStringRef());
4020 }
4021 }
4022 }
4023 }
4024 return object_sp;
4025}
4026
4027Status ProcessGDBRemote::ConfigureStructuredData(
4028 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
4029 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4030}
4031
4032// Establish the largest memory read/write payloads we should use.
4033// If the remote stub has a max packet size, stay under that size.
4034//
4035// If the remote stub's max packet size is crazy large, use a
4036// reasonable largeish default.
4037//
4038// If the remote stub doesn't advertise a max packet size, use a
4039// conservative default.
4040
4041void ProcessGDBRemote::GetMaxMemorySize() {
4042 const uint64_t reasonable_largeish_default = 128 * 1024;
4043 const uint64_t conservative_default = 512;
4044
4045 if (m_max_memory_size == 0) {
4046 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4047 if (stub_max_size != UINT64_MAX(18446744073709551615UL) && stub_max_size != 0) {
4048 // Save the stub's claimed maximum packet size
4049 m_remote_stub_max_memory_size = stub_max_size;
4050
4051 // Even if the stub says it can support ginormous packets,
4052 // don't exceed our reasonable largeish default packet size.
4053 if (stub_max_size > reasonable_largeish_default) {
4054 stub_max_size = reasonable_largeish_default;
4055 }
4056
4057 // Memory packet have other overheads too like Maddr,size:#NN
4058 // Instead of calculating the bytes taken by size and addr every
4059 // time, we take a maximum guess here.
4060 if (stub_max_size > 70)
4061 stub_max_size -= 32 + 32 + 6;
4062 else {
4063 // In unlikely scenario that max packet size is less then 70, we will
4064 // hope that data being written is small enough to fit.
4065 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4066 GDBR_LOG_COMM(1u << 10) | GDBR_LOG_MEMORY(1u << 4)));
4067 if (log)
4068 log->Warning("Packet size is too small. "
4069 "LLDB may face problems while writing memory");
4070 }
4071
4072 m_max_memory_size = stub_max_size;
4073 } else {
4074 m_max_memory_size = conservative_default;
4075 }
4076 }
4077}
4078
4079void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4080 uint64_t user_specified_max) {
4081 if (user_specified_max != 0) {
4082 GetMaxMemorySize();
4083
4084 if (m_remote_stub_max_memory_size != 0) {
4085 if (m_remote_stub_max_memory_size < user_specified_max) {
4086 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4087 // packet size too
4088 // big, go as big
4089 // as the remote stub says we can go.
4090 } else {
4091 m_max_memory_size = user_specified_max; // user's packet size is good
4092 }
4093 } else {
4094 m_max_memory_size =
4095 user_specified_max; // user's packet size is probably fine
4096 }
4097 }
4098}
4099
4100bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4101 const ArchSpec &arch,
4102 ModuleSpec &module_spec) {
4103 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM(1u << 25));
4104
4105 const ModuleCacheKey key(module_file_spec.GetPath(),
4106 arch.GetTriple().getTriple());
4107 auto cached = m_cached_module_specs.find(key);
4108 if (cached != m_cached_module_specs.end()) {
4109 module_spec = cached->second;
4110 return bool(module_spec);
4111 }
4112
4113 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4114 if (log)
4115 log->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4116 __FUNCTION__, module_file_spec.GetPath().c_str(),
4117 arch.GetTriple().getTriple().c_str());
4118 return false;
4119 }
4120
4121 if (log) {
4122 StreamString stream;
4123 module_spec.Dump(stream);
4124 log->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4125 __FUNCTION__, module_file_spec.GetPath().c_str(),
4126 arch.GetTriple().getTriple().c_str(), stream.GetData());
4127 }
4128
4129 m_cached_module_specs[key] = module_spec;
4130 return true;
4131}
4132
4133void ProcessGDBRemote::PrefetchModuleSpecs(
4134 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4135 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4136 if (module_specs) {
4137 for (const FileSpec &spec : module_file_specs)
4138 m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4139 triple.getTriple())] = ModuleSpec();
4140 for (const ModuleSpec &spec : *module_specs)
4141 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4142 triple.getTriple())] = spec;
4143 }
4144}
4145
4146bool ProcessGDBRemote::GetHostOSVersion(uint32_t &major, uint32_t &minor,
4147 uint32_t &update) {
4148 if (m_gdb_comm.GetOSVersion(major, minor, update))
4149 return true;
4150 // We failed to get the host OS version, defer to the base
4151 // implementation to correctly invalidate the arguments.
4152 return Process::GetHostOSVersion(major, minor, update);
4153}
4154
4155namespace {
4156
4157typedef std::vector<std::string> stringVec;
4158
4159typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4160struct RegisterSetInfo {
4161 ConstString name;
4162};
4163
4164typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4165
4166struct GdbServerTargetInfo {
4167 std::string arch;
4168 std::string osabi;
4169 stringVec includes;
4170 RegisterSetMap reg_set_map;
4171};
4172
4173bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4174 GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4175 uint32_t &cur_reg_num, uint32_t &reg_offset) {
4176 if (!feature_node)
4177 return false;
4178
4179 feature_node.ForEachChildElementWithName(
4180 "reg", [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset,
4181 &abi_sp](const XMLNode &reg_node) -> bool {
4182 std::string gdb_group;
4183 std::string gdb_type;
4184 ConstString reg_name;
4185 ConstString alt_name;
4186 ConstString set_name;
4187 std::vector<uint32_t> value_regs;
4188 std::vector<uint32_t> invalidate_regs;
4189 std::vector<uint8_t> dwarf_opcode_bytes;
4190 bool encoding_set = false;
4191 bool format_set = false;
4192 RegisterInfo reg_info = {
4193 NULL__null, // Name
4194 NULL__null, // Alt name
4195 0, // byte size
4196 reg_offset, // offset
4197 eEncodingUint, // encoding
4198 eFormatHex, // format
4199 {
4200 LLDB_INVALID_REGNUM(4294967295U), // eh_frame reg num
4201 LLDB_INVALID_REGNUM(4294967295U), // DWARF reg num
4202 LLDB_INVALID_REGNUM(4294967295U), // generic reg num
4203 cur_reg_num, // process plugin reg num
4204 cur_reg_num // native register number
4205 },
4206 NULL__null,
4207 NULL__null,
4208 NULL__null, // Dwarf Expression opcode bytes pointer
4209 0 // Dwarf Expression opcode bytes length
4210 };
4211
4212 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4213 &reg_name, &alt_name, &set_name, &value_regs,
4214 &invalidate_regs, &encoding_set, &format_set,
4215 &reg_info, &reg_offset, &dwarf_opcode_bytes](
4216 const llvm::StringRef &name,
4217 const llvm::StringRef &value) -> bool {
4218 if (name == "name") {
4219 reg_name.SetString(value);
4220 } else if (name == "bitsize") {
4221 reg_info.byte_size =
4222 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT8;
4223 } else if (name == "type") {
4224 gdb_type = value.str();
4225 } else if (name == "group") {
4226 gdb_group = value.str();
4227 } else if (name == "regnum") {
4228 const uint32_t regnum =
4229 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM(4294967295U), 0);
4230 if (regnum != LLDB_INVALID_REGNUM(4294967295U)) {
4231 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
4232 }
4233 } else if (name == "offset") {
4234 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX(4294967295U), 0);
4235 } else if (name == "altname") {
4236 alt_name.SetString(value);
4237 } else if (name == "encoding") {
4238 encoding_set = true;
4239 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4240 } else if (name == "format") {
4241 format_set = true;
4242 Format format = eFormatInvalid;
4243 if (Args::StringToFormat(value.data(), format, NULL__null).Success())
4244 reg_info.format = format;
4245 else if (value == "vector-sint8")
4246 reg_info.format = eFormatVectorOfSInt8;
4247 else if (value == "vector-uint8")
4248 reg_info.format = eFormatVectorOfUInt8;
4249 else if (value == "vector-sint16")
4250 reg_info.format = eFormatVectorOfSInt16;
4251 else if (value == "vector-uint16")
4252 reg_info.format = eFormatVectorOfUInt16;
4253 else if (value == "vector-sint32")
4254 reg_info.format = eFormatVectorOfSInt32;
4255 else if (value == "vector-uint32")
4256 reg_info.format = eFormatVectorOfUInt32;
4257 else if (value == "vector-float32")
4258 reg_info.format = eFormatVectorOfFloat32;
4259 else if (value == "vector-uint64")
4260 reg_info.format = eFormatVectorOfUInt64;
4261 else if (value == "vector-uint128")
4262 reg_info.format = eFormatVectorOfUInt128;
4263 } else if (name == "group_id") {
4264 const uint32_t set_id =
4265 StringConvert::ToUInt32(value.data(), UINT32_MAX(4294967295U), 0);
4266 RegisterSetMap::const_iterator pos =
4267 target_info.reg_set_map.find(set_id);
4268 if (pos != target_info.reg_set_map.end())
4269 set_name = pos->second.name;
4270 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4271 reg_info.kinds[eRegisterKindEHFrame] =
4272 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM(4294967295U), 0);
4273 } else if (name == "dwarf_regnum") {
4274 reg_info.kinds[eRegisterKindDWARF] =
4275 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM(4294967295U), 0);
4276 } else if (name == "generic") {
4277 reg_info.kinds[eRegisterKindGeneric] =
4278 Args::StringToGenericRegister(value);
4279 } else if (name == "value_regnums") {
4280 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4281 } else if (name == "invalidate_regnums") {
4282 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4283 } else if (name == "dynamic_size_dwarf_expr_bytes") {
4284 StringExtractor opcode_extractor;
4285 std::string opcode_string = value.str();
4286 size_t dwarf_opcode_len = opcode_string.length() / 2;
4287 assert(dwarf_opcode_len > 0)((dwarf_opcode_len > 0) ? static_cast<void> (0) : __assert_fail
("dwarf_opcode_len > 0", "/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 4287, __PRETTY_FUNCTION__))
;
4288
4289 dwarf_opcode_bytes.resize(dwarf_opcode_len);
4290 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4291 opcode_extractor.GetStringRef().swap(opcode_string);
4292 uint32_t ret_val =
4293 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4294 assert(dwarf_opcode_len == ret_val)((dwarf_opcode_len == ret_val) ? static_cast<void> (0) :
__assert_fail ("dwarf_opcode_len == ret_val", "/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 4294, __PRETTY_FUNCTION__))
;
4295 UNUSED_IF_ASSERT_DISABLED(ret_val)((void)(ret_val));
4296 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4297 } else {
4298 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4299 }
4300 return true; // Keep iterating through all attributes
4301 });
4302
4303 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4304 if (gdb_type.find("int") == 0) {
4305 reg_info.format = eFormatHex;
4306 reg_info.encoding = eEncodingUint;
4307 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4308 reg_info.format = eFormatAddressInfo;
4309 reg_info.encoding = eEncodingUint;
4310 } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4311 reg_info.format = eFormatFloat;
4312 reg_info.encoding = eEncodingIEEE754;
4313 }
4314 }
4315
4316 // Only update the register set name if we didn't get a "reg_set"
4317 // attribute.
4318 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4319 if (!set_name && !gdb_group.empty())
4320 set_name.SetCString(gdb_group.c_str());
4321
4322 reg_info.byte_offset = reg_offset;
4323 assert(reg_info.byte_size != 0)((reg_info.byte_size != 0) ? static_cast<void> (0) : __assert_fail
("reg_info.byte_size != 0", "/build/llvm-toolchain-snapshot-6.0~svn316068/tools/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 4323, __PRETTY_FUNCTION__))
;
4324 reg_offset += reg_info.byte_size;
4325 if (!value_regs.empty()) {
4326 value_regs.push_back(LLDB_INVALID_REGNUM(4294967295U));
4327 reg_info.value_regs = value_regs.data();
4328 }
4329 if (!invalidate_regs.empty()) {
4330 invalidate_regs.push_back(LLDB_INVALID_REGNUM(4294967295U));
4331 reg_info.invalidate_regs = invalidate_regs.data();
4332 }
4333
4334 ++cur_reg_num;
4335 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_sp);
4336 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4337
4338 return true; // Keep iterating through all "reg" elements
4339 });
4340 return true;
4341}
4342
4343} // namespace {}
4344
4345// query the target of gdb-remote for extended target information
4346// return: 'true' on success
4347// 'false' on failure
4348bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4349 // Make sure LLDB has an XML parser it can use first
4350 if (!XMLDocument::XMLEnabled())
4351 return false;
4352
4353 // redirect libxml2's error handler since the default prints to stdout
4354
4355 GDBRemoteCommunicationClient &comm = m_gdb_comm;
4356
4357 // check that we have extended feature read support
4358 if (!comm.GetQXferFeaturesReadSupported())
4359 return false;
4360
4361 // request the target xml file
4362 std::string raw;
4363 lldb_private::Status lldberr;
4364 if (!comm.ReadExtFeature(ConstString("features"), ConstString("target.xml"),
4365 raw, lldberr)) {
4366 return false;
4367 }
4368
4369 XMLDocument xml_document;
4370
4371 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml")) {
4372 GdbServerTargetInfo target_info;
4373
4374 XMLNode target_node = xml_document.GetRootElement("target");
4375 if (target_node) {
4376 std::vector<XMLNode> feature_nodes;
4377 target_node.ForEachChildElement([&target_info, &feature_nodes](
4378 const XMLNode &node) -> bool {
4379 llvm::StringRef name = node.GetName();
4380 if (name == "architecture") {
4381 node.GetElementText(target_info.arch);
4382 } else if (name == "osabi") {
4383 node.GetElementText(target_info.osabi);
4384 } else if (name == "xi:include" || name == "include") {
4385 llvm::StringRef href = node.GetAttributeValue("href");
4386 if (!href.empty())
4387 target_info.includes.push_back(href.str());
4388 } else if (name == "feature") {
4389 feature_nodes.push_back(node);
4390 } else if (name == "groups") {
4391 node.ForEachChildElementWithName(
4392 "group", [&target_info](const XMLNode &node) -> bool {
4393 uint32_t set_id = UINT32_MAX(4294967295U);
4394 RegisterSetInfo set_info;
4395
4396 node.ForEachAttribute(
4397 [&set_id, &set_info](const llvm::StringRef &name,
4398 const llvm::StringRef &value) -> bool {
4399 if (name == "id")
4400 set_id = StringConvert::ToUInt32(value.data(),
4401 UINT32_MAX(4294967295U), 0);
4402 if (name == "name")
4403 set_info.name = ConstString(value);
4404 return true; // Keep iterating through all attributes
4405 });
4406
4407 if (set_id != UINT32_MAX(4294967295U))
4408 target_info.reg_set_map[set_id] = set_info;
4409 return true; // Keep iterating through all "group" elements
4410 });
4411 }
4412 return true; // Keep iterating through all children of the target_node
4413 });
4414
4415 // Initialize these outside of ParseRegisters, since they should not be
4416 // reset inside each include feature
4417 uint32_t cur_reg_num = 0;
4418 uint32_t reg_offset = 0;
4419
4420 // Don't use Process::GetABI, this code gets called from DidAttach, and in
4421 // that context we haven't
4422 // set the Target's architecture yet, so the ABI is also potentially
4423 // incorrect.
4424 ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use);
4425 for (auto &feature_node : feature_nodes) {
4426 ParseRegisters(feature_node, target_info, this->m_register_info,
4427 abi_to_use_sp, cur_reg_num, reg_offset);
4428 }
4429
4430 for (const auto &include : target_info.includes) {
4431 // request register file
4432 std::string xml_data;
4433 if (!comm.ReadExtFeature(ConstString("features"), ConstString(include),
4434 xml_data, lldberr))
4435 continue;
4436
4437 XMLDocument include_xml_document;
4438 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(),
4439 include.c_str());
4440 XMLNode include_feature_node =
4441 include_xml_document.GetRootElement("feature");
4442 if (include_feature_node) {
4443 ParseRegisters(include_feature_node, target_info,
4444 this->m_register_info, abi_to_use_sp, cur_reg_num,
4445 reg_offset);
4446 }
4447 }
4448 this->m_register_info.Finalize(arch_to_use);
4449 }
4450 }
4451
4452 return m_register_info.GetNumRegisters() > 0;
4453}
4454
4455Status ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) {
4456 // Make sure LLDB has an XML parser it can use first
4457 if (!XMLDocument::XMLEnabled())
4458 return Status(0, ErrorType::eErrorTypeGeneric);
4459
4460 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS(1u << 1));
4461 if (log)
4462 log->Printf("ProcessGDBRemote::%s", __FUNCTION__);
4463
4464 GDBRemoteCommunicationClient &comm = m_gdb_comm;
4465
4466 // check that we have extended feature read support
4467 if (comm.GetQXferLibrariesSVR4ReadSupported()) {
4468 list.clear();
4469
4470 // request the loaded library list
4471 std::string raw;
4472 lldb_private::Status lldberr;
4473
4474 if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4475 raw, lldberr))
4476 return Status(0, ErrorType::eErrorTypeGeneric);
4477
4478 // parse the xml file in memory
4479 if (log)
4480 log->Printf("parsing: %s", raw.c_str());
4481 XMLDocument doc;
4482
4483 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4484 return Status(0, ErrorType::eErrorTypeGeneric);
4485
4486 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4487 if (!root_element)
4488 return Status();
4489
4490 // main link map structure
4491 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4492 if (!main_lm.empty()) {
4493 list.m_link_map =
4494 StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS(18446744073709551615UL), 0);
4495 }
4496
4497 root_element.ForEachChildElementWithName(
4498 "library", [log, &list](const XMLNode &library) -> bool {
4499
4500 LoadedModuleInfoList::LoadedModuleInfo module;
4501
4502 library.ForEachAttribute(
4503 [&module](const llvm::StringRef &name,
4504 const llvm::StringRef &value) -> bool {
4505
4506 if (name == "name")
4507 module.set_name(value.str());
4508 else if (name == "lm") {
4509 // the address of the link_map struct.
4510 module.set_link_map(StringConvert::ToUInt64(
4511 value.data(), LLDB_INVALID_ADDRESS(18446744073709551615UL), 0));
4512 } else if (name == "l_addr") {
4513 // the displacement as read from the field 'l_addr' of the
4514 // link_map struct.
4515 module.set_base(StringConvert::ToUInt64(
4516 value.data(), LLDB_INVALID_ADDRESS(18446744073709551615UL), 0));
4517 // base address is always a displacement, not an absolute
4518 // value.
4519 module.set_base_is_offset(true);
4520 } else if (name == "l_ld") {
4521 // the memory address of the libraries PT_DYAMIC section.
4522 module.set_dynamic(StringConvert::ToUInt64(
4523 value.data(), LLDB_INVALID_ADDRESS(18446744073709551615UL), 0));
4524 }
4525
4526 return true; // Keep iterating over all properties of "library"
4527 });
4528
4529 if (log) {
4530 std::string name;
4531 lldb::addr_t lm = 0, base = 0, ld = 0;
4532 bool base_is_offset;
4533
4534 module.get_name(name);
4535 module.get_link_map(lm);
4536 module.get_base(base);
4537 module.get_base_is_offset(base_is_offset);
4538 module.get_dynamic(ld);
4539
4540 log->Printf("found (link_map:0x%08" PRIx64"l" "x" ", base:0x%08" PRIx64"l" "x"
4541 "[%s], ld:0x%08" PRIx64"l" "x" ", name:'%s')",
4542 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4543 name.c_str());
4544 }
4545
4546 list.add(module);
4547 return true; // Keep iterating over all "library" elements in the root
4548 // node
4549 });
4550
4551 if (log)
4552 log->Printf("found %" PRId32"d" " modules in total",
4553 (int)list.m_list.size());
4554 } else if (comm.GetQXferLibrariesReadSupported()) {
4555 list.clear();
4556
4557 // request the loaded library list
4558 std::string raw;
4559 lldb_private::Status lldberr;
4560
4561 if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4562 lldberr))
4563 return Status(0, ErrorType::eErrorTypeGeneric);
4564
4565 if (log)
4566 log->Printf("parsing: %s", raw.c_str());
4567 XMLDocument doc;
4568
4569 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4570 return Status(0, ErrorType::eErrorTypeGeneric);
4571
4572 XMLNode root_element = doc.GetRootElement("library-list");
4573 if (!root_element)
4574 return Status();
4575
4576 root_element.ForEachChildElementWithName(
4577 "library", [log, &list](const XMLNode &library) -> bool {
4578 LoadedModuleInfoList::LoadedModuleInfo module;
4579
4580 llvm::StringRef name = library.GetAttributeValue("name");
4581 module.set_name(name.str());
4582
4583 // The base address of a given library will be the address of its
4584 // first section. Most remotes send only one section for Windows
4585 // targets for example.
4586 const XMLNode &section =
4587 library.FindFirstChildElementWithName("section");
4588 llvm::StringRef address = section.GetAttributeValue("address");
4589 module.set_base(
4590 StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS(18446744073709551615UL), 0));
4591 // These addresses are absolute values.
4592 module.set_base_is_offset(false);
4593
4594 if (log) {
4595 std::string name;
4596 lldb::addr_t base = 0;
4597 bool base_is_offset;
4598 module.get_name(name);
4599 module.get_base(base);
4600 module.get_base_is_offset(base_is_offset);
4601
4602 log->Printf("found (base:0x%08" PRIx64"l" "x" "[%s], name:'%s')", base,
4603 (base_is_offset ? "offset" : "absolute"), name.c_str());
4604 }
4605
4606 list.add(module);
4607 return true; // Keep iterating over all "library" elements in the root
4608 // node
4609 });
4610
4611 if (log)
4612 log->Printf("found %" PRId32"d" " modules in total",
4613 (int)list.m_list.size());
4614 } else {
4615 return Status(0, ErrorType::eErrorTypeGeneric);
4616 }
4617
4618 return Status();
4619}
4620
4621lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4622 lldb::addr_t link_map,
4623 lldb::addr_t base_addr,
4624 bool value_is_offset) {
4625 DynamicLoader *loader = GetDynamicLoader();
4626 if (!loader)
4627 return nullptr;
4628
4629 return loader->LoadModuleAtAddress(file, link_map, base_addr,
4630 value_is_offset);
4631}
4632
4633size_t ProcessGDBRemote::LoadModules(LoadedModuleInfoList &module_list) {
4634 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4635
4636 // request a list of loaded libraries from GDBServer
4637 if (GetLoadedModuleList(module_list).Fail())
4638 return 0;
4639
4640 // get a list of all the modules
4641 ModuleList new_modules;
4642
4643 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list.m_list) {
4644 std::string mod_name;
4645 lldb::addr_t mod_base;
4646 lldb::addr_t link_map;
4647 bool mod_base_is_offset;
4648
4649 bool valid = true;
4650 valid &= modInfo.get_name(mod_name);
4651 valid &= modInfo.get_base(mod_base);
4652 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4653 if (!valid)
4654 continue;
4655
4656 if (!modInfo.get_link_map(link_map))
4657 link_map = LLDB_INVALID_ADDRESS(18446744073709551615UL);
4658
4659 FileSpec file(mod_name, true);
4660 lldb::ModuleSP module_sp =
4661 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4662
4663 if (module_sp.get())
4664 new_modules.Append(module_sp);
4665 }
4666
4667 if (new_modules.GetSize() > 0) {
4668 ModuleList removed_modules;
4669 Target &target = GetTarget();
4670 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4671
4672 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4673 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4674
4675 bool found = false;
4676 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4677 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4678 found = true;
4679 }
4680
4681 // The main executable will never be included in libraries-svr4, don't
4682 // remove it
4683 if (!found &&
4684 loaded_module.get() != target.GetExecutableModulePointer()) {
4685 removed_modules.Append(loaded_module);
4686 }
4687 }
4688
4689 loaded_modules.Remove(removed_modules);
4690 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4691
4692 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4693 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4694 if (!obj)
4695 return true;
4696
4697 if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4698 return true;
4699
4700 lldb::ModuleSP module_copy_sp = module_sp;
4701 target.SetExecutableModule(module_copy_sp, false);
4702 return false;
4703 });
4704
4705 loaded_modules.AppendIfNeeded(new_modules);
4706 m_process->GetTarget().ModulesDidLoad(new_modules);
4707 }
4708
4709 return new_modules.GetSize();
4710}
4711
4712size_t ProcessGDBRemote::LoadModules() {
4713 LoadedModuleInfoList module_list;
4714 return LoadModules(module_list);
4715}
4716
4717Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4718 bool &is_loaded,
4719 lldb::addr_t &load_addr) {
4720 is_loaded = false;
4721 load_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
4722
4723 std::string file_path = file.GetPath(false);
4724 if (file_path.empty())
4725 return Status("Empty file name specified");
4726
4727 StreamString packet;
4728 packet.PutCString("qFileLoadAddress:");
4729 packet.PutCStringAsRawHex8(file_path.c_str());
4730
4731 StringExtractorGDBRemote response;
4732 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4733 false) !=
4734 GDBRemoteCommunication::PacketResult::Success)
4735 return Status("Sending qFileLoadAddress packet failed");
4736
4737 if (response.IsErrorResponse()) {
4738 if (response.GetError() == 1) {
4739 // The file is not loaded into the inferior
4740 is_loaded = false;
4741 load_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
4742 return Status();
4743 }
4744
4745 return Status(
4746 "Fetching file load address from remote server returned an error");
4747 }
4748
4749 if (response.IsNormalResponse()) {
4750 is_loaded = true;
4751 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS(18446744073709551615UL));
4752 return Status();
4753 }
4754
4755 return Status(
4756 "Unknown error happened during sending the load address packet");
4757}
4758
4759void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4760 // We must call the lldb_private::Process::ModulesDidLoad () first before we
4761 // do anything
4762 Process::ModulesDidLoad(module_list);
4763
4764 // After loading shared libraries, we can ask our remote GDB server if
4765 // it needs any symbols.
4766 m_gdb_comm.ServeSymbolLookups(this);
4767}
4768
4769void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4770 AppendSTDOUT(out.data(), out.size());
4771}
4772
4773static const char *end_delimiter = "--end--;";
4774static const int end_delimiter_len = 8;
4775
4776void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4777 std::string input = data.str(); // '1' to move beyond 'A'
4778 if (m_partial_profile_data.length() > 0) {
4779 m_partial_profile_data.append(input);
4780 input = m_partial_profile_data;
4781 m_partial_profile_data.clear();
4782 }
4783
4784 size_t found, pos = 0, len = input.length();
4785 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4786 StringExtractorGDBRemote profileDataExtractor(
4787 input.substr(pos, found).c_str());
4788 std::string profile_data =
4789 HarmonizeThreadIdsForProfileData(profileDataExtractor);
4790 BroadcastAsyncProfileData(profile_data);
4791
4792 pos = found + end_delimiter_len;
4793 }
4794
4795 if (pos < len) {
4796 // Last incomplete chunk.
4797 m_partial_profile_data = input.substr(pos);
4798 }
4799}
4800
4801std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4802 StringExtractorGDBRemote &profileDataExtractor) {
4803 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4804 std::string output;
4805 llvm::raw_string_ostream output_stream(output);
4806 llvm::StringRef name, value;
4807
4808 // Going to assuming thread_used_usec comes first, else bail out.
4809 while (profileDataExtractor.GetNameColonValue(name, value)) {
4810 if (name.compare("thread_used_id") == 0) {
4811 StringExtractor threadIDHexExtractor(value);
4812 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
4813
4814 bool has_used_usec = false;
4815 uint32_t curr_used_usec = 0;
4816 llvm::StringRef usec_name, usec_value;
4817 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4818 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4819 if (usec_name.equals("thread_used_usec")) {
4820 has_used_usec = true;
4821 usec_value.getAsInteger(0, curr_used_usec);
4822 } else {
4823 // We didn't find what we want, it is probably
4824 // an older version. Bail out.
4825 profileDataExtractor.SetFilePos(input_file_pos);
4826 }
4827 }
4828
4829 if (has_used_usec) {
4830 uint32_t prev_used_usec = 0;
4831 std::map<uint64_t, uint32_t>::iterator iterator =
4832 m_thread_id_to_used_usec_map.find(thread_id);
4833 if (iterator != m_thread_id_to_used_usec_map.end()) {
4834 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
4835 }
4836
4837 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4838 // A good first time record is one that runs for at least 0.25 sec
4839 bool good_first_time =
4840 (prev_used_usec == 0) && (real_used_usec > 250000);
4841 bool good_subsequent_time =
4842 (prev_used_usec > 0) &&
4843 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4844
4845 if (good_first_time || good_subsequent_time) {
4846 // We try to avoid doing too many index id reservation,
4847 // resulting in fast increase of index ids.
4848
4849 output_stream << name << ":";
4850 int32_t index_id = AssignIndexIDToThread(thread_id);
4851 output_stream << index_id << ";";
4852
4853 output_stream << usec_name << ":" << usec_value << ";";
4854 } else {
4855 // Skip past 'thread_used_name'.
4856 llvm::StringRef local_name, local_value;
4857 profileDataExtractor.GetNameColonValue(local_name, local_value);
4858 }
4859
4860 // Store current time as previous time so that they can be compared
4861 // later.
4862 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
4863 } else {
4864 // Bail out and use old string.
4865 output_stream << name << ":" << value << ";";
4866 }
4867 } else {
4868 output_stream << name << ":" << value << ";";
4869 }
4870 }
4871 output_stream << end_delimiter;
4872 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
4873
4874 return output_stream.str();
4875}
4876
4877void ProcessGDBRemote::HandleStopReply() {
4878 if (GetStopID() != 0)
4879 return;
4880
4881 if (GetID() == LLDB_INVALID_PROCESS_ID0) {
4882 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
4883 if (pid != LLDB_INVALID_PROCESS_ID0)
4884 SetID(pid);
4885 }
4886 BuildDynamicRegisterInfo(true);
4887}
4888
4889static const char *const s_async_json_packet_prefix = "JSON-async:";
4890
4891static StructuredData::ObjectSP
4892ParseStructuredDataPacket(llvm::StringRef packet) {
4893 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS(1u << 1)));
4894
4895 if (!packet.consume_front(s_async_json_packet_prefix)) {
4896 if (log) {
4897 log->Printf(
4898 "GDBRemoteCommmunicationClientBase::%s() received $J packet "
4899 "but was not a StructuredData packet: packet starts with "
4900 "%s",
4901 __FUNCTION__,
4902 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
4903 }
4904 return StructuredData::ObjectSP();
4905 }
4906
4907 // This is an asynchronous JSON packet, destined for a
4908 // StructuredDataPlugin.
4909 StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);
4910 if (log) {
4911 if (json_sp) {
4912 StreamString json_str;
4913 json_sp->Dump(json_str);
4914 json_str.Flush();
4915 log->Printf("ProcessGDBRemote::%s() "
4916 "received Async StructuredData packet: %s",
4917 __FUNCTION__, json_str.GetData());
4918 } else {
4919 log->Printf("ProcessGDBRemote::%s"
4920 "() received StructuredData packet:"
4921 " parse failure",
4922 __FUNCTION__);
4923 }
4924 }
4925 return json_sp;
4926}
4927
4928void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
4929 auto structured_data_sp = ParseStructuredDataPacket(data);
4930 if (structured_data_sp)
4931 RouteAsyncStructuredData(structured_data_sp);
4932}
4933
4934class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
4935public:
4936 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
4937 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
4938 "Tests packet speeds of various sizes to determine "
4939 "the performance characteristics of the GDB remote "
4940 "connection. ",
4941 NULL__null),
4942 m_option_group(),
4943 m_num_packets(LLDB_OPT_SET_1(1U << 0), false, "count", 'c', 0, eArgTypeCount,
4944 "The number of packets to send of each varying size "
4945 "(default is 1000).",
4946 1000),
4947 m_max_send(LLDB_OPT_SET_1(1U << 0), false, "max-send", 's', 0, eArgTypeCount,
4948 "The maximum number of bytes to send in a packet. Sizes "
4949 "increase in powers of 2 while the size is less than or "
4950 "equal to this option value. (default 1024).",
4951 1024),
4952 m_max_recv(LLDB_OPT_SET_1(1U << 0), false, "max-receive", 'r', 0, eArgTypeCount,
4953 "The maximum number of bytes to receive in a packet. Sizes "
4954 "increase in powers of 2 while the size is less than or "
4955 "equal to this option value. (default 1024).",
4956 1024),
4957 m_json(LLDB_OPT_SET_1(1U << 0), false, "json", 'j',
4958 "Print the output as JSON data for easy parsing.", false, true) {
4959 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL0xFFFFFFFFU, LLDB_OPT_SET_1(1U << 0));
4960 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL0xFFFFFFFFU, LLDB_OPT_SET_1(1U << 0));
4961 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL0xFFFFFFFFU, LLDB_OPT_SET_1(1U << 0));
4962 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL0xFFFFFFFFU, LLDB_OPT_SET_1(1U << 0));
4963 m_option_group.Finalize();
4964 }
4965
4966 ~CommandObjectProcessGDBRemoteSpeedTest() {}
4967
4968 Options *GetOptions() override { return &m_option_group; }
4969
4970 bool DoExecute(Args &command, CommandReturnObject &result) override {
4971 const size_t argc = command.GetArgumentCount();
4972 if (argc == 0) {
4973 ProcessGDBRemote *process =
4974 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
4975 .GetProcessPtr();
4976 if (process) {
4977 StreamSP output_stream_sp(
4978 m_interpreter.GetDebugger().GetAsyncOutputStream());
4979 result.SetImmediateOutputStream(output_stream_sp);
4980
4981 const uint32_t num_packets =
4982 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4983 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4984 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4985 const bool json = m_json.GetOptionValue().GetCurrentValue();
4986 const uint64_t k_recv_amount =
4987 4 * 1024 * 1024; // Receive amount in bytes
4988 process->GetGDBRemote().TestPacketSpeed(
4989 num_packets, max_send, max_recv, k_recv_amount, json,
4990 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
4991 result.SetStatus(eReturnStatusSuccessFinishResult);
4992 return true;
4993 }
4994 } else {
4995 result.AppendErrorWithFormat("'%s' takes no arguments",
4996 m_cmd_name.c_str());
4997 }
4998 result.SetStatus(eReturnStatusFailed);
4999 return false;
5000 }
5001
5002protected:
5003 OptionGroupOptions m_option_group;
5004 OptionGroupUInt64 m_num_packets;
5005 OptionGroupUInt64 m_max_send;
5006 OptionGroupUInt64 m_max_recv;
5007 OptionGroupBoolean m_json;
5008};
5009
5010class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
5011private:
5012public:
5013 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5014 : CommandObjectParsed(interpreter, "process plugin packet history",
5015 "Dumps the packet history buffer. ", NULL__null) {}
5016
5017 ~CommandObjectProcessGDBRemotePacketHistory() {}
5018
5019 bool DoExecute(Args &command, CommandReturnObject &result) override {
5020 const size_t argc = command.GetArgumentCount();
5021 if (argc == 0) {
5022 ProcessGDBRemote *process =
5023 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5024 .GetProcessPtr();
5025 if (process) {
5026 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5027 result.SetStatus(eReturnStatusSuccessFinishResult);
5028 return true;
5029 }
5030 } else {
5031 result.AppendErrorWithFormat("'%s' takes no arguments",
5032 m_cmd_name.c_str());
5033 }
5034 result.SetStatus(eReturnStatusFailed);
5035 return false;
5036 }
5037};
5038
5039class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5040private:
5041public:
5042 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5043 : CommandObjectParsed(
5044 interpreter, "process plugin packet xfer-size",
5045 "Maximum size that lldb will try to read/write one one chunk.",
5046 NULL__null) {}
5047
5048 ~CommandObjectProcessGDBRemotePacketXferSize() {}
5049
5050 bool DoExecute(Args &command, CommandReturnObject &result) override {
5051 const size_t argc = command.GetArgumentCount();
5052 if (argc == 0) {
5053 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5054 "amount to be transferred when "
5055 "reading/writing",
5056 m_cmd_name.c_str());
5057 result.SetStatus(eReturnStatusFailed);
5058 return false;
5059 }
5060
5061 ProcessGDBRemote *process =
5062 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5063 if (process) {
5064 const char *packet_size = command.GetArgumentAtIndex(0);
5065 errno(*__errno_location ()) = 0;
5066 uint64_t user_specified_max = strtoul(packet_size, NULL__null, 10);
5067 if (errno(*__errno_location ()) == 0 && user_specified_max != 0) {
5068 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5069 result.SetStatus(eReturnStatusSuccessFinishResult);
5070 return true;
5071 }
5072 }
5073 result.SetStatus(eReturnStatusFailed);
5074 return false;
5075 }
5076};
5077
5078class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5079private:
5080public:
5081 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5082 : CommandObjectParsed(interpreter, "process plugin packet send",
5083 "Send a custom packet through the GDB remote "
5084 "protocol and print the answer. "
5085 "The packet header and footer will automatically "
5086 "be added to the packet prior to sending and "
5087 "stripped from the result.",
5088 NULL__null) {}
5089
5090 ~CommandObjectProcessGDBRemotePacketSend() {}
5091
5092 bool DoExecute(Args &command, CommandReturnObject &result) override {
5093 const size_t argc = command.GetArgumentCount();
5094 if (argc == 0) {
5095 result.AppendErrorWithFormat(
5096 "'%s' takes a one or more packet content arguments",
5097 m_cmd_name.c_str());
5098 result.SetStatus(eReturnStatusFailed);
5099 return false;
5100 }
5101
5102 ProcessGDBRemote *process =
5103 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5104 if (process) {
5105 for (size_t i = 0; i < argc; ++i) {
5106 const char *packet_cstr = command.GetArgumentAtIndex(0);
5107 bool send_async = true;
5108 StringExtractorGDBRemote response;
5109 process->GetGDBRemote().SendPacketAndWaitForResponse(
5110 packet_cstr, response, send_async);
5111 result.SetStatus(eReturnStatusSuccessFinishResult);
5112 Stream &output_strm = result.GetOutputStream();
5113 output_strm.Printf(" packet: %s\n", packet_cstr);
5114 std::string &response_str = response.GetStringRef();
5115
5116 if (strstr(packet_cstr, "qGetProfileData") != NULL__null) {
5117 response_str = process->HarmonizeThreadIdsForProfileData(response);
5118 }
5119
5120 if (response_str.empty())
5121 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5122 else
5123 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5124 }
5125 }
5126 return true;
5127 }
5128};
5129
5130class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
5131private:
5132public:
5133 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5134 : CommandObjectRaw(interpreter, "process plugin packet monitor",
5135 "Send a qRcmd packet through the GDB remote protocol "
5136 "and print the response."
5137 "The argument passed to this command will be hex "
5138 "encoded into a valid 'qRcmd' packet, sent and the "
5139 "response will be printed.") {}
5140
5141 ~CommandObjectProcessGDBRemotePacketMonitor() {}
5142
5143 bool DoExecute(const char *command, CommandReturnObject &result) override {
5144 if (command == NULL__null || command[0] == '\0') {
5145 result.AppendErrorWithFormat("'%s' takes a command string argument",
5146 m_cmd_name.c_str());
5147 result.SetStatus(eReturnStatusFailed);
5148 return false;
5149 }
5150
5151 ProcessGDBRemote *process =
5152 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5153 if (process) {
5154 StreamString packet;
5155 packet.PutCString("qRcmd,");
5156 packet.PutBytesAsRawHex8(command, strlen(command));
5157
5158 bool send_async = true;
5159 StringExtractorGDBRemote response;
5160 process->GetGDBRemote().SendPacketAndWaitForResponse(
5161 packet.GetString(), response, send_async);
5162 result.SetStatus(eReturnStatusSuccessFinishResult);
5163 Stream &output_strm = result.GetOutputStream();
5164 output_strm.Printf(" packet: %s\n", packet.GetData());
5165 const std::string &response_str = response.GetStringRef();
5166
5167 if (response_str.empty())
5168 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5169 else
5170 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5171 }
5172 return true;
5173 }
5174};
5175
5176class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
5177private:
5178public:
5179 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5180 : CommandObjectMultiword(interpreter, "process plugin packet",
5181 "Commands that deal with GDB remote packets.",
5182 NULL__null) {
5183 LoadSubCommand(
5184 "history",
5185 CommandObjectSP(
5186 new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5187 LoadSubCommand(
5188 "send", CommandObjectSP(
5189 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5190 LoadSubCommand(
5191 "monitor",
5192 CommandObjectSP(
5193 new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5194 LoadSubCommand(
5195 "xfer-size",
5196 CommandObjectSP(
5197 new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5198 LoadSubCommand("speed-test",
5199 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5200 interpreter)));
5201 }
5202
5203 ~CommandObjectProcessGDBRemotePacket() {}
5204};
5205
5206class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
5207public:
5208 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5209 : CommandObjectMultiword(
5210 interpreter, "process plugin",
5211 "Commands for operating on a ProcessGDBRemote process.",
5212 "process plugin <subcommand> [<subcommand-options>]") {
5213 LoadSubCommand(
5214 "packet",
5215 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5216 }
5217
5218 ~CommandObjectMultiwordProcessGDBRemote() {}
5219};
5220
5221CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5222 if (!m_command_sp)
5223 m_command_sp.reset(new CommandObjectMultiwordProcessGDBRemote(
5224 GetTarget().GetDebugger().GetCommandInterpreter()));
5225 return m_command_sp.get();
5226}