blob: 93e08b5ce5bd39bbf8d0322a5e4fdddf6459c727 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- 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
Eugene Zelenko0722f082015-10-24 01:28:05 +000010#include "lldb/Host/Config.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012// C Includes
13#include <errno.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000014#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000015#ifndef LLDB_DISABLE_POSIX
Sean Callanan224f6f52012-07-19 18:07:36 +000016#include <netinet/in.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +000017#include <sys/mman.h> // for mmap
Greg Claytonc6c420f2016-08-12 16:46:18 +000018#include <sys/socket.h>
Pavel Labathb6dbe9a2017-07-18 13:14:01 +000019#include <unistd.h>
Zachary Turnerbd22bf22016-08-12 16:52:31 +000020#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000022#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000023#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024
25// C++ Includes
26#include <algorithm>
27#include <map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000028#include <mutex>
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000029#include <sstream>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030
Johnny Chen01a67862011-10-14 00:42:25 +000031#include "lldb/Breakpoint/Watchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000034#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Core/PluginManager.h"
36#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000037#include "lldb/Core/StreamFile.h"
Greg Clayton70b57652011-05-15 01:25:55 +000038#include "lldb/Core/Value.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000039#include "lldb/DataFormatters/FormatManager.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000040#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000041#include "lldb/Host/FileSystem.h"
Zachary Turner39de3112014-09-09 20:54:56 +000042#include "lldb/Host/HostThread.h"
Pavel Labathb6dbe9a2017-07-18 13:14:01 +000043#include "lldb/Host/PosixApi.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000044#include "lldb/Host/PseudoTerminal.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000045#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000046#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000047#include "lldb/Host/ThreadLauncher.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000048#include "lldb/Host/XML.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000049#include "lldb/Interpreter/Args.h"
Greg Clayton02686b82012-10-15 22:42:16 +000050#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000051#include "lldb/Interpreter/CommandObject.h"
52#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000053#include "lldb/Interpreter/CommandReturnObject.h"
Greg Claytone034a042015-05-21 20:52:06 +000054#include "lldb/Interpreter/OptionGroupBoolean.h"
55#include "lldb/Interpreter/OptionGroupUInt64.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000056#include "lldb/Interpreter/OptionValueProperties.h"
57#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000058#include "lldb/Interpreter/Property.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000059#include "lldb/Symbol/ObjectFile.h"
Jason Molenda21586c82015-09-09 03:36:24 +000060#include "lldb/Target/ABI.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061#include "lldb/Target/DynamicLoader.h"
Pavel Labath16064d32018-03-20 11:56:24 +000062#include "lldb/Target/MemoryRegionInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000063#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000064#include "lldb/Target/Target.h"
65#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000066#include "lldb/Target/ThreadPlanCallFunction.h"
Greg Claytonc6c420f2016-08-12 16:46:18 +000067#include "lldb/Utility/CleanUp.h"
Zachary Turner5713a052017-03-22 18:40:07 +000068#include "lldb/Utility/FileSpec.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000069#include "lldb/Utility/StreamString.h"
Pavel Labath38d06322017-06-29 14:32:17 +000070#include "lldb/Utility/Timer.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000071
Eugene Zelenko0722f082015-10-24 01:28:05 +000072// Project includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000073#include "GDBRemoteRegisterContext.h"
74#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000075#include "Plugins/Process/Utility/GDBRemoteSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000076#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000077#include "Plugins/Process/Utility/StopInfoMachException.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000078#include "ProcessGDBRemote.h"
79#include "ProcessGDBRemoteLog.h"
80#include "ThreadGDBRemote.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000081#include "Utility/StringExtractorGDBRemote.h"
82#include "lldb/Host/Host.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000083
Zachary Turner54695a32016-08-29 19:58:14 +000084#include "llvm/ADT/StringSwitch.h"
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000085#include "llvm/Support/Threading.h"
Eugene Zemtsov7993cc52017-03-07 21:34:40 +000086#include "llvm/Support/raw_ostream.h"
Zachary Turner54695a32016-08-29 19:58:14 +000087
Kate Stoneb9c1b512016-09-06 20:57:50 +000088#define DEBUGSERVER_BASENAME "debugserver"
Tamas Berghammerdb264a62015-03-31 09:52:22 +000089using namespace lldb;
90using namespace lldb_private;
91using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000092
Kate Stoneb9c1b512016-09-06 20:57:50 +000093namespace lldb {
94// Provide a function that can easily dump the packet history if we know a
95// ProcessGDBRemote * value (which we can get from logs or from debugging).
96// We need the function in the lldb namespace so it makes it into the final
97// executable since the LLDB shared library only exports stuff in the lldb
98// namespace. This allows you to attach with a debugger and call this
99// function and get the packet history dumped to a file.
100void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
101 StreamFile strm;
Zachary Turner97206d52017-05-12 04:51:55 +0000102 Status error(strm.GetFile().Open(path, File::eOpenOptionWrite |
103 File::eOpenOptionCanCreate));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104 if (error.Success())
105 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(strm);
106}
Eugene Zelenko0722f082015-10-24 01:28:05 +0000107}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000108
Greg Clayton7f982402013-07-15 22:54:20 +0000109namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000110
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111static PropertyDefinition g_properties[] = {
112 {"packet-timeout", OptionValue::eTypeUInt64, true, 1, NULL, NULL,
113 "Specify the default packet timeout in seconds."},
114 {"target-definition-file", OptionValue::eTypeFileSpec, true, 0, NULL, NULL,
115 "The file that provides the description for remote target registers."},
116 {NULL, OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL}};
Ed Maste81b4c5f2016-01-04 01:43:47 +0000117
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118enum { ePropertyPacketTimeout, ePropertyTargetDefinitionFile };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000119
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120class PluginProperties : public Properties {
121public:
122 static ConstString GetSettingName() {
123 return ProcessGDBRemote::GetPluginNameStatic();
124 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000125
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 PluginProperties() : Properties() {
127 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
128 m_collection_sp->Initialize(g_properties);
129 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000130
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 virtual ~PluginProperties() {}
Ed Maste81b4c5f2016-01-04 01:43:47 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 uint64_t GetPacketTimeout() {
134 const uint32_t idx = ePropertyPacketTimeout;
135 return m_collection_sp->GetPropertyAtIndexAsUInt64(
136 NULL, idx, g_properties[idx].default_uint_value);
137 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000138
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 bool SetPacketTimeout(uint64_t timeout) {
140 const uint32_t idx = ePropertyPacketTimeout;
141 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
142 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000143
Kate Stoneb9c1b512016-09-06 20:57:50 +0000144 FileSpec GetTargetDefinitionFile() const {
145 const uint32_t idx = ePropertyTargetDefinitionFile;
146 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
147 }
148};
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000149
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000151
Kate Stoneb9c1b512016-09-06 20:57:50 +0000152static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
153 static ProcessKDPPropertiesSP g_settings_sp;
154 if (!g_settings_sp)
155 g_settings_sp.reset(new PluginProperties());
156 return g_settings_sp;
157}
Ed Maste81b4c5f2016-01-04 01:43:47 +0000158
Eugene Zelenko0722f082015-10-24 01:28:05 +0000159} // anonymous namespace end
Greg Clayton7f982402013-07-15 22:54:20 +0000160
Greg Claytonfda4fab2014-01-10 22:24:11 +0000161// TODO Randomly assigning a port is unsafe. We should get an unused
162// ephemeral port from the kernel and make sure we reserve it before passing
163// it to debugserver.
164
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165#if defined(__APPLE__)
166#define LOW_PORT (IPPORT_RESERVED)
167#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
Greg Claytonfda4fab2014-01-10 22:24:11 +0000168#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000169#define LOW_PORT (1024u)
170#define HIGH_PORT (49151u)
Greg Claytonfda4fab2014-01-10 22:24:11 +0000171#endif
172
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173#if defined(__APPLE__) && \
174 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000175static bool rand_initialized = false;
176
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177static inline uint16_t get_random_port() {
178 if (!rand_initialized) {
179 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181 rand_initialized = true;
182 srand(seed);
183 }
184 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Greg Claytonfda4fab2014-01-10 22:24:11 +0000185}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000186#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000187
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188ConstString ProcessGDBRemote::GetPluginNameStatic() {
189 static ConstString g_name("gdb-remote");
190 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000191}
192
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193const char *ProcessGDBRemote::GetPluginDescriptionStatic() {
194 return "GDB Remote protocol based debugging plug-in.";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000195}
196
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197void ProcessGDBRemote::Terminate() {
198 PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000199}
200
Greg Claytonc3776bf2012-02-09 06:16:32 +0000201lldb::ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
203 ListenerSP listener_sp,
204 const FileSpec *crash_file_path) {
205 lldb::ProcessSP process_sp;
206 if (crash_file_path == NULL)
207 process_sp.reset(new ProcessGDBRemote(target_sp, listener_sp));
208 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000209}
210
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
212 bool plugin_specified_by_name) {
213 if (plugin_specified_by_name)
Jim Ingham5aee1622010-08-09 23:31:02 +0000214 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215
216 // For now we are just making sure the file exists for a given module
217 Module *exe_module = target_sp->GetExecutableModulePointer();
218 if (exe_module) {
219 ObjectFile *exe_objfile = exe_module->GetObjectFile();
220 // We can't debug core files...
221 switch (exe_objfile->GetType()) {
222 case ObjectFile::eTypeInvalid:
223 case ObjectFile::eTypeCoreFile:
224 case ObjectFile::eTypeDebugInfo:
225 case ObjectFile::eTypeObjectFile:
226 case ObjectFile::eTypeSharedLibrary:
227 case ObjectFile::eTypeStubLibrary:
228 case ObjectFile::eTypeJIT:
229 return false;
230 case ObjectFile::eTypeExecutable:
231 case ObjectFile::eTypeDynamicLinker:
232 case ObjectFile::eTypeUnknown:
233 break;
234 }
235 return exe_module->GetFileSpec().Exists();
236 }
237 // However, if there is no executable module, we return true since we might be
238 // preparing to attach.
239 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000240}
241
Eugene Zelenko0722f082015-10-24 01:28:05 +0000242//----------------------------------------------------------------------
243// ProcessGDBRemote constructor
244//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
246 ListenerSP listener_sp)
Pavel Labatha9640122017-11-03 22:12:50 +0000247 : Process(target_sp, listener_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248 m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_last_stop_packet_mutex(),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000249 m_register_info(),
250 m_async_broadcaster(NULL, "lldb.process.gdb-remote.async-broadcaster"),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251 m_async_listener_sp(
252 Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
253 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
254 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
255 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
256 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
257 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
258 m_waiting_for_attach(false), m_destroy_tried_resuming(false),
259 m_command_sp(), m_breakpoint_pc_offset(0),
Pavel Labath16064d32018-03-20 11:56:24 +0000260 m_initial_tid(LLDB_INVALID_THREAD_ID), m_allow_flash_writes(false),
261 m_erased_flash_ranges() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000262 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
263 "async thread should exit");
264 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
265 "async thread continue");
266 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
267 "async thread did exit");
Pavel Labath50556852015-09-03 09:36:22 +0000268
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC));
Pavel Labath50556852015-09-03 09:36:22 +0000270
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271 const uint32_t async_event_mask =
272 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
Pavel Labath50556852015-09-03 09:36:22 +0000273
Kate Stoneb9c1b512016-09-06 20:57:50 +0000274 if (m_async_listener_sp->StartListeningForEvents(
275 &m_async_broadcaster, async_event_mask) != async_event_mask) {
276 if (log)
277 log->Printf("ProcessGDBRemote::%s failed to listen for "
278 "m_async_broadcaster events",
279 __FUNCTION__);
280 }
Pavel Labath50556852015-09-03 09:36:22 +0000281
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 const uint32_t gdb_event_mask =
283 Communication::eBroadcastBitReadThreadDidExit |
284 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
285 if (m_async_listener_sp->StartListeningForEvents(
286 &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
287 if (log)
288 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events",
289 __FUNCTION__);
290 }
Pavel Labath50556852015-09-03 09:36:22 +0000291
Kate Stoneb9c1b512016-09-06 20:57:50 +0000292 const uint64_t timeout_seconds =
293 GetGlobalPluginProperties()->GetPacketTimeout();
294 if (timeout_seconds > 0)
Pavel Labath3aa04912016-10-31 17:19:42 +0000295 m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000296}
297
Eugene Zelenko0722f082015-10-24 01:28:05 +0000298//----------------------------------------------------------------------
299// Destructor
300//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301ProcessGDBRemote::~ProcessGDBRemote() {
302 // m_mach_process.UnregisterNotificationCallbacks (this);
303 Clear();
304 // We need to call finalize on the process before destroying ourselves
305 // to make sure all of the broadcaster cleanup goes as planned. If we
306 // destruct this class, then Process::~Process() might have problems
307 // trying to fully destroy the broadcaster.
308 Finalize();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000309
Kate Stoneb9c1b512016-09-06 20:57:50 +0000310 // The general Finalize is going to try to destroy the process and that SHOULD
311 // shut down the async thread. However, if we don't kill it it will get
312 // stranded and
313 // its connection will go away so when it wakes up it will crash. So kill it
314 // for sure here.
315 StopAsyncThread();
316 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000317}
318
319//----------------------------------------------------------------------
320// PluginInterface
321//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322ConstString ProcessGDBRemote::GetPluginName() { return GetPluginNameStatic(); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000323
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324uint32_t ProcessGDBRemote::GetPluginVersion() { return 1; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000325
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326bool ProcessGDBRemote::ParsePythonTargetDefinition(
327 const FileSpec &target_definition_fspec) {
328 ScriptInterpreter *interpreter =
329 GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Zachary Turner97206d52017-05-12 04:51:55 +0000330 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 StructuredData::ObjectSP module_object_sp(
332 interpreter->LoadPluginModule(target_definition_fspec, error));
333 if (module_object_sp) {
334 StructuredData::DictionarySP target_definition_sp(
335 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
336 "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000337
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338 if (target_definition_sp) {
339 StructuredData::ObjectSP target_object(
340 target_definition_sp->GetValueForKey("host-info"));
341 if (target_object) {
342 if (auto host_info_dict = target_object->GetAsDictionary()) {
343 StructuredData::ObjectSP triple_value =
344 host_info_dict->GetValueForKey("triple");
345 if (auto triple_string_value = triple_value->GetAsString()) {
346 std::string triple_string = triple_string_value->GetValue();
347 ArchSpec host_arch(triple_string.c_str());
348 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
349 GetTarget().SetArchitecture(host_arch);
Greg Clayton312bcbe2013-10-17 01:10:23 +0000350 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 }
Greg Claytonef8180a2013-10-15 00:14:28 +0000352 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 }
354 m_breakpoint_pc_offset = 0;
355 StructuredData::ObjectSP breakpoint_pc_offset_value =
356 target_definition_sp->GetValueForKey("breakpoint-pc-offset");
357 if (breakpoint_pc_offset_value) {
358 if (auto breakpoint_pc_int_value =
359 breakpoint_pc_offset_value->GetAsInteger())
360 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
361 }
362
363 if (m_register_info.SetRegisterInfo(*target_definition_sp,
364 GetTarget().GetArchitecture()) > 0) {
365 return true;
366 }
Greg Claytonef8180a2013-10-15 00:14:28 +0000367 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368 }
369 return false;
Greg Claytonef8180a2013-10-15 00:14:28 +0000370}
371
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372// If the remote stub didn't give us eh_frame or DWARF register numbers for a
373// register,
Jason Molenda21586c82015-09-09 03:36:24 +0000374// see if the ABI can provide them.
375// DWARF and eh_frame register numbers are defined as a part of the ABI.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376static void AugmentRegisterInfoViaABI(RegisterInfo &reg_info,
377 ConstString reg_name, ABISP abi_sp) {
378 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM ||
379 reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM) {
380 if (abi_sp) {
381 RegisterInfo abi_reg_info;
382 if (abi_sp->GetRegisterInfoByName(reg_name, abi_reg_info)) {
383 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM &&
384 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM) {
385 reg_info.kinds[eRegisterKindEHFrame] =
386 abi_reg_info.kinds[eRegisterKindEHFrame];
387 }
388 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM &&
389 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM) {
390 reg_info.kinds[eRegisterKindDWARF] =
391 abi_reg_info.kinds[eRegisterKindDWARF];
392 }
393 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM &&
394 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM) {
395 reg_info.kinds[eRegisterKindGeneric] =
396 abi_reg_info.kinds[eRegisterKindGeneric];
397 }
398 }
399 }
400 }
401}
402
403static size_t SplitCommaSeparatedRegisterNumberString(
404 const llvm::StringRef &comma_separated_regiter_numbers,
405 std::vector<uint32_t> &regnums, int base) {
406 regnums.clear();
407 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
408 value_pair.second = comma_separated_regiter_numbers;
409 do {
410 value_pair = value_pair.second.split(',');
411 if (!value_pair.first.empty()) {
412 uint32_t reg = StringConvert::ToUInt32(value_pair.first.str().c_str(),
413 LLDB_INVALID_REGNUM, base);
414 if (reg != LLDB_INVALID_REGNUM)
415 regnums.push_back(reg);
416 }
417 } while (!value_pair.second.empty());
418 return regnums.size();
419}
420
421void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
422 if (!force && m_register_info.GetNumRegisters() > 0)
423 return;
424
425 m_register_info.Clear();
426
427 // Check if qHostInfo specified a specific packet timeout for this connection.
428 // If so then lets update our setting so the user knows what the timeout is
429 // and can see it.
Pavel Labath3aa04912016-10-31 17:19:42 +0000430 const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
431 if (host_packet_timeout > std::chrono::seconds(0)) {
432 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout.count());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 }
434
435 // Register info search order:
436 // 1 - Use the target definition python file if one is specified.
437 // 2 - If the target definition doesn't have any of the info from the
438 // target.xml (registers) then proceed to read the target.xml.
439 // 3 - Fall back on the qRegisterInfo packets.
440
441 FileSpec target_definition_fspec =
442 GetGlobalPluginProperties()->GetTargetDefinitionFile();
443 if (!target_definition_fspec.Exists()) {
444 // If the filename doesn't exist, it may be a ~ not having been expanded -
445 // try to resolve it.
446 target_definition_fspec.ResolvePath();
447 }
448 if (target_definition_fspec) {
449 // See if we can get register definitions from a python file
450 if (ParsePythonTargetDefinition(target_definition_fspec)) {
451 return;
452 } else {
453 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
454 stream_sp->Printf("ERROR: target description file %s failed to parse.\n",
455 target_definition_fspec.GetPath().c_str());
456 }
457 }
458
459 const ArchSpec &target_arch = GetTarget().GetArchitecture();
460 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
461 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
462
463 // Use the process' architecture instead of the host arch, if available
464 ArchSpec arch_to_use;
465 if (remote_process_arch.IsValid())
466 arch_to_use = remote_process_arch;
467 else
468 arch_to_use = remote_host_arch;
469
470 if (!arch_to_use.IsValid())
471 arch_to_use = target_arch;
472
473 if (GetGDBServerRegisterInfo(arch_to_use))
474 return;
475
476 char packet[128];
477 uint32_t reg_offset = 0;
478 uint32_t reg_num = 0;
479 for (StringExtractorGDBRemote::ResponseType response_type =
480 StringExtractorGDBRemote::eResponse;
481 response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
482 const int packet_len =
483 ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
484 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000485 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000487 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 GDBRemoteCommunication::PacketResult::Success) {
489 response_type = response.GetResponseType();
490 if (response_type == StringExtractorGDBRemote::eResponse) {
491 llvm::StringRef name;
492 llvm::StringRef value;
493 ConstString reg_name;
494 ConstString alt_name;
495 ConstString set_name;
496 std::vector<uint32_t> value_regs;
497 std::vector<uint32_t> invalidate_regs;
498 std::vector<uint8_t> dwarf_opcode_bytes;
499 RegisterInfo reg_info = {
500 NULL, // Name
501 NULL, // Alt name
502 0, // byte size
503 reg_offset, // offset
504 eEncodingUint, // encoding
505 eFormatHex, // format
Jason Molenda21586c82015-09-09 03:36:24 +0000506 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 LLDB_INVALID_REGNUM, // eh_frame reg num
508 LLDB_INVALID_REGNUM, // DWARF reg num
509 LLDB_INVALID_REGNUM, // generic reg num
510 reg_num, // process plugin reg num
511 reg_num // native register number
512 },
513 NULL,
514 NULL,
515 NULL, // Dwarf expression opcode bytes pointer
516 0 // Dwarf expression opcode bytes length
517 };
518
519 while (response.GetNameColonValue(name, value)) {
520 if (name.equals("name")) {
521 reg_name.SetString(value);
522 } else if (name.equals("alt-name")) {
523 alt_name.SetString(value);
524 } else if (name.equals("bitsize")) {
525 value.getAsInteger(0, reg_info.byte_size);
526 reg_info.byte_size /= CHAR_BIT;
527 } else if (name.equals("offset")) {
528 if (value.getAsInteger(0, reg_offset))
529 reg_offset = UINT32_MAX;
530 } else if (name.equals("encoding")) {
531 const Encoding encoding = Args::StringToEncoding(value);
532 if (encoding != eEncodingInvalid)
533 reg_info.encoding = encoding;
534 } else if (name.equals("format")) {
535 Format format = eFormatInvalid;
536 if (Args::StringToFormat(value.str().c_str(), format, NULL)
537 .Success())
538 reg_info.format = format;
539 else {
540 reg_info.format =
541 llvm::StringSwitch<Format>(value)
542 .Case("binary", eFormatBinary)
543 .Case("decimal", eFormatDecimal)
544 .Case("hex", eFormatHex)
545 .Case("float", eFormatFloat)
546 .Case("vector-sint8", eFormatVectorOfSInt8)
547 .Case("vector-uint8", eFormatVectorOfUInt8)
548 .Case("vector-sint16", eFormatVectorOfSInt16)
549 .Case("vector-uint16", eFormatVectorOfUInt16)
550 .Case("vector-sint32", eFormatVectorOfSInt32)
551 .Case("vector-uint32", eFormatVectorOfUInt32)
552 .Case("vector-float32", eFormatVectorOfFloat32)
Valentina Giusticda0ae42016-09-08 14:16:45 +0000553 .Case("vector-uint64", eFormatVectorOfUInt64)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 .Case("vector-uint128", eFormatVectorOfUInt128)
555 .Default(eFormatInvalid);
Jason Molenda21586c82015-09-09 03:36:24 +0000556 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557 } else if (name.equals("set")) {
558 set_name.SetString(value);
559 } else if (name.equals("gcc") || name.equals("ehframe")) {
560 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindEHFrame]))
561 reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM;
562 } else if (name.equals("dwarf")) {
563 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindDWARF]))
564 reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM;
565 } else if (name.equals("generic")) {
566 reg_info.kinds[eRegisterKindGeneric] =
567 Args::StringToGenericRegister(value);
568 } else if (name.equals("container-regs")) {
569 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
570 } else if (name.equals("invalidate-regs")) {
571 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
572 } else if (name.equals("dynamic_size_dwarf_expr_bytes")) {
573 size_t dwarf_opcode_len = value.size() / 2;
574 assert(dwarf_opcode_len > 0);
575
576 dwarf_opcode_bytes.resize(dwarf_opcode_len);
577 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
578
579 StringExtractor opcode_extractor(value);
580 uint32_t ret_val =
581 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
582 assert(dwarf_opcode_len == ret_val);
Hafiz Abid Qadeer05008ca2017-01-19 15:11:01 +0000583 UNUSED_IF_ASSERT_DISABLED(ret_val);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
585 }
Jason Molenda21586c82015-09-09 03:36:24 +0000586 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000587
588 reg_info.byte_offset = reg_offset;
589 assert(reg_info.byte_size != 0);
590 reg_offset += reg_info.byte_size;
591 if (!value_regs.empty()) {
592 value_regs.push_back(LLDB_INVALID_REGNUM);
593 reg_info.value_regs = value_regs.data();
594 }
595 if (!invalidate_regs.empty()) {
596 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
597 reg_info.invalidate_regs = invalidate_regs.data();
598 }
599
600 // We have to make a temporary ABI here, and not use the GetABI because
601 // this code
602 // gets called in DidAttach, when the target architecture (and
603 // consequently the ABI we'll get from
604 // the process) may be wrong.
Jason Molenda43294c92017-06-29 02:57:03 +0000605 ABISP abi_to_use = ABI::FindPlugin(shared_from_this(), arch_to_use);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000606
607 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_to_use);
608
609 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
610 } else {
611 break; // ensure exit before reg_num is incremented
612 }
613 } else {
614 break;
Jason Molenda21586c82015-09-09 03:36:24 +0000615 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000616 }
617
618 if (m_register_info.GetNumRegisters() > 0) {
619 m_register_info.Finalize(GetTarget().GetArchitecture());
620 return;
621 }
622
623 // We didn't get anything if the accumulated reg_num is zero. See if we are
624 // debugging ARM and fill with a hard coded register set until we can get an
625 // updated debugserver down on the devices.
626 // On the other hand, if the accumulated reg_num is positive, see if we can
627 // add composite registers to the existing primordial ones.
628 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
629
630 if (!target_arch.IsValid()) {
631 if (arch_to_use.IsValid() &&
632 (arch_to_use.GetMachine() == llvm::Triple::arm ||
633 arch_to_use.GetMachine() == llvm::Triple::thumb) &&
634 arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple)
635 m_register_info.HardcodeARMRegisters(from_scratch);
636 } else if (target_arch.GetMachine() == llvm::Triple::arm ||
637 target_arch.GetMachine() == llvm::Triple::thumb) {
638 m_register_info.HardcodeARMRegisters(from_scratch);
639 }
640
641 // At this point, we can finalize our register info.
642 m_register_info.Finalize(GetTarget().GetArchitecture());
Jason Molenda21586c82015-09-09 03:36:24 +0000643}
644
Zachary Turner97206d52017-05-12 04:51:55 +0000645Status ProcessGDBRemote::WillLaunch(Module *module) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646 return WillLaunchOrAttach();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000647}
648
Zachary Turner97206d52017-05-12 04:51:55 +0000649Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650 return WillLaunchOrAttach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000651}
652
Zachary Turner97206d52017-05-12 04:51:55 +0000653Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name,
654 bool wait_for_launch) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000655 return WillLaunchOrAttach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000656}
657
Zachary Turner97206d52017-05-12 04:51:55 +0000658Status ProcessGDBRemote::DoConnectRemote(Stream *strm,
659 llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +0000661 Status error(WillLaunchOrAttach());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000662
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 if (error.Fail())
Greg Claytonb766a732011-02-04 01:58:07 +0000664 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665
666 error = ConnectToDebugserver(remote_url);
667
668 if (error.Fail())
669 return error;
670 StartAsyncThread();
671
672 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
673 if (pid == LLDB_INVALID_PROCESS_ID) {
674 // We don't have a valid process ID, so note that we are connected
675 // and could now request to launch or attach, or get remote process
676 // listings...
677 SetPrivateState(eStateConnected);
678 } else {
679 // We have a valid process
680 SetID(pid);
681 GetThreadList();
682 StringExtractorGDBRemote response;
683 if (m_gdb_comm.GetStopReply(response)) {
684 SetLastStopPacket(response);
685
686 // '?' Packets must be handled differently in non-stop mode
687 if (GetTarget().GetNonStopModeEnabled())
688 HandleStopReplySequence();
689
690 Target &target = GetTarget();
691 if (!target.GetArchitecture().IsValid()) {
692 if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
693 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
694 } else {
695 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
696 }
697 }
698
699 const StateType state = SetThreadStopInfo(response);
700 if (state != eStateInvalid) {
701 SetPrivateState(state);
702 } else
Zachary Turner31659452016-11-17 21:15:14 +0000703 error.SetErrorStringWithFormat(
704 "Process %" PRIu64 " was reported after connecting to "
705 "'%s', but state was not stopped: %s",
706 pid, remote_url.str().c_str(), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 } else
708 error.SetErrorStringWithFormat("Process %" PRIu64
709 " was reported after connecting to '%s', "
710 "but no stop reply packet was received",
Zachary Turner31659452016-11-17 21:15:14 +0000711 pid, remote_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000712 }
713
714 if (log)
715 log->Printf("ProcessGDBRemote::%s pid %" PRIu64
716 ": normalizing target architecture initial triple: %s "
717 "(GetTarget().GetArchitecture().IsValid() %s, "
718 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
719 __FUNCTION__, GetID(),
720 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
721 GetTarget().GetArchitecture().IsValid() ? "true" : "false",
722 m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
723
724 if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
725 m_gdb_comm.GetHostArchitecture().IsValid()) {
726 // Prefer the *process'* architecture over that of the *host*, if available.
727 if (m_gdb_comm.GetProcessArchitecture().IsValid())
728 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
729 else
730 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
731 }
732
733 if (log)
734 log->Printf("ProcessGDBRemote::%s pid %" PRIu64
735 ": normalized target architecture triple: %s",
736 __FUNCTION__, GetID(),
737 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
738
739 if (error.Success()) {
740 PlatformSP platform_sp = GetTarget().GetPlatform();
741 if (platform_sp && platform_sp->IsConnected())
742 SetUnixSignals(platform_sp->GetUnixSignals());
743 else
744 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
745 }
746
747 return error;
Greg Claytonb766a732011-02-04 01:58:07 +0000748}
749
Zachary Turner97206d52017-05-12 04:51:55 +0000750Status ProcessGDBRemote::WillLaunchOrAttach() {
751 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 m_stdio_communication.Clear();
753 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000754}
755
756//----------------------------------------------------------------------
757// Process Control
758//----------------------------------------------------------------------
Zachary Turner97206d52017-05-12 04:51:55 +0000759Status ProcessGDBRemote::DoLaunch(Module *exe_module,
760 ProcessLaunchInfo &launch_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000761 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +0000762 Status error;
Greg Clayton982c9762011-11-03 21:22:33 +0000763
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764 if (log)
765 log->Printf("ProcessGDBRemote::%s() entered", __FUNCTION__);
Todd Fiala75f47c32014-10-11 21:42:09 +0000766
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767 uint32_t launch_flags = launch_info.GetFlags().Get();
768 FileSpec stdin_file_spec{};
769 FileSpec stdout_file_spec{};
770 FileSpec stderr_file_spec{};
771 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000772
Kate Stoneb9c1b512016-09-06 20:57:50 +0000773 const FileAction *file_action;
774 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
775 if (file_action) {
776 if (file_action->GetAction() == FileAction::eFileActionOpen)
777 stdin_file_spec = file_action->GetFileSpec();
778 }
779 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
780 if (file_action) {
781 if (file_action->GetAction() == FileAction::eFileActionOpen)
782 stdout_file_spec = file_action->GetFileSpec();
783 }
784 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
785 if (file_action) {
786 if (file_action->GetAction() == FileAction::eFileActionOpen)
787 stderr_file_spec = file_action->GetFileSpec();
788 }
Greg Clayton982c9762011-11-03 21:22:33 +0000789
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790 if (log) {
791 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
792 log->Printf("ProcessGDBRemote::%s provided with STDIO paths via "
793 "launch_info: stdin=%s, stdout=%s, stderr=%s",
794 __FUNCTION__,
795 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
796 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
797 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Vince Harrondf3f00f2015-02-10 21:09:04 +0000798 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 log->Printf("ProcessGDBRemote::%s no STDIO paths given via launch_info",
800 __FUNCTION__);
801 }
Vince Harrondf3f00f2015-02-10 21:09:04 +0000802
Kate Stoneb9c1b512016-09-06 20:57:50 +0000803 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
804 if (stdin_file_spec || disable_stdio) {
805 // the inferior will be reading stdin from the specified file
806 // or stdio is completely disabled
807 m_stdin_forward = false;
808 } else {
809 m_stdin_forward = true;
810 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000811
Kate Stoneb9c1b512016-09-06 20:57:50 +0000812 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
813 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
814 // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
815 // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
816 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000817
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 ObjectFile *object_file = exe_module->GetObjectFile();
819 if (object_file) {
820 error = EstablishConnectionIfNeeded(launch_info);
821 if (error.Success()) {
Pavel Labath07d6f882017-12-11 10:09:14 +0000822 PseudoTerminal pty;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000824
Kate Stoneb9c1b512016-09-06 20:57:50 +0000825 PlatformSP platform_sp(GetTarget().GetPlatform());
826 if (disable_stdio) {
827 // set to /dev/null unless redirected to a file above
828 if (!stdin_file_spec)
829 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false);
830 if (!stdout_file_spec)
831 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false);
832 if (!stderr_file_spec)
833 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false);
834 } else if (platform_sp && platform_sp->IsHost()) {
835 // If the debugserver is local and we aren't disabling STDIO, lets use
836 // a pseudo terminal to instead of relying on the 'O' packets for stdio
837 // since 'O' packets can really slow down debugging if the inferior
838 // does a lot of output.
839 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
840 pty.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, NULL, 0)) {
841 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
Chaoren Lind3173f32015-05-29 19:52:29 +0000842
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843 if (!stdin_file_spec)
844 stdin_file_spec = slave_name;
Chaoren Lind3173f32015-05-29 19:52:29 +0000845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 if (!stdout_file_spec)
847 stdout_file_spec = slave_name;
Greg Clayton71337622011-02-24 22:24:29 +0000848
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849 if (!stderr_file_spec)
850 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000851 }
Vince Harron1b5a74e2015-01-21 22:42:49 +0000852 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000853 log->Printf(
854 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
855 "(IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
856 __FUNCTION__,
857 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
858 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
859 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
860 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000861
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862 if (log)
863 log->Printf("ProcessGDBRemote::%s final STDIO paths after all "
864 "adjustments: stdin=%s, stdout=%s, stderr=%s",
865 __FUNCTION__,
866 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
867 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
868 stderr_file_spec ? stderr_file_spec.GetCString()
869 : "<null>");
Ed Maste81b4c5f2016-01-04 01:43:47 +0000870
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 if (stdin_file_spec)
872 m_gdb_comm.SetSTDIN(stdin_file_spec);
873 if (stdout_file_spec)
874 m_gdb_comm.SetSTDOUT(stdout_file_spec);
875 if (stderr_file_spec)
876 m_gdb_comm.SetSTDERR(stderr_file_spec);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000877
Kate Stoneb9c1b512016-09-06 20:57:50 +0000878 m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
879 m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000880
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 m_gdb_comm.SendLaunchArchPacket(
882 GetTarget().GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000883
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884 const char *launch_event_data = launch_info.GetLaunchEventData();
885 if (launch_event_data != NULL && *launch_event_data != '\0')
886 m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
Eugene Zelenko0722f082015-10-24 01:28:05 +0000887
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 if (working_dir) {
889 m_gdb_comm.SetWorkingDir(working_dir);
890 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000891
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 // Send the environment and the program + arguments after we connect
Pavel Labath62930e52018-01-10 11:57:31 +0000893 m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
Ewan Crawford78baa192015-05-13 09:18:18 +0000894
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895 {
896 // Scope for the scoped timeout object
Pavel Labath3aa04912016-10-31 17:19:42 +0000897 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
898 std::chrono::seconds(10));
Ewan Crawford78baa192015-05-13 09:18:18 +0000899
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
901 if (arg_packet_err == 0) {
902 std::string error_str;
903 if (m_gdb_comm.GetLaunchSuccess(error_str)) {
904 SetID(m_gdb_comm.GetCurrentProcessID());
905 } else {
906 error.SetErrorString(error_str.c_str());
907 }
908 } else {
909 error.SetErrorStringWithFormat("'A' packet returned an error: %i",
910 arg_packet_err);
911 }
912 }
913
914 if (GetID() == LLDB_INVALID_PROCESS_ID) {
915 if (log)
916 log->Printf("failed to connect to debugserver: %s",
917 error.AsCString());
918 KillDebugserverProcess();
919 return error;
920 }
921
922 StringExtractorGDBRemote response;
923 if (m_gdb_comm.GetStopReply(response)) {
Ewan Crawford78baa192015-05-13 09:18:18 +0000924 SetLastStopPacket(response);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000925 // '?' Packets must be handled differently in non-stop mode
926 if (GetTarget().GetNonStopModeEnabled())
927 HandleStopReplySequence();
928
929 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
930
931 if (process_arch.IsValid()) {
932 GetTarget().MergeArchitecture(process_arch);
933 } else {
934 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
935 if (host_arch.IsValid())
936 GetTarget().MergeArchitecture(host_arch);
937 }
938
939 SetPrivateState(SetThreadStopInfo(response));
940
941 if (!disable_stdio) {
Pavel Labath07d6f882017-12-11 10:09:14 +0000942 if (pty.GetMasterFileDescriptor() != PseudoTerminal::invalid_fd)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000943 SetSTDIOFileDescriptor(pty.ReleaseMasterFileDescriptor());
944 }
945 }
946 } else {
947 if (log)
948 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Ewan Crawford78baa192015-05-13 09:18:18 +0000949 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000950 } else {
951 // Set our user ID to an invalid process ID.
952 SetID(LLDB_INVALID_PROCESS_ID);
953 error.SetErrorStringWithFormat(
954 "failed to get object file from '%s' for arch %s",
955 exe_module->GetFileSpec().GetFilename().AsCString(),
956 exe_module->GetArchitecture().GetArchitectureName());
957 }
958 return error;
Ewan Crawford78baa192015-05-13 09:18:18 +0000959}
960
Zachary Turner97206d52017-05-12 04:51:55 +0000961Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
962 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963 // Only connect if we have a valid connect URL
964 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
965
Zachary Turner31659452016-11-17 21:15:14 +0000966 if (!connect_url.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000967 if (log)
968 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
Zachary Turner31659452016-11-17 21:15:14 +0000969 connect_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000970 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
971 new ConnectionFileDescriptor());
972 if (conn_ap.get()) {
973 const uint32_t max_retry_count = 50;
974 uint32_t retry_count = 0;
975 while (!m_gdb_comm.IsConnected()) {
976 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess) {
977 m_gdb_comm.SetConnection(conn_ap.release());
978 break;
979 } else if (error.WasInterrupted()) {
980 // If we were interrupted, don't keep retrying.
981 break;
982 }
983
984 retry_count++;
985
986 if (retry_count >= max_retry_count)
987 break;
988
989 usleep(100000);
990 }
991 }
992 }
993
994 if (!m_gdb_comm.IsConnected()) {
995 if (error.Success())
996 error.SetErrorString("not connected to remote gdb server");
997 return error;
998 }
999
1000 // Start the communications read thread so all incoming data can be
1001 // parsed into packets and queued as they arrive.
1002 if (GetTarget().GetNonStopModeEnabled())
1003 m_gdb_comm.StartReadThread();
1004
1005 // We always seem to be able to open a connection to a local port
1006 // so we need to make sure we can then send data to it. If we can't
1007 // then we aren't actually connected to anything, so try and do the
1008 // handshake with the remote GDB server and make sure that goes
1009 // alright.
1010 if (!m_gdb_comm.HandshakeWithServer(&error)) {
1011 m_gdb_comm.Disconnect();
1012 if (error.Success())
1013 error.SetErrorString("not connected to remote gdb server");
1014 return error;
1015 }
1016
1017 // Send $QNonStop:1 packet on startup if required
1018 if (GetTarget().GetNonStopModeEnabled())
1019 GetTarget().SetNonStopModeEnabled(m_gdb_comm.SetNonStopMode(true));
1020
1021 m_gdb_comm.GetEchoSupported();
1022 m_gdb_comm.GetThreadSuffixSupported();
1023 m_gdb_comm.GetListThreadsInStopReplySupported();
1024 m_gdb_comm.GetHostInfo();
1025 m_gdb_comm.GetVContSupported('c');
1026 m_gdb_comm.GetVAttachOrWaitSupported();
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001027 m_gdb_comm.EnableErrorStringInPacket();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028
1029 // Ask the remote server for the default thread id
1030 if (GetTarget().GetNonStopModeEnabled())
1031 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1032
1033 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1034 for (size_t idx = 0; idx < num_cmds; idx++) {
1035 StringExtractorGDBRemote response;
1036 m_gdb_comm.SendPacketAndWaitForResponse(
1037 GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1038 }
1039 return error;
1040}
1041
1042void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
1043 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1044 if (log)
1045 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1046 if (GetID() != LLDB_INVALID_PROCESS_ID) {
1047 BuildDynamicRegisterInfo(false);
1048
1049 // See if the GDB server supports the qHostInfo information
1050
1051 // See if the GDB server supports the qProcessInfo packet, if so
1052 // prefer that over the Host information as it will be more specific
1053 // to our process.
1054
1055 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1056 if (remote_process_arch.IsValid()) {
1057 process_arch = remote_process_arch;
1058 if (log)
1059 log->Printf("ProcessGDBRemote::%s gdb-remote had process architecture, "
1060 "using %s %s",
1061 __FUNCTION__, process_arch.GetArchitectureName()
1062 ? process_arch.GetArchitectureName()
1063 : "<null>",
1064 process_arch.GetTriple().getTriple().c_str()
1065 ? process_arch.GetTriple().getTriple().c_str()
1066 : "<null>");
1067 } else {
1068 process_arch = m_gdb_comm.GetHostArchitecture();
1069 if (log)
1070 log->Printf("ProcessGDBRemote::%s gdb-remote did not have process "
1071 "architecture, using gdb-remote host architecture %s %s",
1072 __FUNCTION__, process_arch.GetArchitectureName()
1073 ? process_arch.GetArchitectureName()
1074 : "<null>",
1075 process_arch.GetTriple().getTriple().c_str()
1076 ? process_arch.GetTriple().getTriple().c_str()
1077 : "<null>");
1078 }
1079
1080 if (process_arch.IsValid()) {
1081 const ArchSpec &target_arch = GetTarget().GetArchitecture();
1082 if (target_arch.IsValid()) {
1083 if (log)
1084 log->Printf(
1085 "ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1086 __FUNCTION__, target_arch.GetArchitectureName()
1087 ? target_arch.GetArchitectureName()
1088 : "<null>",
1089 target_arch.GetTriple().getTriple().c_str()
1090 ? target_arch.GetTriple().getTriple().c_str()
1091 : "<null>");
1092
1093 // If the remote host is ARM and we have apple as the vendor, then
1094 // ARM executables and shared libraries can have mixed ARM
1095 // architectures.
1096 // You can have an armv6 executable, and if the host is armv7, then the
1097 // system will load the best possible architecture for all shared
1098 // libraries
1099 // it has, so we really need to take the remote host architecture as our
1100 // defacto architecture in this case.
1101
1102 if ((process_arch.GetMachine() == llvm::Triple::arm ||
1103 process_arch.GetMachine() == llvm::Triple::thumb) &&
1104 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
1105 GetTarget().SetArchitecture(process_arch);
1106 if (log)
1107 log->Printf("ProcessGDBRemote::%s remote process is ARM/Apple, "
1108 "setting target arch to %s %s",
1109 __FUNCTION__, process_arch.GetArchitectureName()
1110 ? process_arch.GetArchitectureName()
1111 : "<null>",
1112 process_arch.GetTriple().getTriple().c_str()
1113 ? process_arch.GetTriple().getTriple().c_str()
1114 : "<null>");
1115 } else {
1116 // Fill in what is missing in the triple
1117 const llvm::Triple &remote_triple = process_arch.GetTriple();
1118 llvm::Triple new_target_triple = target_arch.GetTriple();
1119 if (new_target_triple.getVendorName().size() == 0) {
1120 new_target_triple.setVendor(remote_triple.getVendor());
1121
1122 if (new_target_triple.getOSName().size() == 0) {
1123 new_target_triple.setOS(remote_triple.getOS());
1124
1125 if (new_target_triple.getEnvironmentName().size() == 0)
1126 new_target_triple.setEnvironment(
1127 remote_triple.getEnvironment());
1128 }
1129
1130 ArchSpec new_target_arch = target_arch;
1131 new_target_arch.SetTriple(new_target_triple);
1132 GetTarget().SetArchitecture(new_target_arch);
1133 }
1134 }
1135
1136 if (log)
1137 log->Printf("ProcessGDBRemote::%s final target arch after "
1138 "adjustments for remote architecture: %s %s",
1139 __FUNCTION__, target_arch.GetArchitectureName()
1140 ? target_arch.GetArchitectureName()
1141 : "<null>",
1142 target_arch.GetTriple().getTriple().c_str()
1143 ? target_arch.GetTriple().getTriple().c_str()
1144 : "<null>");
1145 } else {
1146 // The target doesn't have a valid architecture yet, set it from
1147 // the architecture we got from the remote GDB server
1148 GetTarget().SetArchitecture(process_arch);
1149 }
1150 }
1151
1152 // Find out which StructuredDataPlugins are supported by the
1153 // debug monitor. These plugins transmit data over async $J packets.
1154 auto supported_packets_array =
1155 m_gdb_comm.GetSupportedStructuredDataPlugins();
1156 if (supported_packets_array)
1157 MapSupportedStructuredDataPlugins(*supported_packets_array);
1158 }
1159}
1160
1161void ProcessGDBRemote::DidLaunch() {
1162 ArchSpec process_arch;
1163 DidLaunchOrAttach(process_arch);
1164}
1165
Zachary Turner97206d52017-05-12 04:51:55 +00001166Status ProcessGDBRemote::DoAttachToProcessWithID(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1168 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00001169 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170
1171 if (log)
1172 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1173
1174 // Clear out and clean up from any current state
1175 Clear();
1176 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1177 error = EstablishConnectionIfNeeded(attach_info);
1178 if (error.Success()) {
1179 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1180
1181 char packet[64];
1182 const int packet_len =
1183 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1184 SetID(attach_pid);
1185 m_async_broadcaster.BroadcastEvent(
1186 eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1187 } else
1188 SetExitStatus(-1, error.AsCString());
1189 }
1190
1191 return error;
1192}
1193
Zachary Turner97206d52017-05-12 04:51:55 +00001194Status ProcessGDBRemote::DoAttachToProcessWithName(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195 const char *process_name, const ProcessAttachInfo &attach_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001196 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 // Clear out and clean up from any current state
1198 Clear();
1199
1200 if (process_name && process_name[0]) {
1201 error = EstablishConnectionIfNeeded(attach_info);
1202 if (error.Success()) {
1203 StreamString packet;
1204
1205 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1206
1207 if (attach_info.GetWaitForLaunch()) {
1208 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1209 packet.PutCString("vAttachWait");
1210 } else {
1211 if (attach_info.GetIgnoreExisting())
1212 packet.PutCString("vAttachWait");
1213 else
1214 packet.PutCString("vAttachOrWait");
1215 }
1216 } else
1217 packet.PutCString("vAttachName");
1218 packet.PutChar(';');
1219 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1220 endian::InlHostByteOrder(),
1221 endian::InlHostByteOrder());
1222
1223 m_async_broadcaster.BroadcastEvent(
1224 eBroadcastBitAsyncContinue,
Zachary Turnerc1564272016-11-16 21:15:24 +00001225 new EventDataBytes(packet.GetString().data(), packet.GetSize()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226
1227 } else
1228 SetExitStatus(-1, error.AsCString());
1229 }
1230 return error;
1231}
1232
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001233lldb::user_id_t ProcessGDBRemote::StartTrace(const TraceOptions &options,
1234 Status &error) {
1235 return m_gdb_comm.SendStartTracePacket(options, error);
1236}
1237
1238Status ProcessGDBRemote::StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
1239 return m_gdb_comm.SendStopTracePacket(uid, thread_id);
1240}
1241
1242Status ProcessGDBRemote::GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
1243 llvm::MutableArrayRef<uint8_t> &buffer,
1244 size_t offset) {
1245 return m_gdb_comm.SendGetDataPacket(uid, thread_id, buffer, offset);
1246}
1247
1248Status ProcessGDBRemote::GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
1249 llvm::MutableArrayRef<uint8_t> &buffer,
1250 size_t offset) {
1251 return m_gdb_comm.SendGetMetaDataPacket(uid, thread_id, buffer, offset);
1252}
1253
1254Status ProcessGDBRemote::GetTraceConfig(lldb::user_id_t uid,
1255 TraceOptions &options) {
1256 return m_gdb_comm.SendGetTraceConfigPacket(uid, options);
1257}
1258
Kate Stoneb9c1b512016-09-06 20:57:50 +00001259void ProcessGDBRemote::DidExit() {
1260 // When we exit, disconnect from the GDB server communications
1261 m_gdb_comm.Disconnect();
1262}
1263
1264void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1265 // If you can figure out what the architecture is, fill it in here.
1266 process_arch.Clear();
1267 DidLaunchOrAttach(process_arch);
1268}
1269
Zachary Turner97206d52017-05-12 04:51:55 +00001270Status ProcessGDBRemote::WillResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 m_continue_c_tids.clear();
1272 m_continue_C_tids.clear();
1273 m_continue_s_tids.clear();
1274 m_continue_S_tids.clear();
1275 m_jstopinfo_sp.reset();
1276 m_jthreadsinfo_sp.reset();
Zachary Turner97206d52017-05-12 04:51:55 +00001277 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278}
1279
Zachary Turner97206d52017-05-12 04:51:55 +00001280Status ProcessGDBRemote::DoResume() {
1281 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1283 if (log)
1284 log->Printf("ProcessGDBRemote::Resume()");
1285
1286 ListenerSP listener_sp(
1287 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1288 if (listener_sp->StartListeningForEvents(
1289 &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
1290 listener_sp->StartListeningForEvents(
1291 &m_async_broadcaster,
1292 ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1293
1294 const size_t num_threads = GetThreadList().GetSize();
1295
1296 StreamString continue_packet;
1297 bool continue_packet_error = false;
1298 if (m_gdb_comm.HasAnyVContSupport()) {
1299 if (!GetTarget().GetNonStopModeEnabled() &&
1300 (m_continue_c_tids.size() == num_threads ||
1301 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1302 m_continue_s_tids.empty() && m_continue_S_tids.empty()))) {
1303 // All threads are continuing, just send a "c" packet
1304 continue_packet.PutCString("c");
1305 } else {
1306 continue_packet.PutCString("vCont");
1307
1308 if (!m_continue_c_tids.empty()) {
1309 if (m_gdb_comm.GetVContSupported('c')) {
1310 for (tid_collection::const_iterator
1311 t_pos = m_continue_c_tids.begin(),
1312 t_end = m_continue_c_tids.end();
1313 t_pos != t_end; ++t_pos)
1314 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1315 } else
1316 continue_packet_error = true;
1317 }
1318
1319 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1320 if (m_gdb_comm.GetVContSupported('C')) {
1321 for (tid_sig_collection::const_iterator
1322 s_pos = m_continue_C_tids.begin(),
1323 s_end = m_continue_C_tids.end();
1324 s_pos != s_end; ++s_pos)
1325 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
1326 s_pos->first);
1327 } else
1328 continue_packet_error = true;
1329 }
1330
1331 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1332 if (m_gdb_comm.GetVContSupported('s')) {
1333 for (tid_collection::const_iterator
1334 t_pos = m_continue_s_tids.begin(),
1335 t_end = m_continue_s_tids.end();
1336 t_pos != t_end; ++t_pos)
1337 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1338 } else
1339 continue_packet_error = true;
1340 }
1341
1342 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1343 if (m_gdb_comm.GetVContSupported('S')) {
1344 for (tid_sig_collection::const_iterator
1345 s_pos = m_continue_S_tids.begin(),
1346 s_end = m_continue_S_tids.end();
1347 s_pos != s_end; ++s_pos)
1348 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
1349 s_pos->first);
1350 } else
1351 continue_packet_error = true;
1352 }
1353
1354 if (continue_packet_error)
Zachary Turnerc1564272016-11-16 21:15:24 +00001355 continue_packet.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356 }
1357 } else
1358 continue_packet_error = true;
1359
1360 if (continue_packet_error) {
1361 // Either no vCont support, or we tried to use part of the vCont
1362 // packet that wasn't supported by the remote GDB server.
1363 // We need to try and make a simple packet that can do our continue
1364 const size_t num_continue_c_tids = m_continue_c_tids.size();
1365 const size_t num_continue_C_tids = m_continue_C_tids.size();
1366 const size_t num_continue_s_tids = m_continue_s_tids.size();
1367 const size_t num_continue_S_tids = m_continue_S_tids.size();
1368 if (num_continue_c_tids > 0) {
1369 if (num_continue_c_tids == num_threads) {
1370 // All threads are resuming...
1371 m_gdb_comm.SetCurrentThreadForRun(-1);
1372 continue_packet.PutChar('c');
1373 continue_packet_error = false;
1374 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1375 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1376 // Only one thread is continuing
1377 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1378 continue_packet.PutChar('c');
1379 continue_packet_error = false;
1380 }
1381 }
1382
1383 if (continue_packet_error && num_continue_C_tids > 0) {
1384 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1385 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1386 num_continue_S_tids == 0) {
1387 const int continue_signo = m_continue_C_tids.front().second;
1388 // Only one thread is continuing
1389 if (num_continue_C_tids > 1) {
1390 // More that one thread with a signal, yet we don't have
1391 // vCont support and we are being asked to resume each
1392 // thread with a signal, we need to make sure they are
1393 // all the same signal, or we can't issue the continue
1394 // accurately with the current support...
1395 if (num_continue_C_tids > 1) {
1396 continue_packet_error = false;
1397 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1398 if (m_continue_C_tids[i].second != continue_signo)
1399 continue_packet_error = true;
1400 }
1401 }
1402 if (!continue_packet_error)
1403 m_gdb_comm.SetCurrentThreadForRun(-1);
1404 } else {
1405 // Set the continue thread ID
1406 continue_packet_error = false;
1407 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1408 }
1409 if (!continue_packet_error) {
1410 // Add threads continuing with the same signo...
1411 continue_packet.Printf("C%2.2x", continue_signo);
1412 }
1413 }
1414 }
1415
1416 if (continue_packet_error && num_continue_s_tids > 0) {
1417 if (num_continue_s_tids == num_threads) {
1418 // All threads are resuming...
1419 m_gdb_comm.SetCurrentThreadForRun(-1);
1420
1421 // If in Non-Stop-Mode use vCont when stepping
1422 if (GetTarget().GetNonStopModeEnabled()) {
1423 if (m_gdb_comm.GetVContSupported('s'))
1424 continue_packet.PutCString("vCont;s");
1425 else
1426 continue_packet.PutChar('s');
1427 } else
1428 continue_packet.PutChar('s');
1429
1430 continue_packet_error = false;
1431 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1432 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1433 // Only one thread is stepping
1434 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1435 continue_packet.PutChar('s');
1436 continue_packet_error = false;
1437 }
1438 }
1439
1440 if (!continue_packet_error && num_continue_S_tids > 0) {
1441 if (num_continue_S_tids == num_threads) {
1442 const int step_signo = m_continue_S_tids.front().second;
1443 // Are all threads trying to step with the same signal?
1444 continue_packet_error = false;
1445 if (num_continue_S_tids > 1) {
1446 for (size_t i = 1; i < num_threads; ++i) {
1447 if (m_continue_S_tids[i].second != step_signo)
1448 continue_packet_error = true;
1449 }
1450 }
1451 if (!continue_packet_error) {
1452 // Add threads stepping with the same signo...
1453 m_gdb_comm.SetCurrentThreadForRun(-1);
1454 continue_packet.Printf("S%2.2x", step_signo);
1455 }
1456 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1457 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1458 // Only one thread is stepping with signal
1459 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1460 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1461 continue_packet_error = false;
1462 }
1463 }
1464 }
1465
1466 if (continue_packet_error) {
1467 error.SetErrorString("can't make continue packet for this resume");
1468 } else {
1469 EventSP event_sp;
1470 if (!m_async_thread.IsJoinable()) {
1471 error.SetErrorString("Trying to resume but the async thread is dead.");
1472 if (log)
1473 log->Printf("ProcessGDBRemote::DoResume: Trying to resume but the "
1474 "async thread is dead.");
1475 return error;
1476 }
1477
1478 m_async_broadcaster.BroadcastEvent(
1479 eBroadcastBitAsyncContinue,
Zachary Turnerc1564272016-11-16 21:15:24 +00001480 new EventDataBytes(continue_packet.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001481 continue_packet.GetSize()));
1482
Pavel Labathd35031e12016-11-30 10:41:42 +00001483 if (listener_sp->GetEvent(event_sp, std::chrono::seconds(5)) == false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484 error.SetErrorString("Resume timed out.");
1485 if (log)
1486 log->Printf("ProcessGDBRemote::DoResume: Resume timed out.");
1487 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1488 error.SetErrorString("Broadcast continue, but the async thread was "
1489 "killed before we got an ack back.");
1490 if (log)
1491 log->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the "
1492 "async thread was killed before we got an ack back.");
1493 return error;
1494 }
1495 }
1496 }
1497
1498 return error;
1499}
1500
1501void ProcessGDBRemote::HandleStopReplySequence() {
1502 while (true) {
1503 // Send vStopped
1504 StringExtractorGDBRemote response;
1505 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1506
1507 // OK represents end of signal list
1508 if (response.IsOKResponse())
1509 break;
1510
1511 // If not OK or a normal packet we have a problem
1512 if (!response.IsNormalResponse())
1513 break;
1514
1515 SetLastStopPacket(response);
1516 }
1517}
1518
1519void ProcessGDBRemote::ClearThreadIDList() {
1520 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1521 m_thread_ids.clear();
1522 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00001523}
1524
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001525size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001526ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) {
1527 m_thread_ids.clear();
1528 m_thread_pcs.clear();
1529 size_t comma_pos;
1530 lldb::tid_t tid;
1531 while ((comma_pos = value.find(',')) != std::string::npos) {
1532 value[comma_pos] = '\0';
1533 // thread in big endian hex
1534 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001535 if (tid != LLDB_INVALID_THREAD_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001536 m_thread_ids.push_back(tid);
1537 value.erase(0, comma_pos + 1);
1538 }
1539 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1540 if (tid != LLDB_INVALID_THREAD_ID)
1541 m_thread_ids.push_back(tid);
1542 return m_thread_ids.size();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001543}
1544
Jason Molenda545304d2015-12-18 00:45:35 +00001545size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001546ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) {
1547 m_thread_pcs.clear();
1548 size_t comma_pos;
1549 lldb::addr_t pc;
1550 while ((comma_pos = value.find(',')) != std::string::npos) {
1551 value[comma_pos] = '\0';
1552 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1553 if (pc != LLDB_INVALID_ADDRESS)
1554 m_thread_pcs.push_back(pc);
1555 value.erase(0, comma_pos + 1);
1556 }
1557 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1558 if (pc != LLDB_INVALID_THREAD_ID)
1559 m_thread_pcs.push_back(pc);
1560 return m_thread_pcs.size();
Jason Molenda545304d2015-12-18 00:45:35 +00001561}
1562
Kate Stoneb9c1b512016-09-06 20:57:50 +00001563bool ProcessGDBRemote::UpdateThreadIDList() {
1564 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001565
Kate Stoneb9c1b512016-09-06 20:57:50 +00001566 if (m_jthreadsinfo_sp) {
1567 // If we have the JSON threads info, we can get the thread list from that
1568 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1569 if (thread_infos && thread_infos->GetSize() > 0) {
1570 m_thread_ids.clear();
1571 m_thread_pcs.clear();
1572 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1573 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1574 if (thread_dict) {
1575 // Set the thread stop info from the JSON dictionary
1576 SetThreadStopInfo(thread_dict);
1577 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1578 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1579 m_thread_ids.push_back(tid);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001580 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001581 return true; // Keep iterating through all thread_info objects
1582 });
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001583 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001584 if (!m_thread_ids.empty())
1585 return true;
1586 } else {
1587 // See if we can get the thread IDs from the current stop reply packets
1588 // that might contain a "threads" key/value pair
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001589
Kate Stoneb9c1b512016-09-06 20:57:50 +00001590 // Lock the thread stack while we access it
1591 // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1592 std::unique_lock<std::recursive_mutex> stop_stack_lock(
1593 m_last_stop_packet_mutex, std::defer_lock);
1594 if (stop_stack_lock.try_lock()) {
1595 // Get the number of stop packets on the stack
1596 int nItems = m_stop_packet_stack.size();
1597 // Iterate over them
1598 for (int i = 0; i < nItems; i++) {
1599 // Get the thread stop info
1600 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1601 const std::string &stop_info_str = stop_info.GetStringRef();
Jason Molenda545304d2015-12-18 00:45:35 +00001602
Kate Stoneb9c1b512016-09-06 20:57:50 +00001603 m_thread_pcs.clear();
1604 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1605 if (thread_pcs_pos != std::string::npos) {
1606 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1607 const size_t end = stop_info_str.find(';', start);
1608 if (end != std::string::npos) {
1609 std::string value = stop_info_str.substr(start, end - start);
1610 UpdateThreadPCsFromStopReplyThreadsValue(value);
1611 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001612 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001613
Kate Stoneb9c1b512016-09-06 20:57:50 +00001614 const size_t threads_pos = stop_info_str.find(";threads:");
1615 if (threads_pos != std::string::npos) {
1616 const size_t start = threads_pos + strlen(";threads:");
1617 const size_t end = stop_info_str.find(';', start);
1618 if (end != std::string::npos) {
1619 std::string value = stop_info_str.substr(start, end - start);
1620 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1621 return true;
1622 }
1623 }
1624 }
1625 }
1626 }
1627
1628 bool sequence_mutex_unavailable = false;
1629 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1630 if (sequence_mutex_unavailable) {
1631 return false; // We just didn't get the list
1632 }
1633 return true;
1634}
1635
1636bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list,
1637 ThreadList &new_thread_list) {
1638 // locker will keep a mutex locked until it goes out of scope
1639 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD));
Pavel Labathe8a7b982017-02-06 19:31:09 +00001640 LLDB_LOGV(log, "pid = {0}", GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001641
1642 size_t num_thread_ids = m_thread_ids.size();
1643 // The "m_thread_ids" thread ID list should always be updated after each stop
1644 // reply packet, but in case it isn't, update it here.
1645 if (num_thread_ids == 0) {
1646 if (!UpdateThreadIDList())
1647 return false;
1648 num_thread_ids = m_thread_ids.size();
1649 }
1650
1651 ThreadList old_thread_list_copy(old_thread_list);
1652 if (num_thread_ids > 0) {
1653 for (size_t i = 0; i < num_thread_ids; ++i) {
1654 tid_t tid = m_thread_ids[i];
1655 ThreadSP thread_sp(
1656 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1657 if (!thread_sp) {
1658 thread_sp.reset(new ThreadGDBRemote(*this, tid));
Pavel Labathe8a7b982017-02-06 19:31:09 +00001659 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1660 thread_sp.get(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001661 } else {
Pavel Labathe8a7b982017-02-06 19:31:09 +00001662 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1663 thread_sp.get(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001664 }
Pavel Labathe0a5b572017-01-20 14:17:16 +00001665
1666 SetThreadPc(thread_sp, i);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001667 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1668 }
1669 }
1670
1671 // Whatever that is left in old_thread_list_copy are not
1672 // present in new_thread_list. Remove non-existent threads from internal id
1673 // table.
1674 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1675 for (size_t i = 0; i < old_num_thread_ids; i++) {
1676 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1677 if (old_thread_sp) {
1678 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1679 m_thread_id_to_index_id_map.erase(old_thread_id);
1680 }
1681 }
1682
1683 return true;
1684}
1685
Pavel Labathe0a5b572017-01-20 14:17:16 +00001686void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1687 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1688 GetByteOrder() != eByteOrderInvalid) {
1689 ThreadGDBRemote *gdb_thread =
1690 static_cast<ThreadGDBRemote *>(thread_sp.get());
1691 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1692 if (reg_ctx_sp) {
1693 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1694 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1695 if (pc_regnum != LLDB_INVALID_REGNUM) {
1696 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1697 }
1698 }
1699 }
1700}
1701
Kate Stoneb9c1b512016-09-06 20:57:50 +00001702bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1703 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1704 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1705 // packet
1706 if (thread_infos_sp) {
1707 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1708 if (thread_infos) {
1709 lldb::tid_t tid;
1710 const size_t n = thread_infos->GetSize();
1711 for (size_t i = 0; i < n; ++i) {
1712 StructuredData::Dictionary *thread_dict =
1713 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1714 if (thread_dict) {
1715 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1716 "tid", tid, LLDB_INVALID_THREAD_ID)) {
1717 if (tid == thread->GetID())
1718 return (bool)SetThreadStopInfo(thread_dict);
1719 }
1720 }
1721 }
1722 }
1723 }
1724 return false;
1725}
1726
1727bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1728 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1729 // packet
1730 if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1731 return true;
1732
1733 // See if we got thread stop info for any threads valid stop info reasons
1734 // threads
1735 // via the "jstopinfo" packet stop reply packet key/value pair?
1736 if (m_jstopinfo_sp) {
1737 // If we have "jstopinfo" then we have stop descriptions for all threads
1738 // that have stop reasons, and if there is no entry for a thread, then
1739 // it has no stop reason.
1740 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1741 if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1742 thread->SetStopInfo(StopInfoSP());
Greg Clayton9e920902012-04-10 02:25:43 +00001743 }
1744 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001745 }
1746
1747 // Fall back to using the qThreadStopInfo packet
1748 StringExtractorGDBRemote stop_packet;
1749 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1750 return SetThreadStopInfo(stop_packet) == eStateStopped;
1751 return false;
Greg Clayton9e920902012-04-10 02:25:43 +00001752}
1753
Kate Stoneb9c1b512016-09-06 20:57:50 +00001754ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1755 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1756 uint8_t signo, const std::string &thread_name, const std::string &reason,
1757 const std::string &description, uint32_t exc_type,
1758 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1759 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1760 // queue_serial are valid
1761 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1762 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1763 ThreadSP thread_sp;
1764 if (tid != LLDB_INVALID_THREAD_ID) {
1765 // Scope for "locker" below
Greg Clayton9e920902012-04-10 02:25:43 +00001766 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001767 // m_thread_list_real does have its own mutex, but we need to
1768 // hold onto the mutex between the call to
1769 // m_thread_list_real.FindThreadByID(...)
1770 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1771 std::lock_guard<std::recursive_mutex> guard(
1772 m_thread_list_real.GetMutex());
1773 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1774
1775 if (!thread_sp) {
1776 // Create the thread if we need to
1777 thread_sp.reset(new ThreadGDBRemote(*this, tid));
1778 m_thread_list_real.AddThread(thread_sp);
1779 }
Greg Clayton9e920902012-04-10 02:25:43 +00001780 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001781
Kate Stoneb9c1b512016-09-06 20:57:50 +00001782 if (thread_sp) {
1783 ThreadGDBRemote *gdb_thread =
1784 static_cast<ThreadGDBRemote *>(thread_sp.get());
1785 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1786
Pavel Labathe0a5b572017-01-20 14:17:16 +00001787 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1788 if (iter != m_thread_ids.end()) {
1789 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1790 }
1791
Kate Stoneb9c1b512016-09-06 20:57:50 +00001792 for (const auto &pair : expedited_register_map) {
1793 StringExtractor reg_value_extractor;
1794 reg_value_extractor.GetStringRef() = pair.second;
1795 DataBufferSP buffer_sp(new DataBufferHeap(
1796 reg_value_extractor.GetStringRef().size() / 2, 0));
1797 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1798 gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
1799 }
1800
1801 thread_sp->SetName(thread_name.empty() ? NULL : thread_name.c_str());
1802
1803 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1804 // Check if the GDB server was able to provide the queue name, kind and
1805 // serial number
1806 if (queue_vars_valid)
1807 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1808 queue_serial, dispatch_queue_t,
1809 associated_with_dispatch_queue);
1810 else
1811 gdb_thread->ClearQueueInfo();
1812
1813 gdb_thread->SetAssociatedWithLibdispatchQueue(
1814 associated_with_dispatch_queue);
1815
1816 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1817 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1818
1819 // Make sure we update our thread stop reason just once
1820 if (!thread_sp->StopInfoIsUpToDate()) {
1821 thread_sp->SetStopInfo(StopInfoSP());
1822 // If there's a memory thread backed by this thread, we need to use it
1823 // to calcualte StopInfo.
1824 ThreadSP memory_thread_sp =
1825 m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
1826 if (memory_thread_sp)
1827 thread_sp = memory_thread_sp;
1828
1829 if (exc_type != 0) {
1830 const size_t exc_data_size = exc_data.size();
1831
1832 thread_sp->SetStopInfo(
1833 StopInfoMachException::CreateStopReasonWithMachException(
1834 *thread_sp, exc_type, exc_data_size,
1835 exc_data_size >= 1 ? exc_data[0] : 0,
1836 exc_data_size >= 2 ? exc_data[1] : 0,
1837 exc_data_size >= 3 ? exc_data[2] : 0));
1838 } else {
1839 bool handled = false;
1840 bool did_exec = false;
1841 if (!reason.empty()) {
1842 if (reason.compare("trace") == 0) {
1843 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1844 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1845 ->GetBreakpointSiteList()
1846 .FindByAddress(pc);
1847
1848 // If the current pc is a breakpoint site then the StopInfo should
1849 // be set to Breakpoint
1850 // Otherwise, it will be set to Trace.
1851 if (bp_site_sp &&
1852 bp_site_sp->ValidForThisThread(thread_sp.get())) {
1853 thread_sp->SetStopInfo(
1854 StopInfo::CreateStopReasonWithBreakpointSiteID(
1855 *thread_sp, bp_site_sp->GetID()));
1856 } else
1857 thread_sp->SetStopInfo(
1858 StopInfo::CreateStopReasonToTrace(*thread_sp));
1859 handled = true;
1860 } else if (reason.compare("breakpoint") == 0) {
1861 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1862 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1863 ->GetBreakpointSiteList()
1864 .FindByAddress(pc);
1865 if (bp_site_sp) {
1866 // If the breakpoint is for this thread, then we'll report the
1867 // hit, but if it is for another thread,
1868 // we can just report no reason. We don't need to worry about
1869 // stepping over the breakpoint here, that
1870 // will be taken care of when the thread resumes and notices
1871 // that there's a breakpoint under the pc.
1872 handled = true;
1873 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1874 thread_sp->SetStopInfo(
1875 StopInfo::CreateStopReasonWithBreakpointSiteID(
1876 *thread_sp, bp_site_sp->GetID()));
1877 } else {
1878 StopInfoSP invalid_stop_info_sp;
1879 thread_sp->SetStopInfo(invalid_stop_info_sp);
Jason Molenda545304d2015-12-18 00:45:35 +00001880 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001881 }
1882 } else if (reason.compare("trap") == 0) {
1883 // Let the trap just use the standard signal stop reason below...
1884 } else if (reason.compare("watchpoint") == 0) {
1885 StringExtractor desc_extractor(description.c_str());
1886 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1887 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1888 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1889 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1890 if (wp_addr != LLDB_INVALID_ADDRESS) {
1891 WatchpointSP wp_sp;
1892 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1893 if ((core >= ArchSpec::kCore_mips_first &&
1894 core <= ArchSpec::kCore_mips_last) ||
1895 (core >= ArchSpec::eCore_arm_generic &&
1896 core <= ArchSpec::eCore_arm_aarch64))
1897 wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1898 wp_hit_addr);
1899 if (!wp_sp)
1900 wp_sp =
1901 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1902 if (wp_sp) {
1903 wp_sp->SetHardwareIndex(wp_index);
1904 watch_id = wp_sp->GetID();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001905 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001906 }
1907 if (watch_id == LLDB_INVALID_WATCH_ID) {
1908 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
1909 GDBR_LOG_WATCHPOINTS));
1910 if (log)
1911 log->Printf("failed to find watchpoint");
1912 }
1913 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1914 *thread_sp, watch_id, wp_hit_addr));
1915 handled = true;
1916 } else if (reason.compare("exception") == 0) {
1917 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1918 *thread_sp, description.c_str()));
1919 handled = true;
1920 } else if (reason.compare("exec") == 0) {
1921 did_exec = true;
1922 thread_sp->SetStopInfo(
1923 StopInfo::CreateStopReasonWithExec(*thread_sp));
1924 handled = true;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001925 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001926 } else if (!signo) {
1927 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1928 lldb::BreakpointSiteSP bp_site_sp =
1929 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1930 pc);
Greg Clayton2e309072015-07-17 23:42:28 +00001931
Kate Stoneb9c1b512016-09-06 20:57:50 +00001932 // If the current pc is a breakpoint site then the StopInfo should
1933 // be set to Breakpoint
1934 // even though the remote stub did not set it as such. This can
1935 // happen when
1936 // the thread is involuntarily interrupted (e.g. due to stops on
1937 // other
1938 // threads) just as it is about to execute the breakpoint
1939 // instruction.
1940 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
1941 thread_sp->SetStopInfo(
1942 StopInfo::CreateStopReasonWithBreakpointSiteID(
1943 *thread_sp, bp_site_sp->GetID()));
1944 handled = true;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001945 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001946 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001947
Kate Stoneb9c1b512016-09-06 20:57:50 +00001948 if (!handled && signo && did_exec == false) {
1949 if (signo == SIGTRAP) {
1950 // Currently we are going to assume SIGTRAP means we are either
1951 // hitting a breakpoint or hardware single stepping.
1952 handled = true;
1953 addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1954 m_breakpoint_pc_offset;
1955 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1956 ->GetBreakpointSiteList()
1957 .FindByAddress(pc);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001958
Kate Stoneb9c1b512016-09-06 20:57:50 +00001959 if (bp_site_sp) {
1960 // If the breakpoint is for this thread, then we'll report the
1961 // hit, but if it is for another thread,
1962 // we can just report no reason. We don't need to worry about
1963 // stepping over the breakpoint here, that
1964 // will be taken care of when the thread resumes and notices
1965 // that there's a breakpoint under the pc.
1966 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1967 if (m_breakpoint_pc_offset != 0)
1968 thread_sp->GetRegisterContext()->SetPC(pc);
1969 thread_sp->SetStopInfo(
1970 StopInfo::CreateStopReasonWithBreakpointSiteID(
1971 *thread_sp, bp_site_sp->GetID()));
1972 } else {
1973 StopInfoSP invalid_stop_info_sp;
1974 thread_sp->SetStopInfo(invalid_stop_info_sp);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001975 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001976 } else {
1977 // If we were stepping then assume the stop was the result of
1978 // the trace. If we were
1979 // not stepping then report the SIGTRAP.
1980 // FIXME: We are still missing the case where we single step
1981 // over a trap instruction.
1982 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1983 thread_sp->SetStopInfo(
1984 StopInfo::CreateStopReasonToTrace(*thread_sp));
Greg Clayton2e309072015-07-17 23:42:28 +00001985 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001986 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1987 *thread_sp, signo, description.c_str()));
1988 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001989 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001990 if (!handled)
1991 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1992 *thread_sp, signo, description.c_str()));
1993 }
1994
1995 if (!description.empty()) {
1996 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1997 if (stop_info_sp) {
1998 const char *stop_info_desc = stop_info_sp->GetDescription();
1999 if (!stop_info_desc || !stop_info_desc[0])
2000 stop_info_sp->SetDescription(description.c_str());
2001 } else {
2002 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2003 *thread_sp, description.c_str()));
2004 }
2005 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002006 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002007 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002008 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002009 }
2010 return thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002011}
2012
Greg Clayton2e309072015-07-17 23:42:28 +00002013lldb::ThreadSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00002014ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
2015 static ConstString g_key_tid("tid");
2016 static ConstString g_key_name("name");
2017 static ConstString g_key_reason("reason");
2018 static ConstString g_key_metype("metype");
2019 static ConstString g_key_medata("medata");
2020 static ConstString g_key_qaddr("qaddr");
2021 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2022 static ConstString g_key_associated_with_dispatch_queue(
2023 "associated_with_dispatch_queue");
2024 static ConstString g_key_queue_name("qname");
2025 static ConstString g_key_queue_kind("qkind");
2026 static ConstString g_key_queue_serial_number("qserialnum");
2027 static ConstString g_key_registers("registers");
2028 static ConstString g_key_memory("memory");
2029 static ConstString g_key_address("address");
2030 static ConstString g_key_bytes("bytes");
2031 static ConstString g_key_description("description");
2032 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002033
Kate Stoneb9c1b512016-09-06 20:57:50 +00002034 // Stop with signal and thread info
2035 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2036 uint8_t signo = 0;
2037 std::string value;
2038 std::string thread_name;
2039 std::string reason;
2040 std::string description;
2041 uint32_t exc_type = 0;
2042 std::vector<addr_t> exc_data;
2043 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2044 ExpeditedRegisterMap expedited_register_map;
2045 bool queue_vars_valid = false;
2046 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2047 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2048 std::string queue_name;
2049 QueueKind queue_kind = eQueueKindUnknown;
2050 uint64_t queue_serial_number = 0;
2051 // Iterate through all of the thread dictionary key/value pairs from the
2052 // structured data dictionary
2053
2054 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2055 &signo, &reason, &description, &exc_type, &exc_data,
2056 &thread_dispatch_qaddr, &queue_vars_valid,
2057 &associated_with_dispatch_queue, &dispatch_queue_t,
2058 &queue_name, &queue_kind, &queue_serial_number](
2059 ConstString key,
2060 StructuredData::Object *object) -> bool {
2061 if (key == g_key_tid) {
2062 // thread in big endian hex
2063 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2064 } else if (key == g_key_metype) {
2065 // exception type in big endian hex
2066 exc_type = object->GetIntegerValue(0);
2067 } else if (key == g_key_medata) {
2068 // exception data in big endian hex
2069 StructuredData::Array *array = object->GetAsArray();
2070 if (array) {
2071 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2072 exc_data.push_back(object->GetIntegerValue());
2073 return true; // Keep iterating through all array items
2074 });
2075 }
2076 } else if (key == g_key_name) {
2077 thread_name = object->GetStringValue();
2078 } else if (key == g_key_qaddr) {
2079 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2080 } else if (key == g_key_queue_name) {
2081 queue_vars_valid = true;
2082 queue_name = object->GetStringValue();
2083 } else if (key == g_key_queue_kind) {
2084 std::string queue_kind_str = object->GetStringValue();
2085 if (queue_kind_str == "serial") {
2086 queue_vars_valid = true;
2087 queue_kind = eQueueKindSerial;
2088 } else if (queue_kind_str == "concurrent") {
2089 queue_vars_valid = true;
2090 queue_kind = eQueueKindConcurrent;
2091 }
2092 } else if (key == g_key_queue_serial_number) {
2093 queue_serial_number = object->GetIntegerValue(0);
2094 if (queue_serial_number != 0)
2095 queue_vars_valid = true;
2096 } else if (key == g_key_dispatch_queue_t) {
2097 dispatch_queue_t = object->GetIntegerValue(0);
2098 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2099 queue_vars_valid = true;
2100 } else if (key == g_key_associated_with_dispatch_queue) {
2101 queue_vars_valid = true;
2102 bool associated = object->GetBooleanValue();
2103 if (associated)
2104 associated_with_dispatch_queue = eLazyBoolYes;
2105 else
2106 associated_with_dispatch_queue = eLazyBoolNo;
2107 } else if (key == g_key_reason) {
2108 reason = object->GetStringValue();
2109 } else if (key == g_key_description) {
2110 description = object->GetStringValue();
2111 } else if (key == g_key_registers) {
2112 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2113
2114 if (registers_dict) {
2115 registers_dict->ForEach(
2116 [&expedited_register_map](ConstString key,
2117 StructuredData::Object *object) -> bool {
2118 const uint32_t reg =
2119 StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10);
2120 if (reg != UINT32_MAX)
2121 expedited_register_map[reg] = object->GetStringValue();
2122 return true; // Keep iterating through all array items
2123 });
2124 }
2125 } else if (key == g_key_memory) {
2126 StructuredData::Array *array = object->GetAsArray();
2127 if (array) {
2128 array->ForEach([this](StructuredData::Object *object) -> bool {
2129 StructuredData::Dictionary *mem_cache_dict =
2130 object->GetAsDictionary();
2131 if (mem_cache_dict) {
2132 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2133 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2134 "address", mem_cache_addr)) {
2135 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
Zachary Turner28333212017-05-12 05:49:54 +00002136 llvm::StringRef str;
2137 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2138 StringExtractor bytes(str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002139 bytes.SetFilePos(0);
2140
2141 const size_t byte_size = bytes.GetStringRef().size() / 2;
2142 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2143 const size_t bytes_copied =
2144 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2145 if (bytes_copied == byte_size)
2146 m_memory_cache.AddL1CacheData(mem_cache_addr,
2147 data_buffer_sp);
2148 }
2149 }
2150 }
2151 }
2152 return true; // Keep iterating through all array items
2153 });
2154 }
2155
2156 } else if (key == g_key_signal)
2157 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2158 return true; // Keep iterating through all dictionary key/value pairs
2159 });
2160
2161 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2162 reason, description, exc_type, exc_data,
2163 thread_dispatch_qaddr, queue_vars_valid,
2164 associated_with_dispatch_queue, dispatch_queue_t,
2165 queue_name, queue_kind, queue_serial_number);
2166}
2167
2168StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2169 stop_packet.SetFilePos(0);
2170 const char stop_type = stop_packet.GetChar();
2171 switch (stop_type) {
2172 case 'T':
2173 case 'S': {
2174 // This is a bit of a hack, but is is required. If we did exec, we
2175 // need to clear our thread lists and also know to rebuild our dynamic
2176 // register info before we lookup and threads and populate the expedited
2177 // register values so we need to know this right away so we can cleanup
2178 // and update our registers.
2179 const uint32_t stop_id = GetStopID();
2180 if (stop_id == 0) {
2181 // Our first stop, make sure we have a process ID, and also make
2182 // sure we know about our registers
2183 if (GetID() == LLDB_INVALID_PROCESS_ID) {
2184 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2185 if (pid != LLDB_INVALID_PROCESS_ID)
2186 SetID(pid);
2187 }
2188 BuildDynamicRegisterInfo(true);
2189 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002190 // Stop with signal and thread info
2191 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002192 const uint8_t signo = stop_packet.GetHexU8();
2193 llvm::StringRef key;
2194 llvm::StringRef value;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002195 std::string thread_name;
2196 std::string reason;
2197 std::string description;
2198 uint32_t exc_type = 0;
2199 std::vector<addr_t> exc_data;
2200 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002201 bool queue_vars_valid =
2202 false; // says if locals below that start with "queue_" are valid
Jason Molenda77f89352016-01-12 07:09:16 +00002203 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2204 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002205 std::string queue_name;
2206 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002207 uint64_t queue_serial_number = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002208 ExpeditedRegisterMap expedited_register_map;
2209 while (stop_packet.GetNameColonValue(key, value)) {
2210 if (key.compare("metype") == 0) {
2211 // exception type in big endian hex
2212 value.getAsInteger(16, exc_type);
2213 } else if (key.compare("medata") == 0) {
2214 // exception data in big endian hex
2215 uint64_t x;
2216 value.getAsInteger(16, x);
2217 exc_data.push_back(x);
2218 } else if (key.compare("thread") == 0) {
2219 // thread in big endian hex
2220 if (value.getAsInteger(16, tid))
2221 tid = LLDB_INVALID_THREAD_ID;
2222 } else if (key.compare("threads") == 0) {
2223 std::lock_guard<std::recursive_mutex> guard(
2224 m_thread_list_real.GetMutex());
Greg Clayton358cf1e2015-06-25 21:46:34 +00002225
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226 m_thread_ids.clear();
2227 // A comma separated list of all threads in the current
2228 // process that includes the thread for this stop reply
2229 // packet
2230 lldb::tid_t tid;
2231 while (!value.empty()) {
2232 llvm::StringRef tid_str;
2233 std::tie(tid_str, value) = value.split(',');
2234 if (tid_str.getAsInteger(16, tid))
2235 tid = LLDB_INVALID_THREAD_ID;
2236 m_thread_ids.push_back(tid);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002237 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002238 } else if (key.compare("thread-pcs") == 0) {
2239 m_thread_pcs.clear();
2240 // A comma separated list of all threads in the current
2241 // process that includes the thread for this stop reply
2242 // packet
2243 lldb::addr_t pc;
2244 while (!value.empty()) {
2245 llvm::StringRef pc_str;
2246 std::tie(pc_str, value) = value.split(',');
2247 if (pc_str.getAsInteger(16, pc))
2248 pc = LLDB_INVALID_ADDRESS;
2249 m_thread_pcs.push_back(pc);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002250 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002251 } else if (key.compare("jstopinfo") == 0) {
2252 StringExtractor json_extractor(value);
2253 std::string json;
2254 // Now convert the HEX bytes into a string value
2255 json_extractor.GetHexByteString(json);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002256
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 // This JSON contains thread IDs and thread stop info for all threads.
2258 // It doesn't contain expedited registers, memory or queue info.
2259 m_jstopinfo_sp = StructuredData::ParseJSON(json);
2260 } else if (key.compare("hexname") == 0) {
2261 StringExtractor name_extractor(value);
2262 std::string name;
2263 // Now convert the HEX bytes into a string value
2264 name_extractor.GetHexByteString(thread_name);
2265 } else if (key.compare("name") == 0) {
2266 thread_name = value;
2267 } else if (key.compare("qaddr") == 0) {
2268 value.getAsInteger(16, thread_dispatch_qaddr);
2269 } else if (key.compare("dispatch_queue_t") == 0) {
2270 queue_vars_valid = true;
2271 value.getAsInteger(16, dispatch_queue_t);
2272 } else if (key.compare("qname") == 0) {
2273 queue_vars_valid = true;
2274 StringExtractor name_extractor(value);
2275 // Now convert the HEX bytes into a string value
2276 name_extractor.GetHexByteString(queue_name);
2277 } else if (key.compare("qkind") == 0) {
2278 queue_kind = llvm::StringSwitch<QueueKind>(value)
2279 .Case("serial", eQueueKindSerial)
2280 .Case("concurrent", eQueueKindConcurrent)
2281 .Default(eQueueKindUnknown);
2282 queue_vars_valid = queue_kind != eQueueKindUnknown;
2283 } else if (key.compare("qserialnum") == 0) {
2284 if (!value.getAsInteger(0, queue_serial_number))
2285 queue_vars_valid = true;
2286 } else if (key.compare("reason") == 0) {
2287 reason = value;
2288 } else if (key.compare("description") == 0) {
2289 StringExtractor desc_extractor(value);
2290 // Now convert the HEX bytes into a string value
2291 desc_extractor.GetHexByteString(description);
2292 } else if (key.compare("memory") == 0) {
2293 // Expedited memory. GDB servers can choose to send back expedited
2294 // memory
2295 // that can populate the L1 memory cache in the process so that things
2296 // like
2297 // the frame pointer backchain can be expedited. This will help stack
2298 // backtracing be more efficient by not having to send as many memory
2299 // read
2300 // requests down the remote GDB server.
2301
2302 // Key/value pair format: memory:<addr>=<bytes>;
2303 // <addr> is a number whose base will be interpreted by the prefix:
2304 // "0x[0-9a-fA-F]+" for hex
2305 // "0[0-7]+" for octal
2306 // "[1-9]+" for decimal
2307 // <bytes> is native endian ASCII hex bytes just like the register
2308 // values
2309 llvm::StringRef addr_str, bytes_str;
2310 std::tie(addr_str, bytes_str) = value.split('=');
2311 if (!addr_str.empty() && !bytes_str.empty()) {
2312 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2313 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2314 StringExtractor bytes(bytes_str);
2315 const size_t byte_size = bytes.GetBytesLeft() / 2;
2316 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2317 const size_t bytes_copied =
2318 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2319 if (bytes_copied == byte_size)
2320 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2321 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002322 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002323 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2324 key.compare("awatch") == 0) {
2325 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2326 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2327 value.getAsInteger(16, wp_addr);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002328
Kate Stoneb9c1b512016-09-06 20:57:50 +00002329 WatchpointSP wp_sp =
2330 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2331 uint32_t wp_index = LLDB_INVALID_INDEX32;
Eugene Zelenko0722f082015-10-24 01:28:05 +00002332
Kate Stoneb9c1b512016-09-06 20:57:50 +00002333 if (wp_sp)
2334 wp_index = wp_sp->GetHardwareIndex();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002335
Kate Stoneb9c1b512016-09-06 20:57:50 +00002336 reason = "watchpoint";
2337 StreamString ostr;
2338 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002339 description = ostr.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002340 } else if (key.compare("library") == 0) {
2341 LoadModules();
2342 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2343 uint32_t reg = UINT32_MAX;
2344 if (!key.getAsInteger(16, reg))
2345 expedited_register_map[reg] = std::move(value);
2346 }
2347 }
2348
2349 if (tid == LLDB_INVALID_THREAD_ID) {
2350 // A thread id may be invalid if the response is old style 'S' packet
2351 // which does not provide the
2352 // thread information. So update the thread list and choose the first one.
2353 UpdateThreadIDList();
2354
2355 if (!m_thread_ids.empty()) {
2356 tid = m_thread_ids.front();
2357 }
2358 }
2359
2360 ThreadSP thread_sp = SetThreadStopInfo(
2361 tid, expedited_register_map, signo, thread_name, reason, description,
2362 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2363 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2364 queue_kind, queue_serial_number);
2365
2366 return eStateStopped;
2367 } break;
2368
2369 case 'W':
2370 case 'X':
2371 // process exited
2372 return eStateExited;
2373
2374 default:
2375 break;
2376 }
2377 return eStateInvalid;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002378}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002379
Kate Stoneb9c1b512016-09-06 20:57:50 +00002380void ProcessGDBRemote::RefreshStateAfterStop() {
2381 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002382
Kate Stoneb9c1b512016-09-06 20:57:50 +00002383 m_thread_ids.clear();
2384 m_thread_pcs.clear();
2385 // Set the thread stop info. It might have a "threads" key whose value is
2386 // a list of all thread IDs in the current process, so m_thread_ids might
2387 // get set.
Greg Claytona5801ad2015-07-15 22:59:03 +00002388
Kate Stoneb9c1b512016-09-06 20:57:50 +00002389 // Scope for the lock
2390 {
2391 // Lock the thread stack while we access it
2392 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2393 // Get the number of stop packets on the stack
2394 int nItems = m_stop_packet_stack.size();
2395 // Iterate over them
2396 for (int i = 0; i < nItems; i++) {
2397 // Get the thread stop info
2398 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2399 // Process thread stop info
2400 SetThreadStopInfo(stop_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002401 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002402 // Clear the thread stop stack
2403 m_stop_packet_stack.clear();
2404 }
2405
2406 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2407 if (m_thread_ids.empty()) {
2408 // No, we need to fetch the thread list manually
2409 UpdateThreadIDList();
2410 }
2411
2412 // If we have queried for a default thread id
2413 if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2414 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2415 m_initial_tid = LLDB_INVALID_THREAD_ID;
2416 }
2417
2418 // Let all threads recover from stopping and do any clean up based
2419 // on the previous thread state (if any).
2420 m_thread_list_real.RefreshStateAfterStop();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002421}
2422
Zachary Turner97206d52017-05-12 04:51:55 +00002423Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2424 Status error;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002425
Kate Stoneb9c1b512016-09-06 20:57:50 +00002426 if (m_public_state.GetValue() == eStateAttaching) {
2427 // We are being asked to halt during an attach. We need to just close
2428 // our file handle and debugserver will go away, and we can be done...
2429 m_gdb_comm.Disconnect();
2430 } else
2431 caused_stop = m_gdb_comm.Interrupt();
2432 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433}
2434
Zachary Turner97206d52017-05-12 04:51:55 +00002435Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2436 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002437 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2438 if (log)
2439 log->Printf("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002440
Kate Stoneb9c1b512016-09-06 20:57:50 +00002441 error = m_gdb_comm.Detach(keep_stopped);
2442 if (log) {
2443 if (error.Success())
2444 log->PutCString(
2445 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
Greg Clayton513c26c2011-01-29 07:10:55 +00002446 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447 log->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2448 error.AsCString() ? error.AsCString() : "<unknown error>");
2449 }
2450
2451 if (!error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002452 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002453
2454 // Sleep for one second to let the process get all detached...
2455 StopAsyncThread();
2456
2457 SetPrivateState(eStateDetached);
2458 ResumePrivateStateThread();
2459
2460 // KillDebugserverProcess ();
2461 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002462}
2463
Zachary Turner97206d52017-05-12 04:51:55 +00002464Status ProcessGDBRemote::DoDestroy() {
2465 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002466 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2467 if (log)
2468 log->Printf("ProcessGDBRemote::DoDestroy()");
Ed Maste81b4c5f2016-01-04 01:43:47 +00002469
Kate Stoneb9c1b512016-09-06 20:57:50 +00002470 // There is a bug in older iOS debugservers where they don't shut down the
2471 // process
2472 // they are debugging properly. If the process is sitting at a breakpoint or
2473 // an exception,
2474 // this can cause problems with restarting. So we check to see if any of our
2475 // threads are stopped
2476 // at a breakpoint, and if so we remove all the breakpoints, resume the
2477 // process, and THEN
2478 // destroy it again.
2479 //
2480 // Note, we don't have a good way to test the version of debugserver, but I
2481 // happen to know that
2482 // the set of all the iOS debugservers which don't support
2483 // GetThreadSuffixSupported() and that of
2484 // the debugservers with this bug are equal. There really should be a better
2485 // way to test this!
2486 //
2487 // We also use m_destroy_tried_resuming to make sure we only do this once, if
2488 // we resume and then halt and
2489 // get called here to destroy again and we're still at a breakpoint or
2490 // exception, then we should
2491 // just do the straight-forward kill.
2492 //
2493 // And of course, if we weren't able to stop the process by the time we get
2494 // here, it isn't
2495 // necessary (or helpful) to do any of this.
Ed Maste81b4c5f2016-01-04 01:43:47 +00002496
Kate Stoneb9c1b512016-09-06 20:57:50 +00002497 if (!m_gdb_comm.GetThreadSuffixSupported() &&
2498 m_public_state.GetValue() != eStateRunning) {
2499 PlatformSP platform_sp = GetTarget().GetPlatform();
Jim Inghamacff8952013-05-02 00:27:30 +00002500
Kate Stoneb9c1b512016-09-06 20:57:50 +00002501 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2502 if (platform_sp && platform_sp->GetName() &&
2503 platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
2504 if (m_destroy_tried_resuming) {
Greg Clayton8cda7f02013-05-21 21:55:59 +00002505 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002506 log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2507 "destroy once already, not doing it again.");
2508 } else {
2509 // At present, the plans are discarded and the breakpoints disabled
2510 // Process::Destroy,
2511 // but we really need it to happen here and it doesn't matter if we do
2512 // it twice.
2513 m_thread_list.DiscardThreadPlans();
2514 DisableAllBreakpointSites();
Greg Clayton8cda7f02013-05-21 21:55:59 +00002515
Kate Stoneb9c1b512016-09-06 20:57:50 +00002516 bool stop_looks_like_crash = false;
2517 ThreadList &threads = GetThreadList();
2518
2519 {
2520 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2521
2522 size_t num_threads = threads.GetSize();
2523 for (size_t i = 0; i < num_threads; i++) {
2524 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2525 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2526 StopReason reason = eStopReasonInvalid;
2527 if (stop_info_sp)
2528 reason = stop_info_sp->GetStopReason();
2529 if (reason == eStopReasonBreakpoint ||
2530 reason == eStopReasonException) {
2531 if (log)
2532 log->Printf(
2533 "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
2534 " stopped with reason: %s.",
2535 thread_sp->GetProtocolID(), stop_info_sp->GetDescription());
2536 stop_looks_like_crash = true;
2537 break;
2538 }
2539 }
2540 }
2541
2542 if (stop_looks_like_crash) {
2543 if (log)
2544 log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2545 "breakpoint, continue and then kill.");
2546 m_destroy_tried_resuming = true;
2547
2548 // If we are going to run again before killing, it would be good to
2549 // suspend all the threads
2550 // before resuming so they won't get into more trouble. Sadly, for
2551 // the threads stopped with
2552 // the breakpoint or exception, the exception doesn't get cleared if
2553 // it is suspended, so we do
2554 // have to run the risk of letting those threads proceed a bit.
2555
2556 {
2557 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2558
2559 size_t num_threads = threads.GetSize();
2560 for (size_t i = 0; i < num_threads; i++) {
2561 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2562 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2563 StopReason reason = eStopReasonInvalid;
2564 if (stop_info_sp)
2565 reason = stop_info_sp->GetStopReason();
2566 if (reason != eStopReasonBreakpoint &&
2567 reason != eStopReasonException) {
2568 if (log)
2569 log->Printf("ProcessGDBRemote::DoDestroy() - Suspending "
2570 "thread: 0x%4.4" PRIx64 " before running.",
2571 thread_sp->GetProtocolID());
2572 thread_sp->SetResumeState(eStateSuspended);
2573 }
2574 }
2575 }
2576 Resume();
2577 return Destroy(false);
2578 }
2579 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002580 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002581 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002582
Kate Stoneb9c1b512016-09-06 20:57:50 +00002583 // Interrupt if our inferior is running...
2584 int exit_status = SIGABRT;
2585 std::string exit_string;
Greg Clayton2e309072015-07-17 23:42:28 +00002586
Kate Stoneb9c1b512016-09-06 20:57:50 +00002587 if (m_gdb_comm.IsConnected()) {
2588 if (m_public_state.GetValue() != eStateAttaching) {
2589 StringExtractorGDBRemote response;
2590 bool send_async = true;
Pavel Labath3aa04912016-10-31 17:19:42 +00002591 GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
2592 std::chrono::seconds(3));
Greg Clayton2e309072015-07-17 23:42:28 +00002593
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002594 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002595 GDBRemoteCommunication::PacketResult::Success) {
2596 char packet_cmd = response.GetChar(0);
2597
2598 if (packet_cmd == 'W' || packet_cmd == 'X') {
2599#if defined(__APPLE__)
2600 // For Native processes on Mac OS X, we launch through the Host
2601 // Platform, then hand the process off
2602 // to debugserver, which becomes the parent process through
2603 // "PT_ATTACH". Then when we go to kill
2604 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we
2605 // call waitpid which returns
2606 // with no error and the correct status. But amusingly enough that
2607 // doesn't seem to actually reap
2608 // the process, but instead it is left around as a Zombie. Probably
2609 // the kernel is in the process of
2610 // switching ownership back to lldb which was the original parent, and
2611 // gets confused in the handoff.
2612 // Anyway, so call waitpid here to finally reap it.
2613 PlatformSP platform_sp(GetTarget().GetPlatform());
2614 if (platform_sp && platform_sp->IsHost()) {
2615 int status;
2616 ::pid_t reap_pid;
2617 reap_pid = waitpid(GetID(), &status, WNOHANG);
2618 if (log)
2619 log->Printf("Reaped pid: %d, status: %d.\n", reap_pid, status);
2620 }
2621#endif
2622 SetLastStopPacket(response);
2623 ClearThreadIDList();
2624 exit_status = response.GetHexU8();
2625 } else {
2626 if (log)
2627 log->Printf("ProcessGDBRemote::DoDestroy - got unexpected response "
2628 "to k packet: %s",
2629 response.GetStringRef().c_str());
2630 exit_string.assign("got unexpected response to k packet: ");
2631 exit_string.append(response.GetStringRef());
2632 }
2633 } else {
2634 if (log)
2635 log->Printf("ProcessGDBRemote::DoDestroy - failed to send k packet");
2636 exit_string.assign("failed to send the k packet");
2637 }
2638 } else {
2639 if (log)
2640 log->Printf("ProcessGDBRemote::DoDestroy - killed or interrupted while "
2641 "attaching");
2642 exit_string.assign("killed or interrupted while attaching.");
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002643 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002644 } else {
2645 // If we missed setting the exit status on the way out, do it here.
2646 // NB set exit status can be called multiple times, the first one sets the
2647 // status.
2648 exit_string.assign("destroying when not connected to debugserver");
2649 }
2650
2651 SetExitStatus(exit_status, exit_string.c_str());
2652
2653 StopAsyncThread();
2654 KillDebugserverProcess();
2655 return error;
Greg Clayton8cda7f02013-05-21 21:55:59 +00002656}
2657
Kate Stoneb9c1b512016-09-06 20:57:50 +00002658void ProcessGDBRemote::SetLastStopPacket(
2659 const StringExtractorGDBRemote &response) {
2660 const bool did_exec =
2661 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2662 if (did_exec) {
2663 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2664 if (log)
2665 log->Printf("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2666
2667 m_thread_list_real.Clear();
2668 m_thread_list.Clear();
2669 BuildDynamicRegisterInfo(true);
2670 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2671 }
2672
2673 // Scope the lock
2674 {
2675 // Lock the thread stack while we access it
2676 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2677
2678 // We are are not using non-stop mode, there can only be one last stop
2679 // reply packet, so clear the list.
2680 if (GetTarget().GetNonStopModeEnabled() == false)
2681 m_stop_packet_stack.clear();
2682
2683 // Add this stop packet to the stop packet stack
2684 // This stack will get popped and examined when we switch to the
2685 // Stopped state
2686 m_stop_packet_stack.push_back(response);
2687 }
2688}
2689
2690void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2691 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
Chaoren Linc963a222015-09-01 16:58:45 +00002692}
2693
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694//------------------------------------------------------------------
2695// Process Queries
2696//------------------------------------------------------------------
2697
Kate Stoneb9c1b512016-09-06 20:57:50 +00002698bool ProcessGDBRemote::IsAlive() {
2699 return m_gdb_comm.IsConnected() && Process::IsAlive();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002700}
2701
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702addr_t ProcessGDBRemote::GetImageInfoAddress() {
2703 // request the link map address via the $qShlibInfoAddr packet
2704 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
Aidan Doddsc0c83852015-05-08 09:36:31 +00002705
Kate Stoneb9c1b512016-09-06 20:57:50 +00002706 // the loaded module list can also provides a link map address
2707 if (addr == LLDB_INVALID_ADDRESS) {
2708 LoadedModuleInfoList list;
2709 if (GetLoadedModuleList(list).Success())
2710 addr = list.m_link_map;
2711 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00002712
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002714}
2715
Kate Stoneb9c1b512016-09-06 20:57:50 +00002716void ProcessGDBRemote::WillPublicStop() {
2717 // See if the GDB remote client supports the JSON threads info.
2718 // If so, we gather stop info for all threads, expedited registers,
2719 // expedited memory, runtime queue information (iOS and MacOSX only),
2720 // and more. Expediting memory will help stack backtracing be much
2721 // faster. Expediting registers will make sure we don't have to read
2722 // the thread registers for GPRs.
2723 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
Greg Clayton2e309072015-07-17 23:42:28 +00002724
Kate Stoneb9c1b512016-09-06 20:57:50 +00002725 if (m_jthreadsinfo_sp) {
2726 // Now set the stop info for each thread and also expedite any registers
2727 // and memory that was in the jThreadsInfo response.
2728 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2729 if (thread_infos) {
2730 const size_t n = thread_infos->GetSize();
2731 for (size_t i = 0; i < n; ++i) {
2732 StructuredData::Dictionary *thread_dict =
2733 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2734 if (thread_dict)
2735 SetThreadStopInfo(thread_dict);
2736 }
Greg Clayton2e309072015-07-17 23:42:28 +00002737 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002738 }
Greg Clayton2e309072015-07-17 23:42:28 +00002739}
2740
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002741//------------------------------------------------------------------
2742// Process Memory
2743//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00002744size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002745 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002746 GetMaxMemorySize();
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002747 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2748 // M and m packets take 2 bytes for 1 byte of memory
2749 size_t max_memory_size =
2750 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2751 if (size > max_memory_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002752 // Keep memory read sizes down to a sane limit. This function will be
2753 // called multiple times in order to complete the task by
2754 // lldb_private::Process so it is ok to do this.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002755 size = max_memory_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002756 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002757
Kate Stoneb9c1b512016-09-06 20:57:50 +00002758 char packet[64];
2759 int packet_len;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002760 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2761 binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2762 (uint64_t)size);
2763 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002764 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002765 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002766 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002767 GDBRemoteCommunication::PacketResult::Success) {
2768 if (response.IsNormalResponse()) {
2769 error.Clear();
2770 if (binary_memory_read) {
2771 // The lower level GDBRemoteCommunication packet receive layer has
2772 // already de-quoted any
2773 // 0x7d character escaping that was present in the packet
Jason Molenda6076bf42014-05-06 04:34:52 +00002774
Kate Stoneb9c1b512016-09-06 20:57:50 +00002775 size_t data_received_size = response.GetBytesLeft();
2776 if (data_received_size > size) {
2777 // Don't write past the end of BUF if the remote debug server gave us
2778 // too
2779 // much data for some reason.
2780 data_received_size = size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002781 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002782 memcpy(buf, response.GetStringRef().data(), data_received_size);
2783 return data_received_size;
2784 } else {
2785 return response.GetHexBytes(
2786 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2787 }
2788 } else if (response.IsErrorResponse())
2789 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2790 else if (response.IsUnsupportedResponse())
2791 error.SetErrorStringWithFormat(
2792 "GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002793 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002794 error.SetErrorStringWithFormat(
2795 "unexpected response to GDB server memory read packet '%s': '%s'",
2796 packet, response.GetStringRef().c_str());
2797 } else {
2798 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2799 }
2800 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002801}
2802
Pavel Labath16064d32018-03-20 11:56:24 +00002803Status ProcessGDBRemote::WriteObjectFile(
2804 std::vector<ObjectFile::LoadableData> entries) {
2805 Status error;
2806 // Sort the entries by address because some writes, like those to flash
2807 // memory, must happen in order of increasing address.
2808 std::stable_sort(
2809 std::begin(entries), std::end(entries),
2810 [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
2811 return a.Dest < b.Dest;
2812 });
2813 m_allow_flash_writes = true;
2814 error = Process::WriteObjectFile(entries);
2815 if (error.Success())
2816 error = FlashDone();
2817 else
2818 // Even though some of the writing failed, try to send a flash done if
2819 // some of the writing succeeded so the flash state is reset to normal,
2820 // but don't stomp on the error status that was set in the write failure
2821 // since that's the one we want to report back.
2822 FlashDone();
2823 m_allow_flash_writes = false;
2824 return error;
2825}
2826
2827bool ProcessGDBRemote::HasErased(FlashRange range) {
2828 auto size = m_erased_flash_ranges.GetSize();
2829 for (size_t i = 0; i < size; ++i)
2830 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2831 return true;
2832 return false;
2833}
2834
2835Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
2836 Status status;
2837
2838 MemoryRegionInfo region;
2839 status = GetMemoryRegionInfo(addr, region);
2840 if (!status.Success())
2841 return status;
2842
2843 // The gdb spec doesn't say if erasures are allowed across multiple regions,
2844 // but we'll disallow it to be safe and to keep the logic simple by worring
2845 // about only one region's block size. DoMemoryWrite is this function's
2846 // primary user, and it can easily keep writes within a single memory region
2847 if (addr + size > region.GetRange().GetRangeEnd()) {
2848 status.SetErrorString("Unable to erase flash in multiple regions");
2849 return status;
2850 }
2851
2852 uint64_t blocksize = region.GetBlocksize();
2853 if (blocksize == 0) {
2854 status.SetErrorString("Unable to erase flash because blocksize is 0");
2855 return status;
2856 }
2857
2858 // Erasures can only be done on block boundary adresses, so round down addr
2859 // and round up size
2860 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2861 size += (addr - block_start_addr);
2862 if ((size % blocksize) != 0)
2863 size += (blocksize - size % blocksize);
2864
2865 FlashRange range(block_start_addr, size);
2866
2867 if (HasErased(range))
2868 return status;
2869
2870 // We haven't erased the entire range, but we may have erased part of it.
2871 // (e.g., block A is already erased and range starts in A and ends in B).
2872 // So, adjust range if necessary to exclude already erased blocks.
2873 if (!m_erased_flash_ranges.IsEmpty()) {
2874 // Assuming that writes and erasures are done in increasing addr order,
2875 // because that is a requirement of the vFlashWrite command. Therefore,
2876 // we only need to look at the last range in the list for overlap.
2877 const auto &last_range = *m_erased_flash_ranges.Back();
2878 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2879 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
2880 // overlap will be less than range.GetByteSize() or else HasErased() would
2881 // have been true
2882 range.SetByteSize(range.GetByteSize() - overlap);
2883 range.SetRangeBase(range.GetRangeBase() + overlap);
2884 }
2885 }
2886
2887 StreamString packet;
2888 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2889 (uint64_t)range.GetByteSize());
2890
2891 StringExtractorGDBRemote response;
2892 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2893 true) ==
2894 GDBRemoteCommunication::PacketResult::Success) {
2895 if (response.IsOKResponse()) {
2896 m_erased_flash_ranges.Insert(range, true);
2897 } else {
2898 if (response.IsErrorResponse())
2899 status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2900 addr);
2901 else if (response.IsUnsupportedResponse())
2902 status.SetErrorStringWithFormat("GDB server does not support flashing");
2903 else
2904 status.SetErrorStringWithFormat(
2905 "unexpected response to GDB server flash erase packet '%s': '%s'",
2906 packet.GetData(), response.GetStringRef().c_str());
2907 }
2908 } else {
2909 status.SetErrorStringWithFormat("failed to send packet: '%s'",
2910 packet.GetData());
2911 }
2912 return status;
2913}
2914
2915Status ProcessGDBRemote::FlashDone() {
2916 Status status;
2917 // If we haven't erased any blocks, then we must not have written anything
2918 // either, so there is no need to actually send a vFlashDone command
2919 if (m_erased_flash_ranges.IsEmpty())
2920 return status;
2921 StringExtractorGDBRemote response;
2922 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, true) ==
2923 GDBRemoteCommunication::PacketResult::Success) {
2924 if (response.IsOKResponse()) {
2925 m_erased_flash_ranges.Clear();
2926 } else {
2927 if (response.IsErrorResponse())
2928 status.SetErrorStringWithFormat("flash done failed");
2929 else if (response.IsUnsupportedResponse())
2930 status.SetErrorStringWithFormat("GDB server does not support flashing");
2931 else
2932 status.SetErrorStringWithFormat(
2933 "unexpected response to GDB server flash done packet: '%s'",
2934 response.GetStringRef().c_str());
2935 }
2936 } else {
2937 status.SetErrorStringWithFormat("failed to send flash done packet");
2938 }
2939 return status;
2940}
2941
Kate Stoneb9c1b512016-09-06 20:57:50 +00002942size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
Zachary Turner97206d52017-05-12 04:51:55 +00002943 size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002944 GetMaxMemorySize();
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002945 // M and m packets take 2 bytes for 1 byte of memory
2946 size_t max_memory_size = m_max_memory_size / 2;
2947 if (size > max_memory_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 // Keep memory read sizes down to a sane limit. This function will be
2949 // called multiple times in order to complete the task by
2950 // lldb_private::Process so it is ok to do this.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002951 size = max_memory_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002952 }
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002953
Pavel Labath16064d32018-03-20 11:56:24 +00002954 StreamGDBRemote packet;
2955
2956 MemoryRegionInfo region;
2957 Status region_status = GetMemoryRegionInfo(addr, region);
2958
2959 bool is_flash =
2960 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2961
2962 if (is_flash) {
2963 if (!m_allow_flash_writes) {
2964 error.SetErrorString("Writing to flash memory is not allowed");
2965 return 0;
2966 }
2967 // Keep the write within a flash memory region
2968 if (addr + size > region.GetRange().GetRangeEnd())
2969 size = region.GetRange().GetRangeEnd() - addr;
2970 // Flash memory must be erased before it can be written
2971 error = FlashErase(addr, size);
2972 if (!error.Success())
2973 return 0;
2974 packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
2975 packet.PutEscapedBytes(buf, size);
2976 } else {
2977 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2978 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2979 endian::InlHostByteOrder());
2980 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002981 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002982 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2983 true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002984 GDBRemoteCommunication::PacketResult::Success) {
2985 if (response.IsOKResponse()) {
2986 error.Clear();
2987 return size;
2988 } else if (response.IsErrorResponse())
2989 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2990 addr);
2991 else if (response.IsUnsupportedResponse())
2992 error.SetErrorStringWithFormat(
2993 "GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002994 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002995 error.SetErrorStringWithFormat(
2996 "unexpected response to GDB server memory write packet '%s': '%s'",
Zachary Turnerc1564272016-11-16 21:15:24 +00002997 packet.GetData(), response.GetStringRef().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002998 } else {
2999 error.SetErrorStringWithFormat("failed to send packet: '%s'",
Zachary Turnerc1564272016-11-16 21:15:24 +00003000 packet.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003001 }
3002 return 0;
3003}
3004
3005lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
3006 uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00003007 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003008 Log *log(
3009 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
3010 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3011
3012 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
3013 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
3014 if (allocated_addr != LLDB_INVALID_ADDRESS ||
3015 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3016 return allocated_addr;
3017 }
3018
3019 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
3020 // Call mmap() to create memory in the inferior..
3021 unsigned prot = 0;
3022 if (permissions & lldb::ePermissionsReadable)
3023 prot |= eMmapProtRead;
3024 if (permissions & lldb::ePermissionsWritable)
3025 prot |= eMmapProtWrite;
3026 if (permissions & lldb::ePermissionsExecutable)
3027 prot |= eMmapProtExec;
3028
3029 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3030 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3031 m_addr_to_mmap_size[allocated_addr] = size;
3032 else {
3033 allocated_addr = LLDB_INVALID_ADDRESS;
3034 if (log)
3035 log->Printf("ProcessGDBRemote::%s no direct stub support for memory "
3036 "allocation, and InferiorCallMmap also failed - is stub "
3037 "missing register context save/restore capability?",
3038 __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003039 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003040 }
3041
3042 if (allocated_addr == LLDB_INVALID_ADDRESS)
3043 error.SetErrorStringWithFormat(
3044 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
3045 (uint64_t)size, GetPermissionsAsCString(permissions));
3046 else
3047 error.Clear();
3048 return allocated_addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003049}
3050
Zachary Turner97206d52017-05-12 04:51:55 +00003051Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
3052 MemoryRegionInfo &region_info) {
Ed Maste81b4c5f2016-01-04 01:43:47 +00003053
Zachary Turner97206d52017-05-12 04:51:55 +00003054 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003055 return error;
3056}
3057
Zachary Turner97206d52017-05-12 04:51:55 +00003058Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003059
Zachary Turner97206d52017-05-12 04:51:55 +00003060 Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003061 return error;
3062}
3063
Zachary Turner97206d52017-05-12 04:51:55 +00003064Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
3065 Status error(m_gdb_comm.GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003066 num, after, GetTarget().GetArchitecture()));
3067 return error;
3068}
3069
Zachary Turner97206d52017-05-12 04:51:55 +00003070Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
3071 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003072 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3073
3074 switch (supported) {
3075 case eLazyBoolCalculate:
3076 // We should never be deallocating memory without allocating memory
3077 // first so we should never get eLazyBoolCalculate
3078 error.SetErrorString(
3079 "tried to deallocate memory without ever allocating memory");
3080 break;
3081
3082 case eLazyBoolYes:
3083 if (!m_gdb_comm.DeallocateMemory(addr))
3084 error.SetErrorStringWithFormat(
3085 "unable to deallocate memory at 0x%" PRIx64, addr);
3086 break;
3087
3088 case eLazyBoolNo:
3089 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2a48f522011-05-14 01:50:35 +00003090 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003091 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3092 if (pos != m_addr_to_mmap_size.end() &&
3093 InferiorCallMunmap(this, addr, pos->second))
3094 m_addr_to_mmap_size.erase(pos);
3095 else
3096 error.SetErrorStringWithFormat(
3097 "unable to deallocate memory at 0x%" PRIx64, addr);
Greg Claytoncec91ef2016-02-26 01:20:20 +00003098 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099 break;
3100 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003101
Kate Stoneb9c1b512016-09-06 20:57:50 +00003102 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003103}
3104
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003105//------------------------------------------------------------------
3106// Process STDIO
3107//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003108size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00003109 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110 if (m_stdio_communication.IsConnected()) {
3111 ConnectionStatus status;
3112 m_stdio_communication.Write(src, src_len, status, NULL);
3113 } else if (m_stdin_forward) {
3114 m_gdb_comm.SendStdinNotification(src, src_len);
3115 }
3116 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003117}
3118
Zachary Turner97206d52017-05-12 04:51:55 +00003119Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
3120 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003121 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003122
Kate Stoneb9c1b512016-09-06 20:57:50 +00003123 // Get logging info
3124 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3125 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003126
Kate Stoneb9c1b512016-09-06 20:57:50 +00003127 // Get the breakpoint address
3128 const addr_t addr = bp_site->GetLoadAddress();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003129
Kate Stoneb9c1b512016-09-06 20:57:50 +00003130 // Log that a breakpoint was requested
3131 if (log)
3132 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3133 ") address = 0x%" PRIx64,
3134 site_id, (uint64_t)addr);
3135
3136 // Breakpoint already exists and is enabled
3137 if (bp_site->IsEnabled()) {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003138 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3140 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3141 site_id, (uint64_t)addr);
3142 return error;
3143 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003144
Kate Stoneb9c1b512016-09-06 20:57:50 +00003145 // Get the software breakpoint trap opcode size
3146 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3147
3148 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
3149 // breakpoint type
3150 // is supported by the remote stub. These are set to true by default, and
3151 // later set to false
3152 // only after we receive an unimplemented response when sending a breakpoint
3153 // packet. This means
3154 // initially that unless we were specifically instructed to use a hardware
3155 // breakpoint, LLDB will
3156 // attempt to set a software breakpoint. HardwareRequired() also queries a
3157 // boolean variable which
3158 // indicates if the user specifically asked for hardware breakpoints. If true
3159 // then we will
3160 // skip over software breakpoints.
3161 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3162 (!bp_site->HardwareRequired())) {
3163 // Try to send off a software breakpoint packet ($Z0)
3164 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3165 eBreakpointSoftware, true, addr, bp_op_size);
3166 if (error_no == 0) {
3167 // The breakpoint was placed successfully
3168 bp_site->SetEnabled(true);
3169 bp_site->SetType(BreakpointSite::eExternal);
3170 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003171 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003172
Kate Stoneb9c1b512016-09-06 20:57:50 +00003173 // SendGDBStoppointTypePacket() will return an error if it was unable to set
3174 // this
3175 // breakpoint. We need to differentiate between a error specific to placing
3176 // this breakpoint
3177 // or if we have learned that this breakpoint type is unsupported. To do
3178 // this, we
3179 // must test the support boolean for this breakpoint type to see if it now
3180 // indicates that
3181 // this breakpoint type is unsupported. If they are still supported then we
3182 // should return
3183 // with the error code. If they are now unsupported, then we would like to
3184 // fall through
3185 // and try another form of breakpoint.
3186 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3187 if (error_no != UINT8_MAX)
3188 error.SetErrorStringWithFormat(
3189 "error: %d sending the breakpoint request", errno);
3190 else
3191 error.SetErrorString("error sending the breakpoint request");
3192 return error;
3193 }
3194
3195 // We reach here when software breakpoints have been found to be
3196 // unsupported. For future
3197 // calls to set a breakpoint, we will not attempt to set a breakpoint with a
3198 // type that is
3199 // known not to be supported.
3200 if (log)
3201 log->Printf("Software breakpoints are unsupported");
3202
3203 // So we will fall through and try a hardware breakpoint
3204 }
3205
3206 // The process of setting a hardware breakpoint is much the same as above. We
3207 // check the
3208 // supported boolean for this breakpoint type, and if it is thought to be
3209 // supported then we
3210 // will try to set this breakpoint with a hardware breakpoint.
3211 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3212 // Try to send off a hardware breakpoint packet ($Z1)
3213 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3214 eBreakpointHardware, true, addr, bp_op_size);
3215 if (error_no == 0) {
3216 // The breakpoint was placed successfully
3217 bp_site->SetEnabled(true);
3218 bp_site->SetType(BreakpointSite::eHardware);
3219 return error;
3220 }
3221
3222 // Check if the error was something other then an unsupported breakpoint
3223 // type
3224 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3225 // Unable to set this hardware breakpoint
3226 if (error_no != UINT8_MAX)
3227 error.SetErrorStringWithFormat(
3228 "error: %d sending the hardware breakpoint request "
3229 "(hardware breakpoint resources might be exhausted or unavailable)",
3230 error_no);
3231 else
3232 error.SetErrorString("error sending the hardware breakpoint request "
3233 "(hardware breakpoint resources "
3234 "might be exhausted or unavailable)");
3235 return error;
3236 }
3237
3238 // We will reach here when the stub gives an unsupported response to a
3239 // hardware breakpoint
3240 if (log)
3241 log->Printf("Hardware breakpoints are unsupported");
3242
3243 // Finally we will falling through to a #trap style breakpoint
3244 }
3245
3246 // Don't fall through when hardware breakpoints were specifically requested
3247 if (bp_site->HardwareRequired()) {
3248 error.SetErrorString("hardware breakpoints are not supported");
3249 return error;
3250 }
3251
3252 // As a last resort we want to place a manual breakpoint. An instruction
3253 // is placed into the process memory using memory write packets.
3254 return EnableSoftwareBreakpoint(bp_site);
3255}
3256
Zachary Turner97206d52017-05-12 04:51:55 +00003257Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3258 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003259 assert(bp_site != NULL);
3260 addr_t addr = bp_site->GetLoadAddress();
3261 user_id_t site_id = bp_site->GetID();
3262 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3263 if (log)
3264 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3265 ") addr = 0x%8.8" PRIx64,
3266 site_id, (uint64_t)addr);
3267
3268 if (bp_site->IsEnabled()) {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003269 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3270
Kate Stoneb9c1b512016-09-06 20:57:50 +00003271 BreakpointSite::Type bp_type = bp_site->GetType();
3272 switch (bp_type) {
3273 case BreakpointSite::eSoftware:
3274 error = DisableSoftwareBreakpoint(bp_site);
3275 break;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003276
Kate Stoneb9c1b512016-09-06 20:57:50 +00003277 case BreakpointSite::eHardware:
3278 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3279 addr, bp_op_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003280 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003281 break;
3282
3283 case BreakpointSite::eExternal: {
3284 GDBStoppointType stoppoint_type;
3285 if (bp_site->IsHardware())
3286 stoppoint_type = eBreakpointHardware;
3287 else
3288 stoppoint_type = eBreakpointSoftware;
3289
3290 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr,
3291 bp_op_size))
3292 error.SetErrorToGenericError();
3293 } break;
3294 }
3295 if (error.Success())
3296 bp_site->SetEnabled(false);
3297 } else {
3298 if (log)
3299 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3300 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3301 site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003302 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003303 }
3304
3305 if (error.Success())
3306 error.SetErrorToGenericError();
3307 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003308}
3309
Johnny Chen11309a32011-09-06 22:38:36 +00003310// Pre-requisite: wp != NULL.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003311static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3312 assert(wp);
3313 bool watch_read = wp->WatchpointRead();
3314 bool watch_write = wp->WatchpointWrite();
Johnny Chen11309a32011-09-06 22:38:36 +00003315
Kate Stoneb9c1b512016-09-06 20:57:50 +00003316 // watch_read and watch_write cannot both be false.
3317 assert(watch_read || watch_write);
3318 if (watch_read && watch_write)
3319 return eWatchpointReadWrite;
3320 else if (watch_read)
3321 return eWatchpointRead;
3322 else // Must be watch_write, then.
3323 return eWatchpointWrite;
Johnny Chen11309a32011-09-06 22:38:36 +00003324}
3325
Zachary Turner97206d52017-05-12 04:51:55 +00003326Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3327 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003328 if (wp) {
3329 user_id_t watchID = wp->GetID();
3330 addr_t addr = wp->GetLoadAddress();
3331 Log *log(
3332 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003333 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003334 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3335 watchID);
3336 if (wp->IsEnabled()) {
3337 if (log)
3338 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3339 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3340 watchID, (uint64_t)addr);
3341 return error;
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003342 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003343
3344 GDBStoppointType type = GetGDBStoppointType(wp);
3345 // Pass down an appropriate z/Z packet...
3346 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3347 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3348 wp->GetByteSize()) == 0) {
3349 wp->SetEnabled(true, notify);
3350 return error;
3351 } else
3352 error.SetErrorString("sending gdb watchpoint packet failed");
3353 } else
3354 error.SetErrorString("watchpoints not supported");
3355 } else {
3356 error.SetErrorString("Watchpoint argument was NULL.");
3357 }
3358 if (error.Success())
3359 error.SetErrorToGenericError();
3360 return error;
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003361}
Kate Stoneb9c1b512016-09-06 20:57:50 +00003362
Zachary Turner97206d52017-05-12 04:51:55 +00003363Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3364 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003365 if (wp) {
3366 user_id_t watchID = wp->GetID();
3367
3368 Log *log(
3369 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3370
3371 addr_t addr = wp->GetLoadAddress();
3372
3373 if (log)
3374 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3375 ") addr = 0x%8.8" PRIx64,
3376 watchID, (uint64_t)addr);
3377
3378 if (!wp->IsEnabled()) {
3379 if (log)
3380 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3381 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3382 watchID, (uint64_t)addr);
3383 // See also 'class WatchpointSentry' within StopInfo.cpp.
3384 // This disabling attempt might come from the user-supplied actions, we'll
3385 // route it in order for
3386 // the watchpoint object to intelligently process this action.
3387 wp->SetEnabled(false, notify);
3388 return error;
3389 }
3390
3391 if (wp->IsHardware()) {
3392 GDBStoppointType type = GetGDBStoppointType(wp);
3393 // Pass down an appropriate z/Z packet...
3394 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3395 wp->GetByteSize()) == 0) {
3396 wp->SetEnabled(false, notify);
3397 return error;
3398 } else
3399 error.SetErrorString("sending gdb watchpoint packet failed");
3400 }
3401 // TODO: clear software watchpoints if we implement them
3402 } else {
3403 error.SetErrorString("Watchpoint argument was NULL.");
3404 }
3405 if (error.Success())
3406 error.SetErrorToGenericError();
3407 return error;
3408}
3409
3410void ProcessGDBRemote::Clear() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003411 m_thread_list_real.Clear();
3412 m_thread_list.Clear();
3413}
3414
Zachary Turner97206d52017-05-12 04:51:55 +00003415Status ProcessGDBRemote::DoSignal(int signo) {
3416 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003417 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3418 if (log)
3419 log->Printf("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3420
3421 if (!m_gdb_comm.SendAsyncSignal(signo))
3422 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3423 return error;
3424}
3425
Zachary Turner97206d52017-05-12 04:51:55 +00003426Status
3427ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003428 // Make sure we aren't already connected?
3429 if (m_gdb_comm.IsConnected())
Zachary Turner97206d52017-05-12 04:51:55 +00003430 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003431
3432 PlatformSP platform_sp(GetTarget().GetPlatform());
3433 if (platform_sp && !platform_sp->IsHost())
Zachary Turner97206d52017-05-12 04:51:55 +00003434 return Status("Lost debug server connection");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003435
3436 auto error = LaunchAndConnectToDebugserver(process_info);
3437 if (error.Fail()) {
3438 const char *error_string = error.AsCString();
3439 if (error_string == nullptr)
3440 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3441 }
3442 return error;
3443}
Eugene Zemtsov30153412017-09-25 17:41:16 +00003444#if !defined(_WIN32)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003445#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3446#endif
3447
3448#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Kate Stoneb9c1b512016-09-06 20:57:50 +00003449static bool SetCloexecFlag(int fd) {
3450#if defined(FD_CLOEXEC)
3451 int flags = ::fcntl(fd, F_GETFD);
3452 if (flags == -1)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003453 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003454 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3455#else
3456 return false;
Greg Claytonc6c420f2016-08-12 16:46:18 +00003457#endif
3458}
3459#endif
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003460
Zachary Turner97206d52017-05-12 04:51:55 +00003461Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003462 const ProcessInfo &process_info) {
3463 using namespace std::placeholders; // For _1, _2, etc.
Pavel Labath998bdc52016-05-11 16:59:04 +00003464
Zachary Turner97206d52017-05-12 04:51:55 +00003465 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003466 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3467 // If we locate debugserver, keep that located version around
3468 static FileSpec g_debugserver_file_spec;
3469
3470 ProcessLaunchInfo debugserver_launch_info;
3471 // Make debugserver run in its own session so signals generated by
3472 // special terminal key sequences (^C) don't affect debugserver.
3473 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3474
3475 const std::weak_ptr<ProcessGDBRemote> this_wp =
3476 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3477 debugserver_launch_info.SetMonitorProcessCallback(
3478 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3479 debugserver_launch_info.SetUserID(process_info.GetUserID());
3480
3481 int communication_fd = -1;
3482#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Eugene Zemtsov30153412017-09-25 17:41:16 +00003483 // Use a socketpair on non-Windows systems for security and performance
3484 // reasons.
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003485 int sockets[2]; /* the pair of socket descriptors */
3486 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3487 error.SetErrorToErrno();
3488 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003489 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003490
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003491 int our_socket = sockets[0];
3492 int gdb_socket = sockets[1];
3493 CleanUp cleanup_our(close, our_socket);
3494 CleanUp cleanup_gdb(close, gdb_socket);
3495
Kate Stoneb9c1b512016-09-06 20:57:50 +00003496 // Don't let any child processes inherit our communication socket
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003497 SetCloexecFlag(our_socket);
3498 communication_fd = gdb_socket;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003499#endif
3500
3501 error = m_gdb_comm.StartDebugserverProcess(
3502 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3503 nullptr, nullptr, communication_fd);
3504
3505 if (error.Success())
3506 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3507 else
3508 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3509
3510 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3511#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3512 // Our process spawned correctly, we can now set our connection to use our
3513 // end of the socket pair
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003514 cleanup_our.disable();
3515 m_gdb_comm.SetConnection(new ConnectionFileDescriptor(our_socket, true));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003516#endif
3517 StartAsyncThread();
3518 }
3519
3520 if (error.Fail()) {
3521 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3522
3523 if (log)
3524 log->Printf("failed to start debugserver process: %s",
3525 error.AsCString());
3526 return error;
3527 }
3528
3529 if (m_gdb_comm.IsConnected()) {
3530 // Finish the connection process by doing the handshake without connecting
3531 // (send NULL URL)
Zachary Turner31659452016-11-17 21:15:14 +00003532 ConnectToDebugserver("");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003533 } else {
3534 error.SetErrorString("connection failed");
3535 }
3536 }
3537 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003538}
3539
Kate Stoneb9c1b512016-09-06 20:57:50 +00003540bool ProcessGDBRemote::MonitorDebugserverProcess(
3541 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3542 bool exited, // True if the process did exit
3543 int signo, // Zero for no signal
3544 int exit_status // Exit value of process if signal is zero
3545 ) {
3546 // "debugserver_pid" argument passed in is the process ID for
3547 // debugserver that we are tracking...
3548 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3549 const bool handled = true;
Greg Claytone4e45922011-11-16 05:37:56 +00003550
Kate Stoneb9c1b512016-09-06 20:57:50 +00003551 if (log)
3552 log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3553 ", signo=%i (0x%x), exit_status=%i)",
3554 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
Greg Clayton6779606a2011-01-22 23:43:18 +00003555
Kate Stoneb9c1b512016-09-06 20:57:50 +00003556 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3557 if (log)
3558 log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3559 static_cast<void *>(process_sp.get()));
3560 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
Pavel Labath194357c2016-05-12 11:10:01 +00003561 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003562
Kate Stoneb9c1b512016-09-06 20:57:50 +00003563 // Sleep for a half a second to make sure our inferior process has
3564 // time to set its exit status before we set it incorrectly when
3565 // both the debugserver and the inferior process shut down.
3566 usleep(500000);
3567 // If our process hasn't yet exited, debugserver might have died.
3568 // If the process did exit, then we are reaping it.
3569 const StateType state = process_sp->GetState();
3570
3571 if (state != eStateInvalid && state != eStateUnloaded &&
3572 state != eStateExited && state != eStateDetached) {
3573 char error_str[1024];
3574 if (signo) {
3575 const char *signal_cstr =
3576 process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3577 if (signal_cstr)
3578 ::snprintf(error_str, sizeof(error_str),
3579 DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3580 else
3581 ::snprintf(error_str, sizeof(error_str),
3582 DEBUGSERVER_BASENAME " died with signal %i", signo);
3583 } else {
3584 ::snprintf(error_str, sizeof(error_str),
3585 DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3586 exit_status);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003587 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003588
3589 process_sp->SetExitStatus(-1, error_str);
3590 }
3591 // Debugserver has exited we need to let our ProcessGDBRemote
3592 // know that it no longer has a debugserver instance
3593 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3594 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003595}
3596
Kate Stoneb9c1b512016-09-06 20:57:50 +00003597void ProcessGDBRemote::KillDebugserverProcess() {
3598 m_gdb_comm.Disconnect();
3599 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3600 Host::Kill(m_debugserver_pid, SIGINT);
3601 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3602 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003603}
3604
Kate Stoneb9c1b512016-09-06 20:57:50 +00003605void ProcessGDBRemote::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +00003606 static llvm::once_flag g_once_flag;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003607
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +00003608 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003609 PluginManager::RegisterPlugin(GetPluginNameStatic(),
3610 GetPluginDescriptionStatic(), CreateInstance,
3611 DebuggerInitialize);
3612 });
Greg Clayton7f982402013-07-15 22:54:20 +00003613}
3614
Kate Stoneb9c1b512016-09-06 20:57:50 +00003615void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3616 if (!PluginManager::GetSettingForProcessPlugin(
3617 debugger, PluginProperties::GetSettingName())) {
3618 const bool is_global_setting = true;
3619 PluginManager::CreateSettingForProcessPlugin(
3620 debugger, GetGlobalPluginProperties()->GetValueProperties(),
3621 ConstString("Properties for the gdb-remote process plug-in."),
3622 is_global_setting);
3623 }
3624}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003625
Kate Stoneb9c1b512016-09-06 20:57:50 +00003626bool ProcessGDBRemote::StartAsyncThread() {
3627 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3628
3629 if (log)
3630 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3631
3632 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3633 if (!m_async_thread.IsJoinable()) {
3634 // Create a thread that watches our internal state and controls which
3635 // events make it to clients (into the DCProcess event queue).
3636
3637 m_async_thread =
3638 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>",
3639 ProcessGDBRemote::AsyncThread, this, NULL);
3640 } else if (log)
3641 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
3642 "already running.",
3643 __FUNCTION__);
3644
3645 return m_async_thread.IsJoinable();
3646}
3647
3648void ProcessGDBRemote::StopAsyncThread() {
3649 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3650
3651 if (log)
3652 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3653
3654 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3655 if (m_async_thread.IsJoinable()) {
3656 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3657
3658 // This will shut down the async thread.
3659 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3660
3661 // Stop the stdio thread
3662 m_async_thread.Join(nullptr);
3663 m_async_thread.Reset();
3664 } else if (log)
3665 log->Printf(
3666 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3667 __FUNCTION__);
3668}
3669
3670bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3671 // get the packet at a string
3672 const std::string &pkt = packet.GetStringRef();
3673 // skip %stop:
3674 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3675
3676 // pass as a thread stop info packet
3677 SetLastStopPacket(stop_info);
3678
3679 // check for more stop reasons
3680 HandleStopReplySequence();
3681
3682 // if the process is stopped then we need to fake a resume
3683 // so that we can stop properly with the new break. This
3684 // is possible due to SetPrivateState() broadcasting the
3685 // state change as a side effect.
3686 if (GetPrivateState() == lldb::StateType::eStateStopped) {
3687 SetPrivateState(lldb::StateType::eStateRunning);
3688 }
3689
3690 // since we have some stopped packets we can halt the process
3691 SetPrivateState(lldb::StateType::eStateStopped);
3692
3693 return true;
3694}
3695
3696thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3697 ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3698
3699 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3700 if (log)
3701 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3702 ") thread starting...",
3703 __FUNCTION__, arg, process->GetID());
3704
3705 EventSP event_sp;
3706 bool done = false;
3707 while (!done) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003708 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003709 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3710 ") listener.WaitForEvent (NULL, event_sp)...",
3711 __FUNCTION__, arg, process->GetID());
Pavel Labathd35031e12016-11-30 10:41:42 +00003712 if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003713 const uint32_t event_type = event_sp->GetType();
3714 if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
Pavel Labath50556852015-09-03 09:36:22 +00003715 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003716 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3717 ") Got an event of type: %d...",
3718 __FUNCTION__, arg, process->GetID(), event_type);
Pavel Labath50556852015-09-03 09:36:22 +00003719
Kate Stoneb9c1b512016-09-06 20:57:50 +00003720 switch (event_type) {
3721 case eBroadcastBitAsyncContinue: {
3722 const EventDataBytes *continue_packet =
3723 EventDataBytes::GetEventDataFromEvent(event_sp.get());
Pavel Labath50556852015-09-03 09:36:22 +00003724
Kate Stoneb9c1b512016-09-06 20:57:50 +00003725 if (continue_packet) {
3726 const char *continue_cstr =
3727 (const char *)continue_packet->GetBytes();
3728 const size_t continue_cstr_len = continue_packet->GetByteSize();
Pavel Labath50556852015-09-03 09:36:22 +00003729 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003730 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3731 ") got eBroadcastBitAsyncContinue: %s",
3732 __FUNCTION__, arg, process->GetID(), continue_cstr);
3733
3734 if (::strstr(continue_cstr, "vAttach") == NULL)
3735 process->SetPrivateState(eStateRunning);
3736 StringExtractorGDBRemote response;
3737
3738 // If in Non-Stop-Mode
3739 if (process->GetTarget().GetNonStopModeEnabled()) {
3740 // send the vCont packet
3741 if (!process->GetGDBRemote().SendvContPacket(
3742 llvm::StringRef(continue_cstr, continue_cstr_len),
3743 response)) {
3744 // Something went wrong
3745 done = true;
3746 break;
3747 }
3748 }
3749 // If in All-Stop-Mode
3750 else {
3751 StateType stop_state =
3752 process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3753 *process, *process->GetUnixSignals(),
3754 llvm::StringRef(continue_cstr, continue_cstr_len),
3755 response);
3756
3757 // We need to immediately clear the thread ID list so we are sure
3758 // to get a valid list of threads.
3759 // The thread ID list might be contained within the "response", or
3760 // the stop reply packet that
3761 // caused the stop. So clear it now before we give the stop reply
3762 // packet to the process
3763 // using the process->SetLastStopPacket()...
3764 process->ClearThreadIDList();
3765
3766 switch (stop_state) {
3767 case eStateStopped:
3768 case eStateCrashed:
3769 case eStateSuspended:
3770 process->SetLastStopPacket(response);
3771 process->SetPrivateState(stop_state);
3772 break;
3773
3774 case eStateExited: {
3775 process->SetLastStopPacket(response);
3776 process->ClearThreadIDList();
3777 response.SetFilePos(1);
3778
3779 int exit_status = response.GetHexU8();
3780 std::string desc_string;
3781 if (response.GetBytesLeft() > 0 &&
3782 response.GetChar('-') == ';') {
3783 llvm::StringRef desc_str;
3784 llvm::StringRef desc_token;
3785 while (response.GetNameColonValue(desc_token, desc_str)) {
3786 if (desc_token != "description")
3787 continue;
3788 StringExtractor extractor(desc_str);
3789 extractor.GetHexByteString(desc_string);
3790 }
3791 }
3792 process->SetExitStatus(exit_status, desc_string.c_str());
3793 done = true;
3794 break;
3795 }
3796 case eStateInvalid: {
3797 // Check to see if we were trying to attach and if we got back
3798 // the "E87" error code from debugserver -- this indicates that
3799 // the process is not debuggable. Return a slightly more
3800 // helpful
3801 // error message about why the attach failed.
3802 if (::strstr(continue_cstr, "vAttach") != NULL &&
3803 response.GetError() == 0x87) {
3804 process->SetExitStatus(-1, "cannot attach to process due to "
3805 "System Integrity Protection");
3806 }
3807 // E01 code from vAttach means that the attach failed
3808 if (::strstr(continue_cstr, "vAttach") != NULL &&
3809 response.GetError() == 0x1) {
3810 process->SetExitStatus(-1, "unable to attach");
3811 } else {
3812 process->SetExitStatus(-1, "lost connection");
3813 }
3814 break;
3815 }
3816
3817 default:
3818 process->SetPrivateState(stop_state);
3819 break;
3820 } // switch(stop_state)
3821 } // else // if in All-stop-mode
3822 } // if (continue_packet)
3823 } // case eBroadcastBitAysncContinue
3824 break;
3825
3826 case eBroadcastBitAsyncThreadShouldExit:
3827 if (log)
3828 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3829 ") got eBroadcastBitAsyncThreadShouldExit...",
3830 __FUNCTION__, arg, process->GetID());
3831 done = true;
3832 break;
3833
3834 default:
3835 if (log)
3836 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3837 ") got unknown event 0x%8.8x",
3838 __FUNCTION__, arg, process->GetID(), event_type);
3839 done = true;
3840 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003841 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003842 } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3843 switch (event_type) {
3844 case Communication::eBroadcastBitReadThreadDidExit:
3845 process->SetExitStatus(-1, "lost connection");
3846 done = true;
3847 break;
3848
3849 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3850 lldb_private::Event *event = event_sp.get();
3851 const EventDataBytes *continue_packet =
3852 EventDataBytes::GetEventDataFromEvent(event);
3853 StringExtractorGDBRemote notify(
3854 (const char *)continue_packet->GetBytes());
3855 // Hand this over to the process to handle
3856 process->HandleNotifyPacket(notify);
3857 break;
3858 }
3859
3860 default:
3861 if (log)
3862 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3863 ") got unknown event 0x%8.8x",
3864 __FUNCTION__, arg, process->GetID(), event_type);
3865 done = true;
3866 break;
3867 }
3868 }
3869 } else {
3870 if (log)
3871 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3872 ") listener.WaitForEvent (NULL, event_sp) => false",
3873 __FUNCTION__, arg, process->GetID());
3874 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003875 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003876 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003877
Kate Stoneb9c1b512016-09-06 20:57:50 +00003878 if (log)
3879 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3880 ") thread exiting...",
3881 __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003882
Kate Stoneb9c1b512016-09-06 20:57:50 +00003883 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003884}
3885
Kate Stoneb9c1b512016-09-06 20:57:50 +00003886// uint32_t
3887// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3888// &matches, std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00003889//{
Kate Stoneb9c1b512016-09-06 20:57:50 +00003890// // If we are planning to launch the debugserver remotely, then we need to
3891// fire up a debugserver
3892// // process and ask it for the list of processes. But if we are local, we
3893// can let the Host do it.
Greg Claytone996fd32011-03-08 22:40:15 +00003894// if (m_local_debugserver)
3895// {
3896// return Host::ListProcessesMatchingName (name, matches, pids);
3897// }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003898// else
Greg Claytone996fd32011-03-08 22:40:15 +00003899// {
3900// // FIXME: Implement talking to the remote debugserver.
3901// return 0;
3902// }
3903//
3904//}
3905//
Kate Stoneb9c1b512016-09-06 20:57:50 +00003906bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3907 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3908 lldb::user_id_t break_loc_id) {
3909 // I don't think I have to do anything here, just make sure I notice the new
3910 // thread when it starts to
3911 // run so I can stop it if that's what I want to do.
3912 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3913 if (log)
3914 log->Printf("Hit New Thread Notification breakpoint.");
3915 return false;
Jim Ingham1c823b42011-01-22 01:33:44 +00003916}
3917
Zachary Turner97206d52017-05-12 04:51:55 +00003918Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003919 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3920 LLDB_LOG(log, "Check if need to update ignored signals");
3921
3922 // QPassSignals package is not supported by the server,
3923 // there is no way we can ignore any signals on server side.
3924 if (!m_gdb_comm.GetQPassSignalsSupported())
Zachary Turner97206d52017-05-12 04:51:55 +00003925 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003926
3927 // No signals, nothing to send.
3928 if (m_unix_signals_sp == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00003929 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003930
3931 // Signals' version hasn't changed, no need to send anything.
3932 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3933 if (new_signals_version == m_last_signals_version) {
3934 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3935 m_last_signals_version);
Zachary Turner97206d52017-05-12 04:51:55 +00003936 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003937 }
3938
3939 auto signals_to_ignore =
3940 m_unix_signals_sp->GetFilteredSignals(false, false, false);
Zachary Turner97206d52017-05-12 04:51:55 +00003941 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003942
3943 LLDB_LOG(log,
3944 "Signals' version changed. old version={0}, new version={1}, "
3945 "signals ignored={2}, update result={3}",
3946 m_last_signals_version, new_signals_version,
3947 signals_to_ignore.size(), error);
3948
3949 if (error.Success())
3950 m_last_signals_version = new_signals_version;
3951
3952 return error;
3953}
3954
Kate Stoneb9c1b512016-09-06 20:57:50 +00003955bool ProcessGDBRemote::StartNoticingNewThreads() {
3956 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3957 if (m_thread_create_bp_sp) {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003958 if (log && log->GetVerbose())
Kate Stoneb9c1b512016-09-06 20:57:50 +00003959 log->Printf("Enabled noticing new thread breakpoint.");
3960 m_thread_create_bp_sp->SetEnabled(true);
3961 } else {
3962 PlatformSP platform_sp(GetTarget().GetPlatform());
3963 if (platform_sp) {
3964 m_thread_create_bp_sp =
3965 platform_sp->SetThreadCreationBreakpoint(GetTarget());
3966 if (m_thread_create_bp_sp) {
3967 if (log && log->GetVerbose())
3968 log->Printf(
3969 "Successfully created new thread notification breakpoint %i",
3970 m_thread_create_bp_sp->GetID());
3971 m_thread_create_bp_sp->SetCallback(
3972 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3973 } else {
3974 if (log)
3975 log->Printf("Failed to create new thread notification breakpoint.");
3976 }
Jason Molendaa3329782014-03-29 18:54:20 +00003977 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003978 }
3979 return m_thread_create_bp_sp.get() != NULL;
Jason Molendaa3329782014-03-29 18:54:20 +00003980}
3981
Kate Stoneb9c1b512016-09-06 20:57:50 +00003982bool ProcessGDBRemote::StopNoticingNewThreads() {
3983 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3984 if (log && log->GetVerbose())
3985 log->Printf("Disabling new thread notification breakpoint.");
3986
3987 if (m_thread_create_bp_sp)
3988 m_thread_create_bp_sp->SetEnabled(false);
3989
3990 return true;
3991}
3992
3993DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3994 if (m_dyld_ap.get() == NULL)
3995 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, NULL));
3996 return m_dyld_ap.get();
3997}
3998
Zachary Turner97206d52017-05-12 04:51:55 +00003999Status ProcessGDBRemote::SendEventData(const char *data) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004000 int return_value;
4001 bool was_supported;
4002
Zachary Turner97206d52017-05-12 04:51:55 +00004003 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004004
4005 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
4006 if (return_value != 0) {
4007 if (!was_supported)
4008 error.SetErrorString("Sending events is not supported for this process.");
4009 else
4010 error.SetErrorStringWithFormat("Error sending event data: %d.",
4011 return_value);
4012 }
4013 return error;
4014}
4015
4016const DataBufferSP ProcessGDBRemote::GetAuxvData() {
4017 DataBufferSP buf;
4018 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
4019 std::string response_string;
4020 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
4021 response_string) ==
4022 GDBRemoteCommunication::PacketResult::Success)
4023 buf.reset(new DataBufferHeap(response_string.c_str(),
4024 response_string.length()));
4025 }
4026 return buf;
Steve Pucci03904ac2014-03-04 23:18:46 +00004027}
4028
Jason Molenda705b1802014-06-13 02:37:02 +00004029StructuredData::ObjectSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004030ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
4031 StructuredData::ObjectSP object_sp;
Jason Molenda705b1802014-06-13 02:37:02 +00004032
Kate Stoneb9c1b512016-09-06 20:57:50 +00004033 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004034 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004035 SystemRuntime *runtime = GetSystemRuntime();
4036 if (runtime) {
4037 runtime->AddThreadExtendedInfoPacketHints(args_dict);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004038 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004039 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004040
Kate Stoneb9c1b512016-09-06 20:57:50 +00004041 StreamString packet;
4042 packet << "jThreadExtendedInfo:";
4043 args_dict->Dump(packet, false);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004044
Kate Stoneb9c1b512016-09-06 20:57:50 +00004045 // FIXME the final character of a JSON dictionary, '}', is the escape
4046 // character in gdb-remote binary mode. lldb currently doesn't escape
4047 // these characters in its packet output -- so we add the quoted version
4048 // of the } character here manually in case we talk to a debugserver which
4049 // un-escapes the characters at packet read time.
4050 packet << (char)(0x7d ^ 0x20);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004051
Kate Stoneb9c1b512016-09-06 20:57:50 +00004052 StringExtractorGDBRemote response;
4053 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004054 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4055 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004056 GDBRemoteCommunication::PacketResult::Success) {
4057 StringExtractorGDBRemote::ResponseType response_type =
4058 response.GetResponseType();
4059 if (response_type == StringExtractorGDBRemote::eResponse) {
4060 if (!response.Empty()) {
4061 object_sp = StructuredData::ParseJSON(response.GetStringRef());
Jason Molenda705b1802014-06-13 02:37:02 +00004062 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004063 }
Jason Molenda705b1802014-06-13 02:37:02 +00004064 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004065 }
4066 return object_sp;
Jason Molenda705b1802014-06-13 02:37:02 +00004067}
4068
Kate Stoneb9c1b512016-09-06 20:57:50 +00004069StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4070 lldb::addr_t image_list_address, lldb::addr_t image_count) {
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004071
Kate Stoneb9c1b512016-09-06 20:57:50 +00004072 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4073 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4074 image_list_address);
4075 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004076
Kate Stoneb9c1b512016-09-06 20:57:50 +00004077 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4078}
4079
4080StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
4081 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4082
4083 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4084
4085 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4086}
4087
4088StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4089 const std::vector<lldb::addr_t> &load_addresses) {
4090 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4091 StructuredData::ArraySP addresses(new StructuredData::Array);
4092
4093 for (auto addr : load_addresses) {
4094 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
4095 addresses->AddItem(addr_sp);
4096 }
4097
4098 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4099
4100 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4101}
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004102
Jason Molenda37397352016-07-22 00:17:55 +00004103StructuredData::ObjectSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004104ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
4105 StructuredData::ObjectSP args_dict) {
4106 StructuredData::ObjectSP object_sp;
Jason Molenda37397352016-07-22 00:17:55 +00004107
Kate Stoneb9c1b512016-09-06 20:57:50 +00004108 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4109 // Scope for the scoped timeout object
Pavel Labath3aa04912016-10-31 17:19:42 +00004110 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
4111 std::chrono::seconds(10));
Jason Molenda37397352016-07-22 00:17:55 +00004112
Kate Stoneb9c1b512016-09-06 20:57:50 +00004113 StreamString packet;
4114 packet << "jGetLoadedDynamicLibrariesInfos:";
4115 args_dict->Dump(packet, false);
Jason Molenda37397352016-07-22 00:17:55 +00004116
Kate Stoneb9c1b512016-09-06 20:57:50 +00004117 // FIXME the final character of a JSON dictionary, '}', is the escape
4118 // character in gdb-remote binary mode. lldb currently doesn't escape
4119 // these characters in its packet output -- so we add the quoted version
4120 // of the } character here manually in case we talk to a debugserver which
4121 // un-escapes the characters at packet read time.
4122 packet << (char)(0x7d ^ 0x20);
4123
4124 StringExtractorGDBRemote response;
4125 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004126 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4127 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004128 GDBRemoteCommunication::PacketResult::Success) {
4129 StringExtractorGDBRemote::ResponseType response_type =
4130 response.GetResponseType();
4131 if (response_type == StringExtractorGDBRemote::eResponse) {
4132 if (!response.Empty()) {
4133 object_sp = StructuredData::ParseJSON(response.GetStringRef());
Jason Molenda37397352016-07-22 00:17:55 +00004134 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004135 }
Jason Molenda37397352016-07-22 00:17:55 +00004136 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004137 }
4138 return object_sp;
Jason Molenda37397352016-07-22 00:17:55 +00004139}
4140
Kate Stoneb9c1b512016-09-06 20:57:50 +00004141StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
4142 StructuredData::ObjectSP object_sp;
4143 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4144
4145 if (m_gdb_comm.GetSharedCacheInfoSupported()) {
4146 StreamString packet;
4147 packet << "jGetSharedCacheInfo:";
4148 args_dict->Dump(packet, false);
4149
4150 // FIXME the final character of a JSON dictionary, '}', is the escape
4151 // character in gdb-remote binary mode. lldb currently doesn't escape
4152 // these characters in its packet output -- so we add the quoted version
4153 // of the } character here manually in case we talk to a debugserver which
4154 // un-escapes the characters at packet read time.
4155 packet << (char)(0x7d ^ 0x20);
4156
4157 StringExtractorGDBRemote response;
4158 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004159 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4160 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004161 GDBRemoteCommunication::PacketResult::Success) {
4162 StringExtractorGDBRemote::ResponseType response_type =
4163 response.GetResponseType();
4164 if (response_type == StringExtractorGDBRemote::eResponse) {
4165 if (!response.Empty()) {
4166 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4167 }
4168 }
4169 }
4170 }
4171 return object_sp;
4172}
4173
Zachary Turner97206d52017-05-12 04:51:55 +00004174Status ProcessGDBRemote::ConfigureStructuredData(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004175 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
4176 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
Todd Fiala75930012016-08-19 04:21:48 +00004177}
Jason Molenda37397352016-07-22 00:17:55 +00004178
Jason Molenda6076bf42014-05-06 04:34:52 +00004179// Establish the largest memory read/write payloads we should use.
4180// If the remote stub has a max packet size, stay under that size.
Ed Maste81b4c5f2016-01-04 01:43:47 +00004181//
4182// If the remote stub's max packet size is crazy large, use a
Jason Molenda6076bf42014-05-06 04:34:52 +00004183// reasonable largeish default.
4184//
4185// If the remote stub doesn't advertise a max packet size, use a
4186// conservative default.
4187
Kate Stoneb9c1b512016-09-06 20:57:50 +00004188void ProcessGDBRemote::GetMaxMemorySize() {
4189 const uint64_t reasonable_largeish_default = 128 * 1024;
4190 const uint64_t conservative_default = 512;
Jason Molenda6076bf42014-05-06 04:34:52 +00004191
Kate Stoneb9c1b512016-09-06 20:57:50 +00004192 if (m_max_memory_size == 0) {
4193 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4194 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4195 // Save the stub's claimed maximum packet size
4196 m_remote_stub_max_memory_size = stub_max_size;
Jason Molenda6076bf42014-05-06 04:34:52 +00004197
Kate Stoneb9c1b512016-09-06 20:57:50 +00004198 // Even if the stub says it can support ginormous packets,
4199 // don't exceed our reasonable largeish default packet size.
4200 if (stub_max_size > reasonable_largeish_default) {
4201 stub_max_size = reasonable_largeish_default;
4202 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004203
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00004204 // Memory packet have other overheads too like Maddr,size:#NN
4205 // Instead of calculating the bytes taken by size and addr every
4206 // time, we take a maximum guess here.
4207 if (stub_max_size > 70)
4208 stub_max_size -= 32 + 32 + 6;
4209 else {
4210 // In unlikely scenario that max packet size is less then 70, we will
4211 // hope that data being written is small enough to fit.
4212 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4213 GDBR_LOG_COMM | GDBR_LOG_MEMORY));
4214 if (log)
4215 log->Warning("Packet size is too small. "
4216 "LLDB may face problems while writing memory");
4217 }
4218
Kate Stoneb9c1b512016-09-06 20:57:50 +00004219 m_max_memory_size = stub_max_size;
4220 } else {
4221 m_max_memory_size = conservative_default;
Jason Molenda6076bf42014-05-06 04:34:52 +00004222 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004223 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004224}
4225
Kate Stoneb9c1b512016-09-06 20:57:50 +00004226void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4227 uint64_t user_specified_max) {
4228 if (user_specified_max != 0) {
4229 GetMaxMemorySize();
Jason Molenda6076bf42014-05-06 04:34:52 +00004230
Kate Stoneb9c1b512016-09-06 20:57:50 +00004231 if (m_remote_stub_max_memory_size != 0) {
4232 if (m_remote_stub_max_memory_size < user_specified_max) {
4233 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4234 // packet size too
4235 // big, go as big
4236 // as the remote stub says we can go.
4237 } else {
4238 m_max_memory_size = user_specified_max; // user's packet size is good
4239 }
4240 } else {
4241 m_max_memory_size =
4242 user_specified_max; // user's packet size is probably fine
Jason Molenda6076bf42014-05-06 04:34:52 +00004243 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004244 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004245}
4246
Kate Stoneb9c1b512016-09-06 20:57:50 +00004247bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4248 const ArchSpec &arch,
4249 ModuleSpec &module_spec) {
4250 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004251
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004252 const ModuleCacheKey key(module_file_spec.GetPath(),
4253 arch.GetTriple().getTriple());
4254 auto cached = m_cached_module_specs.find(key);
4255 if (cached != m_cached_module_specs.end()) {
4256 module_spec = cached->second;
4257 return bool(module_spec);
4258 }
4259
Kate Stoneb9c1b512016-09-06 20:57:50 +00004260 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004261 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004262 log->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4263 __FUNCTION__, module_file_spec.GetPath().c_str(),
4264 arch.GetTriple().getTriple().c_str());
4265 return false;
4266 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004267
Kate Stoneb9c1b512016-09-06 20:57:50 +00004268 if (log) {
4269 StreamString stream;
4270 module_spec.Dump(stream);
4271 log->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4272 __FUNCTION__, module_file_spec.GetPath().c_str(),
Zachary Turnerc1564272016-11-16 21:15:24 +00004273 arch.GetTriple().getTriple().c_str(), stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004274 }
4275
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004276 m_cached_module_specs[key] = module_spec;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004277 return true;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004278}
4279
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004280void ProcessGDBRemote::PrefetchModuleSpecs(
4281 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4282 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4283 if (module_specs) {
4284 for (const FileSpec &spec : module_file_specs)
Pavel Labathcfc7ae62016-09-08 16:58:30 +00004285 m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4286 triple.getTriple())] = ModuleSpec();
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004287 for (const ModuleSpec &spec : *module_specs)
Pavel Labathcfc7ae62016-09-08 16:58:30 +00004288 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4289 triple.getTriple())] = spec;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004290 }
4291}
4292
Kate Stoneb9c1b512016-09-06 20:57:50 +00004293bool ProcessGDBRemote::GetHostOSVersion(uint32_t &major, uint32_t &minor,
4294 uint32_t &update) {
4295 if (m_gdb_comm.GetOSVersion(major, minor, update))
4296 return true;
4297 // We failed to get the host OS version, defer to the base
4298 // implementation to correctly invalidate the arguments.
4299 return Process::GetHostOSVersion(major, minor, update);
Jim Ingham13c30d22015-11-05 22:33:17 +00004300}
4301
Colin Rileyc3c95b22015-04-16 15:51:33 +00004302namespace {
4303
4304typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004305
4306typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004307struct RegisterSetInfo {
4308 ConstString name;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004309};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004310
Greg Claytond04f0ed2015-05-26 18:00:51 +00004311typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004312
Kate Stoneb9c1b512016-09-06 20:57:50 +00004313struct GdbServerTargetInfo {
4314 std::string arch;
4315 std::string osabi;
4316 stringVec includes;
4317 RegisterSetMap reg_set_map;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004318};
Ed Maste81b4c5f2016-01-04 01:43:47 +00004319
Kate Stoneb9c1b512016-09-06 20:57:50 +00004320bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4321 GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4322 uint32_t &cur_reg_num, uint32_t &reg_offset) {
4323 if (!feature_node)
4324 return false;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004325
Kate Stoneb9c1b512016-09-06 20:57:50 +00004326 feature_node.ForEachChildElementWithName(
4327 "reg", [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset,
4328 &abi_sp](const XMLNode &reg_node) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004329 std::string gdb_group;
4330 std::string gdb_type;
4331 ConstString reg_name;
4332 ConstString alt_name;
4333 ConstString set_name;
4334 std::vector<uint32_t> value_regs;
4335 std::vector<uint32_t> invalidate_regs;
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004336 std::vector<uint8_t> dwarf_opcode_bytes;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004337 bool encoding_set = false;
4338 bool format_set = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004339 RegisterInfo reg_info = {
4340 NULL, // Name
4341 NULL, // Alt name
4342 0, // byte size
4343 reg_offset, // offset
4344 eEncodingUint, // encoding
4345 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004346 {
Jason Molendabf67a302015-09-01 05:17:01 +00004347 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004348 LLDB_INVALID_REGNUM, // DWARF reg num
4349 LLDB_INVALID_REGNUM, // generic reg num
Kate Stoneb9c1b512016-09-06 20:57:50 +00004350 cur_reg_num, // process plugin reg num
4351 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004352 },
4353 NULL,
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004354 NULL,
Kate Stoneb9c1b512016-09-06 20:57:50 +00004355 NULL, // Dwarf Expression opcode bytes pointer
4356 0 // Dwarf Expression opcode bytes length
Greg Claytond04f0ed2015-05-26 18:00:51 +00004357 };
Ed Maste81b4c5f2016-01-04 01:43:47 +00004358
Kate Stoneb9c1b512016-09-06 20:57:50 +00004359 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4360 &reg_name, &alt_name, &set_name, &value_regs,
4361 &invalidate_regs, &encoding_set, &format_set,
Zachary Turner3bc714b2017-03-02 00:05:25 +00004362 &reg_info, &reg_offset, &dwarf_opcode_bytes](
Kate Stoneb9c1b512016-09-06 20:57:50 +00004363 const llvm::StringRef &name,
4364 const llvm::StringRef &value) -> bool {
4365 if (name == "name") {
4366 reg_name.SetString(value);
4367 } else if (name == "bitsize") {
4368 reg_info.byte_size =
4369 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4370 } else if (name == "type") {
4371 gdb_type = value.str();
4372 } else if (name == "group") {
4373 gdb_group = value.str();
4374 } else if (name == "regnum") {
4375 const uint32_t regnum =
4376 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4377 if (regnum != LLDB_INVALID_REGNUM) {
4378 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004379 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004380 } else if (name == "offset") {
4381 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4382 } else if (name == "altname") {
4383 alt_name.SetString(value);
4384 } else if (name == "encoding") {
4385 encoding_set = true;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00004386 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004387 } else if (name == "format") {
4388 format_set = true;
4389 Format format = eFormatInvalid;
4390 if (Args::StringToFormat(value.data(), format, NULL).Success())
4391 reg_info.format = format;
4392 else if (value == "vector-sint8")
4393 reg_info.format = eFormatVectorOfSInt8;
4394 else if (value == "vector-uint8")
4395 reg_info.format = eFormatVectorOfUInt8;
4396 else if (value == "vector-sint16")
4397 reg_info.format = eFormatVectorOfSInt16;
4398 else if (value == "vector-uint16")
4399 reg_info.format = eFormatVectorOfUInt16;
4400 else if (value == "vector-sint32")
4401 reg_info.format = eFormatVectorOfSInt32;
4402 else if (value == "vector-uint32")
4403 reg_info.format = eFormatVectorOfUInt32;
4404 else if (value == "vector-float32")
4405 reg_info.format = eFormatVectorOfFloat32;
Valentina Giusticda0ae42016-09-08 14:16:45 +00004406 else if (value == "vector-uint64")
4407 reg_info.format = eFormatVectorOfUInt64;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004408 else if (value == "vector-uint128")
4409 reg_info.format = eFormatVectorOfUInt128;
4410 } else if (name == "group_id") {
4411 const uint32_t set_id =
4412 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4413 RegisterSetMap::const_iterator pos =
4414 target_info.reg_set_map.find(set_id);
4415 if (pos != target_info.reg_set_map.end())
4416 set_name = pos->second.name;
4417 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4418 reg_info.kinds[eRegisterKindEHFrame] =
4419 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4420 } else if (name == "dwarf_regnum") {
4421 reg_info.kinds[eRegisterKindDWARF] =
4422 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4423 } else if (name == "generic") {
4424 reg_info.kinds[eRegisterKindGeneric] =
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00004425 Args::StringToGenericRegister(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004426 } else if (name == "value_regnums") {
4427 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4428 } else if (name == "invalidate_regnums") {
4429 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4430 } else if (name == "dynamic_size_dwarf_expr_bytes") {
4431 StringExtractor opcode_extractor;
4432 std::string opcode_string = value.str();
4433 size_t dwarf_opcode_len = opcode_string.length() / 2;
4434 assert(dwarf_opcode_len > 0);
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004435
Kate Stoneb9c1b512016-09-06 20:57:50 +00004436 dwarf_opcode_bytes.resize(dwarf_opcode_len);
4437 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4438 opcode_extractor.GetStringRef().swap(opcode_string);
4439 uint32_t ret_val =
4440 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4441 assert(dwarf_opcode_len == ret_val);
Hafiz Abid Qadeer05008ca2017-01-19 15:11:01 +00004442 UNUSED_IF_ASSERT_DISABLED(ret_val);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004443 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4444 } else {
4445 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4446 }
4447 return true; // Keep iterating through all attributes
Greg Claytond04f0ed2015-05-26 18:00:51 +00004448 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004449
Kate Stoneb9c1b512016-09-06 20:57:50 +00004450 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4451 if (gdb_type.find("int") == 0) {
4452 reg_info.format = eFormatHex;
4453 reg_info.encoding = eEncodingUint;
4454 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4455 reg_info.format = eFormatAddressInfo;
4456 reg_info.encoding = eEncodingUint;
4457 } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4458 reg_info.format = eFormatFloat;
4459 reg_info.encoding = eEncodingIEEE754;
4460 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004461 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004462
Kate Stoneb9c1b512016-09-06 20:57:50 +00004463 // Only update the register set name if we didn't get a "reg_set"
4464 // attribute.
Greg Claytond04f0ed2015-05-26 18:00:51 +00004465 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4466 if (!set_name && !gdb_group.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004467 set_name.SetCString(gdb_group.c_str());
Ed Maste81b4c5f2016-01-04 01:43:47 +00004468
Greg Claytond04f0ed2015-05-26 18:00:51 +00004469 reg_info.byte_offset = reg_offset;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004470 assert(reg_info.byte_size != 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004471 reg_offset += reg_info.byte_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004472 if (!value_regs.empty()) {
4473 value_regs.push_back(LLDB_INVALID_REGNUM);
4474 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004475 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004476 if (!invalidate_regs.empty()) {
4477 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4478 reg_info.invalidate_regs = invalidate_regs.data();
Greg Claytond04f0ed2015-05-26 18:00:51 +00004479 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004480
Jason Molenda63bd0db2015-09-15 23:20:34 +00004481 ++cur_reg_num;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004482 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004483 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004484
Greg Claytond04f0ed2015-05-26 18:00:51 +00004485 return true; // Keep iterating through all "reg" elements
Kate Stoneb9c1b512016-09-06 20:57:50 +00004486 });
4487 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004488}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004489
Eugene Zelenko0722f082015-10-24 01:28:05 +00004490} // namespace {}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004491
Colin Rileyc3c95b22015-04-16 15:51:33 +00004492// query the target of gdb-remote for extended target information
4493// return: 'true' on success
4494// 'false' on failure
Kate Stoneb9c1b512016-09-06 20:57:50 +00004495bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4496 // Make sure LLDB has an XML parser it can use first
4497 if (!XMLDocument::XMLEnabled())
4498 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004499
Kate Stoneb9c1b512016-09-06 20:57:50 +00004500 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004501
Kate Stoneb9c1b512016-09-06 20:57:50 +00004502 GDBRemoteCommunicationClient &comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004503
Kate Stoneb9c1b512016-09-06 20:57:50 +00004504 // check that we have extended feature read support
4505 if (!comm.GetQXferFeaturesReadSupported())
4506 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004507
Kate Stoneb9c1b512016-09-06 20:57:50 +00004508 // request the target xml file
4509 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004510 lldb_private::Status lldberr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004511 if (!comm.ReadExtFeature(ConstString("features"), ConstString("target.xml"),
4512 raw, lldberr)) {
4513 return false;
4514 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004515
Kate Stoneb9c1b512016-09-06 20:57:50 +00004516 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004517
Kate Stoneb9c1b512016-09-06 20:57:50 +00004518 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml")) {
4519 GdbServerTargetInfo target_info;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004520
Kate Stoneb9c1b512016-09-06 20:57:50 +00004521 XMLNode target_node = xml_document.GetRootElement("target");
4522 if (target_node) {
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004523 std::vector<XMLNode> feature_nodes;
4524 target_node.ForEachChildElement([&target_info, &feature_nodes](
Kate Stoneb9c1b512016-09-06 20:57:50 +00004525 const XMLNode &node) -> bool {
4526 llvm::StringRef name = node.GetName();
4527 if (name == "architecture") {
4528 node.GetElementText(target_info.arch);
4529 } else if (name == "osabi") {
4530 node.GetElementText(target_info.osabi);
4531 } else if (name == "xi:include" || name == "include") {
4532 llvm::StringRef href = node.GetAttributeValue("href");
4533 if (!href.empty())
4534 target_info.includes.push_back(href.str());
4535 } else if (name == "feature") {
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004536 feature_nodes.push_back(node);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004537 } else if (name == "groups") {
4538 node.ForEachChildElementWithName(
4539 "group", [&target_info](const XMLNode &node) -> bool {
4540 uint32_t set_id = UINT32_MAX;
4541 RegisterSetInfo set_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004542
Kate Stoneb9c1b512016-09-06 20:57:50 +00004543 node.ForEachAttribute(
4544 [&set_id, &set_info](const llvm::StringRef &name,
4545 const llvm::StringRef &value) -> bool {
4546 if (name == "id")
4547 set_id = StringConvert::ToUInt32(value.data(),
4548 UINT32_MAX, 0);
4549 if (name == "name")
4550 set_info.name = ConstString(value);
4551 return true; // Keep iterating through all attributes
Greg Claytond04f0ed2015-05-26 18:00:51 +00004552 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004553
Kate Stoneb9c1b512016-09-06 20:57:50 +00004554 if (set_id != UINT32_MAX)
4555 target_info.reg_set_map[set_id] = set_info;
4556 return true; // Keep iterating through all "group" elements
4557 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004558 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004559 return true; // Keep iterating through all children of the target_node
4560 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004561
Jason Molendac4dd04c2018-01-12 01:16:13 +00004562 // If the target.xml includes an architecture entry like
4563 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4564 // <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board)
4565 // use that if we don't have anything better.
4566 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4567 if (target_info.arch == "i386:x86-64")
4568 {
4569 // We don't have any information about vendor or OS.
4570 arch_to_use.SetTriple("x86_64--");
4571 GetTarget().MergeArchitecture(arch_to_use);
4572 }
4573 }
4574
Kate Stoneb9c1b512016-09-06 20:57:50 +00004575 // Initialize these outside of ParseRegisters, since they should not be
4576 // reset inside each include feature
4577 uint32_t cur_reg_num = 0;
4578 uint32_t reg_offset = 0;
4579
4580 // Don't use Process::GetABI, this code gets called from DidAttach, and in
4581 // that context we haven't
4582 // set the Target's architecture yet, so the ABI is also potentially
4583 // incorrect.
Jason Molenda43294c92017-06-29 02:57:03 +00004584 ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use);
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004585 for (auto &feature_node : feature_nodes) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004586 ParseRegisters(feature_node, target_info, this->m_register_info,
4587 abi_to_use_sp, cur_reg_num, reg_offset);
4588 }
4589
4590 for (const auto &include : target_info.includes) {
4591 // request register file
4592 std::string xml_data;
4593 if (!comm.ReadExtFeature(ConstString("features"), ConstString(include),
4594 xml_data, lldberr))
4595 continue;
4596
4597 XMLDocument include_xml_document;
4598 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(),
4599 include.c_str());
4600 XMLNode include_feature_node =
4601 include_xml_document.GetRootElement("feature");
4602 if (include_feature_node) {
4603 ParseRegisters(include_feature_node, target_info,
4604 this->m_register_info, abi_to_use_sp, cur_reg_num,
4605 reg_offset);
4606 }
4607 }
4608 this->m_register_info.Finalize(arch_to_use);
4609 }
4610 }
4611
4612 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004613}
4614
Zachary Turner97206d52017-05-12 04:51:55 +00004615Status ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004616 // Make sure LLDB has an XML parser it can use first
4617 if (!XMLDocument::XMLEnabled())
Zachary Turner97206d52017-05-12 04:51:55 +00004618 return Status(0, ErrorType::eErrorTypeGeneric);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004619
Kate Stoneb9c1b512016-09-06 20:57:50 +00004620 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
4621 if (log)
4622 log->Printf("ProcessGDBRemote::%s", __FUNCTION__);
4623
4624 GDBRemoteCommunicationClient &comm = m_gdb_comm;
4625
4626 // check that we have extended feature read support
4627 if (comm.GetQXferLibrariesSVR4ReadSupported()) {
4628 list.clear();
4629
4630 // request the loaded library list
4631 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004632 lldb_private::Status lldberr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004633
4634 if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4635 raw, lldberr))
Zachary Turner97206d52017-05-12 04:51:55 +00004636 return Status(0, ErrorType::eErrorTypeGeneric);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004637
4638 // parse the xml file in memory
Aidan Doddsc0c83852015-05-08 09:36:31 +00004639 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004640 log->Printf("parsing: %s", raw.c_str());
4641 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004642
Kate Stoneb9c1b512016-09-06 20:57:50 +00004643 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Zachary Turner97206d52017-05-12 04:51:55 +00004644 return Status(0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004645
Kate Stoneb9c1b512016-09-06 20:57:50 +00004646 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4647 if (!root_element)
Zachary Turner97206d52017-05-12 04:51:55 +00004648 return Status();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004649
Kate Stoneb9c1b512016-09-06 20:57:50 +00004650 // main link map structure
4651 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4652 if (!main_lm.empty()) {
4653 list.m_link_map =
4654 StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4655 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004656
Kate Stoneb9c1b512016-09-06 20:57:50 +00004657 root_element.ForEachChildElementWithName(
4658 "library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004659
Kate Stoneb9c1b512016-09-06 20:57:50 +00004660 LoadedModuleInfoList::LoadedModuleInfo module;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004661
Kate Stoneb9c1b512016-09-06 20:57:50 +00004662 library.ForEachAttribute(
Zachary Turner3bc714b2017-03-02 00:05:25 +00004663 [&module](const llvm::StringRef &name,
4664 const llvm::StringRef &value) -> bool {
Ed Maste81b4c5f2016-01-04 01:43:47 +00004665
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004666 if (name == "name")
Kate Stoneb9c1b512016-09-06 20:57:50 +00004667 module.set_name(value.str());
4668 else if (name == "lm") {
4669 // the address of the link_map struct.
4670 module.set_link_map(StringConvert::ToUInt64(
4671 value.data(), LLDB_INVALID_ADDRESS, 0));
4672 } else if (name == "l_addr") {
4673 // the displacement as read from the field 'l_addr' of the
4674 // link_map struct.
4675 module.set_base(StringConvert::ToUInt64(
4676 value.data(), LLDB_INVALID_ADDRESS, 0));
4677 // base address is always a displacement, not an absolute
4678 // value.
4679 module.set_base_is_offset(true);
4680 } else if (name == "l_ld") {
4681 // the memory address of the libraries PT_DYAMIC section.
4682 module.set_dynamic(StringConvert::ToUInt64(
4683 value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004684 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004685
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004686 return true; // Keep iterating over all properties of "library"
Kate Stoneb9c1b512016-09-06 20:57:50 +00004687 });
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004688
Kate Stoneb9c1b512016-09-06 20:57:50 +00004689 if (log) {
4690 std::string name;
4691 lldb::addr_t lm = 0, base = 0, ld = 0;
4692 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004693
Kate Stoneb9c1b512016-09-06 20:57:50 +00004694 module.get_name(name);
4695 module.get_link_map(lm);
4696 module.get_base(base);
4697 module.get_base_is_offset(base_is_offset);
4698 module.get_dynamic(ld);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004699
Kate Stoneb9c1b512016-09-06 20:57:50 +00004700 log->Printf("found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4701 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4702 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4703 name.c_str());
4704 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004705
Kate Stoneb9c1b512016-09-06 20:57:50 +00004706 list.add(module);
4707 return true; // Keep iterating over all "library" elements in the root
4708 // node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004709 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004710
Kate Stoneb9c1b512016-09-06 20:57:50 +00004711 if (log)
4712 log->Printf("found %" PRId32 " modules in total",
4713 (int)list.m_list.size());
4714 } else if (comm.GetQXferLibrariesReadSupported()) {
4715 list.clear();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004716
Kate Stoneb9c1b512016-09-06 20:57:50 +00004717 // request the loaded library list
4718 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004719 lldb_private::Status lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004720
Kate Stoneb9c1b512016-09-06 20:57:50 +00004721 if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4722 lldberr))
Zachary Turner97206d52017-05-12 04:51:55 +00004723 return Status(0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004724
Kate Stoneb9c1b512016-09-06 20:57:50 +00004725 if (log)
4726 log->Printf("parsing: %s", raw.c_str());
4727 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004728
Kate Stoneb9c1b512016-09-06 20:57:50 +00004729 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Zachary Turner97206d52017-05-12 04:51:55 +00004730 return Status(0, ErrorType::eErrorTypeGeneric);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004731
Kate Stoneb9c1b512016-09-06 20:57:50 +00004732 XMLNode root_element = doc.GetRootElement("library-list");
4733 if (!root_element)
Zachary Turner97206d52017-05-12 04:51:55 +00004734 return Status();
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004735
Kate Stoneb9c1b512016-09-06 20:57:50 +00004736 root_element.ForEachChildElementWithName(
4737 "library", [log, &list](const XMLNode &library) -> bool {
4738 LoadedModuleInfoList::LoadedModuleInfo module;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004739
Kate Stoneb9c1b512016-09-06 20:57:50 +00004740 llvm::StringRef name = library.GetAttributeValue("name");
4741 module.set_name(name.str());
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004742
Kate Stoneb9c1b512016-09-06 20:57:50 +00004743 // The base address of a given library will be the address of its
4744 // first section. Most remotes send only one section for Windows
4745 // targets for example.
4746 const XMLNode &section =
4747 library.FindFirstChildElementWithName("section");
4748 llvm::StringRef address = section.GetAttributeValue("address");
4749 module.set_base(
4750 StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4751 // These addresses are absolute values.
4752 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004753
Kate Stoneb9c1b512016-09-06 20:57:50 +00004754 if (log) {
4755 std::string name;
4756 lldb::addr_t base = 0;
4757 bool base_is_offset;
4758 module.get_name(name);
4759 module.get_base(base);
4760 module.get_base_is_offset(base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004761
Kate Stoneb9c1b512016-09-06 20:57:50 +00004762 log->Printf("found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4763 (base_is_offset ? "offset" : "absolute"), name.c_str());
4764 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004765
Kate Stoneb9c1b512016-09-06 20:57:50 +00004766 list.add(module);
4767 return true; // Keep iterating over all "library" elements in the root
4768 // node
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004769 });
4770
Kate Stoneb9c1b512016-09-06 20:57:50 +00004771 if (log)
4772 log->Printf("found %" PRId32 " modules in total",
4773 (int)list.m_list.size());
4774 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00004775 return Status(0, ErrorType::eErrorTypeGeneric);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004776 }
4777
Zachary Turner97206d52017-05-12 04:51:55 +00004778 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004779}
4780
4781lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4782 lldb::addr_t link_map,
4783 lldb::addr_t base_addr,
4784 bool value_is_offset) {
4785 DynamicLoader *loader = GetDynamicLoader();
4786 if (!loader)
4787 return nullptr;
4788
4789 return loader->LoadModuleAtAddress(file, link_map, base_addr,
4790 value_is_offset);
4791}
4792
4793size_t ProcessGDBRemote::LoadModules(LoadedModuleInfoList &module_list) {
4794 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4795
4796 // request a list of loaded libraries from GDBServer
4797 if (GetLoadedModuleList(module_list).Fail())
4798 return 0;
4799
4800 // get a list of all the modules
4801 ModuleList new_modules;
4802
4803 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list.m_list) {
4804 std::string mod_name;
4805 lldb::addr_t mod_base;
4806 lldb::addr_t link_map;
4807 bool mod_base_is_offset;
4808
4809 bool valid = true;
4810 valid &= modInfo.get_name(mod_name);
4811 valid &= modInfo.get_base(mod_base);
4812 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4813 if (!valid)
4814 continue;
4815
4816 if (!modInfo.get_link_map(link_map))
4817 link_map = LLDB_INVALID_ADDRESS;
4818
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00004819 FileSpec file(mod_name, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004820 lldb::ModuleSP module_sp =
4821 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4822
4823 if (module_sp.get())
4824 new_modules.Append(module_sp);
4825 }
4826
4827 if (new_modules.GetSize() > 0) {
4828 ModuleList removed_modules;
4829 Target &target = GetTarget();
4830 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4831
4832 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4833 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4834
4835 bool found = false;
4836 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4837 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4838 found = true;
4839 }
4840
4841 // The main executable will never be included in libraries-svr4, don't
4842 // remove it
4843 if (!found &&
4844 loaded_module.get() != target.GetExecutableModulePointer()) {
4845 removed_modules.Append(loaded_module);
4846 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004847 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004848
Kate Stoneb9c1b512016-09-06 20:57:50 +00004849 loaded_modules.Remove(removed_modules);
4850 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4851
4852 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4853 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4854 if (!obj)
4855 return true;
4856
4857 if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4858 return true;
4859
4860 lldb::ModuleSP module_copy_sp = module_sp;
4861 target.SetExecutableModule(module_copy_sp, false);
4862 return false;
4863 });
4864
4865 loaded_modules.AppendIfNeeded(new_modules);
4866 m_process->GetTarget().ModulesDidLoad(new_modules);
4867 }
4868
4869 return new_modules.GetSize();
4870}
4871
4872size_t ProcessGDBRemote::LoadModules() {
4873 LoadedModuleInfoList module_list;
4874 return LoadModules(module_list);
4875}
4876
Zachary Turner97206d52017-05-12 04:51:55 +00004877Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4878 bool &is_loaded,
4879 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004880 is_loaded = false;
4881 load_addr = LLDB_INVALID_ADDRESS;
4882
4883 std::string file_path = file.GetPath(false);
4884 if (file_path.empty())
Zachary Turner97206d52017-05-12 04:51:55 +00004885 return Status("Empty file name specified");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004886
4887 StreamString packet;
4888 packet.PutCString("qFileLoadAddress:");
4889 packet.PutCStringAsRawHex8(file_path.c_str());
4890
4891 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004892 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4893 false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00004894 GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00004895 return Status("Sending qFileLoadAddress packet failed");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004896
4897 if (response.IsErrorResponse()) {
4898 if (response.GetError() == 1) {
4899 // The file is not loaded into the inferior
4900 is_loaded = false;
4901 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00004902 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004903 }
4904
Zachary Turner97206d52017-05-12 04:51:55 +00004905 return Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004906 "Fetching file load address from remote server returned an error");
4907 }
4908
4909 if (response.IsNormalResponse()) {
4910 is_loaded = true;
4911 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
Zachary Turner97206d52017-05-12 04:51:55 +00004912 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004913 }
4914
Zachary Turner97206d52017-05-12 04:51:55 +00004915 return Status(
4916 "Unknown error happened during sending the load address packet");
Aidan Doddsc0c83852015-05-08 09:36:31 +00004917}
4918
Kate Stoneb9c1b512016-09-06 20:57:50 +00004919void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4920 // We must call the lldb_private::Process::ModulesDidLoad () first before we
4921 // do anything
4922 Process::ModulesDidLoad(module_list);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004923
Kate Stoneb9c1b512016-09-06 20:57:50 +00004924 // After loading shared libraries, we can ask our remote GDB server if
4925 // it needs any symbols.
4926 m_gdb_comm.ServeSymbolLookups(this);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004927}
4928
Kate Stoneb9c1b512016-09-06 20:57:50 +00004929void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4930 AppendSTDOUT(out.data(), out.size());
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004931}
4932
4933static const char *end_delimiter = "--end--;";
4934static const int end_delimiter_len = 8;
4935
Kate Stoneb9c1b512016-09-06 20:57:50 +00004936void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4937 std::string input = data.str(); // '1' to move beyond 'A'
4938 if (m_partial_profile_data.length() > 0) {
4939 m_partial_profile_data.append(input);
4940 input = m_partial_profile_data;
4941 m_partial_profile_data.clear();
4942 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004943
Kate Stoneb9c1b512016-09-06 20:57:50 +00004944 size_t found, pos = 0, len = input.length();
4945 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4946 StringExtractorGDBRemote profileDataExtractor(
4947 input.substr(pos, found).c_str());
4948 std::string profile_data =
4949 HarmonizeThreadIdsForProfileData(profileDataExtractor);
4950 BroadcastAsyncProfileData(profile_data);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004951
Kate Stoneb9c1b512016-09-06 20:57:50 +00004952 pos = found + end_delimiter_len;
4953 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004954
Kate Stoneb9c1b512016-09-06 20:57:50 +00004955 if (pos < len) {
4956 // Last incomplete chunk.
4957 m_partial_profile_data = input.substr(pos);
4958 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004959}
4960
Kate Stoneb9c1b512016-09-06 20:57:50 +00004961std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4962 StringExtractorGDBRemote &profileDataExtractor) {
4963 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4964 std::string output;
4965 llvm::raw_string_ostream output_stream(output);
4966 llvm::StringRef name, value;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004967
Kate Stoneb9c1b512016-09-06 20:57:50 +00004968 // Going to assuming thread_used_usec comes first, else bail out.
4969 while (profileDataExtractor.GetNameColonValue(name, value)) {
4970 if (name.compare("thread_used_id") == 0) {
4971 StringExtractor threadIDHexExtractor(value);
4972 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004973
Kate Stoneb9c1b512016-09-06 20:57:50 +00004974 bool has_used_usec = false;
4975 uint32_t curr_used_usec = 0;
4976 llvm::StringRef usec_name, usec_value;
4977 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4978 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4979 if (usec_name.equals("thread_used_usec")) {
4980 has_used_usec = true;
4981 usec_value.getAsInteger(0, curr_used_usec);
4982 } else {
4983 // We didn't find what we want, it is probably
4984 // an older version. Bail out.
4985 profileDataExtractor.SetFilePos(input_file_pos);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004986 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004987 }
4988
4989 if (has_used_usec) {
4990 uint32_t prev_used_usec = 0;
4991 std::map<uint64_t, uint32_t>::iterator iterator =
4992 m_thread_id_to_used_usec_map.find(thread_id);
4993 if (iterator != m_thread_id_to_used_usec_map.end()) {
4994 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004995 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004996
4997 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4998 // A good first time record is one that runs for at least 0.25 sec
4999 bool good_first_time =
5000 (prev_used_usec == 0) && (real_used_usec > 250000);
5001 bool good_subsequent_time =
5002 (prev_used_usec > 0) &&
5003 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
5004
5005 if (good_first_time || good_subsequent_time) {
5006 // We try to avoid doing too many index id reservation,
5007 // resulting in fast increase of index ids.
5008
5009 output_stream << name << ":";
5010 int32_t index_id = AssignIndexIDToThread(thread_id);
5011 output_stream << index_id << ";";
5012
5013 output_stream << usec_name << ":" << usec_value << ";";
5014 } else {
5015 // Skip past 'thread_used_name'.
5016 llvm::StringRef local_name, local_value;
5017 profileDataExtractor.GetNameColonValue(local_name, local_value);
5018 }
5019
5020 // Store current time as previous time so that they can be compared
5021 // later.
5022 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
5023 } else {
5024 // Bail out and use old string.
5025 output_stream << name << ":" << value << ";";
5026 }
5027 } else {
5028 output_stream << name << ":" << value << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005029 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005030 }
5031 output_stream << end_delimiter;
5032 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005033
Kate Stoneb9c1b512016-09-06 20:57:50 +00005034 return output_stream.str();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005035}
5036
Kate Stoneb9c1b512016-09-06 20:57:50 +00005037void ProcessGDBRemote::HandleStopReply() {
5038 if (GetStopID() != 0)
5039 return;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005040
Kate Stoneb9c1b512016-09-06 20:57:50 +00005041 if (GetID() == LLDB_INVALID_PROCESS_ID) {
5042 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5043 if (pid != LLDB_INVALID_PROCESS_ID)
5044 SetID(pid);
5045 }
5046 BuildDynamicRegisterInfo(true);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005047}
Eugene Zelenko0722f082015-10-24 01:28:05 +00005048
Todd Fialafcdb1af2016-09-10 00:06:29 +00005049static const char *const s_async_json_packet_prefix = "JSON-async:";
5050
5051static StructuredData::ObjectSP
5052ParseStructuredDataPacket(llvm::StringRef packet) {
5053 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
5054
5055 if (!packet.consume_front(s_async_json_packet_prefix)) {
5056 if (log) {
5057 log->Printf(
5058 "GDBRemoteCommmunicationClientBase::%s() received $J packet "
5059 "but was not a StructuredData packet: packet starts with "
5060 "%s",
5061 __FUNCTION__,
5062 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
5063 }
5064 return StructuredData::ObjectSP();
5065 }
5066
5067 // This is an asynchronous JSON packet, destined for a
5068 // StructuredDataPlugin.
5069 StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);
5070 if (log) {
5071 if (json_sp) {
5072 StreamString json_str;
5073 json_sp->Dump(json_str);
5074 json_str.Flush();
5075 log->Printf("ProcessGDBRemote::%s() "
5076 "received Async StructuredData packet: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00005077 __FUNCTION__, json_str.GetData());
Todd Fialafcdb1af2016-09-10 00:06:29 +00005078 } else {
5079 log->Printf("ProcessGDBRemote::%s"
5080 "() received StructuredData packet:"
5081 " parse failure",
5082 __FUNCTION__);
5083 }
5084 }
5085 return json_sp;
5086}
5087
5088void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
5089 auto structured_data_sp = ParseStructuredDataPacket(data);
5090 if (structured_data_sp)
5091 RouteAsyncStructuredData(structured_data_sp);
Todd Fiala75930012016-08-19 04:21:48 +00005092}
5093
Kate Stoneb9c1b512016-09-06 20:57:50 +00005094class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
Greg Claytone034a042015-05-21 20:52:06 +00005095public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005096 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
5097 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
5098 "Tests packet speeds of various sizes to determine "
5099 "the performance characteristics of the GDB remote "
5100 "connection. ",
5101 NULL),
5102 m_option_group(),
5103 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
5104 "The number of packets to send of each varying size "
5105 "(default is 1000).",
5106 1000),
5107 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
5108 "The maximum number of bytes to send in a packet. Sizes "
5109 "increase in powers of 2 while the size is less than or "
5110 "equal to this option value. (default 1024).",
5111 1024),
5112 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
5113 "The maximum number of bytes to receive in a packet. Sizes "
5114 "increase in powers of 2 while the size is less than or "
5115 "equal to this option value. (default 1024).",
5116 1024),
5117 m_json(LLDB_OPT_SET_1, false, "json", 'j',
5118 "Print the output as JSON data for easy parsing.", false, true) {
5119 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5120 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5121 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5122 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5123 m_option_group.Finalize();
5124 }
Greg Claytone034a042015-05-21 20:52:06 +00005125
Kate Stoneb9c1b512016-09-06 20:57:50 +00005126 ~CommandObjectProcessGDBRemoteSpeedTest() {}
Eugene Zelenko0722f082015-10-24 01:28:05 +00005127
Kate Stoneb9c1b512016-09-06 20:57:50 +00005128 Options *GetOptions() override { return &m_option_group; }
Greg Claytone034a042015-05-21 20:52:06 +00005129
Kate Stoneb9c1b512016-09-06 20:57:50 +00005130 bool DoExecute(Args &command, CommandReturnObject &result) override {
5131 const size_t argc = command.GetArgumentCount();
5132 if (argc == 0) {
5133 ProcessGDBRemote *process =
5134 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5135 .GetProcessPtr();
5136 if (process) {
5137 StreamSP output_stream_sp(
5138 m_interpreter.GetDebugger().GetAsyncOutputStream());
5139 result.SetImmediateOutputStream(output_stream_sp);
Greg Claytone034a042015-05-21 20:52:06 +00005140
Kate Stoneb9c1b512016-09-06 20:57:50 +00005141 const uint32_t num_packets =
5142 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5143 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5144 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5145 const bool json = m_json.GetOptionValue().GetCurrentValue();
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00005146 const uint64_t k_recv_amount =
5147 4 * 1024 * 1024; // Receive amount in bytes
5148 process->GetGDBRemote().TestPacketSpeed(
5149 num_packets, max_send, max_recv, k_recv_amount, json,
5150 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005151 result.SetStatus(eReturnStatusSuccessFinishResult);
5152 return true;
5153 }
5154 } else {
5155 result.AppendErrorWithFormat("'%s' takes no arguments",
5156 m_cmd_name.c_str());
Greg Claytone034a042015-05-21 20:52:06 +00005157 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005158 result.SetStatus(eReturnStatusFailed);
5159 return false;
5160 }
5161
Greg Claytone034a042015-05-21 20:52:06 +00005162protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005163 OptionGroupOptions m_option_group;
5164 OptionGroupUInt64 m_num_packets;
5165 OptionGroupUInt64 m_max_send;
5166 OptionGroupUInt64 m_max_recv;
5167 OptionGroupBoolean m_json;
Greg Claytone034a042015-05-21 20:52:06 +00005168};
5169
Kate Stoneb9c1b512016-09-06 20:57:50 +00005170class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005171private:
Greg Clayton998255b2012-10-13 02:07:45 +00005172public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005173 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5174 : CommandObjectParsed(interpreter, "process plugin packet history",
5175 "Dumps the packet history buffer. ", NULL) {}
5176
5177 ~CommandObjectProcessGDBRemotePacketHistory() {}
5178
5179 bool DoExecute(Args &command, CommandReturnObject &result) override {
5180 const size_t argc = command.GetArgumentCount();
5181 if (argc == 0) {
5182 ProcessGDBRemote *process =
5183 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5184 .GetProcessPtr();
5185 if (process) {
5186 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5187 result.SetStatus(eReturnStatusSuccessFinishResult);
5188 return true;
5189 }
5190 } else {
5191 result.AppendErrorWithFormat("'%s' takes no arguments",
5192 m_cmd_name.c_str());
5193 }
5194 result.SetStatus(eReturnStatusFailed);
5195 return false;
5196 }
5197};
5198
5199class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5200private:
5201public:
5202 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5203 : CommandObjectParsed(
5204 interpreter, "process plugin packet xfer-size",
5205 "Maximum size that lldb will try to read/write one one chunk.",
5206 NULL) {}
5207
5208 ~CommandObjectProcessGDBRemotePacketXferSize() {}
5209
5210 bool DoExecute(Args &command, CommandReturnObject &result) override {
5211 const size_t argc = command.GetArgumentCount();
5212 if (argc == 0) {
5213 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5214 "amount to be transferred when "
5215 "reading/writing",
5216 m_cmd_name.c_str());
5217 result.SetStatus(eReturnStatusFailed);
5218 return false;
Greg Clayton998255b2012-10-13 02:07:45 +00005219 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005220
Kate Stoneb9c1b512016-09-06 20:57:50 +00005221 ProcessGDBRemote *process =
5222 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5223 if (process) {
5224 const char *packet_size = command.GetArgumentAtIndex(0);
5225 errno = 0;
5226 uint64_t user_specified_max = strtoul(packet_size, NULL, 10);
5227 if (errno == 0 && user_specified_max != 0) {
5228 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5229 result.SetStatus(eReturnStatusSuccessFinishResult);
5230 return true;
5231 }
5232 }
5233 result.SetStatus(eReturnStatusFailed);
5234 return false;
5235 }
5236};
5237
5238class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5239private:
5240public:
5241 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5242 : CommandObjectParsed(interpreter, "process plugin packet send",
5243 "Send a custom packet through the GDB remote "
5244 "protocol and print the answer. "
5245 "The packet header and footer will automatically "
5246 "be added to the packet prior to sending and "
5247 "stripped from the result.",
5248 NULL) {}
5249
5250 ~CommandObjectProcessGDBRemotePacketSend() {}
5251
5252 bool DoExecute(Args &command, CommandReturnObject &result) override {
5253 const size_t argc = command.GetArgumentCount();
5254 if (argc == 0) {
5255 result.AppendErrorWithFormat(
5256 "'%s' takes a one or more packet content arguments",
5257 m_cmd_name.c_str());
5258 result.SetStatus(eReturnStatusFailed);
5259 return false;
Eugene Zelenko0722f082015-10-24 01:28:05 +00005260 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005261
Kate Stoneb9c1b512016-09-06 20:57:50 +00005262 ProcessGDBRemote *process =
5263 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5264 if (process) {
5265 for (size_t i = 0; i < argc; ++i) {
5266 const char *packet_cstr = command.GetArgumentAtIndex(0);
5267 bool send_async = true;
5268 StringExtractorGDBRemote response;
5269 process->GetGDBRemote().SendPacketAndWaitForResponse(
5270 packet_cstr, response, send_async);
5271 result.SetStatus(eReturnStatusSuccessFinishResult);
5272 Stream &output_strm = result.GetOutputStream();
5273 output_strm.Printf(" packet: %s\n", packet_cstr);
5274 std::string &response_str = response.GetStringRef();
5275
5276 if (strstr(packet_cstr, "qGetProfileData") != NULL) {
5277 response_str = process->HarmonizeThreadIdsForProfileData(response);
Greg Clayton02686b82012-10-15 22:42:16 +00005278 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005279
5280 if (response_str.empty())
5281 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
Greg Clayton02686b82012-10-15 22:42:16 +00005282 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00005283 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5284 }
Greg Clayton02686b82012-10-15 22:42:16 +00005285 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005286 return true;
5287 }
Greg Clayton02686b82012-10-15 22:42:16 +00005288};
5289
Kate Stoneb9c1b512016-09-06 20:57:50 +00005290class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005291private:
Jason Molenda6076bf42014-05-06 04:34:52 +00005292public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005293 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5294 : CommandObjectRaw(interpreter, "process plugin packet monitor",
5295 "Send a qRcmd packet through the GDB remote protocol "
5296 "and print the response."
5297 "The argument passed to this command will be hex "
5298 "encoded into a valid 'qRcmd' packet, sent and the "
Zachary Turnera4496982016-10-05 21:14:38 +00005299 "response will be printed.") {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005300
5301 ~CommandObjectProcessGDBRemotePacketMonitor() {}
5302
5303 bool DoExecute(const char *command, CommandReturnObject &result) override {
5304 if (command == NULL || command[0] == '\0') {
5305 result.AppendErrorWithFormat("'%s' takes a command string argument",
5306 m_cmd_name.c_str());
5307 result.SetStatus(eReturnStatusFailed);
5308 return false;
Jason Molenda6076bf42014-05-06 04:34:52 +00005309 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005310
Kate Stoneb9c1b512016-09-06 20:57:50 +00005311 ProcessGDBRemote *process =
5312 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5313 if (process) {
5314 StreamString packet;
5315 packet.PutCString("qRcmd,");
5316 packet.PutBytesAsRawHex8(command, strlen(command));
Ed Maste81b4c5f2016-01-04 01:43:47 +00005317
Kate Stoneb9c1b512016-09-06 20:57:50 +00005318 bool send_async = true;
5319 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005320 Stream &output_strm = result.GetOutputStream();
Pavel Labath7da84752018-01-10 14:39:08 +00005321 process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5322 packet.GetString(), response, send_async,
5323 [&output_strm](llvm::StringRef output) { output_strm << output; });
5324 result.SetStatus(eReturnStatusSuccessFinishResult);
Zachary Turnerc1564272016-11-16 21:15:24 +00005325 output_strm.Printf(" packet: %s\n", packet.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005326 const std::string &response_str = response.GetStringRef();
Jason Molenda6076bf42014-05-06 04:34:52 +00005327
Kate Stoneb9c1b512016-09-06 20:57:50 +00005328 if (response_str.empty())
5329 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5330 else
5331 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
Jason Molenda6076bf42014-05-06 04:34:52 +00005332 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005333 return true;
5334 }
Jason Molenda6076bf42014-05-06 04:34:52 +00005335};
5336
Kate Stoneb9c1b512016-09-06 20:57:50 +00005337class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005338private:
Greg Clayton02686b82012-10-15 22:42:16 +00005339public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005340 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5341 : CommandObjectMultiword(interpreter, "process plugin packet",
5342 "Commands that deal with GDB remote packets.",
5343 NULL) {
5344 LoadSubCommand(
5345 "history",
5346 CommandObjectSP(
5347 new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5348 LoadSubCommand(
5349 "send", CommandObjectSP(
5350 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5351 LoadSubCommand(
5352 "monitor",
5353 CommandObjectSP(
5354 new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5355 LoadSubCommand(
5356 "xfer-size",
5357 CommandObjectSP(
5358 new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5359 LoadSubCommand("speed-test",
5360 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5361 interpreter)));
5362 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005363
Kate Stoneb9c1b512016-09-06 20:57:50 +00005364 ~CommandObjectProcessGDBRemotePacket() {}
Greg Clayton998255b2012-10-13 02:07:45 +00005365};
5366
Kate Stoneb9c1b512016-09-06 20:57:50 +00005367class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
Greg Claytonba4a0a52013-02-01 23:03:47 +00005368public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005369 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5370 : CommandObjectMultiword(
5371 interpreter, "process plugin",
5372 "Commands for operating on a ProcessGDBRemote process.",
5373 "process plugin <subcommand> [<subcommand-options>]") {
5374 LoadSubCommand(
5375 "packet",
5376 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5377 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005378
Kate Stoneb9c1b512016-09-06 20:57:50 +00005379 ~CommandObjectMultiwordProcessGDBRemote() {}
Greg Claytonba4a0a52013-02-01 23:03:47 +00005380};
5381
Kate Stoneb9c1b512016-09-06 20:57:50 +00005382CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5383 if (!m_command_sp)
5384 m_command_sp.reset(new CommandObjectMultiwordProcessGDBRemote(
5385 GetTarget().GetDebugger().GetCommandInterpreter()));
5386 return m_command_sp.get();
Greg Clayton998255b2012-10-13 02:07:45 +00005387}