blob: 0fb97b2f7db40029f51c529bb4e217b2379a86bb [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>
Pavel Labath6b3c8bb2018-04-05 16:23:54 +000027#include <csignal>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000028#include <map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000029#include <mutex>
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000030#include <sstream>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000031
Johnny Chen01a67862011-10-14 00:42:25 +000032#include "lldb/Breakpoint/Watchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000035#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Core/PluginManager.h"
37#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000038#include "lldb/Core/StreamFile.h"
Greg Clayton70b57652011-05-15 01:25:55 +000039#include "lldb/Core/Value.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000040#include "lldb/DataFormatters/FormatManager.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000041#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000042#include "lldb/Host/FileSystem.h"
Zachary Turner39de3112014-09-09 20:54:56 +000043#include "lldb/Host/HostThread.h"
Pavel Labathb6dbe9a2017-07-18 13:14:01 +000044#include "lldb/Host/PosixApi.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000045#include "lldb/Host/PseudoTerminal.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000046#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000047#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000048#include "lldb/Host/ThreadLauncher.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000049#include "lldb/Host/XML.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000050#include "lldb/Interpreter/Args.h"
Greg Clayton02686b82012-10-15 22:42:16 +000051#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000052#include "lldb/Interpreter/CommandObject.h"
53#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000054#include "lldb/Interpreter/CommandReturnObject.h"
Pavel Labath47cbf4a2018-04-10 09:03:59 +000055#include "lldb/Interpreter/OptionArgParser.h"
Greg Claytone034a042015-05-21 20:52:06 +000056#include "lldb/Interpreter/OptionGroupBoolean.h"
57#include "lldb/Interpreter/OptionGroupUInt64.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000058#include "lldb/Interpreter/OptionValueProperties.h"
59#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000060#include "lldb/Interpreter/Property.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061#include "lldb/Symbol/ObjectFile.h"
Jason Molenda21586c82015-09-09 03:36:24 +000062#include "lldb/Target/ABI.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000063#include "lldb/Target/DynamicLoader.h"
Pavel Labath16064d32018-03-20 11:56:24 +000064#include "lldb/Target/MemoryRegionInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000065#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066#include "lldb/Target/Target.h"
67#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000068#include "lldb/Target/ThreadPlanCallFunction.h"
Greg Claytonc6c420f2016-08-12 16:46:18 +000069#include "lldb/Utility/CleanUp.h"
Zachary Turner5713a052017-03-22 18:40:07 +000070#include "lldb/Utility/FileSpec.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000071#include "lldb/Utility/StreamString.h"
Pavel Labath38d06322017-06-29 14:32:17 +000072#include "lldb/Utility/Timer.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000073
Eugene Zelenko0722f082015-10-24 01:28:05 +000074// Project includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000075#include "GDBRemoteRegisterContext.h"
76#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000077#include "Plugins/Process/Utility/GDBRemoteSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000078#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000079#include "Plugins/Process/Utility/StopInfoMachException.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000080#include "ProcessGDBRemote.h"
81#include "ProcessGDBRemoteLog.h"
82#include "ThreadGDBRemote.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000083#include "lldb/Host/Host.h"
Pavel Labath9af71b32018-03-20 16:14:00 +000084#include "lldb/Utility/StringExtractorGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000085
Zachary Turner54695a32016-08-29 19:58:14 +000086#include "llvm/ADT/StringSwitch.h"
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000087#include "llvm/Support/Threading.h"
Eugene Zemtsov7993cc52017-03-07 21:34:40 +000088#include "llvm/Support/raw_ostream.h"
Zachary Turner54695a32016-08-29 19:58:14 +000089
Kate Stoneb9c1b512016-09-06 20:57:50 +000090#define DEBUGSERVER_BASENAME "debugserver"
Tamas Berghammerdb264a62015-03-31 09:52:22 +000091using namespace lldb;
92using namespace lldb_private;
93using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000094
Kate Stoneb9c1b512016-09-06 20:57:50 +000095namespace lldb {
96// Provide a function that can easily dump the packet history if we know a
97// ProcessGDBRemote * value (which we can get from logs or from debugging).
98// We need the function in the lldb namespace so it makes it into the final
99// executable since the LLDB shared library only exports stuff in the lldb
100// namespace. This allows you to attach with a debugger and call this
101// function and get the packet history dumped to a file.
102void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
103 StreamFile strm;
Zachary Turner97206d52017-05-12 04:51:55 +0000104 Status error(strm.GetFile().Open(path, File::eOpenOptionWrite |
105 File::eOpenOptionCanCreate));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 if (error.Success())
107 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(strm);
108}
Eugene Zelenko0722f082015-10-24 01:28:05 +0000109}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000110
Greg Clayton7f982402013-07-15 22:54:20 +0000111namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000112
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113static PropertyDefinition g_properties[] = {
114 {"packet-timeout", OptionValue::eTypeUInt64, true, 1, NULL, NULL,
115 "Specify the default packet timeout in seconds."},
116 {"target-definition-file", OptionValue::eTypeFileSpec, true, 0, NULL, NULL,
117 "The file that provides the description for remote target registers."},
118 {NULL, OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL}};
Ed Maste81b4c5f2016-01-04 01:43:47 +0000119
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120enum { ePropertyPacketTimeout, ePropertyTargetDefinitionFile };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000121
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122class PluginProperties : public Properties {
123public:
124 static ConstString GetSettingName() {
125 return ProcessGDBRemote::GetPluginNameStatic();
126 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000127
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128 PluginProperties() : Properties() {
129 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
130 m_collection_sp->Initialize(g_properties);
131 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 virtual ~PluginProperties() {}
Ed Maste81b4c5f2016-01-04 01:43:47 +0000134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 uint64_t GetPacketTimeout() {
136 const uint32_t idx = ePropertyPacketTimeout;
137 return m_collection_sp->GetPropertyAtIndexAsUInt64(
138 NULL, idx, g_properties[idx].default_uint_value);
139 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 bool SetPacketTimeout(uint64_t timeout) {
142 const uint32_t idx = ePropertyPacketTimeout;
143 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
144 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146 FileSpec GetTargetDefinitionFile() const {
147 const uint32_t idx = ePropertyTargetDefinitionFile;
148 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
149 }
150};
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000151
Kate Stoneb9c1b512016-09-06 20:57:50 +0000152typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000153
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
155 static ProcessKDPPropertiesSP g_settings_sp;
156 if (!g_settings_sp)
157 g_settings_sp.reset(new PluginProperties());
158 return g_settings_sp;
159}
Ed Maste81b4c5f2016-01-04 01:43:47 +0000160
Eugene Zelenko0722f082015-10-24 01:28:05 +0000161} // anonymous namespace end
Greg Clayton7f982402013-07-15 22:54:20 +0000162
Greg Claytonfda4fab2014-01-10 22:24:11 +0000163// TODO Randomly assigning a port is unsafe. We should get an unused
164// ephemeral port from the kernel and make sure we reserve it before passing
165// it to debugserver.
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167#if defined(__APPLE__)
168#define LOW_PORT (IPPORT_RESERVED)
169#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
Greg Claytonfda4fab2014-01-10 22:24:11 +0000170#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171#define LOW_PORT (1024u)
172#define HIGH_PORT (49151u)
Greg Claytonfda4fab2014-01-10 22:24:11 +0000173#endif
174
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175#if defined(__APPLE__) && \
176 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000177static bool rand_initialized = false;
178
Kate Stoneb9c1b512016-09-06 20:57:50 +0000179static inline uint16_t get_random_port() {
180 if (!rand_initialized) {
181 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000182
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183 rand_initialized = true;
184 srand(seed);
185 }
186 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Greg Claytonfda4fab2014-01-10 22:24:11 +0000187}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000188#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000189
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190ConstString ProcessGDBRemote::GetPluginNameStatic() {
191 static ConstString g_name("gdb-remote");
192 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195const char *ProcessGDBRemote::GetPluginDescriptionStatic() {
196 return "GDB Remote protocol based debugging plug-in.";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000197}
198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199void ProcessGDBRemote::Terminate() {
200 PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000201}
202
Greg Claytonc3776bf2012-02-09 06:16:32 +0000203lldb::ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp,
205 ListenerSP listener_sp,
206 const FileSpec *crash_file_path) {
207 lldb::ProcessSP process_sp;
208 if (crash_file_path == NULL)
209 process_sp.reset(new ProcessGDBRemote(target_sp, listener_sp));
210 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000211}
212
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
214 bool plugin_specified_by_name) {
215 if (plugin_specified_by_name)
Jim Ingham5aee1622010-08-09 23:31:02 +0000216 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217
218 // For now we are just making sure the file exists for a given module
219 Module *exe_module = target_sp->GetExecutableModulePointer();
220 if (exe_module) {
221 ObjectFile *exe_objfile = exe_module->GetObjectFile();
222 // We can't debug core files...
223 switch (exe_objfile->GetType()) {
224 case ObjectFile::eTypeInvalid:
225 case ObjectFile::eTypeCoreFile:
226 case ObjectFile::eTypeDebugInfo:
227 case ObjectFile::eTypeObjectFile:
228 case ObjectFile::eTypeSharedLibrary:
229 case ObjectFile::eTypeStubLibrary:
230 case ObjectFile::eTypeJIT:
231 return false;
232 case ObjectFile::eTypeExecutable:
233 case ObjectFile::eTypeDynamicLinker:
234 case ObjectFile::eTypeUnknown:
235 break;
236 }
237 return exe_module->GetFileSpec().Exists();
238 }
239 // However, if there is no executable module, we return true since we might be
240 // preparing to attach.
241 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000242}
243
Eugene Zelenko0722f082015-10-24 01:28:05 +0000244//----------------------------------------------------------------------
245// ProcessGDBRemote constructor
246//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
248 ListenerSP listener_sp)
Pavel Labatha9640122017-11-03 22:12:50 +0000249 : Process(target_sp, listener_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250 m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_last_stop_packet_mutex(),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000251 m_register_info(),
252 m_async_broadcaster(NULL, "lldb.process.gdb-remote.async-broadcaster"),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 m_async_listener_sp(
254 Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
255 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
256 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
257 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
258 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
259 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
260 m_waiting_for_attach(false), m_destroy_tried_resuming(false),
261 m_command_sp(), m_breakpoint_pc_offset(0),
Pavel Labath16064d32018-03-20 11:56:24 +0000262 m_initial_tid(LLDB_INVALID_THREAD_ID), m_allow_flash_writes(false),
263 m_erased_flash_ranges() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
265 "async thread should exit");
266 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
267 "async thread continue");
268 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
269 "async thread did exit");
Pavel Labath50556852015-09-03 09:36:22 +0000270
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC));
Pavel Labath50556852015-09-03 09:36:22 +0000272
Kate Stoneb9c1b512016-09-06 20:57:50 +0000273 const uint32_t async_event_mask =
274 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
Pavel Labath50556852015-09-03 09:36:22 +0000275
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 if (m_async_listener_sp->StartListeningForEvents(
277 &m_async_broadcaster, async_event_mask) != async_event_mask) {
278 if (log)
279 log->Printf("ProcessGDBRemote::%s failed to listen for "
280 "m_async_broadcaster events",
281 __FUNCTION__);
282 }
Pavel Labath50556852015-09-03 09:36:22 +0000283
Kate Stoneb9c1b512016-09-06 20:57:50 +0000284 const uint32_t gdb_event_mask =
285 Communication::eBroadcastBitReadThreadDidExit |
286 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
287 if (m_async_listener_sp->StartListeningForEvents(
288 &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
289 if (log)
290 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events",
291 __FUNCTION__);
292 }
Pavel Labath50556852015-09-03 09:36:22 +0000293
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294 const uint64_t timeout_seconds =
295 GetGlobalPluginProperties()->GetPacketTimeout();
296 if (timeout_seconds > 0)
Pavel Labath3aa04912016-10-31 17:19:42 +0000297 m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000298}
299
Eugene Zelenko0722f082015-10-24 01:28:05 +0000300//----------------------------------------------------------------------
301// Destructor
302//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303ProcessGDBRemote::~ProcessGDBRemote() {
304 // m_mach_process.UnregisterNotificationCallbacks (this);
305 Clear();
306 // We need to call finalize on the process before destroying ourselves
307 // to make sure all of the broadcaster cleanup goes as planned. If we
308 // destruct this class, then Process::~Process() might have problems
309 // trying to fully destroy the broadcaster.
310 Finalize();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000311
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312 // The general Finalize is going to try to destroy the process and that SHOULD
313 // shut down the async thread. However, if we don't kill it it will get
314 // stranded and
315 // its connection will go away so when it wakes up it will crash. So kill it
316 // for sure here.
317 StopAsyncThread();
318 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000319}
320
321//----------------------------------------------------------------------
322// PluginInterface
323//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324ConstString ProcessGDBRemote::GetPluginName() { return GetPluginNameStatic(); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000325
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326uint32_t ProcessGDBRemote::GetPluginVersion() { return 1; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000327
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328bool ProcessGDBRemote::ParsePythonTargetDefinition(
329 const FileSpec &target_definition_fspec) {
330 ScriptInterpreter *interpreter =
331 GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Zachary Turner97206d52017-05-12 04:51:55 +0000332 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333 StructuredData::ObjectSP module_object_sp(
334 interpreter->LoadPluginModule(target_definition_fspec, error));
335 if (module_object_sp) {
336 StructuredData::DictionarySP target_definition_sp(
337 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
338 "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000339
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 if (target_definition_sp) {
341 StructuredData::ObjectSP target_object(
342 target_definition_sp->GetValueForKey("host-info"));
343 if (target_object) {
344 if (auto host_info_dict = target_object->GetAsDictionary()) {
345 StructuredData::ObjectSP triple_value =
346 host_info_dict->GetValueForKey("triple");
347 if (auto triple_string_value = triple_value->GetAsString()) {
348 std::string triple_string = triple_string_value->GetValue();
349 ArchSpec host_arch(triple_string.c_str());
350 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
351 GetTarget().SetArchitecture(host_arch);
Greg Clayton312bcbe2013-10-17 01:10:23 +0000352 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 }
Greg Claytonef8180a2013-10-15 00:14:28 +0000354 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 }
356 m_breakpoint_pc_offset = 0;
357 StructuredData::ObjectSP breakpoint_pc_offset_value =
358 target_definition_sp->GetValueForKey("breakpoint-pc-offset");
359 if (breakpoint_pc_offset_value) {
360 if (auto breakpoint_pc_int_value =
361 breakpoint_pc_offset_value->GetAsInteger())
362 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
363 }
364
365 if (m_register_info.SetRegisterInfo(*target_definition_sp,
366 GetTarget().GetArchitecture()) > 0) {
367 return true;
368 }
Greg Claytonef8180a2013-10-15 00:14:28 +0000369 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 }
371 return false;
Greg Claytonef8180a2013-10-15 00:14:28 +0000372}
373
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374// If the remote stub didn't give us eh_frame or DWARF register numbers for a
375// register,
Jason Molenda21586c82015-09-09 03:36:24 +0000376// see if the ABI can provide them.
377// DWARF and eh_frame register numbers are defined as a part of the ABI.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378static void AugmentRegisterInfoViaABI(RegisterInfo &reg_info,
379 ConstString reg_name, ABISP abi_sp) {
380 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM ||
381 reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM) {
382 if (abi_sp) {
383 RegisterInfo abi_reg_info;
384 if (abi_sp->GetRegisterInfoByName(reg_name, abi_reg_info)) {
385 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM &&
386 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM) {
387 reg_info.kinds[eRegisterKindEHFrame] =
388 abi_reg_info.kinds[eRegisterKindEHFrame];
389 }
390 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM &&
391 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM) {
392 reg_info.kinds[eRegisterKindDWARF] =
393 abi_reg_info.kinds[eRegisterKindDWARF];
394 }
395 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM &&
396 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM) {
397 reg_info.kinds[eRegisterKindGeneric] =
398 abi_reg_info.kinds[eRegisterKindGeneric];
399 }
400 }
401 }
402 }
403}
404
405static size_t SplitCommaSeparatedRegisterNumberString(
406 const llvm::StringRef &comma_separated_regiter_numbers,
407 std::vector<uint32_t> &regnums, int base) {
408 regnums.clear();
409 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
410 value_pair.second = comma_separated_regiter_numbers;
411 do {
412 value_pair = value_pair.second.split(',');
413 if (!value_pair.first.empty()) {
414 uint32_t reg = StringConvert::ToUInt32(value_pair.first.str().c_str(),
415 LLDB_INVALID_REGNUM, base);
416 if (reg != LLDB_INVALID_REGNUM)
417 regnums.push_back(reg);
418 }
419 } while (!value_pair.second.empty());
420 return regnums.size();
421}
422
423void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
424 if (!force && m_register_info.GetNumRegisters() > 0)
425 return;
426
427 m_register_info.Clear();
428
429 // Check if qHostInfo specified a specific packet timeout for this connection.
430 // If so then lets update our setting so the user knows what the timeout is
431 // and can see it.
Pavel Labath3aa04912016-10-31 17:19:42 +0000432 const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
433 if (host_packet_timeout > std::chrono::seconds(0)) {
434 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout.count());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435 }
436
437 // Register info search order:
438 // 1 - Use the target definition python file if one is specified.
439 // 2 - If the target definition doesn't have any of the info from the
440 // target.xml (registers) then proceed to read the target.xml.
441 // 3 - Fall back on the qRegisterInfo packets.
442
443 FileSpec target_definition_fspec =
444 GetGlobalPluginProperties()->GetTargetDefinitionFile();
445 if (!target_definition_fspec.Exists()) {
446 // If the filename doesn't exist, it may be a ~ not having been expanded -
447 // try to resolve it.
448 target_definition_fspec.ResolvePath();
449 }
450 if (target_definition_fspec) {
451 // See if we can get register definitions from a python file
452 if (ParsePythonTargetDefinition(target_definition_fspec)) {
453 return;
454 } else {
455 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
456 stream_sp->Printf("ERROR: target description file %s failed to parse.\n",
457 target_definition_fspec.GetPath().c_str());
458 }
459 }
460
461 const ArchSpec &target_arch = GetTarget().GetArchitecture();
462 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
463 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
464
465 // Use the process' architecture instead of the host arch, if available
466 ArchSpec arch_to_use;
467 if (remote_process_arch.IsValid())
468 arch_to_use = remote_process_arch;
469 else
470 arch_to_use = remote_host_arch;
471
472 if (!arch_to_use.IsValid())
473 arch_to_use = target_arch;
474
475 if (GetGDBServerRegisterInfo(arch_to_use))
476 return;
477
478 char packet[128];
479 uint32_t reg_offset = 0;
480 uint32_t reg_num = 0;
481 for (StringExtractorGDBRemote::ResponseType response_type =
482 StringExtractorGDBRemote::eResponse;
483 response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
484 const int packet_len =
485 ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
486 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000487 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000489 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490 GDBRemoteCommunication::PacketResult::Success) {
491 response_type = response.GetResponseType();
492 if (response_type == StringExtractorGDBRemote::eResponse) {
493 llvm::StringRef name;
494 llvm::StringRef value;
495 ConstString reg_name;
496 ConstString alt_name;
497 ConstString set_name;
498 std::vector<uint32_t> value_regs;
499 std::vector<uint32_t> invalidate_regs;
500 std::vector<uint8_t> dwarf_opcode_bytes;
501 RegisterInfo reg_info = {
502 NULL, // Name
503 NULL, // Alt name
504 0, // byte size
505 reg_offset, // offset
506 eEncodingUint, // encoding
507 eFormatHex, // format
Jason Molenda21586c82015-09-09 03:36:24 +0000508 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509 LLDB_INVALID_REGNUM, // eh_frame reg num
510 LLDB_INVALID_REGNUM, // DWARF reg num
511 LLDB_INVALID_REGNUM, // generic reg num
512 reg_num, // process plugin reg num
513 reg_num // native register number
514 },
515 NULL,
516 NULL,
517 NULL, // Dwarf expression opcode bytes pointer
518 0 // Dwarf expression opcode bytes length
519 };
520
521 while (response.GetNameColonValue(name, value)) {
522 if (name.equals("name")) {
523 reg_name.SetString(value);
524 } else if (name.equals("alt-name")) {
525 alt_name.SetString(value);
526 } else if (name.equals("bitsize")) {
527 value.getAsInteger(0, reg_info.byte_size);
528 reg_info.byte_size /= CHAR_BIT;
529 } else if (name.equals("offset")) {
530 if (value.getAsInteger(0, reg_offset))
531 reg_offset = UINT32_MAX;
532 } else if (name.equals("encoding")) {
533 const Encoding encoding = Args::StringToEncoding(value);
534 if (encoding != eEncodingInvalid)
535 reg_info.encoding = encoding;
536 } else if (name.equals("format")) {
537 Format format = eFormatInvalid;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000538 if (OptionArgParser::ToFormat(value.str().c_str(), format, NULL)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539 .Success())
540 reg_info.format = format;
541 else {
542 reg_info.format =
543 llvm::StringSwitch<Format>(value)
544 .Case("binary", eFormatBinary)
545 .Case("decimal", eFormatDecimal)
546 .Case("hex", eFormatHex)
547 .Case("float", eFormatFloat)
548 .Case("vector-sint8", eFormatVectorOfSInt8)
549 .Case("vector-uint8", eFormatVectorOfUInt8)
550 .Case("vector-sint16", eFormatVectorOfSInt16)
551 .Case("vector-uint16", eFormatVectorOfUInt16)
552 .Case("vector-sint32", eFormatVectorOfSInt32)
553 .Case("vector-uint32", eFormatVectorOfUInt32)
554 .Case("vector-float32", eFormatVectorOfFloat32)
Valentina Giusticda0ae42016-09-08 14:16:45 +0000555 .Case("vector-uint64", eFormatVectorOfUInt64)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 .Case("vector-uint128", eFormatVectorOfUInt128)
557 .Default(eFormatInvalid);
Jason Molenda21586c82015-09-09 03:36:24 +0000558 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 } else if (name.equals("set")) {
560 set_name.SetString(value);
561 } else if (name.equals("gcc") || name.equals("ehframe")) {
562 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindEHFrame]))
563 reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM;
564 } else if (name.equals("dwarf")) {
565 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindDWARF]))
566 reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM;
567 } else if (name.equals("generic")) {
568 reg_info.kinds[eRegisterKindGeneric] =
569 Args::StringToGenericRegister(value);
570 } else if (name.equals("container-regs")) {
571 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
572 } else if (name.equals("invalidate-regs")) {
573 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
574 } else if (name.equals("dynamic_size_dwarf_expr_bytes")) {
575 size_t dwarf_opcode_len = value.size() / 2;
576 assert(dwarf_opcode_len > 0);
577
578 dwarf_opcode_bytes.resize(dwarf_opcode_len);
579 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
580
581 StringExtractor opcode_extractor(value);
582 uint32_t ret_val =
583 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
584 assert(dwarf_opcode_len == ret_val);
Hafiz Abid Qadeer05008ca2017-01-19 15:11:01 +0000585 UNUSED_IF_ASSERT_DISABLED(ret_val);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000586 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
587 }
Jason Molenda21586c82015-09-09 03:36:24 +0000588 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589
590 reg_info.byte_offset = reg_offset;
591 assert(reg_info.byte_size != 0);
592 reg_offset += reg_info.byte_size;
593 if (!value_regs.empty()) {
594 value_regs.push_back(LLDB_INVALID_REGNUM);
595 reg_info.value_regs = value_regs.data();
596 }
597 if (!invalidate_regs.empty()) {
598 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
599 reg_info.invalidate_regs = invalidate_regs.data();
600 }
601
602 // We have to make a temporary ABI here, and not use the GetABI because
603 // this code
604 // gets called in DidAttach, when the target architecture (and
605 // consequently the ABI we'll get from
606 // the process) may be wrong.
Jason Molenda43294c92017-06-29 02:57:03 +0000607 ABISP abi_to_use = ABI::FindPlugin(shared_from_this(), arch_to_use);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000608
609 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_to_use);
610
611 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
612 } else {
613 break; // ensure exit before reg_num is incremented
614 }
615 } else {
616 break;
Jason Molenda21586c82015-09-09 03:36:24 +0000617 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618 }
619
620 if (m_register_info.GetNumRegisters() > 0) {
621 m_register_info.Finalize(GetTarget().GetArchitecture());
622 return;
623 }
624
625 // We didn't get anything if the accumulated reg_num is zero. See if we are
626 // debugging ARM and fill with a hard coded register set until we can get an
627 // updated debugserver down on the devices.
628 // On the other hand, if the accumulated reg_num is positive, see if we can
629 // add composite registers to the existing primordial ones.
630 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
631
632 if (!target_arch.IsValid()) {
633 if (arch_to_use.IsValid() &&
634 (arch_to_use.GetMachine() == llvm::Triple::arm ||
635 arch_to_use.GetMachine() == llvm::Triple::thumb) &&
636 arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple)
637 m_register_info.HardcodeARMRegisters(from_scratch);
638 } else if (target_arch.GetMachine() == llvm::Triple::arm ||
639 target_arch.GetMachine() == llvm::Triple::thumb) {
640 m_register_info.HardcodeARMRegisters(from_scratch);
641 }
642
643 // At this point, we can finalize our register info.
644 m_register_info.Finalize(GetTarget().GetArchitecture());
Jason Molenda21586c82015-09-09 03:36:24 +0000645}
646
Zachary Turner97206d52017-05-12 04:51:55 +0000647Status ProcessGDBRemote::WillLaunch(Module *module) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 return WillLaunchOrAttach();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000649}
650
Zachary Turner97206d52017-05-12 04:51:55 +0000651Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000652 return WillLaunchOrAttach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000653}
654
Zachary Turner97206d52017-05-12 04:51:55 +0000655Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name,
656 bool wait_for_launch) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 return WillLaunchOrAttach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000658}
659
Zachary Turner97206d52017-05-12 04:51:55 +0000660Status ProcessGDBRemote::DoConnectRemote(Stream *strm,
661 llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000662 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +0000663 Status error(WillLaunchOrAttach());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 if (error.Fail())
Greg Claytonb766a732011-02-04 01:58:07 +0000666 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000667
668 error = ConnectToDebugserver(remote_url);
669
670 if (error.Fail())
671 return error;
672 StartAsyncThread();
673
674 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
675 if (pid == LLDB_INVALID_PROCESS_ID) {
676 // We don't have a valid process ID, so note that we are connected
677 // and could now request to launch or attach, or get remote process
678 // listings...
679 SetPrivateState(eStateConnected);
680 } else {
681 // We have a valid process
682 SetID(pid);
683 GetThreadList();
684 StringExtractorGDBRemote response;
685 if (m_gdb_comm.GetStopReply(response)) {
686 SetLastStopPacket(response);
687
688 // '?' Packets must be handled differently in non-stop mode
689 if (GetTarget().GetNonStopModeEnabled())
690 HandleStopReplySequence();
691
692 Target &target = GetTarget();
693 if (!target.GetArchitecture().IsValid()) {
694 if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
695 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
696 } else {
697 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
698 }
699 }
700
701 const StateType state = SetThreadStopInfo(response);
702 if (state != eStateInvalid) {
703 SetPrivateState(state);
704 } else
Zachary Turner31659452016-11-17 21:15:14 +0000705 error.SetErrorStringWithFormat(
706 "Process %" PRIu64 " was reported after connecting to "
707 "'%s', but state was not stopped: %s",
708 pid, remote_url.str().c_str(), StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 } else
710 error.SetErrorStringWithFormat("Process %" PRIu64
711 " was reported after connecting to '%s', "
712 "but no stop reply packet was received",
Zachary Turner31659452016-11-17 21:15:14 +0000713 pid, remote_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000714 }
715
716 if (log)
717 log->Printf("ProcessGDBRemote::%s pid %" PRIu64
718 ": normalizing target architecture initial triple: %s "
719 "(GetTarget().GetArchitecture().IsValid() %s, "
720 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
721 __FUNCTION__, GetID(),
722 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
723 GetTarget().GetArchitecture().IsValid() ? "true" : "false",
724 m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
725
726 if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
727 m_gdb_comm.GetHostArchitecture().IsValid()) {
728 // Prefer the *process'* architecture over that of the *host*, if available.
729 if (m_gdb_comm.GetProcessArchitecture().IsValid())
730 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
731 else
732 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
733 }
734
735 if (log)
736 log->Printf("ProcessGDBRemote::%s pid %" PRIu64
737 ": normalized target architecture triple: %s",
738 __FUNCTION__, GetID(),
739 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
740
741 if (error.Success()) {
742 PlatformSP platform_sp = GetTarget().GetPlatform();
743 if (platform_sp && platform_sp->IsConnected())
744 SetUnixSignals(platform_sp->GetUnixSignals());
745 else
746 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
747 }
748
749 return error;
Greg Claytonb766a732011-02-04 01:58:07 +0000750}
751
Zachary Turner97206d52017-05-12 04:51:55 +0000752Status ProcessGDBRemote::WillLaunchOrAttach() {
753 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754 m_stdio_communication.Clear();
755 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000756}
757
758//----------------------------------------------------------------------
759// Process Control
760//----------------------------------------------------------------------
Zachary Turner97206d52017-05-12 04:51:55 +0000761Status ProcessGDBRemote::DoLaunch(Module *exe_module,
762 ProcessLaunchInfo &launch_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +0000764 Status error;
Greg Clayton982c9762011-11-03 21:22:33 +0000765
Kate Stoneb9c1b512016-09-06 20:57:50 +0000766 if (log)
767 log->Printf("ProcessGDBRemote::%s() entered", __FUNCTION__);
Todd Fiala75f47c32014-10-11 21:42:09 +0000768
Kate Stoneb9c1b512016-09-06 20:57:50 +0000769 uint32_t launch_flags = launch_info.GetFlags().Get();
770 FileSpec stdin_file_spec{};
771 FileSpec stdout_file_spec{};
772 FileSpec stderr_file_spec{};
773 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000774
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 const FileAction *file_action;
776 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
777 if (file_action) {
778 if (file_action->GetAction() == FileAction::eFileActionOpen)
779 stdin_file_spec = file_action->GetFileSpec();
780 }
781 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
782 if (file_action) {
783 if (file_action->GetAction() == FileAction::eFileActionOpen)
784 stdout_file_spec = file_action->GetFileSpec();
785 }
786 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
787 if (file_action) {
788 if (file_action->GetAction() == FileAction::eFileActionOpen)
789 stderr_file_spec = file_action->GetFileSpec();
790 }
Greg Clayton982c9762011-11-03 21:22:33 +0000791
Kate Stoneb9c1b512016-09-06 20:57:50 +0000792 if (log) {
793 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
794 log->Printf("ProcessGDBRemote::%s provided with STDIO paths via "
795 "launch_info: stdin=%s, stdout=%s, stderr=%s",
796 __FUNCTION__,
797 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
798 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
799 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Vince Harrondf3f00f2015-02-10 21:09:04 +0000800 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 log->Printf("ProcessGDBRemote::%s no STDIO paths given via launch_info",
802 __FUNCTION__);
803 }
Vince Harrondf3f00f2015-02-10 21:09:04 +0000804
Kate Stoneb9c1b512016-09-06 20:57:50 +0000805 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
806 if (stdin_file_spec || disable_stdio) {
807 // the inferior will be reading stdin from the specified file
808 // or stdio is completely disabled
809 m_stdin_forward = false;
810 } else {
811 m_stdin_forward = true;
812 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000813
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
815 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
816 // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
817 // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
818 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000819
Kate Stoneb9c1b512016-09-06 20:57:50 +0000820 ObjectFile *object_file = exe_module->GetObjectFile();
821 if (object_file) {
822 error = EstablishConnectionIfNeeded(launch_info);
823 if (error.Success()) {
Pavel Labath07d6f882017-12-11 10:09:14 +0000824 PseudoTerminal pty;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000825 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000826
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 PlatformSP platform_sp(GetTarget().GetPlatform());
828 if (disable_stdio) {
829 // set to /dev/null unless redirected to a file above
830 if (!stdin_file_spec)
831 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false);
832 if (!stdout_file_spec)
833 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false);
834 if (!stderr_file_spec)
835 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false);
836 } else if (platform_sp && platform_sp->IsHost()) {
837 // If the debugserver is local and we aren't disabling STDIO, lets use
838 // a pseudo terminal to instead of relying on the 'O' packets for stdio
839 // since 'O' packets can really slow down debugging if the inferior
840 // does a lot of output.
841 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
842 pty.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, NULL, 0)) {
843 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
Chaoren Lind3173f32015-05-29 19:52:29 +0000844
Kate Stoneb9c1b512016-09-06 20:57:50 +0000845 if (!stdin_file_spec)
846 stdin_file_spec = slave_name;
Chaoren Lind3173f32015-05-29 19:52:29 +0000847
Kate Stoneb9c1b512016-09-06 20:57:50 +0000848 if (!stdout_file_spec)
849 stdout_file_spec = slave_name;
Greg Clayton71337622011-02-24 22:24:29 +0000850
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 if (!stderr_file_spec)
852 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000853 }
Vince Harron1b5a74e2015-01-21 22:42:49 +0000854 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855 log->Printf(
856 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
857 "(IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
858 __FUNCTION__,
859 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
860 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
861 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
862 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000863
Kate Stoneb9c1b512016-09-06 20:57:50 +0000864 if (log)
865 log->Printf("ProcessGDBRemote::%s final STDIO paths after all "
866 "adjustments: stdin=%s, stdout=%s, stderr=%s",
867 __FUNCTION__,
868 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
869 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
870 stderr_file_spec ? stderr_file_spec.GetCString()
871 : "<null>");
Ed Maste81b4c5f2016-01-04 01:43:47 +0000872
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873 if (stdin_file_spec)
874 m_gdb_comm.SetSTDIN(stdin_file_spec);
875 if (stdout_file_spec)
876 m_gdb_comm.SetSTDOUT(stdout_file_spec);
877 if (stderr_file_spec)
878 m_gdb_comm.SetSTDERR(stderr_file_spec);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000879
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
881 m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000882
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883 m_gdb_comm.SendLaunchArchPacket(
884 GetTarget().GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885
Kate Stoneb9c1b512016-09-06 20:57:50 +0000886 const char *launch_event_data = launch_info.GetLaunchEventData();
887 if (launch_event_data != NULL && *launch_event_data != '\0')
888 m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
Eugene Zelenko0722f082015-10-24 01:28:05 +0000889
Kate Stoneb9c1b512016-09-06 20:57:50 +0000890 if (working_dir) {
891 m_gdb_comm.SetWorkingDir(working_dir);
892 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000893
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894 // Send the environment and the program + arguments after we connect
Pavel Labath62930e52018-01-10 11:57:31 +0000895 m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
Ewan Crawford78baa192015-05-13 09:18:18 +0000896
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897 {
898 // Scope for the scoped timeout object
Pavel Labath3aa04912016-10-31 17:19:42 +0000899 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
900 std::chrono::seconds(10));
Ewan Crawford78baa192015-05-13 09:18:18 +0000901
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902 int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
903 if (arg_packet_err == 0) {
904 std::string error_str;
905 if (m_gdb_comm.GetLaunchSuccess(error_str)) {
906 SetID(m_gdb_comm.GetCurrentProcessID());
907 } else {
908 error.SetErrorString(error_str.c_str());
909 }
910 } else {
911 error.SetErrorStringWithFormat("'A' packet returned an error: %i",
912 arg_packet_err);
913 }
914 }
915
916 if (GetID() == LLDB_INVALID_PROCESS_ID) {
917 if (log)
918 log->Printf("failed to connect to debugserver: %s",
919 error.AsCString());
920 KillDebugserverProcess();
921 return error;
922 }
923
924 StringExtractorGDBRemote response;
925 if (m_gdb_comm.GetStopReply(response)) {
Ewan Crawford78baa192015-05-13 09:18:18 +0000926 SetLastStopPacket(response);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000927 // '?' Packets must be handled differently in non-stop mode
928 if (GetTarget().GetNonStopModeEnabled())
929 HandleStopReplySequence();
930
931 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
932
933 if (process_arch.IsValid()) {
934 GetTarget().MergeArchitecture(process_arch);
935 } else {
936 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
937 if (host_arch.IsValid())
938 GetTarget().MergeArchitecture(host_arch);
939 }
940
941 SetPrivateState(SetThreadStopInfo(response));
942
943 if (!disable_stdio) {
Pavel Labath07d6f882017-12-11 10:09:14 +0000944 if (pty.GetMasterFileDescriptor() != PseudoTerminal::invalid_fd)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945 SetSTDIOFileDescriptor(pty.ReleaseMasterFileDescriptor());
946 }
947 }
948 } else {
949 if (log)
950 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Ewan Crawford78baa192015-05-13 09:18:18 +0000951 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 } else {
953 // Set our user ID to an invalid process ID.
954 SetID(LLDB_INVALID_PROCESS_ID);
955 error.SetErrorStringWithFormat(
956 "failed to get object file from '%s' for arch %s",
957 exe_module->GetFileSpec().GetFilename().AsCString(),
958 exe_module->GetArchitecture().GetArchitectureName());
959 }
960 return error;
Ewan Crawford78baa192015-05-13 09:18:18 +0000961}
962
Zachary Turner97206d52017-05-12 04:51:55 +0000963Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
964 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000965 // Only connect if we have a valid connect URL
966 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
967
Zachary Turner31659452016-11-17 21:15:14 +0000968 if (!connect_url.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 if (log)
970 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
Zachary Turner31659452016-11-17 21:15:14 +0000971 connect_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
973 new ConnectionFileDescriptor());
974 if (conn_ap.get()) {
975 const uint32_t max_retry_count = 50;
976 uint32_t retry_count = 0;
977 while (!m_gdb_comm.IsConnected()) {
978 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess) {
979 m_gdb_comm.SetConnection(conn_ap.release());
980 break;
981 } else if (error.WasInterrupted()) {
982 // If we were interrupted, don't keep retrying.
983 break;
984 }
985
986 retry_count++;
987
988 if (retry_count >= max_retry_count)
989 break;
990
991 usleep(100000);
992 }
993 }
994 }
995
996 if (!m_gdb_comm.IsConnected()) {
997 if (error.Success())
998 error.SetErrorString("not connected to remote gdb server");
999 return error;
1000 }
1001
1002 // Start the communications read thread so all incoming data can be
1003 // parsed into packets and queued as they arrive.
1004 if (GetTarget().GetNonStopModeEnabled())
1005 m_gdb_comm.StartReadThread();
1006
1007 // We always seem to be able to open a connection to a local port
1008 // so we need to make sure we can then send data to it. If we can't
1009 // then we aren't actually connected to anything, so try and do the
1010 // handshake with the remote GDB server and make sure that goes
1011 // alright.
1012 if (!m_gdb_comm.HandshakeWithServer(&error)) {
1013 m_gdb_comm.Disconnect();
1014 if (error.Success())
1015 error.SetErrorString("not connected to remote gdb server");
1016 return error;
1017 }
1018
1019 // Send $QNonStop:1 packet on startup if required
1020 if (GetTarget().GetNonStopModeEnabled())
1021 GetTarget().SetNonStopModeEnabled(m_gdb_comm.SetNonStopMode(true));
1022
1023 m_gdb_comm.GetEchoSupported();
1024 m_gdb_comm.GetThreadSuffixSupported();
1025 m_gdb_comm.GetListThreadsInStopReplySupported();
1026 m_gdb_comm.GetHostInfo();
1027 m_gdb_comm.GetVContSupported('c');
1028 m_gdb_comm.GetVAttachOrWaitSupported();
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00001029 m_gdb_comm.EnableErrorStringInPacket();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030
1031 // Ask the remote server for the default thread id
1032 if (GetTarget().GetNonStopModeEnabled())
1033 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1034
1035 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1036 for (size_t idx = 0; idx < num_cmds; idx++) {
1037 StringExtractorGDBRemote response;
1038 m_gdb_comm.SendPacketAndWaitForResponse(
1039 GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1040 }
1041 return error;
1042}
1043
1044void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
1045 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1046 if (log)
1047 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1048 if (GetID() != LLDB_INVALID_PROCESS_ID) {
1049 BuildDynamicRegisterInfo(false);
1050
1051 // See if the GDB server supports the qHostInfo information
1052
1053 // See if the GDB server supports the qProcessInfo packet, if so
1054 // prefer that over the Host information as it will be more specific
1055 // to our process.
1056
1057 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1058 if (remote_process_arch.IsValid()) {
1059 process_arch = remote_process_arch;
1060 if (log)
1061 log->Printf("ProcessGDBRemote::%s gdb-remote had process architecture, "
1062 "using %s %s",
1063 __FUNCTION__, process_arch.GetArchitectureName()
1064 ? process_arch.GetArchitectureName()
1065 : "<null>",
1066 process_arch.GetTriple().getTriple().c_str()
1067 ? process_arch.GetTriple().getTriple().c_str()
1068 : "<null>");
1069 } else {
1070 process_arch = m_gdb_comm.GetHostArchitecture();
1071 if (log)
1072 log->Printf("ProcessGDBRemote::%s gdb-remote did not have process "
1073 "architecture, using gdb-remote host architecture %s %s",
1074 __FUNCTION__, process_arch.GetArchitectureName()
1075 ? process_arch.GetArchitectureName()
1076 : "<null>",
1077 process_arch.GetTriple().getTriple().c_str()
1078 ? process_arch.GetTriple().getTriple().c_str()
1079 : "<null>");
1080 }
1081
1082 if (process_arch.IsValid()) {
1083 const ArchSpec &target_arch = GetTarget().GetArchitecture();
1084 if (target_arch.IsValid()) {
1085 if (log)
1086 log->Printf(
1087 "ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1088 __FUNCTION__, target_arch.GetArchitectureName()
1089 ? target_arch.GetArchitectureName()
1090 : "<null>",
1091 target_arch.GetTriple().getTriple().c_str()
1092 ? target_arch.GetTriple().getTriple().c_str()
1093 : "<null>");
1094
1095 // If the remote host is ARM and we have apple as the vendor, then
1096 // ARM executables and shared libraries can have mixed ARM
1097 // architectures.
1098 // You can have an armv6 executable, and if the host is armv7, then the
1099 // system will load the best possible architecture for all shared
1100 // libraries
1101 // it has, so we really need to take the remote host architecture as our
1102 // defacto architecture in this case.
1103
1104 if ((process_arch.GetMachine() == llvm::Triple::arm ||
1105 process_arch.GetMachine() == llvm::Triple::thumb) &&
1106 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
1107 GetTarget().SetArchitecture(process_arch);
1108 if (log)
1109 log->Printf("ProcessGDBRemote::%s remote process is ARM/Apple, "
1110 "setting target arch to %s %s",
1111 __FUNCTION__, process_arch.GetArchitectureName()
1112 ? process_arch.GetArchitectureName()
1113 : "<null>",
1114 process_arch.GetTriple().getTriple().c_str()
1115 ? process_arch.GetTriple().getTriple().c_str()
1116 : "<null>");
1117 } else {
1118 // Fill in what is missing in the triple
1119 const llvm::Triple &remote_triple = process_arch.GetTriple();
1120 llvm::Triple new_target_triple = target_arch.GetTriple();
1121 if (new_target_triple.getVendorName().size() == 0) {
1122 new_target_triple.setVendor(remote_triple.getVendor());
1123
1124 if (new_target_triple.getOSName().size() == 0) {
1125 new_target_triple.setOS(remote_triple.getOS());
1126
1127 if (new_target_triple.getEnvironmentName().size() == 0)
1128 new_target_triple.setEnvironment(
1129 remote_triple.getEnvironment());
1130 }
1131
1132 ArchSpec new_target_arch = target_arch;
1133 new_target_arch.SetTriple(new_target_triple);
1134 GetTarget().SetArchitecture(new_target_arch);
1135 }
1136 }
1137
1138 if (log)
1139 log->Printf("ProcessGDBRemote::%s final target arch after "
1140 "adjustments for remote architecture: %s %s",
1141 __FUNCTION__, target_arch.GetArchitectureName()
1142 ? target_arch.GetArchitectureName()
1143 : "<null>",
1144 target_arch.GetTriple().getTriple().c_str()
1145 ? target_arch.GetTriple().getTriple().c_str()
1146 : "<null>");
1147 } else {
1148 // The target doesn't have a valid architecture yet, set it from
1149 // the architecture we got from the remote GDB server
1150 GetTarget().SetArchitecture(process_arch);
1151 }
1152 }
1153
1154 // Find out which StructuredDataPlugins are supported by the
1155 // debug monitor. These plugins transmit data over async $J packets.
1156 auto supported_packets_array =
1157 m_gdb_comm.GetSupportedStructuredDataPlugins();
1158 if (supported_packets_array)
1159 MapSupportedStructuredDataPlugins(*supported_packets_array);
1160 }
1161}
1162
1163void ProcessGDBRemote::DidLaunch() {
1164 ArchSpec process_arch;
1165 DidLaunchOrAttach(process_arch);
1166}
1167
Zachary Turner97206d52017-05-12 04:51:55 +00001168Status ProcessGDBRemote::DoAttachToProcessWithID(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1170 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00001171 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001172
1173 if (log)
1174 log->Printf("ProcessGDBRemote::%s()", __FUNCTION__);
1175
1176 // Clear out and clean up from any current state
1177 Clear();
1178 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1179 error = EstablishConnectionIfNeeded(attach_info);
1180 if (error.Success()) {
1181 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1182
1183 char packet[64];
1184 const int packet_len =
1185 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1186 SetID(attach_pid);
1187 m_async_broadcaster.BroadcastEvent(
1188 eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1189 } else
1190 SetExitStatus(-1, error.AsCString());
1191 }
1192
1193 return error;
1194}
1195
Zachary Turner97206d52017-05-12 04:51:55 +00001196Status ProcessGDBRemote::DoAttachToProcessWithName(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 const char *process_name, const ProcessAttachInfo &attach_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001198 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199 // Clear out and clean up from any current state
1200 Clear();
1201
1202 if (process_name && process_name[0]) {
1203 error = EstablishConnectionIfNeeded(attach_info);
1204 if (error.Success()) {
1205 StreamString packet;
1206
1207 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1208
1209 if (attach_info.GetWaitForLaunch()) {
1210 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1211 packet.PutCString("vAttachWait");
1212 } else {
1213 if (attach_info.GetIgnoreExisting())
1214 packet.PutCString("vAttachWait");
1215 else
1216 packet.PutCString("vAttachOrWait");
1217 }
1218 } else
1219 packet.PutCString("vAttachName");
1220 packet.PutChar(';');
1221 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1222 endian::InlHostByteOrder(),
1223 endian::InlHostByteOrder());
1224
1225 m_async_broadcaster.BroadcastEvent(
1226 eBroadcastBitAsyncContinue,
Zachary Turnerc1564272016-11-16 21:15:24 +00001227 new EventDataBytes(packet.GetString().data(), packet.GetSize()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001228
1229 } else
1230 SetExitStatus(-1, error.AsCString());
1231 }
1232 return error;
1233}
1234
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001235lldb::user_id_t ProcessGDBRemote::StartTrace(const TraceOptions &options,
1236 Status &error) {
1237 return m_gdb_comm.SendStartTracePacket(options, error);
1238}
1239
1240Status ProcessGDBRemote::StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
1241 return m_gdb_comm.SendStopTracePacket(uid, thread_id);
1242}
1243
1244Status ProcessGDBRemote::GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
1245 llvm::MutableArrayRef<uint8_t> &buffer,
1246 size_t offset) {
1247 return m_gdb_comm.SendGetDataPacket(uid, thread_id, buffer, offset);
1248}
1249
1250Status ProcessGDBRemote::GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
1251 llvm::MutableArrayRef<uint8_t> &buffer,
1252 size_t offset) {
1253 return m_gdb_comm.SendGetMetaDataPacket(uid, thread_id, buffer, offset);
1254}
1255
1256Status ProcessGDBRemote::GetTraceConfig(lldb::user_id_t uid,
1257 TraceOptions &options) {
1258 return m_gdb_comm.SendGetTraceConfigPacket(uid, options);
1259}
1260
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261void ProcessGDBRemote::DidExit() {
1262 // When we exit, disconnect from the GDB server communications
1263 m_gdb_comm.Disconnect();
1264}
1265
1266void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1267 // If you can figure out what the architecture is, fill it in here.
1268 process_arch.Clear();
1269 DidLaunchOrAttach(process_arch);
1270}
1271
Zachary Turner97206d52017-05-12 04:51:55 +00001272Status ProcessGDBRemote::WillResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001273 m_continue_c_tids.clear();
1274 m_continue_C_tids.clear();
1275 m_continue_s_tids.clear();
1276 m_continue_S_tids.clear();
1277 m_jstopinfo_sp.reset();
1278 m_jthreadsinfo_sp.reset();
Zachary Turner97206d52017-05-12 04:51:55 +00001279 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280}
1281
Zachary Turner97206d52017-05-12 04:51:55 +00001282Status ProcessGDBRemote::DoResume() {
1283 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1285 if (log)
1286 log->Printf("ProcessGDBRemote::Resume()");
1287
1288 ListenerSP listener_sp(
1289 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1290 if (listener_sp->StartListeningForEvents(
1291 &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
1292 listener_sp->StartListeningForEvents(
1293 &m_async_broadcaster,
1294 ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1295
1296 const size_t num_threads = GetThreadList().GetSize();
1297
1298 StreamString continue_packet;
1299 bool continue_packet_error = false;
1300 if (m_gdb_comm.HasAnyVContSupport()) {
1301 if (!GetTarget().GetNonStopModeEnabled() &&
1302 (m_continue_c_tids.size() == num_threads ||
1303 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1304 m_continue_s_tids.empty() && m_continue_S_tids.empty()))) {
1305 // All threads are continuing, just send a "c" packet
1306 continue_packet.PutCString("c");
1307 } else {
1308 continue_packet.PutCString("vCont");
1309
1310 if (!m_continue_c_tids.empty()) {
1311 if (m_gdb_comm.GetVContSupported('c')) {
1312 for (tid_collection::const_iterator
1313 t_pos = m_continue_c_tids.begin(),
1314 t_end = m_continue_c_tids.end();
1315 t_pos != t_end; ++t_pos)
1316 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1317 } else
1318 continue_packet_error = true;
1319 }
1320
1321 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1322 if (m_gdb_comm.GetVContSupported('C')) {
1323 for (tid_sig_collection::const_iterator
1324 s_pos = m_continue_C_tids.begin(),
1325 s_end = m_continue_C_tids.end();
1326 s_pos != s_end; ++s_pos)
1327 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second,
1328 s_pos->first);
1329 } else
1330 continue_packet_error = true;
1331 }
1332
1333 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1334 if (m_gdb_comm.GetVContSupported('s')) {
1335 for (tid_collection::const_iterator
1336 t_pos = m_continue_s_tids.begin(),
1337 t_end = m_continue_s_tids.end();
1338 t_pos != t_end; ++t_pos)
1339 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1340 } else
1341 continue_packet_error = true;
1342 }
1343
1344 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1345 if (m_gdb_comm.GetVContSupported('S')) {
1346 for (tid_sig_collection::const_iterator
1347 s_pos = m_continue_S_tids.begin(),
1348 s_end = m_continue_S_tids.end();
1349 s_pos != s_end; ++s_pos)
1350 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second,
1351 s_pos->first);
1352 } else
1353 continue_packet_error = true;
1354 }
1355
1356 if (continue_packet_error)
Zachary Turnerc1564272016-11-16 21:15:24 +00001357 continue_packet.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358 }
1359 } else
1360 continue_packet_error = true;
1361
1362 if (continue_packet_error) {
1363 // Either no vCont support, or we tried to use part of the vCont
1364 // packet that wasn't supported by the remote GDB server.
1365 // We need to try and make a simple packet that can do our continue
1366 const size_t num_continue_c_tids = m_continue_c_tids.size();
1367 const size_t num_continue_C_tids = m_continue_C_tids.size();
1368 const size_t num_continue_s_tids = m_continue_s_tids.size();
1369 const size_t num_continue_S_tids = m_continue_S_tids.size();
1370 if (num_continue_c_tids > 0) {
1371 if (num_continue_c_tids == num_threads) {
1372 // All threads are resuming...
1373 m_gdb_comm.SetCurrentThreadForRun(-1);
1374 continue_packet.PutChar('c');
1375 continue_packet_error = false;
1376 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1377 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1378 // Only one thread is continuing
1379 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1380 continue_packet.PutChar('c');
1381 continue_packet_error = false;
1382 }
1383 }
1384
1385 if (continue_packet_error && num_continue_C_tids > 0) {
1386 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1387 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1388 num_continue_S_tids == 0) {
1389 const int continue_signo = m_continue_C_tids.front().second;
1390 // Only one thread is continuing
1391 if (num_continue_C_tids > 1) {
1392 // More that one thread with a signal, yet we don't have
1393 // vCont support and we are being asked to resume each
1394 // thread with a signal, we need to make sure they are
1395 // all the same signal, or we can't issue the continue
1396 // accurately with the current support...
1397 if (num_continue_C_tids > 1) {
1398 continue_packet_error = false;
1399 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1400 if (m_continue_C_tids[i].second != continue_signo)
1401 continue_packet_error = true;
1402 }
1403 }
1404 if (!continue_packet_error)
1405 m_gdb_comm.SetCurrentThreadForRun(-1);
1406 } else {
1407 // Set the continue thread ID
1408 continue_packet_error = false;
1409 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1410 }
1411 if (!continue_packet_error) {
1412 // Add threads continuing with the same signo...
1413 continue_packet.Printf("C%2.2x", continue_signo);
1414 }
1415 }
1416 }
1417
1418 if (continue_packet_error && num_continue_s_tids > 0) {
1419 if (num_continue_s_tids == num_threads) {
1420 // All threads are resuming...
1421 m_gdb_comm.SetCurrentThreadForRun(-1);
1422
1423 // If in Non-Stop-Mode use vCont when stepping
1424 if (GetTarget().GetNonStopModeEnabled()) {
1425 if (m_gdb_comm.GetVContSupported('s'))
1426 continue_packet.PutCString("vCont;s");
1427 else
1428 continue_packet.PutChar('s');
1429 } else
1430 continue_packet.PutChar('s');
1431
1432 continue_packet_error = false;
1433 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1434 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1435 // Only one thread is stepping
1436 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1437 continue_packet.PutChar('s');
1438 continue_packet_error = false;
1439 }
1440 }
1441
1442 if (!continue_packet_error && num_continue_S_tids > 0) {
1443 if (num_continue_S_tids == num_threads) {
1444 const int step_signo = m_continue_S_tids.front().second;
1445 // Are all threads trying to step with the same signal?
1446 continue_packet_error = false;
1447 if (num_continue_S_tids > 1) {
1448 for (size_t i = 1; i < num_threads; ++i) {
1449 if (m_continue_S_tids[i].second != step_signo)
1450 continue_packet_error = true;
1451 }
1452 }
1453 if (!continue_packet_error) {
1454 // Add threads stepping with the same signo...
1455 m_gdb_comm.SetCurrentThreadForRun(-1);
1456 continue_packet.Printf("S%2.2x", step_signo);
1457 }
1458 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1459 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1460 // Only one thread is stepping with signal
1461 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1462 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1463 continue_packet_error = false;
1464 }
1465 }
1466 }
1467
1468 if (continue_packet_error) {
1469 error.SetErrorString("can't make continue packet for this resume");
1470 } else {
1471 EventSP event_sp;
1472 if (!m_async_thread.IsJoinable()) {
1473 error.SetErrorString("Trying to resume but the async thread is dead.");
1474 if (log)
1475 log->Printf("ProcessGDBRemote::DoResume: Trying to resume but the "
1476 "async thread is dead.");
1477 return error;
1478 }
1479
1480 m_async_broadcaster.BroadcastEvent(
1481 eBroadcastBitAsyncContinue,
Zachary Turnerc1564272016-11-16 21:15:24 +00001482 new EventDataBytes(continue_packet.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001483 continue_packet.GetSize()));
1484
Pavel Labathd35031e12016-11-30 10:41:42 +00001485 if (listener_sp->GetEvent(event_sp, std::chrono::seconds(5)) == false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001486 error.SetErrorString("Resume timed out.");
1487 if (log)
1488 log->Printf("ProcessGDBRemote::DoResume: Resume timed out.");
1489 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1490 error.SetErrorString("Broadcast continue, but the async thread was "
1491 "killed before we got an ack back.");
1492 if (log)
1493 log->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the "
1494 "async thread was killed before we got an ack back.");
1495 return error;
1496 }
1497 }
1498 }
1499
1500 return error;
1501}
1502
1503void ProcessGDBRemote::HandleStopReplySequence() {
1504 while (true) {
1505 // Send vStopped
1506 StringExtractorGDBRemote response;
1507 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1508
1509 // OK represents end of signal list
1510 if (response.IsOKResponse())
1511 break;
1512
1513 // If not OK or a normal packet we have a problem
1514 if (!response.IsNormalResponse())
1515 break;
1516
1517 SetLastStopPacket(response);
1518 }
1519}
1520
1521void ProcessGDBRemote::ClearThreadIDList() {
1522 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1523 m_thread_ids.clear();
1524 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00001525}
1526
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001527size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001528ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) {
1529 m_thread_ids.clear();
1530 m_thread_pcs.clear();
1531 size_t comma_pos;
1532 lldb::tid_t tid;
1533 while ((comma_pos = value.find(',')) != std::string::npos) {
1534 value[comma_pos] = '\0';
1535 // thread in big endian hex
1536 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001537 if (tid != LLDB_INVALID_THREAD_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001538 m_thread_ids.push_back(tid);
1539 value.erase(0, comma_pos + 1);
1540 }
1541 tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1542 if (tid != LLDB_INVALID_THREAD_ID)
1543 m_thread_ids.push_back(tid);
1544 return m_thread_ids.size();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001545}
1546
Jason Molenda545304d2015-12-18 00:45:35 +00001547size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001548ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) {
1549 m_thread_pcs.clear();
1550 size_t comma_pos;
1551 lldb::addr_t pc;
1552 while ((comma_pos = value.find(',')) != std::string::npos) {
1553 value[comma_pos] = '\0';
1554 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1555 if (pc != LLDB_INVALID_ADDRESS)
1556 m_thread_pcs.push_back(pc);
1557 value.erase(0, comma_pos + 1);
1558 }
1559 pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16);
1560 if (pc != LLDB_INVALID_THREAD_ID)
1561 m_thread_pcs.push_back(pc);
1562 return m_thread_pcs.size();
Jason Molenda545304d2015-12-18 00:45:35 +00001563}
1564
Kate Stoneb9c1b512016-09-06 20:57:50 +00001565bool ProcessGDBRemote::UpdateThreadIDList() {
1566 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001567
Kate Stoneb9c1b512016-09-06 20:57:50 +00001568 if (m_jthreadsinfo_sp) {
1569 // If we have the JSON threads info, we can get the thread list from that
1570 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1571 if (thread_infos && thread_infos->GetSize() > 0) {
1572 m_thread_ids.clear();
1573 m_thread_pcs.clear();
1574 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1575 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1576 if (thread_dict) {
1577 // Set the thread stop info from the JSON dictionary
1578 SetThreadStopInfo(thread_dict);
1579 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1580 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1581 m_thread_ids.push_back(tid);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001582 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001583 return true; // Keep iterating through all thread_info objects
1584 });
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001585 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001586 if (!m_thread_ids.empty())
1587 return true;
1588 } else {
1589 // See if we can get the thread IDs from the current stop reply packets
1590 // that might contain a "threads" key/value pair
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001591
Kate Stoneb9c1b512016-09-06 20:57:50 +00001592 // Lock the thread stack while we access it
1593 // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1594 std::unique_lock<std::recursive_mutex> stop_stack_lock(
1595 m_last_stop_packet_mutex, std::defer_lock);
1596 if (stop_stack_lock.try_lock()) {
1597 // Get the number of stop packets on the stack
1598 int nItems = m_stop_packet_stack.size();
1599 // Iterate over them
1600 for (int i = 0; i < nItems; i++) {
1601 // Get the thread stop info
1602 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1603 const std::string &stop_info_str = stop_info.GetStringRef();
Jason Molenda545304d2015-12-18 00:45:35 +00001604
Kate Stoneb9c1b512016-09-06 20:57:50 +00001605 m_thread_pcs.clear();
1606 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1607 if (thread_pcs_pos != std::string::npos) {
1608 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1609 const size_t end = stop_info_str.find(';', start);
1610 if (end != std::string::npos) {
1611 std::string value = stop_info_str.substr(start, end - start);
1612 UpdateThreadPCsFromStopReplyThreadsValue(value);
1613 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001614 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001615
Kate Stoneb9c1b512016-09-06 20:57:50 +00001616 const size_t threads_pos = stop_info_str.find(";threads:");
1617 if (threads_pos != std::string::npos) {
1618 const size_t start = threads_pos + strlen(";threads:");
1619 const size_t end = stop_info_str.find(';', start);
1620 if (end != std::string::npos) {
1621 std::string value = stop_info_str.substr(start, end - start);
1622 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1623 return true;
1624 }
1625 }
1626 }
1627 }
1628 }
1629
1630 bool sequence_mutex_unavailable = false;
1631 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1632 if (sequence_mutex_unavailable) {
1633 return false; // We just didn't get the list
1634 }
1635 return true;
1636}
1637
1638bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list,
1639 ThreadList &new_thread_list) {
1640 // locker will keep a mutex locked until it goes out of scope
1641 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD));
Pavel Labathe8a7b982017-02-06 19:31:09 +00001642 LLDB_LOGV(log, "pid = {0}", GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001643
1644 size_t num_thread_ids = m_thread_ids.size();
1645 // The "m_thread_ids" thread ID list should always be updated after each stop
1646 // reply packet, but in case it isn't, update it here.
1647 if (num_thread_ids == 0) {
1648 if (!UpdateThreadIDList())
1649 return false;
1650 num_thread_ids = m_thread_ids.size();
1651 }
1652
1653 ThreadList old_thread_list_copy(old_thread_list);
1654 if (num_thread_ids > 0) {
1655 for (size_t i = 0; i < num_thread_ids; ++i) {
1656 tid_t tid = m_thread_ids[i];
1657 ThreadSP thread_sp(
1658 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1659 if (!thread_sp) {
1660 thread_sp.reset(new ThreadGDBRemote(*this, tid));
Pavel Labathe8a7b982017-02-06 19:31:09 +00001661 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1662 thread_sp.get(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001663 } else {
Pavel Labathe8a7b982017-02-06 19:31:09 +00001664 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1665 thread_sp.get(), thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001666 }
Pavel Labathe0a5b572017-01-20 14:17:16 +00001667
1668 SetThreadPc(thread_sp, i);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001669 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1670 }
1671 }
1672
1673 // Whatever that is left in old_thread_list_copy are not
1674 // present in new_thread_list. Remove non-existent threads from internal id
1675 // table.
1676 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1677 for (size_t i = 0; i < old_num_thread_ids; i++) {
1678 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1679 if (old_thread_sp) {
1680 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1681 m_thread_id_to_index_id_map.erase(old_thread_id);
1682 }
1683 }
1684
1685 return true;
1686}
1687
Pavel Labathe0a5b572017-01-20 14:17:16 +00001688void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1689 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1690 GetByteOrder() != eByteOrderInvalid) {
1691 ThreadGDBRemote *gdb_thread =
1692 static_cast<ThreadGDBRemote *>(thread_sp.get());
1693 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1694 if (reg_ctx_sp) {
1695 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1696 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1697 if (pc_regnum != LLDB_INVALID_REGNUM) {
1698 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1699 }
1700 }
1701 }
1702}
1703
Kate Stoneb9c1b512016-09-06 20:57:50 +00001704bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1705 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1706 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1707 // packet
1708 if (thread_infos_sp) {
1709 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1710 if (thread_infos) {
1711 lldb::tid_t tid;
1712 const size_t n = thread_infos->GetSize();
1713 for (size_t i = 0; i < n; ++i) {
1714 StructuredData::Dictionary *thread_dict =
1715 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1716 if (thread_dict) {
1717 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1718 "tid", tid, LLDB_INVALID_THREAD_ID)) {
1719 if (tid == thread->GetID())
1720 return (bool)SetThreadStopInfo(thread_dict);
1721 }
1722 }
1723 }
1724 }
1725 }
1726 return false;
1727}
1728
1729bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1730 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1731 // packet
1732 if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1733 return true;
1734
1735 // See if we got thread stop info for any threads valid stop info reasons
1736 // threads
1737 // via the "jstopinfo" packet stop reply packet key/value pair?
1738 if (m_jstopinfo_sp) {
1739 // If we have "jstopinfo" then we have stop descriptions for all threads
1740 // that have stop reasons, and if there is no entry for a thread, then
1741 // it has no stop reason.
1742 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1743 if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1744 thread->SetStopInfo(StopInfoSP());
Greg Clayton9e920902012-04-10 02:25:43 +00001745 }
1746 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001747 }
1748
1749 // Fall back to using the qThreadStopInfo packet
1750 StringExtractorGDBRemote stop_packet;
1751 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1752 return SetThreadStopInfo(stop_packet) == eStateStopped;
1753 return false;
Greg Clayton9e920902012-04-10 02:25:43 +00001754}
1755
Kate Stoneb9c1b512016-09-06 20:57:50 +00001756ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1757 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1758 uint8_t signo, const std::string &thread_name, const std::string &reason,
1759 const std::string &description, uint32_t exc_type,
1760 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1761 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1762 // queue_serial are valid
1763 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1764 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1765 ThreadSP thread_sp;
1766 if (tid != LLDB_INVALID_THREAD_ID) {
1767 // Scope for "locker" below
Greg Clayton9e920902012-04-10 02:25:43 +00001768 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001769 // m_thread_list_real does have its own mutex, but we need to
1770 // hold onto the mutex between the call to
1771 // m_thread_list_real.FindThreadByID(...)
1772 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1773 std::lock_guard<std::recursive_mutex> guard(
1774 m_thread_list_real.GetMutex());
1775 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1776
1777 if (!thread_sp) {
1778 // Create the thread if we need to
1779 thread_sp.reset(new ThreadGDBRemote(*this, tid));
1780 m_thread_list_real.AddThread(thread_sp);
1781 }
Greg Clayton9e920902012-04-10 02:25:43 +00001782 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001783
Kate Stoneb9c1b512016-09-06 20:57:50 +00001784 if (thread_sp) {
1785 ThreadGDBRemote *gdb_thread =
1786 static_cast<ThreadGDBRemote *>(thread_sp.get());
1787 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1788
Pavel Labathe0a5b572017-01-20 14:17:16 +00001789 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1790 if (iter != m_thread_ids.end()) {
1791 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1792 }
1793
Kate Stoneb9c1b512016-09-06 20:57:50 +00001794 for (const auto &pair : expedited_register_map) {
1795 StringExtractor reg_value_extractor;
1796 reg_value_extractor.GetStringRef() = pair.second;
1797 DataBufferSP buffer_sp(new DataBufferHeap(
1798 reg_value_extractor.GetStringRef().size() / 2, 0));
1799 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1800 gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
1801 }
1802
1803 thread_sp->SetName(thread_name.empty() ? NULL : thread_name.c_str());
1804
1805 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1806 // Check if the GDB server was able to provide the queue name, kind and
1807 // serial number
1808 if (queue_vars_valid)
1809 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1810 queue_serial, dispatch_queue_t,
1811 associated_with_dispatch_queue);
1812 else
1813 gdb_thread->ClearQueueInfo();
1814
1815 gdb_thread->SetAssociatedWithLibdispatchQueue(
1816 associated_with_dispatch_queue);
1817
1818 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1819 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1820
1821 // Make sure we update our thread stop reason just once
1822 if (!thread_sp->StopInfoIsUpToDate()) {
1823 thread_sp->SetStopInfo(StopInfoSP());
1824 // If there's a memory thread backed by this thread, we need to use it
Jonas Devlieghere8db3f7e2018-04-13 11:31:34 +00001825 // to calculate StopInfo.
1826 if (ThreadSP memory_thread_sp =
1827 m_thread_list.GetBackingThread(thread_sp))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001828 thread_sp = memory_thread_sp;
1829
1830 if (exc_type != 0) {
1831 const size_t exc_data_size = exc_data.size();
1832
1833 thread_sp->SetStopInfo(
1834 StopInfoMachException::CreateStopReasonWithMachException(
1835 *thread_sp, exc_type, exc_data_size,
1836 exc_data_size >= 1 ? exc_data[0] : 0,
1837 exc_data_size >= 2 ? exc_data[1] : 0,
1838 exc_data_size >= 3 ? exc_data[2] : 0));
1839 } else {
1840 bool handled = false;
1841 bool did_exec = false;
1842 if (!reason.empty()) {
1843 if (reason.compare("trace") == 0) {
1844 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1845 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1846 ->GetBreakpointSiteList()
1847 .FindByAddress(pc);
1848
1849 // If the current pc is a breakpoint site then the StopInfo should
1850 // be set to Breakpoint
1851 // Otherwise, it will be set to Trace.
1852 if (bp_site_sp &&
1853 bp_site_sp->ValidForThisThread(thread_sp.get())) {
1854 thread_sp->SetStopInfo(
1855 StopInfo::CreateStopReasonWithBreakpointSiteID(
1856 *thread_sp, bp_site_sp->GetID()));
1857 } else
1858 thread_sp->SetStopInfo(
1859 StopInfo::CreateStopReasonToTrace(*thread_sp));
1860 handled = true;
1861 } else if (reason.compare("breakpoint") == 0) {
1862 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1863 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1864 ->GetBreakpointSiteList()
1865 .FindByAddress(pc);
1866 if (bp_site_sp) {
1867 // If the breakpoint is for this thread, then we'll report the
1868 // hit, but if it is for another thread,
1869 // we can just report no reason. We don't need to worry about
1870 // stepping over the breakpoint here, that
1871 // will be taken care of when the thread resumes and notices
1872 // that there's a breakpoint under the pc.
1873 handled = true;
1874 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1875 thread_sp->SetStopInfo(
1876 StopInfo::CreateStopReasonWithBreakpointSiteID(
1877 *thread_sp, bp_site_sp->GetID()));
1878 } else {
1879 StopInfoSP invalid_stop_info_sp;
1880 thread_sp->SetStopInfo(invalid_stop_info_sp);
Jason Molenda545304d2015-12-18 00:45:35 +00001881 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001882 }
1883 } else if (reason.compare("trap") == 0) {
1884 // Let the trap just use the standard signal stop reason below...
1885 } else if (reason.compare("watchpoint") == 0) {
1886 StringExtractor desc_extractor(description.c_str());
1887 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1888 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1889 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1890 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1891 if (wp_addr != LLDB_INVALID_ADDRESS) {
1892 WatchpointSP wp_sp;
1893 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1894 if ((core >= ArchSpec::kCore_mips_first &&
1895 core <= ArchSpec::kCore_mips_last) ||
1896 (core >= ArchSpec::eCore_arm_generic &&
1897 core <= ArchSpec::eCore_arm_aarch64))
1898 wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1899 wp_hit_addr);
1900 if (!wp_sp)
1901 wp_sp =
1902 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1903 if (wp_sp) {
1904 wp_sp->SetHardwareIndex(wp_index);
1905 watch_id = wp_sp->GetID();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001906 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001907 }
1908 if (watch_id == LLDB_INVALID_WATCH_ID) {
1909 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(
1910 GDBR_LOG_WATCHPOINTS));
1911 if (log)
1912 log->Printf("failed to find watchpoint");
1913 }
1914 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1915 *thread_sp, watch_id, wp_hit_addr));
1916 handled = true;
1917 } else if (reason.compare("exception") == 0) {
1918 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1919 *thread_sp, description.c_str()));
1920 handled = true;
1921 } else if (reason.compare("exec") == 0) {
1922 did_exec = true;
1923 thread_sp->SetStopInfo(
1924 StopInfo::CreateStopReasonWithExec(*thread_sp));
1925 handled = true;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001926 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001927 } else if (!signo) {
1928 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1929 lldb::BreakpointSiteSP bp_site_sp =
1930 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1931 pc);
Greg Clayton2e309072015-07-17 23:42:28 +00001932
Kate Stoneb9c1b512016-09-06 20:57:50 +00001933 // If the current pc is a breakpoint site then the StopInfo should
1934 // be set to Breakpoint
1935 // even though the remote stub did not set it as such. This can
1936 // happen when
1937 // the thread is involuntarily interrupted (e.g. due to stops on
1938 // other
1939 // threads) just as it is about to execute the breakpoint
1940 // instruction.
1941 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) {
1942 thread_sp->SetStopInfo(
1943 StopInfo::CreateStopReasonWithBreakpointSiteID(
1944 *thread_sp, bp_site_sp->GetID()));
1945 handled = true;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001946 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001947 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001948
Kate Stoneb9c1b512016-09-06 20:57:50 +00001949 if (!handled && signo && did_exec == false) {
1950 if (signo == SIGTRAP) {
1951 // Currently we are going to assume SIGTRAP means we are either
1952 // hitting a breakpoint or hardware single stepping.
1953 handled = true;
1954 addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1955 m_breakpoint_pc_offset;
1956 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1957 ->GetBreakpointSiteList()
1958 .FindByAddress(pc);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001959
Kate Stoneb9c1b512016-09-06 20:57:50 +00001960 if (bp_site_sp) {
1961 // If the breakpoint is for this thread, then we'll report the
1962 // hit, but if it is for another thread,
1963 // we can just report no reason. We don't need to worry about
1964 // stepping over the breakpoint here, that
1965 // will be taken care of when the thread resumes and notices
1966 // that there's a breakpoint under the pc.
1967 if (bp_site_sp->ValidForThisThread(thread_sp.get())) {
1968 if (m_breakpoint_pc_offset != 0)
1969 thread_sp->GetRegisterContext()->SetPC(pc);
1970 thread_sp->SetStopInfo(
1971 StopInfo::CreateStopReasonWithBreakpointSiteID(
1972 *thread_sp, bp_site_sp->GetID()));
1973 } else {
1974 StopInfoSP invalid_stop_info_sp;
1975 thread_sp->SetStopInfo(invalid_stop_info_sp);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001976 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001977 } else {
1978 // If we were stepping then assume the stop was the result of
1979 // the trace. If we were
1980 // not stepping then report the SIGTRAP.
1981 // FIXME: We are still missing the case where we single step
1982 // over a trap instruction.
1983 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1984 thread_sp->SetStopInfo(
1985 StopInfo::CreateStopReasonToTrace(*thread_sp));
Greg Clayton2e309072015-07-17 23:42:28 +00001986 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001987 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1988 *thread_sp, signo, description.c_str()));
1989 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001990 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001991 if (!handled)
1992 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1993 *thread_sp, signo, description.c_str()));
1994 }
1995
1996 if (!description.empty()) {
1997 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1998 if (stop_info_sp) {
1999 const char *stop_info_desc = stop_info_sp->GetDescription();
2000 if (!stop_info_desc || !stop_info_desc[0])
2001 stop_info_sp->SetDescription(description.c_str());
2002 } else {
2003 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2004 *thread_sp, description.c_str()));
2005 }
2006 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002007 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002008 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002009 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002010 }
2011 return thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002012}
2013
Greg Clayton2e309072015-07-17 23:42:28 +00002014lldb::ThreadSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00002015ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
2016 static ConstString g_key_tid("tid");
2017 static ConstString g_key_name("name");
2018 static ConstString g_key_reason("reason");
2019 static ConstString g_key_metype("metype");
2020 static ConstString g_key_medata("medata");
2021 static ConstString g_key_qaddr("qaddr");
2022 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2023 static ConstString g_key_associated_with_dispatch_queue(
2024 "associated_with_dispatch_queue");
2025 static ConstString g_key_queue_name("qname");
2026 static ConstString g_key_queue_kind("qkind");
2027 static ConstString g_key_queue_serial_number("qserialnum");
2028 static ConstString g_key_registers("registers");
2029 static ConstString g_key_memory("memory");
2030 static ConstString g_key_address("address");
2031 static ConstString g_key_bytes("bytes");
2032 static ConstString g_key_description("description");
2033 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002034
Kate Stoneb9c1b512016-09-06 20:57:50 +00002035 // Stop with signal and thread info
2036 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2037 uint8_t signo = 0;
2038 std::string value;
2039 std::string thread_name;
2040 std::string reason;
2041 std::string description;
2042 uint32_t exc_type = 0;
2043 std::vector<addr_t> exc_data;
2044 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2045 ExpeditedRegisterMap expedited_register_map;
2046 bool queue_vars_valid = false;
2047 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2048 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2049 std::string queue_name;
2050 QueueKind queue_kind = eQueueKindUnknown;
2051 uint64_t queue_serial_number = 0;
2052 // Iterate through all of the thread dictionary key/value pairs from the
2053 // structured data dictionary
2054
2055 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2056 &signo, &reason, &description, &exc_type, &exc_data,
2057 &thread_dispatch_qaddr, &queue_vars_valid,
2058 &associated_with_dispatch_queue, &dispatch_queue_t,
2059 &queue_name, &queue_kind, &queue_serial_number](
2060 ConstString key,
2061 StructuredData::Object *object) -> bool {
2062 if (key == g_key_tid) {
2063 // thread in big endian hex
2064 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2065 } else if (key == g_key_metype) {
2066 // exception type in big endian hex
2067 exc_type = object->GetIntegerValue(0);
2068 } else if (key == g_key_medata) {
2069 // exception data in big endian hex
2070 StructuredData::Array *array = object->GetAsArray();
2071 if (array) {
2072 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2073 exc_data.push_back(object->GetIntegerValue());
2074 return true; // Keep iterating through all array items
2075 });
2076 }
2077 } else if (key == g_key_name) {
2078 thread_name = object->GetStringValue();
2079 } else if (key == g_key_qaddr) {
2080 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2081 } else if (key == g_key_queue_name) {
2082 queue_vars_valid = true;
2083 queue_name = object->GetStringValue();
2084 } else if (key == g_key_queue_kind) {
2085 std::string queue_kind_str = object->GetStringValue();
2086 if (queue_kind_str == "serial") {
2087 queue_vars_valid = true;
2088 queue_kind = eQueueKindSerial;
2089 } else if (queue_kind_str == "concurrent") {
2090 queue_vars_valid = true;
2091 queue_kind = eQueueKindConcurrent;
2092 }
2093 } else if (key == g_key_queue_serial_number) {
2094 queue_serial_number = object->GetIntegerValue(0);
2095 if (queue_serial_number != 0)
2096 queue_vars_valid = true;
2097 } else if (key == g_key_dispatch_queue_t) {
2098 dispatch_queue_t = object->GetIntegerValue(0);
2099 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2100 queue_vars_valid = true;
2101 } else if (key == g_key_associated_with_dispatch_queue) {
2102 queue_vars_valid = true;
2103 bool associated = object->GetBooleanValue();
2104 if (associated)
2105 associated_with_dispatch_queue = eLazyBoolYes;
2106 else
2107 associated_with_dispatch_queue = eLazyBoolNo;
2108 } else if (key == g_key_reason) {
2109 reason = object->GetStringValue();
2110 } else if (key == g_key_description) {
2111 description = object->GetStringValue();
2112 } else if (key == g_key_registers) {
2113 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2114
2115 if (registers_dict) {
2116 registers_dict->ForEach(
2117 [&expedited_register_map](ConstString key,
2118 StructuredData::Object *object) -> bool {
2119 const uint32_t reg =
2120 StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10);
2121 if (reg != UINT32_MAX)
2122 expedited_register_map[reg] = object->GetStringValue();
2123 return true; // Keep iterating through all array items
2124 });
2125 }
2126 } else if (key == g_key_memory) {
2127 StructuredData::Array *array = object->GetAsArray();
2128 if (array) {
2129 array->ForEach([this](StructuredData::Object *object) -> bool {
2130 StructuredData::Dictionary *mem_cache_dict =
2131 object->GetAsDictionary();
2132 if (mem_cache_dict) {
2133 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2134 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2135 "address", mem_cache_addr)) {
2136 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
Zachary Turner28333212017-05-12 05:49:54 +00002137 llvm::StringRef str;
2138 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2139 StringExtractor bytes(str);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002140 bytes.SetFilePos(0);
2141
2142 const size_t byte_size = bytes.GetStringRef().size() / 2;
2143 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2144 const size_t bytes_copied =
2145 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2146 if (bytes_copied == byte_size)
2147 m_memory_cache.AddL1CacheData(mem_cache_addr,
2148 data_buffer_sp);
2149 }
2150 }
2151 }
2152 }
2153 return true; // Keep iterating through all array items
2154 });
2155 }
2156
2157 } else if (key == g_key_signal)
2158 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2159 return true; // Keep iterating through all dictionary key/value pairs
2160 });
2161
2162 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2163 reason, description, exc_type, exc_data,
2164 thread_dispatch_qaddr, queue_vars_valid,
2165 associated_with_dispatch_queue, dispatch_queue_t,
2166 queue_name, queue_kind, queue_serial_number);
2167}
2168
2169StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2170 stop_packet.SetFilePos(0);
2171 const char stop_type = stop_packet.GetChar();
2172 switch (stop_type) {
2173 case 'T':
2174 case 'S': {
2175 // This is a bit of a hack, but is is required. If we did exec, we
2176 // need to clear our thread lists and also know to rebuild our dynamic
2177 // register info before we lookup and threads and populate the expedited
2178 // register values so we need to know this right away so we can cleanup
2179 // and update our registers.
2180 const uint32_t stop_id = GetStopID();
2181 if (stop_id == 0) {
2182 // Our first stop, make sure we have a process ID, and also make
2183 // sure we know about our registers
2184 if (GetID() == LLDB_INVALID_PROCESS_ID) {
2185 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2186 if (pid != LLDB_INVALID_PROCESS_ID)
2187 SetID(pid);
2188 }
2189 BuildDynamicRegisterInfo(true);
2190 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002191 // Stop with signal and thread info
2192 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002193 const uint8_t signo = stop_packet.GetHexU8();
2194 llvm::StringRef key;
2195 llvm::StringRef value;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002196 std::string thread_name;
2197 std::string reason;
2198 std::string description;
2199 uint32_t exc_type = 0;
2200 std::vector<addr_t> exc_data;
2201 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002202 bool queue_vars_valid =
2203 false; // says if locals below that start with "queue_" are valid
Jason Molenda77f89352016-01-12 07:09:16 +00002204 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2205 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002206 std::string queue_name;
2207 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002208 uint64_t queue_serial_number = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002209 ExpeditedRegisterMap expedited_register_map;
2210 while (stop_packet.GetNameColonValue(key, value)) {
2211 if (key.compare("metype") == 0) {
2212 // exception type in big endian hex
2213 value.getAsInteger(16, exc_type);
2214 } else if (key.compare("medata") == 0) {
2215 // exception data in big endian hex
2216 uint64_t x;
2217 value.getAsInteger(16, x);
2218 exc_data.push_back(x);
2219 } else if (key.compare("thread") == 0) {
2220 // thread in big endian hex
2221 if (value.getAsInteger(16, tid))
2222 tid = LLDB_INVALID_THREAD_ID;
2223 } else if (key.compare("threads") == 0) {
2224 std::lock_guard<std::recursive_mutex> guard(
2225 m_thread_list_real.GetMutex());
Greg Clayton358cf1e2015-06-25 21:46:34 +00002226
Kate Stoneb9c1b512016-09-06 20:57:50 +00002227 m_thread_ids.clear();
2228 // A comma separated list of all threads in the current
2229 // process that includes the thread for this stop reply
2230 // packet
2231 lldb::tid_t tid;
2232 while (!value.empty()) {
2233 llvm::StringRef tid_str;
2234 std::tie(tid_str, value) = value.split(',');
2235 if (tid_str.getAsInteger(16, tid))
2236 tid = LLDB_INVALID_THREAD_ID;
2237 m_thread_ids.push_back(tid);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002238 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002239 } else if (key.compare("thread-pcs") == 0) {
2240 m_thread_pcs.clear();
2241 // A comma separated list of all threads in the current
2242 // process that includes the thread for this stop reply
2243 // packet
2244 lldb::addr_t pc;
2245 while (!value.empty()) {
2246 llvm::StringRef pc_str;
2247 std::tie(pc_str, value) = value.split(',');
2248 if (pc_str.getAsInteger(16, pc))
2249 pc = LLDB_INVALID_ADDRESS;
2250 m_thread_pcs.push_back(pc);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002251 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002252 } else if (key.compare("jstopinfo") == 0) {
2253 StringExtractor json_extractor(value);
2254 std::string json;
2255 // Now convert the HEX bytes into a string value
2256 json_extractor.GetHexByteString(json);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002257
Kate Stoneb9c1b512016-09-06 20:57:50 +00002258 // This JSON contains thread IDs and thread stop info for all threads.
2259 // It doesn't contain expedited registers, memory or queue info.
2260 m_jstopinfo_sp = StructuredData::ParseJSON(json);
2261 } else if (key.compare("hexname") == 0) {
2262 StringExtractor name_extractor(value);
2263 std::string name;
2264 // Now convert the HEX bytes into a string value
2265 name_extractor.GetHexByteString(thread_name);
2266 } else if (key.compare("name") == 0) {
2267 thread_name = value;
2268 } else if (key.compare("qaddr") == 0) {
2269 value.getAsInteger(16, thread_dispatch_qaddr);
2270 } else if (key.compare("dispatch_queue_t") == 0) {
2271 queue_vars_valid = true;
2272 value.getAsInteger(16, dispatch_queue_t);
2273 } else if (key.compare("qname") == 0) {
2274 queue_vars_valid = true;
2275 StringExtractor name_extractor(value);
2276 // Now convert the HEX bytes into a string value
2277 name_extractor.GetHexByteString(queue_name);
2278 } else if (key.compare("qkind") == 0) {
2279 queue_kind = llvm::StringSwitch<QueueKind>(value)
2280 .Case("serial", eQueueKindSerial)
2281 .Case("concurrent", eQueueKindConcurrent)
2282 .Default(eQueueKindUnknown);
2283 queue_vars_valid = queue_kind != eQueueKindUnknown;
2284 } else if (key.compare("qserialnum") == 0) {
2285 if (!value.getAsInteger(0, queue_serial_number))
2286 queue_vars_valid = true;
2287 } else if (key.compare("reason") == 0) {
2288 reason = value;
2289 } else if (key.compare("description") == 0) {
2290 StringExtractor desc_extractor(value);
2291 // Now convert the HEX bytes into a string value
2292 desc_extractor.GetHexByteString(description);
2293 } else if (key.compare("memory") == 0) {
2294 // Expedited memory. GDB servers can choose to send back expedited
2295 // memory
2296 // that can populate the L1 memory cache in the process so that things
2297 // like
2298 // the frame pointer backchain can be expedited. This will help stack
2299 // backtracing be more efficient by not having to send as many memory
2300 // read
2301 // requests down the remote GDB server.
2302
2303 // Key/value pair format: memory:<addr>=<bytes>;
2304 // <addr> is a number whose base will be interpreted by the prefix:
2305 // "0x[0-9a-fA-F]+" for hex
2306 // "0[0-7]+" for octal
2307 // "[1-9]+" for decimal
2308 // <bytes> is native endian ASCII hex bytes just like the register
2309 // values
2310 llvm::StringRef addr_str, bytes_str;
2311 std::tie(addr_str, bytes_str) = value.split('=');
2312 if (!addr_str.empty() && !bytes_str.empty()) {
2313 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2314 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2315 StringExtractor bytes(bytes_str);
2316 const size_t byte_size = bytes.GetBytesLeft() / 2;
2317 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2318 const size_t bytes_copied =
2319 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2320 if (bytes_copied == byte_size)
2321 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2322 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002323 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002324 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2325 key.compare("awatch") == 0) {
2326 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2327 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2328 value.getAsInteger(16, wp_addr);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002329
Kate Stoneb9c1b512016-09-06 20:57:50 +00002330 WatchpointSP wp_sp =
2331 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2332 uint32_t wp_index = LLDB_INVALID_INDEX32;
Eugene Zelenko0722f082015-10-24 01:28:05 +00002333
Kate Stoneb9c1b512016-09-06 20:57:50 +00002334 if (wp_sp)
2335 wp_index = wp_sp->GetHardwareIndex();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002336
Kate Stoneb9c1b512016-09-06 20:57:50 +00002337 reason = "watchpoint";
2338 StreamString ostr;
2339 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002340 description = ostr.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002341 } else if (key.compare("library") == 0) {
2342 LoadModules();
2343 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2344 uint32_t reg = UINT32_MAX;
2345 if (!key.getAsInteger(16, reg))
2346 expedited_register_map[reg] = std::move(value);
2347 }
2348 }
2349
2350 if (tid == LLDB_INVALID_THREAD_ID) {
2351 // A thread id may be invalid if the response is old style 'S' packet
2352 // which does not provide the
2353 // thread information. So update the thread list and choose the first one.
2354 UpdateThreadIDList();
2355
2356 if (!m_thread_ids.empty()) {
2357 tid = m_thread_ids.front();
2358 }
2359 }
2360
2361 ThreadSP thread_sp = SetThreadStopInfo(
2362 tid, expedited_register_map, signo, thread_name, reason, description,
2363 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2364 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2365 queue_kind, queue_serial_number);
2366
2367 return eStateStopped;
2368 } break;
2369
2370 case 'W':
2371 case 'X':
2372 // process exited
2373 return eStateExited;
2374
2375 default:
2376 break;
2377 }
2378 return eStateInvalid;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002379}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002380
Kate Stoneb9c1b512016-09-06 20:57:50 +00002381void ProcessGDBRemote::RefreshStateAfterStop() {
2382 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002383
Kate Stoneb9c1b512016-09-06 20:57:50 +00002384 m_thread_ids.clear();
2385 m_thread_pcs.clear();
2386 // Set the thread stop info. It might have a "threads" key whose value is
2387 // a list of all thread IDs in the current process, so m_thread_ids might
2388 // get set.
Greg Claytona5801ad2015-07-15 22:59:03 +00002389
Kate Stoneb9c1b512016-09-06 20:57:50 +00002390 // Scope for the lock
2391 {
2392 // Lock the thread stack while we access it
2393 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2394 // Get the number of stop packets on the stack
2395 int nItems = m_stop_packet_stack.size();
2396 // Iterate over them
2397 for (int i = 0; i < nItems; i++) {
2398 // Get the thread stop info
2399 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2400 // Process thread stop info
2401 SetThreadStopInfo(stop_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002403 // Clear the thread stop stack
2404 m_stop_packet_stack.clear();
2405 }
2406
2407 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2408 if (m_thread_ids.empty()) {
2409 // No, we need to fetch the thread list manually
2410 UpdateThreadIDList();
2411 }
2412
2413 // If we have queried for a default thread id
2414 if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2415 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2416 m_initial_tid = LLDB_INVALID_THREAD_ID;
2417 }
2418
2419 // Let all threads recover from stopping and do any clean up based
2420 // on the previous thread state (if any).
2421 m_thread_list_real.RefreshStateAfterStop();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002422}
2423
Zachary Turner97206d52017-05-12 04:51:55 +00002424Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2425 Status error;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002426
Kate Stoneb9c1b512016-09-06 20:57:50 +00002427 if (m_public_state.GetValue() == eStateAttaching) {
2428 // We are being asked to halt during an attach. We need to just close
2429 // our file handle and debugserver will go away, and we can be done...
2430 m_gdb_comm.Disconnect();
2431 } else
2432 caused_stop = m_gdb_comm.Interrupt();
2433 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002434}
2435
Zachary Turner97206d52017-05-12 04:51:55 +00002436Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2437 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002438 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2439 if (log)
2440 log->Printf("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002441
Kate Stoneb9c1b512016-09-06 20:57:50 +00002442 error = m_gdb_comm.Detach(keep_stopped);
2443 if (log) {
2444 if (error.Success())
2445 log->PutCString(
2446 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
Greg Clayton513c26c2011-01-29 07:10:55 +00002447 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002448 log->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2449 error.AsCString() ? error.AsCString() : "<unknown error>");
2450 }
2451
2452 if (!error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002453 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002454
2455 // Sleep for one second to let the process get all detached...
2456 StopAsyncThread();
2457
2458 SetPrivateState(eStateDetached);
2459 ResumePrivateStateThread();
2460
2461 // KillDebugserverProcess ();
2462 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002463}
2464
Zachary Turner97206d52017-05-12 04:51:55 +00002465Status ProcessGDBRemote::DoDestroy() {
2466 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002467 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2468 if (log)
2469 log->Printf("ProcessGDBRemote::DoDestroy()");
Ed Maste81b4c5f2016-01-04 01:43:47 +00002470
Kate Stoneb9c1b512016-09-06 20:57:50 +00002471 // There is a bug in older iOS debugservers where they don't shut down the
2472 // process
2473 // they are debugging properly. If the process is sitting at a breakpoint or
2474 // an exception,
2475 // this can cause problems with restarting. So we check to see if any of our
2476 // threads are stopped
2477 // at a breakpoint, and if so we remove all the breakpoints, resume the
2478 // process, and THEN
2479 // destroy it again.
2480 //
2481 // Note, we don't have a good way to test the version of debugserver, but I
2482 // happen to know that
2483 // the set of all the iOS debugservers which don't support
2484 // GetThreadSuffixSupported() and that of
2485 // the debugservers with this bug are equal. There really should be a better
2486 // way to test this!
2487 //
2488 // We also use m_destroy_tried_resuming to make sure we only do this once, if
2489 // we resume and then halt and
2490 // get called here to destroy again and we're still at a breakpoint or
2491 // exception, then we should
2492 // just do the straight-forward kill.
2493 //
2494 // And of course, if we weren't able to stop the process by the time we get
2495 // here, it isn't
2496 // necessary (or helpful) to do any of this.
Ed Maste81b4c5f2016-01-04 01:43:47 +00002497
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498 if (!m_gdb_comm.GetThreadSuffixSupported() &&
2499 m_public_state.GetValue() != eStateRunning) {
2500 PlatformSP platform_sp = GetTarget().GetPlatform();
Jim Inghamacff8952013-05-02 00:27:30 +00002501
Kate Stoneb9c1b512016-09-06 20:57:50 +00002502 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2503 if (platform_sp && platform_sp->GetName() &&
2504 platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) {
2505 if (m_destroy_tried_resuming) {
Greg Clayton8cda7f02013-05-21 21:55:59 +00002506 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002507 log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to "
2508 "destroy once already, not doing it again.");
2509 } else {
2510 // At present, the plans are discarded and the breakpoints disabled
2511 // Process::Destroy,
2512 // but we really need it to happen here and it doesn't matter if we do
2513 // it twice.
2514 m_thread_list.DiscardThreadPlans();
2515 DisableAllBreakpointSites();
Greg Clayton8cda7f02013-05-21 21:55:59 +00002516
Kate Stoneb9c1b512016-09-06 20:57:50 +00002517 bool stop_looks_like_crash = false;
2518 ThreadList &threads = GetThreadList();
2519
2520 {
2521 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2522
2523 size_t num_threads = threads.GetSize();
2524 for (size_t i = 0; i < num_threads; i++) {
2525 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2526 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2527 StopReason reason = eStopReasonInvalid;
2528 if (stop_info_sp)
2529 reason = stop_info_sp->GetStopReason();
2530 if (reason == eStopReasonBreakpoint ||
2531 reason == eStopReasonException) {
2532 if (log)
2533 log->Printf(
2534 "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64
2535 " stopped with reason: %s.",
2536 thread_sp->GetProtocolID(), stop_info_sp->GetDescription());
2537 stop_looks_like_crash = true;
2538 break;
2539 }
2540 }
2541 }
2542
2543 if (stop_looks_like_crash) {
2544 if (log)
2545 log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a "
2546 "breakpoint, continue and then kill.");
2547 m_destroy_tried_resuming = true;
2548
2549 // If we are going to run again before killing, it would be good to
2550 // suspend all the threads
2551 // before resuming so they won't get into more trouble. Sadly, for
2552 // the threads stopped with
2553 // the breakpoint or exception, the exception doesn't get cleared if
2554 // it is suspended, so we do
2555 // have to run the risk of letting those threads proceed a bit.
2556
2557 {
2558 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2559
2560 size_t num_threads = threads.GetSize();
2561 for (size_t i = 0; i < num_threads; i++) {
2562 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2563 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2564 StopReason reason = eStopReasonInvalid;
2565 if (stop_info_sp)
2566 reason = stop_info_sp->GetStopReason();
2567 if (reason != eStopReasonBreakpoint &&
2568 reason != eStopReasonException) {
2569 if (log)
2570 log->Printf("ProcessGDBRemote::DoDestroy() - Suspending "
2571 "thread: 0x%4.4" PRIx64 " before running.",
2572 thread_sp->GetProtocolID());
2573 thread_sp->SetResumeState(eStateSuspended);
2574 }
2575 }
2576 }
2577 Resume();
2578 return Destroy(false);
2579 }
2580 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002582 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002583
Kate Stoneb9c1b512016-09-06 20:57:50 +00002584 // Interrupt if our inferior is running...
2585 int exit_status = SIGABRT;
2586 std::string exit_string;
Greg Clayton2e309072015-07-17 23:42:28 +00002587
Kate Stoneb9c1b512016-09-06 20:57:50 +00002588 if (m_gdb_comm.IsConnected()) {
2589 if (m_public_state.GetValue() != eStateAttaching) {
2590 StringExtractorGDBRemote response;
2591 bool send_async = true;
Pavel Labath3aa04912016-10-31 17:19:42 +00002592 GDBRemoteCommunication::ScopedTimeout(m_gdb_comm,
2593 std::chrono::seconds(3));
Greg Clayton2e309072015-07-17 23:42:28 +00002594
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002595 if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002596 GDBRemoteCommunication::PacketResult::Success) {
2597 char packet_cmd = response.GetChar(0);
2598
2599 if (packet_cmd == 'W' || packet_cmd == 'X') {
2600#if defined(__APPLE__)
2601 // For Native processes on Mac OS X, we launch through the Host
2602 // Platform, then hand the process off
2603 // to debugserver, which becomes the parent process through
2604 // "PT_ATTACH". Then when we go to kill
2605 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we
2606 // call waitpid which returns
2607 // with no error and the correct status. But amusingly enough that
2608 // doesn't seem to actually reap
2609 // the process, but instead it is left around as a Zombie. Probably
2610 // the kernel is in the process of
2611 // switching ownership back to lldb which was the original parent, and
2612 // gets confused in the handoff.
2613 // Anyway, so call waitpid here to finally reap it.
2614 PlatformSP platform_sp(GetTarget().GetPlatform());
2615 if (platform_sp && platform_sp->IsHost()) {
2616 int status;
2617 ::pid_t reap_pid;
2618 reap_pid = waitpid(GetID(), &status, WNOHANG);
2619 if (log)
2620 log->Printf("Reaped pid: %d, status: %d.\n", reap_pid, status);
2621 }
2622#endif
2623 SetLastStopPacket(response);
2624 ClearThreadIDList();
2625 exit_status = response.GetHexU8();
2626 } else {
2627 if (log)
2628 log->Printf("ProcessGDBRemote::DoDestroy - got unexpected response "
2629 "to k packet: %s",
2630 response.GetStringRef().c_str());
2631 exit_string.assign("got unexpected response to k packet: ");
2632 exit_string.append(response.GetStringRef());
2633 }
2634 } else {
2635 if (log)
2636 log->Printf("ProcessGDBRemote::DoDestroy - failed to send k packet");
2637 exit_string.assign("failed to send the k packet");
2638 }
2639 } else {
2640 if (log)
2641 log->Printf("ProcessGDBRemote::DoDestroy - killed or interrupted while "
2642 "attaching");
2643 exit_string.assign("killed or interrupted while attaching.");
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002644 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002645 } else {
2646 // If we missed setting the exit status on the way out, do it here.
2647 // NB set exit status can be called multiple times, the first one sets the
2648 // status.
2649 exit_string.assign("destroying when not connected to debugserver");
2650 }
2651
2652 SetExitStatus(exit_status, exit_string.c_str());
2653
2654 StopAsyncThread();
2655 KillDebugserverProcess();
2656 return error;
Greg Clayton8cda7f02013-05-21 21:55:59 +00002657}
2658
Kate Stoneb9c1b512016-09-06 20:57:50 +00002659void ProcessGDBRemote::SetLastStopPacket(
2660 const StringExtractorGDBRemote &response) {
2661 const bool did_exec =
2662 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2663 if (did_exec) {
2664 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2665 if (log)
2666 log->Printf("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2667
2668 m_thread_list_real.Clear();
2669 m_thread_list.Clear();
2670 BuildDynamicRegisterInfo(true);
2671 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2672 }
2673
2674 // Scope the lock
2675 {
2676 // Lock the thread stack while we access it
2677 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
2678
2679 // We are are not using non-stop mode, there can only be one last stop
2680 // reply packet, so clear the list.
2681 if (GetTarget().GetNonStopModeEnabled() == false)
2682 m_stop_packet_stack.clear();
2683
2684 // Add this stop packet to the stop packet stack
2685 // This stack will get popped and examined when we switch to the
2686 // Stopped state
2687 m_stop_packet_stack.push_back(response);
2688 }
2689}
2690
2691void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2692 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
Chaoren Linc963a222015-09-01 16:58:45 +00002693}
2694
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002695//------------------------------------------------------------------
2696// Process Queries
2697//------------------------------------------------------------------
2698
Kate Stoneb9c1b512016-09-06 20:57:50 +00002699bool ProcessGDBRemote::IsAlive() {
2700 return m_gdb_comm.IsConnected() && Process::IsAlive();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002701}
2702
Kate Stoneb9c1b512016-09-06 20:57:50 +00002703addr_t ProcessGDBRemote::GetImageInfoAddress() {
2704 // request the link map address via the $qShlibInfoAddr packet
2705 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
Aidan Doddsc0c83852015-05-08 09:36:31 +00002706
Kate Stoneb9c1b512016-09-06 20:57:50 +00002707 // the loaded module list can also provides a link map address
2708 if (addr == LLDB_INVALID_ADDRESS) {
2709 LoadedModuleInfoList list;
2710 if (GetLoadedModuleList(list).Success())
2711 addr = list.m_link_map;
2712 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00002713
Kate Stoneb9c1b512016-09-06 20:57:50 +00002714 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002715}
2716
Kate Stoneb9c1b512016-09-06 20:57:50 +00002717void ProcessGDBRemote::WillPublicStop() {
2718 // See if the GDB remote client supports the JSON threads info.
2719 // If so, we gather stop info for all threads, expedited registers,
2720 // expedited memory, runtime queue information (iOS and MacOSX only),
2721 // and more. Expediting memory will help stack backtracing be much
2722 // faster. Expediting registers will make sure we don't have to read
2723 // the thread registers for GPRs.
2724 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
Greg Clayton2e309072015-07-17 23:42:28 +00002725
Kate Stoneb9c1b512016-09-06 20:57:50 +00002726 if (m_jthreadsinfo_sp) {
2727 // Now set the stop info for each thread and also expedite any registers
2728 // and memory that was in the jThreadsInfo response.
2729 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2730 if (thread_infos) {
2731 const size_t n = thread_infos->GetSize();
2732 for (size_t i = 0; i < n; ++i) {
2733 StructuredData::Dictionary *thread_dict =
2734 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2735 if (thread_dict)
2736 SetThreadStopInfo(thread_dict);
2737 }
Greg Clayton2e309072015-07-17 23:42:28 +00002738 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002739 }
Greg Clayton2e309072015-07-17 23:42:28 +00002740}
2741
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002742//------------------------------------------------------------------
2743// Process Memory
2744//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002746 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002747 GetMaxMemorySize();
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002748 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2749 // M and m packets take 2 bytes for 1 byte of memory
2750 size_t max_memory_size =
2751 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2752 if (size > max_memory_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002753 // Keep memory read sizes down to a sane limit. This function will be
2754 // called multiple times in order to complete the task by
2755 // lldb_private::Process so it is ok to do this.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002756 size = max_memory_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002757 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002758
Kate Stoneb9c1b512016-09-06 20:57:50 +00002759 char packet[64];
2760 int packet_len;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002761 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2762 binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2763 (uint64_t)size);
2764 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002765 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002766 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002767 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002768 GDBRemoteCommunication::PacketResult::Success) {
2769 if (response.IsNormalResponse()) {
2770 error.Clear();
2771 if (binary_memory_read) {
2772 // The lower level GDBRemoteCommunication packet receive layer has
2773 // already de-quoted any
2774 // 0x7d character escaping that was present in the packet
Jason Molenda6076bf42014-05-06 04:34:52 +00002775
Kate Stoneb9c1b512016-09-06 20:57:50 +00002776 size_t data_received_size = response.GetBytesLeft();
2777 if (data_received_size > size) {
2778 // Don't write past the end of BUF if the remote debug server gave us
2779 // too
2780 // much data for some reason.
2781 data_received_size = size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002782 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 memcpy(buf, response.GetStringRef().data(), data_received_size);
2784 return data_received_size;
2785 } else {
2786 return response.GetHexBytes(
2787 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2788 }
2789 } else if (response.IsErrorResponse())
2790 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2791 else if (response.IsUnsupportedResponse())
2792 error.SetErrorStringWithFormat(
2793 "GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002794 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 error.SetErrorStringWithFormat(
2796 "unexpected response to GDB server memory read packet '%s': '%s'",
2797 packet, response.GetStringRef().c_str());
2798 } else {
2799 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2800 }
2801 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002802}
2803
Pavel Labath16064d32018-03-20 11:56:24 +00002804Status ProcessGDBRemote::WriteObjectFile(
2805 std::vector<ObjectFile::LoadableData> entries) {
2806 Status error;
2807 // Sort the entries by address because some writes, like those to flash
2808 // memory, must happen in order of increasing address.
2809 std::stable_sort(
2810 std::begin(entries), std::end(entries),
2811 [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
2812 return a.Dest < b.Dest;
2813 });
2814 m_allow_flash_writes = true;
2815 error = Process::WriteObjectFile(entries);
2816 if (error.Success())
2817 error = FlashDone();
2818 else
2819 // Even though some of the writing failed, try to send a flash done if
2820 // some of the writing succeeded so the flash state is reset to normal,
2821 // but don't stomp on the error status that was set in the write failure
2822 // since that's the one we want to report back.
2823 FlashDone();
2824 m_allow_flash_writes = false;
2825 return error;
2826}
2827
2828bool ProcessGDBRemote::HasErased(FlashRange range) {
2829 auto size = m_erased_flash_ranges.GetSize();
2830 for (size_t i = 0; i < size; ++i)
2831 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2832 return true;
2833 return false;
2834}
2835
2836Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
2837 Status status;
2838
2839 MemoryRegionInfo region;
2840 status = GetMemoryRegionInfo(addr, region);
2841 if (!status.Success())
2842 return status;
2843
2844 // The gdb spec doesn't say if erasures are allowed across multiple regions,
2845 // but we'll disallow it to be safe and to keep the logic simple by worring
2846 // about only one region's block size. DoMemoryWrite is this function's
2847 // primary user, and it can easily keep writes within a single memory region
2848 if (addr + size > region.GetRange().GetRangeEnd()) {
2849 status.SetErrorString("Unable to erase flash in multiple regions");
2850 return status;
2851 }
2852
2853 uint64_t blocksize = region.GetBlocksize();
2854 if (blocksize == 0) {
2855 status.SetErrorString("Unable to erase flash because blocksize is 0");
2856 return status;
2857 }
2858
2859 // Erasures can only be done on block boundary adresses, so round down addr
2860 // and round up size
2861 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2862 size += (addr - block_start_addr);
2863 if ((size % blocksize) != 0)
2864 size += (blocksize - size % blocksize);
2865
2866 FlashRange range(block_start_addr, size);
2867
2868 if (HasErased(range))
2869 return status;
2870
2871 // We haven't erased the entire range, but we may have erased part of it.
2872 // (e.g., block A is already erased and range starts in A and ends in B).
2873 // So, adjust range if necessary to exclude already erased blocks.
2874 if (!m_erased_flash_ranges.IsEmpty()) {
2875 // Assuming that writes and erasures are done in increasing addr order,
2876 // because that is a requirement of the vFlashWrite command. Therefore,
2877 // we only need to look at the last range in the list for overlap.
2878 const auto &last_range = *m_erased_flash_ranges.Back();
2879 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2880 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
2881 // overlap will be less than range.GetByteSize() or else HasErased() would
2882 // have been true
2883 range.SetByteSize(range.GetByteSize() - overlap);
2884 range.SetRangeBase(range.GetRangeBase() + overlap);
2885 }
2886 }
2887
2888 StreamString packet;
2889 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2890 (uint64_t)range.GetByteSize());
2891
2892 StringExtractorGDBRemote response;
2893 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2894 true) ==
2895 GDBRemoteCommunication::PacketResult::Success) {
2896 if (response.IsOKResponse()) {
2897 m_erased_flash_ranges.Insert(range, true);
2898 } else {
2899 if (response.IsErrorResponse())
2900 status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2901 addr);
2902 else if (response.IsUnsupportedResponse())
2903 status.SetErrorStringWithFormat("GDB server does not support flashing");
2904 else
2905 status.SetErrorStringWithFormat(
2906 "unexpected response to GDB server flash erase packet '%s': '%s'",
2907 packet.GetData(), response.GetStringRef().c_str());
2908 }
2909 } else {
2910 status.SetErrorStringWithFormat("failed to send packet: '%s'",
2911 packet.GetData());
2912 }
2913 return status;
2914}
2915
2916Status ProcessGDBRemote::FlashDone() {
2917 Status status;
2918 // If we haven't erased any blocks, then we must not have written anything
2919 // either, so there is no need to actually send a vFlashDone command
2920 if (m_erased_flash_ranges.IsEmpty())
2921 return status;
2922 StringExtractorGDBRemote response;
2923 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, true) ==
2924 GDBRemoteCommunication::PacketResult::Success) {
2925 if (response.IsOKResponse()) {
2926 m_erased_flash_ranges.Clear();
2927 } else {
2928 if (response.IsErrorResponse())
2929 status.SetErrorStringWithFormat("flash done failed");
2930 else if (response.IsUnsupportedResponse())
2931 status.SetErrorStringWithFormat("GDB server does not support flashing");
2932 else
2933 status.SetErrorStringWithFormat(
2934 "unexpected response to GDB server flash done packet: '%s'",
2935 response.GetStringRef().c_str());
2936 }
2937 } else {
2938 status.SetErrorStringWithFormat("failed to send flash done packet");
2939 }
2940 return status;
2941}
2942
Kate Stoneb9c1b512016-09-06 20:57:50 +00002943size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
Zachary Turner97206d52017-05-12 04:51:55 +00002944 size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002945 GetMaxMemorySize();
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002946 // M and m packets take 2 bytes for 1 byte of memory
2947 size_t max_memory_size = m_max_memory_size / 2;
2948 if (size > max_memory_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002949 // Keep memory read sizes down to a sane limit. This function will be
2950 // called multiple times in order to complete the task by
2951 // lldb_private::Process so it is ok to do this.
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00002952 size = max_memory_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002953 }
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002954
Pavel Labath16064d32018-03-20 11:56:24 +00002955 StreamGDBRemote packet;
2956
2957 MemoryRegionInfo region;
2958 Status region_status = GetMemoryRegionInfo(addr, region);
2959
2960 bool is_flash =
2961 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2962
2963 if (is_flash) {
2964 if (!m_allow_flash_writes) {
2965 error.SetErrorString("Writing to flash memory is not allowed");
2966 return 0;
2967 }
2968 // Keep the write within a flash memory region
2969 if (addr + size > region.GetRange().GetRangeEnd())
2970 size = region.GetRange().GetRangeEnd() - addr;
2971 // Flash memory must be erased before it can be written
2972 error = FlashErase(addr, size);
2973 if (!error.Success())
2974 return 0;
2975 packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
2976 packet.PutEscapedBytes(buf, size);
2977 } else {
2978 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2979 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2980 endian::InlHostByteOrder());
2981 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002983 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2984 true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002985 GDBRemoteCommunication::PacketResult::Success) {
2986 if (response.IsOKResponse()) {
2987 error.Clear();
2988 return size;
2989 } else if (response.IsErrorResponse())
2990 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2991 addr);
2992 else if (response.IsUnsupportedResponse())
2993 error.SetErrorStringWithFormat(
2994 "GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002995 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002996 error.SetErrorStringWithFormat(
2997 "unexpected response to GDB server memory write packet '%s': '%s'",
Zachary Turnerc1564272016-11-16 21:15:24 +00002998 packet.GetData(), response.GetStringRef().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002999 } else {
3000 error.SetErrorStringWithFormat("failed to send packet: '%s'",
Zachary Turnerc1564272016-11-16 21:15:24 +00003001 packet.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003002 }
3003 return 0;
3004}
3005
3006lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
3007 uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00003008 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003009 Log *log(
3010 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS));
3011 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3012
3013 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
3014 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
3015 if (allocated_addr != LLDB_INVALID_ADDRESS ||
3016 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3017 return allocated_addr;
3018 }
3019
3020 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
3021 // Call mmap() to create memory in the inferior..
3022 unsigned prot = 0;
3023 if (permissions & lldb::ePermissionsReadable)
3024 prot |= eMmapProtRead;
3025 if (permissions & lldb::ePermissionsWritable)
3026 prot |= eMmapProtWrite;
3027 if (permissions & lldb::ePermissionsExecutable)
3028 prot |= eMmapProtExec;
3029
3030 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3031 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3032 m_addr_to_mmap_size[allocated_addr] = size;
3033 else {
3034 allocated_addr = LLDB_INVALID_ADDRESS;
3035 if (log)
3036 log->Printf("ProcessGDBRemote::%s no direct stub support for memory "
3037 "allocation, and InferiorCallMmap also failed - is stub "
3038 "missing register context save/restore capability?",
3039 __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003040 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003041 }
3042
3043 if (allocated_addr == LLDB_INVALID_ADDRESS)
3044 error.SetErrorStringWithFormat(
3045 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
3046 (uint64_t)size, GetPermissionsAsCString(permissions));
3047 else
3048 error.Clear();
3049 return allocated_addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003050}
3051
Zachary Turner97206d52017-05-12 04:51:55 +00003052Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr,
3053 MemoryRegionInfo &region_info) {
Ed Maste81b4c5f2016-01-04 01:43:47 +00003054
Zachary Turner97206d52017-05-12 04:51:55 +00003055 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003056 return error;
3057}
3058
Zachary Turner97206d52017-05-12 04:51:55 +00003059Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003060
Zachary Turner97206d52017-05-12 04:51:55 +00003061 Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003062 return error;
3063}
3064
Zachary Turner97206d52017-05-12 04:51:55 +00003065Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
3066 Status error(m_gdb_comm.GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003067 num, after, GetTarget().GetArchitecture()));
3068 return error;
3069}
3070
Zachary Turner97206d52017-05-12 04:51:55 +00003071Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
3072 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003073 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3074
3075 switch (supported) {
3076 case eLazyBoolCalculate:
3077 // We should never be deallocating memory without allocating memory
3078 // first so we should never get eLazyBoolCalculate
3079 error.SetErrorString(
3080 "tried to deallocate memory without ever allocating memory");
3081 break;
3082
3083 case eLazyBoolYes:
3084 if (!m_gdb_comm.DeallocateMemory(addr))
3085 error.SetErrorStringWithFormat(
3086 "unable to deallocate memory at 0x%" PRIx64, addr);
3087 break;
3088
3089 case eLazyBoolNo:
3090 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2a48f522011-05-14 01:50:35 +00003091 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003092 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3093 if (pos != m_addr_to_mmap_size.end() &&
3094 InferiorCallMunmap(this, addr, pos->second))
3095 m_addr_to_mmap_size.erase(pos);
3096 else
3097 error.SetErrorStringWithFormat(
3098 "unable to deallocate memory at 0x%" PRIx64, addr);
Greg Claytoncec91ef2016-02-26 01:20:20 +00003099 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003100 break;
3101 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003102
Kate Stoneb9c1b512016-09-06 20:57:50 +00003103 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003104}
3105
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003106//------------------------------------------------------------------
3107// Process STDIO
3108//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003109size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00003110 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003111 if (m_stdio_communication.IsConnected()) {
3112 ConnectionStatus status;
3113 m_stdio_communication.Write(src, src_len, status, NULL);
3114 } else if (m_stdin_forward) {
3115 m_gdb_comm.SendStdinNotification(src, src_len);
3116 }
3117 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003118}
3119
Zachary Turner97206d52017-05-12 04:51:55 +00003120Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
3121 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003122 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003123
Kate Stoneb9c1b512016-09-06 20:57:50 +00003124 // Get logging info
3125 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3126 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003127
Kate Stoneb9c1b512016-09-06 20:57:50 +00003128 // Get the breakpoint address
3129 const addr_t addr = bp_site->GetLoadAddress();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003130
Kate Stoneb9c1b512016-09-06 20:57:50 +00003131 // Log that a breakpoint was requested
3132 if (log)
3133 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3134 ") address = 0x%" PRIx64,
3135 site_id, (uint64_t)addr);
3136
3137 // Breakpoint already exists and is enabled
3138 if (bp_site->IsEnabled()) {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003139 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003140 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3141 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3142 site_id, (uint64_t)addr);
3143 return error;
3144 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003145
Kate Stoneb9c1b512016-09-06 20:57:50 +00003146 // Get the software breakpoint trap opcode size
3147 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3148
3149 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
3150 // breakpoint type
3151 // is supported by the remote stub. These are set to true by default, and
3152 // later set to false
3153 // only after we receive an unimplemented response when sending a breakpoint
3154 // packet. This means
3155 // initially that unless we were specifically instructed to use a hardware
3156 // breakpoint, LLDB will
3157 // attempt to set a software breakpoint. HardwareRequired() also queries a
3158 // boolean variable which
3159 // indicates if the user specifically asked for hardware breakpoints. If true
3160 // then we will
3161 // skip over software breakpoints.
3162 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3163 (!bp_site->HardwareRequired())) {
3164 // Try to send off a software breakpoint packet ($Z0)
3165 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3166 eBreakpointSoftware, true, addr, bp_op_size);
3167 if (error_no == 0) {
3168 // The breakpoint was placed successfully
3169 bp_site->SetEnabled(true);
3170 bp_site->SetType(BreakpointSite::eExternal);
3171 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003172 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003173
Kate Stoneb9c1b512016-09-06 20:57:50 +00003174 // SendGDBStoppointTypePacket() will return an error if it was unable to set
3175 // this
3176 // breakpoint. We need to differentiate between a error specific to placing
3177 // this breakpoint
3178 // or if we have learned that this breakpoint type is unsupported. To do
3179 // this, we
3180 // must test the support boolean for this breakpoint type to see if it now
3181 // indicates that
3182 // this breakpoint type is unsupported. If they are still supported then we
3183 // should return
3184 // with the error code. If they are now unsupported, then we would like to
3185 // fall through
3186 // and try another form of breakpoint.
3187 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3188 if (error_no != UINT8_MAX)
3189 error.SetErrorStringWithFormat(
3190 "error: %d sending the breakpoint request", errno);
3191 else
3192 error.SetErrorString("error sending the breakpoint request");
3193 return error;
3194 }
3195
3196 // We reach here when software breakpoints have been found to be
3197 // unsupported. For future
3198 // calls to set a breakpoint, we will not attempt to set a breakpoint with a
3199 // type that is
3200 // known not to be supported.
3201 if (log)
3202 log->Printf("Software breakpoints are unsupported");
3203
3204 // So we will fall through and try a hardware breakpoint
3205 }
3206
3207 // The process of setting a hardware breakpoint is much the same as above. We
3208 // check the
3209 // supported boolean for this breakpoint type, and if it is thought to be
3210 // supported then we
3211 // will try to set this breakpoint with a hardware breakpoint.
3212 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3213 // Try to send off a hardware breakpoint packet ($Z1)
3214 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3215 eBreakpointHardware, true, addr, bp_op_size);
3216 if (error_no == 0) {
3217 // The breakpoint was placed successfully
3218 bp_site->SetEnabled(true);
3219 bp_site->SetType(BreakpointSite::eHardware);
3220 return error;
3221 }
3222
3223 // Check if the error was something other then an unsupported breakpoint
3224 // type
3225 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3226 // Unable to set this hardware breakpoint
3227 if (error_no != UINT8_MAX)
3228 error.SetErrorStringWithFormat(
3229 "error: %d sending the hardware breakpoint request "
3230 "(hardware breakpoint resources might be exhausted or unavailable)",
3231 error_no);
3232 else
3233 error.SetErrorString("error sending the hardware breakpoint request "
3234 "(hardware breakpoint resources "
3235 "might be exhausted or unavailable)");
3236 return error;
3237 }
3238
3239 // We will reach here when the stub gives an unsupported response to a
3240 // hardware breakpoint
3241 if (log)
3242 log->Printf("Hardware breakpoints are unsupported");
3243
3244 // Finally we will falling through to a #trap style breakpoint
3245 }
3246
3247 // Don't fall through when hardware breakpoints were specifically requested
3248 if (bp_site->HardwareRequired()) {
3249 error.SetErrorString("hardware breakpoints are not supported");
3250 return error;
3251 }
3252
3253 // As a last resort we want to place a manual breakpoint. An instruction
3254 // is placed into the process memory using memory write packets.
3255 return EnableSoftwareBreakpoint(bp_site);
3256}
3257
Zachary Turner97206d52017-05-12 04:51:55 +00003258Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3259 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003260 assert(bp_site != NULL);
3261 addr_t addr = bp_site->GetLoadAddress();
3262 user_id_t site_id = bp_site->GetID();
3263 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3264 if (log)
3265 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3266 ") addr = 0x%8.8" PRIx64,
3267 site_id, (uint64_t)addr);
3268
3269 if (bp_site->IsEnabled()) {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003270 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3271
Kate Stoneb9c1b512016-09-06 20:57:50 +00003272 BreakpointSite::Type bp_type = bp_site->GetType();
3273 switch (bp_type) {
3274 case BreakpointSite::eSoftware:
3275 error = DisableSoftwareBreakpoint(bp_site);
3276 break;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003277
Kate Stoneb9c1b512016-09-06 20:57:50 +00003278 case BreakpointSite::eHardware:
3279 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3280 addr, bp_op_size))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003281 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003282 break;
3283
3284 case BreakpointSite::eExternal: {
3285 GDBStoppointType stoppoint_type;
3286 if (bp_site->IsHardware())
3287 stoppoint_type = eBreakpointHardware;
3288 else
3289 stoppoint_type = eBreakpointSoftware;
3290
3291 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr,
3292 bp_op_size))
3293 error.SetErrorToGenericError();
3294 } break;
3295 }
3296 if (error.Success())
3297 bp_site->SetEnabled(false);
3298 } else {
3299 if (log)
3300 log->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3301 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3302 site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003303 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003304 }
3305
3306 if (error.Success())
3307 error.SetErrorToGenericError();
3308 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003309}
3310
Johnny Chen11309a32011-09-06 22:38:36 +00003311// Pre-requisite: wp != NULL.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003312static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3313 assert(wp);
3314 bool watch_read = wp->WatchpointRead();
3315 bool watch_write = wp->WatchpointWrite();
Johnny Chen11309a32011-09-06 22:38:36 +00003316
Kate Stoneb9c1b512016-09-06 20:57:50 +00003317 // watch_read and watch_write cannot both be false.
3318 assert(watch_read || watch_write);
3319 if (watch_read && watch_write)
3320 return eWatchpointReadWrite;
3321 else if (watch_read)
3322 return eWatchpointRead;
3323 else // Must be watch_write, then.
3324 return eWatchpointWrite;
Johnny Chen11309a32011-09-06 22:38:36 +00003325}
3326
Zachary Turner97206d52017-05-12 04:51:55 +00003327Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3328 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003329 if (wp) {
3330 user_id_t watchID = wp->GetID();
3331 addr_t addr = wp->GetLoadAddress();
3332 Log *log(
3333 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003334 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003335 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3336 watchID);
3337 if (wp->IsEnabled()) {
3338 if (log)
3339 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3340 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3341 watchID, (uint64_t)addr);
3342 return error;
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003343 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003344
3345 GDBStoppointType type = GetGDBStoppointType(wp);
3346 // Pass down an appropriate z/Z packet...
3347 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3348 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3349 wp->GetByteSize()) == 0) {
3350 wp->SetEnabled(true, notify);
3351 return error;
3352 } else
3353 error.SetErrorString("sending gdb watchpoint packet failed");
3354 } else
3355 error.SetErrorString("watchpoints not supported");
3356 } else {
3357 error.SetErrorString("Watchpoint argument was NULL.");
3358 }
3359 if (error.Success())
3360 error.SetErrorToGenericError();
3361 return error;
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003362}
Kate Stoneb9c1b512016-09-06 20:57:50 +00003363
Zachary Turner97206d52017-05-12 04:51:55 +00003364Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3365 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003366 if (wp) {
3367 user_id_t watchID = wp->GetID();
3368
3369 Log *log(
3370 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3371
3372 addr_t addr = wp->GetLoadAddress();
3373
3374 if (log)
3375 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3376 ") addr = 0x%8.8" PRIx64,
3377 watchID, (uint64_t)addr);
3378
3379 if (!wp->IsEnabled()) {
3380 if (log)
3381 log->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3382 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3383 watchID, (uint64_t)addr);
3384 // See also 'class WatchpointSentry' within StopInfo.cpp.
3385 // This disabling attempt might come from the user-supplied actions, we'll
3386 // route it in order for
3387 // the watchpoint object to intelligently process this action.
3388 wp->SetEnabled(false, notify);
3389 return error;
3390 }
3391
3392 if (wp->IsHardware()) {
3393 GDBStoppointType type = GetGDBStoppointType(wp);
3394 // Pass down an appropriate z/Z packet...
3395 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3396 wp->GetByteSize()) == 0) {
3397 wp->SetEnabled(false, notify);
3398 return error;
3399 } else
3400 error.SetErrorString("sending gdb watchpoint packet failed");
3401 }
3402 // TODO: clear software watchpoints if we implement them
3403 } else {
3404 error.SetErrorString("Watchpoint argument was NULL.");
3405 }
3406 if (error.Success())
3407 error.SetErrorToGenericError();
3408 return error;
3409}
3410
3411void ProcessGDBRemote::Clear() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003412 m_thread_list_real.Clear();
3413 m_thread_list.Clear();
3414}
3415
Zachary Turner97206d52017-05-12 04:51:55 +00003416Status ProcessGDBRemote::DoSignal(int signo) {
3417 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003418 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3419 if (log)
3420 log->Printf("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3421
3422 if (!m_gdb_comm.SendAsyncSignal(signo))
3423 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3424 return error;
3425}
3426
Zachary Turner97206d52017-05-12 04:51:55 +00003427Status
3428ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003429 // Make sure we aren't already connected?
3430 if (m_gdb_comm.IsConnected())
Zachary Turner97206d52017-05-12 04:51:55 +00003431 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003432
3433 PlatformSP platform_sp(GetTarget().GetPlatform());
3434 if (platform_sp && !platform_sp->IsHost())
Zachary Turner97206d52017-05-12 04:51:55 +00003435 return Status("Lost debug server connection");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003436
3437 auto error = LaunchAndConnectToDebugserver(process_info);
3438 if (error.Fail()) {
3439 const char *error_string = error.AsCString();
3440 if (error_string == nullptr)
3441 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3442 }
3443 return error;
3444}
Eugene Zemtsov30153412017-09-25 17:41:16 +00003445#if !defined(_WIN32)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003446#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3447#endif
3448
3449#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Kate Stoneb9c1b512016-09-06 20:57:50 +00003450static bool SetCloexecFlag(int fd) {
3451#if defined(FD_CLOEXEC)
3452 int flags = ::fcntl(fd, F_GETFD);
3453 if (flags == -1)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003454 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003455 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3456#else
3457 return false;
Greg Claytonc6c420f2016-08-12 16:46:18 +00003458#endif
3459}
3460#endif
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003461
Zachary Turner97206d52017-05-12 04:51:55 +00003462Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003463 const ProcessInfo &process_info) {
3464 using namespace std::placeholders; // For _1, _2, etc.
Pavel Labath998bdc52016-05-11 16:59:04 +00003465
Zachary Turner97206d52017-05-12 04:51:55 +00003466 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003467 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3468 // If we locate debugserver, keep that located version around
3469 static FileSpec g_debugserver_file_spec;
3470
3471 ProcessLaunchInfo debugserver_launch_info;
3472 // Make debugserver run in its own session so signals generated by
3473 // special terminal key sequences (^C) don't affect debugserver.
3474 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3475
3476 const std::weak_ptr<ProcessGDBRemote> this_wp =
3477 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3478 debugserver_launch_info.SetMonitorProcessCallback(
3479 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false);
3480 debugserver_launch_info.SetUserID(process_info.GetUserID());
3481
3482 int communication_fd = -1;
3483#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
Eugene Zemtsov30153412017-09-25 17:41:16 +00003484 // Use a socketpair on non-Windows systems for security and performance
3485 // reasons.
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003486 int sockets[2]; /* the pair of socket descriptors */
3487 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3488 error.SetErrorToErrno();
3489 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003490 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003491
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003492 int our_socket = sockets[0];
3493 int gdb_socket = sockets[1];
3494 CleanUp cleanup_our(close, our_socket);
3495 CleanUp cleanup_gdb(close, gdb_socket);
3496
Kate Stoneb9c1b512016-09-06 20:57:50 +00003497 // Don't let any child processes inherit our communication socket
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003498 SetCloexecFlag(our_socket);
3499 communication_fd = gdb_socket;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003500#endif
3501
3502 error = m_gdb_comm.StartDebugserverProcess(
3503 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3504 nullptr, nullptr, communication_fd);
3505
3506 if (error.Success())
3507 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3508 else
3509 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3510
3511 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3512#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3513 // Our process spawned correctly, we can now set our connection to use our
3514 // end of the socket pair
Vedant Kumarebc6bc82018-02-23 22:08:38 +00003515 cleanup_our.disable();
3516 m_gdb_comm.SetConnection(new ConnectionFileDescriptor(our_socket, true));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003517#endif
3518 StartAsyncThread();
3519 }
3520
3521 if (error.Fail()) {
3522 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3523
3524 if (log)
3525 log->Printf("failed to start debugserver process: %s",
3526 error.AsCString());
3527 return error;
3528 }
3529
3530 if (m_gdb_comm.IsConnected()) {
3531 // Finish the connection process by doing the handshake without connecting
3532 // (send NULL URL)
Zachary Turner31659452016-11-17 21:15:14 +00003533 ConnectToDebugserver("");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003534 } else {
3535 error.SetErrorString("connection failed");
3536 }
3537 }
3538 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003539}
3540
Kate Stoneb9c1b512016-09-06 20:57:50 +00003541bool ProcessGDBRemote::MonitorDebugserverProcess(
3542 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3543 bool exited, // True if the process did exit
3544 int signo, // Zero for no signal
3545 int exit_status // Exit value of process if signal is zero
3546 ) {
3547 // "debugserver_pid" argument passed in is the process ID for
3548 // debugserver that we are tracking...
3549 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3550 const bool handled = true;
Greg Claytone4e45922011-11-16 05:37:56 +00003551
Kate Stoneb9c1b512016-09-06 20:57:50 +00003552 if (log)
3553 log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3554 ", signo=%i (0x%x), exit_status=%i)",
3555 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
Greg Clayton6779606a2011-01-22 23:43:18 +00003556
Kate Stoneb9c1b512016-09-06 20:57:50 +00003557 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3558 if (log)
3559 log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3560 static_cast<void *>(process_sp.get()));
3561 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
Pavel Labath194357c2016-05-12 11:10:01 +00003562 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003563
Kate Stoneb9c1b512016-09-06 20:57:50 +00003564 // Sleep for a half a second to make sure our inferior process has
3565 // time to set its exit status before we set it incorrectly when
3566 // both the debugserver and the inferior process shut down.
3567 usleep(500000);
3568 // If our process hasn't yet exited, debugserver might have died.
3569 // If the process did exit, then we are reaping it.
3570 const StateType state = process_sp->GetState();
3571
3572 if (state != eStateInvalid && state != eStateUnloaded &&
3573 state != eStateExited && state != eStateDetached) {
3574 char error_str[1024];
3575 if (signo) {
3576 const char *signal_cstr =
3577 process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3578 if (signal_cstr)
3579 ::snprintf(error_str, sizeof(error_str),
3580 DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3581 else
3582 ::snprintf(error_str, sizeof(error_str),
3583 DEBUGSERVER_BASENAME " died with signal %i", signo);
3584 } else {
3585 ::snprintf(error_str, sizeof(error_str),
3586 DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3587 exit_status);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003588 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003589
3590 process_sp->SetExitStatus(-1, error_str);
3591 }
3592 // Debugserver has exited we need to let our ProcessGDBRemote
3593 // know that it no longer has a debugserver instance
3594 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3595 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003596}
3597
Kate Stoneb9c1b512016-09-06 20:57:50 +00003598void ProcessGDBRemote::KillDebugserverProcess() {
3599 m_gdb_comm.Disconnect();
3600 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3601 Host::Kill(m_debugserver_pid, SIGINT);
3602 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3603 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003604}
3605
Kate Stoneb9c1b512016-09-06 20:57:50 +00003606void ProcessGDBRemote::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +00003607 static llvm::once_flag g_once_flag;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003608
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +00003609 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003610 PluginManager::RegisterPlugin(GetPluginNameStatic(),
3611 GetPluginDescriptionStatic(), CreateInstance,
3612 DebuggerInitialize);
3613 });
Greg Clayton7f982402013-07-15 22:54:20 +00003614}
3615
Kate Stoneb9c1b512016-09-06 20:57:50 +00003616void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3617 if (!PluginManager::GetSettingForProcessPlugin(
3618 debugger, PluginProperties::GetSettingName())) {
3619 const bool is_global_setting = true;
3620 PluginManager::CreateSettingForProcessPlugin(
3621 debugger, GetGlobalPluginProperties()->GetValueProperties(),
3622 ConstString("Properties for the gdb-remote process plug-in."),
3623 is_global_setting);
3624 }
3625}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003626
Kate Stoneb9c1b512016-09-06 20:57:50 +00003627bool ProcessGDBRemote::StartAsyncThread() {
3628 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3629
3630 if (log)
3631 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3632
3633 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3634 if (!m_async_thread.IsJoinable()) {
3635 // Create a thread that watches our internal state and controls which
3636 // events make it to clients (into the DCProcess event queue).
3637
3638 m_async_thread =
3639 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>",
3640 ProcessGDBRemote::AsyncThread, this, NULL);
3641 } else if (log)
3642 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
3643 "already running.",
3644 __FUNCTION__);
3645
3646 return m_async_thread.IsJoinable();
3647}
3648
3649void ProcessGDBRemote::StopAsyncThread() {
3650 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3651
3652 if (log)
3653 log->Printf("ProcessGDBRemote::%s ()", __FUNCTION__);
3654
3655 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3656 if (m_async_thread.IsJoinable()) {
3657 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3658
3659 // This will shut down the async thread.
3660 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3661
3662 // Stop the stdio thread
3663 m_async_thread.Join(nullptr);
3664 m_async_thread.Reset();
3665 } else if (log)
3666 log->Printf(
3667 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3668 __FUNCTION__);
3669}
3670
3671bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) {
3672 // get the packet at a string
3673 const std::string &pkt = packet.GetStringRef();
3674 // skip %stop:
3675 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3676
3677 // pass as a thread stop info packet
3678 SetLastStopPacket(stop_info);
3679
3680 // check for more stop reasons
3681 HandleStopReplySequence();
3682
3683 // if the process is stopped then we need to fake a resume
3684 // so that we can stop properly with the new break. This
3685 // is possible due to SetPrivateState() broadcasting the
3686 // state change as a side effect.
3687 if (GetPrivateState() == lldb::StateType::eStateStopped) {
3688 SetPrivateState(lldb::StateType::eStateRunning);
3689 }
3690
3691 // since we have some stopped packets we can halt the process
3692 SetPrivateState(lldb::StateType::eStateStopped);
3693
3694 return true;
3695}
3696
3697thread_result_t ProcessGDBRemote::AsyncThread(void *arg) {
3698 ProcessGDBRemote *process = (ProcessGDBRemote *)arg;
3699
3700 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3701 if (log)
3702 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3703 ") thread starting...",
3704 __FUNCTION__, arg, process->GetID());
3705
3706 EventSP event_sp;
3707 bool done = false;
3708 while (!done) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003709 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003710 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3711 ") listener.WaitForEvent (NULL, event_sp)...",
3712 __FUNCTION__, arg, process->GetID());
Pavel Labathd35031e12016-11-30 10:41:42 +00003713 if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003714 const uint32_t event_type = event_sp->GetType();
3715 if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) {
Pavel Labath50556852015-09-03 09:36:22 +00003716 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003717 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3718 ") Got an event of type: %d...",
3719 __FUNCTION__, arg, process->GetID(), event_type);
Pavel Labath50556852015-09-03 09:36:22 +00003720
Kate Stoneb9c1b512016-09-06 20:57:50 +00003721 switch (event_type) {
3722 case eBroadcastBitAsyncContinue: {
3723 const EventDataBytes *continue_packet =
3724 EventDataBytes::GetEventDataFromEvent(event_sp.get());
Pavel Labath50556852015-09-03 09:36:22 +00003725
Kate Stoneb9c1b512016-09-06 20:57:50 +00003726 if (continue_packet) {
3727 const char *continue_cstr =
3728 (const char *)continue_packet->GetBytes();
3729 const size_t continue_cstr_len = continue_packet->GetByteSize();
Pavel Labath50556852015-09-03 09:36:22 +00003730 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003731 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3732 ") got eBroadcastBitAsyncContinue: %s",
3733 __FUNCTION__, arg, process->GetID(), continue_cstr);
3734
3735 if (::strstr(continue_cstr, "vAttach") == NULL)
3736 process->SetPrivateState(eStateRunning);
3737 StringExtractorGDBRemote response;
3738
3739 // If in Non-Stop-Mode
3740 if (process->GetTarget().GetNonStopModeEnabled()) {
3741 // send the vCont packet
3742 if (!process->GetGDBRemote().SendvContPacket(
3743 llvm::StringRef(continue_cstr, continue_cstr_len),
3744 response)) {
3745 // Something went wrong
3746 done = true;
3747 break;
3748 }
3749 }
3750 // If in All-Stop-Mode
3751 else {
3752 StateType stop_state =
3753 process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3754 *process, *process->GetUnixSignals(),
3755 llvm::StringRef(continue_cstr, continue_cstr_len),
3756 response);
3757
3758 // We need to immediately clear the thread ID list so we are sure
3759 // to get a valid list of threads.
3760 // The thread ID list might be contained within the "response", or
3761 // the stop reply packet that
3762 // caused the stop. So clear it now before we give the stop reply
3763 // packet to the process
3764 // using the process->SetLastStopPacket()...
3765 process->ClearThreadIDList();
3766
3767 switch (stop_state) {
3768 case eStateStopped:
3769 case eStateCrashed:
3770 case eStateSuspended:
3771 process->SetLastStopPacket(response);
3772 process->SetPrivateState(stop_state);
3773 break;
3774
3775 case eStateExited: {
3776 process->SetLastStopPacket(response);
3777 process->ClearThreadIDList();
3778 response.SetFilePos(1);
3779
3780 int exit_status = response.GetHexU8();
3781 std::string desc_string;
3782 if (response.GetBytesLeft() > 0 &&
3783 response.GetChar('-') == ';') {
3784 llvm::StringRef desc_str;
3785 llvm::StringRef desc_token;
3786 while (response.GetNameColonValue(desc_token, desc_str)) {
3787 if (desc_token != "description")
3788 continue;
3789 StringExtractor extractor(desc_str);
3790 extractor.GetHexByteString(desc_string);
3791 }
3792 }
3793 process->SetExitStatus(exit_status, desc_string.c_str());
3794 done = true;
3795 break;
3796 }
3797 case eStateInvalid: {
3798 // Check to see if we were trying to attach and if we got back
3799 // the "E87" error code from debugserver -- this indicates that
3800 // the process is not debuggable. Return a slightly more
3801 // helpful
3802 // error message about why the attach failed.
3803 if (::strstr(continue_cstr, "vAttach") != NULL &&
3804 response.GetError() == 0x87) {
3805 process->SetExitStatus(-1, "cannot attach to process due to "
3806 "System Integrity Protection");
3807 }
3808 // E01 code from vAttach means that the attach failed
3809 if (::strstr(continue_cstr, "vAttach") != NULL &&
3810 response.GetError() == 0x1) {
3811 process->SetExitStatus(-1, "unable to attach");
3812 } else {
3813 process->SetExitStatus(-1, "lost connection");
3814 }
3815 break;
3816 }
3817
3818 default:
3819 process->SetPrivateState(stop_state);
3820 break;
3821 } // switch(stop_state)
3822 } // else // if in All-stop-mode
3823 } // if (continue_packet)
3824 } // case eBroadcastBitAysncContinue
3825 break;
3826
3827 case eBroadcastBitAsyncThreadShouldExit:
3828 if (log)
3829 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3830 ") got eBroadcastBitAsyncThreadShouldExit...",
3831 __FUNCTION__, arg, process->GetID());
3832 done = true;
3833 break;
3834
3835 default:
3836 if (log)
3837 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3838 ") got unknown event 0x%8.8x",
3839 __FUNCTION__, arg, process->GetID(), event_type);
3840 done = true;
3841 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003842 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003843 } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) {
3844 switch (event_type) {
3845 case Communication::eBroadcastBitReadThreadDidExit:
3846 process->SetExitStatus(-1, "lost connection");
3847 done = true;
3848 break;
3849
3850 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: {
3851 lldb_private::Event *event = event_sp.get();
3852 const EventDataBytes *continue_packet =
3853 EventDataBytes::GetEventDataFromEvent(event);
3854 StringExtractorGDBRemote notify(
3855 (const char *)continue_packet->GetBytes());
3856 // Hand this over to the process to handle
3857 process->HandleNotifyPacket(notify);
3858 break;
3859 }
3860
3861 default:
3862 if (log)
3863 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3864 ") got unknown event 0x%8.8x",
3865 __FUNCTION__, arg, process->GetID(), event_type);
3866 done = true;
3867 break;
3868 }
3869 }
3870 } else {
3871 if (log)
3872 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3873 ") listener.WaitForEvent (NULL, event_sp) => false",
3874 __FUNCTION__, arg, process->GetID());
3875 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003876 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003877 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003878
Kate Stoneb9c1b512016-09-06 20:57:50 +00003879 if (log)
3880 log->Printf("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64
3881 ") thread exiting...",
3882 __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003883
Kate Stoneb9c1b512016-09-06 20:57:50 +00003884 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003885}
3886
Kate Stoneb9c1b512016-09-06 20:57:50 +00003887// uint32_t
3888// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3889// &matches, std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00003890//{
Kate Stoneb9c1b512016-09-06 20:57:50 +00003891// // If we are planning to launch the debugserver remotely, then we need to
3892// fire up a debugserver
3893// // process and ask it for the list of processes. But if we are local, we
3894// can let the Host do it.
Greg Claytone996fd32011-03-08 22:40:15 +00003895// if (m_local_debugserver)
3896// {
3897// return Host::ListProcessesMatchingName (name, matches, pids);
3898// }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003899// else
Greg Claytone996fd32011-03-08 22:40:15 +00003900// {
3901// // FIXME: Implement talking to the remote debugserver.
3902// return 0;
3903// }
3904//
3905//}
3906//
Kate Stoneb9c1b512016-09-06 20:57:50 +00003907bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3908 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3909 lldb::user_id_t break_loc_id) {
3910 // I don't think I have to do anything here, just make sure I notice the new
3911 // thread when it starts to
3912 // run so I can stop it if that's what I want to do.
3913 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3914 if (log)
3915 log->Printf("Hit New Thread Notification breakpoint.");
3916 return false;
Jim Ingham1c823b42011-01-22 01:33:44 +00003917}
3918
Zachary Turner97206d52017-05-12 04:51:55 +00003919Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003920 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3921 LLDB_LOG(log, "Check if need to update ignored signals");
3922
3923 // QPassSignals package is not supported by the server,
3924 // there is no way we can ignore any signals on server side.
3925 if (!m_gdb_comm.GetQPassSignalsSupported())
Zachary Turner97206d52017-05-12 04:51:55 +00003926 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003927
3928 // No signals, nothing to send.
3929 if (m_unix_signals_sp == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00003930 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003931
3932 // Signals' version hasn't changed, no need to send anything.
3933 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3934 if (new_signals_version == m_last_signals_version) {
3935 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3936 m_last_signals_version);
Zachary Turner97206d52017-05-12 04:51:55 +00003937 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003938 }
3939
3940 auto signals_to_ignore =
3941 m_unix_signals_sp->GetFilteredSignals(false, false, false);
Zachary Turner97206d52017-05-12 04:51:55 +00003942 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003943
3944 LLDB_LOG(log,
3945 "Signals' version changed. old version={0}, new version={1}, "
3946 "signals ignored={2}, update result={3}",
3947 m_last_signals_version, new_signals_version,
3948 signals_to_ignore.size(), error);
3949
3950 if (error.Success())
3951 m_last_signals_version = new_signals_version;
3952
3953 return error;
3954}
3955
Kate Stoneb9c1b512016-09-06 20:57:50 +00003956bool ProcessGDBRemote::StartNoticingNewThreads() {
3957 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3958 if (m_thread_create_bp_sp) {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003959 if (log && log->GetVerbose())
Kate Stoneb9c1b512016-09-06 20:57:50 +00003960 log->Printf("Enabled noticing new thread breakpoint.");
3961 m_thread_create_bp_sp->SetEnabled(true);
3962 } else {
3963 PlatformSP platform_sp(GetTarget().GetPlatform());
3964 if (platform_sp) {
3965 m_thread_create_bp_sp =
3966 platform_sp->SetThreadCreationBreakpoint(GetTarget());
3967 if (m_thread_create_bp_sp) {
3968 if (log && log->GetVerbose())
3969 log->Printf(
3970 "Successfully created new thread notification breakpoint %i",
3971 m_thread_create_bp_sp->GetID());
3972 m_thread_create_bp_sp->SetCallback(
3973 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3974 } else {
3975 if (log)
3976 log->Printf("Failed to create new thread notification breakpoint.");
3977 }
Jason Molendaa3329782014-03-29 18:54:20 +00003978 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003979 }
3980 return m_thread_create_bp_sp.get() != NULL;
Jason Molendaa3329782014-03-29 18:54:20 +00003981}
3982
Kate Stoneb9c1b512016-09-06 20:57:50 +00003983bool ProcessGDBRemote::StopNoticingNewThreads() {
3984 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3985 if (log && log->GetVerbose())
3986 log->Printf("Disabling new thread notification breakpoint.");
3987
3988 if (m_thread_create_bp_sp)
3989 m_thread_create_bp_sp->SetEnabled(false);
3990
3991 return true;
3992}
3993
3994DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3995 if (m_dyld_ap.get() == NULL)
3996 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, NULL));
3997 return m_dyld_ap.get();
3998}
3999
Zachary Turner97206d52017-05-12 04:51:55 +00004000Status ProcessGDBRemote::SendEventData(const char *data) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004001 int return_value;
4002 bool was_supported;
4003
Zachary Turner97206d52017-05-12 04:51:55 +00004004 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004005
4006 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
4007 if (return_value != 0) {
4008 if (!was_supported)
4009 error.SetErrorString("Sending events is not supported for this process.");
4010 else
4011 error.SetErrorStringWithFormat("Error sending event data: %d.",
4012 return_value);
4013 }
4014 return error;
4015}
4016
4017const DataBufferSP ProcessGDBRemote::GetAuxvData() {
4018 DataBufferSP buf;
4019 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
4020 std::string response_string;
4021 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::",
4022 response_string) ==
4023 GDBRemoteCommunication::PacketResult::Success)
4024 buf.reset(new DataBufferHeap(response_string.c_str(),
4025 response_string.length()));
4026 }
4027 return buf;
Steve Pucci03904ac2014-03-04 23:18:46 +00004028}
4029
Jason Molenda705b1802014-06-13 02:37:02 +00004030StructuredData::ObjectSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004031ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
4032 StructuredData::ObjectSP object_sp;
Jason Molenda705b1802014-06-13 02:37:02 +00004033
Kate Stoneb9c1b512016-09-06 20:57:50 +00004034 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004035 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004036 SystemRuntime *runtime = GetSystemRuntime();
4037 if (runtime) {
4038 runtime->AddThreadExtendedInfoPacketHints(args_dict);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004039 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004040 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004041
Kate Stoneb9c1b512016-09-06 20:57:50 +00004042 StreamString packet;
4043 packet << "jThreadExtendedInfo:";
4044 args_dict->Dump(packet, false);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004045
Kate Stoneb9c1b512016-09-06 20:57:50 +00004046 // FIXME the final character of a JSON dictionary, '}', is the escape
4047 // character in gdb-remote binary mode. lldb currently doesn't escape
4048 // these characters in its packet output -- so we add the quoted version
4049 // of the } character here manually in case we talk to a debugserver which
4050 // un-escapes the characters at packet read time.
4051 packet << (char)(0x7d ^ 0x20);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004052
Kate Stoneb9c1b512016-09-06 20:57:50 +00004053 StringExtractorGDBRemote response;
4054 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004055 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4056 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004057 GDBRemoteCommunication::PacketResult::Success) {
4058 StringExtractorGDBRemote::ResponseType response_type =
4059 response.GetResponseType();
4060 if (response_type == StringExtractorGDBRemote::eResponse) {
4061 if (!response.Empty()) {
4062 object_sp = StructuredData::ParseJSON(response.GetStringRef());
Jason Molenda705b1802014-06-13 02:37:02 +00004063 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004064 }
Jason Molenda705b1802014-06-13 02:37:02 +00004065 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004066 }
4067 return object_sp;
Jason Molenda705b1802014-06-13 02:37:02 +00004068}
4069
Kate Stoneb9c1b512016-09-06 20:57:50 +00004070StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4071 lldb::addr_t image_list_address, lldb::addr_t image_count) {
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004072
Kate Stoneb9c1b512016-09-06 20:57:50 +00004073 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4074 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4075 image_list_address);
4076 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004077
Kate Stoneb9c1b512016-09-06 20:57:50 +00004078 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4079}
4080
4081StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
4082 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4083
4084 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4085
4086 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4087}
4088
4089StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
4090 const std::vector<lldb::addr_t> &load_addresses) {
4091 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4092 StructuredData::ArraySP addresses(new StructuredData::Array);
4093
4094 for (auto addr : load_addresses) {
4095 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
4096 addresses->AddItem(addr_sp);
4097 }
4098
4099 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4100
4101 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4102}
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004103
Jason Molenda37397352016-07-22 00:17:55 +00004104StructuredData::ObjectSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004105ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
4106 StructuredData::ObjectSP args_dict) {
4107 StructuredData::ObjectSP object_sp;
Jason Molenda37397352016-07-22 00:17:55 +00004108
Kate Stoneb9c1b512016-09-06 20:57:50 +00004109 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4110 // Scope for the scoped timeout object
Pavel Labath3aa04912016-10-31 17:19:42 +00004111 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
4112 std::chrono::seconds(10));
Jason Molenda37397352016-07-22 00:17:55 +00004113
Kate Stoneb9c1b512016-09-06 20:57:50 +00004114 StreamString packet;
4115 packet << "jGetLoadedDynamicLibrariesInfos:";
4116 args_dict->Dump(packet, false);
Jason Molenda37397352016-07-22 00:17:55 +00004117
Kate Stoneb9c1b512016-09-06 20:57:50 +00004118 // FIXME the final character of a JSON dictionary, '}', is the escape
4119 // character in gdb-remote binary mode. lldb currently doesn't escape
4120 // these characters in its packet output -- so we add the quoted version
4121 // of the } character here manually in case we talk to a debugserver which
4122 // un-escapes the characters at packet read time.
4123 packet << (char)(0x7d ^ 0x20);
4124
4125 StringExtractorGDBRemote response;
4126 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004127 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4128 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004129 GDBRemoteCommunication::PacketResult::Success) {
4130 StringExtractorGDBRemote::ResponseType response_type =
4131 response.GetResponseType();
4132 if (response_type == StringExtractorGDBRemote::eResponse) {
4133 if (!response.Empty()) {
4134 object_sp = StructuredData::ParseJSON(response.GetStringRef());
Jason Molenda37397352016-07-22 00:17:55 +00004135 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004136 }
Jason Molenda37397352016-07-22 00:17:55 +00004137 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004138 }
4139 return object_sp;
Jason Molenda37397352016-07-22 00:17:55 +00004140}
4141
Kate Stoneb9c1b512016-09-06 20:57:50 +00004142StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
4143 StructuredData::ObjectSP object_sp;
4144 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4145
4146 if (m_gdb_comm.GetSharedCacheInfoSupported()) {
4147 StreamString packet;
4148 packet << "jGetSharedCacheInfo:";
4149 args_dict->Dump(packet, false);
4150
4151 // FIXME the final character of a JSON dictionary, '}', is the escape
4152 // character in gdb-remote binary mode. lldb currently doesn't escape
4153 // these characters in its packet output -- so we add the quoted version
4154 // of the } character here manually in case we talk to a debugserver which
4155 // un-escapes the characters at packet read time.
4156 packet << (char)(0x7d ^ 0x20);
4157
4158 StringExtractorGDBRemote response;
4159 response.SetResponseValidatorToJSON();
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004160 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4161 false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00004162 GDBRemoteCommunication::PacketResult::Success) {
4163 StringExtractorGDBRemote::ResponseType response_type =
4164 response.GetResponseType();
4165 if (response_type == StringExtractorGDBRemote::eResponse) {
4166 if (!response.Empty()) {
4167 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4168 }
4169 }
4170 }
4171 }
4172 return object_sp;
4173}
4174
Zachary Turner97206d52017-05-12 04:51:55 +00004175Status ProcessGDBRemote::ConfigureStructuredData(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004176 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
4177 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
Todd Fiala75930012016-08-19 04:21:48 +00004178}
Jason Molenda37397352016-07-22 00:17:55 +00004179
Jason Molenda6076bf42014-05-06 04:34:52 +00004180// Establish the largest memory read/write payloads we should use.
4181// If the remote stub has a max packet size, stay under that size.
Ed Maste81b4c5f2016-01-04 01:43:47 +00004182//
4183// If the remote stub's max packet size is crazy large, use a
Jason Molenda6076bf42014-05-06 04:34:52 +00004184// reasonable largeish default.
4185//
4186// If the remote stub doesn't advertise a max packet size, use a
4187// conservative default.
4188
Kate Stoneb9c1b512016-09-06 20:57:50 +00004189void ProcessGDBRemote::GetMaxMemorySize() {
4190 const uint64_t reasonable_largeish_default = 128 * 1024;
4191 const uint64_t conservative_default = 512;
Jason Molenda6076bf42014-05-06 04:34:52 +00004192
Kate Stoneb9c1b512016-09-06 20:57:50 +00004193 if (m_max_memory_size == 0) {
4194 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4195 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4196 // Save the stub's claimed maximum packet size
4197 m_remote_stub_max_memory_size = stub_max_size;
Jason Molenda6076bf42014-05-06 04:34:52 +00004198
Kate Stoneb9c1b512016-09-06 20:57:50 +00004199 // Even if the stub says it can support ginormous packets,
4200 // don't exceed our reasonable largeish default packet size.
4201 if (stub_max_size > reasonable_largeish_default) {
4202 stub_max_size = reasonable_largeish_default;
4203 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004204
Hafiz Abid Qadeer68d7f372017-01-24 22:55:36 +00004205 // Memory packet have other overheads too like Maddr,size:#NN
4206 // Instead of calculating the bytes taken by size and addr every
4207 // time, we take a maximum guess here.
4208 if (stub_max_size > 70)
4209 stub_max_size -= 32 + 32 + 6;
4210 else {
4211 // In unlikely scenario that max packet size is less then 70, we will
4212 // hope that data being written is small enough to fit.
4213 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
4214 GDBR_LOG_COMM | GDBR_LOG_MEMORY));
4215 if (log)
4216 log->Warning("Packet size is too small. "
4217 "LLDB may face problems while writing memory");
4218 }
4219
Kate Stoneb9c1b512016-09-06 20:57:50 +00004220 m_max_memory_size = stub_max_size;
4221 } else {
4222 m_max_memory_size = conservative_default;
Jason Molenda6076bf42014-05-06 04:34:52 +00004223 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004224 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004225}
4226
Kate Stoneb9c1b512016-09-06 20:57:50 +00004227void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4228 uint64_t user_specified_max) {
4229 if (user_specified_max != 0) {
4230 GetMaxMemorySize();
Jason Molenda6076bf42014-05-06 04:34:52 +00004231
Kate Stoneb9c1b512016-09-06 20:57:50 +00004232 if (m_remote_stub_max_memory_size != 0) {
4233 if (m_remote_stub_max_memory_size < user_specified_max) {
4234 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
4235 // packet size too
4236 // big, go as big
4237 // as the remote stub says we can go.
4238 } else {
4239 m_max_memory_size = user_specified_max; // user's packet size is good
4240 }
4241 } else {
4242 m_max_memory_size =
4243 user_specified_max; // user's packet size is probably fine
Jason Molenda6076bf42014-05-06 04:34:52 +00004244 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004245 }
Jason Molenda6076bf42014-05-06 04:34:52 +00004246}
4247
Kate Stoneb9c1b512016-09-06 20:57:50 +00004248bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4249 const ArchSpec &arch,
4250 ModuleSpec &module_spec) {
4251 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004252
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004253 const ModuleCacheKey key(module_file_spec.GetPath(),
4254 arch.GetTriple().getTriple());
4255 auto cached = m_cached_module_specs.find(key);
4256 if (cached != m_cached_module_specs.end()) {
4257 module_spec = cached->second;
4258 return bool(module_spec);
4259 }
4260
Kate Stoneb9c1b512016-09-06 20:57:50 +00004261 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004262 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004263 log->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4264 __FUNCTION__, module_file_spec.GetPath().c_str(),
4265 arch.GetTriple().getTriple().c_str());
4266 return false;
4267 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004268
Kate Stoneb9c1b512016-09-06 20:57:50 +00004269 if (log) {
4270 StreamString stream;
4271 module_spec.Dump(stream);
4272 log->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4273 __FUNCTION__, module_file_spec.GetPath().c_str(),
Zachary Turnerc1564272016-11-16 21:15:24 +00004274 arch.GetTriple().getTriple().c_str(), stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004275 }
4276
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004277 m_cached_module_specs[key] = module_spec;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004278 return true;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004279}
4280
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004281void ProcessGDBRemote::PrefetchModuleSpecs(
4282 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4283 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4284 if (module_specs) {
4285 for (const FileSpec &spec : module_file_specs)
Pavel Labathcfc7ae62016-09-08 16:58:30 +00004286 m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4287 triple.getTriple())] = ModuleSpec();
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004288 for (const ModuleSpec &spec : *module_specs)
Pavel Labathcfc7ae62016-09-08 16:58:30 +00004289 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4290 triple.getTriple())] = spec;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00004291 }
4292}
4293
Kate Stoneb9c1b512016-09-06 20:57:50 +00004294bool ProcessGDBRemote::GetHostOSVersion(uint32_t &major, uint32_t &minor,
4295 uint32_t &update) {
4296 if (m_gdb_comm.GetOSVersion(major, minor, update))
4297 return true;
4298 // We failed to get the host OS version, defer to the base
4299 // implementation to correctly invalidate the arguments.
4300 return Process::GetHostOSVersion(major, minor, update);
Jim Ingham13c30d22015-11-05 22:33:17 +00004301}
4302
Colin Rileyc3c95b22015-04-16 15:51:33 +00004303namespace {
4304
4305typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004306
4307typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004308struct RegisterSetInfo {
4309 ConstString name;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004310};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004311
Greg Claytond04f0ed2015-05-26 18:00:51 +00004312typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004313
Kate Stoneb9c1b512016-09-06 20:57:50 +00004314struct GdbServerTargetInfo {
4315 std::string arch;
4316 std::string osabi;
4317 stringVec includes;
4318 RegisterSetMap reg_set_map;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004319};
Ed Maste81b4c5f2016-01-04 01:43:47 +00004320
Kate Stoneb9c1b512016-09-06 20:57:50 +00004321bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4322 GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp,
4323 uint32_t &cur_reg_num, uint32_t &reg_offset) {
4324 if (!feature_node)
4325 return false;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004326
Kate Stoneb9c1b512016-09-06 20:57:50 +00004327 feature_node.ForEachChildElementWithName(
4328 "reg", [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset,
4329 &abi_sp](const XMLNode &reg_node) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004330 std::string gdb_group;
4331 std::string gdb_type;
4332 ConstString reg_name;
4333 ConstString alt_name;
4334 ConstString set_name;
4335 std::vector<uint32_t> value_regs;
4336 std::vector<uint32_t> invalidate_regs;
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004337 std::vector<uint8_t> dwarf_opcode_bytes;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004338 bool encoding_set = false;
4339 bool format_set = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004340 RegisterInfo reg_info = {
4341 NULL, // Name
4342 NULL, // Alt name
4343 0, // byte size
4344 reg_offset, // offset
4345 eEncodingUint, // encoding
4346 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004347 {
Jason Molendabf67a302015-09-01 05:17:01 +00004348 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004349 LLDB_INVALID_REGNUM, // DWARF reg num
4350 LLDB_INVALID_REGNUM, // generic reg num
Kate Stoneb9c1b512016-09-06 20:57:50 +00004351 cur_reg_num, // process plugin reg num
4352 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004353 },
4354 NULL,
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004355 NULL,
Kate Stoneb9c1b512016-09-06 20:57:50 +00004356 NULL, // Dwarf Expression opcode bytes pointer
4357 0 // Dwarf Expression opcode bytes length
Greg Claytond04f0ed2015-05-26 18:00:51 +00004358 };
Ed Maste81b4c5f2016-01-04 01:43:47 +00004359
Kate Stoneb9c1b512016-09-06 20:57:50 +00004360 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4361 &reg_name, &alt_name, &set_name, &value_regs,
4362 &invalidate_regs, &encoding_set, &format_set,
Zachary Turner3bc714b2017-03-02 00:05:25 +00004363 &reg_info, &reg_offset, &dwarf_opcode_bytes](
Kate Stoneb9c1b512016-09-06 20:57:50 +00004364 const llvm::StringRef &name,
4365 const llvm::StringRef &value) -> bool {
4366 if (name == "name") {
4367 reg_name.SetString(value);
4368 } else if (name == "bitsize") {
4369 reg_info.byte_size =
4370 StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4371 } else if (name == "type") {
4372 gdb_type = value.str();
4373 } else if (name == "group") {
4374 gdb_group = value.str();
4375 } else if (name == "regnum") {
4376 const uint32_t regnum =
4377 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4378 if (regnum != LLDB_INVALID_REGNUM) {
4379 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004380 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004381 } else if (name == "offset") {
4382 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4383 } else if (name == "altname") {
4384 alt_name.SetString(value);
4385 } else if (name == "encoding") {
4386 encoding_set = true;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00004387 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004388 } else if (name == "format") {
4389 format_set = true;
4390 Format format = eFormatInvalid;
Pavel Labath47cbf4a2018-04-10 09:03:59 +00004391 if (OptionArgParser::ToFormat(value.data(), format, NULL).Success())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004392 reg_info.format = format;
4393 else if (value == "vector-sint8")
4394 reg_info.format = eFormatVectorOfSInt8;
4395 else if (value == "vector-uint8")
4396 reg_info.format = eFormatVectorOfUInt8;
4397 else if (value == "vector-sint16")
4398 reg_info.format = eFormatVectorOfSInt16;
4399 else if (value == "vector-uint16")
4400 reg_info.format = eFormatVectorOfUInt16;
4401 else if (value == "vector-sint32")
4402 reg_info.format = eFormatVectorOfSInt32;
4403 else if (value == "vector-uint32")
4404 reg_info.format = eFormatVectorOfUInt32;
4405 else if (value == "vector-float32")
4406 reg_info.format = eFormatVectorOfFloat32;
Valentina Giusticda0ae42016-09-08 14:16:45 +00004407 else if (value == "vector-uint64")
4408 reg_info.format = eFormatVectorOfUInt64;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004409 else if (value == "vector-uint128")
4410 reg_info.format = eFormatVectorOfUInt128;
4411 } else if (name == "group_id") {
4412 const uint32_t set_id =
4413 StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4414 RegisterSetMap::const_iterator pos =
4415 target_info.reg_set_map.find(set_id);
4416 if (pos != target_info.reg_set_map.end())
4417 set_name = pos->second.name;
4418 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4419 reg_info.kinds[eRegisterKindEHFrame] =
4420 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4421 } else if (name == "dwarf_regnum") {
4422 reg_info.kinds[eRegisterKindDWARF] =
4423 StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4424 } else if (name == "generic") {
4425 reg_info.kinds[eRegisterKindGeneric] =
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00004426 Args::StringToGenericRegister(value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004427 } else if (name == "value_regnums") {
4428 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4429 } else if (name == "invalidate_regnums") {
4430 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4431 } else if (name == "dynamic_size_dwarf_expr_bytes") {
4432 StringExtractor opcode_extractor;
4433 std::string opcode_string = value.str();
4434 size_t dwarf_opcode_len = opcode_string.length() / 2;
4435 assert(dwarf_opcode_len > 0);
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004436
Kate Stoneb9c1b512016-09-06 20:57:50 +00004437 dwarf_opcode_bytes.resize(dwarf_opcode_len);
4438 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4439 opcode_extractor.GetStringRef().swap(opcode_string);
4440 uint32_t ret_val =
4441 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
4442 assert(dwarf_opcode_len == ret_val);
Hafiz Abid Qadeer05008ca2017-01-19 15:11:01 +00004443 UNUSED_IF_ASSERT_DISABLED(ret_val);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004444 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
4445 } else {
4446 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4447 }
4448 return true; // Keep iterating through all attributes
Greg Claytond04f0ed2015-05-26 18:00:51 +00004449 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004450
Kate Stoneb9c1b512016-09-06 20:57:50 +00004451 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4452 if (gdb_type.find("int") == 0) {
4453 reg_info.format = eFormatHex;
4454 reg_info.encoding = eEncodingUint;
4455 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4456 reg_info.format = eFormatAddressInfo;
4457 reg_info.encoding = eEncodingUint;
4458 } else if (gdb_type == "i387_ext" || gdb_type == "float") {
4459 reg_info.format = eFormatFloat;
4460 reg_info.encoding = eEncodingIEEE754;
4461 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004462 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004463
Kate Stoneb9c1b512016-09-06 20:57:50 +00004464 // Only update the register set name if we didn't get a "reg_set"
4465 // attribute.
Greg Claytond04f0ed2015-05-26 18:00:51 +00004466 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4467 if (!set_name && !gdb_group.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004468 set_name.SetCString(gdb_group.c_str());
Ed Maste81b4c5f2016-01-04 01:43:47 +00004469
Greg Claytond04f0ed2015-05-26 18:00:51 +00004470 reg_info.byte_offset = reg_offset;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004471 assert(reg_info.byte_size != 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004472 reg_offset += reg_info.byte_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004473 if (!value_regs.empty()) {
4474 value_regs.push_back(LLDB_INVALID_REGNUM);
4475 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004476 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004477 if (!invalidate_regs.empty()) {
4478 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4479 reg_info.invalidate_regs = invalidate_regs.data();
Greg Claytond04f0ed2015-05-26 18:00:51 +00004480 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004481
Jason Molenda63bd0db2015-09-15 23:20:34 +00004482 ++cur_reg_num;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004483 AugmentRegisterInfoViaABI(reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004484 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004485
Greg Claytond04f0ed2015-05-26 18:00:51 +00004486 return true; // Keep iterating through all "reg" elements
Kate Stoneb9c1b512016-09-06 20:57:50 +00004487 });
4488 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004489}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004490
Eugene Zelenko0722f082015-10-24 01:28:05 +00004491} // namespace {}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004492
Colin Rileyc3c95b22015-04-16 15:51:33 +00004493// query the target of gdb-remote for extended target information
4494// return: 'true' on success
4495// 'false' on failure
Kate Stoneb9c1b512016-09-06 20:57:50 +00004496bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4497 // Make sure LLDB has an XML parser it can use first
4498 if (!XMLDocument::XMLEnabled())
4499 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004500
Kate Stoneb9c1b512016-09-06 20:57:50 +00004501 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004502
Kate Stoneb9c1b512016-09-06 20:57:50 +00004503 GDBRemoteCommunicationClient &comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004504
Kate Stoneb9c1b512016-09-06 20:57:50 +00004505 // check that we have extended feature read support
4506 if (!comm.GetQXferFeaturesReadSupported())
4507 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004508
Kate Stoneb9c1b512016-09-06 20:57:50 +00004509 // request the target xml file
4510 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004511 lldb_private::Status lldberr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004512 if (!comm.ReadExtFeature(ConstString("features"), ConstString("target.xml"),
4513 raw, lldberr)) {
4514 return false;
4515 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004516
Kate Stoneb9c1b512016-09-06 20:57:50 +00004517 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004518
Kate Stoneb9c1b512016-09-06 20:57:50 +00004519 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml")) {
4520 GdbServerTargetInfo target_info;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004521
Kate Stoneb9c1b512016-09-06 20:57:50 +00004522 XMLNode target_node = xml_document.GetRootElement("target");
4523 if (target_node) {
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004524 std::vector<XMLNode> feature_nodes;
4525 target_node.ForEachChildElement([&target_info, &feature_nodes](
Kate Stoneb9c1b512016-09-06 20:57:50 +00004526 const XMLNode &node) -> bool {
4527 llvm::StringRef name = node.GetName();
4528 if (name == "architecture") {
4529 node.GetElementText(target_info.arch);
4530 } else if (name == "osabi") {
4531 node.GetElementText(target_info.osabi);
4532 } else if (name == "xi:include" || name == "include") {
4533 llvm::StringRef href = node.GetAttributeValue("href");
4534 if (!href.empty())
4535 target_info.includes.push_back(href.str());
4536 } else if (name == "feature") {
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004537 feature_nodes.push_back(node);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004538 } else if (name == "groups") {
4539 node.ForEachChildElementWithName(
4540 "group", [&target_info](const XMLNode &node) -> bool {
4541 uint32_t set_id = UINT32_MAX;
4542 RegisterSetInfo set_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004543
Kate Stoneb9c1b512016-09-06 20:57:50 +00004544 node.ForEachAttribute(
4545 [&set_id, &set_info](const llvm::StringRef &name,
4546 const llvm::StringRef &value) -> bool {
4547 if (name == "id")
4548 set_id = StringConvert::ToUInt32(value.data(),
4549 UINT32_MAX, 0);
4550 if (name == "name")
4551 set_info.name = ConstString(value);
4552 return true; // Keep iterating through all attributes
Greg Claytond04f0ed2015-05-26 18:00:51 +00004553 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004554
Kate Stoneb9c1b512016-09-06 20:57:50 +00004555 if (set_id != UINT32_MAX)
4556 target_info.reg_set_map[set_id] = set_info;
4557 return true; // Keep iterating through all "group" elements
4558 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004559 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004560 return true; // Keep iterating through all children of the target_node
4561 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004562
Jason Molendac4dd04c2018-01-12 01:16:13 +00004563 // If the target.xml includes an architecture entry like
4564 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4565 // <architecture>arm</architecture> (seen from Segger JLink on unspecified arm board)
4566 // use that if we don't have anything better.
4567 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4568 if (target_info.arch == "i386:x86-64")
4569 {
4570 // We don't have any information about vendor or OS.
4571 arch_to_use.SetTriple("x86_64--");
4572 GetTarget().MergeArchitecture(arch_to_use);
4573 }
4574 }
4575
Kate Stoneb9c1b512016-09-06 20:57:50 +00004576 // Initialize these outside of ParseRegisters, since they should not be
4577 // reset inside each include feature
4578 uint32_t cur_reg_num = 0;
4579 uint32_t reg_offset = 0;
4580
4581 // Don't use Process::GetABI, this code gets called from DidAttach, and in
4582 // that context we haven't
4583 // set the Target's architecture yet, so the ABI is also potentially
4584 // incorrect.
Jason Molenda43294c92017-06-29 02:57:03 +00004585 ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use);
Vadim Chugunov3293b9d2017-09-16 03:53:13 +00004586 for (auto &feature_node : feature_nodes) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004587 ParseRegisters(feature_node, target_info, this->m_register_info,
4588 abi_to_use_sp, cur_reg_num, reg_offset);
4589 }
4590
4591 for (const auto &include : target_info.includes) {
4592 // request register file
4593 std::string xml_data;
4594 if (!comm.ReadExtFeature(ConstString("features"), ConstString(include),
4595 xml_data, lldberr))
4596 continue;
4597
4598 XMLDocument include_xml_document;
4599 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(),
4600 include.c_str());
4601 XMLNode include_feature_node =
4602 include_xml_document.GetRootElement("feature");
4603 if (include_feature_node) {
4604 ParseRegisters(include_feature_node, target_info,
4605 this->m_register_info, abi_to_use_sp, cur_reg_num,
4606 reg_offset);
4607 }
4608 }
4609 this->m_register_info.Finalize(arch_to_use);
4610 }
4611 }
4612
4613 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004614}
4615
Zachary Turner97206d52017-05-12 04:51:55 +00004616Status ProcessGDBRemote::GetLoadedModuleList(LoadedModuleInfoList &list) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004617 // Make sure LLDB has an XML parser it can use first
4618 if (!XMLDocument::XMLEnabled())
Zachary Turner97206d52017-05-12 04:51:55 +00004619 return Status(0, ErrorType::eErrorTypeGeneric);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004620
Kate Stoneb9c1b512016-09-06 20:57:50 +00004621 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS);
4622 if (log)
4623 log->Printf("ProcessGDBRemote::%s", __FUNCTION__);
4624
4625 GDBRemoteCommunicationClient &comm = m_gdb_comm;
4626
4627 // check that we have extended feature read support
4628 if (comm.GetQXferLibrariesSVR4ReadSupported()) {
4629 list.clear();
4630
4631 // request the loaded library list
4632 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004633 lldb_private::Status lldberr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004634
4635 if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""),
4636 raw, lldberr))
Zachary Turner97206d52017-05-12 04:51:55 +00004637 return Status(0, ErrorType::eErrorTypeGeneric);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004638
4639 // parse the xml file in memory
Aidan Doddsc0c83852015-05-08 09:36:31 +00004640 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004641 log->Printf("parsing: %s", raw.c_str());
4642 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004643
Kate Stoneb9c1b512016-09-06 20:57:50 +00004644 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Zachary Turner97206d52017-05-12 04:51:55 +00004645 return Status(0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004646
Kate Stoneb9c1b512016-09-06 20:57:50 +00004647 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4648 if (!root_element)
Zachary Turner97206d52017-05-12 04:51:55 +00004649 return Status();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004650
Kate Stoneb9c1b512016-09-06 20:57:50 +00004651 // main link map structure
4652 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4653 if (!main_lm.empty()) {
4654 list.m_link_map =
4655 StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4656 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004657
Kate Stoneb9c1b512016-09-06 20:57:50 +00004658 root_element.ForEachChildElementWithName(
4659 "library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004660
Kate Stoneb9c1b512016-09-06 20:57:50 +00004661 LoadedModuleInfoList::LoadedModuleInfo module;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004662
Kate Stoneb9c1b512016-09-06 20:57:50 +00004663 library.ForEachAttribute(
Zachary Turner3bc714b2017-03-02 00:05:25 +00004664 [&module](const llvm::StringRef &name,
4665 const llvm::StringRef &value) -> bool {
Ed Maste81b4c5f2016-01-04 01:43:47 +00004666
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004667 if (name == "name")
Kate Stoneb9c1b512016-09-06 20:57:50 +00004668 module.set_name(value.str());
4669 else if (name == "lm") {
4670 // the address of the link_map struct.
4671 module.set_link_map(StringConvert::ToUInt64(
4672 value.data(), LLDB_INVALID_ADDRESS, 0));
4673 } else if (name == "l_addr") {
4674 // the displacement as read from the field 'l_addr' of the
4675 // link_map struct.
4676 module.set_base(StringConvert::ToUInt64(
4677 value.data(), LLDB_INVALID_ADDRESS, 0));
4678 // base address is always a displacement, not an absolute
4679 // value.
4680 module.set_base_is_offset(true);
4681 } else if (name == "l_ld") {
4682 // the memory address of the libraries PT_DYAMIC section.
4683 module.set_dynamic(StringConvert::ToUInt64(
4684 value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004685 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004686
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004687 return true; // Keep iterating over all properties of "library"
Kate Stoneb9c1b512016-09-06 20:57:50 +00004688 });
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004689
Kate Stoneb9c1b512016-09-06 20:57:50 +00004690 if (log) {
4691 std::string name;
4692 lldb::addr_t lm = 0, base = 0, ld = 0;
4693 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004694
Kate Stoneb9c1b512016-09-06 20:57:50 +00004695 module.get_name(name);
4696 module.get_link_map(lm);
4697 module.get_base(base);
4698 module.get_base_is_offset(base_is_offset);
4699 module.get_dynamic(ld);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004700
Kate Stoneb9c1b512016-09-06 20:57:50 +00004701 log->Printf("found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4702 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4703 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4704 name.c_str());
4705 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004706
Kate Stoneb9c1b512016-09-06 20:57:50 +00004707 list.add(module);
4708 return true; // Keep iterating over all "library" elements in the root
4709 // node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004710 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004711
Kate Stoneb9c1b512016-09-06 20:57:50 +00004712 if (log)
4713 log->Printf("found %" PRId32 " modules in total",
4714 (int)list.m_list.size());
4715 } else if (comm.GetQXferLibrariesReadSupported()) {
4716 list.clear();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004717
Kate Stoneb9c1b512016-09-06 20:57:50 +00004718 // request the loaded library list
4719 std::string raw;
Zachary Turner97206d52017-05-12 04:51:55 +00004720 lldb_private::Status lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004721
Kate Stoneb9c1b512016-09-06 20:57:50 +00004722 if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw,
4723 lldberr))
Zachary Turner97206d52017-05-12 04:51:55 +00004724 return Status(0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004725
Kate Stoneb9c1b512016-09-06 20:57:50 +00004726 if (log)
4727 log->Printf("parsing: %s", raw.c_str());
4728 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004729
Kate Stoneb9c1b512016-09-06 20:57:50 +00004730 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Zachary Turner97206d52017-05-12 04:51:55 +00004731 return Status(0, ErrorType::eErrorTypeGeneric);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004732
Kate Stoneb9c1b512016-09-06 20:57:50 +00004733 XMLNode root_element = doc.GetRootElement("library-list");
4734 if (!root_element)
Zachary Turner97206d52017-05-12 04:51:55 +00004735 return Status();
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004736
Kate Stoneb9c1b512016-09-06 20:57:50 +00004737 root_element.ForEachChildElementWithName(
4738 "library", [log, &list](const XMLNode &library) -> bool {
4739 LoadedModuleInfoList::LoadedModuleInfo module;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004740
Kate Stoneb9c1b512016-09-06 20:57:50 +00004741 llvm::StringRef name = library.GetAttributeValue("name");
4742 module.set_name(name.str());
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004743
Kate Stoneb9c1b512016-09-06 20:57:50 +00004744 // The base address of a given library will be the address of its
4745 // first section. Most remotes send only one section for Windows
4746 // targets for example.
4747 const XMLNode &section =
4748 library.FindFirstChildElementWithName("section");
4749 llvm::StringRef address = section.GetAttributeValue("address");
4750 module.set_base(
4751 StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4752 // These addresses are absolute values.
4753 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004754
Kate Stoneb9c1b512016-09-06 20:57:50 +00004755 if (log) {
4756 std::string name;
4757 lldb::addr_t base = 0;
4758 bool base_is_offset;
4759 module.get_name(name);
4760 module.get_base(base);
4761 module.get_base_is_offset(base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004762
Kate Stoneb9c1b512016-09-06 20:57:50 +00004763 log->Printf("found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4764 (base_is_offset ? "offset" : "absolute"), name.c_str());
4765 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004766
Kate Stoneb9c1b512016-09-06 20:57:50 +00004767 list.add(module);
4768 return true; // Keep iterating over all "library" elements in the root
4769 // node
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004770 });
4771
Kate Stoneb9c1b512016-09-06 20:57:50 +00004772 if (log)
4773 log->Printf("found %" PRId32 " modules in total",
4774 (int)list.m_list.size());
4775 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00004776 return Status(0, ErrorType::eErrorTypeGeneric);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004777 }
4778
Zachary Turner97206d52017-05-12 04:51:55 +00004779 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004780}
4781
4782lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4783 lldb::addr_t link_map,
4784 lldb::addr_t base_addr,
4785 bool value_is_offset) {
4786 DynamicLoader *loader = GetDynamicLoader();
4787 if (!loader)
4788 return nullptr;
4789
4790 return loader->LoadModuleAtAddress(file, link_map, base_addr,
4791 value_is_offset);
4792}
4793
4794size_t ProcessGDBRemote::LoadModules(LoadedModuleInfoList &module_list) {
4795 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4796
4797 // request a list of loaded libraries from GDBServer
4798 if (GetLoadedModuleList(module_list).Fail())
4799 return 0;
4800
4801 // get a list of all the modules
4802 ModuleList new_modules;
4803
4804 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list.m_list) {
4805 std::string mod_name;
4806 lldb::addr_t mod_base;
4807 lldb::addr_t link_map;
4808 bool mod_base_is_offset;
4809
4810 bool valid = true;
4811 valid &= modInfo.get_name(mod_name);
4812 valid &= modInfo.get_base(mod_base);
4813 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4814 if (!valid)
4815 continue;
4816
4817 if (!modInfo.get_link_map(link_map))
4818 link_map = LLDB_INVALID_ADDRESS;
4819
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00004820 FileSpec file(mod_name, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004821 lldb::ModuleSP module_sp =
4822 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4823
4824 if (module_sp.get())
4825 new_modules.Append(module_sp);
4826 }
4827
4828 if (new_modules.GetSize() > 0) {
4829 ModuleList removed_modules;
4830 Target &target = GetTarget();
4831 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4832
4833 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4834 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4835
4836 bool found = false;
4837 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4838 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4839 found = true;
4840 }
4841
4842 // The main executable will never be included in libraries-svr4, don't
4843 // remove it
4844 if (!found &&
4845 loaded_module.get() != target.GetExecutableModulePointer()) {
4846 removed_modules.Append(loaded_module);
4847 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004848 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004849
Kate Stoneb9c1b512016-09-06 20:57:50 +00004850 loaded_modules.Remove(removed_modules);
4851 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4852
4853 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4854 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4855 if (!obj)
4856 return true;
4857
4858 if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4859 return true;
4860
4861 lldb::ModuleSP module_copy_sp = module_sp;
4862 target.SetExecutableModule(module_copy_sp, false);
4863 return false;
4864 });
4865
4866 loaded_modules.AppendIfNeeded(new_modules);
4867 m_process->GetTarget().ModulesDidLoad(new_modules);
4868 }
4869
4870 return new_modules.GetSize();
4871}
4872
4873size_t ProcessGDBRemote::LoadModules() {
4874 LoadedModuleInfoList module_list;
4875 return LoadModules(module_list);
4876}
4877
Zachary Turner97206d52017-05-12 04:51:55 +00004878Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4879 bool &is_loaded,
4880 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004881 is_loaded = false;
4882 load_addr = LLDB_INVALID_ADDRESS;
4883
4884 std::string file_path = file.GetPath(false);
4885 if (file_path.empty())
Zachary Turner97206d52017-05-12 04:51:55 +00004886 return Status("Empty file name specified");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004887
4888 StreamString packet;
4889 packet.PutCString("qFileLoadAddress:");
4890 packet.PutCStringAsRawHex8(file_path.c_str());
4891
4892 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00004893 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
4894 false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00004895 GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00004896 return Status("Sending qFileLoadAddress packet failed");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004897
4898 if (response.IsErrorResponse()) {
4899 if (response.GetError() == 1) {
4900 // The file is not loaded into the inferior
4901 is_loaded = false;
4902 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00004903 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004904 }
4905
Zachary Turner97206d52017-05-12 04:51:55 +00004906 return Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004907 "Fetching file load address from remote server returned an error");
4908 }
4909
4910 if (response.IsNormalResponse()) {
4911 is_loaded = true;
4912 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
Zachary Turner97206d52017-05-12 04:51:55 +00004913 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004914 }
4915
Zachary Turner97206d52017-05-12 04:51:55 +00004916 return Status(
4917 "Unknown error happened during sending the load address packet");
Aidan Doddsc0c83852015-05-08 09:36:31 +00004918}
4919
Kate Stoneb9c1b512016-09-06 20:57:50 +00004920void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4921 // We must call the lldb_private::Process::ModulesDidLoad () first before we
4922 // do anything
4923 Process::ModulesDidLoad(module_list);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004924
Kate Stoneb9c1b512016-09-06 20:57:50 +00004925 // After loading shared libraries, we can ask our remote GDB server if
4926 // it needs any symbols.
4927 m_gdb_comm.ServeSymbolLookups(this);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004928}
4929
Kate Stoneb9c1b512016-09-06 20:57:50 +00004930void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4931 AppendSTDOUT(out.data(), out.size());
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004932}
4933
4934static const char *end_delimiter = "--end--;";
4935static const int end_delimiter_len = 8;
4936
Kate Stoneb9c1b512016-09-06 20:57:50 +00004937void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4938 std::string input = data.str(); // '1' to move beyond 'A'
4939 if (m_partial_profile_data.length() > 0) {
4940 m_partial_profile_data.append(input);
4941 input = m_partial_profile_data;
4942 m_partial_profile_data.clear();
4943 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004944
Kate Stoneb9c1b512016-09-06 20:57:50 +00004945 size_t found, pos = 0, len = input.length();
4946 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4947 StringExtractorGDBRemote profileDataExtractor(
4948 input.substr(pos, found).c_str());
4949 std::string profile_data =
4950 HarmonizeThreadIdsForProfileData(profileDataExtractor);
4951 BroadcastAsyncProfileData(profile_data);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004952
Kate Stoneb9c1b512016-09-06 20:57:50 +00004953 pos = found + end_delimiter_len;
4954 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004955
Kate Stoneb9c1b512016-09-06 20:57:50 +00004956 if (pos < len) {
4957 // Last incomplete chunk.
4958 m_partial_profile_data = input.substr(pos);
4959 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004960}
4961
Kate Stoneb9c1b512016-09-06 20:57:50 +00004962std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4963 StringExtractorGDBRemote &profileDataExtractor) {
4964 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4965 std::string output;
4966 llvm::raw_string_ostream output_stream(output);
4967 llvm::StringRef name, value;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004968
Kate Stoneb9c1b512016-09-06 20:57:50 +00004969 // Going to assuming thread_used_usec comes first, else bail out.
4970 while (profileDataExtractor.GetNameColonValue(name, value)) {
4971 if (name.compare("thread_used_id") == 0) {
4972 StringExtractor threadIDHexExtractor(value);
4973 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004974
Kate Stoneb9c1b512016-09-06 20:57:50 +00004975 bool has_used_usec = false;
4976 uint32_t curr_used_usec = 0;
4977 llvm::StringRef usec_name, usec_value;
4978 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4979 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4980 if (usec_name.equals("thread_used_usec")) {
4981 has_used_usec = true;
4982 usec_value.getAsInteger(0, curr_used_usec);
4983 } else {
4984 // We didn't find what we want, it is probably
4985 // an older version. Bail out.
4986 profileDataExtractor.SetFilePos(input_file_pos);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004987 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004988 }
4989
4990 if (has_used_usec) {
4991 uint32_t prev_used_usec = 0;
4992 std::map<uint64_t, uint32_t>::iterator iterator =
4993 m_thread_id_to_used_usec_map.find(thread_id);
4994 if (iterator != m_thread_id_to_used_usec_map.end()) {
4995 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00004996 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004997
4998 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4999 // A good first time record is one that runs for at least 0.25 sec
5000 bool good_first_time =
5001 (prev_used_usec == 0) && (real_used_usec > 250000);
5002 bool good_subsequent_time =
5003 (prev_used_usec > 0) &&
5004 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
5005
5006 if (good_first_time || good_subsequent_time) {
5007 // We try to avoid doing too many index id reservation,
5008 // resulting in fast increase of index ids.
5009
5010 output_stream << name << ":";
5011 int32_t index_id = AssignIndexIDToThread(thread_id);
5012 output_stream << index_id << ";";
5013
5014 output_stream << usec_name << ":" << usec_value << ";";
5015 } else {
5016 // Skip past 'thread_used_name'.
5017 llvm::StringRef local_name, local_value;
5018 profileDataExtractor.GetNameColonValue(local_name, local_value);
5019 }
5020
5021 // Store current time as previous time so that they can be compared
5022 // later.
5023 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
5024 } else {
5025 // Bail out and use old string.
5026 output_stream << name << ":" << value << ";";
5027 }
5028 } else {
5029 output_stream << name << ":" << value << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005030 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005031 }
5032 output_stream << end_delimiter;
5033 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005034
Kate Stoneb9c1b512016-09-06 20:57:50 +00005035 return output_stream.str();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005036}
5037
Kate Stoneb9c1b512016-09-06 20:57:50 +00005038void ProcessGDBRemote::HandleStopReply() {
5039 if (GetStopID() != 0)
5040 return;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005041
Kate Stoneb9c1b512016-09-06 20:57:50 +00005042 if (GetID() == LLDB_INVALID_PROCESS_ID) {
5043 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5044 if (pid != LLDB_INVALID_PROCESS_ID)
5045 SetID(pid);
5046 }
5047 BuildDynamicRegisterInfo(true);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005048}
Eugene Zelenko0722f082015-10-24 01:28:05 +00005049
Todd Fialafcdb1af2016-09-10 00:06:29 +00005050static const char *const s_async_json_packet_prefix = "JSON-async:";
5051
5052static StructuredData::ObjectSP
5053ParseStructuredDataPacket(llvm::StringRef packet) {
5054 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
5055
5056 if (!packet.consume_front(s_async_json_packet_prefix)) {
5057 if (log) {
5058 log->Printf(
5059 "GDBRemoteCommmunicationClientBase::%s() received $J packet "
5060 "but was not a StructuredData packet: packet starts with "
5061 "%s",
5062 __FUNCTION__,
5063 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
5064 }
5065 return StructuredData::ObjectSP();
5066 }
5067
5068 // This is an asynchronous JSON packet, destined for a
5069 // StructuredDataPlugin.
5070 StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(packet);
5071 if (log) {
5072 if (json_sp) {
5073 StreamString json_str;
5074 json_sp->Dump(json_str);
5075 json_str.Flush();
5076 log->Printf("ProcessGDBRemote::%s() "
5077 "received Async StructuredData packet: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00005078 __FUNCTION__, json_str.GetData());
Todd Fialafcdb1af2016-09-10 00:06:29 +00005079 } else {
5080 log->Printf("ProcessGDBRemote::%s"
5081 "() received StructuredData packet:"
5082 " parse failure",
5083 __FUNCTION__);
5084 }
5085 }
5086 return json_sp;
5087}
5088
5089void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
5090 auto structured_data_sp = ParseStructuredDataPacket(data);
5091 if (structured_data_sp)
5092 RouteAsyncStructuredData(structured_data_sp);
Todd Fiala75930012016-08-19 04:21:48 +00005093}
5094
Kate Stoneb9c1b512016-09-06 20:57:50 +00005095class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
Greg Claytone034a042015-05-21 20:52:06 +00005096public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005097 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
5098 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
5099 "Tests packet speeds of various sizes to determine "
5100 "the performance characteristics of the GDB remote "
5101 "connection. ",
5102 NULL),
5103 m_option_group(),
5104 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
5105 "The number of packets to send of each varying size "
5106 "(default is 1000).",
5107 1000),
5108 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
5109 "The maximum number of bytes to send in a packet. Sizes "
5110 "increase in powers of 2 while the size is less than or "
5111 "equal to this option value. (default 1024).",
5112 1024),
5113 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
5114 "The maximum number of bytes to receive in a packet. Sizes "
5115 "increase in powers of 2 while the size is less than or "
5116 "equal to this option value. (default 1024).",
5117 1024),
5118 m_json(LLDB_OPT_SET_1, false, "json", 'j',
5119 "Print the output as JSON data for easy parsing.", false, true) {
5120 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5121 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5122 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5123 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5124 m_option_group.Finalize();
5125 }
Greg Claytone034a042015-05-21 20:52:06 +00005126
Kate Stoneb9c1b512016-09-06 20:57:50 +00005127 ~CommandObjectProcessGDBRemoteSpeedTest() {}
Eugene Zelenko0722f082015-10-24 01:28:05 +00005128
Kate Stoneb9c1b512016-09-06 20:57:50 +00005129 Options *GetOptions() override { return &m_option_group; }
Greg Claytone034a042015-05-21 20:52:06 +00005130
Kate Stoneb9c1b512016-09-06 20:57:50 +00005131 bool DoExecute(Args &command, CommandReturnObject &result) override {
5132 const size_t argc = command.GetArgumentCount();
5133 if (argc == 0) {
5134 ProcessGDBRemote *process =
5135 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5136 .GetProcessPtr();
5137 if (process) {
5138 StreamSP output_stream_sp(
5139 m_interpreter.GetDebugger().GetAsyncOutputStream());
5140 result.SetImmediateOutputStream(output_stream_sp);
Greg Claytone034a042015-05-21 20:52:06 +00005141
Kate Stoneb9c1b512016-09-06 20:57:50 +00005142 const uint32_t num_packets =
5143 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5144 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5145 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5146 const bool json = m_json.GetOptionValue().GetCurrentValue();
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00005147 const uint64_t k_recv_amount =
5148 4 * 1024 * 1024; // Receive amount in bytes
5149 process->GetGDBRemote().TestPacketSpeed(
5150 num_packets, max_send, max_recv, k_recv_amount, json,
5151 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005152 result.SetStatus(eReturnStatusSuccessFinishResult);
5153 return true;
5154 }
5155 } else {
5156 result.AppendErrorWithFormat("'%s' takes no arguments",
5157 m_cmd_name.c_str());
Greg Claytone034a042015-05-21 20:52:06 +00005158 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005159 result.SetStatus(eReturnStatusFailed);
5160 return false;
5161 }
5162
Greg Claytone034a042015-05-21 20:52:06 +00005163protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005164 OptionGroupOptions m_option_group;
5165 OptionGroupUInt64 m_num_packets;
5166 OptionGroupUInt64 m_max_send;
5167 OptionGroupUInt64 m_max_recv;
5168 OptionGroupBoolean m_json;
Greg Claytone034a042015-05-21 20:52:06 +00005169};
5170
Kate Stoneb9c1b512016-09-06 20:57:50 +00005171class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005172private:
Greg Clayton998255b2012-10-13 02:07:45 +00005173public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005174 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
5175 : CommandObjectParsed(interpreter, "process plugin packet history",
5176 "Dumps the packet history buffer. ", NULL) {}
5177
5178 ~CommandObjectProcessGDBRemotePacketHistory() {}
5179
5180 bool DoExecute(Args &command, CommandReturnObject &result) override {
5181 const size_t argc = command.GetArgumentCount();
5182 if (argc == 0) {
5183 ProcessGDBRemote *process =
5184 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5185 .GetProcessPtr();
5186 if (process) {
5187 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5188 result.SetStatus(eReturnStatusSuccessFinishResult);
5189 return true;
5190 }
5191 } else {
5192 result.AppendErrorWithFormat("'%s' takes no arguments",
5193 m_cmd_name.c_str());
5194 }
5195 result.SetStatus(eReturnStatusFailed);
5196 return false;
5197 }
5198};
5199
5200class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
5201private:
5202public:
5203 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
5204 : CommandObjectParsed(
5205 interpreter, "process plugin packet xfer-size",
5206 "Maximum size that lldb will try to read/write one one chunk.",
5207 NULL) {}
5208
5209 ~CommandObjectProcessGDBRemotePacketXferSize() {}
5210
5211 bool DoExecute(Args &command, CommandReturnObject &result) override {
5212 const size_t argc = command.GetArgumentCount();
5213 if (argc == 0) {
5214 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5215 "amount to be transferred when "
5216 "reading/writing",
5217 m_cmd_name.c_str());
5218 result.SetStatus(eReturnStatusFailed);
5219 return false;
Greg Clayton998255b2012-10-13 02:07:45 +00005220 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005221
Kate Stoneb9c1b512016-09-06 20:57:50 +00005222 ProcessGDBRemote *process =
5223 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5224 if (process) {
5225 const char *packet_size = command.GetArgumentAtIndex(0);
5226 errno = 0;
5227 uint64_t user_specified_max = strtoul(packet_size, NULL, 10);
5228 if (errno == 0 && user_specified_max != 0) {
5229 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5230 result.SetStatus(eReturnStatusSuccessFinishResult);
5231 return true;
5232 }
5233 }
5234 result.SetStatus(eReturnStatusFailed);
5235 return false;
5236 }
5237};
5238
5239class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5240private:
5241public:
5242 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5243 : CommandObjectParsed(interpreter, "process plugin packet send",
5244 "Send a custom packet through the GDB remote "
5245 "protocol and print the answer. "
5246 "The packet header and footer will automatically "
5247 "be added to the packet prior to sending and "
5248 "stripped from the result.",
5249 NULL) {}
5250
5251 ~CommandObjectProcessGDBRemotePacketSend() {}
5252
5253 bool DoExecute(Args &command, CommandReturnObject &result) override {
5254 const size_t argc = command.GetArgumentCount();
5255 if (argc == 0) {
5256 result.AppendErrorWithFormat(
5257 "'%s' takes a one or more packet content arguments",
5258 m_cmd_name.c_str());
5259 result.SetStatus(eReturnStatusFailed);
5260 return false;
Eugene Zelenko0722f082015-10-24 01:28:05 +00005261 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005262
Kate Stoneb9c1b512016-09-06 20:57:50 +00005263 ProcessGDBRemote *process =
5264 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5265 if (process) {
5266 for (size_t i = 0; i < argc; ++i) {
5267 const char *packet_cstr = command.GetArgumentAtIndex(0);
5268 bool send_async = true;
5269 StringExtractorGDBRemote response;
5270 process->GetGDBRemote().SendPacketAndWaitForResponse(
5271 packet_cstr, response, send_async);
5272 result.SetStatus(eReturnStatusSuccessFinishResult);
5273 Stream &output_strm = result.GetOutputStream();
5274 output_strm.Printf(" packet: %s\n", packet_cstr);
5275 std::string &response_str = response.GetStringRef();
5276
5277 if (strstr(packet_cstr, "qGetProfileData") != NULL) {
5278 response_str = process->HarmonizeThreadIdsForProfileData(response);
Greg Clayton02686b82012-10-15 22:42:16 +00005279 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005280
5281 if (response_str.empty())
5282 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
Greg Clayton02686b82012-10-15 22:42:16 +00005283 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00005284 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
5285 }
Greg Clayton02686b82012-10-15 22:42:16 +00005286 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005287 return true;
5288 }
Greg Clayton02686b82012-10-15 22:42:16 +00005289};
5290
Kate Stoneb9c1b512016-09-06 20:57:50 +00005291class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005292private:
Jason Molenda6076bf42014-05-06 04:34:52 +00005293public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005294 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5295 : CommandObjectRaw(interpreter, "process plugin packet monitor",
5296 "Send a qRcmd packet through the GDB remote protocol "
5297 "and print the response."
5298 "The argument passed to this command will be hex "
5299 "encoded into a valid 'qRcmd' packet, sent and the "
Zachary Turnera4496982016-10-05 21:14:38 +00005300 "response will be printed.") {}
Kate Stoneb9c1b512016-09-06 20:57:50 +00005301
5302 ~CommandObjectProcessGDBRemotePacketMonitor() {}
5303
5304 bool DoExecute(const char *command, CommandReturnObject &result) override {
5305 if (command == NULL || command[0] == '\0') {
5306 result.AppendErrorWithFormat("'%s' takes a command string argument",
5307 m_cmd_name.c_str());
5308 result.SetStatus(eReturnStatusFailed);
5309 return false;
Jason Molenda6076bf42014-05-06 04:34:52 +00005310 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005311
Kate Stoneb9c1b512016-09-06 20:57:50 +00005312 ProcessGDBRemote *process =
5313 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5314 if (process) {
5315 StreamString packet;
5316 packet.PutCString("qRcmd,");
5317 packet.PutBytesAsRawHex8(command, strlen(command));
Ed Maste81b4c5f2016-01-04 01:43:47 +00005318
Kate Stoneb9c1b512016-09-06 20:57:50 +00005319 bool send_async = true;
5320 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005321 Stream &output_strm = result.GetOutputStream();
Pavel Labath7da84752018-01-10 14:39:08 +00005322 process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5323 packet.GetString(), response, send_async,
5324 [&output_strm](llvm::StringRef output) { output_strm << output; });
5325 result.SetStatus(eReturnStatusSuccessFinishResult);
Zachary Turnerc1564272016-11-16 21:15:24 +00005326 output_strm.Printf(" packet: %s\n", packet.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005327 const std::string &response_str = response.GetStringRef();
Jason Molenda6076bf42014-05-06 04:34:52 +00005328
Kate Stoneb9c1b512016-09-06 20:57:50 +00005329 if (response_str.empty())
5330 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5331 else
5332 output_strm.Printf("response: %s\n", response.GetStringRef().c_str());
Jason Molenda6076bf42014-05-06 04:34:52 +00005333 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005334 return true;
5335 }
Jason Molenda6076bf42014-05-06 04:34:52 +00005336};
5337
Kate Stoneb9c1b512016-09-06 20:57:50 +00005338class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
Eugene Zelenko0722f082015-10-24 01:28:05 +00005339private:
Greg Clayton02686b82012-10-15 22:42:16 +00005340public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005341 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5342 : CommandObjectMultiword(interpreter, "process plugin packet",
5343 "Commands that deal with GDB remote packets.",
5344 NULL) {
5345 LoadSubCommand(
5346 "history",
5347 CommandObjectSP(
5348 new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5349 LoadSubCommand(
5350 "send", CommandObjectSP(
5351 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5352 LoadSubCommand(
5353 "monitor",
5354 CommandObjectSP(
5355 new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5356 LoadSubCommand(
5357 "xfer-size",
5358 CommandObjectSP(
5359 new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5360 LoadSubCommand("speed-test",
5361 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5362 interpreter)));
5363 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005364
Kate Stoneb9c1b512016-09-06 20:57:50 +00005365 ~CommandObjectProcessGDBRemotePacket() {}
Greg Clayton998255b2012-10-13 02:07:45 +00005366};
5367
Kate Stoneb9c1b512016-09-06 20:57:50 +00005368class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
Greg Claytonba4a0a52013-02-01 23:03:47 +00005369public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005370 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5371 : CommandObjectMultiword(
5372 interpreter, "process plugin",
5373 "Commands for operating on a ProcessGDBRemote process.",
5374 "process plugin <subcommand> [<subcommand-options>]") {
5375 LoadSubCommand(
5376 "packet",
5377 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5378 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005379
Kate Stoneb9c1b512016-09-06 20:57:50 +00005380 ~CommandObjectMultiwordProcessGDBRemote() {}
Greg Claytonba4a0a52013-02-01 23:03:47 +00005381};
5382
Kate Stoneb9c1b512016-09-06 20:57:50 +00005383CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5384 if (!m_command_sp)
5385 m_command_sp.reset(new CommandObjectMultiwordProcessGDBRemote(
5386 GetTarget().GetDebugger().GetCommandInterpreter()));
5387 return m_command_sp.get();
Greg Clayton998255b2012-10-13 02:07:45 +00005388}