Bug Summary

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