Bug Summary

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